Модуль:Convert/tester/doc

Это страница документации Модуль:Convert/tester.

Этот модуль запускает юнит-тесты и сравнивает результаты выполнения шаблона с ожидаемым текстом. Кроме того, модуль может показывать результаты развёртки шаблона.

Модуль предназначен для тестирования Module:Convert, но может быть полезен и для других шаблонов, которые требуют много однострочных тестов.

Примеры тестовПравить

It is not necessary to save the testcases page before viewing test results. For example, Module:Convert/песочница/тесты could be edited to change the tests. While still editing that page, paste "Module talk:Convert/песочница/тесты" (without quotes) into the page title box under "Preview page with this template", then click "Show preview".

Страница обсуждения юнит-тестов (например, Обсуждение модуля:Convert/песочница/тесты) содержит:

{{#invoke:convert/песочница/тесты|run_tests}}

Страница юнит-тестов (например, Module:Convert/песочница/тесты) может содержать:

local tests = [==[

Тестируемый шаблон должен быть в начале строки.
Строки не начинающиеся с вызова шаблона игнорируются.
{{convert/песочница|1|acre|lk=on}}            1 [[акр]] (0,40 [[гектар|га]])
{{convert/песочница|1|m2|acres|lk=on}}        1 [[Квадратный метр|квадратный метр]] (0,00025 [[акр|акров]])
{{convert/песочница|0.16|/l|2|disp=table}}    align="right"|0.16\n|align="right"|0.61

]==]

local p = require('Module:Convert/tester')
p.tests = tests
return p

If wanted, the tests can be run using a template different from the one specified in the tests. For example, the following would run the tests from Module:Convert/sandbox/testcases, but would change the name of each template found on that page to "convert/sandbox2".

{{#invoke:convert/sandbox/testcases|run_tests|template=convert/sandbox2}}

Формат тестовПравить

Tests are extracted from a multiline string. Any line that does not start with a template is ignored. Each processed line starts with a template, and is followed by whitespace, then the wikitext which should result from expanding the template.

The expected output must be entered in a single line. If the template outputs multiple lines, those lines must be joined with "\n" (two characters—backslash n).

The templates do not have to be the same, for example, the following tests would work:

local tests = [==[

{{convert|12|m}}                            12 metres (39 ft)
{{convert/sandbox|12|m}}                    12 metres (39 ft)
{{age|1989|7|23|2003|7|14}}                 13
{{age in days|2007|5|24|2008|4|23}}         335

]==]

In the results, the status column shows "Pass" if the output from the template exactly matches the expected text. If there is no expected text, the template output is shown in the Actual column with a blank status. If the given expected text differs from the template output, the template output is shown in the Actual column with status "Fail", and the number of fails is shown at the top of the page. Searching the page for "Fail" will find each problem. Any "Fail" result is followed by a row showing the nowiki actual and expected wikitext.

Задание тестовПравить

If using a testcases module (as in the above example), the test text is assigned to p.tests before executing run_tests.

Alternatively, the test text can be read from any page, or from any section on any page. For example, the following wikitext could be entered in a sandbox:

== Mixed tests ==
<pre>
{{convert|12|m}}                            12 metres (39 ft)
{{convert/sandbox|0.16|/l|2|disp=table}}    align="right"|0.16\n|align="right"|0.61
{{age in days|2007|5|24|2008|4|23}}         335
--- The following line is incorrect to demonstrate a "fail".
{{convert|12|m|lk=on}}                      12 [[meter|metres]] (39 [[Foot|ft]])
The following line demonstrates the result when no expected text is provided.
{{convert/sandbox|1|-|5|in|mm|lk=on}}
</pre>

Given the above, the tests can be run as shown in the following section.

Instead of specifying the tests with a multiline string, it is possible to assign a table to p.tests as shown in the following testcases module.

local tests = {
    -- Each test item is of form { template, expected }.
    { '{{convert|12|m}}', '12 metres (39 ft)' },
    { '{{convert/sandbox|0.16|/l|2|disp=table}}', 'align="right"|0.16\n|align="right"|0.61' },
    { '{{age in days|2007|5|24|2008|4|23}}', '335' },
    { '{{convert|12|m|lk=on}}', '12 [[meter|metres]] (39 [[Foot|ft]])' },
    { '{{convert/sandbox|1|-|5|in|mm|lk=on}}' },
}

local p = require('Module:Convert/tester')
p.tests = tests
return p

This example provides the same results as the multiline string at "Mixed tests" above.

Запуск тестов с любой страницыПравить

Entering either of the following lines of wikitext in a sandbox or talk page would run the tests found at the specified location. The first line would show all tests on page "Template talk:Example", while the second would show only those tests on that page that are in the "Mixed tests" section.

{{#invoke:convert/tester|run_tests|page=Template talk:Example}}
{{#invoke:convert/tester|run_tests|page=Template talk:Example|section=Mixed tests}}

As a demonstration, the following line is used to produce the table shown below, including the comment that starts with three dashes.

{{#invoke:convert/tester|run_tests|page=Module:Convert/tester/doc|section=Задание тестов|show=all}}

3 tests failed, 1 test ignored because expected text is blank.

Template Expected Actual, if different Status
{{convert|12|m}} 12 metres (39 ft) 12 метров (39 футов) Fail
(above, nowiki) 12 metres (39&nbsp;ft) 12 метров (39&nbsp;[[фут]]ов)
{{convert/sandbox|0.16|/l|2|disp=table}} align="right"|0.16
|align="right"|0.61
style="text-align:right;"|0,16
|style="text-align:right;"|0,61
Fail
(above, nowiki) align="right"|0.16
|align="right"|0.61
style="text-align:right;"|0,16
|style="text-align:right;"|0,61
{{age in days|2007|5|24|2008|4|23}} 335 Pass
The following line is incorrect to demonstrate a "fail". Cmnt
{{convert|12|m|lk=on}} 12 metres (39 ft) 12 метров (39 футов) Fail
(above, nowiki) 12 [[meter|metres]] (39&nbsp;[[Foot|ft]]) 12 [[Метр|метров]] (39&nbsp;[[фут]]ов)
{{convert/sandbox|1|-|5|in|mm|lk=on}} 1–5 дюймов (25–127 мм)

Создание ожидаемых результатовПравить

Функцию make_tests можно использовать для создания тестов в формате, ожидаемом run_tests. For example, previewing either of the following in a sandbox would show the results from expanding each template found on the specified page.

{{#invoke:convert/tester|make_tests|page=Template talk:Example}}
{{#invoke:convert/tester|make_tests|page=Template talk:Example|show=all}}

When using make_tests, any expected results in the input are ignored. Instead, the module shows each template and its actual output as plain text which can be copied to make a testcases page. The templates to be processed can be specified by setting p.tests or by specifying a page with an optional section.

If |show=all is included, any non-template lines are included in the result. The output could then be copied and used to replace the page with the tests in order to update the expected text for each template, but without changing non-template lines.

As a demonstration, the following line is used to produce the text shown below.

{{#invoke:convert/tester|make_tests|page=Module:Convert/tester/doc|section=Задание тестов}}
{{convert|12|m}}                          12 метров (39&nbsp;[[фут]]ов)
{{convert/sandbox|0.16|/l|2|disp=table}}  style="text-align:right;"|0,16\n|style="text-align:right;"|0,61
{{age in days|2007|5|24|2008|4|23}}       335
{{convert|12|m|lk=on}}                    12 [[Метр|метров]] (39&nbsp;[[фут]]ов)
{{convert/sandbox|1|-|5|in|mm|lk=on}}     1–5 [[дюйм|дюймов]] (25–127&nbsp;[[Миллиметр|мм]])

Использование параметра show=allПравить

Параметр |show=all можно использовать как при вызове make_tests так и run_tests.

Пример использования make_tests показан в предыдущем разделе.

Использование |show=all с run_tests добавляет строки комментариев в таблицу результатов, но не все, а только начинающиеся с трёх дефисов. Например, если в тесте указано:

Добавлено 12 января 2014.
--- Следующие тесты проверяют опцию widget.
{{example|1|2|widget=on}}          ...(ожидаемый результат)...

То после вызова run_tests строка "Следующие тесты проверяют опцию widget." появится в таблице результатов, только если задано |show=all. Комментрии имеют особый цвет фона, а в столбце состояния также отображается «Cmnt», чтобы их можно найти легче найти.

Сравнение кода модуля с кодом в песочницеПравить

When viewing a module, the documentation page is displayed; if the module has a sandbox, the documentation includes "Editors can experiment in this module's sandbox" with a link to diff the module and its sandbox.

The tester module provides a compare function which can check a series of modules, and compare each with its sandbox. A table is displayed showing whether the content is different, with a diff link.

For example, the following wikitext could be used.

{{#invoke:convert/tester|compare|Example|Example/data}}

The names "Example" and "Example/data" do not include a colon (:), so "Module:" is assumed. The command compares Module:Example with Module:Example/sandbox, and Module:Example/data with Module:Example/data/sandbox.

It is also possible for a module to define pairs of page titles in p.pairs (a table), and to use the tester module to generate a table for each pair of titles.

The result will be a bulleted list, with each lines starting by '*' and ending by a newline for each pair of compared pages.

The input lists of pairs may also include items that are a string (instead of a table specifying the pair of pages to compare). That string, which can contain any wikitext, will be output as is as a separate line in the result. You can use it to split a long list into sections with some headings. You can also use it to insert one or more comment lines after the results of comparing a pair (just use a static string starting by '*:' to not break the list, and to indent that comment below). For example it is expected that a sandbox should be different from the non-sandbox version of a template if they are only used to call a module and the only difference should be the name of the sandbox module instead of the normal version of that module.

As a convenience, certain keywords are defined in this module: if one of them is recognized, then the actual list of pair comes from the module itself and you don't need to specify a list of pairs. For example, the following uses the "convert" keyword to get the list of pairs of pages related to the Module:Convert.

{{#invoke:convert/tester|compare|convert}}

Результат сравнения может выглядеть так: