python-docs-fr/library/unittest.mock-examples.po
2019-12-06 14:19:13 +01:00

1065 lines
41 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2001-2016, Python Software Foundation
# This file is distributed under the same license as the Python package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Python 3.6\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-04-02 22:11+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ../Doc/library/unittest.mock-examples.rst:2
msgid ":mod:`unittest.mock` --- getting started"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:13
msgid "Using Mock"
msgstr "Utilisation de Mock ou l'art de singer"
#: ../Doc/library/unittest.mock-examples.rst:16
msgid "Mock Patching Methods"
msgstr "Simulation des méthodes"
#: ../Doc/library/unittest.mock-examples.rst:18
msgid "Common uses for :class:`Mock` objects include:"
msgstr "Usages courant de :class:`Mock` :"
#: ../Doc/library/unittest.mock-examples.rst:20
msgid "Patching methods"
msgstr "Substitution des méthodes"
#: ../Doc/library/unittest.mock-examples.rst:21
msgid "Recording method calls on objects"
msgstr "Enregistrement des appels faits sur les objets"
#: ../Doc/library/unittest.mock-examples.rst:23
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 :"
#: ../Doc/library/unittest.mock-examples.rst:31
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é."
#: ../Doc/library/unittest.mock-examples.rst:36
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."
#: ../Doc/library/unittest.mock-examples.rst:40
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."
#: ../Doc/library/unittest.mock-examples.rst:45
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`` :"
#: ../Doc/library/unittest.mock-examples.rst:62
msgid "Mock for Method Calls on an Object"
msgstr "S'assurer de la bonne utilisation d'un objet"
#: ../Doc/library/unittest.mock-examples.rst:64
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."
#: ../Doc/library/unittest.mock-examples.rst:69
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."
#: ../Doc/library/unittest.mock-examples.rst:77
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."
#: ../Doc/library/unittest.mock-examples.rst:85
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."
#: ../Doc/library/unittest.mock-examples.rst:92
msgid "Mocking Classes"
msgstr "Simulation des classes"
#: ../Doc/library/unittest.mock-examples.rst:94
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."
#: ../Doc/library/unittest.mock-examples.rst:99
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 ""
#: ../Doc/library/unittest.mock-examples.rst:116
msgid "Naming your mocks"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:118
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 ""
#: ../Doc/library/unittest.mock-examples.rst:130
msgid "Tracking all Calls"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:132
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 ""
#: ../Doc/library/unittest.mock-examples.rst:144
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 ""
#: ../Doc/library/unittest.mock-examples.rst:149
msgid ""
"You use the :data:`call` object to construct lists for comparing with "
"``mock_calls``:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:158
msgid "Setting Return Values and Attributes"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:160
msgid "Setting the return values on a mock object is trivially easy:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:167
msgid "Of course you can do the same for methods on the mock:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:174
msgid "The return value can also be set in the constructor:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:180
msgid "If you need an attribute setting on your mock, just do it:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:187
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 ""
#: ../Doc/library/unittest.mock-examples.rst:191
msgid ""
"We can use :data:`call` to construct the set of calls in a \"chained call\" "
"like this for easy assertion afterwards:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:205
msgid ""
"It is the call to ``.call_list()`` that turns our call object into a list of "
"calls representing the chained calls."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:210
msgid "Raising exceptions with mocks"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:212
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 ""
#: ../Doc/library/unittest.mock-examples.rst:224
msgid "Side effect functions and iterables"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:226
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 ""
#: ../Doc/library/unittest.mock-examples.rst:241
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 ""
#: ../Doc/library/unittest.mock-examples.rst:258
msgid "Creating a Mock from an Existing Object"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:260
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 ""
#: ../Doc/library/unittest.mock-examples.rst:267
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 ""
#: ../Doc/library/unittest.mock-examples.rst:280
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 ""
#: ../Doc/library/unittest.mock-examples.rst:291
msgid ""
"If you want this smarter matching to also work with method calls on the "
"mock, you can use :ref:`auto-speccing <auto-speccing>`."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:294
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 ""
#: ../Doc/library/unittest.mock-examples.rst:301
msgid "Patch Decorators"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:305
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 <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 <where-to-patch>`."
#: ../Doc/library/unittest.mock-examples.rst:310
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 ""
#: ../Doc/library/unittest.mock-examples.rst:316
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 ""
#: ../Doc/library/unittest.mock-examples.rst:324
msgid "``patch.object``:"
msgstr "``patch.object``:"
#: ../Doc/library/unittest.mock-examples.rst:341
msgid ""
"If you are patching a module (including :mod:`builtins`) then use :func:"
"`patch` instead of :func:`patch.object`:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:351
msgid ""
"The module name can be 'dotted', in the form ``package.module`` if needed:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:360
msgid "A nice pattern is to actually decorate test methods themselves:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:371
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 ""
#: ../Doc/library/unittest.mock-examples.rst:383
msgid "You can stack up multiple patch decorators using this pattern:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:394
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 ""
#: ../Doc/library/unittest.mock-examples.rst:399
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 ::"
#: ../Doc/library/unittest.mock-examples.rst:410
msgid ""
"``patch``, ``patch.object`` and ``patch.dict`` can all be used as context "
"managers."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:412
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 ""
#: ../Doc/library/unittest.mock-examples.rst:427
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 ""
#: ../Doc/library/unittest.mock-examples.rst:435
msgid "Further Examples"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:438
msgid "Here are some more examples for some slightly more advanced scenarios."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:442
msgid "Mocking chained calls"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:444
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 ""
#: ../Doc/library/unittest.mock-examples.rst:449
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 ""
#: ../Doc/library/unittest.mock-examples.rst:457
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 ""
#: ../Doc/library/unittest.mock-examples.rst:461
msgid "So, suppose we have some code that looks a little bit like this:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:470
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 ""
#: ../Doc/library/unittest.mock-examples.rst:474
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 ""
#: ../Doc/library/unittest.mock-examples.rst:481
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 ""
#: ../Doc/library/unittest.mock-examples.rst:487
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 ""
#: ../Doc/library/unittest.mock-examples.rst:496
msgid ""
"With these we monkey patch the \"mock backend\" in place and can make the "
"real call:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:502
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 ""
#: ../Doc/library/unittest.mock-examples.rst:513
msgid "Partial mocking"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:515
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 ""
#: ../Doc/library/unittest.mock-examples.rst:520
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 ""
#: ../Doc/library/unittest.mock-examples.rst:524
msgid ""
"The :func:`patch decorator <patch>` 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 ""
#: ../Doc/library/unittest.mock-examples.rst:539
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 <where-to-patch>`."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:542
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 ""
#: ../Doc/library/unittest.mock-examples.rst:547
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 ""
#: ../Doc/library/unittest.mock-examples.rst:550
msgid ""
"An alternative way of dealing with mocking dates, or other builtin classes, "
"is discussed in `this blog entry <https://williambert.online/2011/07/how-to-"
"unit-testing-in-django-with-mocking-and-patching/>`_."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:556
msgid "Mocking a Generator Method"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:558
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 ""
#: ../Doc/library/unittest.mock-examples.rst:561
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 ""
#: ../Doc/library/unittest.mock-examples.rst:566
msgid ""
"Here's an example class with an \"iter\" method implemented as a generator:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:578
msgid "How would we mock this class, and in particular its \"iter\" method?"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:580
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 ""
#: ../Doc/library/unittest.mock-examples.rst:588
msgid ""
"There are also generator expressions and more `advanced uses <http://www."
"dabeaz.com/coroutines/index.html>`_ 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 <http://www.dabeaz."
"com/generators/>`_."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:596
msgid "Applying the same patch to every test method"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:598
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. For Python 2.6 or more recent 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 ""
#: ../Doc/library/unittest.mock-examples.rst:622
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 ""
#: ../Doc/library/unittest.mock-examples.rst:638
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 ""
#: ../Doc/library/unittest.mock-examples.rst:656
msgid "Mocking Unbound Methods"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:658
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 ""
#: ../Doc/library/unittest.mock-examples.rst:669
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 ""
#: ../Doc/library/unittest.mock-examples.rst:690
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 ""
#: ../Doc/library/unittest.mock-examples.rst:695
msgid "Checking multiple calls with mock"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:697
msgid ""
"mock has a nice API for making assertions about how your mock objects are "
"used."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:704
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 ""
#: ../Doc/library/unittest.mock-examples.rst:715
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 ""
#: ../Doc/library/unittest.mock-examples.rst:727
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 ""
#: ../Doc/library/unittest.mock-examples.rst:737
msgid "Coping with mutable arguments"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:739
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 ""
#: ../Doc/library/unittest.mock-examples.rst:744
msgid ""
"Here's some example code that shows the problem. Imagine the following "
"functions defined in 'mymodule'::"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:755
msgid ""
"When we try to test that ``grob`` calls ``frob`` with the correct argument "
"look what happens:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:770
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 ""
#: ../Doc/library/unittest.mock-examples.rst:774
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 ""
#: ../Doc/library/unittest.mock-examples.rst:803
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 ""
#: ../Doc/library/unittest.mock-examples.rst:809
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 ""
#: ../Doc/library/unittest.mock-examples.rst:823
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 ""
#: ../Doc/library/unittest.mock-examples.rst:847
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 ""
#: ../Doc/library/unittest.mock-examples.rst:853
msgid "Nesting Patches"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:855
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 ""
#: ../Doc/library/unittest.mock-examples.rst:873
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 ""
#: ../Doc/library/unittest.mock-examples.rst:901
msgid "Mocking a dictionary with MagicMock"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:903
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 ""
#: ../Doc/library/unittest.mock-examples.rst:906
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 ""
#: ../Doc/library/unittest.mock-examples.rst:910
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 ""
#: ../Doc/library/unittest.mock-examples.rst:914
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 ""
#: ../Doc/library/unittest.mock-examples.rst:930
msgid ""
"An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide "
"the magic methods you specifically want:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:937
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 ""
#: ../Doc/library/unittest.mock-examples.rst:945
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 ""
#: ../Doc/library/unittest.mock-examples.rst:964
msgid ""
"After it has been used you can make assertions about the access using the "
"normal mock methods and attributes:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:976
msgid "Mock subclasses and their attributes"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:978
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 ""
#: ../Doc/library/unittest.mock-examples.rst:994
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1010
msgid ""
"Sometimes this is inconvenient. For example, `one user <https://code.google."
"com/p/mock/issues/detail?id=105>`_ is subclassing mock to created a `Twisted "
"adaptor <https://twistedmatrix.com/documents/11.0.0/api/twisted.python."
"components.html>`_. Having this applied to attributes too actually causes "
"errors."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1016
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1033
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1039
msgid "Mocking imports with patch.dict"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1041
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1045
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1052
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1059
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1065
msgid "Here's an example that mocks out the 'fooble' module."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1076
msgid ""
"As you can see the ``import fooble`` succeeds, but on exit there is no "
"'fooble' left in :data:`sys.modules`."
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1079
msgid "This also works for the ``from module import name`` form:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1089
msgid "With slightly more work you can also mock package imports:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1102
msgid "Tracking order of calls and less verbose call assertions"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1104
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1109
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1126
msgid ""
"We can then assert about the calls, including the order, by comparing with "
"the ``mock_calls`` attribute on the manager mock:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1133
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1153
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1167
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1170
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1182
msgid "More complex argument matching"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1184
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1187
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1194
msgid ""
"You can see in this example how a 'standard' call to ``assert_called_with`` "
"isn't sufficient:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1209
msgid ""
"A comparison function for our ``Foo`` class might look something like this:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1221
msgid ""
"And a matcher object that can use comparison functions like this for its "
"equality operation would look something like this:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1232
msgid "Putting all this together:"
msgstr ""
#: ../Doc/library/unittest.mock-examples.rst:1237
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1250
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 ""
#: ../Doc/library/unittest.mock-examples.rst:1253
msgid ""
"As of version 1.5, the Python testing library `PyHamcrest <https://"
"pyhamcrest.readthedocs.org/>`_ provides similar functionality, that may be "
"useful here, in the form of its equality matcher (`hamcrest.library."
"integration.match_equality <https://pyhamcrest.readthedocs.org/en/"
"release-1.8/integration/#module-hamcrest.library.integration."
"match_equality>`_)."
msgstr ""