Clean up `test_get_all_profiles_avatar_urls`.

This test was using the anti-pattern of doing an
assertion inside a conditional.

I added the `findOne` helper to make it easier
to write robust tests for scenarios like this.
This commit is contained in:
Steve Howell 2020-03-19 14:14:38 +00:00 committed by showell
parent b25e02aa14
commit 80acbb9fdf
2 changed files with 44 additions and 9 deletions

View File

@ -1,7 +1,8 @@
from contextlib import contextmanager from contextlib import contextmanager
from email.utils import parseaddr from email.utils import parseaddr
from fakeldap import MockLDAP from fakeldap import MockLDAP
from typing import (cast, Any, Dict, Iterable, Iterator, List, Optional, from typing import (cast, Any, Callable, Dict, Iterable,
Iterator, List, Optional,
Tuple, Union, Set) Tuple, Union, Set)
from django.apps import apps from django.apps import apps
@ -820,6 +821,36 @@ class ZulipTestCase(TestCase):
r for r in data r for r in data
if r['id'] == db_id][0] if r['id'] == db_id][0]
def findOne(self,
lst: List[Any],
predicate: Callable[[Any], bool],
member_name: str) -> Any:
matches = [
item for item in lst
if predicate(item)
]
if len(matches) == 1:
# Happy path!
return matches[0]
print('\nERROR: findOne fails on this list:\n')
for item in lst:
print(item)
if len(matches) == 0:
raise ValueError(
'No matches: {}'.format(member_name)
)
raise ValueError(
'Too many matches ({}): {}'.format(
len(matches),
member_name
)
)
def init_default_ldap_database(self) -> None: def init_default_ldap_database(self) -> None:
""" """
Takes care of the mock_ldap setup, loads Takes care of the mock_ldap setup, loads

View File

@ -1383,16 +1383,20 @@ class GetProfileTest(ZulipTestCase):
self.assert_json_error(result, "Invalid message ID") self.assert_json_error(result, "Invalid message ID")
def test_get_all_profiles_avatar_urls(self) -> None: def test_get_all_profiles_avatar_urls(self) -> None:
user_profile = self.example_user('hamlet') hamlet = self.example_user('hamlet')
result = self.api_get(self.example_user("hamlet"), "/api/v1/users") result = self.api_get(hamlet, "/api/v1/users")
self.assert_json_success(result) self.assert_json_success(result)
for user in result.json()['members']: my_user = self.findOne(
if user['email'] == self.example_email("hamlet"): result.json()['members'],
self.assertEqual( lambda user: user['email'] == hamlet.email,
user['avatar_url'], 'member for Hamlet'
avatar_url(user_profile), )
)
self.assertEqual(
my_user['avatar_url'],
avatar_url(hamlet),
)
class FakeEmailDomainTest(ZulipTestCase): class FakeEmailDomainTest(ZulipTestCase):
@override_settings(FAKE_EMAIL_DOMAIN="invaliddomain") @override_settings(FAKE_EMAIL_DOMAIN="invaliddomain")