diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py index b5c68ea0a5..56b1b05412 100644 --- a/zerver/lib/test_classes.py +++ b/zerver/lib/test_classes.py @@ -1,7 +1,8 @@ from contextlib import contextmanager from email.utils import parseaddr 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) from django.apps import apps @@ -820,6 +821,36 @@ class ZulipTestCase(TestCase): r for r in data 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: """ Takes care of the mock_ldap setup, loads diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py index 6c793c769c..f591b6d21a 100644 --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -1383,16 +1383,20 @@ class GetProfileTest(ZulipTestCase): self.assert_json_error(result, "Invalid message ID") def test_get_all_profiles_avatar_urls(self) -> None: - user_profile = self.example_user('hamlet') - result = self.api_get(self.example_user("hamlet"), "/api/v1/users") + hamlet = self.example_user('hamlet') + result = self.api_get(hamlet, "/api/v1/users") self.assert_json_success(result) - for user in result.json()['members']: - if user['email'] == self.example_email("hamlet"): - self.assertEqual( - user['avatar_url'], - avatar_url(user_profile), - ) + my_user = self.findOne( + result.json()['members'], + lambda user: user['email'] == hamlet.email, + 'member for Hamlet' + ) + + self.assertEqual( + my_user['avatar_url'], + avatar_url(hamlet), + ) class FakeEmailDomainTest(ZulipTestCase): @override_settings(FAKE_EMAIL_DOMAIN="invaliddomain")