Skip to content

Commit 705dcbd

Browse files
eraydbighappyface
authored andcommitted
Add more unit tests (#366)
* Add test coverage for coercion API * Complete test coverage for SchemaStorage * Add test coverage for ObjectIterator * Add tests for ConstraintError * Add exception test for JsonPointer * MabeEnum\Enum appears to use singletons - add testing const * Don't check this line for coverage mbstring is on all test platforms, so this line will never be reached. * Add test for TypeConstraint::validateTypeNameWording() * Add test for exception on TypeConstraint::validateType() * PHPunit doesn't like an explanation with its @codeCoverageIgnore... * Add various tests for UriRetriever * Add tests for FileGetContents * Add tests for JsonSchema\Uri\Retrievers\Curl * Add missing bad-syntax test file * Restrict ignore to the exception line only * Fix exception scope
1 parent b8d2611 commit 705dcbd

14 files changed

+396
-20
lines changed

src/JsonSchema/ConstraintError.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class ConstraintError extends \MabeEnum\Enum
3333
const MAXIMUM = 'maximum';
3434
const MIN_ITEMS = 'minItems';
3535
const MINIMUM = 'minimum';
36+
const MISSING_ERROR = 'missingError';
3637
const MISSING_MAXIMUM = 'missingMaximum';
3738
const MISSING_MINIMUM = 'missingMinimum';
3839
const MAX_ITEMS = 'maxItems';
@@ -83,6 +84,7 @@ public function getMessage()
8384
self::MINIMUM => 'Must have a minimum value greater than or equal to %d',
8485
self::MISSING_MAXIMUM => 'Use of exclusiveMaximum requires presence of maximum',
8586
self::MISSING_MINIMUM => 'Use of exclusiveMinimum requires presence of minimum',
87+
/*self::MISSING_ERROR => 'Used for tests; this error is deliberately commented out',*/
8688
self::MULTIPLE_OF => 'Must be a multiple of %d',
8789
self::NOT => 'Matched a schema which it should not',
8890
self::ONE_OF => 'Failed to match exactly one schema',

src/JsonSchema/Constraints/StringConstraint.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ private function strlen($string)
5555
return mb_strlen($string, mb_detect_encoding($string));
5656
}
5757

58-
return strlen($string);
58+
// mbstring is present on all test platforms, so strlen() can be ignored for coverage
59+
return strlen($string); // @codeCoverageIgnore
5960
}
6061
}

src/JsonSchema/Uri/Retrievers/Curl.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
namespace JsonSchema\Uri\Retrievers;
1111

12+
use JsonSchema\Exception\RuntimeException;
1213
use JsonSchema\Validator;
1314

1415
/**
@@ -23,7 +24,8 @@ class Curl extends AbstractRetriever
2324
public function __construct()
2425
{
2526
if (!function_exists('curl_init')) {
26-
throw new \RuntimeException('cURL not installed');
27+
// Cannot test this, because curl_init is present on all test platforms plus mock
28+
throw new RuntimeException('cURL not installed'); // @codeCoverageIgnore
2729
}
2830
}
2931

src/JsonSchema/Uri/Retrievers/FileGetContents.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,10 @@ public function retrieve($uri)
5050

5151
$this->messageBody = $response;
5252
if (!empty($http_response_header)) {
53-
$this->fetchContentType($http_response_header);
54-
} else {
53+
// $http_response_header cannot be tested, because it's defined in the method's local scope
54+
// See http://php.net/manual/en/reserved.variables.httpresponseheader.php for more info.
55+
$this->fetchContentType($http_response_header); // @codeCoverageIgnore
56+
} else { // @codeCoverageIgnore
5557
// Could be a "file://" url or something else - fake up the response
5658
$this->contentType = null;
5759
}

tests/ConstraintErrorTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the JsonSchema package.
5+
*
6+
* For the full copyright and license information, please view the LICENSE
7+
* file that was distributed with this source code.
8+
*/
9+
10+
namespace JsonSchema\Tests;
11+
12+
use JsonSchema\ConstraintError;
13+
14+
class ConstraintErrorTest extends \PHPUnit_Framework_TestCase
15+
{
16+
public function testGetValidMessage()
17+
{
18+
$e = ConstraintError::ALL_OF();
19+
$this->assertEquals('Failed to match all schemas', $e->getMessage());
20+
}
21+
22+
public function testGetInvalidMessage()
23+
{
24+
$e = ConstraintError::MISSING_ERROR();
25+
26+
$this->setExpectedException(
27+
'\JsonSchema\Exception\InvalidArgumentException',
28+
'Missing error message for missingError'
29+
);
30+
$e->getMessage();
31+
}
32+
}

tests/Constraints/CoerciveTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,15 @@ public function testInvalidCoerceCasesUsingAssoc($input, $schema, $errors = arra
116116
$this->assertFalse($validator->isValid(), print_r($validator->getErrors(), true));
117117
}
118118

119+
public function testCoerceAPI()
120+
{
121+
$input = json_decode('{"propertyOne": "10"}');
122+
$schema = json_decode('{"properties":{"propertyOne":{"type":"number"}}}');
123+
$v = new Validator();
124+
$v->coerce($input, $schema);
125+
$this->assertEquals('{"propertyOne":10}', json_encode($input));
126+
}
127+
119128
public function getValidCoerceTests()
120129
{
121130
return array(

tests/Constraints/TypeTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,31 @@ private function assertTypeConstraintError($expected, TypeConstraint $actual)
9292
$this->assertEquals($expected, $actualMessage); // first equal for the diff
9393
$this->assertSame($expected, $actualMessage); // the same for the strictness
9494
}
95+
96+
public function testValidateTypeNameWording()
97+
{
98+
$t = new TypeConstraint();
99+
$r = new \ReflectionObject($t);
100+
$m = $r->getMethod('validateTypeNameWording');
101+
$m->setAccessible(true);
102+
103+
$this->setExpectedException(
104+
'\UnexpectedValueException',
105+
"No wording for 'notAValidTypeName' available, expected wordings are: [an integer, a number, a boolean, an object, an array, a string, a null]"
106+
);
107+
$m->invoke($t, 'notAValidTypeName');
108+
}
109+
110+
public function testValidateTypeException()
111+
{
112+
$t = new TypeConstraint();
113+
$data = new \StdClass();
114+
$schema = json_decode('{"type": "notAValidTypeName"}');
115+
116+
$this->setExpectedException(
117+
'JsonSchema\Exception\InvalidArgumentException',
118+
'object is an invalid type for notAValidTypeName'
119+
);
120+
$t->check($data, $schema);
121+
}
95122
}

tests/Entity/JsonPointerTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,4 +109,13 @@ public function testJsonPointerWithPropertyPaths()
109109
$this->assertEquals(array('~definitions/general', '%custom%'), $modified->getPropertyPaths());
110110
$this->assertEquals('#/~0definitions~1general/%25custom%25', $modified->getPropertyPathAsString());
111111
}
112+
113+
public function testCreateWithInvalidValue()
114+
{
115+
$this->setExpectedException(
116+
'\JsonSchema\Exception\InvalidArgumentException',
117+
'Ref value must be a string'
118+
);
119+
new JsonPointer(null);
120+
}
112121
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the JsonSchema package.
5+
*
6+
* For the full copyright and license information, please view the LICENSE
7+
* file that was distributed with this source code.
8+
*/
9+
10+
namespace JsonSchema\Tests\Iterators;
11+
12+
use JsonSchema\Iterator\ObjectIterator;
13+
14+
class ObjectIteratorTest extends \PHPUnit_Framework_TestCase
15+
{
16+
protected $testObject;
17+
18+
public function setUp()
19+
{
20+
$this->testObject = (object) array(
21+
'subOne' => (object) array(
22+
'propertyOne' => 'valueOne',
23+
'propertyTwo' => 'valueTwo',
24+
'propertyThree' => 'valueThree'
25+
),
26+
'subTwo' => (object) array(
27+
'propertyFour' => 'valueFour',
28+
'subThree' => (object) array(
29+
'propertyFive' => 'valueFive',
30+
'propertySix' => 'valueSix'
31+
)
32+
),
33+
'propertySeven' => 'valueSeven'
34+
);
35+
}
36+
37+
public function testCreate()
38+
{
39+
$i = new ObjectIterator($this->testObject);
40+
41+
$this->assertInstanceOf('\JsonSchema\Iterator\ObjectIterator', $i);
42+
}
43+
44+
public function testInitialState()
45+
{
46+
$i = new ObjectIterator($this->testObject);
47+
48+
$this->assertEquals($this->testObject, $i->current());
49+
}
50+
51+
public function testCount()
52+
{
53+
$i = new ObjectIterator($this->testObject);
54+
55+
$this->assertEquals(4, $i->count());
56+
}
57+
58+
public function testKey()
59+
{
60+
$i = new ObjectIterator($this->testObject);
61+
62+
while ($i->key() != 2) {
63+
$i->next();
64+
}
65+
66+
$this->assertEquals($this->testObject->subTwo->subThree, $i->current());
67+
}
68+
69+
public function testAlwaysObjects()
70+
{
71+
$i= new ObjectIterator($this->testObject);
72+
73+
foreach ($i as $item) {
74+
$this->assertInstanceOf('\StdClass', $item);
75+
}
76+
}
77+
78+
public function testReachesAllProperties()
79+
{
80+
$i = new ObjectIterator($this->testObject);
81+
82+
$count = 0;
83+
foreach ($i as $item) {
84+
$count += count(get_object_vars($item));
85+
}
86+
87+
$this->assertEquals(10, $count);
88+
}
89+
}

