Skip to content

Commit

Permalink
Fix test coverage for the tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon Betts committed Jun 22, 2023
1 parent 975f547 commit ab30f3f
Show file tree
Hide file tree
Showing 18 changed files with 77 additions and 225 deletions.
3 changes: 2 additions & 1 deletion .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ omit =
[report]
show_missing = True
precision = 2
fail_under = 98.27
fail_under = 98.44

skip_covered = True
6 changes: 3 additions & 3 deletions tests/h/activity/bucketing_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ def __eq__(self, timeframe):
and self.document_buckets == timeframe.document_buckets
)

def __repr__(self):
# pragma: no cover
return f'{self.__class__} "{self.label}" with {len(self.document_buckets)} document buckets'
# pragma: nocover
def __repr__(self): # pragma: nocover
return f'{self.__class__} "{self.label}" with {len(self.document_buckets)} document buckets' # pragma: nocover


@pytest.mark.usefixtures("factories")
Expand Down
8 changes: 2 additions & 6 deletions tests/h/activity/query_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,12 +404,8 @@ def test_it_returns_each_annotations_group(self, _fetch_groups, pyramid_request)
for bucket in timeframe.document_buckets.values():
presented_annotations.extend(bucket.presented_annotations)

for group in _fetch_groups.return_value:
for presented_annotation in presented_annotations:
if presented_annotation["group"] == group:
break
else:
assert False
expected_groups = [anno["group"] for anno in presented_annotations]
assert _fetch_groups.return_value == expected_groups

def test_it_returns_each_annotations_incontext_link(self, links, pyramid_request):
def incontext_link(request, annotation):
Expand Down
9 changes: 7 additions & 2 deletions tests/h/app_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def test_it_configures_pyramid_sentry_plugin(self, pyramid_config):
def pyramid_config(self, pyramid_config):
# Mock out jinja2 related stuff
pyramid_config.get_jinja2_environment = mock.create_autospec(
# pragma: nocover
spec=lambda: JinjaEnvironment() # pylint: disable=unnecessary-lambda
)

Expand All @@ -34,9 +35,13 @@ def pyramid_config(self, pyramid_config):
auto_reload=True,
)

pyramid_config.add_jinja2_extension = mock.create_autospec(lambda name: True)
pyramid_config.add_jinja2_extension = mock.create_autospec(
lambda name: True
) # pragma: nocover

# Prevent us from really loading the includes
pyramid_config.include = mock.create_autospec(lambda name: True)
pyramid_config.include = mock.create_autospec(
lambda name: True
) # pragma: nocover

return pyramid_config
18 changes: 0 additions & 18 deletions tests/h/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,6 @@ def all(self):
return self.flags


class DummySession:
def __init__(self):
self.added = []
self.deleted = []
self.flushed = False

def add(self, obj):
self.added.append(obj)

def flush(self):
self.flushed = True


# A fake version of colander.Invalid
class FakeInvalid:
def __init__(self, errors):
Expand Down Expand Up @@ -145,11 +132,6 @@ def fake_feature():
return DummyFeature()


@pytest.fixture
def fake_db_session():
return DummySession()


@pytest.fixture
def form_validating_to():
def form_validating_to(appstruct):
Expand Down
4 changes: 0 additions & 4 deletions tests/h/eventqueue_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,6 @@ def test_response_callback_publishes_events(self, publish_all, pyramid_request):
queue.response_callback(pyramid_request, None)
assert publish_all.called

@pytest.fixture
def log(self, patch):
return patch("h.eventqueue.log")

@pytest.fixture
def publish_all(self, patch):
return patch("h.eventqueue.EventQueue.publish_all")
Expand Down
14 changes: 0 additions & 14 deletions tests/h/feeds/atom_test.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
"""Unit tests for h/atom.py."""
from datetime import datetime, timedelta
from unittest import mock

import pytest

from h import models
from h.feeds import atom


def _annotation(**kwargs):
args = {
"userid": "acct:[email protected]",
"created": datetime.utcnow(),
"updated": datetime.utcnow(),
"target_selectors": [],
"document": models.Document(),
}
args.update(kwargs)
return models.Annotation(**args)


def test_feed_id():
feed = atom.feed_from_annotations([], "atom_url", mock.Mock())

Expand Down
4 changes: 0 additions & 4 deletions tests/h/models/token_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,3 @@ def test_refresh_token_expired_is_true_if_in_past(self):
token = Token(refresh_token_expires=refresh_token_expires)

assert token.refresh_token_expired is True


def one_hour_from_now():
return datetime.datetime.now() + datetime.timedelta(hours=1)
8 changes: 0 additions & 8 deletions tests/h/schemas/api/group_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,6 @@ def test_validate_raises_ValidationError_groupid_authority_mismatch(
{"name": "Shambles", "groupid": "group:[email protected]"}
)

@pytest.fixture
def appstruct(self):
return {
"groupid": "group:[email protected]",
"name": "DingDong!",
"description": "OH, hello there",
}

