Test Patcher Download

0 views
Skip to first unread message

Jenelle Centeno

unread,
Aug 5, 2024, 3:19:30 AM8/5/24
to chisundpacock
Inmy attempt to learn TDD, trying to learn unit testing and using mock with python. Slowly getting the hang of it, but unsure if I'm doing this correctly. Forewarned: I'm stucking using python 2.4 because the vendor API's come as pre-compiled 2.4 pyc files, so I'm using mock 0.8.0 and unittest ( not unittest2 )

To expand on my answer to question #3, the problem is that the patch() decorator only applies while the decorated function is running. As soon as setUp() returns, the patch is removed. In your case, that works, but I bet it would confuse someone looking at this test. If you really only want the patch to happen during setUp(), I would suggest using the with statement to make it obvious that the patch is going to be removed.


The following example has two test cases. TestPatchAsDecorator shows that decorating the class will apply the patch during the test method, but not during setUp(). TestPatchInSetUp shows how you can apply the patch so that it's in place during both setUp() and the test method. Calling self.addCleanUp() makes sure that the patch will be removed during tearDown().


unittest.mock provides a core Mock class removing the need tocreate a host of stubs throughout your test suite. After performing anaction, you can make assertions about which methods / attributes were usedand arguments they were called with. You can also specify return values andset needed attributes in the normal way.


Additionally, mock provides a patch() decorator that handles patchingmodule and class level attributes within the scope of a test, along withsentinel for creating unique objects. See the quick guide forsome examples of how to use Mock, MagicMock andpatch().


Mock and MagicMock objects create all attributes andmethods as you access them and store details of how they have been used. Youcan configure them, to specify return values or limit what attributes areavailable, and then make assertions about how they have been used:


The patch() decorator / context manager makes it easy to mock classes orobjects in a module under test. The object you specify will be replaced with amock (or other object) during the test and restored when the test ends:


When you nest patch decorators the mocks are passed in to the decoratedfunction in the same order they applied (the normal Python order thatdecorators are applied). This means from the bottom up, so in the exampleabove the mock for module.ClassName1 is passed in first.


Mock allows you to assign functions (or other Mock instances) to magic methodsand they will be called appropriately. The MagicMock class is just a Mockvariant that has all of the magic methods pre-created for you (well, all theuseful ones anyway).


For ensuring that the mock objects in your tests have the same api as theobjects they are replacing, you can use auto-speccing.Auto-speccing can be done through the autospec argument to patch, or thecreate_autospec() function. Auto-speccing creates mock objects thathave the same attributes and methods as the objects they are replacing, andany functions and methods (including constructors) have the same callsignature as the real object.


Mock is a flexible mock object intended to replace the use of stubs andtest doubles throughout your code. Mocks are callable and create attributes asnew mocks when you access them [1]. Accessing the same attribute will alwaysreturn the same mock. Mocks record how you use them, allowing you to makeassertions about what your code has done to them.


The patch() decorators makes it easy to temporarily replace classesin a particular module with a Mock object. By default patch() will createa MagicMock for you. You can specify an alternative class of Mock usingthe new_callable argument to patch().


spec: This can be either a list of strings or an existing object (aclass or instance) that acts as the specification for the mock object. Ifyou pass in an object then a list of strings is formed by calling dir onthe object (excluding unsupported magic attributes and methods).Accessing any attribute not in this list will raise an AttributeError.


side_effect: A function to be called whenever the Mock is called. Seethe side_effect attribute. Useful for raising exceptions ordynamically changing return values. The function is called with the samearguments as the mock, and unless it returns DEFAULT, the returnvalue of this function is used as the return value.


Create the child mocks for attributes and return value.By default child mocks will be the same type as the parent.Subclasses of Mock may want to override this to customize the waychild mocks are made.


If you pass in a function it will be called with same arguments as themock and unless the function returns the DEFAULT singleton thecall to the mock will then return whatever the function returns. If thefunction returns DEFAULT then the mock will return its normalvalue (from the return_value).


