Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions arches_search/utils/search/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,7 @@ def compile(self) -> SearchResult:
The matches in the graphs graph_slugs names, how many there are, and how
many of them each of those graphs holds.
"""
requested_slugs = set(self.search_payload.graph_slugs or [])
requested_graphs = [
graph for graph in self._named_graphs if graph.slug in requested_slugs
]
requested_graphs = self._requested_graphs()
if not requested_graphs:
return SearchResult(
results=self._base_resources().none(),
Expand All @@ -184,6 +181,17 @@ def compile(self) -> SearchResult:
),
)
Comment thread
aarongundel marked this conversation as resolved.
Resolved

def compile_results(self) -> QuerySet:
Comment thread
aarongundel marked this conversation as resolved.
Resolved
"""The matches only, without the counts compile() runs."""
requested_graphs = self._requested_graphs()
if not requested_graphs:
return self._base_resources().none()
return self._permitted_matches(requested_graphs)

def _requested_graphs(self) -> List[SearchableGraph]:
requested_slugs = set(self.search_payload.graph_slugs or [])
return [graph for graph in self._named_graphs if graph.slug in requested_slugs]

@cached_property
def _named_graphs(self) -> List[SearchableGraph]:
"""
Expand Down
8 changes: 4 additions & 4 deletions arches_search/views/api/search_mvt.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def post(self, request):
try:
search_payload = SearchPayload.from_body(body)
validate_search_payload(search_payload)
SearchCompiler(search_payload, request.user).compile()
SearchCompiler(search_payload, request.user).compile_results()
except ValidationError as error:
return JSONResponse({"error": str(error)}, status=400)

Expand All @@ -86,15 +86,15 @@ def get(self, request, context_id, zoom, x, y):
return HttpResponse(cached_tile, content_type="application/x-protobuf")

try:
search_result = SearchCompiler(
matches = SearchCompiler(
SearchPayload.from_body(body), request.user
).compile()
).compile_results()
except ValidationError:
# The context was checked as the user who created it. Another user
# may not be able to read a node it names, and gets nothing drawn.
return HttpResponse(b"", content_type="application/x-protobuf")

search_results_queryset = search_result.results.values("resourceinstanceid")
search_results_queryset = matches.values("resourceinstanceid")
mvt_tile = self._generate_tile(search_results_queryset, zoom, x, y)

mvt_cache.set(tile_key, mvt_tile, settings.TILE_CACHE_TIMEOUT)
Expand Down
118 changes: 118 additions & 0 deletions tests/integration/utils/search/test_search_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
from django.db import connection
from django.test import TestCase, override_settings
from django.test.utils import CaptureQueriesContext
from django.contrib.auth.models import Group
from django.urls import reverse

from arches.app.utils.permission_backend import assign_perm
from arches.app.models.models import (
GraphModel,
ResourceInstance,
Expand Down Expand Up @@ -209,6 +211,79 @@ def _search_models_payloads(self, search_models, operator, operands):
for graph in (self.graph_a, self.graph_b)
]

def _compile_results_ids(self, **kwargs):
slugs = kwargs.pop("graph_slugs", [self.graph_a.slug, self.graph_b.slug])
payload = SearchPayload(
graph_slugs=slugs,
term_search=kwargs.get("term_search"),
advanced_search_queries=kwargs.get("advanced_search_queries"),
)
compiler = SearchCompiler(payload, self.user)
return set(
compiler.compile_results().values_list("resourceinstanceid", flat=True)
), self._result_ids(SearchCompiler(payload, self.user).compile())

def test_compile_results_matches_compile_with_no_requested_graphs(self):
results_ids, compile_ids = self._compile_results_ids(graph_slugs=[])
self.assertEqual(results_ids, set())
self.assertEqual(results_ids, compile_ids)

def test_compile_results_matches_compile_for_a_term_search(self):
results_ids, compile_ids = self._compile_results_ids(
term_search={"terms": ["amber"], "max_hops": 0}
)
self.assertTrue(results_ids)
self.assertEqual(results_ids, compile_ids)

def test_compile_results_matches_compile_for_an_advanced_search(self):
results_ids, compile_ids = self._compile_results_ids(
advanced_search_queries=self._search_models_payloads(
["DateSearch", "DateRangeSearch"],
"BETWEEN",
[
{"type": "LITERAL", "value": "1890-01-01"},
{"type": "LITERAL", "value": "1910-01-01"},
],
)
)
self.assertEqual(results_ids, {self.amber_mineral.resourceinstanceid})
self.assertEqual(results_ids, compile_ids)

def test_compile_results_refuses_a_payload_naming_an_unsearched_graph(self):
payload = SearchPayload(
graph_slugs=[self.graph_a.slug],
term_search=None,
advanced_search_queries=[
{
"graph_slug": self.graph_a.slug + "-typo",
"scope": "RESOURCE",
"logic": "AND",
"clauses": [],
"groups": [],
"aggregations": [],
"relationship": None,
}
],
)
with self.assertRaises(ValidationError):
SearchCompiler(payload, self.user).compile_results()

