Skip to content

Commit 68b0e36

Browse files
Guillaume MORELsanpii
Guillaume MOREL
authored andcommitted
Fix ability to test json payload against json schema
1 parent 96dec04 commit 68b0e36

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

fixtures/www/json/booking.json

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"Booking": {
3+
"id": "1",
4+
"price": "77.21"
5+
}, "Metadata":
6+
{
7+
"First": {
8+
"bad_property_name": true,
9+
"default_value": true
10+
}
11+
}
12+
}

src/Context/JsonContext.php

+21
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Behat\Gherkin\Node\PyStringNode;
66

77
use Behat\Gherkin\Node\TableNode;
8+
use Behat\Mink\Exception\ExpectationException;
89
use Behatch\Json\Json;
910
use Behatch\Json\JsonSchema;
1011
use Behatch\Json\JsonInspector;
@@ -311,6 +312,26 @@ public function theJsonShouldBeValidAccordingToThisSchema(PyStringNode $schema)
311312
);
312313
}
313314

315+
/**
316+
* @Then the JSON should be invalid according to this schema:
317+
*/
318+
public function theJsonShouldBeInvalidAccordingToThisSchema(PyStringNode $schema)
319+
{
320+
try {
321+
$isValid = $this->inspector->validate(
322+
$this->getJson(),
323+
new JsonSchema($schema)
324+
);
325+
326+
} catch (\Exception $e) {
327+
$isValid = false;
328+
}
329+
330+
if (true === $isValid) {
331+
throw new ExpectationException('Expected to receive invalid json, got valid one', $this->getSession());
332+
}
333+
}
334+
314335
/**
315336
* @Then the JSON should be valid according to the schema :filename
316337
*/

tests/features/json.feature

+37
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,43 @@ Feature: Testing JSONContext
9191
}
9292
"""
9393

94+
Scenario: Json validation deep
95+
Given I am on "/json/booking.json"
96+
Then the JSON should be invalid according to this schema:
97+
"""
98+
{
99+
"type":"object",
100+
"$schema": "http://json-schema.org/draft-03/schema",
101+
"required":false,
102+
"properties":{
103+
"Booking": {
104+
"type":"object",
105+
"required":false
106+
},
107+
"Metadata": {
108+
"type":"object",
109+
"required":false,
110+
"properties":{
111+
"First": {
112+
"type":"object",
113+
"required":false,
114+
"properties":{
115+
"default_value": {
116+
"type":"boolean",
117+
"required":false
118+
},
119+
"enabled": {
120+
"type":"boolean",
121+
"required":true
122+
}
123+
}
124+
}
125+
}
126+
}
127+
}
128+
}
129+
"""
130+
94131
Scenario: Json contents validation
95132
Given I am on "/json/imajson.json"
96133
Then the JSON should be equal to:

0 commit comments

Comments
 (0)