slidge.util.test#

Module Contents#

Classes#

SlixTestPlus

A Slixmpp specific TestCase class that provides

SlidgeTest

A Slixmpp specific TestCase class that provides

Functions#

reset_subclasses()

Reset registered subclasses between test classes.

class slidge.util.test.SlixTestPlus(*args, **kwargs)#

A Slixmpp specific TestCase class that provides methods for comparing message, iq, and presence stanzas.

Methods:

Message – Create a Message stanza object. Iq – Create an Iq stanza object. Presence – Create a Presence stanza object. check_jid – Check a JID and its component parts. check – Compare a stanza against an XML string. stream_start – Initialize a dummy XMPP client. stream_close – Disconnect the XMPP client. make_header – Create a stream header. send_header – Check that the given header has been sent. send_feature – Send a raw XML element. send – Check that the XMPP client sent the given

generic stanza.

recv – Queue data for XMPP client to receive, or

verify the data that was received from a live connection.

recv_header – Check that a given stream header

was received.

recv_feature – Check that a given, raw XML element

was recveived.

fix_namespaces – Add top-level namespace to an XML object. compare – Compare XML objects against each other.

setUp()#

Hook method for setting up the test fixture before exercising it.

check(stanza, criteria, method='exact', defaults=None, use_values=True)#

Create and compare several stanza objects to a correct XML string.

If use_values is False, tests using stanza.values will not be used.

Some stanzas provide default values for some interfaces, but these defaults can be problematic for testing since they can easily be forgotten when supplying the XML string. A list of interfaces that use defaults may be provided and the generated stanzas will use the default values for those interfaces if needed.

However, correcting the supplied XML is not possible for interfaces that add or remove XML elements. Only interfaces that map to XML attributes may be set using the defaults parameter. The supplied XML must take into account any extra elements that are included by default.

Arguments:

stanza – The stanza object to test. criteria – An expression the stanza must match against. method – The type of matching to use; one of:

‘exact’, ‘mask’, ‘id’, ‘xpath’, and ‘stanzapath’. Defaults to the value of self.match_method.

defaults – A list of stanza interfaces that have default

values. These interfaces will be set to their defaults for the given and generated stanzas to prevent unexpected test failures.

use_values – Indicates if testing using stanza.values should

be used. Defaults to True.

Message(*args, **kwargs)#

Create a Message stanza.

Uses same arguments as StanzaBase.__init__

Arguments:

xml – An XML object to use for the Message’s values.

Iq(*args, **kwargs)#

Create an Iq stanza.

Uses same arguments as StanzaBase.__init__

Arguments:

xml – An XML object to use for the Iq’s values.

Presence(*args, **kwargs)#

Create a Presence stanza.

Uses same arguments as StanzaBase.__init__

Arguments:

xml – An XML object to use for the Iq’s values.

check_jid(jid, user=None, domain=None, resource=None, bare=None, full=None, string=None)#

Verify the components of a JID.

Arguments:

jid – The JID object to test. user – Optional. The user name portion of the JID. domain – Optional. The domain name portion of the JID. resource – Optional. The resource portion of the JID. bare – Optional. The bare JID. full – Optional. The full JID. string – Optional. The string version of the JID.

stream_disconnect()#

Simulate a stream disconnection.

stream_start(mode='client', skip=True, header=None, socket='mock', jid='tester@localhost/resource', password='test', server='localhost', port=5222, sasl_mech=None, plugins=None, plugin_config={})#

Initialize an XMPP client or component using a dummy XML stream.

Arguments:

mode – Either ‘client’ or ‘component’. Defaults to ‘client’. skip – Indicates if the first item in the sent queue (the

stream header) should be removed. Tests that wish to test initializing the stream should set this to False. Otherwise, the default of True should be used.

socket – Either ‘mock’ or ‘live’ to indicate if the socket

should be a dummy, mock socket or a live, functioning socket. Defaults to ‘mock’.

jid – The JID to use for the connection.

Defaults to ‘tester@localhost/resource’.

password – The password to use for the connection.

