weekly quick-entry form (#2793)

This commit is contained in:
Kevin Papst
2021-10-18 11:12:46 +02:00
committed by GitHub
parent 64893e0a95
commit 9ab098af86
105 changed files with 3356 additions and 778 deletions

View File

@@ -527,7 +527,7 @@ class TimesheetControllerTest extends APIControllerBaseTest
'begin' => ($dateTime->createDateTime('- 7 hours'))->format('Y-m-d\TH:m:0'),
'end' => ($dateTime->createDateTime())->format('Y-m-d\TH:m:0'),
'description' => 'foo',
'exported' => true,
'billable' => false,
];
$this->request($client, '/api/timesheets/' . $timesheets[0]->getId(), 'PATCH', [], json_encode($data));
$this->assertTrue($client->getResponse()->isSuccessful());
@@ -537,7 +537,8 @@ class TimesheetControllerTest extends APIControllerBaseTest
self::assertApiResponseTypeStructure('TimesheetEntity', $result);
$this->assertNotEmpty($result['id']);
$this->assertEquals(25200, $result['duration']);
$this->assertEquals(1, $result['exported']);
$this->assertEquals('foo', $result['description']);
$this->assertFalse($result['billable']);
}
public function testPatchActionWithInvalidUser()

View File

@@ -0,0 +1,102 @@
<?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\Controller;
use App\Tests\DataFixtures\TimesheetFixtures;
/**
* @group integration
*/
class QuickEntryControllerTest extends ControllerBaseTest
{
public function testIsSecure()
{
$this->assertUrlIsSecured('/quick_entry');
}
public function testIndexAction()
{
$client = $this->getClientForAuthenticatedUser();
$this->request($client, '/quick_entry');
$this->assertTrue($client->getResponse()->isSuccessful());
$node = $client->getCrawler()->filter('section.content form[name=quick_entry_form]');
self::assertEquals(1, $node->filter('div.btn-group.week-picker-btn-group')->count());
self::assertEquals(1, $node->filter('input.btn-primary[type=submit]')->count());
$addBtn = $node->filter('button.btn-success[type=button]');
self::assertEquals(1, $addBtn->count());
self::assertNotNull($addBtn->attr('data-collection-prototype'));
self::assertNotNull($addBtn->attr('data-collection-holder'));
$rows = $client->getCrawler()->filter('section.content form[name=quick_entry_form] table.dataTable tbody tr:not(.summary)');
self::assertEquals(3, $rows->count());
$validate = $rows->getIterator()[0];
$columns = [];
foreach ($validate->childNodes as $childNode) {
if ($childNode instanceof \DOMText) {
continue;
}
if ($childNode instanceof \DOMElement && $childNode->tagName === 'td') {
$columns[] = $childNode;
}
}
// project + activity + 7 days (duration) + row totals
self::assertCount(10, $columns);
$this->assertPageActions($client, [
'back' => $this->createUrl('/timesheet/'),
'help' => 'https://www.kimai.org/documentation/weekly-times.html'
]);
}
public function testIndexActionWith()
{
$client = $this->getClientForAuthenticatedUser();
$fixture = new TimesheetFixtures();
$fixture->setAmount(50);
$fixture->setUser($this->getUserByRole());
$fixture->setStartDate(new \DateTime('-7 days'));
$this->importFixture($fixture);
$this->request($client, '/quick_entry');
$this->assertTrue($client->getResponse()->isSuccessful());
$node = $client->getCrawler()->filter('section.content form[name=quick_entry_form]');
self::assertEquals(1, $node->filter('div.btn-group.week-picker-btn-group')->count());
self::assertEquals(1, $node->filter('input.btn-primary[type=submit]')->count());
$addBtn = $node->filter('button.btn-success[type=button]');
self::assertEquals(1, $addBtn->count());
self::assertNotNull($addBtn->attr('data-collection-prototype'));
self::assertNotNull($addBtn->attr('data-collection-holder'));
$rows = $client->getCrawler()->filter('section.content form[name=quick_entry_form] table.dataTable tbody tr:not(.summary)');
self::assertGreaterThanOrEqual(3, $rows->count());
$validate = $rows->getIterator()[0];
$columns = [];
foreach ($validate->childNodes as $childNode) {
if ($childNode instanceof \DOMText) {
continue;
}
if ($childNode instanceof \DOMElement && $childNode->tagName === 'td') {
$columns[] = $childNode;
}
}
// project + activity + 7 days (duration) + row totals
self::assertCount(10, $columns);
$this->assertPageActions($client, [
'back' => $this->createUrl('/timesheet/'),
'help' => 'https://www.kimai.org/documentation/weekly-times.html'
]);
}
}

View File

@@ -44,6 +44,7 @@ class TimesheetControllerTest extends ControllerBaseTest
'visibility' => '#',
'download toolbar-action modal-ajax-form' => $this->createUrl('/timesheet/export/'),
'create modal-ajax-form' => $this->createUrl('/timesheet/create'),
'quick_entry create-ts' => $this->createUrl('/quick_entry'),
'help' => 'https://www.kimai.org/documentation/timesheet.html'
]);
}

View File

