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: TestCase

Save and restore the config.mylang and config.family.

abstract_class = True#
setUp()[source]#

Prepare the environment for running main() in a script.

tearDown()[source]#

Restore the environment.

class tests.aspects.CheckHostnameMixin(methodName='runTest')[source]#

Bases: TestCaseBase

Check 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.

classmethod setUpClass()[source]#

Set up the test class.

Prevent tests running if the host is down.

class tests.aspects.DefaultDrySiteTestCase(*args, **kwargs)[source]#

Bases: DefaultSiteTestCase

Run tests using the config specified site in offline mode.

abstract_class = True#
dry = True#
class tests.aspects.DefaultSiteTestCase(*args, **kwargs)[source]#

Bases: TestCase

Run tests against the config specified site.

abstract_class = True#
code = 'test'#
family = 'wikipedia'#
classmethod override_default_site(site)[source]#

Override the default site.

Parameters:

site (BaseSite) – site tests should use

class tests.aspects.DefaultWikibaseClientTestCase(*args, **kwargs)[source]#

Bases: WikibaseClientTestCase, DefaultSiteTestCase

Run tests against any site connected to a Wikibase.

abstract_class = True#
class tests.aspects.DefaultWikidataClientTestCase(*args, **kwargs)[source]#

Bases: DefaultWikibaseClientTestCase

Run tests against any site connected to Wikidata.

abstract_class = True#
classmethod setUpClass()[source]#

Set up the test class.

Require the data repository is wikidata.org.

class tests.aspects.DeprecationTestCase(*args, **kwargs)[source]#

Bases: TestCase

Test 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 INSTEAD it only counts those supplying an alternative and when NO_INSTEAD only those not supplying one.

assertDeprecationClass(cls)[source]#

Assert that all deprecation warning are of one class.

assertDeprecationFile(filename)[source]#

Assert that all deprecation warning are of one filename.

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.

assertNoDeprecation(msg=None)[source]#

Assert that no deprecation warning happened.

assertOneDeprecation(msg=None, count=1)[source]#

Assert that exactly one deprecation message happened and reset.

assertOneDeprecationParts(deprecated=None, instead=None, count=1)[source]#

Assert that exactly one deprecation message happened and reset.

It uses the same arguments as assertDeprecationParts.

property deprecation_messages#

Return captured deprecation warnings.

setUp()[source]#

Set up unit test.

classmethod setUpClass()[source]#

Only operate in debug mode.

source_adjustment_skips = [<class 'unittest.case._AssertRaisesContext'>, <function TestCase.assertRaises>, <function TestCase.assertRaisesRegex>, <class 'unittest.case._AssertRaisesBaseContext'>]#
tearDown()[source]#

Tear down unit test.

class tests.aspects.DisableSiteMixin(methodName='runTest')[source]#

Bases: TestCaseBase

Test 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.

setUp()[source]#

Set up test.

tearDown()[source]#

Tear down test.

class tests.aspects.DisconnectedSiteMixin(methodName='runTest')[source]#

Bases: TestCaseBase

Test 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.

setUp()[source]#

Set up test.

tearDown()[source]#

Tear down test.

class tests.aspects.ForceCacheMixin(methodName='runTest')[source]#

Bases: TestCaseBase

Aggressively 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.

setUp()[source]#

Set up test.

tearDown()[source]#

Tear down test.

class tests.aspects.HttpbinTestCase(*args, **kwargs)[source]#

Bases: TestCase

Custom test case class, which allows dry httpbin tests with pytest-httpbin.

Test cases, which use httpbin, need to inherit this class.

abstract_class = True#
fetch(*args, **kwargs)[source]#

Delegate http request to http.fetch but skip on ServerError.

get_httpbin_hostname()[source]#

Return httpbin hostname.

get_httpbin_url(path='')[source]#

Return url of httpbin.

sites = {'httpbin': {'hostname': 'httpbin.org'}}#
class tests.aspects.MetaTestCaseClass(name, bases, dct)[source]#

Bases: type

Test meta class.

Create the new class.

static add_base(bases, subclass)[source]#

Return a tuple of bases with the subclasses added if not already.

static add_method(dct, test_name, method, doc=None, doc_suffix=None)[source]#

Set method’s __name__ and __doc__ and add it to dct.

class tests.aspects.NeedRightsMixin(methodName='runTest')[source]#

Bases: TestCaseBase

Require 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.

classmethod setUpClass()[source]#

Set up the test class.

Skip the test class if the user does not have required rights.

class tests.aspects.PatchingTestCase(*args, **kwargs)[source]#

Bases: TestCase

Easily patch and unpatch instances.

abstract_class = True#
patch(obj, attr_name, replacement)[source]#

Patch the obj’s attribute with the replacement.

It will be reset after each tearDown.

static patched(obj, attr_name)[source]#

Apply patching information.

setUp()[source]#

Set up the test by initializing the patched list.

tearDown()[source]#

Tear down the test by unpatching the patched.

class tests.aspects.PwbTestCase(*args, **kwargs)[source]#

Bases: TestCase

Test cases use pwb.py to 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 = False’ is 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#
pwb = True#
setUp()[source]#

Prepare the environment for running the pwb.py script.

tearDown()[source]#

Restore the environment after running the pwb.py script.

class tests.aspects.RecentChangesTestCase(*args, **kwargs)[source]#

Bases: WikimediaDefaultSiteTestCase

Test cases for tests that use recent change.

abstract_class = True#
length = 3#
classmethod setUpClass()[source]#

Set up test class.

class tests.aspects.RequireLoginMixin(methodName='runTest')[source]#

Bases: TestCaseBase

Run 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.

get_userpage(site=None)[source]#

Create a User object for the user’s userpage.

