ProtoJsonRequestTest.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace Tests\Unit;
  3. use Google\Protobuf\Internal\Message;
  4. use GuzzleHttp\Client;
  5. use Illuminate\Support\Facades\Log;
  6. use Uraus\Kku\Response;
  7. /**
  8. * protobuf请求测试
  9. *
  10. */
  11. abstract class ProtoJsonRequestTest extends \Tests\TestCase implements ProtoJsonRequest
  12. {
  13. protected Client $client;
  14. protected string $baseUrl = ''; // 修改为实际运行的服务器地址
  15. public $assertEquals = 200;
  16. /**
  17. *
  18. * @var string $token
  19. */
  20. public $token = '';
  21. public function setUp(): void
  22. {
  23. parent::setUp();
  24. $this->baseUrl = env('UNITTEST_URL', 'http://localhost:8000');
  25. $this->client = new Client([
  26. 'base_uri' => $this->baseUrl,
  27. 'timeout' => 5.0,
  28. 'http_errors' => false,
  29. 'verify' => false // 禁用 SSL 验证
  30. ]);
  31. }
  32. /**
  33. *
  34. * @return Message
  35. * @throws \GuzzleHttp\Exception\GuzzleException
  36. */
  37. public function protobufRequest(): Message
  38. {
  39. Log::info('准备 测试数据');
  40. // 1. 准备 Protobuf 请求数据
  41. $requestJson = $this->requestProtobufJson();
  42. Log::info('序列化请求数据完成', [
  43. 'data_length' => strlen($requestJson),
  44. 'request_data' => $requestJson
  45. ]);
  46. // 2. 发送真实的 HTTP 请求
  47. Log::info('发送 HTTP 请求');
  48. $response = $this->client->post('/gameapi', [
  49. 'body' => $requestJson,
  50. 'headers' => [
  51. 'token'=>$this->token,
  52. 'Content-Type' => 'application/json',
  53. 'Accept' => 'application/json'
  54. ]
  55. ]);
  56. Log::info('收到 HTTP 响应', [
  57. 'status_code' => $response->getStatusCode(),
  58. 'headers' => $response->getHeaders()
  59. ]);
  60. // 3. 验证 HTTP 响应状态码
  61. $this->assertEquals($this->assertEquals, $response->getStatusCode());
  62. // 4. 解析响应数据
  63. $responseContent = $response->getBody()->getContents();
  64. Log::info('获取响应内容', [
  65. 'content_length' => strlen($responseContent)
  66. ]);
  67. $protoResponse = new Response();
  68. $protoResponse->mergeFromJsonString($responseContent);
  69. Log::info('测试完成');
  70. return $protoResponse;
  71. }
  72. }