IndexTipitakaChapterTest.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. use App\Models\PaliText;
  3. use App\Services\OpenSearchService;
  4. use App\Services\PaliContentService;
  5. use Illuminate\Foundation\Testing\RefreshDatabase;
  6. use Illuminate\Support\Str;
  7. uses(RefreshDatabase::class);
  8. /*
  9. * opensearch:index-tipitaka --granularity=chapter:每个「章节 × channel」建一份文档。
  10. *
  11. * 回归:求一本书最后一章的结束段时曾用 `->first()->value('paragraph')`,模型实例上的 value()
  12. * 新开不带条件的查询、拿到全表第一行的段号,最后一章的范围为空,从不被索引。
  13. * OpenSearch 与取文都换成假的,只看建了哪些文档。
  14. */
  15. function itcParagraph(int $book, int $para, int $level, string $toc = ''): void
  16. {
  17. (new PaliText)->forceFill([
  18. 'book' => $book,
  19. 'paragraph' => $para,
  20. 'level' => $level,
  21. 'class' => '',
  22. 'toc' => $toc,
  23. 'text' => $toc,
  24. 'html' => '',
  25. 'pcd_book_id' => 0,
  26. 'chapter_len' => 1,
  27. 'chapter_strlen' => 10,
  28. 'uid' => (string) Str::uuid(),
  29. ])->save();
  30. }
  31. it('indexes every chapter of a book, including the last one', function () {
  32. // 先放一本段号更小的书:修复前 value() 拿到的「全表第一行」就是它,最后一章的范围变空
  33. itcParagraph(1, 1, 1, 'other book');
  34. itcParagraph(9300, 3, 1, 'Book');
  35. itcParagraph(9300, 4, 2, '1. First');
  36. itcParagraph(9300, 5, 100);
  37. itcParagraph(9300, 6, 2, '2. Last');
  38. itcParagraph(9300, 7, 100);
  39. itcParagraph(9300, 8, 100);
  40. $channel = makeChannel((string) Str::uuid(), 'pali');
  41. foreach ([4, 5, 6, 7, 8] as $para) {
  42. makeSentence($channel, 9300, $para, 1, "para {$para}");
  43. }
  44. $this->mock(PaliContentService::class, function ($mock) {
  45. $mock->shouldReceive('readParagraph')->andReturnUsing(fn ($book, $para) => [
  46. 'display' => "<p>{$para}</p>",
  47. 'sentences' => [['html' => "title {$para}"]],
  48. ]);
  49. });
  50. $created = [];
  51. $this->mock(OpenSearchService::class, function ($mock) use (&$created) {
  52. $mock->shouldReceive('testConnection')->andReturn([true, 'ok']);
  53. $mock->shouldReceive('create')->andReturnUsing(function (string $id, array $body) use (&$created) {
  54. $created[$id] = $body;
  55. return [];
  56. });
  57. });
  58. $this->artisan('opensearch:index-tipitaka', ['book' => 9300, '--granularity' => 'chapter', '--summary' => 'off'])
  59. ->assertExitCode(0);
  60. // 书名那一段(9300:3)到下一个标题之间没有句子,不建文档
  61. expect(array_keys($created))->toBe([
  62. "tipitaka_chapter_9300-4_{$channel}",
  63. "tipitaka_chapter_9300-6_{$channel}",
  64. ])->and($created["tipitaka_chapter_9300-6_{$channel}"]['content']['text']['zh'])->toBe('678');
  65. });