LocaleV3Test.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. use Illuminate\Foundation\Testing\RefreshDatabase;
  3. uses(RefreshDatabase::class);
  4. /**
  5. * v3 的语言协商(V3\NegotiateLocale):按 Accept-Language 本地化 Problem Details 的
  6. * detail 与 errors。title 按 RFC 9457 保持稳定英文。
  7. *
  8. * 用两个不写库、不发信的失败请求做探针:
  9. * POST /api/v3/sessions(缺字段) → 422,validation.php 的文案
  10. * POST /api/v3/invites(错验证码) → 422,messages.php 的文案
  11. */
  12. function wrongCode(array $headers = [])
  13. {
  14. return test()->postJson('/api/v3/invites', ['email' => 'locale@example.test', 'code' => '000000'], $headers);
  15. }
  16. it('falls back to en without Accept-Language', function () {
  17. wrongCode()
  18. ->assertStatus(422)
  19. ->assertJsonPath('errors.code.0', 'The verification code is incorrect or has expired.')
  20. ->assertHeader('Content-Language', 'en');
  21. });
  22. it('localizes messages and validation errors to zh-Hans', function () {
  23. wrongCode(['Accept-Language' => 'zh-Hans'])
  24. ->assertJsonPath('errors.code.0', '验证码不正确或已过期。')
  25. ->assertJsonPath('detail', '验证码不正确或已过期。')
  26. ->assertHeader('Content-Language', 'zh-Hans');
  27. $this->postJson('/api/v3/sessions', [], ['Accept-Language' => 'zh-Hans'])
  28. ->assertStatus(422)
  29. ->assertJsonPath('errors.login.0', 'login 字段是必填项。');
  30. });
  31. it('keeps the Problem title in English', function () {
  32. $title = wrongCode(['Accept-Language' => 'zh-Hans'])->json('title');
  33. expect($title)->toBe(wrongCode()->json('title'));
  34. });
  35. it('maps regional Chinese tags to simplified and traditional', function (string $header, string $expected) {
  36. wrongCode(['Accept-Language' => $header])->assertJsonPath('errors.code.0', $expected);
  37. })->with([
  38. 'zh-CN' => ['zh-CN', '验证码不正确或已过期。'],
  39. 'zh-TW' => ['zh-TW', '驗證碼不正確或已過期。'],
  40. 'zh-Hant-HK' => ['zh-Hant-HK', '驗證碼不正確或已過期。'],
  41. ]);
  42. it('honours q values and skips unsupported languages', function () {
  43. wrongCode(['Accept-Language' => 'fr-FR, en;q=0.5, zh-CN;q=0.9'])
  44. ->assertHeader('Content-Language', 'zh-Hans');
  45. wrongCode(['Accept-Language' => 'fr-FR, de'])
  46. ->assertHeader('Content-Language', 'en');
  47. });
  48. it('marks responses as varying by Accept-Language', function () {
  49. $vary = wrongCode(['Accept-Language' => 'zh-Hans'])->headers->get('Vary');
  50. expect($vary)->toContain('Accept-Language');
  51. });
  52. it('does not set cookies', function () {
  53. expect(wrongCode(['Accept-Language' => 'zh-Hans'])->headers->getCookies())->toBeEmpty();
  54. });