dev-resources.site
for different kinds of informations.
python: Mock variations
Published at
3/7/2023
Categories
python
mock
Author
Kenichiro Nakamura
This is my note on how to create various mocks. Please let me know if you have trouble creating a mock in your test.
import pytest
from unittest.mock import Mock
# Create a mock with one attribute.
def test_mock_with_one_attribute():
mock = Mock(one_attribute='one')
assert "one" == mock.one_attribute
# Create a mock with multiple attributes.
def test_mock_with_multiple_attributes():
mock = Mock(**{"one_attribute":"one","two_attribute":"two"})
assert "one" == mock.one_attribute
assert "two" == mock.two_attribute
# Create a mock with name attribute. As name is an argument of Mock,
# we need to speficy it after create mock object.
def test_mock_name_attribute():
mock = Mock()
mock.name = "ken"
assert "ken" == mock.name
# Set return value when the mock itself is called as function.
def test_mock_as_function():
mock = Mock(return_value='result')
assert "result" == mock()
# Create a mock with one method.
def test_mock_with_one_method():
mock = Mock(**{"my_method.return_value":"result"})
assert "result" == mock.my_method()
# Create a mock with several methods and attributes at once.
def test_mock_with_methods_and_attributes():
mock = Mock(**{"my_method.return_value":"result_my",
"another_method.return_value":"result_another",
"one_attribute":"one",
"two_attribute":"two"})
assert "result_my" == mock.my_method()
assert "result_another" == mock.another_method()
assert "one" == mock.one_attribute
assert "two" == mock.two_attribute
# Create a method that returns Exception.
def test_mock_with_side_effect_exception():
mock = Mock(side_effect=Exception("dummy"))
with pytest.raises(Exception) as e:
mock()
assert "dummy" == str(e.value)
# Create a mock and inner mock as it's attribute
def test_mock_with_innter_mock_multiple_attributes():
mock = Mock(data = Mock(**{"one_attribute":"one","two_attribute":"two"}))
assert "one" == mock.data.one_attribute
assert "two" == mock.data.two_attribute
Articles
12 articles in total
Azure Open AI in VNet
read article
Azure ML Prompt flow: Use content safety before sending a request to LLM
read article
Don't waste time to write README, use readme-ai instead
read article
C#: Azure Open AI and Function Calling
read article
Visual Studio: Live Unit Test is awesome
read article
C#: Pass Lambda Expression to Select LINQ at Runtime
read article
C#: Pass Lambda Expression to Where LINQ at Runtime
read article
python: unit test with fixture and patch decorators
read article
python: Mock variations
currently reading
python: use multiple patch decorators to mock functions
read article
python: unit test with mock functions from different modules
read article
C# 11: New raw string literals feature makes my life easier!
read article
Featured ones: