From 3938b76378e281c7df7db372fc3f0dae7bef15e7 Mon Sep 17 00:00:00 2001 From: Guillaume MOREL Date: Tue, 7 Oct 2014 13:43:20 +0200 Subject: [PATCH] Fix ability to test json payload against json schema --- features/json.feature | 37 ++++++++++++++++++++++++++++++++++ fixtures/www/json/booking.json | 12 +++++++++++ src/Context/JsonContext.php | 21 +++++++++++++++++++ src/Json/Json.php | 2 +- 4 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 fixtures/www/json/booking.json diff --git a/features/json.feature b/features/json.feature index 2742fe57..61c91165 100644 --- a/features/json.feature +++ b/features/json.feature @@ -72,6 +72,43 @@ Feature: Testing JSONContext } """ + Scenario: Json validation deep + Given I am on "/json/booking.json" + Then the JSON should be invalid according to this schema: + """ + { + "type":"object", + "$schema": "http://json-schema.org/draft-03/schema", + "required":false, + "properties":{ + "Booking": { + "type":"object", + "required":false + }, + "Metadata": { + "type":"object", + "required":false, + "properties":{ + "First": { + "type":"object", + "required":false, + "properties":{ + "default_value": { + "type":"boolean", + "required":false + }, + "enabled": { + "type":"boolean", + "required":true + } + } + } + } + } + } + } + """ + Scenario: Json contents validation Given I am on "/json/imajson.json" Then the JSON should be equal to: diff --git a/fixtures/www/json/booking.json b/fixtures/www/json/booking.json new file mode 100644 index 00000000..eac43e70 --- /dev/null +++ b/fixtures/www/json/booking.json @@ -0,0 +1,12 @@ +{ + "Booking": { + "id": "1", + "price": "77.21" + }, "Metadata": + { + "First": { + "bad_property_name": true, + "default_value": true + } + } +} diff --git a/src/Context/JsonContext.php b/src/Context/JsonContext.php index 59e03c8c..198c532b 100644 --- a/src/Context/JsonContext.php +++ b/src/Context/JsonContext.php @@ -4,6 +4,7 @@ use Behat\Gherkin\Node\PyStringNode; +use Behat\Mink\Exception\ExpectationException; use Sanpi\Behatch\Json\Json; use Sanpi\Behatch\Json\JsonSchema; use Sanpi\Behatch\Json\JsonInspector; @@ -158,6 +159,26 @@ public function theJsonShouldBeValidAccordingToThisSchema(PyStringNode $schema) ); } + /** + * @Then the JSON should be invalid according to this schema: + */ + public function theJsonShouldBeInvalidAccordingToThisSchema(PyStringNode $schema) + { + try { + $isValid = $this->inspector->validate( + $this->getJson(), + new JsonSchema($schema) + ); + + } catch (\Exception $e) { + $isValid = false; + } + + if (true === $isValid) { + throw new ExpectationException('Expected to receive invalid json, got valid one', $this->getSession()); + } + } + /** * @Then the JSON should be valid according to the schema :filename */ diff --git a/src/Json/Json.php b/src/Json/Json.php index 8f7e6294..0a984248 100644 --- a/src/Json/Json.php +++ b/src/Json/Json.php @@ -6,7 +6,7 @@ class Json { - private $content; + protected $content; public function __construct($content) {