PaliWordFormV3Test.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. use App\Models\WordIndex;
  3. use Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Support\Facades\DB;
  5. uses(RefreshDatabase::class);
  6. /*
  7. * GET /v3/pali-word-forms/{word}:词 → 词根 → 三藏里出现过的词形与次数(取代 v2 case/{word})。
  8. * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
  9. */
  10. function wordIndex(string $word, int $count, int $bold = 0): void
  11. {
  12. WordIndex::forceCreate([
  13. 'id' => random_int(1, PHP_INT_MAX >> 33),
  14. 'word' => $word,
  15. 'word_en' => $word,
  16. 'count' => $count,
  17. 'normal' => $count - $bold,
  18. 'bold' => $bold,
  19. 'is_base' => 0,
  20. 'len' => mb_strlen($word),
  21. ]);
  22. }
  23. it('lists the forms of the word itself first, sorted by count, with bold counts', function () {
  24. wordIndex('vitakko', 1070, 52);
  25. wordIndex('vitakkaṃ', 236, 21);
  26. wordIndex('vitakkassāti', 3, 2); // 连音 iti
  27. wordIndex('unrelated', 99);
  28. $res = $this->getJson('/api/v3/pali-word-forms/vitakka')->assertOk();
  29. $res->assertJsonPath('data.0.base', 'vitakka')
  30. ->assertJsonPath('data.0.forms', [
  31. ['word' => 'vitakko', 'count' => 1070, 'bold' => 52],
  32. ['word' => 'vitakkaṃ', 'count' => 236, 'bold' => 21],
  33. ['word' => 'vitakkassāti', 'count' => 3, 'bold' => 2],
  34. ])
  35. ->assertJsonPath('meta.total', count($res->json('data')));
  36. expect(collect($res->json('data'))->pluck('forms')->flatten(1)->pluck('word'))->not->toContain('unrelated');
  37. });
  38. it('is case-insensitive', function () {
  39. wordIndex('vitakko', 10);
  40. $this->getJson('/api/v3/pali-word-forms/Vitakka')
  41. ->assertOk()
  42. ->assertJsonPath('data.0.base', 'vitakka');
  43. });
  44. it('returns an empty list when no form occurs in the canon', function () {
  45. $this->getJson('/api/v3/pali-word-forms/qqqzzz')
  46. ->assertOk()
  47. ->assertJsonPath('data', [])
  48. ->assertJsonPath('meta.total', 0);
  49. });
  50. it('rejects an over-long word with 404 (path constraint)', function () {
  51. $this->getJson('/api/v3/pali-word-forms/'.str_repeat('a', 65))->assertNotFound();
  52. });
  53. it('looks up all candidate forms in a single query', function () {
  54. wordIndex('vitakko', 10);
  55. wordIndex('dhammo', 10);
  56. $queries = function (string $word): int {
  57. DB::flushQueryLog();
  58. DB::enableQueryLog();
  59. $this->getJson("/api/v3/pali-word-forms/{$word}")->assertOk();
  60. return count(DB::getQueryLog());
  61. };
  62. // 词根多少、候选词形多少都不影响查询次数
  63. expect($queries('vitakka'))->toBe($queries('dhammo'))->toBe(1);
  64. });