API endpoint for Timesheet entries (#332)

This commit is contained in:
Kevin Papst
2018-11-18 19:43:58 +01:00
committed by GitHub
parent 8cb52e22b1
commit b1c06eed7b
35 changed files with 1073 additions and 118 deletions

View File

@@ -139,11 +139,14 @@ abstract class APIControllerBaseTest extends ControllerBaseTest
* @param string $url
* @param string $method
* @param array $parameters
* @param string $content
* @return Crawler
*/
protected function request(Client $client, string $url, $method = 'GET', array $parameters = [])
protected function request(Client $client, string $url, $method = 'GET', array $parameters = [], string $content = null)
{
return $client->request($method, $this->createUrl($url), $parameters, [], ['HTTP_CONTENT_TYPE' => 'application/json']);
$server = ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'];
return $client->request($method, $this->createUrl($url), $parameters, [], $server, $content);
}
/**
@@ -167,4 +170,23 @@ abstract class APIControllerBaseTest extends ControllerBaseTest
json_decode($client->getResponse()->getContent(), true)
);
}
/**
* @param Response $response
* @param string[] $failedFields
*/
protected function assertApiCallValidationError(Response $response, array $failedFields)
{
$this->assertFalse($response->isSuccessful());
$result = json_decode($response->getContent(), true);
$this->assertArrayHasKey('errors', $result);
$this->assertArrayHasKey('children', $result['errors']);
$data = $result['errors']['children'];
foreach ($failedFields as $fieldName) {
$this->assertArrayHasKey($fieldName, $data);
$this->assertArrayHasKey('errors', $data[$fieldName]);
}
}
}

View File

@@ -75,7 +75,7 @@ class ActivityControllerTest extends APIControllerBaseTest
$hasProject = $expected[$i][0];
$this->assertStructure($activity, $hasProject);
if ($hasProject) {
$this->assertEquals($expected[$i][0], $activity['project_id']);
$this->assertEquals($expected[$i][0], $activity['project']);
}
}
}
@@ -100,7 +100,10 @@ class ActivityControllerTest extends APIControllerBaseTest
$result = json_decode($client->getResponse()->getContent(), true);
$this->assertInternalType('array', $result);
$this->assertStructure($result, false);
$expectedKeys = ['id', 'name', 'comment', 'visible'];
$actual = array_keys($result);
$this->assertEquals($expectedKeys, $actual);
}
public function testNotFound()
@@ -108,19 +111,18 @@ class ActivityControllerTest extends APIControllerBaseTest
$this->assertEntityNotFound(User::ROLE_USER, '/api/activities/2');
}
protected function assertStructure(array $result, $project = true)
protected function assertStructure(array $result, $full = true)
{
$expectedKeys = [
'id', 'name', 'comment', 'visible'
];
$expectedKeys = ['id', 'name', 'visible'];
if ($project) {
$expectedKeys[] = 'project_id';
if ($full) {
$expectedKeys = ['id', 'name', 'visible', 'project'];
}
$actual = array_keys($result);
sort($actual);
sort($expectedKeys);
$this->assertEquals(count($expectedKeys), count($actual), 'Activity entity has different amount of keys: ' . $result['id']);
$this->assertEquals($expectedKeys, $actual, 'Activity structure does not match');
}
}

View File

@@ -31,7 +31,7 @@ class CustomerControllerTest extends APIControllerBaseTest
$this->assertInternalType('array', $result);
$this->assertNotEmpty($result);
$this->assertEquals(1, count($result));
$this->assertStructure($result[0]);
$this->assertStructure($result[0], false);
}
public function testGetEntity()
@@ -41,7 +41,7 @@ class CustomerControllerTest extends APIControllerBaseTest
$result = json_decode($client->getResponse()->getContent(), true);
$this->assertInternalType('array', $result);
$this->assertStructure($result);
$this->assertStructure($result, true);
}
public function testNotFound()
@@ -49,16 +49,21 @@ class CustomerControllerTest extends APIControllerBaseTest
$this->assertEntityNotFound(User::ROLE_USER, '/api/customers/2');
}
protected function assertStructure(array $result)
protected function assertStructure(array $result, $full = true)
{
$expectedKeys = [
'id', 'name', 'number', 'comment', 'visible', 'company', 'contact', 'address', 'country', 'currency',
'phone', 'fax', 'mobile', 'mail', 'timezone'
];
$expectedKeys = ['id', 'name', 'visible'];
if ($full) {
$expectedKeys = [
'id', 'name', 'number', 'comment', 'visible', 'company', 'contact', 'address', 'country', 'currency',
'phone', 'fax', 'mobile', 'mail', 'timezone'
];
}
$actual = array_keys($result);
sort($actual);
sort($expectedKeys);
$this->assertEquals(count($expectedKeys), count($actual), 'Customer entity has different amount of keys');
$this->assertEquals($expectedKeys, $actual, 'Customer structure does not match');
}
}

