Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a new Trait which allows to deal with Validator Constraints #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,45 @@ class MyCoolTest extends WebTestCase
}
```

## WithValidatorAssertionsTrait : Verify Validation Constraints after a request

With this trait, you gain assertions methods which deal with Validation Constraints (requires WithClientTrait).

```php
<?php

use Liior\SymfonyTestHelpers\Concerns\WithClientTrait;
use Liior\SymfonyTestHelpers\Concerns\WithValidatorAssertionsTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class MyCoolTest extends WebTestCase
{
use WithClientTrait;
use WithValidatorAssertionsTrait;

public function testItRuns()
{
$this->initializeClient();

// Don't forget to enable profiler before your request or none of this will work !
$this->client->enableProfiler();

$this->post('/save', [
'firstName' => '', // It should create a violation
'lastName' => 'Dupont', // It should not
'age' => 2000 // It should create a violation
]);

// You can do some assertions about the validator's violations list
$this->assertNoValidatorErrors(); // Will fail
$this->assertValidatorErrorsCount(2); // Will succeed
$this->assertValidatorHasError('firstName'); // Will succeed
$this->assertValidatorHasErrors(['firstName', 'age']); // Will succeed
$this->assertValidatorHasErrors(['firstName', 'lastName']); // Will fail (since lastName did not violate a constraint)
}
}
```

## WithFakerTrait: Using faker made easy

With this trait, you gain access to faker.
Expand Down
101 changes: 101 additions & 0 deletions src/Concerns/WithValidatorAssertionsTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

namespace Liior\SymfonyTestHelpers\Concerns;

use Liior\SymfonyTestHelpers\Exception\ProfilerNotEnabledException;
use Symfony\Component\HttpKernel\Profiler\Profile;

trait WithValidatorAssertionsTrait
{
/**
* Asserts that not validations error occured
*/
public function assertNoValidatorErrors(): self
{
return $this->assertValidatorErrorsCount(0);
}

/**
* Asserts that a specific number of errors occured in the validation process
*/
public function assertValidatorErrorsCount(int $count): self
{
$violations = $this->getViolationsCount($this->getProfile());

$this->assertEquals($count, $violations, sprintf('Failed asserting that validator had %s errors, %s found !', $count, $violations));

return $this;
}

/**
* Asserts that the validator found an error for the specified propertyPath
*/
public function assertValidatorHasError(string $propertyPath): self
{
$violations = $this->createConstraintsViolationsArray($this->getProfile());

$this->assertArrayHasKey(
$propertyPath,
$violations,
sprintf('Failed asserting that "%s" has a validation error', $propertyPath)
);

return $this;
}

/**
* Asserts that the validator found a set of errors for the specified properties
*/
public function assertValidatorHasErrors(array $properties): self
{
$violations = $this->createConstraintsViolationsArray($this->getProfile());

$notExistingProperties = [];

foreach ($properties as $propertyPath) {
if (!array_key_exists($propertyPath, $violations)) {
$notExistingProperties[] = $propertyPath;
}
}

$this->assertEquals(
0,
count($notExistingProperties),
sprintf('Failed asserting that validator has these validation errors : %s', join(', ', $notExistingProperties))
);

return $this;
}

protected function getViolationsCount(Profile $profile): int
{
return $profile->getCollector('validator')->getViolationsCount();
}

protected function createConstraintsViolationsArray(Profile $profile): array
{
$calls = $profile->getCollector('validator')->getCalls();

$violations = [];

foreach ($calls as $call) {
foreach ($call->violations as $violation) {
$propertyPath = str_replace('data.', '', $violation->propertyPath);
$violations[$propertyPath] = $violation->message;
}
}

return $violations;
}

protected function getProfile(): Profile
{
$profile = $this->client->getProfile();

if (!$profile) {
throw new ProfilerNotEnabledException();
}

return $profile;
}
}
16 changes: 16 additions & 0 deletions src/Exception/ProfilerNotEnabledException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Liior\SymfonyTestHelpers\Exception;

use RuntimeException;

class ProfilerNotEnabledException extends RuntimeException
{
public function __construct()
{
parent::__construct(\sprintf(
'Profiler was not initialized thus you should not call Validator assertions. Did you forget to call "%s" first?',
'$client->enableProfiler()'
));
}
}
2 changes: 2 additions & 0 deletions src/WebTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Liior\SymfonyTestHelpers\Concerns\WithFakerTrait;
use Liior\SymfonyTestHelpers\Concerns\WithClientTrait;
use Liior\SymfonyTestHelpers\Concerns\WithContainerTrait;
use Liior\SymfonyTestHelpers\Concerns\WithValidatorAssertionsTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;

class WebTestCase extends BaseWebTestCase
Expand All @@ -18,4 +19,5 @@ class WebTestCase extends BaseWebTestCase
use WithClientTrait;
use WithDatabaseTrait;
use WithFakerTrait;
use WithValidatorAssertionsTrait;
}