Defaults to ‘test’.

server – The name of the XMPP server. Defaults to ‘localhost’. port – The port to use when connecting to the server.

Defaults to 5222.

plugins – List of plugins to register. By default, all plugins

are loaded.

make_header(sto='', sfrom='', sid='', stream_ns='http://etherx.jabber.org/streams', default_ns='jabber:client', default_lang='en', version='1.0', xml_header=True)#

Create a stream header to be received by the test XMPP agent.

The header must be saved and passed to stream_start.

Arguments:

sto – The recipient of the stream header. sfrom – The agent sending the stream header. sid – The stream’s id. stream_ns – The namespace of the stream’s root element. default_ns – The default stanza namespace. version – The stream version. xml_header – Indicates if the XML version header should be

appended before the stream header.

recv(data, defaults=None, method='exact', use_values=True, timeout=1)#

Pass data to the dummy XMPP client as if it came from an XMPP server.

If using a live connection, verify what the server has sent.

Arguments:
data – If a dummy socket is being used, the XML that is to

be received next. Otherwise it is the criteria used to match against live data that is received.

defaults – A list of stanza interfaces with default values that

may interfere with comparisons.

method – Select the type of comparison to use for

verifying the received stanza. Options are ‘exact’, ‘id’, ‘stanzapath’, ‘xpath’, and ‘mask’. Defaults to the value of self.match_method.

use_values – Indicates if stanza comparisons should test using

stanza.values. Defaults to True.

timeout – Time to wait in seconds for data to be received by

a live connection.

recv_header(sto='', sfrom='', sid='', stream_ns='http://etherx.jabber.org/streams', default_ns='jabber:client', version='1.0', xml_header=False, timeout=1)#

Check that a given stream header was received.

Arguments:

sto – The recipient of the stream header. sfrom – The agent sending the stream header. sid – The stream’s id. Set to None to ignore. stream_ns – The namespace of the stream’s root element. default_ns – The default stanza namespace. version – The stream version. xml_header – Indicates if the XML version header should be

appended before the stream header.

timeout – Length of time to wait in seconds for a

response.

recv_feature(data, method='mask', use_values=True, timeout=1)#
send_header(sto='', sfrom='', sid='', stream_ns='http://etherx.jabber.org/streams', default_ns='jabber:client', default_lang='en', version='1.0', xml_header=False, timeout=1)#

Check that a given stream header was sent.

Arguments:

sto – The recipient of the stream header. sfrom – The agent sending the stream header. sid – The stream’s id. stream_ns – The namespace of the stream’s root element. default_ns – The default stanza namespace. version – The stream version. xml_header – Indicates if the XML version header should be

appended before the stream header.

timeout – Length of time to wait in seconds for a

response.

send_feature(data, method='mask', use_values=True, timeout=1)#
send(data, defaults=None, use_values=True, timeout=0.5, method='exact')#

Check that the XMPP client sent the given stanza XML.

Extracts the next sent stanza and compares it with the given XML using check.

Arguments:

stanza_class – The class of the sent stanza object. data – The XML string of the expected Message stanza,

or an equivalent stanza object.

use_values – Modifies the type of tests used by check_message. defaults – A list of stanza interfaces that have defaults

values which may interfere with comparisons.

timeout – Time in seconds to wait for a stanza before

failing the check.

method – Select the type of comparison to use for

verifying the sent stanza. Options are ‘exact’, ‘id’, ‘stanzapath’, ‘xpath’, and ‘mask’. Defaults to the value of self.match_method.

stream_close()#

Disconnect the dummy XMPP client.

Can be safely called even if stream_start has not been called.

Must be placed in the tearDown method of a test class to ensure that the XMPP client is disconnected after an error.

fix_namespaces(xml, ns=None)#

Assign a namespace to an element and any children that don’t have a namespace.

Arguments:

xml – The XML object to fix. ns – The namespace to add to the XML object.

compare(xml, *other)#

Compare XML objects.

Arguments:

xml – The XML object to compare against. *other – The list of XML objects to compare.

tearDown()#

