53 lines
2.8 KiB
Python
53 lines
2.8 KiB
Python
import json
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
from search.api import Api, ApiError
|
|
|
|
|
|
class SearchApiTest(unittest.TestCase):
|
|
def make_api(self, root: Path) -> Api:
|
|
document = root / "documents/7"
|
|
edition = document / "editions/10"
|
|
edition.mkdir(parents=True)
|
|
(document / "document.json").write_text(json.dumps({
|
|
"source_code": "7", "available_languages": ["ru"],
|
|
"editions": [{"source_code": "10", "available_languages": ["ru"]},],
|
|
}), encoding="utf-8")
|
|
(edition / "edition.json").write_text(json.dumps({"source_code": "10", "available_languages": ["ru"]}), encoding="utf-8")
|
|
(edition / "ru").mkdir()
|
|
(edition / "ru/content.html").write_text("<p>Текст</p>", encoding="utf-8")
|
|
(edition / "ru/content.txt").write_text("Текст\n", encoding="utf-8")
|
|
return Api("http://opensearch:9200", "current", root)
|
|
|
|
def test_search_pagination_filters_and_highlight(self):
|
|
with tempfile.TemporaryDirectory() as temporary:
|
|
api = self.make_api(Path(temporary))
|
|
response = {"hits": {"hits": [{"_source": {"document_code": "7", "edition_code": "10", "document_name_ru": "Закон"}, "highlight": {"text_ru": ["<em>Закон</em>"]}}]}}
|
|
with patch("search.api.request_json", return_value=response) as request:
|
|
status, payload = api.handle("GET", "/search?q=%D0%B7%D0%B0%D0%BA%D0%BE%D0%BD&language=ru&page=2&page_size=5&status=%D0%94%D0%B5%D0%B9%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82")
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual(payload["results"][0]["snippet"], "<em>Закон</em>")
|
|
body = json.loads(request.call_args.args[2])
|
|
self.assertEqual((body["from"], body["size"]), (5, 6))
|
|
self.assertIn({"term": {"status_ru": "Действует"}}, body["query"]["bool"]["filter"])
|
|
|
|
def test_document_editions_openapi_and_validation(self):
|
|
with tempfile.TemporaryDirectory() as temporary:
|
|
api = self.make_api(Path(temporary))
|
|
self.assertEqual(api.handle("GET", "/openapi.json")[1]["info"]["version"], "v1")
|
|
self.assertEqual(api.handle("GET", "/documents/7")[1]["current_edition"]["source_code"], "10")
|
|
self.assertEqual(api.handle("GET", "/documents/7/editions/10?language=ru")[1]["content"]["ru"]["text"], "Текст\n")
|
|
with self.assertRaisesRegex(ApiError, "q is required"):
|
|
api.handle("GET", "/search")
|
|
with self.assertRaisesRegex(ApiError, "date_from must be an ISO date"):
|
|
api.handle("GET", "/search?q=x&date_from=tomorrow")
|
|
with self.assertRaisesRegex(ApiError, "document not found"):
|
|
api.handle("GET", "/documents/%2E%2E")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|