def test_compile_results_issues_no_count_query(self):
payload = SearchPayload(
graph_slugs=[self.graph_a.slug, self.graph_b.slug],
term_search={"terms": ["amber"], "max_hops": 0},
advanced_search_queries=None,
)
with CaptureQueriesContext(connection) as queries:
list(
SearchCompiler(payload, self.user)
.compile_results()
.values("resourceinstanceid")
)
self.assertTrue(queries.captured_queries)
for query in queries.captured_queries:
self.assertNotIn("COUNT(", query["sql"].upper())

def test_text_match_direct_only_max_hops_zero(self):
result = self._search(term_search={"terms": ["amber"], "max_hops": 0})
self.assertEqual(
Expand Down Expand Up @@ -798,3 +873,46 @@ def test_pre_filter_narrows_addressed_and_unaddressed_graphs_alike(self):
self.assertEqual(ids & self.DOG_IDS, {DOG_B_ID})
with self.subTest("the unaddressed graph is narrowed to it"):
self.assertEqual(ids & self.PERSON_IDS, {PERSON_A_ID, PERSON_B_ID})


class CompileResultsPermissionTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.member = get_user_model().objects.create_user(
username="compile-results-member", password="password"
)
cls.group = Group.objects.create(name="compile_results_group")
cls.member.groups.add(cls.group)
cls.graph = GraphModel.objects.create(
graphid=uuid.uuid4(),
name="Permissioned",
slug="compile-results-permissioned",
isresource=True,
is_active=True,
)
cls.granted = ResourceInstance.objects.create(
resourceinstanceid=uuid.uuid4(), graph=cls.graph
)
cls.hidden = ResourceInstance.objects.create(
resourceinstanceid=uuid.uuid4(), graph=cls.graph
)
assign_perm("view_resourceinstance", cls.group, cls.granted)

def test_compile_results_applies_the_permission_filter(self):
payload = SearchPayload(
graph_slugs=[self.graph.slug],
term_search=None,
advanced_search_queries=None,
)
results_ids = set(
SearchCompiler(payload, self.member)
.compile_results()
.values_list("resourceinstanceid", flat=True)
)
compile_ids = set(
SearchCompiler(payload, self.member)
.compile()
.results.values_list("resourceinstanceid", flat=True)
)
self.assertEqual(results_ids, {self.granted.resourceinstanceid})
self.assertEqual(results_ids, compile_ids)
104 changes: 104 additions & 0 deletions tests/test_search_mvt_context_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import json
import uuid
from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.db.models import QuerySet
from django.test import TestCase, override_settings
from django.urls import reverse

from arches.app.models.models import GraphModel

from arches_search.utils.search import SearchCompiler
from arches_search.views.api.search_mvt import SearchMVTAPI

# python manage.py test tests.test_search_mvt_context_api --settings="tests.test_settings"

TILE_BYTES = b"fixed-tile"
SEARCHRESULTS_CACHES = {
"default": {"BACKEND": "django.core.cache.backends.dummy.DummyCache"},
"searchresults": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "mvt-context-test",
},
}


@override_settings(CACHES=SEARCHRESULTS_CACHES)
class SearchMVTSkipsCountTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = get_user_model().objects.create_superuser(
username="mvt-context-admin",
email="mvt-context@example.com",
password="password",
)
cls.graph = GraphModel.objects.create(
graphid=uuid.uuid4(),
name="MVT",
slug="mvt-context-graph",
isresource=True,
is_active=True,
)

def setUp(self):
self.client.force_login(self.user)
compile_patcher = patch.object(
SearchCompiler,
"compile",
side_effect=AssertionError("compile() should not be called"),
)
compile_patcher.start()
self.addCleanup(compile_patcher.stop)

def _post_context(self, body):
return self.client.post(
reverse("search_mvt_context"),
json.dumps(body),
content_type="application/json",
)

def test_a_valid_context_is_created_without_compile(self):
response = self._post_context({"graph_slugs": [self.graph.slug]})

self.assertEqual(response.status_code, 200)
self.assertIn("context_id", response.json())

def test_an_invalid_payload_is_still_a_400(self):
response = self._post_context(
{
"graph_slugs": [self.graph.slug],
"advanced_search_queries": [
{
"graph_slug": self.graph.slug + "-typo",
"scope": "RESOURCE",
"logic": "AND",
"clauses": [],
"groups": [],
"aggregations": [],
"relationship": None,
}
],
}
)

self.assertEqual(response.status_code, 400)

def test_a_tile_is_generated_from_the_matches_without_compile(self):
context_id = self._post_context({"graph_slugs": [self.graph.slug]}).json()[
"context_id"
]

with patch.object(
SearchMVTAPI, "_generate_tile", return_value=TILE_BYTES
) as generate_tile:
response = self.client.get(
reverse(
"search_mvt",
kwargs={"context_id": context_id, "zoom": 6, "x": 9, "y": 24},
)
)

self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, TILE_BYTES)
self.assertIsInstance(generate_tile.call_args.args[0], QuerySet)
Loading