Hook method for deconstructing the test fixture after testing it.

addTypeEqualityFunc(typeobj, function)#

Add a type specific assertEqual style function to compare a type.

This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.

Args:
typeobj: The data type to call this function on when both values

are of the same type in assertEqual().

function: The callable taking two arguments and an optional

msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.

addCleanup(function, /, *args, **kwargs)#

Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success.

Cleanup items are called even if setUp fails (unlike tearDown).

enterContext(cm)#

Enters the supplied context manager.

If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method.

classmethod addClassCleanup(function, /, *args, **kwargs)#

Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).

classmethod enterClassContext(cm)#

Same as enterContext, but class-wide.

classmethod setUpClass()#

Hook method for setting up class fixture before running tests in the class.

classmethod tearDownClass()#

Hook method for deconstructing the class fixture after running all tests in the class.

shortDescription()#

Returns a one-line description of the test, or None if no description has been provided.

The default implementation of this method returns the first line of the specified test method’s docstring.

subTest(msg=_subtest_msg_sentinel, **params)#

Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed.

doCleanups()#

Execute all cleanup functions. Normally called for you after tearDown.

classmethod doClassCleanups()#

Execute all class cleanup functions. Normally called for you after tearDownClass.

debug()#

Run the test without collecting errors in a TestResult

skipTest(reason)#

Skip this test.

fail(msg=None)#

Fail immediately, with the given message.

assertFalse(expr, msg=None)#

Check that the expression is false.

assertTrue(expr, msg=None)#

Check that the expression is true.

assertRaises(expected_exception, *args, **kwargs)#

Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertRaises(SomeException):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertRaises is used as a context object.

The context manager keeps a reference to the exception as the ‘exception’ attribute. This allows you to inspect the exception after the assertion:

with self.assertRaises(SomeException) as cm:
    do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
assertWarns(expected_warning, *args, **kwargs)#

Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertWarns(SomeWarning):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertWarns is used as a context object.

The context manager keeps a reference to the first matching warning as the ‘warning’ attribute; similarly, the ‘filename’ and ‘lineno’ attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:

with self.assertWarns(SomeWarning) as cm:
    do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
assertLogs(logger=None, level=None)#

Fail unless a log message of level level or higher is emitted on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger.

This method must be used as a context manager, and will yield a recording object with two attributes: output and records. At the end of the context manager, the output attribute will be a list of the matching formatted log messages and the records attribute will be a list of the corresponding LogRecord objects.

Example:

with self.assertLogs('foo', level='INFO') as cm:
    logging.getLogger('foo').info('first message')
    logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])
assertNoLogs(logger=None, level=None)#

Fail unless no log messages of level level or higher are emitted on logger_name or its children.

This method must be used as a context manager.

assertEqual(first, second, msg=None)#

Fail if the two objects are unequal as determined by the ‘==’ operator.

assertNotEqual(first, second, msg=None)#

Fail if the two objects are equal as determined by the ‘!=’ operator.

assertAlmostEqual(first, second, places=None, msg=None, delta=None)#

Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

If the two objects compare equal then they will automatically compare almost equal.

assertNotAlmostEqual(first, second, places=None, msg=None, delta=None)#

Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

Objects that are equal automatically fail.

assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)#

An equality assertion for ordered sequences (like lists and tuples).

For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.

Args:

seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no

datatype should be enforced.

msg: Optional message to use on failure instead of a list of

differences.

assertListEqual(list1, list2, msg=None)#

A list-specific equality assertion.

Args:

list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of

differences.

assertTupleEqual(tuple1, tuple2, msg=None)#

A tuple-specific equality assertion.

Args:

tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of

differences.

assertSetEqual(set1, set2, msg=None)#

A set-specific equality assertion.

Args:

set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of

differences.

assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).

assertIn(member, container, msg=None)#

Just like self.assertTrue(a in b), but with a nicer default message.

assertNotIn(member, container, msg=None)#

Just like self.assertTrue(a not in b), but with a nicer default message.

assertIs(expr1, expr2, msg=None)#

