# Copyright (C) 2001-2018, Python Software Foundation # For licence information, see README file. # msgid "" msgstr "" "Project-Id-Version: Python 3\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2023-01-15 22:33+0100\n" "PO-Revision-Date: 2019-12-01 23:32+0100\n" "Last-Translator: \n" "Language-Team: FRENCH \n" "Language: fr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Poedit 2.2.1\n" #: library/unittest.mock-examples.rst:2 msgid ":mod:`unittest.mock` --- getting started" msgstr "" #: library/unittest.mock-examples.rst:27 msgid "Using Mock" msgstr "Utilisation de Mock ou l'art de singer" #: library/unittest.mock-examples.rst:30 msgid "Mock Patching Methods" msgstr "Simulation des méthodes" #: library/unittest.mock-examples.rst:32 msgid "Common uses for :class:`Mock` objects include:" msgstr "Usages courant de :class:`Mock` :" #: library/unittest.mock-examples.rst:34 msgid "Patching methods" msgstr "Substitution des méthodes" #: library/unittest.mock-examples.rst:35 msgid "Recording method calls on objects" msgstr "Enregistrement des appels faits sur les objets" #: library/unittest.mock-examples.rst:37 msgid "" "You might want to replace a method on an object to check that it is called " "with the correct arguments by another part of the system:" msgstr "" "On peut remplacer une méthode sur un objet pour contrôler qu'elle est bien " "appelée avec le nombre correct d'arguments :" #: library/unittest.mock-examples.rst:45 msgid "" "Once our mock has been used (``real.method`` in this example) it has methods " "and attributes that allow you to make assertions about how it has been used." msgstr "" "Une fois notre objet simulacre appelé (via ``real.method`` dans notre " "exemple), il fournit des méthodes et attributs permettant de valider comment " "il a été appelé." #: library/unittest.mock-examples.rst:50 msgid "" "In most of these examples the :class:`Mock` and :class:`MagicMock` classes " "are interchangeable. As the ``MagicMock`` is the more capable class it makes " "a sensible one to use by default." msgstr "" "Dans la majeure partie des exemples donnés ici, les classes :class:`Mock` " "et :class:`MagicMock` sont interchangeables. Étant donné que ``MagicMock`` " "est la classe la plus puissante des deux, cela fait sens de l'utiliser par " "défaut." #: library/unittest.mock-examples.rst:54 msgid "" "Once the mock has been called its :attr:`~Mock.called` attribute is set to " "``True``. More importantly we can use the :meth:`~Mock.assert_called_with` " "or :meth:`~Mock.assert_called_once_with` method to check that it was called " "with the correct arguments." msgstr "" "Une fois l'objet Mock appelé, son attribut :attr:`~Mock.called` est défini à " "``True``. Qui plus est, nous pouvons utiliser les méthodes :meth:`~Mock." "assert_called_with` ou :meth:`~Mock.assert_called_once_with` pour contrôler " "qu'il a été appelé avec les bons arguments." #: library/unittest.mock-examples.rst:59 msgid "" "This example tests that calling ``ProductionClass().method`` results in a " "call to the ``something`` method:" msgstr "" "Cet exemple teste que l'appel de la méthode ``ProductionClass().method`` " "implique bien celui de la méthode ``something`` :" #: library/unittest.mock-examples.rst:76 msgid "Mock for Method Calls on an Object" msgstr "S'assurer de la bonne utilisation d'un objet" #: library/unittest.mock-examples.rst:78 msgid "" "In the last example we patched a method directly on an object to check that " "it was called correctly. Another common use case is to pass an object into a " "method (or some part of the system under test) and then check that it is " "used in the correct way." msgstr "" "Dans l'exemple précédent, nous avons directement remplacé une méthode par un " "objet (afin de valider que l'appel était correct). Une autre façon de faire " "est de passer un objet Mock en argument d'une méthode (ou de tout autre " "partie du code à tester) et ensuite de contrôler que notre objet a été " "utilisé de la façon attendue." #: library/unittest.mock-examples.rst:83 msgid "" "The simple ``ProductionClass`` below has a ``closer`` method. If it is " "called with an object then it calls ``close`` on it." msgstr "" "Ci-dessous, ``ProductionClass`` dispose d'une méthode ``closer``. Si on " "l'appelle avec un objet, alors elle appelle la méthode ``close`` dessus." #: library/unittest.mock-examples.rst:91 msgid "" "So to test it we need to pass in an object with a ``close`` method and check " "that it was called correctly." msgstr "" "Ainsi, pour tester cette classe, nous devons lui passer un objet ayant une " "méthode ``close``, puis vérifier qu'elle a bien été appelée." #: library/unittest.mock-examples.rst:99 msgid "" "We don't have to do any work to provide the 'close' method on our mock. " "Accessing close creates it. So, if 'close' hasn't already been called then " "accessing it in the test will create it, but :meth:`~Mock." "assert_called_with` will raise a failure exception." msgstr "" "En fait, nous n'avons pas à nous soucier de fournir la méthode ``close`` " "dans notre objet « simulé ». Le simple fait d'accéder à la méthode ``close`` " "l'a crée. Si par contre la méthode ``close`` n'a pas été appelée alors, bien " "que le test la créée en y accédant, :meth:`~Mock.assert_called_with` lèvera " "une exception." #: library/unittest.mock-examples.rst:106 msgid "Mocking Classes" msgstr "Simulation des classes" #: library/unittest.mock-examples.rst:108 msgid "" "A common use case is to mock out classes instantiated by your code under " "test. When you patch a class, then that class is replaced with a mock. " "Instances are created by *calling the class*. This means you access the " "\"mock instance\" by looking at the return value of the mocked class." msgstr "" "Un cas d'utilisation courant consiste à émuler les classes instanciées par " "le code que nous testons. Quand on *patch* une classe, alors cette classe " "est remplacée par un objet *mock*. Les instances de la classe étant créées " "en *appelant la classe*, on accède à « l'instance *mock* » via la valeur de " "retour de la classe émulée." #: library/unittest.mock-examples.rst:113 msgid "" "In the example below we have a function ``some_function`` that instantiates " "``Foo`` and calls a method on it. The call to :func:`patch` replaces the " "class ``Foo`` with a mock. The ``Foo`` instance is the result of calling the " "mock, so it is configured by modifying the mock :attr:`~Mock." "return_value`. ::" msgstr "" #: library/unittest.mock-examples.rst:130 msgid "Naming your mocks" msgstr "" #: library/unittest.mock-examples.rst:132 msgid "" "It can be useful to give your mocks a name. The name is shown in the repr of " "the mock and can be helpful when the mock appears in test failure messages. " "The name is also propagated to attributes or methods of the mock:" msgstr "" #: library/unittest.mock-examples.rst:144 msgid "Tracking all Calls" msgstr "" #: library/unittest.mock-examples.rst:146 msgid "" "Often you want to track more than a single call to a method. The :attr:" "`~Mock.mock_calls` attribute records all calls to child attributes of the " "mock - and also to their children." msgstr "" #: library/unittest.mock-examples.rst:158 msgid "" "If you make an assertion about ``mock_calls`` and any unexpected methods " "have been called, then the assertion will fail. This is useful because as " "well as asserting that the calls you expected have been made, you are also " "checking that they were made in the right order and with no additional calls:" msgstr "" #: library/unittest.mock-examples.rst:163 msgid "" "You use the :data:`call` object to construct lists for comparing with " "``mock_calls``:" msgstr "" #: library/unittest.mock-examples.rst:170 msgid "" "However, parameters to calls that return mocks are not recorded, which means " "it is not possible to track nested calls where the parameters used to create " "ancestors are important:" msgstr "" #: library/unittest.mock-examples.rst:181 msgid "Setting Return Values and Attributes" msgstr "" #: library/unittest.mock-examples.rst:183 msgid "Setting the return values on a mock object is trivially easy:" msgstr "" #: library/unittest.mock-examples.rst:190 msgid "Of course you can do the same for methods on the mock:" msgstr "" #: library/unittest.mock-examples.rst:197 msgid "The return value can also be set in the constructor:" msgstr "" #: library/unittest.mock-examples.rst:203 msgid "If you need an attribute setting on your mock, just do it:" msgstr "" #: library/unittest.mock-examples.rst:210 msgid "" "Sometimes you want to mock up a more complex situation, like for example " "``mock.connection.cursor().execute(\"SELECT 1\")``. If we wanted this call " "to return a list, then we have to configure the result of the nested call." msgstr "" #: library/unittest.mock-examples.rst:214 msgid "" "We can use :data:`call` to construct the set of calls in a \"chained call\" " "like this for easy assertion afterwards:" msgstr "" #: library/unittest.mock-examples.rst:228 msgid "" "It is the call to ``.call_list()`` that turns our call object into a list of " "calls representing the chained calls." msgstr "" #: library/unittest.mock-examples.rst:233 msgid "Raising exceptions with mocks" msgstr "" #: library/unittest.mock-examples.rst:235 msgid "" "A useful attribute is :attr:`~Mock.side_effect`. If you set this to an " "exception class or instance then the exception will be raised when the mock " "is called." msgstr "" #: library/unittest.mock-examples.rst:247 msgid "Side effect functions and iterables" msgstr "" #: library/unittest.mock-examples.rst:249 msgid "" "``side_effect`` can also be set to a function or an iterable. The use case " "for ``side_effect`` as an iterable is where your mock is going to be called " "several times, and you want each call to return a different value. When you " "set ``side_effect`` to an iterable every call to the mock returns the next " "value from the iterable:" msgstr "" #: library/unittest.mock-examples.rst:264 msgid "" "For more advanced use cases, like dynamically varying the return values " "depending on what the mock is called with, ``side_effect`` can be a " "function. The function will be called with the same arguments as the mock. " "Whatever the function returns is what the call returns:" msgstr "" #: library/unittest.mock-examples.rst:281 msgid "Mocking asynchronous iterators" msgstr "" #: library/unittest.mock-examples.rst:283 msgid "" "Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock :ref:" "`async-iterators` through ``__aiter__``. The :attr:`~Mock.return_value` " "attribute of ``__aiter__`` can be used to set the return values to be used " "for iteration." msgstr "" #: library/unittest.mock-examples.rst:298 msgid "Mocking asynchronous context manager" msgstr "" #: library/unittest.mock-examples.rst:300 msgid "" "Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock :ref:" "`async-context-managers` through ``__aenter__`` and ``__aexit__``. By " "default, ``__aenter__`` and ``__aexit__`` are ``AsyncMock`` instances that " "return an async function." msgstr "" #: library/unittest.mock-examples.rst:322 msgid "Creating a Mock from an Existing Object" msgstr "" #: library/unittest.mock-examples.rst:324 msgid "" "One problem with over use of mocking is that it couples your tests to the " "implementation of your mocks rather than your real code. Suppose you have a " "class that implements ``some_method``. In a test for another class, you " "provide a mock of this object that *also* provides ``some_method``. If later " "you refactor the first class, so that it no longer has ``some_method`` - " "then your tests will continue to pass even though your code is now broken!" msgstr "" #: library/unittest.mock-examples.rst:331 msgid "" ":class:`Mock` allows you to provide an object as a specification for the " "mock, using the *spec* keyword argument. Accessing methods / attributes on " "the mock that don't exist on your specification object will immediately " "raise an attribute error. If you change the implementation of your " "specification, then tests that use that class will start failing immediately " "without you having to instantiate the class in those tests." msgstr "" #: library/unittest.mock-examples.rst:344 msgid "" "Using a specification also enables a smarter matching of calls made to the " "mock, regardless of whether some parameters were passed as positional or " "named arguments::" msgstr "" #: library/unittest.mock-examples.rst:355 msgid "" "If you want this smarter matching to also work with method calls on the " "mock, you can use :ref:`auto-speccing `." msgstr "" #: library/unittest.mock-examples.rst:358 msgid "" "If you want a stronger form of specification that prevents the setting of " "arbitrary attributes as well as the getting of them then you can use " "*spec_set* instead of *spec*." msgstr "" #: library/unittest.mock-examples.rst:365 msgid "Patch Decorators" msgstr "" #: library/unittest.mock-examples.rst:369 msgid "" "With :func:`patch` it matters that you patch objects in the namespace where " "they are looked up. This is normally straightforward, but for a quick guide " "read :ref:`where to patch `." msgstr "" "Avec :func:`patch`, il est important de *patcher* les objets dans l'espace " "de nommage où ils sont recherchés. C'est ce qui se fait normalement, mais " "pour un guide rapide, lisez :ref:`où patcher `." #: library/unittest.mock-examples.rst:374 msgid "" "A common need in tests is to patch a class attribute or a module attribute, " "for example patching a builtin or patching a class in a module to test that " "it is instantiated. Modules and classes are effectively global, so patching " "on them has to be undone after the test or the patch will persist into other " "tests and cause hard to diagnose problems." msgstr "" #: library/unittest.mock-examples.rst:380 msgid "" "mock provides three convenient decorators for this: :func:`patch`, :func:" "`patch.object` and :func:`patch.dict`. ``patch`` takes a single string, of " "the form ``package.module.Class.attribute`` to specify the attribute you are " "patching. It also optionally takes a value that you want the attribute (or " "class or whatever) to be replaced with. 'patch.object' takes an object and " "the name of the attribute you would like patched, plus optionally the value " "to patch it with." msgstr "" #: library/unittest.mock-examples.rst:388 msgid "``patch.object``::" msgstr "``patch.object`` ::" #: library/unittest.mock-examples.rst:405 msgid "" "If you are patching a module (including :mod:`builtins`) then use :func:" "`patch` instead of :func:`patch.object`:" msgstr "" #: library/unittest.mock-examples.rst:415 msgid "" "The module name can be 'dotted', in the form ``package.module`` if needed::" msgstr "" #: library/unittest.mock-examples.rst:424 msgid "A nice pattern is to actually decorate test methods themselves:" msgstr "" #: library/unittest.mock-examples.rst:435 msgid "" "If you want to patch with a Mock, you can use :func:`patch` with only one " "argument (or :func:`patch.object` with two arguments). The mock will be " "created for you and passed into the test function / method:" msgstr "" #: library/unittest.mock-examples.rst:447 msgid "You can stack up multiple patch decorators using this pattern::" msgstr "" #: library/unittest.mock-examples.rst:458 #, fuzzy msgid "" "When you nest patch decorators the mocks are passed in to the decorated " "function in the same order they applied (the normal *Python* order that " "decorators are applied). This means from the bottom up, so in the example " "above the mock for ``test_module.ClassName2`` is passed in first." msgstr "" "Lorsque l'on imbrique des décorateurs de patchs, les *mocks* sont transmis à " "la fonction décorée dans le même ordre qu'ils ont été déclarés (l'ordre " "normal *Python* des décorateurs est appliqué). Cela signifie du bas vers le " "haut, donc dans l'exemple ci-dessus, l'objet simulacre pour ``module." "ClassName1`` est passé en premier." #: library/unittest.mock-examples.rst:463 msgid "" "There is also :func:`patch.dict` for setting values in a dictionary just " "during a scope and restoring the dictionary to its original state when the " "test ends:" msgstr "" "Il existe également :func:`patch.dict` pour définir des valeurs d'un " "dictionnaire au sein d'une portée et restaurer ce dictionnaire à son état " "d'origine lorsque le test se termine :" #: library/unittest.mock-examples.rst:474 msgid "" "``patch``, ``patch.object`` and ``patch.dict`` can all be used as context " "managers." msgstr "" #: library/unittest.mock-examples.rst:476 msgid "" "Where you use :func:`patch` to create a mock for you, you can get a " "reference to the mock using the \"as\" form of the with statement:" msgstr "" #: library/unittest.mock-examples.rst:491 msgid "" "As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used " "as class decorators. When used in this way it is the same as applying the " "decorator individually to every method whose name starts with \"test\"." msgstr "" #: library/unittest.mock-examples.rst:499 msgid "Further Examples" msgstr "" #: library/unittest.mock-examples.rst:502 msgid "Here are some more examples for some slightly more advanced scenarios." msgstr "" #: library/unittest.mock-examples.rst:506 msgid "Mocking chained calls" msgstr "" #: library/unittest.mock-examples.rst:508 msgid "" "Mocking chained calls is actually straightforward with mock once you " "understand the :attr:`~Mock.return_value` attribute. When a mock is called " "for the first time, or you fetch its ``return_value`` before it has been " "called, a new :class:`Mock` is created." msgstr "" #: library/unittest.mock-examples.rst:513 msgid "" "This means that you can see how the object returned from a call to a mocked " "object has been used by interrogating the ``return_value`` mock:" msgstr "" #: library/unittest.mock-examples.rst:521 msgid "" "From here it is a simple step to configure and then make assertions about " "chained calls. Of course another alternative is writing your code in a more " "testable way in the first place..." msgstr "" #: library/unittest.mock-examples.rst:525 msgid "So, suppose we have some code that looks a little bit like this:" msgstr "" #: library/unittest.mock-examples.rst:534 msgid "" "Assuming that ``BackendProvider`` is already well tested, how do we test " "``method()``? Specifically, we want to test that the code section ``# more " "code`` uses the response object in the correct way." msgstr "" #: library/unittest.mock-examples.rst:538 msgid "" "As this chain of calls is made from an instance attribute we can monkey " "patch the ``backend`` attribute on a ``Something`` instance. In this " "particular case we are only interested in the return value from the final " "call to ``start_call`` so we don't have much configuration to do. Let's " "assume the object it returns is 'file-like', so we'll ensure that our " "response object uses the builtin :func:`open` as its ``spec``." msgstr "" #: library/unittest.mock-examples.rst:545 msgid "" "To do this we create a mock instance as our mock backend and create a mock " "response object for it. To set the response as the return value for that " "final ``start_call`` we could do this::" msgstr "" #: library/unittest.mock-examples.rst:551 msgid "" "We can do that in a slightly nicer way using the :meth:`~Mock." "configure_mock` method to directly set the return value for us::" msgstr "" #: library/unittest.mock-examples.rst:560 msgid "" "With these we monkey patch the \"mock backend\" in place and can make the " "real call::" msgstr "" #: library/unittest.mock-examples.rst:566 msgid "" "Using :attr:`~Mock.mock_calls` we can check the chained call with a single " "assert. A chained call is several calls in one line of code, so there will " "be several entries in ``mock_calls``. We can use :meth:`call.call_list` to " "create this list of calls for us::" msgstr "" #: library/unittest.mock-examples.rst:577 msgid "Partial mocking" msgstr "" #: library/unittest.mock-examples.rst:579 msgid "" "In some tests I wanted to mock out a call to :meth:`datetime.date.today` to " "return a known date, but I didn't want to prevent the code under test from " "creating new date objects. Unfortunately :class:`datetime.date` is written " "in C, and so I couldn't just monkey-patch out the static :meth:`date.today` " "method." msgstr "" #: library/unittest.mock-examples.rst:584 msgid "" "I found a simple way of doing this that involved effectively wrapping the " "date class with a mock, but passing through calls to the constructor to the " "real class (and returning real instances)." msgstr "" #: library/unittest.mock-examples.rst:588 msgid "" "The :func:`patch decorator ` is used here to mock out the ``date`` " "class in the module under test. The :attr:`side_effect` attribute on the " "mock date class is then set to a lambda function that returns a real date. " "When the mock date class is called a real date will be constructed and " "returned by ``side_effect``. ::" msgstr "" #: library/unittest.mock-examples.rst:602 msgid "" "Note that we don't patch :class:`datetime.date` globally, we patch ``date`` " "in the module that *uses* it. See :ref:`where to patch `." msgstr "" #: library/unittest.mock-examples.rst:605 msgid "" "When ``date.today()`` is called a known date is returned, but calls to the " "``date(...)`` constructor still return normal dates. Without this you can " "find yourself having to calculate an expected result using exactly the same " "algorithm as the code under test, which is a classic testing anti-pattern." msgstr "" #: library/unittest.mock-examples.rst:610 msgid "" "Calls to the date constructor are recorded in the ``mock_date`` attributes " "(``call_count`` and friends) which may also be useful for your tests." msgstr "" #: library/unittest.mock-examples.rst:613 msgid "" "An alternative way of dealing with mocking dates, or other builtin classes, " "is discussed in `this blog entry `_." msgstr "" #: library/unittest.mock-examples.rst:619 msgid "Mocking a Generator Method" msgstr "" #: library/unittest.mock-examples.rst:621 msgid "" "A Python generator is a function or method that uses the :keyword:`yield` " "statement to return a series of values when iterated over [#]_." msgstr "" #: library/unittest.mock-examples.rst:624 msgid "" "A generator method / function is called to return the generator object. It " "is the generator object that is then iterated over. The protocol method for " "iteration is :meth:`~container.__iter__`, so we can mock this using a :class:" "`MagicMock`." msgstr "" #: library/unittest.mock-examples.rst:629 msgid "" "Here's an example class with an \"iter\" method implemented as a generator:" msgstr "" #: library/unittest.mock-examples.rst:641 msgid "How would we mock this class, and in particular its \"iter\" method?" msgstr "" #: library/unittest.mock-examples.rst:643 msgid "" "To configure the values returned from the iteration (implicit in the call " "to :class:`list`), we need to configure the object returned by the call to " "``foo.iter()``." msgstr "" #: library/unittest.mock-examples.rst:651 msgid "" "There are also generator expressions and more `advanced uses `_ of generators, but we aren't concerned " "about them here. A very good introduction to generators and how powerful " "they are is: `Generator Tricks for Systems Programmers `_." msgstr "" #: library/unittest.mock-examples.rst:659 msgid "Applying the same patch to every test method" msgstr "" #: library/unittest.mock-examples.rst:661 msgid "" "If you want several patches in place for multiple test methods the obvious " "way is to apply the patch decorators to every method. This can feel like " "unnecessary repetition. Instead, you can use :func:`patch` (in all its " "various forms) as a class decorator. This applies the patches to all test " "methods on the class. A test method is identified by methods whose names " "start with ``test``::" msgstr "" #: library/unittest.mock-examples.rst:685 msgid "" "An alternative way of managing patches is to use the :ref:`start-and-stop`. " "These allow you to move the patching into your ``setUp`` and ``tearDown`` " "methods. ::" msgstr "" #: library/unittest.mock-examples.rst:702 msgid "" "If you use this technique you must ensure that the patching is \"undone\" by " "calling ``stop``. This can be fiddlier than you might think, because if an " "exception is raised in the setUp then tearDown is not called. :meth:" "`unittest.TestCase.addCleanup` makes this easier::" msgstr "" #: library/unittest.mock-examples.rst:720 msgid "Mocking Unbound Methods" msgstr "" #: library/unittest.mock-examples.rst:722 msgid "" "Whilst writing tests today I needed to patch an *unbound method* (patching " "the method on the class rather than on the instance). I needed self to be " "passed in as the first argument because I want to make asserts about which " "objects were calling this particular method. The issue is that you can't " "patch with a mock for this, because if you replace an unbound method with a " "mock it doesn't become a bound method when fetched from the instance, and so " "it doesn't get self passed in. The workaround is to patch the unbound method " "with a real function instead. The :func:`patch` decorator makes it so simple " "to patch out methods with a mock that having to create a real function " "becomes a nuisance." msgstr "" #: library/unittest.mock-examples.rst:733 msgid "" "If you pass ``autospec=True`` to patch then it does the patching with a " "*real* function object. This function object has the same signature as the " "one it is replacing, but delegates to a mock under the hood. You still get " "your mock auto-created in exactly the same way as before. What it means " "though, is that if you use it to patch out an unbound method on a class the " "mocked function will be turned into a bound method if it is fetched from an " "instance. It will have ``self`` passed in as the first argument, which is " "exactly what I wanted:" msgstr "" #: library/unittest.mock-examples.rst:754 msgid "" "If we don't use ``autospec=True`` then the unbound method is patched out " "with a Mock instance instead, and isn't called with ``self``." msgstr "" #: library/unittest.mock-examples.rst:759 msgid "Checking multiple calls with mock" msgstr "" #: library/unittest.mock-examples.rst:761 msgid "" "mock has a nice API for making assertions about how your mock objects are " "used." msgstr "" #: library/unittest.mock-examples.rst:768 msgid "" "If your mock is only being called once you can use the :meth:" "`assert_called_once_with` method that also asserts that the :attr:" "`call_count` is one." msgstr "" #: library/unittest.mock-examples.rst:779 msgid "" "Both ``assert_called_with`` and ``assert_called_once_with`` make assertions " "about the *most recent* call. If your mock is going to be called several " "times, and you want to make assertions about *all* those calls you can use :" "attr:`~Mock.call_args_list`:" msgstr "" #: library/unittest.mock-examples.rst:791 msgid "" "The :data:`call` helper makes it easy to make assertions about these calls. " "You can build up a list of expected calls and compare it to " "``call_args_list``. This looks remarkably similar to the repr of the " "``call_args_list``:" msgstr "" #: library/unittest.mock-examples.rst:801 msgid "Coping with mutable arguments" msgstr "" #: library/unittest.mock-examples.rst:803 msgid "" "Another situation is rare, but can bite you, is when your mock is called " "with mutable arguments. ``call_args`` and ``call_args_list`` store " "*references* to the arguments. If the arguments are mutated by the code " "under test then you can no longer make assertions about what the values were " "when the mock was called." msgstr "" #: library/unittest.mock-examples.rst:808 msgid "" "Here's some example code that shows the problem. Imagine the following " "functions defined in 'mymodule'::" msgstr "" #: library/unittest.mock-examples.rst:819 msgid "" "When we try to test that ``grob`` calls ``frob`` with the correct argument " "look what happens::" msgstr "" #: library/unittest.mock-examples.rst:834 msgid "" "One possibility would be for mock to copy the arguments you pass in. This " "could then cause problems if you do assertions that rely on object identity " "for equality." msgstr "" #: library/unittest.mock-examples.rst:838 msgid "" "Here's one solution that uses the :attr:`side_effect` functionality. If you " "provide a ``side_effect`` function for a mock then ``side_effect`` will be " "called with the same args as the mock. This gives us an opportunity to copy " "the arguments and store them for later assertions. In this example I'm using " "*another* mock to store the arguments so that I can use the mock methods for " "doing the assertion. Again a helper function sets this up for me. ::" msgstr "" #: library/unittest.mock-examples.rst:867 msgid "" "``copy_call_args`` is called with the mock that will be called. It returns a " "new mock that we do the assertion on. The ``side_effect`` function makes a " "copy of the args and calls our ``new_mock`` with the copy." msgstr "" #: library/unittest.mock-examples.rst:873 msgid "" "If your mock is only going to be used once there is an easier way of " "checking arguments at the point they are called. You can simply do the " "checking inside a ``side_effect`` function." msgstr "" #: library/unittest.mock-examples.rst:887 msgid "" "An alternative approach is to create a subclass of :class:`Mock` or :class:" "`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments. Here's " "an example implementation:" msgstr "" #: library/unittest.mock-examples.rst:911 msgid "" "When you subclass ``Mock`` or ``MagicMock`` all dynamically created " "attributes, and the ``return_value`` will use your subclass automatically. " "That means all children of a ``CopyingMock`` will also have the type " "``CopyingMock``." msgstr "" #: library/unittest.mock-examples.rst:917 msgid "Nesting Patches" msgstr "" #: library/unittest.mock-examples.rst:919 msgid "" "Using patch as a context manager is nice, but if you do multiple patches you " "can end up with nested with statements indenting further and further to the " "right::" msgstr "" #: library/unittest.mock-examples.rst:937 msgid "" "With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can " "achieve the same effect without the nested indentation. A simple helper " "method, ``create_patch``, puts the patch in place and returns the created " "mock for us::" msgstr "" #: library/unittest.mock-examples.rst:965 msgid "Mocking a dictionary with MagicMock" msgstr "" #: library/unittest.mock-examples.rst:967 msgid "" "You may want to mock a dictionary, or other container object, recording all " "access to it whilst having it still behave like a dictionary." msgstr "" #: library/unittest.mock-examples.rst:970 msgid "" "We can do this with :class:`MagicMock`, which will behave like a dictionary, " "and using :data:`~Mock.side_effect` to delegate dictionary access to a real " "underlying dictionary that is under our control." msgstr "" #: library/unittest.mock-examples.rst:974 msgid "" "When the :meth:`__getitem__` and :meth:`__setitem__` methods of our " "``MagicMock`` are called (normal dictionary access) then ``side_effect`` is " "called with the key (and in the case of ``__setitem__`` the value too). We " "can also control what is returned." msgstr "" #: library/unittest.mock-examples.rst:978 msgid "" "After the ``MagicMock`` has been used we can use attributes like :data:" "`~Mock.call_args_list` to assert about how the dictionary was used:" msgstr "" #: library/unittest.mock-examples.rst:994 msgid "" "An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide " "the magic methods you specifically want:" msgstr "" #: library/unittest.mock-examples.rst:1001 msgid "" "A *third* option is to use ``MagicMock`` but passing in ``dict`` as the " "*spec* (or *spec_set*) argument so that the ``MagicMock`` created only has " "dictionary magic methods available:" msgstr "" #: library/unittest.mock-examples.rst:1009 msgid "" "With these side effect functions in place, the ``mock`` will behave like a " "normal dictionary but recording the access. It even raises a :exc:`KeyError` " "if you try to access a key that doesn't exist." msgstr "" #: library/unittest.mock-examples.rst:1028 msgid "" "After it has been used you can make assertions about the access using the " "normal mock methods and attributes:" msgstr "" #: library/unittest.mock-examples.rst:1040 msgid "Mock subclasses and their attributes" msgstr "" #: library/unittest.mock-examples.rst:1042 msgid "" "There are various reasons why you might want to subclass :class:`Mock`. One " "reason might be to add helper methods. Here's a silly example:" msgstr "" #: library/unittest.mock-examples.rst:1058 msgid "" "The standard behaviour for ``Mock`` instances is that attributes and the " "return value mocks are of the same type as the mock they are accessed on. " "This ensures that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` " "attributes are ``MagicMocks`` [#]_. So if you're subclassing to add helper " "methods then they'll also be available on the attributes and return value " "mock of instances of your subclass." msgstr "" #: library/unittest.mock-examples.rst:1074 msgid "" "Sometimes this is inconvenient. For example, `one user `_ is subclassing mock to created a `Twisted " "adaptor `_. Having this applied to attributes too actually causes " "errors." msgstr "" #: library/unittest.mock-examples.rst:1080 msgid "" "``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to " "create these \"sub-mocks\" for attributes and return values. You can prevent " "your subclass being used for attributes by overriding this method. The " "signature is that it takes arbitrary keyword arguments (``**kwargs``) which " "are then passed onto the mock constructor:" msgstr "" #: library/unittest.mock-examples.rst:1097 msgid "" "An exception to this rule are the non-callable mocks. Attributes use the " "callable variant because otherwise non-callable mocks couldn't have callable " "methods." msgstr "" #: library/unittest.mock-examples.rst:1103 msgid "Mocking imports with patch.dict" msgstr "" #: library/unittest.mock-examples.rst:1105 msgid "" "One situation where mocking can be hard is where you have a local import " "inside a function. These are harder to mock because they aren't using an " "object from the module namespace that we can patch out." msgstr "" #: library/unittest.mock-examples.rst:1109 msgid "" "Generally local imports are to be avoided. They are sometimes done to " "prevent circular dependencies, for which there is *usually* a much better " "way to solve the problem (refactor the code) or to prevent \"up front " "costs\" by delaying the import. This can also be solved in better ways than " "an unconditional local import (store the module as a class or module " "attribute and only do the import on first use)." msgstr "" #: library/unittest.mock-examples.rst:1116 msgid "" "That aside there is a way to use ``mock`` to affect the results of an " "import. Importing fetches an *object* from the :data:`sys.modules` " "dictionary. Note that it fetches an *object*, which need not be a module. " "Importing a module for the first time results in a module object being put " "in ``sys.modules``, so usually when you import something you get a module " "back. This need not be the case however." msgstr "" #: library/unittest.mock-examples.rst:1123 msgid "" "This means you can use :func:`patch.dict` to *temporarily* put a mock in " "place in :data:`sys.modules`. Any imports whilst this patch is active will " "fetch the mock. When the patch is complete (the decorated function exits, " "the with statement body is complete or ``patcher.stop()`` is called) then " "whatever was there previously will be restored safely." msgstr "" #: library/unittest.mock-examples.rst:1129 msgid "Here's an example that mocks out the 'fooble' module." msgstr "" #: library/unittest.mock-examples.rst:1141 msgid "" "As you can see the ``import fooble`` succeeds, but on exit there is no " "'fooble' left in :data:`sys.modules`." msgstr "" #: library/unittest.mock-examples.rst:1144 msgid "This also works for the ``from module import name`` form:" msgstr "" #: library/unittest.mock-examples.rst:1154 msgid "With slightly more work you can also mock package imports:" msgstr "" #: library/unittest.mock-examples.rst:1167 msgid "Tracking order of calls and less verbose call assertions" msgstr "" #: library/unittest.mock-examples.rst:1169 msgid "" "The :class:`Mock` class allows you to track the *order* of method calls on " "your mock objects through the :attr:`~Mock.method_calls` attribute. This " "doesn't allow you to track the order of calls between separate mock objects, " "however we can use :attr:`~Mock.mock_calls` to achieve the same effect." msgstr "" #: library/unittest.mock-examples.rst:1174 msgid "" "Because mocks track calls to child mocks in ``mock_calls``, and accessing an " "arbitrary attribute of a mock creates a child mock, we can create our " "separate mocks from a parent one. Calls to those child mock will then all be " "recorded, in order, in the ``mock_calls`` of the parent:" msgstr "" #: library/unittest.mock-examples.rst:1191 msgid "" "We can then assert about the calls, including the order, by comparing with " "the ``mock_calls`` attribute on the manager mock:" msgstr "" #: library/unittest.mock-examples.rst:1198 msgid "" "If ``patch`` is creating, and putting in place, your mocks then you can " "attach them to a manager mock using the :meth:`~Mock.attach_mock` method. " "After attaching calls will be recorded in ``mock_calls`` of the manager. ::" msgstr "" #: library/unittest.mock-examples.rst:1217 msgid "" "If many calls have been made, but you're only interested in a particular " "sequence of them then an alternative is to use the :meth:`~Mock." "assert_has_calls` method. This takes a list of calls (constructed with the :" "data:`call` object). If that sequence of calls are in :attr:`~Mock." "mock_calls` then the assert succeeds." msgstr "" #: library/unittest.mock-examples.rst:1231 msgid "" "Even though the chained call ``m.one().two().three()`` aren't the only calls " "that have been made to the mock, the assert still succeeds." msgstr "" #: library/unittest.mock-examples.rst:1234 msgid "" "Sometimes a mock may have several calls made to it, and you are only " "interested in asserting about *some* of those calls. You may not even care " "about the order. In this case you can pass ``any_order=True`` to " "``assert_has_calls``:" msgstr "" #: library/unittest.mock-examples.rst:1246 msgid "More complex argument matching" msgstr "" #: library/unittest.mock-examples.rst:1248 msgid "" "Using the same basic concept as :data:`ANY` we can implement matchers to do " "more complex assertions on objects used as arguments to mocks." msgstr "" #: library/unittest.mock-examples.rst:1251 msgid "" "Suppose we expect some object to be passed to a mock that by default " "compares equal based on object identity (which is the Python default for " "user defined classes). To use :meth:`~Mock.assert_called_with` we would need " "to pass in the exact same object. If we are only interested in some of the " "attributes of this object then we can create a matcher that will check these " "attributes for us." msgstr "" #: library/unittest.mock-examples.rst:1258 msgid "" "You can see in this example how a 'standard' call to ``assert_called_with`` " "isn't sufficient:" msgstr "" #: library/unittest.mock-examples.rst:1273 msgid "" "A comparison function for our ``Foo`` class might look something like this:" msgstr "" #: library/unittest.mock-examples.rst:1285 msgid "" "And a matcher object that can use comparison functions like this for its " "equality operation would look something like this:" msgstr "" #: library/unittest.mock-examples.rst:1296 msgid "Putting all this together:" msgstr "" #: library/unittest.mock-examples.rst:1301 msgid "" "The ``Matcher`` is instantiated with our compare function and the ``Foo`` " "object we want to compare against. In ``assert_called_with`` the ``Matcher`` " "equality method will be called, which compares the object the mock was " "called with against the one we created our matcher with. If they match then " "``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is " "raised:" msgstr "" #: library/unittest.mock-examples.rst:1314 msgid "" "With a bit of tweaking you could have the comparison function raise the :exc:" "`AssertionError` directly and provide a more useful failure message." msgstr "" #: library/unittest.mock-examples.rst:1317 msgid "" "As of version 1.5, the Python testing library `PyHamcrest `_ provides similar functionality, that may be " "useful here, in the form of its equality matcher (`hamcrest.library." "integration.match_equality `_)." msgstr ""