Python Monkey Patch Property
Posted : admin On 09.09.2019Is it at all possible to monkey patch the value of a @property of an instance of a class that I do not control? Class Foo: @property def bar(self. Is it at all possible to monkey patch the value of a @property of an instance of a class that I do not control? Class Foo: @property def bar(self.
New in version 3.3. Source code: is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. Provides a core class removing the need to create a host of stubs throughout your test suite. After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. You can also specify return values and set needed attributes in the normal way. Additionally, mock provides a decorator that handles patching module and class level attributes within the scope of a test, along with for creating unique objects.
See the for some examples of how to use, and. Mock is very easy to use and is designed for use with.
Mock is based on the ‘action - assertion’ pattern instead of ‘record - replay’ used by many mocking frameworks. There is a backport of for earlier versions of Python, available as. mock = Mock mock.
str = Mock ( returnvalue = 'wheeeeee' ) str ( mock ) 'wheeeeee' For ensuring that the mock objects in your tests have the same api as the objects they are replacing, you can use. Auto-speccing can be done through the autospec argument to patch, or the function.
See More On Stackoverflow
Auto-speccing creates mock objects that have the same attributes and methods as the objects they are replacing, and any functions and methods (including constructors) have the same call signature as the real object. This ensures that your mocks will fail in the same way as your production code if they are used incorrectly.
from unittest.mock import createautospec def function ( a, b, c ). mockfunction = createautospec ( function, returnvalue = 'fishy' ) mockfunction ( 1, 2, 3 ) 'fishy' mockfunction. Assertcalledoncewith ( 1, 2, 3 ) mockfunction ( 'wrong arguments' ) Traceback (most recent call last). TypeError: takes exactly 3 arguments (1 given) can also be used on classes, where it copies the signature of the init method, and on callable objects where it copies the signature of the call method. The Mock Class is a flexible mock object intended to replace the use of stubs and test doubles throughout your code.
Mocks are callable and create attributes as new mocks when you access them. Accessing the same attribute will always return the same mock. Mocks record how you use them, allowing you to make assertions about what your code has done to them. Is a subclass of with all the magic methods pre-created and ready to use.
There are also non-callable variants, useful when you are mocking out objects that aren’t callable: and The decorators makes it easy to temporarily replace classes in a particular module with a object. By default will create a for you.
You can specify an alternative class of using the newcallable argument to. Class unittest.mock. Mock ( spec=None, sideeffect=None, returnvalue=DEFAULT, wraps=None, name=None, specset=None, unsafe=False,.kwargs ) Create a new object. Takes several optional arguments that specify the behaviour of the Mock object:. spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an.
If spec is an object (rather than a list of strings) then returns the class of the spec object. This allows mocks to pass tests. specset: A stricter variant of spec. If used, attempting to set or get an attribute on the mock that isn’t on the object passed as specset will raise an. sideeffect: A function to be called whenever the Mock is called.
See the attribute. Useful for raising exceptions or dynamically changing return values.
The function is called with the same arguments as the mock, and unless it returns, the return value of this function is used as the return value. Alternatively sideeffect can be an exception class or instance. In this case the exception will be raised when the mock is called.
If sideeffect is an iterable then each call to the mock will return the next value from the iterable. A sideeffect can be cleared by setting it to None. returnvalue: The value returned when the mock is called. By default this is a new Mock (created on first access).
See the attribute. unsafe: By default if any attribute starts with assert or assret will raise an. Passing unsafe=True will allow access to these attributes. New in version 3.5. wraps: Item for the mock object to wrap.
If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an ). If the mock has an explicit returnvalue set then calls are not passed to the wrapped object and the returnvalue is returned instead. name: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks.
Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. See the method for details. Assertcalled (.args,.kwargs ) Assert that the mock was called at least once. mock = Mock ( returnvalue = None ) mock ( 'foo', bar = 'baz' ) mock. Assertcalledoncewith ( 'foo', bar = 'baz' ) mock ( 'other', bar = 'values' ) mock.
Assertcalledoncewith ( 'other', bar = 'values' ) Traceback (most recent call last). AssertionError: Expected 'mock' to be called once. Called 2 times. Assertanycall (.args,.kwargs ) assert the mock has been called with the specified arguments. The assert passes if the mock has ever been called, unlike and that only pass if the call is the most recent one, and in the case of it must also be the only call. mock = Mock ( returnvalue = None ) mock ( 1, 2, arg = 'thing' ) mock ( 'some', 'thing', 'else' ) mock.

Assertanycall ( 1, 2, arg = 'thing' ) asserthascalls ( calls, anyorder=False ) assert the mock has been called with the specified calls. The list is checked for the calls. If anyorder is false (the default) then the calls must be sequential. There can be extra calls before or after the specified calls. If anyorder is true then the calls can be in any order, but they must all appear in. Note returnvalue, and are keyword only argument.
Mockaddspec ( spec, specset=False ) Add a spec to a mock. Spec can either be an object or a list of strings.
Only attributes on the spec can be fetched as attributes from the mock. If specset is true then only attributes on the spec can be set. Attachmock ( mock, attribute ) Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the and attributes of this one. Configuremock (.kwargs ) Set attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call. mock = Mock ( returnvalue = 3 ) mock.
Returnvalue 3 mock 3 sideeffect This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised. If you pass in a function it will be called with same arguments as the mock and unless the function returns the singleton the call to the mock will then return whatever the function returns. If the function returns then the mock will return its normal value (from the ). If you pass in an iterable, it is used to retrieve an iterator which must yield a value on every call. This value can either be an exception instance to be raised, or a value to be returned from the call to the mock ( handling is identical to the function case). An example of a mock that raises an exception (to test exception handling of an API).
mock = Mock ( returnvalue = None ) print ( mock. Callargs ) None mock mock. Callargs call mock. Callargs True mock ( 3, 4 ) mock.
Callargs call(3, 4) mock. Callargs (( 3, 4 ),) True mock ( 3, 4, 5, key = 'fish', next = 'w00t!'
Callargs call(3, 4, 5, key='fish', next='w00t!' ), along with members of the lists, and are objects.
These are tuples, so they can be unpacked to get at the individual arguments and make more complex assertions. Callargslist This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list.
The object can be used for conveniently constructing lists of calls to compare with. mock = MagicMock result = mock ( 1, 2, 3 ) mock. First ( a = 3 ) mock. Second int ( mock ) 1 result ( 1 ) expected = call ( 1, 2, 3 ), call.
First ( a = 3 ), call. int , call ( 1 ) mock. Mockcalls expected True Members of are objects. These can be unpacked as tuples to get at the individual arguments. class Normally the attribute of an object will return its type.

For a mock object with a spec, class returns the spec class instead. This allows mock objects to pass tests for the object they are replacing / masquerading as. class Foo. Def foo ( self ). Return 'something'. Def foo ( self, value ).
with patch ( 'main.Foo.foo', newcallable = PropertyMock ) as mockfoo. Returnvalue = 'mockity-mock'. Thisfoo = Foo. Print ( thisfoo.
Mockity-mock mockfoo. Mockcalls call, call(6) Because of the way mock attributes are stored you can’t directly attach a to a mock object. Instead you can attach it to the mock type object. Calling Mock objects are callable. The call will return the value set as the attribute. The default return value is a new Mock object; it is created the first time the return value is accessed (either explicitly or by calling the Mock) - but it is stored and the same one returned each time. Calls made to the object will be recorded in the attributes like and.
Give More Feedback
If is set then it will be called after the call has been recorded, so if sideeffect raises an exception the call is still recorded. The simplest way to make a mock raise an exception when called is to make an exception class or instance. m = MagicMock ( sideeffect = IndexError ) m ( 1, 2, 3 ) Traceback (most recent call last). IndexError m.
Mockcalls call(1, 2, 3) m. Sideeffect = KeyError ( 'Bang!' ) m ( 'two', 'three', 'four' ) Traceback (most recent call last). KeyError: 'Bang!' Mockcalls call(1, 2, 3), call('two', 'three', 'four') If sideeffect is a function then whatever that function returns is what calls to the mock return. The sideeffect function is called with the same arguments as the mock.
This allows you to vary the return value of the call dynamically, based on the input. thing1 = object thing2 = object parent = MagicMock with patch ( 'main.thing1', returnvalue = None ) as child1. With patch ( 'main.thing2', returnvalue = None ) as child2.
Attachmock ( child1, 'child1' ). Attachmock ( child2, 'child2' ). Child1 ( 'one' ). Child2 ( 'two' ). Mockcalls call.child1('one'), call.child2('two') The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn’t create these but instead raises an.

This is because the interpreter will often implicitly request these methods, and gets very confused to get a new Mock object when it expects a magic method. If you need magic method support see.
Note is straightforward to use. The key is to do the patching in the right namespace.
See the section. Patch ( target, new=DEFAULT, spec=None, create=False, specset=None, autospec=None, newcallable=None,.kwargs ) acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the target is patched with a new object. When the function/with statement exits the patch is undone. If new is omitted, then the target is replaced with a.
If is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function. If is used as a context manager the created mock is returned by the context manager. Target should be a string in the form 'package.module.ClassName'. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling from. The target is imported when the decorated function is executed, not at decoration time. The spec and specset keyword arguments are passed to the if patch is creating one for you. In addition you can pass spec=True or specset=True, which causes patch to pass in the object being mocked as the spec/specset object.
Newcallable allows you to specify a different class, or callable object, that will be called to create the new object. By default is used. A more powerful form of spec is autospec. If you set autospec=True then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a if they are called with the wrong signature.
For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class. See the function and. Instead of autospec=True you can pass autospec=someobject to use an arbitrary object as the spec instead of the one being replaced.