@@ -104,12 +104,8 @@ class TimesheetValidationTest extends KernelTestCase
$this->assertHasViolationForField($entity, 'customer');
}
public function testValidationCustomerInvisibleDoesNotTriggerOnStoppedEntites()
private function createStoppedTimesheet(Project $project, Activity $activity, ?int $id = null): Timesheet
{
$customer = (new Customer())->setVisible(false);
$project = (new Project())->setName('foo')->setCustomer($customer);
$activity = (new Activity())->setName('hello-world')->setProject($project);
$entity = new Timesheet();
$entity
->setUser(new User())
@@ -119,9 +115,39 @@ class TimesheetValidationTest extends KernelTestCase
->setEnd(new \DateTime())
;
if ($id !== null) {
$o = new \ReflectionClass($entity);
$p = $o->getProperty('id');
$p->setAccessible(true);
$p->setValue($entity, $id);
$p->setAccessible(false);
}
return $entity;
}
public function testValidationCustomerInvisibleDoesNotTriggerOnStoppedEntities()
{
$customer = (new Customer())->setVisible(false);
$project = (new Project())->setName('foo')->setCustomer($customer);
$activity = (new Activity())->setName('hello-world')->setProject($project);
$entity = $this->createStoppedTimesheet($project, $activity, 99);
$this->assertHasNoViolations($entity);
}
public function testValidationCustomerInvisibleDoesTriggerOnNewEntities()
{
$customer = (new Customer())->setVisible(false);
$project = (new Project())->setName('foo')->setCustomer($customer);
$activity = (new Activity())->setName('hello-world')->setProject($project);
$entity = $this->createStoppedTimesheet($project, $activity);
$this->assertHasViolationForField($entity, 'customer');
}
public function testValidationProjectInvisible()
{
$customer = new Customer();
@@ -139,24 +165,28 @@ class TimesheetValidationTest extends KernelTestCase
$this->assertHasViolationForField($entity, 'project');
}
public function testValidationProjectInvisibleDoesNotTriggerOnStoppedEntites()
public function testValidationProjectInvisibleDoesNotTriggerOnStoppedEntities()
{
$customer = new Customer();
$project = (new Project())->setName('foo')->setCustomer($customer)->setVisible(false);
$activity = (new Activity())->setName('hello-world')->setProject($project);
$entity = new Timesheet();
$entity
->setUser(new User())
->setActivity($activity)
->setProject($project)
->setBegin(new \DateTime())
->setEnd(new \DateTime())
;
$entity = $this->createStoppedTimesheet($project, $activity, 1);
$this->assertHasNoViolations($entity);
}
public function testValidationProjectInvisibleDoesTriggerOnNewEntities()
{
$customer = new Customer();
$project = (new Project())->setName('foo')->setCustomer($customer)->setVisible(false);
$activity = (new Activity())->setName('hello-world')->setProject($project);
$entity = $this->createStoppedTimesheet($project, $activity);
$this->assertHasViolationForField($entity, 'project');
}
public function testValidationActivityInvisible()
{
$customer = new Customer();
@@ -174,24 +204,28 @@ class TimesheetValidationTest extends KernelTestCase
$this->assertHasViolationForField($entity, 'activity');
}
public function testValidationActivityInvisibleDoesNotTriggerOnStoppedEntites()
public function testValidationActivityInvisibleDoesNotTriggerOnStoppedEntities()
{
$customer = new Customer();
$project = (new Project())->setName('foo')->setCustomer($customer);
$activity = (new Activity())->setName('hello-world')->setProject($project)->setVisible(false);
$entity = new Timesheet();
$entity
->setUser(new User())
->setActivity($activity)
->setProject($project)
->setBegin(new \DateTime())
->setEnd(new \DateTime())
;
$entity = $this->createStoppedTimesheet($project, $activity, 2);
$this->assertHasNoViolations($entity);
}
public function testValidationActivityInvisibleDoesTriggerOnNewEntities()
{
$customer = new Customer();
$project = (new Project())->setName('foo')->setCustomer($customer);
$activity = (new Activity())->setName('hello-world')->setProject($project)->setVisible(false);
$entity = $this->createStoppedTimesheet($project, $activity);
$this->assertHasViolationForField($entity, 'activity');
}
public function testValidationEndNotEarlierThanBegin()
{
$entity = $this->getEntity();

View File

@@ -0,0 +1,23 @@
<?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\EventSubscriber\Actions;
use App\EventSubscriber\Actions\QuickEntrySubscriber;
/**
* @covers \App\EventSubscriber\Actions\QuickEntrySubscriber
*/
class QuickEntrySubscriberTest extends AbstractActionsSubscriberTest
{
public function testEventName()
{
$this->assertGetSubscribedEvent(QuickEntrySubscriber::class, 'weekly_times');
}
}

View File

@@ -0,0 +1,28 @@
<?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\EventSubscriber;
use App\Event\ConfigureMainMenuEvent;
use App\EventSubscriber\MenuSubscriber;
use PHPUnit\Framework\TestCase;
/**
* @covers \App\EventSubscriber\MenuSubscriber
*/
class MenuSubscriberTest extends TestCase
{
public function testGetSubscribedEvents()
{
$events = MenuSubscriber::getSubscribedEvents();
$this->assertArrayHasKey(ConfigureMainMenuEvent::class, $events);
$methodName = $events[ConfigureMainMenuEvent::class][0];
$this->assertTrue(method_exists(MenuSubscriber::class, $methodName));
}
}

View File

@@ -71,6 +71,7 @@ class DurationStringToSecondsTransformerTest extends TestCase
['00:00', 0],
['0', null],
[null, null],
['87600000000:00:00', 315360000000000],
];
}
@@ -80,6 +81,8 @@ class DurationStringToSecondsTransformerTest extends TestCase
['xxx'],
[':::'],
['0::0'],
['87600000000:00:01'],
[315360000000001],
];
}

View File

@@ -98,4 +98,14 @@ class DurationTypeTest extends TypeTestCase
self::assertArrayNotHasKey('duration_presets', $view->vars);
}
public function testHasDurationInputClass()
{
$view = $this->factory->create(DurationType::class, 3600, [
'attr' => ['class' => 'testing']
])->createView();
self::assertArrayHasKey('class', $view->vars['attr']);
self::assertStringContainsString('duration-input testing', $view->vars['attr']['class']);
}
}

View File

