1 | <?php |
||
26 | trait Assert |
||
27 | { |
||
28 | /** |
||
29 | * Asserts that json content is valid according to the provided schema file. |
||
30 | * |
||
31 | * Example: |
||
32 | * |
||
33 | * static::assertJsonMatchesSchema('./schema.json', json_decode('{"foo":1}')) |
||
34 | * |
||
35 | * @param string $schema Path to the schema file |
||
36 | * @param array|object $content JSON array or object |
||
37 | */ |
||
38 | 9 | public static function assertJsonMatchesSchema($schema, $content) |
|
39 | { |
||
40 | // Assume references are relative to the current file |
||
41 | // Create an issue or pull request if you need more complex use cases |
||
42 | 9 | $refResolver = new RefResolver(new UriRetriever(), new UriResolver()); |
|
43 | 9 | $schemaObj = $refResolver->resolve('file://' . realpath($schema)); |
|
44 | |||
45 | 9 | $validator = new Validator(); |
|
46 | 9 | $validator->check($content, $schemaObj); |
|
47 | |||
48 | 9 | $message = '- Property: %s, Contraint: %s, Message: %s'; |
|
49 | 9 | $messages = array_map(function ($exception) use ($message) { |
|
50 | 3 | return sprintf($message, $exception['property'], $exception['constraint'], $exception['message']); |
|
51 | 9 | }, $validator->getErrors()); |
|
52 | 9 | $messages[] = '- Response: '.json_encode($content); |
|
53 | |||
54 | 9 | \PHPUnit_Framework_Assert::assertTrue($validator->isValid(), implode("\n", $messages)); |
|
55 | 6 | } |
|
56 | |||
57 | /** |
||
58 | * Asserts that json content is valid according to the provided schema string. |
||
59 | * |
||
60 | * @param string $schema Schema data |
||
61 | * @param array|object $content JSON content |
||
62 | */ |
||
63 | 2 | public static function assertJsonMatchesSchemaString($schema, $content) |
|
70 | |||
71 | /** |
||
72 | * Asserts if the value retrieved with the expression equals the expected value. |
||
73 | * |
||
74 | * Example: |
||
75 | * |
||
76 | * static::assertJsonValueEquals(33, 'foo.bar[0]', $json); |
||
77 | * |
||
78 | * @param mixed $expected Expected value |
||
79 | * @param string $expression Expression to retrieve the result |
||
80 | * (e.g. locations[?state == 'WA'].name | sort(@)) |
||
81 | * @param array|object $json JSON Content |
||
82 | */ |
||
83 | 4 | public static function assertJsonValueEquals($expected, $expression, $json) |
|
84 | { |
||
85 | 4 | $result = \JmesPath\Env::search($expression, $json); |
|
86 | |||
87 | 4 | \PHPUnit_Framework_Assert::assertEquals($expected, $result); |
|
88 | 3 | \PHPUnit_Framework_Assert::assertInternalType(gettype($expected), $result); |
|
89 | 3 | } |
|
90 | |||
91 | /** |
||
92 | * Helper method to deserialise a JSON string into an object. |
||
93 | * |
||
94 | * @param mixed $data The JSON string |
||
95 | * |
||
96 | * @return array|object |
||
97 | */ |
||
98 | 4 | public static function getJsonObject($data) |
|
102 | } |
||
103 |