@pytest.fixture
def schema(self):
schema = GroupAPISchema(
Expand Down
109 changes: 37 additions & 72 deletions tests/h/search/query_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# pylint: disable=too-many-lines
import datetime

import elasticsearch_dsl
Expand Down Expand Up @@ -924,91 +923,57 @@ def test_matches_replies_of_replies_to_an_annotation(self, Annotation, search):


class TestTagsAggregation:
def test_it_returns_annotation_counts_by_tag(self, Annotation, search):
@pytest.mark.parametrize(
"limit,expected",
(
[
2,
[
{"count": 2, "tag": "tag_a"},
{"count": 1, "tag": "tag_b"},
],
],
[1, [{"count": 2, "tag": "tag_a"}]],
),
)
def test_it_returns_annotation_counts_by_tag(
self, Annotation, search, limit, expected
):
for _ in range(2):
Annotation(tags=["tag_a"])
Annotation(tags=["tag_b"])

search.append_aggregation(query.TagsAggregation())
search.append_aggregation(query.TagsAggregation(limit=limit))
result = search.run(webob.multidict.MultiDict({}))

tag_results = result.aggregations["tags"]
count_for_tag_a = next(r for r in tag_results if r["tag"] == "tag_a")["count"]
count_for_tag_b = next(r for r in tag_results if r["tag"] == "tag_b")["count"]

assert len(tag_results) == 2
assert count_for_tag_a == 2
assert count_for_tag_b == 1

def test_it_limits_number_of_annotation_counts_by_tag_returned(
self, Annotation, search
):
bucket_limit = 2

Annotation(tags=["tag_a"])
for _ in range(3):
Annotation(tags=["tag_b"])
for _ in range(2):
Annotation(tags=["tag_c"])

search.append_aggregation(query.TagsAggregation(bucket_limit))
result = search.run(webob.multidict.MultiDict({}))

tag_results = result.aggregations["tags"]
count_for_tag_b = next(r for r in tag_results if r["tag"] == "tag_b")["count"]
count_for_tag_c = next(r for r in tag_results if r["tag"] == "tag_c")["count"]

assert len(tag_results) == bucket_limit
assert count_for_tag_b == 3
assert count_for_tag_c == 2
assert result.aggregations["tags"] == expected


class TestUsersAggregation:
def test_it_returns_annotation_counts_by_user(self, Annotation, search):
for _ in range(2):
Annotation(userid="acct:[email protected]")
Annotation(userid="acct:[email protected]")

search.append_aggregation(query.UsersAggregation())
result = search.run(webob.multidict.MultiDict({}))

users_results = result.aggregations["users"]
count_pa = next(r for r in users_results if r["user"] == "acct:[email protected]")[
"count"
]
count_pb = next(r for r in users_results if r["user"] == "acct:[email protected]")[
"count"
]

assert len(users_results) == 2
assert count_pa == 2
assert count_pb == 1

def test_it_limits_number_of_annotation_counts_by_user_returned(
self, Annotation, search
@pytest.mark.parametrize(
"limit,expected",
(
[
2,
[
{"count": 2, "user": "acct:[email protected]"},
{"count": 1, "user": "acct:[email protected]"},
],
],
[1, [{"count": 2, "user": "acct:[email protected]"}]],
),
)
def test_it_returns_annotation_counts_by_user(
self, Annotation, search, limit, expected
):
bucket_limit = 2

Annotation(userid="acct:[email protected]")
for _ in range(3):
Annotation(userid="acct:[email protected]")
Annotation(userid="acct:[email protected]")
for _ in range(2):
Annotation(userid="acct:pc@example.com")
Annotation(userid="acct:b@example.com")

search.append_aggregation(query.UsersAggregation(limit=bucket_limit))
search.append_aggregation(query.UsersAggregation(limit=limit))
result = search.run(webob.multidict.MultiDict({}))

users_results = result.aggregations["users"]
count_pb = next(r for r in users_results if r["user"] == "acct:[email protected]")[
"count"
]
count_pc = next(r for r in users_results if r["user"] == "acct:[email protected]")[
"count"
]

assert len(users_results) == bucket_limit
assert count_pb == 3
assert count_pc == 2
assert result.aggregations["users"] == expected


@pytest.fixture
Expand Down
5 changes: 0 additions & 5 deletions tests/h/services/group_list_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,11 +316,6 @@ def other_authority_user(factories, other_authority):
return factories.User(authority=other_authority)


@pytest.fixture
def origin():
return "http://foo.com"


@pytest.fixture
def document_uri():
return "http://foo.com/bar/fun.html"
Expand Down
22 changes: 1 addition & 21 deletions tests/h/services/group_members_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

import pytest

from h.models import GroupScope, User
from h.models import User
from h.services.group_members import GroupMembersService, group_members_factory
from tests.common.matchers import Matcher


class TestMemberJoin:
Expand Down Expand Up @@ -207,11 +206,6 @@ def fetch(userid):
return fetch


@pytest.fixture
def origins():
return ["http://example.com"]


@pytest.fixture
def publish():
return mock.Mock(spec_set=[])
Expand All @@ -225,17 +219,3 @@ def group_members_service(db_session, usr_group_members_service, publish):
@pytest.fixture
def creator(factories):
return factories.User(username="group_creator")


class GroupScopeWithOrigin(Matcher):
"""Matches any GroupScope with the given origin."""

def __init__(
self, origin
): # pylint:disable=super-init-not-called #:(Overwriting __eq__ instead)
self.origin = origin

def __eq__(self, group_scope):
if not isinstance(group_scope, GroupScope):
return False
return group_scope.origin == self.origin
Loading

0 comments on commit ab30f3f

Please sign in to comment.