async def test_no_dispatch_on_unknown_trigger( self, dispatch_mock: AsyncMock) -> None: sample: SampleMachine = SampleMachine() with self.assertLogs(PACKAGE_NAME, level='ERROR') as cm: await sample.trigger("unknown_trigger") self.assertEqual( cm.output, ["ERROR:actyon:no trigger found: unknown_trigger"]) dispatch_mock.assert_not_awaited()
def test_fire_registered_event_cancel(self): bot = Bot("app_name", "version") on_message = AsyncMock() on_message.__name__ = "on_message" on_message.return_value = False bot.register_event(on_message) watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) message = AsyncMock() message.content = "hello there" self._await(bot.on_message(message)) on_message.assert_awaited_once_with(message) watcher_callback.assert_not_awaited()
def test_no_mention(self): bot = Bot("app_name", "version") bot.enforce_write_permission = False simple_callback = AsyncMock() bot.register_command("test", simple_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "hello there" self._await(bot.on_message(message)) simple_callback.assert_not_awaited() watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited()
async def test_app_with_lifespan_uses_callbacks(): startup = AsyncMock(return_value=None) shutdown = AsyncMock(return_value=None) seal(startup), seal(shutdown) async with TestClient( AppWithLifespan( app=AppBasic(MgFixed(RsText("Hello there!"))), startup=startup, shutdown=shutdown, ), ) as client: startup.assert_awaited_once() shutdown.assert_not_awaited() resp = await client.get("/") assert resp.status_code == 200 assert resp.content == b"Hello there!" shutdown.assert_awaited_once()
def test_mention_command_regex(self): bot = Bot("app_name", "version") bot.enforce_write_permission = False bot.client.user.id = "12345" regex_callback = AsyncMock() bot.register_command("^t[eo]a?st$", regex_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "<@12345> toast hey" self._await(bot.on_message(message)) regex_callback.assert_awaited_once_with(bot.client, message, "toast", "hey") watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited()
def test_mention_command_simple(self): bot = Bot("app_name", "version") bot.enforce_write_permission = False bot.client.user.id = "12345" simple_callback = AsyncMock() bot.register_command("test", simple_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "<@12345> test arg0 arg1" self._await(bot.on_message(message)) simple_callback.assert_awaited_once_with(bot.client, message, "test", "arg0", "arg1") watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited()
def test_any_mention_off(self): bot = Bot("app_name", "version") bot.enforce_write_permission = False bot.any_mention = False bot.client.user.id = "12345" simple_callback = AsyncMock() bot.register_command("test", simple_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "test <@12345> arg0 arg1" message.channel.type == discord.ChannelType.private message.mentions = [bot.client.user] self._await(bot.on_message(message)) simple_callback.assert_not_awaited() watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited()
async def test_on_event(app, client, store: GlobalConfigStore): cb = AsyncMock() store.listeners.add(cb) # Empty await store._on_event('topic', {}) assert store.units['temperature'] == 'degC' cb.assert_not_awaited() # Unrelated await store._on_event( 'topic', { 'changed': [{ 'id': 'imperialist_units', 'namespace': const.GLOBAL_NAMESPACE, 'temperature': 'degF', }] }) assert store.units['temperature'] == 'degC' cb.assert_not_awaited() # Same await store._on_event( 'topic', { 'changed': [{ 'id': const.GLOBAL_UNITS_ID, 'namespace': const.GLOBAL_NAMESPACE, 'temperature': 'degC', }] }) assert store.units['temperature'] == 'degC' cb.assert_not_awaited() # Units changed cb.reset_mock() await store._on_event( 'topic', { 'changed': [{ 'id': const.GLOBAL_UNITS_ID, 'namespace': const.GLOBAL_NAMESPACE, 'temperature': 'degF', }] }) assert store.units['temperature'] == 'degF' cb.assert_awaited_with() # Timezone changed cb.reset_mock() await store._on_event( 'topic', { 'changed': [{ 'id': const.GLOBAL_TIME_ZONE_ID, 'namespace': const.GLOBAL_NAMESPACE, 'name': 'Europe/Amsterdam', 'posixValue': 'CET-1CEST,M3.5.0,M10.5.0/3', }] }) assert store.time_zone['name'] == 'Europe/Amsterdam' cb.assert_awaited_with()
async def test_authenticate(monkeypatch): import tome.middleware.auth fake_app = AsyncMock() fake_validate_api_key = AsyncMock() fake_validate_auth_token = AsyncMock() middleware = tome.middleware.auth.AuthenticationMiddleware(fake_app) monkeypatch.setattr(tome.middleware.auth.auth, "validate_api_key", fake_validate_api_key) monkeypatch.setattr(tome.middleware.auth.auth, "validate_auth_token", fake_validate_auth_token) fake_request = type("", (), {})() fake_request.headers = MutableHeaders({}) assert await middleware.authenticate(fake_request) == (None, ["anonymous"]) fake_request.headers["authorization"] = "fake" assert await middleware.authenticate(fake_request) == (None, ["anonymous"]) key = uuid.uuid4() fake_request.headers["authorization"] = "Bearer api-key-" + key.hex await middleware.authenticate(fake_request) fake_validate_api_key.assert_awaited_once_with(key) fake_validate_auth_token.assert_not_awaited() with pytest.raises(HTTPException) as exc_info: fake_request.headers["authorization"] = "Bearer api-key-invalid" await middleware.authenticate(fake_request) assert exc_info.value.status_code == 401 fake_validate_api_key.reset_mock() fake_validate_auth_token.reset_mock() fake_request.headers["authorization"] = "Bearer foobar-auth-token" await middleware.authenticate(fake_request) fake_validate_api_key.assert_not_awaited() fake_validate_auth_token.assert_awaited_once_with(b"foobar-auth-token")
def test_mention_no_permission(self): bot = Bot("app_name", "version") bot.client.user.id = "12345" simple_callback = AsyncMock() bot.register_command("test", simple_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "<@12345> test hey" message.channel.__repr__ = lambda *a: "test_channel" message.guild.__repr__ = lambda *a: "test_guild" permissions = AsyncMock() permissions.send_messages = False message.channel.permissions_for = lambda u: permissions self._await(bot.on_message(message)) simple_callback.assert_not_awaited() watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited() message.author.create_dm.assert_awaited_once() message.author.dm_channel.send.assert_awaited_once_with( f"Hi, this bot doesn't have the permission to send a message to" f" #test_channel in server 'test_guild'")
class AsyncMockAssert(unittest.TestCase): def setUp(self): self.mock = AsyncMock() async def _runnable_test(self, *args): if not args: await self.mock() else: await self.mock(*args) def test_assert_awaited(self): with self.assertRaises(AssertionError): self.mock.assert_awaited() asyncio.run(self._runnable_test()) self.mock.assert_awaited() def test_assert_awaited_once(self): with self.assertRaises(AssertionError): self.mock.assert_awaited_once() asyncio.run(self._runnable_test()) self.mock.assert_awaited_once() asyncio.run(self._runnable_test()) with self.assertRaises(AssertionError): self.mock.assert_awaited_once() def test_assert_awaited_with(self): asyncio.run(self._runnable_test()) msg = 'expected await not found' with self.assertRaisesRegex(AssertionError, msg): self.mock.assert_awaited_with('foo') asyncio.run(self._runnable_test('foo')) self.mock.assert_awaited_with('foo') asyncio.run(self._runnable_test('SomethingElse')) with self.assertRaises(AssertionError): self.mock.assert_awaited_with('foo') def test_assert_awaited_once_with(self): with self.assertRaises(AssertionError): self.mock.assert_awaited_once_with('foo') asyncio.run(self._runnable_test('foo')) self.mock.assert_awaited_once_with('foo') asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_awaited_once_with('foo') def test_assert_any_wait(self): with self.assertRaises(AssertionError): self.mock.assert_any_await('NormalFoo') asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_any_await('NormalFoo') asyncio.run(self._runnable_test('NormalFoo')) self.mock.assert_any_await('NormalFoo') asyncio.run(self._runnable_test('SomethingElse')) self.mock.assert_any_await('NormalFoo') def test_assert_has_awaits_no_order(self): calls = [call('NormalFoo'), call('baz')] with self.assertRaises(AssertionError) as cm: self.mock.assert_has_awaits(calls) self.assertEqual(len(cm.exception.args), 1) asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('NormalFoo')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('baz')) self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('SomethingElse')) self.mock.assert_has_awaits(calls) def test_assert_has_awaits_ordered(self): calls = [call('NormalFoo'), call('baz')] with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('baz')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('NormalFoo')) self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('qux')) self.mock.assert_has_awaits(calls, any_order=True) def test_assert_not_awaited(self): self.mock.assert_not_awaited() asyncio.run(self._runnable_test()) with self.assertRaises(AssertionError): self.mock.assert_not_awaited()
class AsyncMockAssert(unittest.TestCase): def setUp(self): self.mock = AsyncMock() async def _runnable_test(self, *args, **kwargs): await self.mock(*args, **kwargs) async def _await_coroutine(self, coroutine): return await coroutine def test_assert_called_but_not_awaited(self): mock = AsyncMock(AsyncClass) with self.assertWarns(RuntimeWarning): # Will raise a warning because never awaited mock.async_method() self.assertTrue(asyncio.iscoroutinefunction(mock.async_method)) mock.async_method.assert_called() mock.async_method.assert_called_once() mock.async_method.assert_called_once_with() with self.assertRaises(AssertionError): mock.assert_awaited() with self.assertRaises(AssertionError): mock.async_method.assert_awaited() def test_assert_called_then_awaited(self): mock = AsyncMock(AsyncClass) mock_coroutine = mock.async_method() mock.async_method.assert_called() mock.async_method.assert_called_once() mock.async_method.assert_called_once_with() with self.assertRaises(AssertionError): mock.async_method.assert_awaited() asyncio.run(self._await_coroutine(mock_coroutine)) # Assert we haven't re-called the function mock.async_method.assert_called_once() mock.async_method.assert_awaited() mock.async_method.assert_awaited_once() mock.async_method.assert_awaited_once_with() def test_assert_called_and_awaited_at_same_time(self): with self.assertRaises(AssertionError): self.mock.assert_awaited() with self.assertRaises(AssertionError): self.mock.assert_called() asyncio.run(self._runnable_test()) self.mock.assert_called_once() self.mock.assert_awaited_once() def test_assert_called_twice_and_awaited_once(self): mock = AsyncMock(AsyncClass) coroutine = mock.async_method() with self.assertWarns(RuntimeWarning): # The first call will be awaited so no warning there # But this call will never get awaited, so it will warn here mock.async_method() with self.assertRaises(AssertionError): mock.async_method.assert_awaited() mock.async_method.assert_called() asyncio.run(self._await_coroutine(coroutine)) mock.async_method.assert_awaited() mock.async_method.assert_awaited_once() def test_assert_called_once_and_awaited_twice(self): mock = AsyncMock(AsyncClass) coroutine = mock.async_method() mock.async_method.assert_called_once() asyncio.run(self._await_coroutine(coroutine)) with self.assertRaises(RuntimeError): # Cannot reuse already awaited coroutine asyncio.run(self._await_coroutine(coroutine)) mock.async_method.assert_awaited() def test_assert_awaited_but_not_called(self): with self.assertRaises(AssertionError): self.mock.assert_awaited() with self.assertRaises(AssertionError): self.mock.assert_called() with self.assertRaises(TypeError): # You cannot await an AsyncMock, it must be a coroutine asyncio.run(self._await_coroutine(self.mock)) with self.assertRaises(AssertionError): self.mock.assert_awaited() with self.assertRaises(AssertionError): self.mock.assert_called() def test_assert_has_calls_not_awaits(self): kalls = [call('foo')] with self.assertWarns(RuntimeWarning): # Will raise a warning because never awaited self.mock('foo') self.mock.assert_has_calls(kalls) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(kalls) def test_assert_has_mock_calls_on_async_mock_no_spec(self): with self.assertWarns(RuntimeWarning): # Will raise a warning because never awaited self.mock() kalls_empty = [('', (), {})] self.assertEqual(self.mock.mock_calls, kalls_empty) with self.assertWarns(RuntimeWarning): # Will raise a warning because never awaited self.mock('foo') self.mock('baz') mock_kalls = ([call(), call('foo'), call('baz')]) self.assertEqual(self.mock.mock_calls, mock_kalls) def test_assert_has_mock_calls_on_async_mock_with_spec(self): a_class_mock = AsyncMock(AsyncClass) with self.assertWarns(RuntimeWarning): # Will raise a warning because never awaited a_class_mock.async_method() kalls_empty = [('', (), {})] self.assertEqual(a_class_mock.async_method.mock_calls, kalls_empty) self.assertEqual(a_class_mock.mock_calls, [call.async_method()]) with self.assertWarns(RuntimeWarning): # Will raise a warning because never awaited a_class_mock.async_method(1, 2, 3, a=4, b=5) method_kalls = [call(), call(1, 2, 3, a=4, b=5)] mock_kalls = [ call.async_method(), call.async_method(1, 2, 3, a=4, b=5) ] self.assertEqual(a_class_mock.async_method.mock_calls, method_kalls) self.assertEqual(a_class_mock.mock_calls, mock_kalls) def test_async_method_calls_recorded(self): with self.assertWarns(RuntimeWarning): # Will raise warnings because never awaited self.mock.something(3, fish=None) self.mock.something_else.something(6, cake=sentinel.Cake) self.assertEqual(self.mock.method_calls, [("something", (3, ), { 'fish': None }), ("something_else.something", (6, ), { 'cake': sentinel.Cake })], "method calls not recorded correctly") self.assertEqual(self.mock.something_else.method_calls, [("something", (6, ), { 'cake': sentinel.Cake })], "method calls not recorded correctly") def test_async_arg_lists(self): def assert_attrs(mock): names = ('call_args_list', 'method_calls', 'mock_calls') for name in names: attr = getattr(mock, name) self.assertIsInstance(attr, _CallList) self.assertIsInstance(attr, list) self.assertEqual(attr, []) assert_attrs(self.mock) with self.assertWarns(RuntimeWarning): # Will raise warnings because never awaited self.mock() self.mock(1, 2) self.mock(a=3) self.mock.reset_mock() assert_attrs(self.mock) a_mock = AsyncMock(AsyncClass) with self.assertWarns(RuntimeWarning): # Will raise warnings because never awaited a_mock.async_method() a_mock.async_method(1, a=3) a_mock.reset_mock() assert_attrs(a_mock) def test_assert_awaited(self): with self.assertRaises(AssertionError): self.mock.assert_awaited() asyncio.run(self._runnable_test()) self.mock.assert_awaited() def test_assert_awaited_once(self): with self.assertRaises(AssertionError): self.mock.assert_awaited_once() asyncio.run(self._runnable_test()) self.mock.assert_awaited_once() asyncio.run(self._runnable_test()) with self.assertRaises(AssertionError): self.mock.assert_awaited_once() def test_assert_awaited_with(self): msg = 'Not awaited' with self.assertRaisesRegex(AssertionError, msg): self.mock.assert_awaited_with('foo') asyncio.run(self._runnable_test()) msg = 'expected await not found' with self.assertRaisesRegex(AssertionError, msg): self.mock.assert_awaited_with('foo') asyncio.run(self._runnable_test('foo')) self.mock.assert_awaited_with('foo') asyncio.run(self._runnable_test('SomethingElse')) with self.assertRaises(AssertionError): self.mock.assert_awaited_with('foo') def test_assert_awaited_once_with(self): with self.assertRaises(AssertionError): self.mock.assert_awaited_once_with('foo') asyncio.run(self._runnable_test('foo')) self.mock.assert_awaited_once_with('foo') asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_awaited_once_with('foo') def test_assert_any_wait(self): with self.assertRaises(AssertionError): self.mock.assert_any_await('foo') asyncio.run(self._runnable_test('baz')) with self.assertRaises(AssertionError): self.mock.assert_any_await('foo') asyncio.run(self._runnable_test('foo')) self.mock.assert_any_await('foo') asyncio.run(self._runnable_test('SomethingElse')) self.mock.assert_any_await('foo') def test_assert_has_awaits_no_order(self): calls = [call('foo'), call('baz')] with self.assertRaises(AssertionError) as cm: self.mock.assert_has_awaits(calls) self.assertEqual(len(cm.exception.args), 1) asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('baz')) self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('SomethingElse')) self.mock.assert_has_awaits(calls) def test_assert_has_awaits_ordered(self): calls = [call('foo'), call('baz')] with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('baz')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('bamf')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('foo')) self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('qux')) self.mock.assert_has_awaits(calls, any_order=True) def test_assert_not_awaited(self): self.mock.assert_not_awaited() asyncio.run(self._runnable_test()) with self.assertRaises(AssertionError): self.mock.assert_not_awaited() def test_assert_has_awaits_not_matching_spec_error(self): async def f(x=None): pass self.mock = AsyncMock(spec=f) asyncio.run(self._runnable_test(1)) with self.assertRaisesRegex( AssertionError, '^{}$'.format( re.escape('Awaits not found.\n' 'Expected: [call()]\n' 'Actual: [call(1)]'))) as cm: self.mock.assert_has_awaits([call()]) self.assertIsNone(cm.exception.__cause__) with self.assertRaisesRegex( AssertionError, '^{}$'.format( re.escape('Error processing expected awaits.\n' "Errors: [None, TypeError('too many positional " "arguments')]\n" 'Expected: [call(), call(1, 2)]\n' 'Actual: [call(1)]'))) as cm: self.mock.assert_has_awaits([call(), call(1, 2)]) self.assertIsInstance(cm.exception.__cause__, TypeError)
class AsyncMockAssert(unittest.TestCase): def setUp(self): self.mock = AsyncMock() async def _runnable_test(self, *args): if not args: await self.mock() else: await self.mock(*args) def test_assert_awaited(self): with self.assertRaises(AssertionError): self.mock.assert_awaited() asyncio.run(self._runnable_test()) self.mock.assert_awaited() def test_assert_awaited_once(self): with self.assertRaises(AssertionError): self.mock.assert_awaited_once() asyncio.run(self._runnable_test()) self.mock.assert_awaited_once() asyncio.run(self._runnable_test()) with self.assertRaises(AssertionError): self.mock.assert_awaited_once() def test_assert_awaited_with(self): asyncio.run(self._runnable_test()) msg = 'expected await not found' with self.assertRaisesRegex(AssertionError, msg): self.mock.assert_awaited_with('foo') asyncio.run(self._runnable_test('foo')) self.mock.assert_awaited_with('foo') asyncio.run(self._runnable_test('SomethingElse')) with self.assertRaises(AssertionError): self.mock.assert_awaited_with('foo') def test_assert_awaited_once_with(self): with self.assertRaises(AssertionError): self.mock.assert_awaited_once_with('foo') asyncio.run(self._runnable_test('foo')) self.mock.assert_awaited_once_with('foo') asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_awaited_once_with('foo') def test_assert_any_wait(self): with self.assertRaises(AssertionError): self.mock.assert_any_await('NormalFoo') asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_any_await('NormalFoo') asyncio.run(self._runnable_test('NormalFoo')) self.mock.assert_any_await('NormalFoo') asyncio.run(self._runnable_test('SomethingElse')) self.mock.assert_any_await('NormalFoo') def test_assert_has_awaits_no_order(self): calls = [call('NormalFoo'), call('baz')] with self.assertRaises(AssertionError) as cm: self.mock.assert_has_awaits(calls) self.assertEqual(len(cm.exception.args), 1) asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('NormalFoo')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('baz')) self.mock.assert_has_awaits(calls) asyncio.run(self._runnable_test('SomethingElse')) self.mock.assert_has_awaits(calls) def test_awaits_asserts_with_any(self): class Foo: def __eq__(self, other): pass asyncio.run(self._runnable_test(Foo(), 1)) self.mock.assert_has_awaits([call(ANY, 1)]) self.mock.assert_awaited_with(ANY, 1) self.mock.assert_any_await(ANY, 1) def test_awaits_asserts_with_spec_and_any(self): class Foo: def __eq__(self, other): pass mock_with_spec = AsyncMock(spec=Foo) async def _custom_mock_runnable_test(*args): await mock_with_spec(*args) asyncio.run(_custom_mock_runnable_test(Foo(), 1)) mock_with_spec.assert_has_awaits([call(ANY, 1)]) mock_with_spec.assert_awaited_with(ANY, 1) mock_with_spec.assert_any_await(ANY, 1) def test_assert_has_awaits_ordered(self): calls = [call('NormalFoo'), call('baz')] with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('baz')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('foo')) with self.assertRaises(AssertionError): self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('NormalFoo')) self.mock.assert_has_awaits(calls, any_order=True) asyncio.run(self._runnable_test('qux')) self.mock.assert_has_awaits(calls, any_order=True) def test_assert_not_awaited(self): self.mock.assert_not_awaited() asyncio.run(self._runnable_test()) with self.assertRaises(AssertionError): self.mock.assert_not_awaited()
async def test_auth_middleware_call(monkeypatch): import tome.middleware.auth fake_user = object() fake_auth = object() fake_app = AsyncMock() fake_receive = AsyncMock() fake_send = AsyncMock() async def fake_authenticate_correct(_self, _request): return fake_user, fake_auth monkeypatch.setattr( tome.middleware.auth.AuthenticationMiddleware, "authenticate", fake_authenticate_correct, ) middleware = tome.middleware.auth.AuthenticationMiddleware(fake_app) scope = { "type": "fake" } # other events should be passed straight through to app await middleware(scope, fake_receive, fake_send) fake_app.assert_awaited_once_with(scope, fake_receive, fake_send) fake_send.assert_not_awaited() fake_receive.assert_not_awaited() fake_app.reset_mock() scope = {"type": "http"} await middleware(scope, fake_receive, fake_send) fake_app.assert_awaited_once_with(scope, fake_receive, fake_send) assert scope["user"] == fake_user assert scope["auth"] == fake_auth fake_app.reset_mock() scope = {"type": "websocket"} await middleware(scope, fake_receive, fake_send) fake_app.assert_awaited_once_with(scope, fake_receive, fake_send) assert scope["user"] == fake_user assert scope["auth"] == fake_auth async def fake_authenticate_incorrect(_self, _request): raise HTTPException("foo bar", 418) monkeypatch.setattr( tome.middleware.auth.AuthenticationMiddleware, "authenticate", fake_authenticate_incorrect, ) fake_app.reset_mock() scope = {"type": "http"} await middleware(scope, fake_receive, fake_send) fake_app.assert_not_awaited() fake_app.reset_mock() fake_send.reset_mock() scope = {"type": "websocket"} await middleware(scope, fake_receive, fake_send) # http code 4xx -> ws code 41xx) fake_send.assert_awaited_once_with({ "type": "websocket.close", "code": 4118 }) fake_app.assert_not_awaited()
async def test_zero_max_number(self): mock_func = AsyncMock() assert [x async for x in cursor_based_pagination(mock_func, CHUNK_SIZE, 0)] == [] mock_func.assert_not_awaited()