View File

@@ -35,7 +35,7 @@ class ProjectControllerTest extends APIControllerBaseTest
$this->assertInternalType('array', $result);
$this->assertNotEmpty($result);
$this->assertEquals(1, count($result));
$this->assertStructure($result[0]);
$this->assertStructure($result[0], false);
}
protected function loadProjectTestData(Client $client)
@@ -87,8 +87,8 @@ class ProjectControllerTest extends APIControllerBaseTest
for ($i = 0; $i < count($expected); $i++) {
$project = $result[$i];
$compare = $expected[$i];
$this->assertStructure($project, $compare[0]);
$this->assertEquals($compare[1], $project['customer_id']);
$this->assertStructure($project, false);
$this->assertEquals($compare[1], $project['customer']);
}
}
@@ -119,21 +119,22 @@ class ProjectControllerTest extends APIControllerBaseTest
$this->assertEntityNotFound(User::ROLE_USER, '/api/projects/2');
}
protected function assertStructure(array $result, $complete = true)
protected function assertStructure(array $result, $full = true)
{
$expectedKeys = [
'id', 'name', 'comment', 'visible', 'budget', 'order_number', 'customer_id'
'id', 'name', 'comment', 'visible', 'budget', 'order_number', 'customer'
];
if (!$complete) {
if (!$full) {
$expectedKeys = [
'id', 'name', 'visible', 'budget', 'customer_id'
'id', 'name', 'visible', 'customer'
];
}
$actual = array_keys($result);
sort($actual);
sort($expectedKeys);
$this->assertEquals(count($expectedKeys), count($actual), 'Project entity has different amount of keys');
$this->assertEquals($expectedKeys, $actual, 'Project structure does not match');
}
}

View File

