respect-validation/tests/feature/ValidationExceptionStackTraceTest.php
Henrique Moody 9dac855c9e
Customize overwriting file and line in ValidationException
I've already changed the `ValidationException` so as not to let the file
and line from the Validator.php [1]. However, one could go even further
when creating more customizations on top of this library, and allowing
to customize the line could be very useful.

What motivated me making this change because it will be handy when I get
back to work on [Assertion][].

[1]: 75a9b8e94f
[Assertion]: https://github.com/Respect/Assertion
2024-12-26 20:37:54 +01:00

67 lines
2.1 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Test\Stubs\MyValidator;
test('Should overwrite file and line in the Validator class', function (): void {
try {
v::intType()->assert('string');
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});
test('Should overwrite file and line via the ValidatorDefaults class', function (): void {
try {
MyValidator::assertIntType('string');
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});
test('Should not overwrite file and line when created manually', function (): void {
try {
throw new ValidationException('message', 'fullMessage', ['id' => 'message']);
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});
test('Should not overwrite file and line when file cannot be ever traced', function (): void {
try {
throw new ValidationException('message', 'fullMessage', ['id' => 'message'], ['/tmp/unknown']);
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});
test('Should go not overwrite file and line when it runs out of choices', function (): void {
try {
$trace = array_unique(
array_filter(
array_map(
fn($trace) => $trace['file'] ?? null,
debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)
)
)
);
$trace[] = __FILE__;
throw new ValidationException('message', 'fullMessage', ['id' => 'message'], $trace);
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});