Skip to main content

TestContextDecorator

A base class that can either be used as a context manager during tests or as a test function or unittest.TestCase subclass decorator to perform temporary alterations.

Attributes

AttributeTypeDescription
attr_namestring = Noneattribute assigned the return value of enable() if used as a class decorator.
kwarg_namestring = Nonekeyword argument passing the return value of enable() if used as a function decorator.

Constructor

Signature

def TestContextDecorator(
attr_name: string = None,
kwarg_name: string = None
) - > null

Parameters

NameTypeDescription
attr_namestring = NoneThe name of the attribute to which the return value of enable() is assigned when used as a class decorator.
kwarg_namestring = NoneThe name of the keyword argument used to pass the return value of enable() when used as a function decorator.

Methods


enable()

@classmethod
def enable() - > any

Activates the temporary alterations and returns an object to be used within the test context; must be implemented by subclasses.

Returns

TypeDescription
anyThe context object or resource being enabled for the duration of the test.

disable()

@classmethod
def disable() - > null

Reverts the temporary alterations made by the enable method; must be implemented by subclasses.

Returns

TypeDescription
nullNothing is returned.

decorate_class()

@classmethod
def decorate_class(
cls: type
) - > type

Wraps a unittest.TestCase subclass to enable the context during setUp and automatically disable it via addCleanup.

Parameters

NameTypeDescription
clstypeThe unittest.TestCase subclass to be decorated.

Returns

TypeDescription
typeThe decorated unittest.TestCase subclass with modified setUp logic.

decorate_callable()

@classmethod
def decorate_callable(
func: callable
) - > callable

Wraps a function or coroutine to execute within the context manager, optionally passing the context as a keyword argument.

Parameters

NameTypeDescription
funccallableThe function or coroutine to be decorated.

Returns

TypeDescription
callableA wrapped version of the original function or coroutine that manages the context lifecycle.