@@ -0,0 +1,133 @@
<?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\Form\Type;
use App\Entity\Timesheet;
use App\Entity\User;
use App\Form\Type\QuickEntryTimesheetType;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Security\Core\Security;
/**
* @covers \App\Form\Type\QuickEntryTimesheetType
*/
class QuickEntryTimesheetTypeTest extends TypeTestCase
{
protected function getExtensions()
{
$auth = $this->createMock(Security::class);
$auth->method('getUser')->willReturn(new User());
$auth->method('isGranted')->willReturn(true);
$type = new QuickEntryTimesheetType($auth);
return [
new PreloadedExtension([$type], []),
];
}
public function getTestData()
{
yield [4.5, 16200];
yield ['4,5', 16200];
yield ['4:30', 16200];
yield ['4h30m', 16200];
}
/**
* @dataProvider getTestData
*/
public function testSubmitValidData($value, $expectedDuration)
{
$data = ['duration' => $value];
$model = $this->createDefaultModel();
$form = $this->factory->create(QuickEntryTimesheetType::class, $model);
$form->submit($data);
$this->assertTrue($form->isSynchronized());
$this->assertEquals($expectedDuration, $model->getDuration());
$this->assertEquals($expectedDuration, $model->getDuration(true));
}
private function createDefaultModel(): Timesheet
{
$begin = new \DateTime('2020-02-15 12:30:00');
$end = new \DateTime('2020-02-15 14:00:00');
$model = new Timesheet();
$model->setBegin($begin);
$model->setEnd($end);
return $model;
}
public function testPresetPopulatesView()
{
$view = $this->factory->create(QuickEntryTimesheetType::class, $this->createDefaultModel(), [
'duration_minutes' => 15,
'duration_hours' => 5,
])->createView();
$vars = $view->children['duration']->vars;
self::assertArrayHasKey('duration_presets', $vars);
self::assertCount(20, $vars['duration_presets']);
self::assertEquals('0:30', $vars['duration_presets'][1]);
self::assertEquals('4:45', $vars['duration_presets'][18]);
}
public function testPresetsAreNotGeneratedOnMissingHours()
{
$view = $this->factory->create(QuickEntryTimesheetType::class, $this->createDefaultModel())->createView();
$vars = $view->children['duration']->vars;
self::assertArrayNotHasKey('duration_presets', $vars);
}
public function testPresetsAreNotGeneratedOnMissingMinutes()
{
$view = $this->factory->create(QuickEntryTimesheetType::class, $this->createDefaultModel(), [
'duration_hours' => 5,
])->createView();
$vars = $view->children['duration']->vars;
self::assertArrayNotHasKey('duration_presets', $vars);
}
public function testPresetsAreNotGeneratedOnNegativeMinutes()
{
$view = $this->factory->create(QuickEntryTimesheetType::class, $this->createDefaultModel(), [
'duration_minutes' => -1,
'duration_hours' => 5,
])->createView();
$vars = $view->children['duration']->vars;
self::assertArrayNotHasKey('duration_presets', $vars);
}
public function testPresetsAreNotGeneratedOnNegativeHours()
{
$view = $this->factory->create(QuickEntryTimesheetType::class, $this->createDefaultModel(), [
'duration_minutes' => 5,
'duration_hours' => -1,
])->createView();
$vars = $view->children['duration']->vars;
self::assertArrayNotHasKey('duration_presets', $vars);
}
}

View File

@@ -0,0 +1,129 @@
<?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\Model;
use App\Entity\Activity;
use App\Entity\Project;
use App\Entity\Timesheet;
use App\Entity\User;
use App\Model\QuickEntryModel;
use PHPUnit\Framework\TestCase;
/**
* @covers \App\Model\QuickEntryModel
*/
class QuickEntryModelTest extends TestCase
{
public function testEmptyModel()
{
$sut = new QuickEntryModel();
self::assertTrue($sut->isPrototype());
self::assertNull($sut->getProject());
self::assertNull($sut->getActivity());
self::assertNull($sut->getUser());
self::assertEquals([], $sut->getNewTimesheet());
self::assertEquals([], $sut->getTimesheets());
self::assertNull($sut->getLatestEntry());
self::assertNull($sut->getFirstEntry());
self::assertFalse($sut->hasNewTimesheet());
self::assertFalse($sut->hasExistingTimesheet());
self::assertFalse($sut->hasTimesheetWithDuration());
}
public function testFullModel()
{
$user = new User();
$project = new Project();
$activity = new Activity();
$sut = new QuickEntryModel($user, $project, $activity);
self::assertFalse($sut->hasNewTimesheet());
$t = new Timesheet();
$t->setDuration(null);
$sut->addTimesheet($t);
self::assertFalse($sut->hasNewTimesheet());
$t = new Timesheet();
$t->setDuration(1);
$sut->addTimesheet($t);
self::assertTrue($sut->hasNewTimesheet());
self::assertCount(1, $sut->getNewTimesheet());
self::assertFalse($sut->isPrototype());
self::assertSame($project, $sut->getProject());
self::assertSame($activity, $sut->getActivity());
self::assertSame($user, $sut->getUser());
$t1 = new Timesheet();
$t1->setBegin(new \DateTime('2020-05-30'));
$sut->addTimesheet($t1);
$t2 = new Timesheet();
$t2->setBegin(new \DateTime('2020-01-19'));
$sut->addTimesheet($t2);
$t3 = new Timesheet();
$t3->setBegin(new \DateTime('2020-06-01'));
$sut->addTimesheet($t3);
$t4 = new Timesheet();
$t4->setBegin(new \DateTime('2020-01-09'));
$sut->addTimesheet($t4);
self::assertSame($t3, $sut->getLatestEntry());
self::assertEquals('2020-06-01', $sut->getLatestEntry()->getBegin()->format('Y-m-d'));
self::assertSame($t4, $sut->getFirstEntry());
self::assertEquals('2020-01-09', $sut->getFirstEntry()->getBegin()->format('Y-m-d'));
self::assertCount(5, $sut->getNewTimesheet());
self::assertCount(6, $sut->getTimesheets());
self::assertFalse($sut->hasExistingTimesheet());
self::assertTrue($sut->hasTimesheetWithDuration());
$sut->setProject(null);
self::assertNull($sut->getProject());
$project2 = new Project();
$sut->setProject($project2);
self::assertSame($project2, $sut->getProject());
$sut->setActivity(null);
self::assertNull($sut->getActivity());
$activity2 = new Activity();
$sut->setActivity($activity2);
self::assertSame($activity2, $sut->getActivity());
$sut->setTimesheets([$t1, $t2, $t3, $t4]);
self::assertCount(4, $sut->getNewTimesheet());
self::assertCount(4, $sut->getTimesheets());
}
public function testHasExistingTimesheet()
{
$sut = new QuickEntryModel();
self::assertTrue($sut->isPrototype());
self::assertFalse($sut->hasExistingTimesheet());
$mock = $this->createMock(Timesheet::class);
$mock->method('getId')->willReturn(1);
$sut->addTimesheet($mock);
self::assertTrue($sut->hasExistingTimesheet());
self::assertFalse($sut->isPrototype());
}
public function testDefaultModel()
{
$user = new User();
$project = new Project();
$activity = new Activity();
$sut = new QuickEntryModel($user, $project, $activity);
self::assertFalse($sut->isPrototype());
self::assertSame($project, $sut->getProject());
self::assertSame($activity, $sut->getActivity());
self::assertSame($user, $sut->getUser());
}
}

