Skip to content

Commit

Permalink
For missing properties, the key for that error in set to ""
Browse files Browse the repository at this point in the history
- Expected bahavior is that the key would be set to the poperty name.
- added tests to ensure the "property" is populated regardless
of required attribute is completely missing or has empty value.
  • Loading branch information
samkeen committed Jun 16, 2015
1 parent 7dfe4f1 commit a71086d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/JsonSchema/Constraints/UndefinedConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ protected function validateCommonProperties($value, $schema = null, $path = null
// Draft 4 - Required is an array of strings - e.g. "required": ["foo", ...]
foreach ($schema->required as $required) {
if (!property_exists($value, $required)) {
$this->addError($path, "the property " . $required . " is required");
$this->addError($required, "the property " . $required . " is required");
}
}
} else if (isset($schema->required) && !is_array($schema->required)) {
Expand Down
64 changes: 64 additions & 0 deletions tests/JsonSchema/Tests/Constraints/RequiredPropertyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,72 @@

namespace JsonSchema\Tests\Constraints;

use JsonSchema\Constraints\UndefinedConstraint;

class RequiredPropertyTest extends BaseTestCase
{

public function testErrorPropertyIsPopulatedForRequiredIfMissingInInput()
{
$validator = new UndefinedConstraint();
$document = json_decode(
'{
"bar": 42
}'
);
$schema = json_decode(
'{
"type": "object",
"properties": {
"foo": {"type": "number"},
"bar": {"type": "number"}
},
"required": ["foo"]
}'
);

$validator->check($document, $schema);
$error = $validator->getErrors();
$this->assertErrorHasExpectedPropertyValue($error, "foo");
}

public function testErrorPropertyIsPopulatedForRequiredIfEmptyValueInInput()
{
$validator = new UndefinedConstraint();
$document = json_decode(
'{
"bar": 42,
"foo": null
}'
);
$schema = json_decode(
'{
"type": "object",
"properties": {
"foo": {"type": "number"},
"bar": {"type": "number"}
},
"required": ["foo"]
}'
);

$validator->check($document, $schema);
$error = $validator->getErrors();
$this->assertErrorHasExpectedPropertyValue($error, "foo");
}

protected function assertErrorHasExpectedPropertyValue($error, $propertyValue)
{
if (!(isset($error[0]) && is_array($error[0]) && isset($error[0]['property']))) {
$this->fail(
"Malformed error response. Expected to have subset in form: array(0 => array('property' => <value>)))"
. " . Error response was: " . json_encode($error)
);
}
$this->assertEquals($propertyValue, $error[0]['property']);

}

public function getInvalidTests()
{
return array(
Expand Down

0 comments on commit a71086d

Please sign in to comment.