|
19 | 19 | use Codeception\Util\JsonType; |
20 | 20 | use Codeception\Util\XmlStructure; |
21 | 21 | use Codeception\Util\Soap as XmlUtils; |
| 22 | +use JsonSchema\Validator as JsonSchemaValidator; |
| 23 | +use JsonSchema\Constraints\Constraint as JsonContraint; |
22 | 24 |
|
23 | 25 | /** |
24 | 26 | * Module for testing REST WebService. |
@@ -841,6 +843,57 @@ public function seeResponseContainsJson($json = []) |
841 | 843 | ); |
842 | 844 | } |
843 | 845 |
|
| 846 | + /** |
| 847 | + * Checks whether last response matches the supplied json schema |
| 848 | + * Supply schema as json string |
| 849 | + * |
| 850 | + * @part json |
| 851 | + */ |
| 852 | + public function seeResponseIsValidOnJsonSchema($schema) |
| 853 | + { |
| 854 | + $responseContent = $this->connectionModule->_getResponseContent(); |
| 855 | + \PHPUnit\Framework\Assert::assertNotEquals('', $responseContent, 'response is empty'); |
| 856 | + $responseObject = json_decode($responseContent); |
| 857 | + $errorCode = json_last_error(); |
| 858 | + $errorMessage = json_last_error_msg(); |
| 859 | + \PHPUnit\Framework\Assert::assertEquals( |
| 860 | + JSON_ERROR_NONE, |
| 861 | + $errorCode, |
| 862 | + sprintf( |
| 863 | + "Invalid json: %s. System message: %s.", |
| 864 | + $responseContent, |
| 865 | + $errorMessage |
| 866 | + ) |
| 867 | + ); |
| 868 | + |
| 869 | + \PHPUnit\Framework\Assert::assertNotEquals('', $schema, 'schema is empty'); |
| 870 | + $schemaObject = json_decode($schema, true); |
| 871 | + $errorCode = json_last_error(); |
| 872 | + $errorMessage = json_last_error_msg(); |
| 873 | + \PHPUnit\Framework\Assert::assertEquals( |
| 874 | + JSON_ERROR_NONE, |
| 875 | + $errorCode, |
| 876 | + sprintf( |
| 877 | + "Invalid schema json: %s. System message: %s.", |
| 878 | + $responseContent, |
| 879 | + $errorMessage |
| 880 | + ) |
| 881 | + ); |
| 882 | + |
| 883 | + $validator = new JsonSchemaValidator(); |
| 884 | + $validator->validate($responseObject, $schemaObject, JsonContraint::CHECK_MODE_VALIDATE_SCHEMA); |
| 885 | + $outcome = $validator->isValid(); |
| 886 | + $error = ""; |
| 887 | + if (!$outcome) { |
| 888 | + $errors = $validator->getErrors(); |
| 889 | + $error = array_shift($errors)["message"]; |
| 890 | + } |
| 891 | + \PHPUnit\Framework\Assert::assertTrue( |
| 892 | + $outcome, |
| 893 | + $error |
| 894 | + ); |
| 895 | + } |
| 896 | + |
844 | 897 | /** |
845 | 898 | * Returns current response so that it can be used in next scenario steps. |
846 | 899 | * |
|
0 commit comments