Python Mocking with unitest.mock: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * unittest Module =Overview=")
 
Line 2: Line 2:
* [[Python_Module_unittest#unittest.mock|unittest Module]]
* [[Python_Module_unittest#unittest.mock|unittest Module]]
=Overview=
=Overview=
=Mocking=
To mock a class and a method of that class:
<syntaxhighlight lang='py'>
from unittest.mock import Mock
class SomeClass:
    def __init__(self, state):
        self.state = state
    def some_method(self):
        return self.state
sc = SomeClass('A')
assert 'A' == sc.some_method()
sc_mock = Mock(SomeClass)
sc_mock.some_method = Mock(return_value='blah')
assert 'blah' == sc_mock.some_method()
</syntaxhighlight>
<font color=darkkhaki>
How to simulate different return values for a mocked function depending on an argument value?
</font>
==Mocking a Property==
{{External|https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock}}
<syntaxhighlight lang='py'>
from unittest.mock import patch, PropertyMock
class A:
    @property
    def property_a(self):
        return "pa"
with patch('__main__.A.property_a', new_callable=PropertyMock) as mock_property:
    mock_property.return_value = 'mocked pa'
    a = A()
    assert a.property_a == 'mocked pa'
</syntaxhighlight>
==Mocking a Method==
<syntaxhighlight lang='py'>
from unittest.mock import patch
class A:
    def method_a(self):
        return "ma"
with patch.object(A, 'method_a', return_value='mocked ma') as mock_method:
    a = A()
    assert a.method_a() == 'mocked ma'
</syntaxhighlight>

Revision as of 00:04, 28 August 2022

Internal

Overview

Mocking

To mock a class and a method of that class:

from unittest.mock import Mock


class SomeClass:
    def __init__(self, state):
        self.state = state

    def some_method(self):
        return self.state


sc = SomeClass('A')
assert 'A' == sc.some_method()

sc_mock = Mock(SomeClass)
sc_mock.some_method = Mock(return_value='blah')

assert 'blah' == sc_mock.some_method()


How to simulate different return values for a mocked function depending on an argument value?

Mocking a Property

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock
from unittest.mock import patch, PropertyMock

class A:
    @property
    def property_a(self):
        return "pa"

with patch('__main__.A.property_a', new_callable=PropertyMock) as mock_property:
    mock_property.return_value = 'mocked pa'
    a = A()
    assert a.property_a == 'mocked pa'

Mocking a Method

from unittest.mock import patch

class A:
    def method_a(self):
        return "ma"

with patch.object(A, 'method_a', return_value='mocked ma') as mock_method:
    a = A()
    assert a.method_a() == 'mocked ma'