View File

@@ -0,0 +1,37 @@
<?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\Model;
use App\Model\QuickEntryModel;
use App\Model\QuickEntryWeek;
use PHPUnit\Framework\TestCase;
/**
* @covers \App\Model\QuickEntryWeek
*/
class QuickEntryWeekTest extends TestCase
{
public function testModel()
{
$date = new \DateTime();
$rows = [];
$sut = new QuickEntryWeek($date, $rows);
self::assertSame($date, $sut->getDate());
self::assertEquals([], $sut->getRows());
$rows = [
new QuickEntryModel()
];
$sut->setRows($rows);
self::assertSame($rows, $sut->getRows());
}
}

View File

@@ -31,7 +31,18 @@ class ProjectFormTypeQueryTest extends BaseFormTypeQueryTest
$sut->setWithCustomer(true);
self::assertTrue($sut->withCustomer());
self::assertNull($sut->getProjectToIgnore());
self::assertInstanceOf(ProjectFormTypeQuery::class, $sut->setProjectToIgnore($project));
$sut->setProjectToIgnore($project);
self::assertSame($project, $sut->getProjectToIgnore());
self::assertNotNull($sut->getProjectStart());
self::assertNotNull($sut->getProjectEnd());
$date = new \DateTime('2019-04-20');
$sut->setProjectStart($date);
self::assertSame($date, $sut->getProjectStart());
$date = new \DateTime('2020-01-01');
$sut->setProjectEnd($date);
self::assertSame($date, $sut->getProjectEnd());
}
}

View File

@@ -17,6 +17,7 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\Intl\Util\IntlTestHelper;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
/**
* @covers \App\Twig\LocaleFormatExtensions
@@ -82,6 +83,22 @@ class LocaleFormatExtensionsTest extends TestCase
}
}
public function testGetTests()
{
$tests = ['weekend', 'today'];
$i = 0;
$sut = $this->getSut('de', []);
$twigTests = $sut->getTests();
$this->assertCount(\count($tests), $twigTests);
/** @var TwigTest $test */
foreach ($twigTests as $test) {
$this->assertInstanceOf(TwigTest::class, $test);
$this->assertEquals($tests[$i++], $test->getName());
}
}
/**
* @param string $locale
* @param \DateTime|string $date
@@ -494,6 +511,39 @@ class LocaleFormatExtensionsTest extends TestCase
$this->assertEquals('0.00', $sut->durationDecimal(null));
}
private function getTest(string $name): TwigTest
{
$sut = $this->getSut('en', $this->localeEn);
foreach ($sut->getTests() as $test) {
if ($test->getName() === $name) {
return $test;
}
}
throw new \Exception('Unknown twig test: ' . $name);
}
public function testIsToday()
{
$test = $this->getTest('today');
self::assertTrue(\call_user_func($test->getCallable(), new \DateTime()));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('-1 day')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('+1 day')));
self::assertFalse(\call_user_func($test->getCallable(), new \stdClass()));
self::assertFalse(\call_user_func($test->getCallable(), null));
}
public function testIsWeekend()
{
$test = $this->getTest('weekend');
self::assertTrue(\call_user_func($test->getCallable(), new \DateTime('first saturday this month')));
self::assertTrue(\call_user_func($test->getCallable(), new \DateTime('first sunday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first monday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first friday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \stdClass()));
self::assertFalse(\call_user_func($test->getCallable(), null));
}
protected function getTimesheet($seconds)
{
$begin = new \DateTime();

View File

@@ -16,6 +16,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\ColorChoices
* @covers \App\Validator\Constraints\ColorChoicesValidator
*/
class ColorChoicesValidatorTest extends ConstraintValidatorTestCase

View File

@@ -16,6 +16,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\DateTimeFormat
* @covers \App\Validator\Constraints\DateTimeFormatValidator
*/
class DateTimeFormatValidatorTest extends ConstraintValidatorTestCase

View File

@@ -17,6 +17,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\Duration
* @covers \App\Validator\Constraints\DurationValidator
*/
class DurationValidatorTest extends ConstraintValidatorTestCase

View File

@@ -16,6 +16,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\HexColor
* @covers \App\Validator\Constraints\HexColorValidator
*/
class HexColorValidatorTest extends ConstraintValidatorTestCase

View File

@@ -17,6 +17,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\Project
* @covers \App\Validator\Constraints\ProjectValidator
*/
class ProjectValidatorTest extends ConstraintValidatorTestCase
@@ -48,4 +49,10 @@ class ProjectValidatorTest extends ConstraintValidatorTestCase
->setCode(ProjectConstraint::END_BEFORE_BEGIN_ERROR)
->assertRaised();
}
public function testGetTargets()
{
$constraint = new ProjectConstraint();
self::assertEquals('class', $constraint->getTargets());
}
}

View File

