diff --git a/core/common/mixins.py b/core/common/mixins.py index 041bb3bb7..6c9b85f0c 100644 --- a/core/common/mixins.py +++ b/core/common/mixins.py @@ -46,6 +46,7 @@ INCLUDE_PARENT_CONCEPTS, INCLUDE_CHILD_CONCEPTS, INCLUDE_PARENT_CONCEPT_URLS, INCLUDE_CHILD_CONCEPT_URLS, INCLUDE_HIERARCHY_PATH, INCLUDE_SUMMARY) MAX_UNPAGINATED_RESULTS = 1000 # `Compress` lists; above this, users.list_unpaginated (ocl_online#230) +FACETS_CACHE_SUFFIX = '#for-anyone' # a facetsOnly answer's cache key ends with it class CustomPaginator: @@ -185,6 +186,9 @@ def __get_cached_data_if_any(self, request): if query_string: key_body += '?' + query_string key_headers += '?' + query_string + if self.only_facets(): # get_facets(for_requester=False)'s, not the answers cached before as one requester's + key_body += FACETS_CACHE_SUFFIX + key_headers += FACETS_CACHE_SUFFIX return key_body, cache.get(key_body) or None, key_headers, cache.get(key_headers) or None @@ -235,6 +239,8 @@ def _list(self, request): # pylint:disable=too-many-locals,too-many-branches,to cache_key_body, data, cache_key_headers, headers = self.__get_cached_data_if_any(request) if self.request.query_params.get('_force_cache_clear') in TRUTHY: data = None + if data and self.only_facets(): # cached as anyone sees them, so as this requester sees them + return Response({'facets': {'fields': self.get_requester_facets(data['facets']['fields'])}}) if not data: search_string = query_params.get('type', None) @@ -245,12 +251,12 @@ def _list(self, request): # pylint:disable=too-many-locals,too-many-branches,to return self.get_csv(request) if self.only_facets(): - data = {'facets': {'fields': self.get_facets()}} + data = {'facets': {'fields': self.get_facets(for_requester=False)}} # the same for everyone if cache_key_body is not None: timeout = 60 * 60 * 24 # 1 day cache.set(cache_key_body, data, timeout=timeout) cache.set(cache_key_headers, headers, timeout=timeout) - return Response(data) + return Response({'facets': {'fields': self.get_requester_facets(data['facets']['fields'])}}) if self.only_search_stats() and search_term: return Response( self.get_search_stats( diff --git a/core/common/search.py b/core/common/search.py index dc494e5c1..3abdf5ecb 100644 --- a/core/common/search.py +++ b/core/common/search.py @@ -39,8 +39,11 @@ def get_visible_repo_criteria(user): class CustomESFacetedSearch(FacetedSearch): - def __init__(self, query=None, filters=None, sort=(), _search=None): # pylint: disable=dangerous-default-value + def __init__(self, query=None, filters=None, sort=(), _search=None, extra_facets=None): # pylint: disable=dangerous-default-value + """extra_facets: facets to compute alongside the class's, by name.""" self._search = _search + if extra_facets: + self.facets = {**self.facets, **extra_facets} super().__init__(query=query, filters=filters or {}, sort=sort) @staticmethod diff --git a/core/common/views.py b/core/common/views.py index 214a10991..9a5ed6ac0 100644 --- a/core/common/views.py +++ b/core/common/views.py @@ -13,7 +13,7 @@ from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from elasticsearch import RequestError, TransportError -from elasticsearch_dsl import Q +from elasticsearch_dsl import Q, TermsFacet from pydash import get, compact from rest_framework import response, generics, status from rest_framework.generics import ListAPIView, RetrieveUpdateDestroyAPIView @@ -27,7 +27,7 @@ LIMIT_PARAM, NOT_FOUND, MUST_SPECIFY_EXTRA_PARAM_IN_BODY, INCLUDE_RETIRED_PARAM, VERBOSE_PARAM, HEAD, LATEST, \ BRIEF_PARAM, ES_REQUEST_TIMEOUT, INCLUDE_INACTIVE, FHIR_LIMIT_PARAM, RAW_PARAM, SEARCH_MAP_CODES_PARAM, \ INCLUDE_SEARCH_META_PARAM, EXCLUDE_FUZZY_SEARCH_PARAM, EXCLUDE_WILDCARD_SEARCH_PARAM, UPDATED_BY_USERNAME_PARAM, \ - CANONICAL_URL_REQUEST_PARAM, CHECKSUMS_PARAM, ACCESS_TYPE_NONE, HTTP_COMPRESS_HEADER + CANONICAL_URL_REQUEST_PARAM, CHECKSUMS_PARAM, ACCESS_TYPE_NONE, HTTP_COMPRESS_HEADER, FACET_SIZE from core.common.exceptions import Http400 from core.common.mixins import PathWalkerMixin from core.common.permissions import CanViewConceptDictionary @@ -68,6 +68,10 @@ class BaseAPIView(generics.GenericAPIView, PathWalkerMixin): collection_facets = ('collection', 'collection_url', 'collection_owner_url') max_viewable_collection_urls = 1000 _viewable_collection_urls = None # get_viewable_collection_urls's, read once per request and facet value + max_collection_facet_names = 3 * FACET_SIZE # keep_collection_facets_viewable's + # the facets that name collection versions or expansions, with the index field holding the URLs they come from + collection_url_facets = {'collection': 'collection_url', 'collection_version': 'collection_url', + 'expansion': 'expansion_url'} def get_throttles(self): return ThrottleUtil.get_throttles_by_user_plan(self.request.user) @@ -714,9 +718,14 @@ def exclude_hidden_latest_releases(self, results, latest_attr): criterion = criteria if criterion is None else criterion | criteria return results if criterion is None else results.exclude(criterion) - def get_facets(self): # pylint: disable=too-many-branches + def get_facets(self, for_requester=True): # pylint: disable=too-many-branches + """ + The search's facets. Without for_requester, before get_requester_facets: the same for everyone who can run + the search, so they can be cached. + """ facets = {} parent_repo = None + params = {} if self.facet_class: if self.is_user_document(): @@ -724,13 +733,15 @@ def get_facets(self): # pylint: disable=too-many-branches params = { 'query': self.get_search_string(lower=False), - '_search': self.__get_search_results( - ignore_retired_filter=True, sort=False, highlight=False, force=True) + '_search': self.get_facets_search() } if 'source' in self.kwargs and self.is_concept_document(): parent_repo = params['parent'] = get(self, 'parent_resource') if self.map_codes_release: params['release'] = self.map_codes_release + if self.is_source_child_document_model(): # see keep_collection_facets_viewable + params['extra_facets'] = { + '_collection_names': TermsFacet(field='collection', size=self.max_collection_facet_names)} faceted_search = self.facet_class(**params) # pylint: disable=not-callable faceted_search.params(request_timeout=ES_REQUEST_TIMEOUT) @@ -739,8 +750,6 @@ def get_facets(self): # pylint: disable=too-many-branches facets = s.facets.to_dict() except TransportError as ex: # pragma: no cover raise Http400(detail=get(ex, 'info') or get(ex, 'error') or str(ex)) from ex - if not get(self.request.user, 'is_authenticated'): - facets.pop('updatedBy', None) if self.should_search_latest_repo() and self.is_source_child_document_model() and 'source_version' in facets: facets['source_version'] = [facet for facet in facets['source_version'] if facet[0] != 'HEAD'] is_global_scope = ('org' not in self.kwargs and 'user' not in self.kwargs and not self.user_is_self) @@ -769,10 +778,76 @@ def get_facets(self): # pylint: disable=too-many-branches facets.pop('is_latest_version', None) if parent_repo and self.is_concept_document(): - return parent_repo.get_ordered_concept_facets_by_filter_order(facets) + facets = parent_repo.get_ordered_concept_facets_by_filter_order(facets) + + return self.get_requester_facets(facets, get(params, '_search')) if for_requester else facets + + def get_facets_search(self): + return self.__get_search_results(ignore_retired_filter=True, sort=False, highlight=False, force=True) + def get_requester_facets(self, facets, search=None): + """get_facets(for_requester=False)'s facets as this requester sees them; `search`: get_facets_search's.""" + if not get(self.request.user, 'is_authenticated'): + facets.pop('updatedBy', None) + self.keep_collection_facets_viewable(facets, search) return facets + def keep_collection_facets_viewable(self, facets, search=None): + """ + The collection, collection_version and expansion facets name the collection versions and expansions a match + is in as the index lists them: those the requester can't view, and those since deleted, too. Here each name + counts only the matches in the ones they can view, as the collection filter matches them + (get_collection_facet_criterion), in one more request; a name with none is left out. Staff see them as they + are. The collections counted are those _collection_names lists: the top max_collection_facet_names among the + matches. One past them isn't counted, so its names can be missing, never wrong. + """ + from core.collections.models import Collection + collections = [name for name, _, _ in facets.pop('_collection_names', [])] + present = {facet: {name for name, _, _ in facets[facet]} for facet in self.collection_url_facets + if facets.get(facet)} + viewable = Collection.get_viewable_versions_criteria(self.request.user) + if not present or viewable is None: + return + urls = self.get_viewable_collection_facet_urls(present, collections, viewable) + counts = {} + if urls: + search = (search or self.get_facets_search()).extra(size=0).params(request_timeout=ES_REQUEST_TIMEOUT) + search.aggs.bucket('viewable', 'filters', filters={ + str(i): Q('terms', **{self.collection_url_facets[facet]: sorted(values)}) + for i, ((facet, _), values) in enumerate(urls.items())}) + try: + buckets = search.execute().aggregations.viewable.buckets + except TransportError as ex: # pragma: no cover + raise Http400(detail=get(ex, 'info') or get(ex, 'error') or str(ex)) from ex + counts = {key: buckets[str(i)].doc_count for i, key in enumerate(urls)} + for facet in present: + facets[facet] = sorted( + [(name, count, False) for (_facet, name), count in counts.items() if _facet == facet and count], + key=lambda bucket: (-bucket[1], bucket[0]))[:FACET_SIZE] + + @staticmethod + def get_viewable_collection_facet_urls(facets, collections, viewable): + """ + {(facet, name): urls} for these collection facets ({facet: the names it lists}), from these collections' + versions the requester can view (`viewable`): their URLs by collection and version name, as the collection + filter matches them, and their expansions' URLs by expansion name. A version or expansion name counts only if + its facet lists it, so the request stays the facets' size. Names read as the documents read them from their + expansions' URIs (to_parent_kwargs_from_uri). + """ + from core.collections.models import Collection, Expansion + versions = Collection.objects.filter(viewable, mnemonic__in=collections) + urls = {} + for uri in versions.values_list('uri', flat=True): + parts = uri.strip('/').split('/') + for facet, name in [('collection', parts[3]), ('collection_version', parts[4] if len(parts) > 4 else HEAD)]: + if facet in facets and (facet == 'collection' or name in facets[facet]): + urls.setdefault((facet, name), set()).add(uri) + if 'expansion' in facets: + for uri, name in Expansion.objects.filter( + collection_version__in=versions, mnemonic__in=facets['expansion']).values_list('uri', 'mnemonic'): + urls.setdefault(('expansion', name), set()).add(uri) + return urls + def get_extras_searchable_fields_from_query_params(self): query_params = self.request.query_params.dict() result = {} diff --git a/core/integration_tests/tests_access_control.py b/core/integration_tests/tests_access_control.py index a089b6110..e0c81a48a 100644 --- a/core/integration_tests/tests_access_control.py +++ b/core/integration_tests/tests_access_control.py @@ -11,7 +11,7 @@ from django.test import tag, override_settings from core.client_configs.models import ClientConfig from core.collections.documents import CollectionDocument -from core.collections.models import Collection, CollectionReference +from core.collections.models import Collection, CollectionReference, Expansion from core.collections.tests.factories import OrganizationCollectionFactory, UserCollectionFactory, ExpansionFactory from core.common.constants import ACCESS_TYPE_NONE, ACCESS_TYPE_VIEW, RETIRED_ACCESS_TYPE_EDIT, ROLE_ADMIN from core.common.permissions import HasOwnership @@ -2108,7 +2108,8 @@ def setUp(self): super().setUp() self.patch_concept_es_mapping_for_ci() self.tag = f'qc{uuid.uuid4().hex[:6]}' - self.source = OrganizationSourceFactory(organization=self.org, public_access=ACCESS_TYPE_VIEW) + self.source = OrganizationSourceFactory( + organization=self.org, mnemonic=f'src{self.tag}', public_access=ACCESS_TYPE_VIEW) nowhere = ConceptFactory(parent=self.source, mnemonic=f'nowhere{self.tag}') self.concepts, self.mappings = {}, {} for key in ['inP', 'inQhead', 'inQv1', 'inRv1']: @@ -2271,6 +2272,117 @@ def test_collection_facets_on_a_cached_source_version_list_answer_each_requester self.assertEqual(self.listed(url, self.member, 'concepts'), ['inP'], url) self.assertEqual(self.listed(url, self.outsider, 'concepts'), [], url) self.assertEqual(self.listed(url, None, 'concepts'), [], url) + # a cached facetsOnly answer is each requester's own + url = f'{release.uri}concepts/' + self.assertIn(f'{self.tag}P', self.collection_facet(url, self.member)) + self.assertIn(f'{self.tag}P', self.collection_facet(url, self.staff)) + self.assertNotIn(f'{self.tag}P', self.collection_facet(url, self.outsider)) + self.assertNotIn(f'{self.tag}P', self.collection_facet(url, None)) + self.assertIn(f'{self.tag}P', self.collection_facet(url, self.member)) + # nor does it outlast the requester's access + self.member.organizations.remove(self.org) + self.assertNotIn(f'{self.tag}P', self.collection_facet(url, self.member)) + + def facets(self, url, user): + """The facets `url` answers (facetsOnly), each a {name: count}.""" + response = self.request('get', f'{url}{"&" if "?" in url else "?"}facetsOnly=true', user) + self.assertEqual(response.status_code, 200, (url, user)) + return {facet: {bucket[0]: bucket[1] for bucket in buckets} + for facet, buckets in response.data['facets']['fields'].items()} + + def collection_facet(self, url, user): + """The collection facet `url` answers, this test's collections only.""" + return {name: count for name, count in self.facets(url, user).get('collection', {}).items() + if name.startswith(self.tag)} + + def add_latest_versions_to_heads(self): + """P's and Q's HEADs hold their concepts' and mappings' latest versions too, which facets read.""" + for head, key in [(self.p_head, 'inP'), (self.q_head, 'inQhead')]: + head.expansion.concepts.add(self.concepts[key].get_latest_version()) + head.expansion.mappings.add(self.mappings[key].get_latest_version()) + ConceptDocument().update(Concept.objects.filter(parent=self.source), refresh=True) + MappingDocument().update(Mapping.objects.filter(parent=self.source), refresh=True) + + def assert_collection_facets( # pylint: disable=too-many-arguments + self, outsiders, members, resources=('concepts', 'mappings'), staff=None, lists=True): + """ + Signed out and an outsider see the collection facet of this test's source `outsiders`; a member `members`, and + staff `staff` (by default `members`). With `lists`, each name counts what its collection filter lists for them + (a list filtered by collection reads every version; facets, like the unfiltered list, the latest). + """ + for resource in resources: + url = f'/{resource}/?source={self.source.mnemonic}' + for user, expected in [(None, outsiders), (self.outsider, outsiders), (self.member, members), + (self.staff, staff or members)]: + facet = self.collection_facet(url, user) + self.assertEqual(facet, {f'{self.tag}{name}': count for name, count in expected.items()}, (url, user)) + for name, count in facet.items() if lists else []: + rows = self.listed(f'{url}&collection={name}', user, resource) + self.assertEqual(len(rows), count, (name, user, resource, rows)) + + def test_the_collection_facet_names_only_versions_the_requester_can_view(self): + # facets read latest versions: Q's v1 alone holds one, which only members can view + self.assert_collection_facets({'R': 1}, {'P': 1, 'Q': 1, 'R': 1}, lists=False) + self.add_latest_versions_to_heads() + self.assert_collection_facets({'Q': 1, 'R': 1}, {'P': 1, 'Q': 2, 'R': 1}) + # a private collection of the same name under another owner counts only for those who can view it + other = OrganizationFactory() + other_q = OrganizationCollectionFactory( + organization=other, mnemonic=self.q_head.mnemonic, public_access=ACCESS_TYPE_NONE) + ExpansionFactory(collection_version=other_q).concepts.add( + *[concept.get_latest_version() for concept in self.concepts.values()]) + ConceptDocument().update(Concept.objects.filter(parent=self.source), refresh=True) + self.assert_collection_facets( + {'Q': 1, 'R': 1}, {'P': 1, 'Q': 2, 'R': 1}, ['concepts'], staff={'P': 1, 'Q': 4, 'R': 1}) + + def test_the_collection_facet_leaves_out_deleted_versions(self): + """The index keeps a deleted version's members until they're indexed again; staff see the index as it is.""" + self.add_latest_versions_to_heads() + Collection.objects.filter(id__in=[self.p_v1.id, self.p_head.id]).delete() + for resource in ['concepts', 'mappings']: + url = f'/{resource}/?source={self.source.mnemonic}' + self.assertEqual(self.collection_facet(url, self.member), {f'{self.tag}Q': 2, f'{self.tag}R': 1}) + self.assertEqual(self.collection_facet(url, self.staff), + {f'{self.tag}P': 1, f'{self.tag}Q': 2, f'{self.tag}R': 1}) + # an expansion deleted alone leaves its version's indexed members counted, as the collection filter finds them + Expansion.objects.filter(collection_version=self.r_v1).delete() + url = f'/concepts/?source={self.source.mnemonic}' + self.assertEqual(self.collection_facet(url, None), {f'{self.tag}Q': 1, f'{self.tag}R': 1}) + self.assertEqual(self.listed(f'{url}&collection={self.tag}R', None, 'concepts'), ['inRv1']) + + def test_collection_version_and_expansion_facets_name_only_versions_the_requester_can_view(self): + hidden = OrganizationCollectionFactory( + organization=self.org, mnemonic=f'{self.tag}S', version=f'hidden{self.tag}', released=True, + public_access=ACCESS_TYPE_NONE) + ExpansionFactory(collection_version=hidden, mnemonic=f'hidden{self.tag}').concepts.add( + *[concept.get_latest_version() for concept in self.concepts.values()]) + self.add_latest_versions_to_heads() + spaced = OrganizationCollectionFactory( + organization=self.org, mnemonic=self.r_head.mnemonic, version='v 2', released=True, + public_access=ACCESS_TYPE_VIEW) + ExpansionFactory(collection_version=spaced).concepts.add(self.concepts['inRv1'].get_latest_version()) + ConceptDocument().update(Concept.objects.filter(parent=self.source), refresh=True) + url = f'{self.source.uri}concepts/' + # a version's name reads as its members' documents have it, for everyone + spaced_keys = {key for key in self.facets(url, self.staff)['collection_version'] if key.startswith('v')} + self.assertEqual(len(spaced_keys), 2, spaced_keys) + for user in [None, self.outsider, self.member]: + self.assertLessEqual(spaced_keys, set(self.facets(url, user)['collection_version']), user) + for user in [None, self.outsider]: + facets = self.facets(url, user) + self.assertEqual(self.collection_facet(url, user), {f'{self.tag}Q': 1, f'{self.tag}R': 1}, user) + self.assertNotIn(f'hidden{self.tag}', facets['collection_version'], user) + self.assertNotIn(f'hidden{self.tag}', facets['expansion'], user) + self.assertEqual(facets['collection_version']['v1'], 1, user) + for user in [self.member, self.staff]: + facets = self.facets(url, user) + self.assertEqual(facets['collection_version'][f'hidden{self.tag}'], 4, user) + self.assertEqual(facets['expansion'][f'hidden{self.tag}'], 4, user) + self.assertEqual(self.facets(url, self.member)['collection_version']['v1'], 3) + # neither facet is a query-string filter: naming one of their buckets lists the scope as it is + everything = self.listed(url, self.outsider, 'concepts') + for query in ['collectionVersion=v1', f'collectionVersion=hidden{self.tag}', f'expansion=hidden{self.tag}']: + self.assertEqual(self.listed(f'{url}?{query}', self.outsider, 'concepts'), everything, query) def test_a_prefix_matching_too_many_versions_answers_400(self): url = f'/concepts/?collection={self.tag}*' diff --git a/core/integration_tests/tests_concepts.py b/core/integration_tests/tests_concepts.py index db60bc05b..e15232dda 100644 --- a/core/integration_tests/tests_concepts.py +++ b/core/integration_tests/tests_concepts.py @@ -26,6 +26,7 @@ from core.sources.models import CloneLimitExceeded from core.collections.tests.factories import OrganizationCollectionFactory, ExpansionFactory from core.common.constants import ACCESS_TYPE_NONE, OPENMRS_VALIDATION_SCHEMA +from core.common.mixins import FACETS_CACHE_SUFFIX from core.common.tests import OCLAPITestCase, PREVIEW_GROUP_NAME from core.concepts.constants import CONCEPT_HARD_DELETE_REQUIRES_HEAD_ONLY from core.concepts.documents import ConceptDocument @@ -3432,13 +3433,15 @@ def test_repo_version_concepts_with_hierarchy_includes_are_not_cached(self): def test_repo_version_concepts_facets_are_cached(self): body_key, _ = self.source_v1.get_concepts_cache_keys() - facets_key = body_key + '?facetsOnly=true' + facets_key = body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX response = self.client.get(f'/orgs/{self.org}/sources/MySource/v1/concepts/?facetsOnly=true') self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertEqual(cache.get(facets_key), response.data) + # cached as anyone sees them; answered as this requester (signed out: no updatedBy) sees them + cached = cache.get(facets_key)['facets']['fields'] + self.assertLessEqual(response.data['facets']['fields'].items(), cached.items()) self.assertIsNone(cache.get(body_key)) # facets do not collide with the plain listing def test_repo_version_concepts_facets_are_served_from_cache(self): @@ -3447,12 +3450,22 @@ def test_repo_version_concepts_facets_are_served_from_cache(self): self.assertEqual(self.client.get(url).status_code, 200) - cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) + cache.set(body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX, {'facets': {'fields': {'fromCache': []}}}) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, {'facets': {'fields': {'fromCache': []}}}) + def test_repo_version_concepts_facets_ignore_answers_cached_before(self): + """An answer cached for one requester before facets were cached for anyone isn't read for another.""" + body_key, _ = self.source_v1.get_concepts_cache_keys() + cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) + + response = self.client.get(f'/orgs/{self.org}/sources/MySource/v1/concepts/?facetsOnly=true') + + self.assertEqual(response.status_code, 200) + self.assertNotIn('fromCache', response.data['facets']['fields']) + def test_head_version_concepts_facets_are_not_cached(self): body_key, _ = self.source.get_concepts_cache_keys() @@ -3460,7 +3473,7 @@ def test_head_version_concepts_facets_are_not_cached(self): self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertIsNone(cache.get(body_key + '?facetsOnly=true')) + self.assertIsNone(cache.get(body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX)) def test_repo_version_concepts_with_search_are_not_cached(self): body_key, headers_key = self.source_v1.get_concepts_cache_keys() diff --git a/core/integration_tests/tests_mappings.py b/core/integration_tests/tests_mappings.py index 69a395bc7..da4975158 100644 --- a/core/integration_tests/tests_mappings.py +++ b/core/integration_tests/tests_mappings.py @@ -4,6 +4,7 @@ from rest_framework.exceptions import ErrorDetail from core.collections.tests.factories import OrganizationCollectionFactory, ExpansionFactory +from core.common.mixins import FACETS_CACHE_SUFFIX from core.common.tests import OCLAPITestCase from core.concepts.tests.factories import ConceptFactory, ConceptNameFactory from core.integration_tests.test_utils import SourceChildListQueryCountMixin @@ -1090,13 +1091,15 @@ def test_repo_version_mappings_are_served_from_cache(self): def test_repo_version_mappings_facets_are_cached(self): body_key, _ = self.source_v1.get_mappings_cache_keys() - facets_key = body_key + '?facetsOnly=true' + facets_key = body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX response = self.client.get(f'/orgs/{self.org}/sources/MapCacheSource/v1/mappings/?facetsOnly=true') self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertEqual(cache.get(facets_key), response.data) + # cached as anyone sees them; answered as this requester (signed out: no updatedBy) sees them + cached = cache.get(facets_key)['facets']['fields'] + self.assertLessEqual(response.data['facets']['fields'].items(), cached.items()) self.assertIsNone(cache.get(body_key)) # facets do not collide with the plain listing def test_repo_version_mappings_facets_are_served_from_cache(self): @@ -1105,7 +1108,7 @@ def test_repo_version_mappings_facets_are_served_from_cache(self): self.assertEqual(self.client.get(url).status_code, 200) - cache.set(body_key + '?facetsOnly=true', {'facets': {'fields': {'fromCache': []}}}) + cache.set(body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX, {'facets': {'fields': {'fromCache': []}}}) response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -1118,7 +1121,7 @@ def test_head_version_mappings_facets_are_not_cached(self): self.assertEqual(response.status_code, 200) self.assertIn('facets', response.data) - self.assertIsNone(cache.get(body_key + '?facetsOnly=true')) + self.assertIsNone(cache.get(body_key + '?facetsOnly=true' + FACETS_CACHE_SUFFIX)) def test_repo_version_mappings_with_search_are_not_cached(self): body_key, headers_key = self.source_v1.get_mappings_cache_keys()