ProtoJsonRequestTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. public function setUp(): void
  17. {
  18. parent::setUp();
  19. $this->baseUrl = env('UNITTEST_URL', 'http://localhost:8000');
  20. $this->client = new Client([
  21. 'base_uri' => $this->baseUrl,
  22. 'timeout' => 5.0,
  23. 'http_errors' => false,
  24. 'verify' => false // 禁用 SSL 验证
  25. ]);
  26. }
  27. /**
  28. *
  29. * @return Message
  30. * @throws \GuzzleHttp\Exception\GuzzleException
  31. */
  32. public function protobufRequest(): Message
  33. {
  34. Log::info('准备 测试数据');
  35. // 1. 准备 Protobuf 请求数据
  36. $requestJson = $this->requestProtobufJson();
  37. Log::info('序列化请求数据完成', [
  38. 'data_length' => strlen($requestJson),
  39. 'request_data' => $requestJson
  40. ]);
  41. // 2. 发送真实的 HTTP 请求
  42. Log::info('发送 HTTP 请求');
  43. $response = $this->client->post('/gameapi', [
  44. 'body' => $requestJson,
  45. 'headers' => [
  46. 'Content-Type' => 'application/json',
  47. 'Accept' => 'application/json'
  48. ]
  49. ]);
  50. Log::info('收到 HTTP 响应', [
  51. 'status_code' => $response->getStatusCode(),
  52. 'headers' => $response->getHeaders()
  53. ]);
  54. // 3. 验证 HTTP 响应状态码
  55. $this->assertEquals($this->assertEquals, $response->getStatusCode());
  56. // 4. 解析响应数据
  57. $responseContent = $response->getBody()->getContents();
  58. Log::info('获取响应内容', [
  59. 'content_length' => strlen($responseContent)
  60. ]);
  61. $protoResponse = new Response();
  62. $protoResponse->mergeFromJsonString($responseContent);
  63. Log::info('测试完成');
  64. return $protoResponse;
  65. }
  66. }