@@ -0,0 +1,123 @@
<?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\Activity;
use App\Entity\Project;
use App\Entity\Timesheet;
use App\Model\QuickEntryModel as QuickEntryModelEntity;
use App\Validator\Constraints\QuickEntryModel;
use App\Validator\Constraints\QuickEntryModelValidator;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\QuickEntryModel
* @covers \App\Validator\Constraints\QuickEntryModelValidator
*/
class QuickEntryModelValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator()
{
return new QuickEntryModelValidator();
}
public function testConstraintIsInvalid()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate(new Timesheet(), new NotBlank());
}
public function testInvalidValueThrowsException()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate(new Timesheet(), new QuickEntryModel());
}
public function testTriggersOnMissingProjectAndActivity()
{
$model = new QuickEntryModelEntity();
$timesheet = new Timesheet();
$timesheet->setBegin(new \DateTime());
$timesheet->setBegin(new \DateTime('+ 1 hour'));
$model->addTimesheet($timesheet);
$this->validator->validate($model, new QuickEntryModel());
$this->buildViolation('An activity needs to be selected.')
->atPath('property.path.activity')
->setCode(QuickEntryModel::ACTIVITY_REQUIRED)
->buildNextViolation('A project needs to be selected.')
->atPath('property.path.project')
->setCode(QuickEntryModel::PROJECT_REQUIRED)
->assertRaised();
}
public function testTriggersOnMissingActivity()
{
$model = new QuickEntryModelEntity();
$model->setProject(new Project());
$timesheet = new Timesheet();
$timesheet->setBegin(new \DateTime());
$timesheet->setBegin(new \DateTime('+ 1 hour'));
$model->addTimesheet($timesheet);
$this->validator->validate($model, new QuickEntryModel());
$this->buildViolation('An activity needs to be selected.')
->atPath('property.path.activity')
->setCode(QuickEntryModel::ACTIVITY_REQUIRED)
->assertRaised();
}
public function testTriggersOnMissingProject()
{
$model = new QuickEntryModelEntity();
$model->setActivity(new Activity());
$timesheet = new Timesheet();
$timesheet->setBegin(new \DateTime());
$timesheet->setBegin(new \DateTime('+ 1 hour'));
$model->addTimesheet($timesheet);
$this->validator->validate($model, new QuickEntryModel());
$this->buildViolation('A project needs to be selected.')
->atPath('property.path.project')
->setCode(QuickEntryModel::PROJECT_REQUIRED)
->assertRaised();
}
public function testDoesNotTriggerOnPrototype()
{
$model = new QuickEntryModelEntity();
$this->validator->validate($model, new QuickEntryModel());
$this->assertNoViolation();
}
public function testDoesNotTriggerOnProperlyFilled()
{
$model = new QuickEntryModelEntity();
$model->setActivity(new Activity());
$model->setProject(new Project());
$timesheet = new Timesheet();
$timesheet->setBegin(new \DateTime());
$timesheet->setBegin(new \DateTime('+ 1 hour'));
$model->addTimesheet($timesheet);
$this->validator->validate($model, new QuickEntryModel());
$this->assertNoViolation();
}
}

View File

@@ -0,0 +1,61 @@
<?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\Activity;
use App\Entity\Timesheet;
use App\Validator\Constraints\QuickEntryTimesheet;
use App\Validator\Constraints\QuickEntryTimesheetValidator;
use App\Validator\Constraints\TimesheetBasic;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\QuickEntryTimesheet
* @covers \App\Validator\Constraints\QuickEntryTimesheetValidator
*/
class QuickEntryTimesheetValidatorTest extends ConstraintValidatorTestCase
{
protected function createConstraint(): Constraint
{
return new QuickEntryTimesheet();
}
protected function createValidator()
{
return new QuickEntryTimesheetValidator([new TimesheetBasic()]);
}
public function testConstraintIsInvalid()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate(new Timesheet(), new NotBlank());
}
public function testInvalidValueThrowsException()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate(new Activity(), $this->createConstraint());
}
public function testNotTriggersOnEmptyDurationAndNewTimesheet()
{
$timesheet = new Timesheet();
$timesheet->setDuration(null);
$this->validator->validate($timesheet, $this->createConstraint());
$this->assertNoViolation();
}
}

View File

@@ -18,6 +18,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\Role
* @covers \App\Validator\Constraints\RoleValidator
*/
class RoleValidatorTest extends ConstraintValidatorTestCase

View File

@@ -19,6 +19,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\Team
* @covers \App\Validator\Constraints\TeamValidator
*/
class TeamValidatorTest extends ConstraintValidatorTestCase

View File

@@ -17,6 +17,7 @@ use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimeFormat
* @covers \App\Validator\Constraints\TimeFormatValidator
*/
class TimeFormatValidatorTest extends ConstraintValidatorTestCase

View File

