mock天生器函数和contxt manager仅须要修改该函数中的特定magic mthod,分别是__aiter和__aenter__。示比方下
import unittestfrom unittest.mock import AsyncMock, Mockclass TestMockingDemo(unittest.IsolatedAsyncioTestCase): async def test_mock_generator(self): expected_values = ["foo", "bar", "baz"] my_mock_generator = AsyncMock() my_mock_generator.__aiter__.return_value = expected_values actual_values = [] async for value in my_mock_generator: actual_values.append(value) self.assertListEqual(expected_values, actual_values) async def test_mock_context_manager(self): mock_cm = AsyncMock() # Note that by default an AsyncMock returns more AsyncMocks - we have to replace it with a Mock if we want a # synchronous function mock_cm.get_state = Mock(return_value="Not entered") # Get a context object as a result of entering the context manager. Alternatively, __aenter__ could return # mock_cm, to emulate the behaviour of returning self upon entering the context manager mock_ctx = AsyncMock() mock_cm.__aenter__.return_value = mock_ctx mock_ctx.get_state = Mock(return_value="Entered") print(mock_cm.get_state()) self.assertEqual("Not entered", mock_cm.get_state()) async with mock_cm as entered_ctx: print(entered_ctx.get_state()) self.assertEqual("Entered", entered_ctx.get_state()) async def test_mock_has_awaits(self): my_mock = AsyncMock() my_mock.assert_not_awaited() await my_mock(27) my_mock.assert_awaited_once_with(27)Reference