<commit_before>===========================
 Getting Started with Mock
===========================

.. _getting-started:

.. index:: Getting Started

.. testsetup::

    import os, sys
    if not os.getcwd() in sys.path:
        sys.path.append(os.getcwd())

    import unittest
    from mock import Mock, sentinel, patch

    class SomeClass(object):
        static_method = None
        class_method = None
        attribute = None

    sys.modules['package'] = package = Mock(name='package')
    sys.modules['package.module'] = module = package.module


For comprehensive examples, see the unit tests included in the full source
distribution.


Using Mock
==========

Mock Patching Methods
---------------------

``Mock`` objects can be used for:

* Patching methods
* Recording method calls on objects

.. doctest::

    >>> from mock import Mock
    >>> real = SomeClass()
    >>> real.method = Mock()
    >>> real.method(3, 4, 5, key='value')
    <mock.Mock object at 0x...>

Once the mock has been used it has methods and attributes that allow you to
make assertions about how it has been used.

`Mock` objects are callable. If they are called then the ``called`` attribute is
set to `True`.

This example tests that calling ``method`` results in a call to ``something``:

.. doctest::

    >>> from mock import Mock
    >>> class ProductionClass(object):
    ...     def method(self):
    ...         self.something()
    ...     def something(self):
    ...         pass
    ...
    >>> real = ProductionClass()
    >>> real.something = Mock()
    >>> real.method()
    >>> real.something.called
    True

If you want access to the actual arguments the mock was called with, for example
to make assertions about the arguments themselves, then this information is
available.

.. doctest::

    >>> real = ProductionClass()
    >>> real.something = Mock()
    >>> real.method()
    >>> real.something.call_count
    1
    >>> args, kwargs = (), {}
    >>> assert real.something.call_args == (args, kwargs)
    >>> assert real.something.call_args_list == [(args, kwargs)]

Checking ``call_args_list`` tests how many times the mock was called, and the
arguments for each call, in a single assertion.

From 0.7.0 you can omit empty args and keyword args, which makes comparisons
less verbose:

.. doctest::

    >>> real = ProductionClass()
    >>> real.something = Mock()
    >>> real.method()
    >>> assert real.something.call_args == ()
    >>> assert real.something.call_args_list == [()]

If the mock has only been called once then you can use
:meth:`Mock.assert_called_once_with`:

.. doctest::

    >>> real = ProductionClass()
    >>> real.something = Mock()
    >>> real.method()
    >>> real.something.assert_called_once_with()

If you don't care how many times an object has been called, but are just
interested in the most recent call, then you can use
:meth:`Mock.assert_called_with`:

.. doctest::

    >>> mock = Mock(return_value=None)
    >>> mock(1, 2, 3)
    >>> mock.assert_called_with(1, 2, 3)


Mock for Method Calls on an Object
----------------------------------

.. doctest::

    >>> class ProductionClass(object):
    ...     def closer(self, something):
    ...         something.close()
    ...
    >>> real = ProductionClass()
    >>> mock = Mock()
    >>> real.closer(mock)
    >>> mock.close.assert_called_with()


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.

As ``close`` is a mock object is has all the attributes from the previous
example.


Mocking Classes
---------------

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. e.g.

