Jump to content

Module:Mock title/doc

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 14:32, 15 August 2023 (start documentation). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

This module allows you to easily mock Scribunto title objects. This can be useful when writing unit tests for modules which depend on whether a certain page exists, or whether a certain page is a redirect, etc. If you don't use mock title objects, then you run the risk of some editor changing a page that your test cases relied on (e.g. redirecting it or deleting it), thus breaking your tests. By using mock objects, you get to specify things like existence status and redirect status in your tests, making them more resilient against changes to real pages.

Usage

Loading the module

Load the module using require:

local mMockTitle = require('Module:Mock title')

Registering titles to mock

You can register a title to be mocked with the registerMockTitle function.

mMockTitle.registerMockTitle({title = "Main Page", isRedirect = true, redirectTarget = "Wikipedia:Village stocks"})

Or you can register multiple titles at once using registerMockTitles.

mMockTitle.registerMockTitles(
    {title = "File:Example.png", height = 250, width = 200},
    {title = "Template:3x", editProtection = "templateeditor"}
)

You can also register a mock for the current page with registerMockCurrentTitle.

mMockTitle.registerMockCurrentTitle({title = "User:Example"})

Patching title constructors

During tests, you can use the patchTitleConstructors function to temporarily replace the title constructors mw.title.new, mw.title.makeTitle and mw.title.getCurrentTitle with functions that return the mock titles that you registered. You pass patchTitleConstructors your own function containing your test code; while the function is running the title constructors will return mock titles, but after it finishes running they will be restored to their original versions.

local function logCurrentTitle()
    mw.log(mw.title.getCurrentTitle().prefixedText)
end

logCurrentTitle() -- Logs "Module:Mock title"
mMockTitle.patchTitleConstructors(logCurrentTitle) -- Logs "User:Example"
logCurrentTitle() -- Logs "Module:Mock title"