Skip to content

Commit

Permalink
Merge pull request #1053 from sklump/unit-tests-json-ld-and-admin-ser…
Browse files Browse the repository at this point in the history
…ver-multitenancy

Unit test coverage: json-ld, multitenancy in admin-server setup
  • Loading branch information
ianco authored Mar 25, 2021
2 parents 12d51e3 + c5cf8d9 commit 46c2265
Show file tree
Hide file tree
Showing 36 changed files with 460 additions and 176 deletions.
10 changes: 5 additions & 5 deletions aries_cloudagent/admin/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,10 @@ def topic_filter(self) -> Set[str]:
@topic_filter.setter
def topic_filter(self, val: Sequence[str]):
"""Setter for the target's topic filter."""
filter = set(val) if val else None
if filter and "*" in filter:
filter = None
self._topic_filter = filter
filt = set(val) if val else None
if filt and "*" in filt:
filt = None
self._topic_filter = filt


@web.middleware
Expand Down Expand Up @@ -336,7 +336,7 @@ async def setup_context(request: web.Request, handler):
self.context, token
)
except MultitenantManagerError as err:
raise web.HTTPUnauthorized(err.roll_up)
raise web.HTTPUnauthorized(reason=err.roll_up)
except (jwt.InvalidTokenError, StorageNotFoundError):
raise web.HTTPUnauthorized()

Expand Down
120 changes: 120 additions & 0 deletions aries_cloudagent/admin/tests/test_admin_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,39 @@
from ..server import AdminServer, AdminSetupError


class TestAdminResponder(AsyncTestCase):
async def test_admin_responder(self):
admin_responder = test_module.AdminResponder(
None, async_mock.CoroutineMock(), async_mock.CoroutineMock()
)

assert admin_responder.send_fn is admin_responder._send
assert admin_responder.webhook_fn is admin_responder._webhook

message = test_module.OutboundMessage(payload="hello")
await admin_responder.send_outbound(message)
assert admin_responder._send.called_once_with(None, message)

await admin_responder.send_webhook("topic", {"payload": "hello"})
assert admin_responder._webhook.called_once_with("topic", {"outbound": "hello"})


class TestWebhookTarget(AsyncTestCase):
async def test_webhook_target(self):
webhook_target = test_module.WebhookTarget(
endpoint="localhost:8888",
topic_filter=["birthdays", "animal videos"],
max_attempts=None,
)
assert webhook_target.topic_filter == {"birthdays", "animal videos"}

webhook_target.topic_filter = []
assert webhook_target.topic_filter is None

webhook_target.topic_filter = ["duct cleaning", "*"]
assert webhook_target.topic_filter is None


class TestAdminServer(AsyncTestCase):
async def setUp(self):
self.message_results = []
Expand Down Expand Up @@ -185,6 +218,93 @@ async def test_import_routes(self):
server = self.get_admin_server({"admin.admin_insecure_mode": True}, context)
app = await server.make_application()

async def test_import_routes_multitenant_middleware(self):
# imports all default admin routes
context = InjectionContext()
context.injector.bind_instance(ProtocolRegistry, ProtocolRegistry())
profile = InMemoryProfile.test_profile()
context.injector.bind_instance(
test_module.MultitenantManager,
test_module.MultitenantManager(profile),
)
await DefaultContextBuilder().load_plugins(context)
server = self.get_admin_server(
{
"admin.admin_insecure_mode": False,
"admin.admin_api_key": "test-api-key",
},
context,
)

# cover multitenancy start code
app = await server.make_application()
app["swagger_dict"] = {}
await server.on_startup(app)

# multitenant authz
[mt_authz_middle] = [
m for m in app.middlewares if ".check_multitenant_authorization" in str(m)
]

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

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

mock_request = async_mock.MagicMock(
method="GET",
headers={"Authorization": "Bearer ..."},
path="/protected/non-multitenancy/non-server",
text=async_mock.CoroutineMock(return_value="abc123"),
)
mock_handler = async_mock.CoroutineMock()
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(
method="GET",
headers={"Authorization": "Non-bearer ..."},
path="/protected/non-multitenancy/non-server",
text=async_mock.CoroutineMock(return_value="abc123"),
)
with self.assertRaises(test_module.web.HTTPUnauthorized):
await setup_ctx_middle(mock_request, None)

mock_request = async_mock.MagicMock(
method="GET",
headers={"Authorization": "Bearer ..."},
path="/protected/non-multitenancy/non-server",
text=async_mock.CoroutineMock(return_value="abc123"),
)
with async_mock.patch.object(
server.multitenant_manager,
"get_profile_for_token",
async_mock.CoroutineMock(),
) as mock_get_profile:
mock_get_profile.side_effect = [
test_module.MultitenantManagerError("corrupt token"),
test_module.StorageNotFoundError("out of memory"),
]
for i in range(2):
with self.assertRaises(test_module.web.HTTPUnauthorized):
await setup_ctx_middle(mock_request, None)

async def test_register_external_plugin_x(self):
context = InjectionContext()
context.injector.bind_instance(ProtocolRegistry, ProtocolRegistry())
Expand Down
3 changes: 1 addition & 2 deletions aries_cloudagent/admin/tests/test_request_context.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from asynctest import mock as asyn_mock, TestCase as AsyncTestCase