.. doctest::

    >>> def some_function():
    ...     instance = Foo()
    ...     return instance.method()
    ...
    >>> with patch('

@patch('package.MyClassName')
def test_something(self, my_mock):
    instance_mock = my_mock.return_value
    instance_mock.my_method.return_value = 'xyz'

mock autocreates a new mock to be the return value of any mock. So you control the behaviour of the instances of mocked classes by configuring my_mock.return_value.




Naming your mocks
-----------------

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:

.. doctest::
<commit_msg>New example in getting started doc<commit_after>===========================
 Getting Started with Mock
===========================

.. _getting-started:

.. index:: Getting Started

.. testsetup::

    import os, sys
    if not os.getcwd() in sys.path:
        sys.path.append(os.getcwd())

    import unittest
    from mock import Mock, sentinel, patch

    class SomeClass(object):
        static_method = None
        class_method = None
        attribute = None

    sys.modules['package'] = package = Mock(name='package')
    sys.modules['package.module'] = module = package.module
    sys.modules['module'] = package.module


For comprehensive examples, see the unit tests included in the full source
distribution.


Using Mock
==========

Mock Patching Methods
---------------------

``Mock`` objects can be used for:

* Patching methods
* Recording method calls on objects

.. doctest::

    >>> from mock import Mock
    >>> real = SomeClass()
    >>> real.method = Mock()
    >>> real.method(3, 4, 5, key='value')
    <mock.Mock object at 0x...>

Once the mock has been used it has methods and attributes that allow you to
make assertions about how it has been used.

`Mock` objects are callable. If they are called then the ``called`` attribute is
set to `True`.

This example tests that calling ``method`` results in a call to ``something``:

.. doctest::

    >>> from mock import Mock
    >>> class ProductionClass(object):
    ...     def method(self):
    ...         self.something()
    ...     def something(self):
    ...         pass
    ...
    >>> real = ProductionClass()
    >>> real.something = Mock()
    >>> real.method()
    >>> real.something.called
    True

If you want access to the actual arguments the mock was called with, for example
to make assertions about the arguments themselves, then this information is
available.

.. doctest::

    >>> real = ProductionClass()
    >>> real.something = Mock()
    >>> real.method()
    >>> real.something.call_count
    1
    >>> args, kwargs = (), {}
    >>> assert real.something.call_args == (args, kwargs)
    >>> assert real.something.call_args_list == [(args, kwargs)]

Checking ``call_args_list`` tests how many times the mock was called, and the
arguments for each call, in a single assertion.

From 0.7.0 you can omit empty args and keyword args, which makes comparisons
less verbose:

.. doctest::

    >>> real = ProductionClass()
    >>> real.something = Mock()
    >>> real.method()
    >>> assert real.something.call_args == ()
    >>> assert real.something.call_args_list == [()]

If the mock has only been called once then you can use
:meth:`Mock.assert_called_once_with`:

.. doctest::

    >>> real = ProductionClass()
    >>> real.something = Mock()
    >>> real.method()
    >>> real.something.assert_called_once_with()

If you don't care how many times an object has been called, but are just
interested in the most recent call, then you can use
:meth:`Mock.assert_called_with`:

.. doctest::

    >>> mock = Mock(return_value=None)
    >>> mock(1, 2, 3)
    >>> mock.assert_called_with(1, 2, 3)


Mock for Method Calls on an Object
----------------------------------

.. doctest::

    >>> class ProductionClass(object):
    ...     def closer(self, something):
    ...         something.close()
    ...
    >>> real = ProductionClass()
    >>> mock = Mock()
    >>> real.closer(mock)
    >>> mock.close.assert_called_with()


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.

As ``close`` is a mock object is has all the attributes from the previous
example.


Mocking Classes
---------------

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.

In the example below we have a function `some_function` that instantiates `Foo`
and calls a method on it. We can mock out the class `Foo`, and configure the
behaviour of the `Foo` instance by configuring the `mock.return_value`.

.. doctest::

    >>> def some_function():
    ...     instance = module.Foo()
    ...     return instance.method()
    ...
    >>> with patch('module.Foo') as mock:
    ...     instance = mock.return_value
    ...     instance.method.return_value = 'the result'
    ...     result = some_function()
    ...     assert result == 'the result'


Naming your mocks
-----------------

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:

.. doctest::

{'fraction_non_alphanumeric': 0.14010110388940472, 'fraction_numerical': 0.002888682554420716, 'mean_word_length': 2.885370741482966, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 221, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7024107', 'n_tokens_mistral': 2767, 'n_tokens_neox': 2626, 'n_words': 1079}