AssertableJsonString.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Testing;
  12. use ArrayAccess;
  13. use Closure;
  14. use Countable;
  15. use Hyperf\Collection\Arr;
  16. use Hyperf\Contract\Jsonable;
  17. use Hyperf\Stringable\Str;
  18. use Hyperf\Testing\Assert as PHPUnit;
  19. use JsonSerializable;
  20. use function Hyperf\Collection\data_get;
  21. class AssertableJsonString implements ArrayAccess, Countable
  22. {
  23. /**
  24. * The original encoded json.
  25. *
  26. * @var array|Jsonable|JsonSerializable|string
  27. */
  28. public $json;
  29. /**
  30. * The decoded json contents.
  31. *
  32. * @var null|array
  33. */
  34. protected $decoded;
  35. /**
  36. * Create a new assertable JSON string instance.
  37. *
  38. * @param array|Jsonable|JsonSerializable|string $jsonable
  39. */
  40. public function __construct($jsonable)
  41. {
  42. $this->json = $jsonable;
  43. if ($jsonable instanceof JsonSerializable) {
  44. $this->decoded = $jsonable->jsonSerialize();
  45. } elseif ($jsonable instanceof Jsonable) {
  46. $this->decoded = json_decode($jsonable->__toString(), true);
  47. } elseif (is_array($jsonable)) {
  48. $this->decoded = $jsonable;
  49. } else {
  50. $this->decoded = json_decode($jsonable, true);
  51. }
  52. }
  53. /**
  54. * Validate and return the decoded response JSON.
  55. *
  56. * @param null|string $key
  57. * @return mixed
  58. */
  59. public function json($key = null)
  60. {
  61. return data_get($this->decoded, $key);
  62. }
  63. /**
  64. * Assert that the response JSON has the expected count of items at the given key.
  65. *
  66. * @param null|string $key
  67. * @return $this
  68. */
  69. public function assertCount(int $count, $key = null)
  70. {
  71. if (! is_null($key)) {
  72. PHPUnit::assertCount(
  73. $count,
  74. data_get($this->decoded, $key),
  75. "Failed to assert that the response count matched the expected {$count}"
  76. );
  77. return $this;
  78. }
  79. PHPUnit::assertCount(
  80. $count,
  81. $this->decoded,
  82. "Failed to assert that the response count matched the expected {$count}"
  83. );
  84. return $this;
  85. }
  86. /**
  87. * Assert that the response has the exact given JSON.
  88. *
  89. * @return $this
  90. */
  91. public function assertExact(array $data)
  92. {
  93. $actual = $this->reorderAssocKeys((array) $this->decoded);
  94. $expected = $this->reorderAssocKeys($data);
  95. PHPUnit::assertEquals(
  96. json_encode($expected, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
  97. json_encode($actual, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
  98. );
  99. return $this;
  100. }
  101. /**
  102. * Assert that the response has the similar JSON as given.
  103. *
  104. * @return $this
  105. */
  106. public function assertSimilar(array $data)
  107. {
  108. $actual = json_encode(
  109. Arr::sortRecursive((array) $this->decoded),
  110. JSON_UNESCAPED_UNICODE
  111. );
  112. PHPUnit::assertEquals(json_encode(Arr::sortRecursive($data), JSON_UNESCAPED_UNICODE), $actual);
  113. return $this;
  114. }
  115. /**
  116. * Assert that the response contains the given JSON fragment.
  117. *
  118. * @return $this
  119. */
  120. public function assertFragment(array $data)
  121. {
  122. $actual = json_encode(
  123. Arr::sortRecursive((array) $this->decoded),
  124. JSON_UNESCAPED_UNICODE
  125. );
  126. foreach (Arr::sortRecursive($data) as $key => $value) {
  127. $expected = $this->jsonSearchStrings($key, $value);
  128. PHPUnit::assertTrue(
  129. Str::contains($actual, $expected),
  130. 'Unable to find JSON fragment: ' . PHP_EOL . PHP_EOL .
  131. '[' . json_encode([$key => $value], JSON_UNESCAPED_UNICODE) . ']' . PHP_EOL . PHP_EOL .
  132. 'within' . PHP_EOL . PHP_EOL .
  133. "[{$actual}]."
  134. );
  135. }
  136. return $this;
  137. }
  138. /**
  139. * Assert that the response does not contain the given JSON fragment.
  140. *
  141. * @param bool $exact
  142. * @return $this
  143. */
  144. public function assertMissing(array $data, $exact = false)
  145. {
  146. if ($exact) {
  147. return $this->assertMissingExact($data);
  148. }
  149. $actual = json_encode(
  150. Arr::sortRecursive((array) $this->decoded),
  151. JSON_UNESCAPED_UNICODE
  152. );
  153. foreach (Arr::sortRecursive($data) as $key => $value) {
  154. $unexpected = $this->jsonSearchStrings($key, $value);
  155. PHPUnit::assertFalse(
  156. Str::contains($actual, $unexpected),
  157. 'Found unexpected JSON fragment: ' . PHP_EOL . PHP_EOL .
  158. '[' . json_encode([$key => $value], JSON_UNESCAPED_UNICODE) . ']' . PHP_EOL . PHP_EOL .
  159. 'within' . PHP_EOL . PHP_EOL .
  160. "[{$actual}]."
  161. );
  162. }
  163. return $this;
  164. }
  165. /**
  166. * Assert that the response does not contain the exact JSON fragment.
  167. *
  168. * @return $this
  169. */
  170. public function assertMissingExact(array $data)
  171. {
  172. $actual = json_encode(
  173. Arr::sortRecursive((array) $this->decoded),
  174. JSON_UNESCAPED_UNICODE
  175. );
  176. foreach (Arr::sortRecursive($data) as $key => $value) {
  177. $unexpected = $this->jsonSearchStrings($key, $value);
  178. if (! Str::contains($actual, $unexpected)) {
  179. return $this;
  180. }
  181. }
  182. PHPUnit::fail(
  183. 'Found unexpected JSON fragment: ' . PHP_EOL . PHP_EOL .
  184. '[' . json_encode($data, JSON_UNESCAPED_UNICODE) . ']' . PHP_EOL . PHP_EOL .
  185. 'within' . PHP_EOL . PHP_EOL .
  186. "[{$actual}]."
  187. );
  188. }
  189. /**
  190. * Assert that the response does not contain the given path.
  191. *
  192. * @param string $path
  193. * @return $this
  194. */
  195. public function assertMissingPath($path)
  196. {
  197. PHPUnit::assertFalse(Arr::has($this->json(), $path));
  198. return $this;
  199. }
  200. /**
  201. * Assert that the expected value and type exists at the given path in the response.
  202. *
  203. * @param string $path
  204. * @param mixed $expect
  205. * @return $this
  206. */
  207. public function assertPath($path, $expect)
  208. {
  209. if ($expect instanceof Closure) {
  210. PHPUnit::assertTrue($expect($this->json($path)));
  211. } else {
  212. PHPUnit::assertSame($expect, $this->json($path));
  213. }
  214. return $this;
  215. }
  216. /**
  217. * Assert that the response has a given JSON structure.
  218. *
  219. * @param null|array $responseData
  220. * @return $this
  221. */
  222. public function assertStructure(?array $structure = null, $responseData = null)
  223. {
  224. if (is_null($structure)) {
  225. return $this->assertSimilar($this->decoded);
  226. }
  227. if (! is_null($responseData)) {
  228. return (new static($responseData))->assertStructure($structure);
  229. }
  230. foreach ($structure as $key => $value) {
  231. if (is_array($value) && $key === '*') {
  232. PHPUnit::assertIsArray($this->decoded);
  233. foreach ($this->decoded as $responseDataItem) {
  234. $this->assertStructure($structure['*'], $responseDataItem);
  235. }
  236. } elseif (is_array($value)) {
  237. PHPUnit::assertArrayHasKey($key, $this->decoded);
  238. $this->assertStructure($structure[$key], $this->decoded[$key]);
  239. } else {
  240. PHPUnit::assertArrayHasKey($value, $this->decoded);
  241. }
  242. }
  243. return $this;
  244. }
  245. /**
  246. * Assert that the response is a superset of the given JSON.
  247. *
  248. * @param bool $strict
  249. * @return $this
  250. */
  251. public function assertSubset(array $data, $strict = false)
  252. {
  253. PHPUnit::assertArraySubset(
  254. $data,
  255. $this->decoded,
  256. $strict,
  257. $this->assertJsonMessage($data)
  258. );
  259. return $this;
  260. }
  261. /**
  262. * Get the total number of items in the underlying JSON array.
  263. */
  264. public function count(): int
  265. {
  266. return count($this->decoded);
  267. }
  268. /**
  269. * Determine whether an offset exists.
  270. *
  271. * @param mixed $offset
  272. */
  273. public function offsetExists($offset): bool
  274. {
  275. return isset($this->decoded[$offset]);
  276. }
  277. /**
  278. * Get the value at the given offset.
  279. *
  280. * @param string $offset
  281. */
  282. public function offsetGet($offset): mixed
  283. {
  284. return $this->decoded[$offset];
  285. }
  286. /**
  287. * Set the value at the given offset.
  288. *
  289. * @param string $offset
  290. * @param mixed $value
  291. */
  292. public function offsetSet($offset, $value): void
  293. {
  294. $this->decoded[$offset] = $value;
  295. }
  296. /**
  297. * Unset the value at the given offset.
  298. *
  299. * @param string $offset
  300. */
  301. public function offsetUnset($offset): void
  302. {
  303. unset($this->decoded[$offset]);
  304. }
  305. /**
  306. * Reorder associative array keys to make it easy to compare arrays.
  307. *
  308. * @return array
  309. */
  310. protected function reorderAssocKeys(array $data)
  311. {
  312. $data = Arr::dot($data);
  313. ksort($data);
  314. $result = [];
  315. foreach ($data as $key => $value) {
  316. Arr::set($result, $key, $value);
  317. }
  318. return $result;
  319. }
  320. /**
  321. * Get the assertion message for assertJson.
  322. *
  323. * @return string
  324. */
  325. protected function assertJsonMessage(array $data)
  326. {
  327. $expected = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  328. $actual = json_encode($this->decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  329. return 'Unable to find JSON: ' . PHP_EOL . PHP_EOL .
  330. "[{$expected}]" . PHP_EOL . PHP_EOL .
  331. 'within response JSON:' . PHP_EOL . PHP_EOL .
  332. "[{$actual}]." . PHP_EOL . PHP_EOL;
  333. }
  334. /**
  335. * Get the strings we need to search for when examining the JSON.
  336. *
  337. * @param string $key
  338. * @param string $value
  339. * @return array
  340. */
  341. protected function jsonSearchStrings($key, $value)
  342. {
  343. $needle = Str::substr(json_encode([$key => $value], JSON_UNESCAPED_UNICODE), 1, -1);
  344. return [
  345. $needle . ']',
  346. $needle . '}',
  347. $needle . ',',
  348. ];
  349. }
  350. }