from ...core.in_memory import InMemoryProfile
from ...core.profile import ProfileSession
Expand Down
3 changes: 2 additions & 1 deletion aries_cloudagent/cache/tests/test_in_memory_cache.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from asyncio import ensure_future, sleep, wait_for
import pytest

from asyncio import ensure_future, sleep, wait_for

from ..base import CacheError
from ..in_memory import InMemoryCache

Expand Down
3 changes: 1 addition & 2 deletions aries_cloudagent/commands/tests/test_help.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from asynctest import mock as async_mock, TestCase as AsyncTestCase

from .. import help as command

Expand Down
3 changes: 1 addition & 2 deletions aries_cloudagent/commands/tests/test_init.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from asynctest import mock as async_mock, TestCase as AsyncTestCase

from ... import commands as test_module

Expand Down
4 changes: 2 additions & 2 deletions aries_cloudagent/commands/tests/test_provision.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
import pytest

from asynctest import mock as async_mock, TestCase as AsyncTestCase

from ...config.base import ConfigError
from ...config.error import ArgsParseError
from ...core.profile import Profile
Expand Down
4 changes: 2 additions & 2 deletions aries_cloudagent/commands/tests/test_start.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import sys

from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from asynctest import mock as async_mock, TestCase as AsyncTestCase

from ...config.error import ArgsParseError

from .. import start as test_module


Expand Down
2 changes: 1 addition & 1 deletion aries_cloudagent/config/tests/test_ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

from asynctest import TestCase as AsyncTestCase, mock as async_mock

from .. import argparse
from ...core.in_memory import InMemoryProfile
from ...ledger.base import BaseLedger
from ...ledger.error import LedgerError
from ...wallet.base import BaseWallet
from .. import argparse

from .. import ledger as test_module
from ..injection_context import InjectionContext
Expand Down
3 changes: 2 additions & 1 deletion aries_cloudagent/config/tests/test_logging.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import contextlib

from asynctest import mock as async_mock
from io import StringIO

from asynctest import mock as async_mock
from tempfile import NamedTemporaryFile

from .. import logging as test_module
Expand Down
1 change: 1 addition & 0 deletions aries_cloudagent/core/tests/test_conductor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from io import StringIO

from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock

Expand Down
1 change: 0 additions & 1 deletion aries_cloudagent/core/tests/test_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import json

from asynctest import TestCase as AsyncTestCase, mock as async_mock

from marshmallow import EXCLUDE

from ...config.injection_context import InjectionContext
Expand Down
5 changes: 2 additions & 3 deletions aries_cloudagent/indy/sdk/tests/test_holder.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import json

import pytest

from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from asynctest import mock as async_mock, TestCase as AsyncTestCase

import indy.anoncreds

from indy.error import IndyError, ErrorCode

from ...holder import IndyHolder
Expand Down
6 changes: 3 additions & 3 deletions aries_cloudagent/indy/sdk/tests/test_issuer.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import json
import pytest

from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from asynctest import mock as async_mock, TestCase as AsyncTestCase

from indy.error import (
AnoncredsRevocationRegistryFullError,
Expand All @@ -15,9 +14,10 @@
from ....indy.sdk.profile import IndySdkProfile
from ....indy.sdk.wallet_setup import IndyWalletConfig
from ....wallet.indy import IndySdkWallet
from ...issuer import IndyIssuerRevocationRegistryFullError
from ....ledger.indy import IndySdkLedgerPool

from ...issuer import IndyIssuerRevocationRegistryFullError

from .. import issuer as test_module


Expand Down
5 changes: 3 additions & 2 deletions aries_cloudagent/indy/sdk/tests/test_util.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import pytest

from os import makedirs
from os.path import join
from pathlib import Path
from shutil import rmtree

from asynctest import TestCase as AsyncTestCase, mock as async_mock

import indy.blob_storage

from asynctest import mock as async_mock, TestCase as AsyncTestCase

from ...util import indy_client_dir, generate_pr_nonce, tails_path

from ..util import create_tails_reader, create_tails_writer
Expand Down
4 changes: 1 addition & 3 deletions aries_cloudagent/indy/sdk/tests/test_verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
from copy import deepcopy
from time import time

from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock

from asynctest import mock as async_mock, TestCase as AsyncTestCase
from indy.error import IndyError

from .. import verifier as test_module
Expand Down
3 changes: 2 additions & 1 deletion aries_cloudagent/indy/sdk/tests/test_wallet_plugin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pytest

from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
import pytest

from ....ledger.base import BaseLedger
from ....wallet.base import BaseWallet, DIDInfo
Expand Down
2 changes: 1 addition & 1 deletion aries_cloudagent/ledger/tests/test_indy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from os import path

from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock, TestCase as AsyncTestCase
from asynctest import mock as async_mock

from ...cache.in_memory import InMemoryCache
Expand Down
3 changes: 1 addition & 2 deletions aries_cloudagent/ledger/tests/test_routes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from asynctest import mock as async_mock, TestCase as AsyncTestCase

from ...admin.request_context import AdminRequestContext
from ...ledger.base import BaseLedger
Expand Down
Loading

0 comments on commit 46c2265

Please sign in to comment.