Just like self.assertTrue(a is b), but with a nicer default message.

assertIsNot(expr1, expr2, msg=None)#

Just like self.assertTrue(a is not b), but with a nicer default message.

assertDictContainsSubset(subset, dictionary, msg=None)#

Checks whether dictionary is a superset of subset.

assertCountEqual(first, second, msg=None)#

Asserts that two iterables have the same elements, the same number of times, without regard to order.

self.assertEqual(Counter(list(first)),

Counter(list(second)))

Example:
  • [0, 1, 1] and [1, 0, 1] compare equal.

  • [0, 0, 1] and [0, 1] compare unequal.

assertMultiLineEqual(first, second, msg=None)#

Assert that two multi-line strings are equal.

assertLess(a, b, msg=None)#

Just like self.assertTrue(a < b), but with a nicer default message.

assertLessEqual(a, b, msg=None)#

Just like self.assertTrue(a <= b), but with a nicer default message.

assertGreater(a, b, msg=None)#

Just like self.assertTrue(a > b), but with a nicer default message.

assertGreaterEqual(a, b, msg=None)#

Just like self.assertTrue(a >= b), but with a nicer default message.

assertIsNone(obj, msg=None)#

Same as self.assertTrue(obj is None), with a nicer default message.

assertIsNotNone(obj, msg=None)#

Included for symmetry with assertIsNone.

assertIsInstance(obj, cls, msg=None)#

Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.

assertNotIsInstance(obj, cls, msg=None)#

Included for symmetry with assertIsInstance.

assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)#

Asserts that the message in a raised exception matches a regex.

Args:

expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected

to be found in error message.

args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used

when assertRaisesRegex is used as a context manager.

assertWarnsRegex(expected_warning, expected_regex, *args, **kwargs)#

Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.

Args:

expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected

to be found in error message.

args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used

when assertWarnsRegex is used as a context manager.

assertRegex(text, expected_regex, msg=None)#

Fail the test unless the text matches the regular expression.

assertNotRegex(text, unexpected_regex, msg=None)#

Fail the test if the text matches the regular expression.

class slidge.util.test.SlidgeTest(*args, **kwargs)#

A Slixmpp specific TestCase class that provides methods for comparing message, iq, and presence stanzas.

Methods:

Message – Create a Message stanza object. Iq – Create an Iq stanza object. Presence – Create a Presence stanza object. check_jid – Check a JID and its component parts. check – Compare a stanza against an XML string. stream_start – Initialize a dummy XMPP client. stream_close – Disconnect the XMPP client. make_header – Create a stream header. send_header – Check that the given header has been sent. send_feature – Send a raw XML element. send – Check that the XMPP client sent the given

generic stanza.

recv – Queue data for XMPP client to receive, or

verify the data that was received from a live connection.

recv_header – Check that a given stream header

was received.

recv_feature – Check that a given, raw XML element

was recveived.

fix_namespaces – Add top-level namespace to an XML object. compare – Compare XML objects against each other.

classmethod setUpClass()#

Hook method for setting up class fixture before running tests in the class.

setUp()#

Hook method for setting up the test fixture before exercising it.

classmethod tearDownClass()#

Hook method for deconstructing the class fixture after running all tests in the class.

check(stanza, criteria, method='exact', defaults=None, use_values=True)#

Create and compare several stanza objects to a correct XML string.

If use_values is False, tests using stanza.values will not be used.

Some stanzas provide default values for some interfaces, but these defaults can be problematic for testing since they can easily be forgotten when supplying the XML string. A list of interfaces that use defaults may be provided and the generated stanzas will use the default values for those interfaces if needed.

However, correcting the supplied XML is not possible for interfaces that add or remove XML elements. Only interfaces that map to XML attributes may be set using the defaults parameter. The supplied XML must take into account any extra elements that are included by default.

Arguments:

stanza – The stanza object to test. criteria – An expression the stanza must match against. method – The type of matching to use; one of:

‘exact’, ‘mask’, ‘id’, ‘xpath’, and ‘stanzapath’. Defaults to the value of self.match_method.

