1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace VGirol\JsonApiAssert\Asserts\Content; |
4
|
|
|
|
5
|
|
|
use DMS\PHPUnitExtensions\ArraySubset\Constraint\ArraySubset; |
6
|
|
|
use PHPUnit\Framework\Assert as PHPUnit; |
7
|
|
|
use PHPUnit\Framework\AssertionFailedError; |
8
|
|
|
use VGirol\JsonApiAssert\Messages; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* This trait adds the ability to test errors content. |
12
|
|
|
*/ |
13
|
|
|
trait AssertErrors |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Asserts that an errors array contains a given subset of expected errors. |
17
|
|
|
* |
18
|
|
|
* It will do the following checks : |
19
|
|
|
* 1) asserts that the errors array is valid (@see assertIsValidErrorsObject). |
20
|
|
|
* 2) asserts that the errors array length is greater or equal than the expected errors array length. |
21
|
|
|
* 3) asserts that each expected error is present in the errors array. |
22
|
|
|
* |
23
|
|
|
* @link https://jsonapi.org/format/#error-objects |
24
|
|
|
* |
25
|
|
|
* @param array $expected An array of expected error objects |
26
|
|
|
* @param array $errors An array of errors to inspect |
27
|
|
|
* @param boolean $strict If true, unsafe characters are not allowed when checking members name. |
28
|
|
|
* |
29
|
|
|
* @return void |
30
|
|
|
* @throws \PHPUnit\Framework\AssertionFailedError |
31
|
|
|
*/ |
32
|
18 |
|
public static function assertErrorsContains($expected, $errors, $strict) |
33
|
|
|
{ |
34
|
|
|
try { |
35
|
18 |
|
static::assertIsValidErrorsObject($expected, $strict); |
36
|
3 |
|
} catch (AssertionFailedError $e) { |
37
|
3 |
|
static::invalidArgument(1, 'errors object', $expected); |
38
|
|
|
} |
39
|
|
|
|
40
|
15 |
|
static::assertIsValidErrorsObject($errors, $strict); |
41
|
|
|
|
42
|
12 |
|
PHPUnit::assertGreaterThanOrEqual( |
43
|
12 |
|
count($expected), |
44
|
12 |
|
count($errors), |
45
|
12 |
|
Messages::ERRORS_OBJECT_CONTAINS_NOT_ENOUGH_ERRORS |
46
|
|
|
); |
47
|
|
|
|
48
|
9 |
|
foreach ($expected as $expectedError) { |
49
|
9 |
|
$test = false; |
50
|
9 |
|
foreach ($errors as $error) { |
51
|
9 |
|
$constraint = new ArraySubset($expectedError, true); |
52
|
9 |
|
if ($constraint->evaluate($error, '', true)) { |
53
|
3 |
|
$test = true; |
54
|
3 |
|
break; |
55
|
|
|
} |
56
|
|
|
} |
57
|
9 |
|
PHPUnit::assertTrue( |
58
|
9 |
|
$test, |
59
|
3 |
|
sprintf( |
60
|
9 |
|
Messages::ERRORS_OBJECT_DOES_NOT_CONTAIN_EXPECTED_ERROR, |
61
|
9 |
|
var_export($expectedError, true) |
62
|
|
|
) |
63
|
|
|
); |
64
|
|
|
} |
65
|
3 |
|
} |
66
|
|
|
} |
67
|
|
|
|