2
0

SearchV3Test.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. <?php
  2. use App\Services\OpenSearchService;
  3. use GuzzleHttp\Exception\ConnectException;
  4. use GuzzleHttp\Psr7\Request as PsrRequest;
  5. use OpenSearch\Exception\BadRequestHttpException;
  6. use OpenSearch\Exception\NotFoundHttpException;
  7. /*
  8. * /v3/search 与 /v3/search/{id}(OpenSearch 全文检索)。
  9. *
  10. * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
  11. * OpenSearch 一律 mock,不连真实集群;整章文档的 channel 权限见 ChannelContentAccessV3Test。
  12. */
  13. /** 一条 OpenSearch 原始命中 */
  14. function rawSearchHit(array $source = [], array $highlight = []): array
  15. {
  16. return [
  17. '_id' => $source['id'] ?? 'tipitaka_paragraph_pi_26-392',
  18. '_score' => 12.5,
  19. '_source' => $source + [
  20. 'id' => 'tipitaka_paragraph_pi_26-392',
  21. 'resource_id' => '3bfe314f-da34-11ec-9f5a-076a934e828a',
  22. 'resource_type' => 'tipitaka',
  23. 'granularity' => 'paragraph',
  24. 'language' => 'pi',
  25. 'related_id' => '26-392',
  26. 'title' => ['text' => ['pali' => '95.']],
  27. 'content' => ['text' => ['pali' => 'Dukkhāti dukkha saṃkiṇṇo']],
  28. 'bold_single' => 'dukkha saṃkiṇṇo',
  29. 'path' => 'a/b/c',
  30. 'category' => ['añña', 'dīpanī'],
  31. 'updated_at' => '2026-11-16T07:39:25+00:00',
  32. ],
  33. 'highlight' => $highlight,
  34. ];
  35. }
  36. /** 让 OpenSearchService::search 返回给定命中,并把收到的参数记进 $captured */
  37. function fakeSearchResult(array $hits, int $total, ?array &$captured = null, array $aggregations = []): void
  38. {
  39. test()->mock(OpenSearchService::class)
  40. ->shouldReceive('search')
  41. ->andReturnUsing(function (array $params) use ($hits, $total, &$captured, $aggregations) {
  42. $captured = $params;
  43. return [
  44. 'hits' => ['total' => ['value' => $total, 'relation' => 'eq'], 'hits' => $hits],
  45. 'aggregations' => $aggregations,
  46. ];
  47. });
  48. }
  49. it('returns normalized hits with pagination meta', function () {
  50. fakeSearchResult([rawSearchHit([], [
  51. 'title.text.pali' => ['<mark>95</mark>.'],
  52. 'content.text.pali' => ['<mark>Dukkhāti</mark> dukkha'],
  53. ])], 45);
  54. $res = $this->getJson('/api/v3/search?q=dukkha&per_page=20&page=2')->assertSuccessful();
  55. $hit = $res->json('data.0');
  56. expect($hit)->toHaveKeys(['id', 'resource_type', 'resource_id', 'granularity', 'language', 'related_id',
  57. 'score', 'title', 'content', 'highlight', 'bold', 'path', 'category', 'tags', 'updated_at'])
  58. ->and($hit)->not->toHaveKeys(['_source', 'display'])
  59. ->and($hit['related_id'])->toBe('26-392')
  60. ->and($hit['highlight'])->toBe('<mark>Dukkhāti</mark> dukkha') // 正文片段优先于标题
  61. ->and($hit['bold'])->toBe(['dukkha', 'saṃkiṇṇo']);
  62. expect($res->json('meta'))->toMatchArray([
  63. 'current_page' => 2, 'per_page' => 20, 'total' => 45, 'total_relation' => 'eq', 'last_page' => 3,
  64. ])->not->toHaveKey('facets');
  65. });
  66. it('maps filters onto the search service and skips aggregations by default', function () {
  67. $captured = null;
  68. fakeSearchResult([], 0, $captured);
  69. $this->getJson('/api/v3/search?'.http_build_query([
  70. 'q' => 'dukkha', 'search_mode' => 'definition', 'resource_type' => 'tipitaka',
  71. 'granularity' => 'paragraph', 'category' => 'sutta, mūla', 'tags' => 'a,b',
  72. 'related_id' => ['93-5', '93-6'], 'page_refs' => ['V3.81'],
  73. 'channel' => '9d389085-197a-47b7-87bd-d214994c2784',
  74. ]))->assertSuccessful();
  75. expect($captured)->toMatchArray([
  76. 'query' => 'dukkha', 'searchMode' => 'definition', 'resourceType' => 'tipitaka',
  77. 'granularity' => 'paragraph', 'category' => ['sutta', 'mūla'], 'tags' => ['a', 'b'],
  78. 'relatedId' => ['93-5', '93-6'], 'pageRefs' => ['V3.81'],
  79. 'channel' => '9d389085-197a-47b7-87bd-d214994c2784', 'aggregations' => false,
  80. 'page' => 1, 'pageSize' => 20,
  81. ]);
  82. });
  83. it('returns facets only when asked', function () {
  84. $captured = null;
  85. fakeSearchResult([], 0, $captured, [
  86. 'language' => ['buckets' => [['key' => 'pi', 'doc_count' => 7]]],
  87. ]);
  88. $this->getJson('/api/v3/search?q=dukkha&facets=true')
  89. ->assertSuccessful()
  90. ->assertJsonPath('meta.facets.language.0', ['key' => 'pi', 'count' => 7]);
  91. expect($captured['aggregations'])->toBeTrue();
  92. });
  93. it('accepts the same parameters in a POST body', function () {
  94. $captured = null;
  95. fakeSearchResult([rawSearchHit()], 1, $captured);
  96. $this->postJson('/api/v3/search', ['q' => 'dukkha', 'facets' => true, 'related_id' => ['26-392']])
  97. ->assertSuccessful()
  98. ->assertJsonPath('data.0.related_id', '26-392');
  99. expect($captured['relatedId'])->toBe(['26-392'])
  100. ->and($captured['aggregations'])->toBeTrue();
  101. });
  102. it('rejects invalid parameters', function (array $query, string $field) {
  103. $this->getJson('/api/v3/search?'.http_build_query($query))
  104. ->assertUnprocessable()
  105. ->assertJsonValidationErrors($field)
  106. ->assertHeader('Content-Type', 'application/problem+json');
  107. })->with([
  108. 'missing q' => [[], 'q'],
  109. 'unknown mode' => [['q' => 'x', 'search_mode' => 'bogus'], 'search_mode'],
  110. 'unknown resource type' => [['q' => 'x', 'resource_type' => 'article'], 'resource_type'],
  111. 'per_page too large' => [['q' => 'x', 'per_page' => 101], 'per_page'],
  112. 'too deep' => [['q' => 'x', 'per_page' => 100, 'page' => 101], 'page'],
  113. 'channel not uuid' => [['q' => 'x', 'channel' => 'abc'], 'channel'],
  114. ]);
  115. it('answers 503 with a readable detail when the search cluster is unreachable', function () {
  116. test()->mock(OpenSearchService::class)
  117. ->shouldReceive('search')
  118. ->andThrow(new ConnectException('Connection refused', new PsrRequest('POST', 'http://opensearch')));
  119. $res = $this->getJson('/api/v3/search?q=dukkha', ['Accept-Language' => 'zh-Hans'])
  120. ->assertServiceUnavailable()
  121. ->assertJsonPath('type', 'urn:problem:search-unavailable');
  122. expect($res->json('detail'))->not->toBe('site.search_unavailable')
  123. ->and($res->getContent())->not->toContain('Connection refused');
  124. });
  125. it('does not leak OpenSearch errors that are real bugs', function () {
  126. test()->mock(OpenSearchService::class)
  127. ->shouldReceive('search')
  128. ->andThrow(new BadRequestHttpException('illegal_argument_exception: Text fields are not optimised'));
  129. config(['app.debug' => false]);
  130. $res = $this->getJson('/api/v3/search?q=dukkha')->assertInternalServerError();
  131. expect($res->getContent())->not->toContain('illegal_argument_exception');
  132. });
  133. it('shows one document with its display html', function () {
  134. test()->mock(OpenSearchService::class)
  135. ->shouldReceive('get')
  136. ->with('term_x')
  137. ->andReturn(rawSearchHit([
  138. 'id' => 'term_x', 'resource_type' => 'term', 'related_id' => null,
  139. 'bold_single' => ['苦', 'dukkha'],
  140. 'content' => ['text' => ['zh' => '苦'], 'display' => '<p>苦</p>'],
  141. ]));
  142. $this->getJson('/api/v3/search/term_x')
  143. ->assertSuccessful()
  144. ->assertJsonPath('data.id', 'term_x')
  145. ->assertJsonPath('data.display', '<p>苦</p>')
  146. ->assertJsonPath('data.bold', ['苦', 'dukkha'])
  147. ->assertJsonPath('data.related_id', null);
  148. });
  149. it('answers 404 only when the document does not exist', function () {
  150. test()->mock(OpenSearchService::class)
  151. ->shouldReceive('get')
  152. ->andThrow(new NotFoundHttpException('not found'));
  153. $this->getJson('/api/v3/search/term_missing')->assertNotFound();
  154. });
  155. it('answers 503 instead of 404 when the cluster is down while showing', function () {
  156. test()->mock(OpenSearchService::class)
  157. ->shouldReceive('get')
  158. ->andThrow(new ConnectException('Connection refused', new PsrRequest('GET', 'http://opensearch')));
  159. $this->getJson('/api/v3/search/term_x')->assertServiceUnavailable();
  160. });
  161. it('only registers GET and POST on the collection', function () {
  162. $this->putJson('/api/v3/search/term_x', [])->assertMethodNotAllowed();
  163. });