Skip to content

Commit

Permalink
chore: normalize references to mock, replace async_mock
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Bluhm <[email protected]>
  • Loading branch information
dbluhm committed Oct 27, 2023
1 parent 176c044 commit 8f07d20
Show file tree
Hide file tree
Showing 175 changed files with 9,582 additions and 10,290 deletions.
104 changes: 48 additions & 56 deletions aries_cloudagent/admin/tests/test_admin_server.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json

import pytest
import mock as async_mock
import mock
from unittest import IsolatedAsyncioTestCase
from aiohttp import ClientSession, DummyCookieJar, TCPConnector, web
from aiohttp.test_utils import unused_port
Expand Down Expand Up @@ -36,66 +36,62 @@ async def asyncTearDown(self):
self.client_session = None

async def test_debug_middleware(self):
with async_mock.patch.object(
test_module, "LOGGER", async_mock.MagicMock()
) as mock_logger:
mock_logger.isEnabledFor = async_mock.MagicMock(return_value=True)
mock_logger.debug = async_mock.MagicMock()
with mock.patch.object(test_module, "LOGGER", mock.MagicMock()) as mock_logger:
mock_logger.isEnabledFor = mock.MagicMock(return_value=True)
mock_logger.debug = mock.MagicMock()

request = async_mock.MagicMock(
request = mock.MagicMock(
method="GET",
path_qs="/hello/world?a=1&b=2",
match_info={"match": "info"},
text=async_mock.AsyncMock(return_value="abc123"),
text=mock.AsyncMock(return_value="abc123"),
)
handler = async_mock.AsyncMock()
handler = mock.AsyncMock()

await test_module.debug_middleware(request, handler)
mock_logger.isEnabledFor.assert_called_once()
assert mock_logger.debug.call_count == 3

async def test_ready_middleware(self):
with async_mock.patch.object(
test_module, "LOGGER", async_mock.MagicMock()
) as mock_logger:
mock_logger.isEnabledFor = async_mock.MagicMock(return_value=True)
mock_logger.debug = async_mock.MagicMock()
mock_logger.info = async_mock.MagicMock()
mock_logger.error = async_mock.MagicMock()

request = async_mock.MagicMock(
rel_url="/", app=async_mock.MagicMock(_state={"ready": False})
with mock.patch.object(test_module, "LOGGER", mock.MagicMock()) as mock_logger:
mock_logger.isEnabledFor = mock.MagicMock(return_value=True)
mock_logger.debug = mock.MagicMock()
mock_logger.info = mock.MagicMock()
mock_logger.error = mock.MagicMock()

request = mock.MagicMock(
rel_url="/", app=mock.MagicMock(_state={"ready": False})
)
handler = async_mock.AsyncMock(return_value="OK")
handler = mock.AsyncMock(return_value="OK")
with self.assertRaises(test_module.web.HTTPServiceUnavailable):
await test_module.ready_middleware(request, handler)

request.app._state["ready"] = True
assert await test_module.ready_middleware(request, handler) == "OK"

request.app._state["ready"] = True
handler = async_mock.AsyncMock(
handler = mock.AsyncMock(
side_effect=test_module.LedgerConfigError("Bad config")
)
with self.assertRaises(test_module.LedgerConfigError):
await test_module.ready_middleware(request, handler)

request.app._state["ready"] = True
handler = async_mock.AsyncMock(
handler = mock.AsyncMock(
side_effect=test_module.web.HTTPFound(location="/api/doc")
)
with self.assertRaises(test_module.web.HTTPFound):
await test_module.ready_middleware(request, handler)

request.app._state["ready"] = True
handler = async_mock.AsyncMock(
handler = mock.AsyncMock(
side_effect=test_module.asyncio.CancelledError("Cancelled")
)
with self.assertRaises(test_module.asyncio.CancelledError):
await test_module.ready_middleware(request, handler)

request.app._state["ready"] = True
handler = async_mock.AsyncMock(side_effect=KeyError("No such thing"))
handler = mock.AsyncMock(side_effect=KeyError("No such thing"))
with self.assertRaises(KeyError):
await test_module.ready_middleware(request, handler)

Expand All @@ -110,10 +106,8 @@ def get_admin_server(
# middleware is task queue xor collector: cover both over test suite
task_queue = (settings or {}).pop("task_queue", None)

plugin_registry = async_mock.MagicMock(
test_module.PluginRegistry, autospec=True
)
plugin_registry.post_process_routes = async_mock.MagicMock()
plugin_registry = mock.MagicMock(test_module.PluginRegistry, autospec=True)
plugin_registry.post_process_routes = mock.MagicMock()
context.injector.bind_instance(test_module.PluginRegistry, plugin_registry)

collector = Collector()
Expand All @@ -129,10 +123,10 @@ def get_admin_server(
profile,
self.outbound_message_router,
self.webhook_router,
conductor_stop=async_mock.AsyncMock(),
conductor_stop=mock.AsyncMock(),
task_queue=TaskQueue(max_active=4) if task_queue else None,
conductor_stats=(
None if task_queue else async_mock.AsyncMock(return_value={"a": 1})
None if task_queue else mock.AsyncMock(return_value={"a": 1})
),
)

Expand Down Expand Up @@ -165,17 +159,15 @@ async def test_start_stop(self):
server = self.get_admin_server(settings)
await server.start()
assert server.app._client_max_size == 4 * 1024 * 1024
with async_mock.patch.object(
server, "websocket_queues", async_mock.MagicMock()
with mock.patch.object(
server, "websocket_queues", mock.MagicMock()
) as mock_wsq:
mock_wsq.values = async_mock.MagicMock(
return_value=[async_mock.MagicMock(stop=async_mock.MagicMock())]
mock_wsq.values = mock.MagicMock(
return_value=[mock.MagicMock(stop=mock.MagicMock())]
)
await server.stop()

with async_mock.patch.object(
web.TCPSite, "start", async_mock.AsyncMock()
) as mock_start:
with mock.patch.object(web.TCPSite, "start", mock.AsyncMock()) as mock_start:
mock_start.side_effect = OSError("Failure to launch")
with self.assertRaises(AdminSetupError):
await self.get_admin_server(settings).start()
Expand All @@ -199,7 +191,7 @@ async def test_import_routes_multitenant_middleware(self):
context.injector.bind_instance(GoalCodeRegistry, GoalCodeRegistry())
context.injector.bind_instance(
test_module.BaseMultitenantManager,
async_mock.MagicMock(spec=test_module.BaseMultitenantManager),
mock.MagicMock(spec=test_module.BaseMultitenantManager),
)
await DefaultContextBuilder().load_plugins(context)
server = self.get_admin_server(
Expand All @@ -220,66 +212,66 @@ async def test_import_routes_multitenant_middleware(self):
m for m in app.middlewares if ".check_multitenant_authorization" in str(m)
]

mock_request = async_mock.MagicMock(
mock_request = mock.MagicMock(
method="GET",
headers={"Authorization": "Bearer ..."},
path="/multitenancy/etc",
text=async_mock.AsyncMock(return_value="abc123"),
text=mock.AsyncMock(return_value="abc123"),
)
with self.assertRaises(test_module.web.HTTPUnauthorized):
await mt_authz_middle(mock_request, None)

mock_request = async_mock.MagicMock(
mock_request = mock.MagicMock(
method="GET",
headers={},
path="/protected/non-multitenancy/non-server",
text=async_mock.AsyncMock(return_value="abc123"),
text=mock.AsyncMock(return_value="abc123"),
)
with self.assertRaises(test_module.web.HTTPUnauthorized):
await mt_authz_middle(mock_request, None)

mock_request = async_mock.MagicMock(
mock_request = mock.MagicMock(
method="GET",
headers={"Authorization": "Bearer ..."},
path="/protected/non-multitenancy/non-server",
text=async_mock.AsyncMock(return_value="abc123"),
text=mock.AsyncMock(return_value="abc123"),
)
mock_handler = async_mock.AsyncMock()
mock_handler = mock.AsyncMock()
await mt_authz_middle(mock_request, mock_handler)
assert mock_handler.called_once_with(mock_request)

mock_request = async_mock.MagicMock(
mock_request = mock.MagicMock(
method="GET",
headers={"Authorization": "Non-bearer ..."},
path="/test",
text=async_mock.AsyncMock(return_value="abc123"),
text=mock.AsyncMock(return_value="abc123"),
)
mock_handler = async_mock.AsyncMock()
mock_handler = mock.AsyncMock()
await mt_authz_middle(mock_request, mock_handler)
assert mock_handler.called_once_with(mock_request)

# multitenant setup context exception paths
[setup_ctx_middle] = [m for m in app.middlewares if ".setup_context" in str(m)]

mock_request = async_mock.MagicMock(
mock_request = mock.MagicMock(
method="GET",
headers={"Authorization": "Non-bearer ..."},
path="/protected/non-multitenancy/non-server",
text=async_mock.AsyncMock(return_value="abc123"),
text=mock.AsyncMock(return_value="abc123"),
)
with self.assertRaises(test_module.web.HTTPUnauthorized):
await setup_ctx_middle(mock_request, None)

mock_request = async_mock.MagicMock(
mock_request = mock.MagicMock(
method="GET",
headers={"Authorization": "Bearer ..."},
path="/protected/non-multitenancy/non-server",
text=async_mock.AsyncMock(return_value="abc123"),
text=mock.AsyncMock(return_value="abc123"),
)
with async_mock.patch.object(
with mock.patch.object(
server.multitenant_manager,
"get_profile_for_token",
async_mock.AsyncMock(),
mock.AsyncMock(),
) as mock_get_profile:
mock_get_profile.side_effect = [
test_module.MultitenantManagerError("corrupt token"),
Expand Down Expand Up @@ -493,8 +485,8 @@ async def server():
)
async def test_on_record_event(server, event_topic, webhook_topic):
profile = InMemoryProfile.test_profile()
with async_mock.patch.object(
server, "send_webhook", async_mock.AsyncMock()
with mock.patch.object(
server, "send_webhook", mock.AsyncMock()
) as mock_send_webhook:
await server._on_record_event(profile, Event(event_topic, None))
mock_send_webhook.assert_called_once_with(profile, webhook_topic, None)
Expand Down
18 changes: 9 additions & 9 deletions aries_cloudagent/askar/didcomm/tests/test_v2.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json

from unittest import mock as async_mock
from unittest import mock
import pytest

from aries_askar import AskarError, Key, KeyAlg, Session
Expand Down Expand Up @@ -70,19 +70,19 @@ async def test_es_encrypt_x(self, session: Session):
):
_ = test_module.ecdh_es_encrypt({}, MESSAGE)

with async_mock.patch(
with mock.patch(
"aries_askar.Key.generate",
async_mock.MagicMock(side_effect=AskarError(99, "")),
mock.MagicMock(side_effect=AskarError(99, "")),
):
with pytest.raises(
test_module.DidcommEnvelopeError,
match="Error creating content encryption key",
):
_ = test_module.ecdh_es_encrypt({BOB_KID: bob_pk}, MESSAGE)

with async_mock.patch(
with mock.patch(
"aries_askar.Key.aead_encrypt",
async_mock.MagicMock(side_effect=AskarError(99, "")),
mock.MagicMock(side_effect=AskarError(99, "")),
):
with pytest.raises(
test_module.DidcommEnvelopeError,
Expand Down Expand Up @@ -188,9 +188,9 @@ async def test_1pu_encrypt_x(self, session: Session):
{BOB_KID: bob_pk, "alt": alt_pk}, ALICE_KID, alice_sk, MESSAGE
)

with async_mock.patch(
with mock.patch(
"aries_askar.Key.generate",
async_mock.MagicMock(side_effect=AskarError(99, "")),
mock.MagicMock(side_effect=AskarError(99, "")),
):
with pytest.raises(
test_module.DidcommEnvelopeError,
Expand All @@ -200,9 +200,9 @@ async def test_1pu_encrypt_x(self, session: Session):
{BOB_KID: bob_pk}, ALICE_KID, alice_sk, MESSAGE
)

with async_mock.patch(
with mock.patch(
"aries_askar.Key.aead_encrypt",
async_mock.MagicMock(side_effect=AskarError(99, "")),
mock.MagicMock(side_effect=AskarError(99, "")),
):
with pytest.raises(
test_module.DidcommEnvelopeError,
Expand Down
14 changes: 7 additions & 7 deletions aries_cloudagent/commands/tests/test_help.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from unittest import mock as async_mock
from unittest import mock
from unittest import IsolatedAsyncioTestCase

from .. import help as command


class TestHelp(IsolatedAsyncioTestCase):
def test_exec_help(self):
with async_mock.patch.object(
with mock.patch.object(
command.ArgumentParser, "print_help"
) as mock_print_help, async_mock.patch(
"builtins.print", async_mock.MagicMock()
) as mock_print_help, mock.patch(
"builtins.print", mock.MagicMock()
) as mock_print:
command.execute([])
mock_print_help.assert_called_once()
Expand All @@ -18,10 +18,10 @@ def test_exec_help(self):
mock_print.assert_called_once_with(command.__version__)

def test_main(self):
with async_mock.patch.object(
with mock.patch.object(
command, "__name__", "__main__"
) as mock_name, async_mock.patch.object(
command, "execute", async_mock.MagicMock()
) as mock_name, mock.patch.object(
command, "execute", mock.MagicMock()
) as mock_execute:
command.main()
mock_execute.assert_called_once
10 changes: 5 additions & 5 deletions aries_cloudagent/commands/tests/test_init.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from unittest import mock as async_mock
from unittest import mock
from unittest import IsolatedAsyncioTestCase

from ... import commands as test_module
Expand All @@ -10,11 +10,11 @@ def test_available(self):
assert len(avail) == 4

def test_run(self):
with async_mock.patch.object(
test_module, "load_command", async_mock.MagicMock()
with mock.patch.object(
test_module, "load_command", mock.MagicMock()
) as mock_load:
mock_module = async_mock.MagicMock()
mock_module.execute = async_mock.MagicMock()
mock_module = mock.MagicMock()
mock_module.execute = mock.MagicMock()
mock_load.return_value = mock_module

test_module.run_command("hello", ["world"])
Expand Down
Loading

0 comments on commit 8f07d20

Please sign in to comment.