Integrated FOSUserBundle (#216)

This commit is contained in:
Kevin Papst
2018-07-21 22:36:36 +02:00
committed by GitHub
parent 2d2525cff2
commit 75246e9db2
77 changed files with 1413 additions and 514 deletions

15
tests/.env.dist.mysql Normal file
View File

@@ -0,0 +1,15 @@
DATABASE_PREFIX=abc_
MAILER_FROM=kimai@example.com
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=c88c14fa70a424e7a12d459b9dd9df7f
###< symfony/framework-bundle ###
###> doctrine/doctrine-bundle ###
DATABASE_URL=mysql://travis@127.0.0.1:3306/kimai_migrations
###< doctrine/doctrine-bundle ###
###> symfony/swiftmailer-bundle ###
MAILER_URL=null://localhost
###< symfony/swiftmailer-bundle ###

15
tests/.env.dist.sqlite Normal file
View File

@@ -0,0 +1,15 @@
DATABASE_PREFIX=abc_
MAILER_FROM=kimai@example.com
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=c88c14fa70a424e7a12d459b9dd9df7f
###< symfony/framework-bundle ###
###> doctrine/doctrine-bundle ###
DATABASE_URL=sqlite:///%kernel.project_dir%/var/data/kimai_migrations.sqlite
###< doctrine/doctrine-bundle ###
###> symfony/swiftmailer-bundle ###
MAILER_URL=null://localhost
###< symfony/swiftmailer-bundle ###

View File

@@ -15,6 +15,7 @@ use App\Tests\Controller\ControllerBaseTest;
/**
* @coversDefaultClass \App\Controller\Admin\ActivityController
* @group integration
* @group legacy
*/
class ActivityControllerTest extends ControllerBaseTest
{

View File

@@ -15,6 +15,7 @@ use App\Tests\Controller\ControllerBaseTest;
/**
* @coversDefaultClass \App\Controller\Admin\UserController
* @group integration
* @group legacy
*/
class UserControllerTest extends ControllerBaseTest
{
@@ -30,4 +31,62 @@ class UserControllerTest extends ControllerBaseTest
$this->assertAccessIsGranted($client, '/admin/user/');
$this->assertHasDataTable($client);
}
/**
* @dataProvider getValidationTestData
*/
public function testValidationForCreateAction(array $formData, array $validationFields)
{
$this->assertFormHasValidationError(
User::ROLE_SUPER_ADMIN,
'/admin/user/create',
'form[name=user_create]',
$formData,
$validationFields
);
}
public function getValidationTestData()
{
return [
[
// invalid fields: username, password_second, email, enabled
[
'user_create' => [
'username' => '',
'plainPassword' => ['first' => 'sdfsdf'],
'alias' => 'ycvyxcb',
'title' => '34rtwrtewrt',
'avatar' => 'asdfawer',
'email' => '',
]
],
[
'#user_create_username',
'#user_create_plainPassword_first',
'#user_create_email',
]
],
// invalid fields: username, password, email, enabled
[
[
'user_create' => [
'username' => '',
'plainPassword' => ['first' => 'sdfsdf', 'second' => 'sdfxxx'],
'alias' => 'ycvyxcb',
'title' => '34rtwrtewrt',
'avatar' => 'asdfawer',
'email' => 'ydfbvsdfgs', // email is not working
'enabled' => '3',
]
],
[
'#user_create_username',
'#user_create_plainPassword_first',
'#user_create_email',
'#user_create_enabled',
]
],
];
}
}

View File

@@ -103,7 +103,6 @@ abstract class ControllerBaseTest extends WebTestCase
/**
* @param string $url
* @param string $method
* @param Client|null $client
*/
protected function assertUrlIsSecured(string $url, $method = 'GET')
{
@@ -163,4 +162,41 @@ abstract class ControllerBaseTest extends WebTestCase
{
$this->assertContains('<table class="table table-striped table-hover dataTable" role="grid">', $client->getResponse()->getContent());
}
/**
* @param string $role the USER role to use for the request
* @param string $url the URL of the page displaying the initial form to submit
* @param string $formSelector a selector to find the form to test
* @param array $formData values to fill in the form
* @param array $fieldNames array of form-fields that should fail
* @param bool $disableValidation whether the form should validate before submitting or not
*/
protected function assertFormHasValidationError($role, $url, $formSelector, array $formData, array $fieldNames, $disableValidation = true)
{
$client = $this->getClientForAuthenticatedUser($role);
$crawler = $client->request('GET', '/' . self::DEFAULT_LANGUAGE . $url);
$form = $crawler->filter($formSelector)->form();
if ($disableValidation) {
$form->disableValidation();
}
$result = $client->submit($form, $formData);
$submittedForm = $result->filter($formSelector);
$validationErrors = $submittedForm->filter('li.text-danger');
$this->assertEquals(
count($fieldNames),
count($validationErrors),
sprintf('Expected %s validation errors, found %s', count($fieldNames), count($validationErrors))
);
foreach ($fieldNames as $name) {
$field = $submittedForm->filter($name);
$this->assertNotNull($field, 'Could not find form field: ' . $name);
$list = $field->nextAll();
$this->assertNotNull($list, 'Form field has no validation message: ' . $name);
$validation = $list->filter('li.text-danger');
$this->assertGreaterThanOrEqual(1, count($validation), 'Form field has no validation message: ' . $name);
}
}
}

View File

@@ -9,49 +9,61 @@
namespace App\Tests\Entity;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\Validation;
/**
* @covers \App\Entity\Timesheet
*/
abstract class AbstractEntityTest extends TestCase
abstract class AbstractEntityTest extends KernelTestCase
{
/**
* @param $value
* @param $entity
* @param array|string $fieldNames
*/
protected function assertHasViolationForField($value, $fieldNames)
protected function assertHasViolationForField($entity, $fieldNames)
{
$validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
$validations = $validator->validate($value);
self::bootKernel();
$validator = static::$kernel->getContainer()->get('validator');
$violations = $validator->validate($entity);
if (!is_array($fieldNames)) {
$fieldNames = [$fieldNames];
}
$expected = count($fieldNames);
$actual = $violations->count();
$this->assertEquals($expected, $actual, sprintf('Expected %s violations, found %s.', $expected, $actual));
$violatedFields = [];
/** @var ConstraintViolationInterface $validation */
foreach ($validations as $validation) {
$violatedFields[] = $validation->getPropertyPath();
foreach ($violations as $validation) {
$violatedFields[$validation->getPropertyPath()] = $validation->getPropertyPath();
}
foreach ($fieldNames as $id => $propertyPath) {
$foundField = false;
if (in_array($propertyPath, $violatedFields)) {
$foundField = true;
unset($violatedFields[$id]);
unset($violatedFields[$propertyPath]);
}
$this->assertTrue($foundField, 'Failed finding violation for field: ' . $propertyPath);
}
$this->assertEmpty($violatedFields, sprintf('Unexpected violations found: %s', implode(', ', $violatedFields)));
}
$expected = count($fieldNames);
$actual = $validations->count();
protected function assertHasNoViolations($entity)
{
self::bootKernel();
$validator = static::$kernel->getContainer()->get('validator');
$this->assertEquals($expected, $actual, sprintf('Expected %s violations, found %s.', $expected, $actual));
$violations = $validator->validate($entity);
$actual = $violations->count();
$this->assertEquals(0, $actual, sprintf('Expected 0 violations, found %s.', $actual));
}
}

110
tests/Entity/UserTest.php Normal file
View File

@@ -0,0 +1,110 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Entity;
use App\Entity\User;
use App\Entity\UserPreference;
/**
* @covers \App\Entity\User
*/
class UserTest extends AbstractEntityTest
{
public function getInvalidTestData()
{
return [
['', ''],
[null, null],
['test', 'test@'], // too short username
[str_pad('#', 61, '-'), 'test@x.'], // too long username
[str_pad('#', 61, '-'), 'test@x.', ['xxxxx']], // too short password and invalid role
];
}
/**
* @dataProvider getInvalidTestData
*/
public function testInvalidValues($username, $email, $roles = [])
{
$defaultFields = [
'username', 'email'
];
$user = new User();
$user->setUsername($username);
$user->setEmail($email);
if (!empty($roles)) {
$user->setRoles($roles);
$defaultFields[] = 'roles';
}
$this->assertHasViolationForField($user, $defaultFields);
}
public function getValidTestData()
{
return [
[str_pad('#', 6, '-'), 'test@x.x'], // shortest possible username
[str_pad('#', 60, '-'), 'test@x.x', ['ROLE_CUSTOMER']], // longest possible password and valid role
];
}
/**
* @dataProvider getValidTestData
*/
public function testValidValues($username, $email, $roles = [])
{
$user = new User();
$user->setUsername($username);
$user->setEmail($email);
if (!empty($roles)) {
$user->setRoles($roles);
}
$this->assertHasNoViolations($user);
}
public function testDatetime()
{
$date = new \DateTime('+1 day');
$user = new User();
$user->setRegisteredAt($date);
$this->assertEquals($date, $user->getRegisteredAt());
}
public function testPreferences()
{
$user = new User();
$this->assertNull($user->getPreference('test'));
$this->assertNull($user->getPreferenceValue('test'));
$this->assertEquals('foo', $user->getPreferenceValue('test', 'foo'));
$preference = new UserPreference();
$preference
->setName('test')
->setValue('foobar');
$user->addPreference($preference);
$this->assertEquals('foobar', $user->getPreferenceValue('test', 'foo'));
$this->assertEquals($preference, $user->getPreference('test'));
}
public function testToString()
{
$user = new User();
$user->setUsername('bar');
$this->assertEquals('bar', (string) $user);
$this->assertEquals('bar', $user->getUsername());
$user->setAlias('foo');
$this->assertEquals('foo', (string) $user);
$this->assertEquals('foo', $user->getAlias());
}
}

View File

@@ -0,0 +1,68 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Voter;
use App\Entity\User;
use App\EventSubscriber\RegistrationSubscriber;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserManagerInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* @covers \App\EventSubscriber\RegistrationSubscriber
*/
class RegistrationSubscriberTest extends TestCase
{
public function testGetSubscribedEvents()
{
$events = RegistrationSubscriber::getSubscribedEvents();
$this->assertArrayHasKey(FOSUserEvents::REGISTRATION_SUCCESS, $events);
$methodName = $events[FOSUserEvents::REGISTRATION_SUCCESS][0];
$this->assertTrue(method_exists(RegistrationSubscriber::class, $methodName));
}
/**
* @dataProvider getTestData
*/
public function testRoleAssignmentForNewUser(array $existingUsers, $expectedRoles)
{
$user = new User();
$user->setAlias('foo');
$this->assertEquals([User::ROLE_USER], $user->getRoles());
$userManager = $this->getMockBuilder(UserManagerInterface::class)->getMock();
$userManager->method('findUsers')->willReturn($existingUsers);
$form = $this->getMockBuilder(FormInterface::class)->getMock();
$form->method('getData')->willReturn($user);
$request = $this->getMockBuilder(Request::class)->getMock();
$event = new FormEvent($form, $request);
$sut = new RegistrationSubscriber($userManager);
$sut->onRegistrationSuccess($event);
$this->assertEquals($expectedRoles, $user->getRoles());
}
public function getTestData()
{
return [
// NewFirstUserGetsSuperAdminRole
[[], [User::ROLE_SUPER_ADMIN, User::ROLE_USER]],
// NewUserGetUserRole
[[new User()], [User::ROLE_USER]],
];
}
}

View File

@@ -82,7 +82,7 @@ class TimesheetQueryTest extends BaseQueryTest
{
$this->assertEquals(TimesheetQuery::STATE_ALL, $sut->getState());
$sut->setState('foo-bar');
$sut->setState(PHP_INT_MAX);
$this->assertEquals(TimesheetQuery::STATE_ALL, $sut->getState());
$sut->setState(TimesheetQuery::STATE_STOPPED);

View File

@@ -0,0 +1,59 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Validator\Constraints;
use App\Entity\User;
use App\Validator\Constraints\Role;
use App\Validator\Constraints\RoleValidator;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* @covers \App\Validator\Constraints\RoleValidator
*/
class RoleValidatorTest extends TestCase
{
public function getValidRoles()
{
return [
[User::ROLE_CUSTOMER],
[User::ROLE_USER],
[User::ROLE_TEAMLEAD],
[User::ROLE_ADMIN],
[User::ROLE_SUPER_ADMIN],
];
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testConstraintIsInvalid()
{
$validator = new RoleValidator();
$validator->validate('foo', new NotBlank());
}
/**
* @dataProvider getValidRoles
*/
public function testConstraintWithValidRole($role)
{
$constraint = new Role();
$validator = new RoleValidator();
$validator->validate($role, $constraint);
// the above line would break if the role is invalid, we need the next assert to mark the test as valid
$this->assertNull(null);
}
public function testValidationError()
{
$this->markTestIncomplete(__CLASS__ . ': validation message not tested yet');
}
}

View File

@@ -40,15 +40,15 @@ class TimesheetVoterTest extends TestCase
public function getTestData()
{
$user0 = $this->getUser(0, 'ROLE_CUSTOMER');
$user1 = $this->getUser(1, 'ROLE_USER');
$user2 = $this->getUser(1, 'ROLE_TEAMLEAD');
$user0 = $this->getUser(0, User::ROLE_CUSTOMER);
$user1 = $this->getUser(1, User::ROLE_USER);
$user2 = $this->getUser(1, User::ROLE_TEAMLEAD);
return [
[$user0, false, new Customer(), ['edit'], VoterInterface::ACCESS_ABSTAIN],
[$user1, false, $this->getTimesheet($user1), ['edit'], VoterInterface::ACCESS_GRANTED],
[$user1, false, $this->getTimesheet($user0), ['edit'], VoterInterface::ACCESS_DENIED],
[$user2, true, $this->getTimesheet($user1), ['edit'], VoterInterface::ACCESS_GRANTED],
[$user0, false, new Customer(), [TimesheetVoter::EDIT], VoterInterface::ACCESS_ABSTAIN],
[$user1, false, $this->getTimesheet($user1), [TimesheetVoter::EDIT], VoterInterface::ACCESS_GRANTED],
[$user1, false, $this->getTimesheet($user0), [TimesheetVoter::EDIT], VoterInterface::ACCESS_DENIED],
[$user2, true, $this->getTimesheet($user1), [TimesheetVoter::EDIT], VoterInterface::ACCESS_GRANTED],
];
}