defaults – A list of stanza interfaces that have default

values. These interfaces will be set to their defaults for the given and generated stanzas to prevent unexpected test failures.

use_values – Indicates if testing using stanza.values should

be used. Defaults to True.

Message(*args, **kwargs)#

Create a Message stanza.

Uses same arguments as StanzaBase.__init__

Arguments:

xml – An XML object to use for the Message’s values.

Iq(*args, **kwargs)#

Create an Iq stanza.

Uses same arguments as StanzaBase.__init__

Arguments:

xml – An XML object to use for the Iq’s values.

Presence(*args, **kwargs)#

Create a Presence stanza.

Uses same arguments as StanzaBase.__init__

Arguments:

xml – An XML object to use for the Iq’s values.

check_jid(jid, user=None, domain=None, resource=None, bare=None, full=None, string=None)#

Verify the components of a JID.

Arguments:

jid – The JID object to test. user – Optional. The user name portion of the JID. domain – Optional. The domain name portion of the JID. resource – Optional. The resource portion of the JID. bare – Optional. The bare JID. full – Optional. The full JID. string – Optional. The string version of the JID.

stream_disconnect()#

Simulate a stream disconnection.

stream_start(mode='client', skip=True, header=None, socket='mock', jid='tester@localhost/resource', password='test', server='localhost', port=5222, sasl_mech=None, plugins=None, plugin_config={})#

Initialize an XMPP client or component using a dummy XML stream.

Arguments:

mode – Either ‘client’ or ‘component’. Defaults to ‘client’. skip – Indicates if the first item in the sent queue (the

stream header) should be removed. Tests that wish to test initializing the stream should set this to False. Otherwise, the default of True should be used.

socket – Either ‘mock’ or ‘live’ to indicate if the socket

should be a dummy, mock socket or a live, functioning socket. Defaults to ‘mock’.

jid – The JID to use for the connection.

Defaults to ‘tester@localhost/resource’.

password – The password to use for the connection.

Defaults to ‘test’.

server – The name of the XMPP server. Defaults to ‘localhost’. port – The port to use when connecting to the server.

Defaults to 5222.

plugins – List of plugins to register. By default, all plugins

are loaded.

make_header(sto='', sfrom='', sid='', stream_ns='http://etherx.jabber.org/streams', default_ns='jabber:client', default_lang='en', version='1.0', xml_header=True)#

Create a stream header to be received by the test XMPP agent.

The header must be saved and passed to stream_start.

Arguments:

sto – The recipient of the stream header. sfrom – The agent sending the stream header. sid – The stream’s id. stream_ns – The namespace of the stream’s root element. default_ns – The default stanza namespace. version – The stream version. xml_header – Indicates if the XML version header should be

appended before the stream header.

recv(data, defaults=None, method='exact', use_values=True, timeout=1)#

Pass data to the dummy XMPP client as if it came from an XMPP server.

If using a live connection, verify what the server has sent.

Arguments:
data – If a dummy socket is being used, the XML that is to

be received next. Otherwise it is the criteria used to match against live data that is received.

defaults – A list of stanza interfaces with default values that

may interfere with comparisons.

method – Select the type of comparison to use for

verifying the received stanza. Options are ‘exact’, ‘id’, ‘stanzapath’, ‘xpath’, and ‘mask’. Defaults to the value of self.match_method.

use_values – Indicates if stanza comparisons should test using

stanza.values. Defaults to True.

timeout – Time to wait in seconds for data to be received by

a live connection.

recv_header(sto='', sfrom='', sid='', stream_ns='http://etherx.jabber.org/streams', default_ns='jabber:client', version='1.0', xml_header=False, timeout=1)#

Check that a given stream header was received.

Arguments:

sto – The recipient of the stream header. sfrom – The agent sending the stream header. sid – The stream’s id. Set to None to ignore. stream_ns – The namespace of the stream’s root element. default_ns – The default stanza namespace. version – The stream version. xml_header – Indicates if the XML version header should be

appended before the stream header.

timeout – Length of time to wait in seconds for a

