ErrorWrappingDecoderTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. declare(strict_types=1);
  3. namespace JsonMachineTest\JsonDecoder;
  4. use JsonMachine\Items;
  5. use JsonMachine\JsonDecoder\DecodingError;
  6. use JsonMachine\JsonDecoder\ErrorWrappingDecoder;
  7. use JsonMachine\JsonDecoder\ExtJsonDecoder;
  8. use JsonMachine\JsonDecoder\InvalidResult;
  9. use JsonMachine\JsonDecoder\ValidResult;
  10. use PHPUnit_Framework_TestCase;
  11. /**
  12. * @covers \JsonMachine\JsonDecoder\ErrorWrappingDecoder
  13. */
  14. class ErrorWrappingDecoderTest extends PHPUnit_Framework_TestCase
  15. {
  16. /**
  17. * @dataProvider data_testCorrectlyWrapsResults
  18. */
  19. public function testCorrectlyWrapsResults(array $case)
  20. {
  21. $innerDecoder = new StubDecoder($case['result']);
  22. $decoder = new ErrorWrappingDecoder($innerDecoder);
  23. $result = $decoder->decode('"json"');
  24. $this->assertTrue($result->isOk());
  25. $this->assertEquals($case['wrappedResult'], $result);
  26. }
  27. public function data_testCorrectlyWrapsResults()
  28. {
  29. $notOkResult = new InvalidResult('Error happened.');
  30. $okResult = new ValidResult('json');
  31. $wrappedNotOkResult = new ValidResult(new DecodingError('"json"', 'Error happened.'));
  32. $wrappedOkResult = $okResult;
  33. return [
  34. [
  35. [
  36. 'result' => $notOkResult,
  37. 'wrappedResult' => $wrappedNotOkResult,
  38. ],
  39. ],
  40. [
  41. [
  42. 'result' => $okResult,
  43. 'wrappedResult' => $wrappedOkResult,
  44. ],
  45. ],
  46. ];
  47. }
  48. public function testCatchesErrorInsideIteratedJsonChunk()
  49. {
  50. $json = /* @lang JSON */ '
  51. {
  52. "results": [
  53. {"correct": "correct"},
  54. {"incorrect": nulll},
  55. {"correct": "correct"}
  56. ]
  57. }
  58. ';
  59. $items = Items::fromString($json, [
  60. 'pointer' => '/results',
  61. 'decoder' => new ErrorWrappingDecoder(new ExtJsonDecoder(true)),
  62. ]);
  63. $result = iterator_to_array($items);
  64. $this->assertSame('correct', $result[0]['correct']);
  65. $this->assertSame('correct', $result[2]['correct']);
  66. /** @var DecodingError $decodingError */
  67. $decodingError = $result[1];
  68. $this->assertInstanceOf(DecodingError::class, $decodingError);
  69. $this->assertSame('{"incorrect":nulll}', $decodingError->getMalformedJson());
  70. $this->assertSame('Syntax error', $decodingError->getErrorMessage());
  71. }
  72. }