@@ -0,0 +1,243 @@
<?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\Activity;
use App\Entity\Customer;
use App\Entity\Project;
use App\Entity\Timesheet;
use App\Validator\Constraints\TimesheetBasic;
use App\Validator\Constraints\TimesheetBasicValidator;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetBasic
* @covers \App\Validator\Constraints\TimesheetBasicValidator
*/
class TimesheetBasicValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator()
{
return $this->createMyValidator();
}
protected function createMyValidator()
{
return new TimesheetBasicValidator();
}
public function testConstraintIsInvalid()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate(new Timesheet(), new NotBlank());
}
public function testInvalidValueThrowsException()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate(new NotBlank(), new TimesheetBasic(['message' => 'myMessage']));
}
public function testEmptyTimesheet()
{
$timesheet = new Timesheet();
$this->validator->validate($timesheet, new TimesheetBasic(['message' => 'myMessage']));
$this->buildViolation('You must submit a begin date.')
->atPath('property.path.begin')
->setCode(TimesheetBasic::MISSING_BEGIN_ERROR)
->buildNextViolation('An activity needs to be selected.')
->atPath('property.path.activity')
->setCode(TimesheetBasic::MISSING_ACTIVITY_ERROR)
->buildNextViolation('A project needs to be selected.')
->atPath('property.path.project')
->setCode(TimesheetBasic::MISSING_PROJECT_ERROR)
->assertRaised();
}
public function testFutureBegin()
{
$begin = new \DateTime('+10 hour');
$timesheet = new Timesheet();
$timesheet->setBegin($begin);
$this->validator->validate($timesheet, new TimesheetBasic(['message' => 'myMessage']));
$this
->buildViolation('An activity needs to be selected.')
->atPath('property.path.activity')
->setCode(TimesheetBasic::MISSING_ACTIVITY_ERROR)
->buildNextViolation('A project needs to be selected.')
->atPath('property.path.project')
->setCode(TimesheetBasic::MISSING_PROJECT_ERROR)
// The test context is not able to handle calls to validate() - see ConstraintValidatorTestCase::createContext()
// therefor sub-constraints will not be executed :-(
/*
->buildNextViolation('The begin date cannot be in the future.')
->atPath('property.path.begin')
->setCode(TimesheetFutureTimes::BEGIN_IN_FUTURE_ERROR)
*/
->assertRaised();
}
public function testEndBeforeBegin()
{
$end = new \DateTime('-10 hour');
$begin = new \DateTime('-1 hour');
$timesheet = new Timesheet();
$timesheet->setBegin($begin);
$timesheet->setEnd($end);
$this->validator->validate($timesheet, new TimesheetBasic(['message' => 'myMessage']));
$this->buildViolation('End date must not be earlier then start date.')
->atPath('property.path.end')
->setCode(TimesheetBasic::END_BEFORE_BEGIN_ERROR)
->buildNextViolation('An activity needs to be selected.')
->atPath('property.path.activity')
->setCode(TimesheetBasic::MISSING_ACTIVITY_ERROR)
->buildNextViolation('A project needs to be selected.')
->atPath('property.path.project')
->setCode(TimesheetBasic::MISSING_PROJECT_ERROR)
->assertRaised();
}
public function testProjectMismatch()
{
$end = new \DateTime('-1 hour');
$begin = new \DateTime('-10 hour');
$activity = new Activity();
$project1 = new Project();
$project2 = new Project();
$project2->setCustomer(new Customer());
$activity->setProject($project1);
$timesheet = new Timesheet();
$timesheet
->setBegin($begin)
->setEnd($end)
->setActivity($activity)
->setProject($project2)
;
$this->validator->validate($timesheet, new TimesheetBasic(['message' => 'myMessage']));
$this->buildViolation('Project mismatch, project specific activity and timesheet project are different.')
->atPath('property.path.project')
->setCode(TimesheetBasic::ACTIVITY_PROJECT_MISMATCH_ERROR)
->assertRaised();
}
public function testDisabledValuesDuringStart()
{
$begin = new \DateTime('-10 hour');
$customer = new Customer();
$customer->setVisible(false);
$activity = new Activity();
$activity->setVisible(false);
$project = new Project();
$project->setVisible(false);
$project->setCustomer($customer);
$activity->setProject($project);
$timesheet = new Timesheet();
$timesheet
->setBegin($begin)
->setActivity($activity)
->setProject($project)
;
$this->validator->validate($timesheet, new TimesheetBasic(['message' => 'myMessage']));
$this->buildViolation('Cannot start a disabled activity.')
->atPath('property.path.activity')
->setCode(TimesheetBasic::DISABLED_ACTIVITY_ERROR)
->buildNextViolation('Cannot start a disabled project.')
->atPath('property.path.project')
->setCode(TimesheetBasic::DISABLED_PROJECT_ERROR)
->buildNextViolation('Cannot start a disabled customer.')
->atPath('property.path.customer')
->setCode(TimesheetBasic::DISABLED_CUSTOMER_ERROR)
->assertRaised();
}
public function getProjectStartEndTestData()
{
yield [new \DateTime(), new \DateTime(), [
['begin', TimesheetBasic::PROJECT_NOT_STARTED, 'The project has not started at that time.'],
['end', TimesheetBasic::PROJECT_NOT_STARTED, 'The project has not started at that time.'],
]];
yield [new \DateTime('-9 hour'), new \DateTime('-2 hour'), [
['begin', TimesheetBasic::PROJECT_NOT_STARTED, 'The project has not started at that time.'],
['end', TimesheetBasic::PROJECT_ALREADY_ENDED, 'The project is finished at that time.'],
]];
yield [new \DateTime('-19 hour'), new \DateTime('-12 hour'), [
['begin', TimesheetBasic::PROJECT_ALREADY_ENDED, 'The project is finished at that time.'],
['end', TimesheetBasic::PROJECT_ALREADY_ENDED, 'The project is finished at that time.'],
]];
yield [new \DateTime('-19 hour'), new \DateTime('-2 hour'), [
['end', TimesheetBasic::PROJECT_ALREADY_ENDED, 'The project is finished at that time.'],
]];
yield [new \DateTime('-9 hour'), new \DateTime(), [
['begin', TimesheetBasic::PROJECT_NOT_STARTED, 'The project has not started at that time.'],
]];
}
/**
* @dataProvider getProjectStartEndTestData
*/
public function testEndBeforeWithProjectStartAndEnd(\DateTime $start, \DateTime $end, array $violations)
{
$timesheet = new Timesheet();
$timesheet->setBegin(new \DateTime('-10 hour'));
$timesheet->setEnd(new \DateTime('-1 hour'));
$customer = new Customer();
$project = new Project();
$project->setStart($start);
$project->setEnd($end);
$project->setCustomer($customer);
$timesheet->setProject($project);
$timesheet->setActivity(new Activity());
$this->validator->validate($timesheet, new TimesheetBasic(['message' => 'myMessage']));
$assertion = null;
foreach ($violations as $violation) {
if (null === $assertion) {
$assertion = $this->buildViolation($violation[2])
->atPath('property.path.' . $violation[0])
->setCode($violation[1])
;
} else {
$assertion = $assertion->buildNextViolation($violation[2])
->atPath('property.path.' . $violation[0])
->setCode($violation[1])
;
}
}
$assertion->assertRaised();
}
public function testGetTargets()
{
$constraint = new TimesheetBasic();
self::assertEquals('class', $constraint->getTargets());
}
}

View File

