tests.aspects module#
Test aspects to allow fine grained control over what tests are executed.
Several parts of the test infrastructure are implemented as mixins, such as API result caching and excessive test durations.
- class tests.aspects.AlteredDefaultSiteTestCase(*args, **kwargs)[source]#
Bases:
TestCaseSave and restore the config.mylang and config.family.
- abstract_class = True#
- class tests.aspects.CheckHostnameMixin(methodName='runTest')[source]#
Bases:
TestCaseBaseCheck the hostname is online before running tests.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- class tests.aspects.DefaultDrySiteTestCase(*args, **kwargs)[source]#
Bases:
DefaultSiteTestCaseRun tests using the config specified site in offline mode.
- abstract_class = True#
- dry = True#
- class tests.aspects.DefaultSiteTestCase(*args, **kwargs)[source]#
Bases:
TestCaseRun tests against the config specified site.
- abstract_class = True#
- code = 'test'#
- family = 'wikipedia'#
- class tests.aspects.DefaultWikibaseClientTestCase(*args, **kwargs)[source]#
Bases:
WikibaseClientTestCase,DefaultSiteTestCaseRun tests against any site connected to a Wikibase.
- abstract_class = True#
- class tests.aspects.DefaultWikidataClientTestCase(*args, **kwargs)[source]#
Bases:
DefaultWikibaseClientTestCaseRun tests against any site connected to Wikidata.
- abstract_class = True#
- class tests.aspects.DeprecationTestCase(*args, **kwargs)[source]#
Bases:
TestCaseTest cases for deprecation function in the tools module.
- INSTEAD = <object object>#
- NO_INSTEAD = <object object>#
- abstract_class = True#
- assertDeprecation(msg=None)[source]#
Assert that a deprecation warning happened.
- Parameters:
msg (str or None or INSTEAD or NO_INSTEAD) – Either the specific message or None to allow any generic message. When set to
INSTEADit only counts those supplying an alternative and whenNO_INSTEADonly those not supplying one.- Return type:
None
- assertDeprecationClass(cls)[source]#
Assert that all deprecation warning are of one class.
- Return type:
None
- assertDeprecationFile(filename)[source]#
Assert that all deprecation warning are of one filename.
- Return type:
None
- assertDeprecationParts(deprecated=None, instead=None)[source]#
Assert that a deprecation warning happened.
To simplify deprecation tests it just requires the to separated parts and forwards the result to
assertDeprecation.- Parameters:
deprecated (str or None) – The deprecated string. If None it uses a generic match depending on instead.
instead (str or None or True or False) – The instead string unless deprecated is None. If it’s None it allows any generic deprecation string, on True only those where instead string is present and on False only those where it’s missing. If the deprecation string is not None, no instead string is expected when instead evaluates to False.
- Return type:
None
- assertNoDeprecation(msg=None)[source]#
Assert that no deprecation warning happened.
- Return type:
None
- assertOneDeprecation(msg=None, count=1)[source]#
Assert that exactly one deprecation message happened and reset.
- Return type:
None
- assertOneDeprecationParts(deprecated=None, instead=None, count=1)[source]#
Assert that exactly one deprecation message happened and reset.
It uses the same arguments as
assertDeprecationParts.- Return type:
None
- property deprecation_messages#
Return captured deprecation warnings.
- source_adjustment_skips = [<class 'unittest.case._AssertRaisesBaseContext'>, <class 'unittest.case._AssertRaisesContext'>, <function TestCase.assertRaises>, <function TestCase.assertRaisesRegex>]#
- class tests.aspects.DisableSiteMixin(methodName='runTest')[source]#
Bases:
TestCaseBaseTest cases not connected to a Site object.
Do not use this for mock Site objects.
Never set a class or instance variable called ‘site’ As it will prevent tests from executing when invoked as: $ pytest -a ‘not site’
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- class tests.aspects.DisconnectedSiteMixin(methodName='runTest')[source]#
Bases:
TestCaseBaseTest cases using a disconnected Site object.
Do not use this for mock Site objects.
Never set a class or instance variable called ‘site’ As it will prevent tests from executing when invoked as: $ pytest -a ‘not site’
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- class tests.aspects.ForceCacheMixin(methodName='runTest')[source]#
Bases:
TestCaseBaseAggressively cached API test cases.
Patches pywikibot.data.api to aggressively cache API responses.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- class tests.aspects.HttpbinTestCase(*args, **kwargs)[source]#
Bases:
TestCaseCustom test case class, which allows dry httpbin tests.
Test cases, which use httpbin, need to inherit this class.
- abstract_class = True#
- sites = {'httpbin': {'hostname': 'httpbin.org'}}#
- class tests.aspects.MetaTestCaseClass(name, bases, dct)[source]#
Bases:
typeTest meta class.
Create the new class.
Changed in version 9.3: raises AttributeError instead of AssertionError for duplicated hostname, raises Exception instead of AssertionError for missing or wrong “net” attribute with hostnames.
- Raises:
AttributeError – hostname already found
Exception – Test classes using “pwb” must set “site” or test classes without a “site” configured must set “net” or test method must accept either 1 or 2 arguments or “net” must be True with hostnames defined.
- class tests.aspects.NeedRightsMixin(methodName='runTest')[source]#
Bases:
TestCaseBaseRequire specific rights.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- class tests.aspects.PatchingTestCase(*args, **kwargs)[source]#
Bases:
TestCaseEasily patch and unpatch instances.
- abstract_class = True#
- class tests.aspects.PwbTestCase(*args, **kwargs)[source]#
Bases:
TestCaseTest cases use
pwbto invoke scripts.Test cases which use pwb typically also access a site, and use the network. Even during initialisation, scripts may call
pywikibot.handle_args(), which initialises loggers and uses the network to determine if the code is stale.The flag ‘pwb’ is used by the TestCase metaclass to check that a test site is set declared in the class properties, or that
site = Falseis added to the class properties in the unlikely scenario that the test case uses pwb in a way that doesn’t use a site.If a test class is marked as
site = False , the metaclass will also check that the ``net`flag is explicitly set.- abstract_class = True#
- execute(args, **kwargs)[source]#
Run
tests.utils.execute_pwb()with default site.Changed in version 9.1: pass all arguments to
tests.utils.execute_pwb(); make this method public.- Parameters:
args (list[str]) –
pwbwarapper script argumentskwargs – keyword arguments of
tests.utils.execute_pwb()
- pwb = True#
- class tests.aspects.Python314AssertionsMixin[source]#
Bases:
objectMixin providing assertion methods added in Python 3.14 for unittest.
This mixin ensures TestCase compatibility on older Python versions.
The mixin will be removed without deprecation period once Python 3.14 becomes the minimum requirement for Pywikibot, likely with Pywikibot 16.
Added in version 10.3.
- assertEndsWith(s, suffix, msg=None)[source]#
Fail if the string s does not end with suffix.
- Parameters:
s (str) – The string to check.
suffix (str) – The expected suffix.
msg (str | None) – Optional custom failure message.
- Return type:
None
- assertHasAttr(obj, name, msg=None)[source]#
Fail if the object obj does not have an attribute name.
- Parameters:
obj (object) – The object to check.
name (str) – The expected attribute name.
msg (str | None) – Optional custom failure message.
- Return type:
None
- assertIsSubclass(cls, superclass, msg=None)[source]#
Fail if cls is not a subclass of superclass.
- Parameters:
cls (type) – The class to test.
superclass (type | tuple[type, ...]) – The expected superclass or tuple of superclasses.
msg (str | None) – Optional custom failure message.
- Return type:
None
- assertNotEndsWith(s, suffix, msg=None)[source]#
Fail if the string s ends with suffix.
- Parameters:
s (str) – The string to check.
suffix (str) – The unwanted suffix.
msg (str | None) – Optional custom failure message.
- Return type:
None
- assertNotHasAttr(obj, name, msg=None)[source]#
Fail if the object obj has an attribute name.
- Parameters:
obj (object) – The object to check.
name (str) – The unwanted attribute name.
msg (str | None) – Optional custom failure message.
- Return type:
None
- assertNotIsSubclass(cls, superclass, msg=None)[source]#
Fail if cls is a subclass of superclass.
- Parameters:
cls (type) – The class to test.
superclass (type | tuple[type, ...]) – The superclass or tuple of superclasses to reject.
msg (str | None) – Optional custom failure message.
- Return type:
None
- class tests.aspects.RecentChangesTestCase(*args, **kwargs)[source]#
Bases:
WikimediaDefaultSiteTestCaseTest cases for tests that use recent change.
- abstract_class = True#
- length = 3#
- class tests.aspects.RequireLoginMixin(methodName='runTest')[source]#
Bases:
TestCaseBaseRun tests against a specific site, with a login.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- classmethod require_site_user(family, code)[source]#
Check the user config has a valid login to the site.
- Return type:
None
- class tests.aspects.ScriptMainTestCase(*args, **kwargs)[source]#
Bases:
AlteredDefaultSiteTestCaseTests that depend on the default site being set to the test site.
- abstract_class = True#
- class tests.aspects.SiteAttributeTestCase(*args, **kwargs)[source]#
Bases:
TestCaseAdd the sites as attributes to the instances.
- abstract_class = True#
- class tests.aspects.SiteNotPermitted(code, fam=None, user=None)[source]#
Bases:
BaseSiteSite interface to prevent sites being loaded.
- class tests.aspects.SiteWriteMixin(methodName='runTest')[source]#
Bases:
TestCaseBaseTest cases involving writing to the server.
When editing, the API should not be patched to use CachedRequest. This class prevents that.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- classmethod setUpClass()[source]#
Set up the test class.
Reject write test classes configured with non-test wikis, or caching. Prevent test classes from writing to the site by default.
The test class is skipped unless environment variable
PYWIKIBOT_TEST_WRITEis set to 1.Changed in version 9.2:
PYWIKIBOT_TEST_WRITE_FAILenvironment variable was discarded, see Environment variables.- Raises:
Exception – test class cannot use write attribute together with cached and must be run on test sites only.
- Return type:
None
- class tests.aspects.TestCase(*args, **kwargs)[source]#
Bases:
TestCaseBaseRun tests on pre-defined sites.
- abstract_class = True#
- get_missing_article(site=None)[source]#
Get a Page which refers to a missing page on the site.
- Return type:
- classmethod get_site(name=None)[source]#
Return the prefetched Site object.
Changed in version 9.3: raises Exception instead of AssertionError for site mismatch
- Raises:
Exception – method called for multiple sites without name argument given or name not found in sites attribute or cls.site is not equal to cls.sites content for the given name.
- class tests.aspects.TestCaseBase(methodName='runTest')[source]#
Bases:
TestTimerMixin,Python314AssertionsMixinBase class for all tests.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- _get_gen_pages(gen, site=None)[source]#
Get pages from gen, asserting they are Page from site.
Changed in version 9.3: the count parameter was dropped; all pages from gen are tested.
- assertAPIError(code, info=None, callable_obj=None, *args, regex=None, **kwargs)[source]#
Assert that a specific APIError wrapped around
assertRaises.If no callable object is defined and it returns a context manager, that context manager will return the underlying context manager used by
assertRaises. So it’s possible to access the APIError by using it’sexceptionattribute.- Parameters:
code (str) – The code of the error which must have happened.
info (str or None) – The info string of the error or None if no it shouldn’t be checked.
callable_obj (callable) – The object that will be tested. If None it returns a context manager like
assertRaises.args – The positional arguments forwarded to the callable object.
kwargs – The keyword arguments forwarded to the callable object.
- Returns:
Context manager if callable_obj is None and None otherwise.
- Return type:
None or context manager
- assertLength(seq, other, msg=None)[source]#
Verify that a sequence seq has the length of other.
- Return type:
None
- assertPageInNamespaces(page, namespaces)[source]#
Assert that Pages is in namespaces.
- Parameters:
page (pywikibot.BasePage) – Page
namespaces (int | set[int]) – expected namespaces
- Return type:
None
- assertPageTitlesCountEqual(gen, titles, site=None)[source]#
Test that pages in gen match expected titles, regardless of order.
- assertPageTitlesEqual(gen, titles, site=None)[source]#
Test that pages in gen match expected titles.
- assertPagesInNamespaces(gen, namespaces)[source]#
Assert that generator returns Pages all in namespaces.
- Parameters:
gen (generator) – generator to iterate
namespaces (int | set[int]) – expected namespaces
- Return type:
None
- assertPagesInNamespacesAll(gen, namespaces, skip=False)[source]#
Try to confirm that generator returns Pages for all namespaces.
Changed in version 9.3: raises TypeError instead of AssertionError
- Parameters:
gen (generator) – generator to iterate
namespaces (int | set[int]) – expected namespaces
skip (bool) – skip test if not all namespaces found
- Raises:
TypeError – Invalid namespaces type
- Return type:
None
- class tests.aspects.TestTimerMixin(methodName='runTest')[source]#
Bases:
TestCaseTime each test and report excessive durations.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
- test_duration_warning_interval = 10#
- class tests.aspects.WikibaseClientTestCase(*args, **kwargs)[source]#
Bases:
WikibaseTestCaseRun tests against a specific site connected to a wikibase.
- abstract_class = True#
- class tests.aspects.WikibaseTestCase(*args, **kwargs)[source]#
Bases:
TestCaseRun tests against a wikibase site.
- abstract_class = True#
- classmethod setUpClass()[source]#
Set up the test class.
Checks that all sites are configured with a Wikibase repository, with Site.has_data_repository() returning True, and all sites use the same data repository.
- Return type:
None
- wikibase = True#
- class tests.aspects.WikidataTestCase(*args, **kwargs)[source]#
Bases:
WikibaseTestCaseTest cases use Wikidata.
- abstract_class = True#
- cached = True#
- code = 'wikidata'#
- family = 'wikidata'#
- class tests.aspects.WikimediaDefaultSiteTestCase(*args, **kwargs)[source]#
Bases:
DefaultSiteTestCaseTest class to run against a WMF site, preferring the default site.
- abstract_class = True#
- classmethod setUpClass()[source]#
Set up the test class.
Check that the default site is a Wikimedia site. Use en.wikipedia.org as a fallback.
Changed in version 9.3: raises Exception instead of AssertionError
- Raises:
Exception – “site” or “sites” attribute is missing or “sites” entries count is different from 1.
- Return type:
None
- tests.aspects.require_modules(*required_modules)[source]#
Require that the given list of modules can be imported.
- tests.aspects.require_version(version_needed, /, reason='')[source]#
Skip test unless a minimum MediaWiki version is available.
The required version must include a comparison operator (e.g.
<1.31wmf4or>=1.43). If the site’s version does not satisfy the condition, the test is skipped.This decorator can only be used for
TestCasehaving a single site. It cannot be used for DrySite tests. Version checks are only supported for the current site — not for related sites like data or image repositories.Added in version 8.0.
Changed in version 10.0: TypeError and ValueError are used for validation fails. version_needed parameter is positional only.
- Parameters:
version_needed (str) – The version needed
reason (str) – A reason for skipping the test.
- Raises:
TypeError – self.site is not a BaseSite or the decorated method has parameters.
ValueError – The given version_needed parameter is invalid or an operand is given on the left or the version number is invalid