response.

recv_feature(data, method='mask', use_values=True, timeout=1)#
send_header(sto='', sfrom='', sid='', stream_ns='http://etherx.jabber.org/streams', default_ns='jabber:client', default_lang='en', version='1.0', xml_header=False, timeout=1)#

Check that a given stream header was sent.

Arguments:

sto – The recipient of the stream header. sfrom – The agent sending the stream header. sid – The stream’s id. stream_ns – The namespace of the stream’s root element. default_ns – The default stanza namespace. version – The stream version. xml_header – Indicates if the XML version header should be

appended before the stream header.

timeout – Length of time to wait in seconds for a

response.

send_feature(data, method='mask', use_values=True, timeout=1)#
send(data, defaults=None, use_values=True, timeout=0.5, method='exact')#

Check that the XMPP client sent the given stanza XML.

Extracts the next sent stanza and compares it with the given XML using check.

Arguments:

stanza_class – The class of the sent stanza object. data – The XML string of the expected Message stanza,

or an equivalent stanza object.

use_values – Modifies the type of tests used by check_message. defaults – A list of stanza interfaces that have defaults

values which may interfere with comparisons.

timeout – Time in seconds to wait for a stanza before

failing the check.

method – Select the type of comparison to use for

verifying the sent stanza. Options are ‘exact’, ‘id’, ‘stanzapath’, ‘xpath’, and ‘mask’. Defaults to the value of self.match_method.

stream_close()#

Disconnect the dummy XMPP client.

Can be safely called even if stream_start has not been called.

Must be placed in the tearDown method of a test class to ensure that the XMPP client is disconnected after an error.

fix_namespaces(xml, ns=None)#

Assign a namespace to an element and any children that don’t have a namespace.

Arguments:

xml – The XML object to fix. ns – The namespace to add to the XML object.

compare(xml, *other)#

Compare XML objects.

Arguments:

xml – The XML object to compare against. *other – The list of XML objects to compare.

tearDown()#

Hook method for deconstructing the test fixture after testing it.

addTypeEqualityFunc(typeobj, function)#

Add a type specific assertEqual style function to compare a type.

This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.

Args:
typeobj: The data type to call this function on when both values

are of the same type in assertEqual().

function: The callable taking two arguments and an optional

msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.

addCleanup(function, /, *args, **kwargs)#

Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success.

Cleanup items are called even if setUp fails (unlike tearDown).

enterContext(cm)#

Enters the supplied context manager.

If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method.

classmethod addClassCleanup(function, /, *args, **kwargs)#

Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).

classmethod enterClassContext(cm)#

Same as enterContext, but class-wide.

shortDescription()#

Returns a one-line description of the test, or None if no description has been provided.

The default implementation of this method returns the first line of the specified test method’s docstring.

subTest(msg=_subtest_msg_sentinel, **params)#

Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed.

doCleanups()#

Execute all cleanup functions. Normally called for you after tearDown.

classmethod doClassCleanups()#

Execute all class cleanup functions. Normally called for you after tearDownClass.

debug()#

Run the test without collecting errors in a TestResult

skipTest(reason)#

Skip this test.

fail(msg=None)#

Fail immediately, with the given message.

assertFalse(expr, msg=None)#

Check that the expression is false.

assertTrue(expr, msg=None)#

Check that the expression is true.

assertRaises(expected_exception, *args, **kwargs)#

Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertRaises(SomeException):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertRaises is used as a context object.

The context manager keeps a reference to the exception as the ‘exception’ attribute. This allows you to inspect the exception after the assertion:

with self.assertRaises(SomeException) as cm:
    do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
assertWarns(expected_warning, *args, **kwargs)#

Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertWarns(SomeWarning):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertWarns is used as a context object.

The context manager keeps a reference to the first matching warning as the ‘warning’ attribute; similarly, the ‘filename’ and ‘lineno’ attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:

with self.assertWarns(SomeWarning) as cm:
    do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
assertLogs(logger=None, level=None)#

Fail unless a log message of level level or higher is emitted on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger.