@@ -0,0 +1,187 @@
<?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\API;
use App\Entity\Activity;
use App\Entity\Customer;
use App\Entity\Project;
use App\Entity\User;
use App\Tests\DataFixtures\TimesheetFixtures;
/**
* @coversDefaultClass \App\API\TimesheetController
* @group integration
*/
class TimesheetControllerTest extends APIControllerBaseTest
{
public function setUp()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
$em = $client->getContainer()->get('doctrine.orm.entity_manager');
$fixture = new TimesheetFixtures();
$fixture
->setFixedRate(true)
->setHourlyRate(true)
->setAmount(10)
->setUser($this->getUserByRole($em, User::ROLE_USER))
->setStartDate(new \DateTime('-10 days'))
;
$this->importFixture($em, $fixture);
}
public function testIsSecure()
{
$this->assertUrlIsSecured('/api/timesheets');
}
public function testGetCollection()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
$this->assertAccessIsGranted($client, '/api/timesheets');
$result = json_decode($client->getResponse()->getContent(), true);
$this->assertInternalType('array', $result);
$this->assertNotEmpty($result);
$this->assertEquals(10, count($result));
$this->assertDefaultStructure($result[0], false);
}
public function testGetEntity()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
$this->assertAccessIsGranted($client, '/api/timesheets/1');
$result = json_decode($client->getResponse()->getContent(), true);
$this->assertInternalType('array', $result);
$this->assertDefaultStructure($result);
}
public function testPostAction()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
$data = [
'activity' => 1,
'project' => 1,
'begin' => (new \DateTime('- 8 hours'))->format('Y-m-d H:m'),
'end' => (new \DateTime())->format('Y-m-d H:m'),
'description' => 'foo',
'fixedRate' => 2016,
'hourlyRate' => 127
];
$this->request($client, '/api/timesheets', 'POST', [], json_encode($data));
$this->assertTrue($client->getResponse()->isSuccessful());
$result = json_decode($client->getResponse()->getContent(), true);
$this->assertInternalType('array', $result);
$this->assertDefaultStructure($result);
$this->assertNotEmpty($result['id']);
$this->assertEquals(28800, $result['duration']);
$this->assertEquals(2016, $result['rate']);
}
// check for project, as this is a required field. It will not be included in the select, as it is
// already filtered within the repository due to the hidden customer
public function testPostActionWithInvisibleProject()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
$em = $client->getContainer()->get('doctrine.orm.entity_manager');
$customer = (new Customer())->setName('foo-bar-1')->setVisible(false)->setCountry('DE')->setTimezone('Euopre/Berlin');
$em->persist($customer);
$project = (new Project())->setName('foo-bar-2')->setVisible(true)->setCustomer($customer);
$em->persist($project);
$activity = (new Activity())->setName('foo-bar-3')->setVisible(true);
$em->persist($activity);
$em->flush();
$data = [
'activity' => $activity->getId(),
'project' => $project->getId(),
'begin' => (new \DateTime('- 8 hours'))->format('Y-m-d H:m'),
'end' => (new \DateTime())->format('Y-m-d H:m'),
'description' => 'foo',
'fixedRate' => 2016,
'hourlyRate' => 127
];
$this->request($client, '/api/timesheets', 'POST', [], json_encode($data));
$this->assertApiCallValidationError($client->getResponse(), ['project']);
}
// check for activity, as this is a required field. It will not be included in the select, as it is
// already filtered within the repository due to the hidden flag
public function testPostActionWithInvisibleActivity()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
$em = $client->getContainer()->get('doctrine.orm.entity_manager');
$customer = (new Customer())->setName('foo-bar-1')->setVisible(true)->setCountry('DE')->setTimezone('Euopre/Berlin');
$em->persist($customer);
$project = (new Project())->setName('foo-bar-2')->setVisible(true)->setCustomer($customer);
$em->persist($project);
$activity = (new Activity())->setName('foo-bar-3')->setVisible(false);
$em->persist($activity);
$em->flush();
$data = [
'activity' => $activity->getId(),
'project' => $project->getId(),
'begin' => (new \DateTime('- 8 hours'))->format('Y-m-d H:m'),
'end' => (new \DateTime())->format('Y-m-d H:m'),
'description' => 'foo',
'fixedRate' => 2016,
'hourlyRate' => 127
];
$this->request($client, '/api/timesheets', 'POST', [], json_encode($data));
$this->assertApiCallValidationError($client->getResponse(), ['activity']);
}
public function testPostActionWithIdIsNotAllowed()
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
$data = [
'id' => 1,
'activity' => 1,
'project' => 1,
'begin' => (new \DateTime('- 8 hours'))->format('Y-m-d H:m'),
'end' => (new \DateTime())->format('Y-m-d H:m'),
'description' => 'foo',
'fixedRate' => 2016,
'hourlyRate' => 127
];
$this->request($client, '/api/timesheets', 'POST', [], json_encode($data));
$this->assertFalse($client->getResponse()->isSuccessful());
$this->assertEquals(400, $client->getResponse()->getStatusCode());
}
public function testNotFound()
{
$this->assertEntityNotFound(User::ROLE_USER, '/api/timesheets/20');
}
protected function assertDefaultStructure(array $result, $full = true)
{
$expectedKeys = [
'id', 'begin', 'end', 'duration', 'rate', 'activity', 'project', 'user'
];
if ($full) {
$expectedKeys = array_merge($expectedKeys, [
'description', 'fixed_rate', 'hourly_rate'
]);
}
$actual = array_keys($result);
sort($actual);
sort($expectedKeys);
$this->assertEquals($expectedKeys, $actual, 'Timesheet structure does not match');
}
}

View File

@@ -32,7 +32,7 @@ class UserControllerTest extends APIControllerBaseTest
$this->assertInternalType('array', $result);
$this->assertNotEmpty($result);
$this->assertEquals(6, count($result));
$this->assertStructure($result[0]);
$this->assertStructure($result[0], false);
}
public function testGetEntity()
@@ -50,15 +50,18 @@ class UserControllerTest extends APIControllerBaseTest
$this->assertEntityNotFound(User::ROLE_SUPER_ADMIN, '/api/users/99');
}
protected function assertStructure(array $result)
protected function assertStructure(array $result, $full = true)
{
$expectedKeys = [
'id', 'username', 'enabled', 'roles', 'alias', 'title', 'avatar'
];
$expectedKeys = ['id', 'username', 'enabled', 'alias'];
if ($full) {
$expectedKeys = ['id', 'username', 'enabled', 'roles', 'alias', 'title', 'avatar'];
}
$actual = array_keys($result);
sort($actual);
sort($expectedKeys);
$this->assertEquals(count($expectedKeys), count($actual), 'User entity has different amount of keys');
$this->assertEquals($expectedKeys, $actual, 'User structure does not match');
}
}

View File

