ApiTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. use GuzzleHttp\Client;
  3. use GuzzleHttp\Handler\MockHandler;
  4. use GuzzleHttp\HandlerStack;
  5. use GuzzleHttp\Psr7\Response;
  6. use mattvb91\TronTrx\Api;
  7. use mattvb91\TronTrx\Exceptions\TronErrorException;
  8. use PHPUnit\Framework\TestCase;
  9. class ApiTest extends TestCase
  10. {
  11. /**
  12. * @covers \mattvb91\TronTrx\Api::getClient
  13. * @covers \mattvb91\TronTrx\Api::__construct
  14. */
  15. public function testGetClientReturnsInstanceOfClient()
  16. {
  17. $api = new Api(new Client());
  18. $this->assertInstanceOf(Client::class, $api->getClient());
  19. }
  20. /**
  21. * @covers \mattvb91\TronTrx\Api::post
  22. * @covers \mattvb91\TronTrx\Api::checkForErrorResponse
  23. */
  24. public function testPostAssocTrueFalse()
  25. {
  26. // Create a mock and queue two responses.
  27. $response = new Response(200, [], json_encode([
  28. 'test' => true,
  29. ]));
  30. $mock = new MockHandler([
  31. $response,
  32. $response,
  33. new Response(200, [], json_encode(['Error' => 'Error'])),
  34. ]);
  35. $handler = HandlerStack::create($mock);
  36. $client = new Client(['handler' => $handler]);
  37. $api = new Api($client);
  38. $this->assertArrayHasKey('test', $api->post('/test', ['data' => []], true));
  39. $response = $api->post('/test');
  40. $this->assertObjectHasAttribute('test', $response);
  41. $this->assertTrue($response->test);
  42. }
  43. /**
  44. * @covers \mattvb91\TronTrx\Api::checkForErrorResponse
  45. * @dataProvider getResponses
  46. */
  47. public function testErrorExceptionIsThrownWithAssoc($client, $assoc)
  48. {
  49. $api = new Api($client);
  50. $this->expectException(TronErrorException::class);
  51. $api->post('/test', [], $assoc);
  52. }
  53. public function getResponses()
  54. {
  55. $errorResponse = new Response(200, [], json_encode(['Error' => 'Error']));
  56. $codeResponse = new Response(200, [], json_encode(['code' => 'code', 'message' => bin2hex('test message')]));
  57. $mock = new MockHandler([
  58. $errorResponse,
  59. $errorResponse,
  60. $codeResponse,
  61. $codeResponse,
  62. ]);
  63. $handler = HandlerStack::create($mock);
  64. $client = new Client(['handler' => $handler]);
  65. return [
  66. [$client, true],
  67. [$client, false],
  68. [$client, true],
  69. [$client, false],
  70. ];
  71. }
  72. }