@@ -0,0 +1,111 @@
<?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\Timesheet;
use App\Entity\User;
use App\Validator\Constraints\TimesheetExported;
use App\Validator\Constraints\TimesheetExportedValidator;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetExported
* @covers \App\Validator\Constraints\TimesheetExportedValidator
*/
class TimesheetExportedValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator()
{
return $this->createMyValidator(true);
}
protected function createMyValidator(bool $allowEdit)
{
$auth = $this->createMock(Security::class);
$auth->method('getUser')->willReturn(new User());
$auth->method('isGranted')->willReturnCallback(
function ($attributes, $subject = null) use ($allowEdit) {
switch ($attributes) {
case 'edit_exported_timesheet':
return $allowEdit;
}
return false;
}
);
return new TimesheetExportedValidator($auth);
}
public function testConstraintIsInvalid()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate(new Timesheet(), new NotBlank());
}
public function testInvalidValueThrowsException()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate(new NotBlank(), new TimesheetExported(['message' => 'myMessage']));
}
public function testTriggersOnMissingPermission()
{
$this->validator = $this->createMyValidator(false);
$this->validator->initialize($this->context);
$timesheet = new Timesheet();
$timesheet->setExported(true);
$this->validator->validate($timesheet, new TimesheetExported());
$this->buildViolation('This timesheet is already exported.')
->atPath('property.path.exported')
->setCode(TimesheetExported::TIMESHEET_EXPORTED)
->assertRaised();
}
public function testDoesNotTriggerWithPermission()
{
$this->validator = $this->createMyValidator(true);
$this->validator->initialize($this->context);
$timesheet = new Timesheet();
$timesheet->setExported(true);
$this->validator->validate($timesheet, new TimesheetExported());
$this->assertNoViolation();
}
public function testDoesNotTriggerIfNotExported()
{
$this->validator = $this->createMyValidator(false);
$this->validator->initialize($this->context);
$timesheet = new Timesheet();
$timesheet->setExported(false);
$this->validator->validate($timesheet, new TimesheetExported());
$this->assertNoViolation();
}
public function testGetTargets()
{
$constraint = new TimesheetExported();
self::assertEquals('class', $constraint->getTargets());
}
}

View File

@@ -19,6 +19,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetFutureTimes
* @covers \App\Validator\Constraints\TimesheetFutureTimesValidator
*/
class TimesheetFutureTimesValidatorTest extends ConstraintValidatorTestCase

View File

@@ -22,6 +22,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetLockdown
* @covers \App\Validator\Constraints\TimesheetLockdownValidator
*/
class TimesheetLockdownValidatorTest extends ConstraintValidatorTestCase

View File

@@ -19,6 +19,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetLongRunning
* @covers \App\Validator\Constraints\TimesheetLongRunningValidator
*/
class TimesheetLongRunningValidatorTest extends ConstraintValidatorTestCase
@@ -73,6 +74,33 @@ class TimesheetLongRunningValidatorTest extends ConstraintValidatorTestCase
->assertRaised();
}
public function testLongRunningTriggersOverMaximum()
{
$timesheet = new Timesheet();
$timesheet->setBegin(new \DateTime());
$timesheet->setEnd(new \DateTime());
$timesheet->setDuration(31536001);
$this->validator->validate($timesheet, new TimesheetLongRunning());
$this->buildViolation('Maximum duration exceeded.')
->atPath('property.path.duration')
->setCode(TimesheetLongRunning::MAXIMUM)
->assertRaised();
}
public function testLongRunningDoesNotTriggerOnMaximum()
{
$timesheet = new Timesheet();
$timesheet->setBegin(new \DateTime());
$timesheet->setEnd(new \DateTime());
$timesheet->setDuration(31536000);
$this->validator->validate($timesheet, new TimesheetLongRunning());
$this->assertNoViolation();
}
public function testLongRunningNotTriggersIfConfiguredToZero()
{
$this->validator = $this->createMyValidator(0);
@@ -114,4 +142,10 @@ class TimesheetLongRunningValidatorTest extends ConstraintValidatorTestCase
$this->validator->validate($timesheet, new TimesheetLongRunning());
$this->assertNoViolation();
}
public function testGetTargets()
{
$constraint = new TimesheetLongRunning();
self::assertEquals('class', $constraint->getTargets());
}
}

View File

@@ -20,6 +20,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetMultiUpdate
* @covers \App\Validator\Constraints\TimesheetMultiUpdateValidator
*/
class TimesheetMultiUpdateValidatorTest extends ConstraintValidatorTestCase

View File

@@ -17,6 +17,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetMultiUser
* @covers \App\Validator\Constraints\TimesheetMultiUserValidator
*/
class TimesheetMultiUserValidatorTest extends ConstraintValidatorTestCase

View File

@@ -20,6 +20,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetOverlapping
* @covers \App\Validator\Constraints\TimesheetOverlappingValidator
*/
class TimesheetOverlappingValidatorTest extends ConstraintValidatorTestCase

View File

@@ -24,6 +24,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\TimesheetRestart
* @covers \App\Validator\Constraints\TimesheetRestartValidator
*/
class TimesheetRestartValidatorTest extends ConstraintValidatorTestCase

View File

