Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Commit

Permalink
Merge pull request #8861 from matrix-org/rav/remove_unused_mocks
Browse files Browse the repository at this point in the history
Remove some unnecessary mocking from the unit tests
  • Loading branch information
richvdh authored Dec 3, 2020
2 parents ed51728 + 269ba1b commit 66f75c5
Show file tree
Hide file tree
Showing 7 changed files with 7 additions and 143 deletions.
1 change: 1 addition & 0 deletions changelog.d/8861.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Remove some unnecessary stubbing from unit tests.
18 changes: 2 additions & 16 deletions tests/api/test_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from mock import Mock

import jsonschema

from twisted.internet import defer
Expand All @@ -28,7 +26,7 @@
from synapse.events import make_event_from_dict

from tests import unittest
from tests.utils import DeferredMockCallable, MockHttpResource, setup_test_homeserver
from tests.utils import setup_test_homeserver

user_localpart = "test_user"

Expand All @@ -42,21 +40,9 @@ def MockEvent(**kwargs):


class FilteringTestCase(unittest.TestCase):
@defer.inlineCallbacks
def setUp(self):
self.mock_federation_resource = MockHttpResource()

self.mock_http_client = Mock(spec=[])
self.mock_http_client.put_json = DeferredMockCallable()

hs = yield setup_test_homeserver(
self.addCleanup,
federation_http_client=self.mock_http_client,
keyring=Mock(),
)

hs = setup_test_homeserver(self.addCleanup)
self.filtering = hs.get_filtering()

self.datastore = hs.get_datastore()

def test_errors_on_invalid_filters(self):
Expand Down
2 changes: 0 additions & 2 deletions tests/handlers/test_directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ def register_query_handler(query_type, handler):
self.mock_registry.register_query_handler = register_query_handler

hs = self.setup_test_homeserver(
federation_http_client=None,
resource_for_federation=Mock(),
federation_client=self.mock_federation,
federation_registry=self.mock_registry,
)
Expand Down
2 changes: 0 additions & 2 deletions tests/handlers/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ def register_query_handler(query_type, handler):

hs = yield setup_test_homeserver(
self.addCleanup,
federation_http_client=None,
resource_for_federation=Mock(),
federation_client=self.mock_federation,
federation_server=Mock(),
federation_registry=self.mock_registry,
Expand Down
11 changes: 3 additions & 8 deletions tests/storage/test_redaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.


from mock import Mock

from canonicaljson import json

from twisted.internet import defer
Expand All @@ -30,12 +27,10 @@


class RedactionTestCase(unittest.HomeserverTestCase):
def make_homeserver(self, reactor, clock):
config = self.default_config()
def default_config(self):
config = super().default_config()
config["redaction_retention_period"] = "30d"
return self.setup_test_homeserver(
resource_for_federation=Mock(), federation_http_client=None, config=config
)
return config

def prepare(self, reactor, clock, hs):
self.store = hs.get_datastore()
Expand Down
8 changes: 0 additions & 8 deletions tests/storage/test_roommember.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from unittest.mock import Mock

from synapse.api.constants import Membership
from synapse.rest.admin import register_servlets_for_client_rest_resource
from synapse.rest.client.v1 import login, room
Expand All @@ -34,12 +32,6 @@ class RoomMemberStoreTestCase(unittest.HomeserverTestCase):
room.register_servlets,
]

def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
resource_for_federation=Mock(), federation_http_client=None
)
return hs

def prepare(self, reactor, clock, hs: TestHomeServer):

# We can't test the RoomMemberStore on its own without the other event
Expand Down
108 changes: 1 addition & 107 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,26 @@
import time
import uuid
import warnings
from inspect import getcallargs
from typing import Type
from urllib import parse as urlparse

from mock import Mock, patch

from twisted.internet import defer, reactor
from twisted.internet import defer

from synapse.api.constants import EventTypes
from synapse.api.errors import CodeMessageException, cs_error
from synapse.api.room_versions import RoomVersions
from synapse.config.database import DatabaseConnectionConfig
from synapse.config.homeserver import HomeServerConfig
from synapse.config.server import DEFAULT_ROOM_VERSION
from synapse.federation.transport import server as federation_server
from synapse.http.server import HttpServer
from synapse.logging.context import current_context, set_current_context
from synapse.server import HomeServer
from synapse.storage import DataStore
from synapse.storage.database import LoggingDatabaseConnection
from synapse.storage.engines import PostgresEngine, create_engine
from synapse.storage.prepare_database import prepare_database
from synapse.util.ratelimitutils import FederationRateLimiter

# set this to True to run the tests against postgres instead of sqlite.
#
Expand Down Expand Up @@ -342,32 +339,9 @@ async def validate_hash(p, h):

hs.get_auth_handler().validate_hash = validate_hash

fed = kwargs.get("resource_for_federation", None)
if fed:
register_federation_servlets(hs, fed)

return hs


def register_federation_servlets(hs, resource):
federation_server.register_servlets(
hs,
resource=resource,
authenticator=federation_server.Authenticator(hs),
ratelimiter=FederationRateLimiter(
hs.get_clock(), config=hs.config.rc_federation
),
)


def get_mock_call_args(pattern_func, mock_func):
""" Return the arguments the mock function was called with interpreted
by the pattern functions argument list.
"""
invoked_args, invoked_kargs = mock_func.call_args
return getcallargs(pattern_func, *invoked_args, **invoked_kargs)


def mock_getRawHeaders(headers=None):
headers = headers if headers is not None else {}

Expand Down Expand Up @@ -553,86 +527,6 @@ def time_bound_deferred(self, d, *args, **kwargs):
return d


def _format_call(args, kwargs):
return ", ".join(
["%r" % (a) for a in args] + ["%s=%r" % (k, v) for k, v in kwargs.items()]
)


class DeferredMockCallable:
"""A callable instance that stores a set of pending call expectations and
return values for them. It allows a unit test to assert that the given set
of function calls are eventually made, by awaiting on them to be called.
"""

def __init__(self):
self.expectations = []
self.calls = []

def __call__(self, *args, **kwargs):
self.calls.append((args, kwargs))

if not self.expectations:
raise ValueError(
"%r has no pending calls to handle call(%s)"
% (self, _format_call(args, kwargs))
)

for (call, result, d) in self.expectations:
if args == call[1] and kwargs == call[2]:
d.callback(None)
return result

failure = AssertionError(
"Was not expecting call(%s)" % (_format_call(args, kwargs))
)

for _, _, d in self.expectations:
try:
d.errback(failure)
except Exception:
pass

raise failure

def expect_call_and_return(self, call, result):
self.expectations.append((call, result, defer.Deferred()))

@defer.inlineCallbacks
def await_calls(self, timeout=1000):
deferred = defer.DeferredList(
[d for _, _, d in self.expectations], fireOnOneErrback=True
)

timer = reactor.callLater(
timeout / 1000,
deferred.errback,
AssertionError(
"%d pending calls left: %s"
% (
len([e for e in self.expectations if not e[2].called]),
[e for e in self.expectations if not e[2].called],
)
),
)

yield deferred

timer.cancel()

self.calls = []

def assert_had_no_calls(self):
if self.calls:
calls = self.calls
self.calls = []

raise AssertionError(
"Expected not to received any calls, got:\n"
+ "\n".join(["call(%s)" % _format_call(c[0], c[1]) for c in calls])
)


async def create_room(hs, room_id: str, creator_id: str):
"""Creates and persist a creation event for the given room
"""
Expand Down

0 comments on commit 66f75c5

Please sign in to comment.