@@ -0,0 +1,80 @@
<?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\Calendar;
use App\Calendar\TimesheetEntity;
use App\Entity\Activity;
use App\Entity\Customer;
use App\Entity\Project;
use App\Entity\Timesheet;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \App\Calendar\TimesheetEntity
*/
class TimesheetEntityTest extends TestCase
{
public function testConstruct()
{
$activity = new Activity();
$activity->setName('activity');
$customer = new Customer();
$customer->setName('customer');
$project = new Project();
$project->setName('project');
$project->setCustomer($customer);
$timesheet = new Timesheet();
$timesheet->setActivity($activity);
$timesheet->setProject($project);
$sut = new TimesheetEntity($timesheet);
$this->assertEquals('customer', $sut->getCustomer());
$this->assertEquals('project', $sut->getProject());
$this->assertEquals('activity', $sut->getTitle());
$sut->setId(13);
$this->assertEquals(13, $sut->getId());
$date = new \DateTime('-13 hours');
$sut->setStart($date);
$this->assertEquals($date, $sut->getStart());
$date = new \DateTime('-3 hours');
$sut->setEnd($date);
$this->assertEquals($date, $sut->getEnd());
$sut->setTitle('sdfsdf');
$this->assertEquals('sdfsdf', $sut->getTitle());
$sut->setCustomer('aaaaaaaa');
$this->assertEquals('aaaaaaaa', $sut->getCustomer());
$sut->setProject('bbbbbbbbbb');
$this->assertEquals('bbbbbbbbbb', $sut->getProject());
$sut->setActivity('cccccccc');
$this->assertEquals('cccccccc', $sut->getActivity());
$this->assertEquals('#f39c12', $sut->getBorderColor());
$sut->setBorderColor('#cccccc');
$this->assertEquals('#cccccc', $sut->getBorderColor());
$this->assertEquals('#f39c12', $sut->getBackgroundColor());
$sut->setBackgroundColor('#ffffff');
$this->assertEquals('#ffffff', $sut->getBackgroundColor());
$sut->setDescription('foo-bar');
$this->assertEquals('foo-bar', $sut->getDescription());
}
}

View File