@@ -9,19 +9,15 @@
namespace App\Tests\Validator\Constraints;
use App\Entity\Activity;
use App\Entity\Customer;
use App\Entity\Project;
use App\Entity\Timesheet;
use App\Validator\Constraints\Timesheet as TimesheetConstraint;
use App\Validator\Constraints\TimesheetFutureTimes;
use App\Validator\Constraints\TimesheetValidator;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
use Symfony\Component\Validator\Test\ConstraintViolationAssertion;
/**
* @covers \App\Validator\Constraints\Timesheet
* @covers \App\Validator\Constraints\TimesheetValidator
*/
class TimesheetValidatorTest extends ConstraintValidatorTestCase
@@ -49,190 +45,4 @@ class TimesheetValidatorTest extends ConstraintValidatorTestCase
$this->validator->validate(new NotBlank(), new TimesheetConstraint(['message' => 'myMessage']));
}
public function testEmptyTimesheet()
{
$timesheet = new Timesheet();
$this->validator->validate($timesheet, new TimesheetConstraint(['message' => 'myMessage']));
$this->buildViolation('You must submit a begin date.')
->atPath('property.path.begin')
->setCode(TimesheetConstraint::MISSING_BEGIN_ERROR)
->buildNextViolation('A timesheet must have an activity.')
->atPath('property.path.activity')
->setCode(TimesheetConstraint::MISSING_ACTIVITY_ERROR)
->buildNextViolation('A timesheet must have a project.')
->atPath('property.path.project')
->setCode(TimesheetConstraint::MISSING_PROJECT_ERROR)
->assertRaised();
}
public function testFutureBegin()
{
$begin = new \DateTime('+10 hour');
$timesheet = new Timesheet();
$timesheet->setBegin($begin);
$this->validator->validate($timesheet, new TimesheetConstraint(['message' => 'myMessage']));
$this
->buildViolation('A timesheet must have an activity.')
->atPath('property.path.activity')
->setCode(TimesheetConstraint::MISSING_ACTIVITY_ERROR)
->buildNextViolation('A timesheet must have a project.')
->atPath('property.path.project')
->setCode(TimesheetConstraint::MISSING_PROJECT_ERROR)
// The test context is not able to handle calls to validate() - see ConstraintValidatorTestCase::createContext()
// therefor sub-constraints will not be executed :-(
/*
->buildNextViolation('The begin date cannot be in the future.')
->atPath('property.path.begin')
->setCode(TimesheetFutureTimes::BEGIN_IN_FUTURE_ERROR)
*/
->assertRaised();
}
public function testEndBeforeBegin()
{
$end = new \DateTime('-10 hour');
$begin = new \DateTime('-1 hour');
$timesheet = new Timesheet();
$timesheet->setBegin($begin);
$timesheet->setEnd($end);
$this->validator->validate($timesheet, new TimesheetConstraint(['message' => 'myMessage']));
$this->buildViolation('End date must not be earlier then start date.')
->atPath('property.path.end')
->setCode(TimesheetConstraint::END_BEFORE_BEGIN_ERROR)
->buildNextViolation('A timesheet must have an activity.')
->atPath('property.path.activity')
->setCode(TimesheetConstraint::MISSING_ACTIVITY_ERROR)
->buildNextViolation('A timesheet must have a project.')
->atPath('property.path.project')
->setCode(TimesheetConstraint::MISSING_PROJECT_ERROR)
->assertRaised();
}
public function testProjectMismatch()
{
$end = new \DateTime('-1 hour');
$begin = new \DateTime('-10 hour');
$activity = new Activity();
$project1 = new Project();
$project2 = new Project();
$activity->setProject($project1);
$timesheet = new Timesheet();
$timesheet
->setBegin($begin)
->setEnd($end)
->setActivity($activity)
->setProject($project2)
;
$this->validator->validate($timesheet, new TimesheetConstraint(['message' => 'myMessage']));
$this->buildViolation('Project mismatch, project specific activity and timesheet project are different.')
->atPath('property.path.project')
->setCode(TimesheetConstraint::ACTIVITY_PROJECT_MISMATCH_ERROR)
->assertRaised();
}
public function testDisabledValuesDuringStart()
{
$begin = new \DateTime('-10 hour');
$customer = new Customer();
$customer->setVisible(false);
$activity = new Activity();
$activity->setVisible(false);
$project = new Project();
$project->setVisible(false);
$project->setCustomer($customer);
$activity->setProject($project);
$timesheet = new Timesheet();
$timesheet
->setBegin($begin)
->setActivity($activity)
->setProject($project)
;
$this->validator->validate($timesheet, new TimesheetConstraint(['message' => 'myMessage']));
$this->buildViolation('Cannot start a disabled activity.')
->atPath('property.path.activity')
->setCode(TimesheetConstraint::DISABLED_ACTIVITY_ERROR)
->buildNextViolation('Cannot start a disabled project.')
->atPath('property.path.project')
->setCode(TimesheetConstraint::DISABLED_PROJECT_ERROR)
->buildNextViolation('Cannot start a disabled customer.')
->atPath('property.path.customer')
->setCode(TimesheetConstraint::DISABLED_CUSTOMER_ERROR)
->assertRaised();
}
public function getProjectStartEndTestData()
{
yield [new \DateTime(), new \DateTime(), [
['begin', TimesheetConstraint::PROJECT_NOT_STARTED, 'The project has not started at that time.'],
['end', TimesheetConstraint::PROJECT_NOT_STARTED, 'The project has not started at that time.'],
]];
yield [new \DateTime('-9 hour'), new \DateTime('-2 hour'), [
['begin', TimesheetConstraint::PROJECT_NOT_STARTED, 'The project has not started at that time.'],
['end', TimesheetConstraint::PROJECT_ALREADY_ENDED, 'The project is finished at that time.'],
]];
yield [new \DateTime('-19 hour'), new \DateTime('-12 hour'), [
['begin', TimesheetConstraint::PROJECT_ALREADY_ENDED, 'The project is finished at that time.'],
['end', TimesheetConstraint::PROJECT_ALREADY_ENDED, 'The project is finished at that time.'],
]];
yield [new \DateTime('-19 hour'), new \DateTime('-2 hour'), [
['end', TimesheetConstraint::PROJECT_ALREADY_ENDED, 'The project is finished at that time.'],
]];
yield [new \DateTime('-9 hour'), new \DateTime(), [
['begin', TimesheetConstraint::PROJECT_NOT_STARTED, 'The project has not started at that time.'],
]];
}
/**
* @dataProvider getProjectStartEndTestData
*/
public function testEndBeforeWithProjectStartAndEnd(\DateTime $start, \DateTime $end, array $violations)
{
$timesheet = new Timesheet();
$timesheet->setBegin(new \DateTime('-10 hour'));
$timesheet->setEnd(new \DateTime('-1 hour'));
$customer = new Customer();
$project = new Project();
$project->setStart($start);
$project->setEnd($end);
$project->setCustomer($customer);
$timesheet->setProject($project);
$timesheet->setActivity(new Activity());
$this->validator->validate($timesheet, new TimesheetConstraint(['message' => 'myMessage']));
/** @var ConstraintViolationAssertion $assertion */
$assertion = null;
foreach ($violations as $violation) {
if (null === $assertion) {
$assertion = $this->buildViolation($violation[2])
->atPath('property.path.' . $violation[0])
->setCode($violation[1])
;
} else {
$assertion = $assertion->buildNextViolation($violation[2])
->atPath('property.path.' . $violation[0])
->setCode($violation[1])
;
}
}
$assertion->assertRaised();
}
}

View File

@@ -19,6 +19,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\User
* @covers \App\Validator\Constraints\UserValidator
*/
class UserValidatorTest extends ConstraintValidatorTestCase