This method must be used as a context manager, and will yield a recording object with two attributes: output and records. At the end of the context manager, the output attribute will be a list of the matching formatted log messages and the records attribute will be a list of the corresponding LogRecord objects.

Example:

with self.assertLogs('foo', level='INFO') as cm:
    logging.getLogger('foo').info('first message')
    logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])
assertNoLogs(logger=None, level=None)#

Fail unless no log messages of level level or higher are emitted on logger_name or its children.

This method must be used as a context manager.

assertEqual(first, second, msg=None)#

Fail if the two objects are unequal as determined by the ‘==’ operator.

assertNotEqual(first, second, msg=None)#

Fail if the two objects are equal as determined by the ‘!=’ operator.

assertAlmostEqual(first, second, places=None, msg=None, delta=None)#

Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

If the two objects compare equal then they will automatically compare almost equal.

assertNotAlmostEqual(first, second, places=None, msg=None, delta=None)#

Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

Objects that are equal automatically fail.

assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)#

An equality assertion for ordered sequences (like lists and tuples).

For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.

Args:

seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no

datatype should be enforced.

msg: Optional message to use on failure instead of a list of

differences.

assertListEqual(list1, list2, msg=None)#

A list-specific equality assertion.

Args:

list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of

differences.

assertTupleEqual(tuple1, tuple2, msg=None)#

A tuple-specific equality assertion.

Args:

tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of

differences.

assertSetEqual(set1, set2, msg=None)#

A set-specific equality assertion.

Args:

set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of

differences.

assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).

assertIn(member, container, msg=None)#

Just like self.assertTrue(a in b), but with a nicer default message.

assertNotIn(member, container, msg=None)#

Just like self.assertTrue(a not in b), but with a nicer default message.

assertIs(expr1, expr2, msg=None)#

Just like self.assertTrue(a is b), but with a nicer default message.

assertIsNot(expr1, expr2, msg=None)#

Just like self.assertTrue(a is not b), but with a nicer default message.

assertDictContainsSubset(subset, dictionary, msg=None)#

Checks whether dictionary is a superset of subset.

assertCountEqual(first, second, msg=None)#

Asserts that two iterables have the same elements, the same number of times, without regard to order.

self.assertEqual(Counter(list(first)),

Counter(list(second)))

Example:
  • [0, 1, 1] and [1, 0, 1] compare equal.

  • [0, 0, 1] and [0, 1] compare unequal.

assertMultiLineEqual(first, second, msg=None)#

Assert that two multi-line strings are equal.

assertLess(a, b, msg=None)#

Just like self.assertTrue(a < b), but with a nicer default message.

assertLessEqual(a, b, msg=None)#

Just like self.assertTrue(a <= b), but with a nicer default message.

assertGreater(a, b, msg=None)#

Just like self.assertTrue(a > b), but with a nicer default message.

assertGreaterEqual(a, b, msg=None)#

Just like self.assertTrue(a >= b), but with a nicer default message.

assertIsNone(obj, msg=None)#

Same as self.assertTrue(obj is None), with a nicer default message.

assertIsNotNone(obj, msg=None)#

Included for symmetry with assertIsNone.

assertIsInstance(obj, cls, msg=None)#

Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.

assertNotIsInstance(obj, cls, msg=None)#

Included for symmetry with assertIsInstance.

assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)#

Asserts that the message in a raised exception matches a regex.

Args:

expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected

to be found in error message.

args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used

when assertRaisesRegex is used as a context manager.

assertWarnsRegex(expected_warning, expected_regex, *args, **kwargs)#

Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.

Args:

expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected

to be found in error message.

args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used

when assertWarnsRegex is used as a context manager.

assertRegex(text, expected_regex, msg=None)#

Fail the test unless the text matches the regular expression.

assertNotRegex(text, unexpected_regex, msg=None)#

Fail the test if the text matches the regular expression.

slidge.util.test.reset_subclasses()#

Reset registered subclasses between test classes.

Needed because these classes are meant to only be subclassed once and raise exceptions otherwise.