login = True#
classmethod require_site_user(family, code)[source]#

Check the user config has a valid login to the site.

setUp()[source]#

Set up the test case.

Login to the site if it is not logged in.

classmethod setUpClass()[source]#

Set up the test class.

Skip the test class if the user config does not have a valid login to the site.

tearDown()[source]#

Log back into the site.

class tests.aspects.ScriptMainTestCase(*args, **kwargs)[source]#

Bases: AlteredDefaultSiteTestCase

Tests that depend on the default site being set to the test site.

abstract_class = True#
setUp()[source]#

Prepare the environment for running main() in a script.

class tests.aspects.SiteAttributeTestCase(*args, **kwargs)[source]#

Bases: TestCase

Add the sites as attributes to the instances.

abstract_class = True#
classmethod setUpClass()[source]#

Add each initialized site as an attribute to cls.

class tests.aspects.SiteNotPermitted(code, fam=None, user=None)[source]#

Bases: BaseSite

Site interface to prevent sites being loaded.

class tests.aspects.SiteWriteMixin(methodName='runTest')[source]#

Bases: TestCaseBase

Test 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.

If class attribute ‘write’ is -1, the test class is skipped unless environment variable PYWIKIBOT_TEST_WRITE_FAIL is set to 1.

Otherwise the test class is skipped unless environment variable PYWIKIBOT_TEST_WRITE is set to 1.

class tests.aspects.TestCase(*args, **kwargs)[source]#

Bases: TestCaseBase

Run tests on pre-defined sites.

abstract_class = True#
get_mainpage(site=None, force=False)[source]#

Create a Page object for the sites main page.

Parameters:
  • site (pywikibot.site.APISite or None) – Override current site, obtained using get_site.

  • force (bool) – Get an unused Page object

Return type:

Page

get_missing_article(site=None)[source]#

Get a Page which refers to a missing page on the site.

Return type:

Page

classmethod get_site(name=None)[source]#

Return the prefetched Site object.

classmethod has_site_user(family, code)[source]#

Check the user config has a user for the site.

classmethod setUpClass()[source]#

Set up the test class.

Prefetch the Site object for each of the sites the test class has declared are needed.

class tests.aspects.TestCaseBase(methodName='runTest')[source]#

Bases: TestTimerMixin

Base 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.

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’s exception attribute.

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

assertIsEmpty(seq, msg=None)[source]#

Check that the sequence is empty.

assertIsNotEmpty(seq, msg=None)[source]#

Check that the sequence is not empty.

assertLength(seq, other, msg=None)[source]#

Verify that a sequence seq has the length of other.

assertPageInNamespaces(page, namespaces)[source]#

Assert that Pages is in namespaces.

Parameters:
  • page (pywikibot.BasePage) – Page

  • namespaces (int or set of int) – expected namespaces

assertPageTitlesCountEqual(gen, titles, site=None)[source]#

Test that pages in gen match expected titles, regardless of order.

Only iterates to the length of titles plus two.

Parameters:
  • gen (Iterable[Page]) – Page generator

  • titles (iterator) – Expected titles

  • site (pywikibot.site.APISite) – Site of expected pages

assertPageTitlesEqual(gen, titles, site=None)[source]#

Test that pages in gen match expected titles.

Only iterates to the length of titles plus two.

Parameters:
  • gen (Iterable[Page]) – Page generator

  • titles (iterator) – Expected titles

  • site (pywikibot.site.APISite) – Site of expected pages

assertPagesInNamespaces(gen, namespaces)[source]#

Assert that generator returns Pages all in namespaces.

Parameters:
  • gen (generator) – generator to iterate

  • namespaces (int or set of int) – expected namespaces

assertPagesInNamespacesAll(gen, namespaces, skip=False)[source]#

Try to confirm that generator returns Pages for all namespaces.

Parameters:
  • gen (generator) – generator to iterate

  • namespaces (int or set of int) – expected namespaces

  • skip – skip test if not all namespaces found

  • skip – bool

class tests.aspects.TestTimerMixin(methodName='runTest')[source]#

Bases: TestCase

Time 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.

setUp()[source]#

Set up test.

tearDown()[source]#

Tear down test.

test_duration_warning_interval = 10#
class tests.aspects.WikibaseClientTestCase(*args, **kwargs)[source]#

Bases: WikibaseTestCase

Run tests against a specific site connected to a wikibase.

abstract_class = True#
classmethod setUpClass()[source]#

Set up the test class.

Checks that all sites are configured as a Wikibase client, with Site.has_data_repository returning True.

class tests.aspects.WikibaseTestCase(*args, **kwargs)[source]#

Bases: TestCase

Run tests against a wikibase site.

abstract_class = True#
classmethod get_repo()[source]#

Return the prefetched DataSite object.

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.

wikibase = True#
class tests.aspects.WikidataTestCase(*args, **kwargs)[source]#

Bases: WikibaseTestCase

Test cases use Wikidata.

abstract_class = True#
cached = True#
code = 'wikidata'#
family = 'wikidata'#
class tests.aspects.WikimediaDefaultSiteTestCase(*args, **kwargs)[source]#

Bases: DefaultSiteTestCase

Test 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.

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]#

Require minimum MediaWiki version to be queried.

The version needed for the test; must be given with a preleading rich comparisons operator like <1.27wmf4 or >=1.39. If the comparison does not match the test will be skipped.

This decorator can only be used for TestCase having a single site. It cannot be used for DrySite tests. In addition version comparison for other than the current site e.g. for the related data or image repositoy of the current site is ot possible.

New in version 8.0.0.

Parameters:
  • version_needed (str) – The version needed

  • reason (str) – A reason for skipping the test.

Raises:

Exception – Usage validation fails