If you pass in an iterable, it is used to retrieve an iterator whichmust yield a value on every call. This value can either be an exceptioninstance to be raised, or a value to be returned from the call to themock (DEFAULT handling is identical to the function case).


call_args, along with members of the lists call_args_list,method_calls and mock_calls are call objects.These are tuples, so they can be unpacked to get at the individualarguments and make more complex assertions. Seecalls as tuples.


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 beencalled). Before any calls have been made it is an empty list. Thecall object can be used for conveniently constructing lists ofcalls to compare with call_args_list.


Normally the __class__ attribute of an object will return its type.For a mock object with a spec, __class__ returns the spec classinstead. This allows mock objects to pass isinstance() tests for theobject they are replacing / masquerading as:


The mock classes and the patch() decorators all take arbitrary keywordarguments for configuration. For the patch() decorators the keywords arepassed to the constructor of the mock being created. The keyword argumentsare for configuring attributes of the mock:


Setting the spec of a Mock, MagicMock, or AsyncMockto a class with asynchronous and synchronous functions will automaticallydetect the synchronous functions and set them as MagicMock (if theparent mock is AsyncMock or MagicMock) or Mock (ifthe parent mock is Mock). All asynchronous functions will beAsyncMock.


Mock objects are callable. The call will return the value set as thereturn_value attribute. The default return value is a new Mockobject; it is created the first time the return value is accessed (eitherexplicitly or by calling the Mock) - but it is stored and the same onereturned each time.


If side_effect is a function then whatever that function returns is whatcalls to the mock return. The side_effect function is called with thesame arguments as the mock. This allows you to vary the return value of thecall dynamically, based on the input:


If you want the mock to still return the default return value (a new mock), orany set return value, then there are two ways of doing this. Either returnmock.return_value from inside side_effect, or return DEFAULT:


The patch decorators are used for patching objects only within the scope ofthe function they decorate. They automatically handle the unpatching for you,even if exceptions are raised. All of these functions can also be used in withstatements or as class decorators.


patch() acts as a function decorator, class decorator or a contextmanager. Inside the body of the function or with statement, the targetis patched with a new object. When the function/with statement exitsthe patch is undone.


If new is omitted, then the target is replaced with anAsyncMock if the patched object is an async function ora MagicMock otherwise.If patch() is used as a decorator and new isomitted, the created mock is passed in as an extra argument to thedecorated function. If patch() is used as a context manager the createdmock is returned by the context manager.


target should be a string in the form 'package.module.ClassName'. Thetarget is imported and the specified object replaced with the newobject, so the target must be importable from the environment you arecalling patch() from. The target is imported when the decorated functionis executed, not at decoration time.


Patch can be used as a TestCase class decorator. It works bydecorating each test method in the class. This reduces the boilerplatecode when your test methods share a common patchings set. patch() findstests by looking for method names that start with patch.TEST_PREFIX.By default this is 'test', which matches the way unittest finds tests.You can specify an alternative prefix by setting patch.TEST_PREFIX.


When patch() is creating a mock for you, it is common that the first thingyou need to do is to configure the mock. Some of that configuration can be donein the call to patch. Any arbitrary keywords you pass into the call will beused to set attributes on the created mock:


patch.object() can be used as a decorator, class decorator or a contextmanager. Arguments new, spec, create, spec_set, autospec andnew_callable have the same meaning as for patch(). Like patch(),patch.object() takes arbitrary keyword arguments for configuring the mockobject it creates.


Use DEFAULT as the value if you want patch.multiple() to createmocks for you. In this case the created mocks are passed into a decoratedfunction by keyword, and a dictionary is returned when patch.multiple() isused as a context manager.


patch.multiple() can be used as a decorator, class decorator or a contextmanager. The arguments spec, spec_set, create, autospec andnew_callable have the same meaning as for patch(). These arguments willbe applied to all patches done by patch.multiple().


If you want patch.multiple() to create mocks for you, then you can useDEFAULT as the value. If you use patch.multiple() as a decoratorthen the created mocks are passed into the decorated function by keyword.

3a8082e126
Reply all
Reply to author
Forward
0 new messages