Protobuf2ControllerTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Tests\Unit;
  3. use Tests\TestCase;
  4. use GuzzleHttp\Client;
  5. use Illuminate\Support\Facades\Log;
  6. use Uraus\App\ResponseHelloAreYouOk;
  7. class Protobuf2ControllerTest extends TestCase
  8. {
  9. private Client $client;
  10. private string $baseUrl = ''; // 修改为实际运行的服务器地址
  11. public function setUp(): void
  12. {
  13. parent::setUp();
  14. $this->baseUrl = env('UNITTEST_URL', 'http://localhost:8000');
  15. $this->client = new Client([
  16. 'base_uri' => $this->baseUrl,
  17. 'timeout' => 5.0,
  18. 'http_errors' => false,
  19. 'verify' => false // 禁用 SSL 验证
  20. ]);
  21. Log::info('测试开始,设置客户端配置', [
  22. 'base_uri' => $this->baseUrl
  23. ]);
  24. }
  25. /**
  26. * 测试 Hello 模块的 AreYouOk 请求
  27. */
  28. public function testHelloAreYouOk()
  29. {
  30. Log::info('准备 Hello/AreYouOk 测试数据');
  31. // 1. 准备 Protobuf 请求数据
  32. $areYouOk = new ResponseHelloAreYouOk();
  33. $areYouOk->setMsg("你好" . uniqid());
  34. $areYouOk->setTimes(time());
  35. $requestData = $areYouOk->serializeToString();
  36. Log::info('序列化请求数据完成', [
  37. 'data_length' => strlen($requestData),
  38. 'request_data' => $areYouOk->serializeToJsonString()
  39. ]);
  40. // 2. 发送真实的 HTTP 请求
  41. Log::info('发送 HTTP 请求');
  42. $response = $this->client->post('/api/protobuf/HelloAreYouOk', [
  43. 'body' => $requestData,
  44. 'headers' => [
  45. 'Content-Type' => 'application/x-protobuf',
  46. 'Accept' => 'application/x-protobuf'
  47. ]
  48. ]);
  49. Log::info('收到 HTTP 响应', [
  50. 'status_code' => $response->getStatusCode(),
  51. 'headers' => $response->getHeaders()
  52. ]);
  53. // 3. 验证 HTTP 响应状态码
  54. $this->assertEquals(200, $response->getStatusCode());
  55. // 4. 解析响应数据
  56. $responseContent = $response->getBody()->getContents();
  57. Log::info('获取响应内容', [
  58. 'content_length' => strlen($responseContent)
  59. ]);
  60. $protoResponse = new ResponseHelloAreYouOk();
  61. $protoResponse->mergeFromString($responseContent);
  62. dump($protoResponse->serializeToJsonString());
  63. Log::info('测试完成');
  64. }
  65. }