@@ -82,11 +82,12 @@ abstract class ControllerBaseTest extends WebTestCase
* @param string $url
* @param string $method
* @param array $parameters
* @param string $content
* @return \Symfony\Component\DomCrawler\Crawler
*/
protected function request(Client $client, string $url, $method = 'GET', array $parameters = [])
protected function request(Client $client, string $url, $method = 'GET', array $parameters = [], string $content = null)
{
return $client->request($method, $this->createUrl($url), $parameters);
return $client->request($method, $this->createUrl($url), $parameters, [], [], $content);
}
/**

View File

@@ -39,6 +39,14 @@ class HelpControllerTest extends ControllerBaseTest
$this->assertContains('<a href="/en/help/">Back</a>', $client->getResponse()->getContent());
}
public function testMissingPage()
{
$client = $this->getClientForAuthenticatedUser();
$this->request($client, '/help/foo');
$this->assertFalse($client->getResponse()->isSuccessful());
$this->assertEquals(404, $client->getResponse()->getStatusCode());
}
public function testValidateRouteDoesNotAllowSpecialChars()
{
$client = $this->getClientForAuthenticatedUser();

View File

@@ -43,9 +43,40 @@ class TimesheetFixtures extends Fixture
* @var string
*/
protected $startDate = '2018-04-01';
/**
* @var bool
*/
protected $fixedRate = false;
/**
* @var bool
*/
protected $hourlyRate = false;
/**
* @param bool $fixedRate
* @return TimesheetFixtures
*/
public function setFixedRate(bool $fixedRate)
{
$this->fixedRate = $fixedRate;
return $this;
}
/**
* @param bool $hourlyRate
* @return TimesheetFixtures
*/
public function setHourlyRate(bool $hourlyRate)
{
$this->hourlyRate = $hourlyRate;
return $this;
}
/**
* @param string|\DateTime $date
* @return TimesheetFixtures
*/
public function setStartDate($date)
{
@@ -53,6 +84,8 @@ class TimesheetFixtures extends Fixture
$date = $date->format('Y-m-d');
}
$this->startDate = $date;
return $this;
}
/**
@@ -232,6 +265,14 @@ class TimesheetFixtures extends Fixture
->setRate(round(($duration / 3600) * $rate))
->setBegin($start);
if ($this->fixedRate) {
$entry->setFixedRate(rand(10, 100));
}
if ($this->hourlyRate) {
$entry->setHourlyRate($rate);
}
if ($setEndDate) {
$entry
->setEnd($end)

View File

@@ -88,8 +88,9 @@ class TimesheetTest extends AbstractEntityTest
public function testValidationProjectMismatch()
{
$project = (new Project())->setName('foo');
$project2 = (new Project())->setName('bar');
$customer = new Customer();
$project = (new Project())->setName('foo')->setCustomer($customer);
$project2 = (new Project())->setName('bar')->setCustomer($customer);
$activity = (new Activity())->setName('hello-world')->setProject($project);
$entity = new Timesheet();
@@ -103,6 +104,57 @@ class TimesheetTest extends AbstractEntityTest
$this->assertHasViolationForField($entity, 'project');
}
public function testValidationCustomerInvisible()
{
$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())
->setActivity($activity)
->setProject($project)
->setBegin(new \DateTime())
;
$this->assertHasViolationForField($entity, 'customer');
}
public function testValidationProjectInvisible()
{
$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())
;
$this->assertHasViolationForField($entity, 'project');
}
public function testValidationActivityInvisible()
{
$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())
;
$this->assertHasViolationForField($entity, 'activity');
}
public function testValidationEndNotEarlierThanBegin()
{
$entity = $this->getEntity();

View File

@@ -0,0 +1,39 @@
<?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\ConfigureAdminMenuEvent;
use KevinPapst\AdminLTEBundle\Event\SidebarMenuEvent;
use KevinPapst\AdminLTEBundle\Model\MenuItemModel;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
/**
* @covers \App\Event\ConfigureAdminMenuEvent
*/
class ConfigureAdminMenuEventTest extends TestCase
{
public function testGetterAndSetter()
{
$request = new Request();
$request->setLocale('de');
$event = new SidebarMenuEvent($request);
$admin = new MenuItemModel('admin', 'foo', 'bar');
$event->addItem($admin);
$event->addItem(new MenuItemModel('foo', 'foo', 'bar'));
$sut = new ConfigureAdminMenuEvent($request, $event);
$this->assertEquals($request, $sut->getRequest());
$this->assertEquals($event, $sut->getMenu());
$this->assertEquals($admin, $sut->getAdminMenu());
}
}

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\EventSubscriber;
use App\Entity\User;
use App\Event\DashboardEvent;
use App\Model\DashboardSection;
use PHPUnit\Framework\TestCase;
/**
* @covers \App\Event\DashboardEvent
*/
class DashboardEventTest extends TestCase
{
public function testGetterAndSetter()
{
$user = new User();
$user->setAlias('foo');
$sut = new DashboardEvent($user);
$this->assertEquals($user, $sut->getUser());
$this->assertEquals([], $sut->getSections());
$section = new DashboardSection('foo');
$sut->addSection($section);
$this->assertEquals([$section], $sut->getSections());
}
}

View File

@@ -0,0 +1,57 @@
<?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\Entity\User;
use App\Entity\UserPreference;
use App\Event\UserPreferenceEvent;
use PHPUnit\Framework\TestCase;
/**
* @covers \App\Event\UserPreferenceEvent
*/
class UserPreferenceEventTest extends TestCase
{
public function testGetterAndSetter()
{
$user = new User();
$user->setAlias('foo');
$pref = new UserPreference();
$pref->setName('foo')->setValue('bar');
$sut = new UserPreferenceEvent($user, []);
$this->assertEquals($user, $sut->getUser());
$this->assertEquals([], $sut->getPreferences());
$sut->addUserPreference($pref);
$this->assertEquals([$pref], $sut->getPreferences());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testDuplicatePreferenceThrowsException()
{
$user = new User();
$user->setAlias('foo');
$pref = new UserPreference();
$pref->setName('foo')->setValue('bar');
$pref2 = new UserPreference();
$pref2->setName('foo')->setValue('hello');
$sut = new UserPreferenceEvent($user, []);
$sut->addUserPreference($pref);
$sut->addUserPreference($pref2);
}
}

View File

@@ -36,7 +36,7 @@ class DebugRendererTest extends AbstractRendererTest
$rows = $data['entries'];
$this->assertEquals($expectedRows, count($rows));
foreach($rows as $row) {
foreach ($rows as $row) {
$this->assertEntryStructure($row);
}
@@ -75,7 +75,7 @@ class DebugRendererTest extends AbstractRendererTest
'customer.comment',
];
foreach($keys as $key) {
foreach ($keys as $key) {
$this->assertArrayHasKey($key, $model);
}
@@ -115,7 +115,7 @@ class DebugRendererTest extends AbstractRendererTest
'entry.customer_id',
];
foreach($keys as $key) {
foreach ($keys as $key) {
$this->assertArrayHasKey($key, $model);
}