tests/SchemaStorageTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,4 +264,18 @@ private function getInvalidSchema()
264264
)
265265
);
266266
}
267+
268+
public function testGetUriRetriever()
269+
{
270+
$s = new SchemaStorage();
271+
$s->addSchema('http://json-schema.org/draft-04/schema#');
272+
$this->assertInstanceOf('\JsonSchema\Uri\UriRetriever', $s->getUriRetriever());
273+
}
274+
275+
public function testGetUriResolver()
276+
{
277+
$s = new SchemaStorage();
278+
$s->addSchema('http://json-schema.org/draft-04/schema#');
279+
$this->assertInstanceOf('\JsonSchema\Uri\UriResolver', $s->getUriResolver());
280+
}
267281
}

tests/Uri/Retrievers/CurlTest.php

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
3+
namespace JsonSchema\Tests\Uri\Retrievers
4+
{
5+
use JsonSchema\Uri\Retrievers\Curl;
6+
7+
class CurlTest extends \PHPUnit_Framework_TestCase
8+
{
9+
public function testRetrieveFile()
10+
{
11+
$c = new Curl();
12+
$c->retrieve(realpath(__DIR__ . '/../../fixtures/foobar.json'));
13+
}
14+
15+
public function testRetrieveNonexistantFile()
16+
{
17+
$c = new Curl();
18+
19+
$this->setExpectedException(
20+
'\JsonSchema\Exception\ResourceNotFoundException',
21+
'JSON schema not found'
22+
);
23+
$c->retrieve(__DIR__ . '/notARealFile');
24+
}
25+
26+
public function testNoContentType()
27+
{
28+
$c = new Curl();
29+
$c->retrieve(realpath(__DIR__ . '/../../fixtures') . '/foobar-noheader.json');
30+
}
31+
}
32+
}
33+
34+
namespace JsonSchema\Uri\Retrievers
35+
{
36+
function curl_exec($curl)
37+
{
38+
$uri = curl_getinfo($curl, \CURLINFO_EFFECTIVE_URL);
39+
40+
if ($uri === realpath(__DIR__ . '/../../fixtures/foobar.json')) {
41+
// return file with headers
42+
$headers = implode("\n", array(
43+
'Content-Type: application/json'
44+
));
45+
46+
return sprintf("%s\r\n\r\n%s", $headers, file_get_contents($uri));
47+
} elseif ($uri === realpath(__DIR__ . '/../../fixtures') . '/foobar-noheader.json') {
48+
// return file without headers
49+
$uri = realpath(__DIR__ . '/../../fixtures/foobar.json');
50+
51+
return "\r\n\r\n" . file_get_contents($uri);
52+
}
53+
54+
// fallback to real curl_exec
55+
return \curl_exec($curl);
56+
}
57+
}

0 commit comments

Comments
 (0)