Added tasks endpoints; Added more test

This commit is contained in:
Constantin Graf
2024-03-21 21:26:42 +01:00
parent 33eff16b6b
commit 4edfa7e941
33 changed files with 810 additions and 52 deletions

View File

@@ -26,7 +26,7 @@ class AddOrganizationMember implements AddsTeamMembers
*/
public function add(User $owner, Organization $organization, string $email, ?string $role = null): void
{
Gate::forUser($owner)->authorize('addTeamMember', $organization);
Gate::forUser($owner)->authorize('addTeamMember', $organization); // TODO: refactor after owner refactoring
$this->validate($organization, $email, $role);

View File

@@ -91,6 +91,7 @@ class ProjectController extends Controller
$this->checkPermission($organization, 'projects:update', $project);
$project->name = $request->input('name');
$project->color = $request->input('color');
$project->client_id = $request->input('project_id');
$project->save();
return new ProjectResource($project);

View File

@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Requests\V1\Task\TaskIndexRequest;
use App\Http\Requests\V1\Task\TaskStoreRequest;
use App\Http\Requests\V1\Task\TaskUpdateRequest;
use App\Http\Resources\V1\Task\TaskCollection;
use App\Http\Resources\V1\Task\TaskResource;
use App\Models\Organization;
use App\Models\Task;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;
class TaskController extends Controller
{
protected function checkPermission(Organization $organization, string $permission, ?Task $task = null): void
{
parent::checkPermission($organization, $permission);
if ($task !== null && $task->organization_id !== $organization->id) {
throw new AuthorizationException('Task does not belong to organization');
}
}
/**
* Get tasks
*
* @return TaskCollection<TaskResource>
*
* @throws AuthorizationException
*
* @operationId getTasks
*/
public function index(Organization $organization, TaskIndexRequest $request): TaskCollection
{
$this->checkPermission($organization, 'tasks:view');
$projectId = $request->input('project_id');
$query = Task::query()
->whereBelongsTo($organization, 'organization');
if ($projectId !== null) {
$query->where('project_id', '=', $projectId);
}
$tasks = $query->paginate();
return new TaskCollection($tasks);
}
/**
* Create task
*
* @throws AuthorizationException
*
* @operationId createTask
*/
public function store(Organization $organization, TaskStoreRequest $request): JsonResource
{
$this->checkPermission($organization, 'tasks:create');
$task = new Task();
$task->name = $request->input('name');
$task->project_id = $request->input('project_id');
$task->organization()->associate($organization);
$task->save();
return new TaskResource($task);
}
/**
* Update task
*
* @throws AuthorizationException
*
* @operationId updateTask
*/
public function update(Organization $organization, Task $task, TaskUpdateRequest $request): JsonResource
{
$this->checkPermission($organization, 'tasks:update', $task);
$task->name = $request->input('name');
$task->save();
return new TaskResource($task);
}
/**
* Delete task
*
* @throws AuthorizationException
*
* @operationId deleteTask
*/
public function destroy(Organization $organization, Task $task): JsonResponse
{
$this->checkPermission($organization, 'tasks:delete', $task);
$task->delete();
return response()
->json(null, 204);
}
}

View File

@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Task;
use App\Models\Organization;
use App\Models\Project;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
/**
* @property Organization $organization Organization from model binding
*/
class TaskIndexRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
*/
public function rules(): array
{
return [
'project_id' => [
'uuid',
new ExistsEloquent(Project::class, null, function (Builder $builder): Builder {
/** @var Builder<Project> $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
];
}
}

View File

@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Task;
use App\Models\Organization;
use App\Models\Project;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
/**
* @property Organization $organization Organization from model binding
*/
class TaskStoreRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
*/
public function rules(): array
{
return [
'name' => [
// TODO: unique
'required',
'string',
'min:1',
'max:255',
],
'project_id' => [
'required',
new ExistsEloquent(Project::class, null, function (Builder $builder): Builder {
/** @var Builder<Project> $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
];
}
}

View File

@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Task;
use App\Models\Organization;
use App\Models\Project;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
/**
* @property Organization $organization Organization from model binding
*/
class TaskUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
*/
public function rules(): array
{
return [
'name' => [
// TODO: unique
'required',
'string',
'min:1',
'max:255',
],
'project_id' => [
new ExistsEloquent(Project::class, null, function (Builder $builder): Builder {
/** @var Builder<Project> $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
];
}
}

View File

@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Task;
use App\Http\Resources\PaginatedResourceCollection;
use Illuminate\Http\Resources\Json\ResourceCollection;
class TaskCollection extends ResourceCollection implements PaginatedResourceCollection
{
/**
* The resource that this resource collects.
*
* @var string
*/
public $collects = TaskResource::class;
}

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Task;
use App\Http\Resources\V1\BaseResource;
use App\Models\Tag;
use App\Models\Task;
use Illuminate\Http\Request;
/**
* @property Task $resource
*/
class TaskResource extends BaseResource
{
/**
* Transform the resource into an array.
*
* @return array<string, string|bool|int|null>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID */
'id' => $this->resource->id,
/** @var string $name Name */
'name' => $this->resource->name,
/** @var string $project_id ID of the project */
'project_id' => $this->resource->project_id,
/** @var string $created_at When the tag was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
/** @var string $updated_at When the tag was last updated */
'updated_at' => $this->formatDateTime($this->resource->updated_at),
];
}
}

View File

@@ -9,12 +9,15 @@ use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
/**
* @property string $id
* @property string $name
* @property string $project_id
* @property string $organization_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Project $project
* @property-read Organization $organization
*

View File

@@ -20,7 +20,6 @@ use Dedoc\Scramble\Support\Generator\SecuritySchemes\OAuthFlow;
use Filament\Forms\Components\Section;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;

View File

@@ -59,6 +59,10 @@ class JetstreamServiceProvider extends ServiceProvider
'projects:create',
'projects:update',
'projects:delete',
'tasks:view',
'tasks:create',
'tasks:update',
'tasks:delete',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
@@ -87,6 +91,10 @@ class JetstreamServiceProvider extends ServiceProvider
'projects:create',
'projects:update',
'projects:delete',
'tasks:view',
'tasks:create',
'tasks:update',
'tasks:delete',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
@@ -106,6 +114,7 @@ class JetstreamServiceProvider extends ServiceProvider
Jetstream::role('employee', 'Employee', [
'projects:view',
'tags:view',
'tasks:view',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',

View File

@@ -30,7 +30,7 @@ class OrganizationFactory extends Factory
public function withOwner(?User $owner = null): self
{
return $this->state(fn (array $attributes) => [
'user_id' => $owner === null ? User::factory() : $owner,
'user_id' => $owner === null ? User::factory() : $owner->getKey(),
]);
}
}

View File

@@ -28,6 +28,7 @@ class UserFactory extends Factory
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'two_factor_secret' => null,
'two_factor_confirmed_at' => null,
'two_factor_recovery_codes' => null,
'remember_token' => Str::random(10),
'profile_photo_path' => null,

View File

@@ -8,6 +8,7 @@ use App\Http\Controllers\Api\V1\MemberController;
use App\Http\Controllers\Api\V1\OrganizationController;
use App\Http\Controllers\Api\V1\ProjectController;
use App\Http\Controllers\Api\V1\TagController;
use App\Http\Controllers\Api\V1\TaskController;
use App\Http\Controllers\Api\V1\TimeEntryController;
use Illuminate\Support\Facades\Route;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -69,6 +70,14 @@ Route::middleware('auth:api')->prefix('v1')->name('v1.')->group(static function
Route::delete('/organizations/{organization}/clients/{client}', [ClientController::class, 'destroy'])->name('destroy');
});
// Task routes
Route::name('tasks.')->group(static function () {
Route::get('/organizations/{organization}/tasks', [TaskController::class, 'index'])->name('index');
Route::post('/organizations/{organization}/tasks', [TaskController::class, 'store'])->name('store');
Route::put('/organizations/{organization}/tasks/{task}', [TaskController::class, 'update'])->name('update');
Route::delete('/organizations/{organization}/tasks/{task}', [TaskController::class, 'destroy'])->name('destroy');
});
// Import routes
Route::name('import.')->group(static function () {
Route::post('/organizations/{organization}/import', [ImportController::class, 'import'])->name('import');

View File

@@ -14,6 +14,19 @@ class ProfileInformationTest extends TestCase
{
use RefreshDatabase;
public function test_show_profile_information_succeeds(): void
{
// Arrange
$user = User::factory()->withPersonalOrganization()->create();
$this->actingAs($user);
// Act
$response = $this->get('/user/profile');
// Assert
$response->assertSuccessful();
}
public function test_profile_information_can_be_updated(): void
{
// Arrange

View File

@@ -37,6 +37,6 @@ class RemoveTeamMemberTest extends TestCase
$response = $this->delete('/teams/'.$user->currentTeam->id.'/members/'.$user->id);
$response->assertStatus(403);
$response->assertForbidden();
}
}

View File

@@ -18,11 +18,16 @@ class ApiEndpointTestAbstract extends TestCase
* @param array<string> $permissions
* @return object{user: User, organization: Organization}
*/
protected function createUserWithPermission(array $permissions): object
protected function createUserWithPermission(array $permissions, bool $isOwner = false): object
{
Jetstream::role('custom-test', 'Custom Test', $permissions)->description('Role custom for testing');
$organization = Organization::factory()->create();
Jetstream::role('custom-test', 'Custom Test', $permissions)
->description('Role custom for testing');
$user = User::factory()->create();
if ($isOwner) {
$organization = Organization::factory()->withOwner($user)->create();
} else {
$organization = Organization::factory()->create();
}
$organization->users()->attach($user, [
'role' => 'custom-test',
]);

View File

@@ -23,7 +23,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
$response = $this->getJson(route('api.v1.clients.index', [$data->organization->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_index_endpoint_returns_list_of_all_clients_of_organization_ordered_by_created_at_desc_per_default(): void
@@ -66,7 +66,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_store_endpoint_creates_new_client(): void
@@ -106,7 +106,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_update_endpoint_fails_if_user_is_not_part_of_client_organization(): void
@@ -126,7 +126,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
$this->assertDatabaseHas(Client::class, [
'id' => $client->getKey(),
'name' => $client->name,
@@ -173,7 +173,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.clients.destroy', [$data->organization->getKey(), $client->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_destroy_endpoint_fails_if_user_is_not_part_of_client_organization(): void
@@ -190,7 +190,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.clients.destroy', [$data->organization->getKey(), $client->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
$this->assertDatabaseHas(Client::class, [
'id' => $client->getKey(),
'name' => $client->name,

View File

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Tests\Unit\Endpoint\Api\V1;
use App\Models\Organization;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\Importers\ReportDto;
use App\Service\Import\ImportService;
use Laravel\Passport\Passport;
@@ -28,7 +29,35 @@ class ImportEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_import_return_error_message_if_import_fails(): void
{
$user = $this->createUserWithPermission([
'import',
]);
$this->mock(ImportService::class, function (MockInterface $mock) use (&$user): void {
$mock->shouldReceive('import')
->withArgs(function (Organization $organization, string $importerType, string $data) use (&$user): bool {
return $organization->is($user->organization) && $importerType === 'toggl_time_entries' && $data === 'some data';
})
->andThrow(new ImportException('This is a test error!'))
->once();
});
Passport::actingAs($user->user);
// Act
$response = $this->postJson(route('api.v1.import.import', ['organization' => $user->organization->id]), [
'type' => 'toggl_time_entries',
'data' => 'some data',
]);
// Assert
$response->assertStatus(400);
$response->assertExactJson([
'message' => 'This is a test error!',
]);
}
public function test_import_calls_import_service_if_user_has_permission(): void

View File

@@ -8,7 +8,7 @@ use App\Models\Organization;
use App\Models\User;
use Laravel\Passport\Passport;
class UserEndpointTest extends ApiEndpointTestAbstract
class MemberEndpointTest extends ApiEndpointTestAbstract
{
public function test_index_returns_members_of_organization(): void
{
@@ -25,6 +25,29 @@ class UserEndpointTest extends ApiEndpointTestAbstract
$response->assertStatus(200);
}
public function test_invite_placeholder_succeeds_if_data_is_valid(): void
{
$data = $this->createUserWithPermission([
'users:invite-placeholder',
], true);
$user = User::factory()->create([
'is_placeholder' => true,
]);
$data->organization->users()->attach($user, [
'role' => 'placeholder',
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.users.invite-placeholder', [
'organization' => $data->organization->id,
'user' => $user->id,
]));
// Assert
$response->assertStatus(204);
}
public function test_invite_placeholder_fails_if_user_does_not_have_permission(): void
{
// Arrange
@@ -40,7 +63,7 @@ class UserEndpointTest extends ApiEndpointTestAbstract
$response = $this->postJson(route('api.v1.users.invite-placeholder', ['organization' => $data->organization->id, 'user' => $user->id]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_invite_placeholder_fails_if_user_is_not_part_of_organization(): void
@@ -60,7 +83,7 @@ class UserEndpointTest extends ApiEndpointTestAbstract
$response = $this->postJson(route('api.v1.users.invite-placeholder', ['organization' => $data->organization->id, 'user' => $user->id]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_invite_placeholder_returns_400_if_user_is_not_placeholder(): void

View File

@@ -20,7 +20,7 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
$response = $this->getJson(route('api.v1.organizations.show', [$data->organization->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_show_endpoint_returns_organization(): void
@@ -53,7 +53,7 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_update_endpoint_updates_project(): void

View File

@@ -24,7 +24,7 @@ class ProjectEndpointTest extends ApiEndpointTestAbstract
$response = $this->getJson(route('api.v1.projects.index', [$data->organization->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_index_endpoint_returns_list_of_all_projects_of_organization(): void
@@ -58,7 +58,7 @@ class ProjectEndpointTest extends ApiEndpointTestAbstract
$response = $this->getJson(route('api.v1.projects.show', [$data->organization->getKey(), $project->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_show_endpoint_fails_if_user_has_no_permission_to_view_projects(): void
@@ -73,7 +73,7 @@ class ProjectEndpointTest extends ApiEndpointTestAbstract
$response = $this->getJson(route('api.v1.projects.show', [$data->organization->getKey(), $project->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_show_endpoint_returns_project(): void
@@ -108,7 +108,7 @@ class ProjectEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_store_endpoint_creates_new_project(): void
@@ -180,7 +180,7 @@ class ProjectEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_update_endpoint_fails_if_user_has_no_permission_to_update_projects(): void
@@ -199,7 +199,7 @@ class ProjectEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_update_endpoint_updates_project(): void
@@ -240,7 +240,7 @@ class ProjectEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.projects.destroy', [$data->organization->getKey(), $project->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_destroy_endpoint_fails_if_user_has_no_permission_to_delete_projects(): void
@@ -255,7 +255,7 @@ class ProjectEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.projects.destroy', [$data->organization->getKey(), $project->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_destroy_endpoint_deletes_project(): void

View File

@@ -23,7 +23,7 @@ class TagEndpointTest extends ApiEndpointTestAbstract
$response = $this->getJson(route('api.v1.tags.index', [$data->organization->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_index_endpoint_returns_list_of_all_tags_of_organization_ordered_by_created_at_desc_per_default(): void
@@ -66,7 +66,7 @@ class TagEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_store_endpoint_creates_new_tag(): void
@@ -106,7 +106,7 @@ class TagEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_update_endpoint_fails_if_user_is_not_part_of_tag_organization(): void
@@ -126,7 +126,7 @@ class TagEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
$this->assertDatabaseHas(Tag::class, [
'id' => $tag->getKey(),
'name' => $tag->name,
@@ -173,7 +173,7 @@ class TagEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.tags.destroy', [$data->organization->getKey(), $tag->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_destroy_endpoint_fails_if_user_is_not_part_of_tag_organization(): void
@@ -190,7 +190,7 @@ class TagEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.tags.destroy', [$data->organization->getKey(), $tag->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
$this->assertDatabaseHas(Tag::class, [
'id' => $tag->getKey(),
'name' => $tag->name,

View File

@@ -0,0 +1,243 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Endpoint\Api\V1;
use App\Models\Project;
use App\Models\Task;
use Laravel\Passport\Passport;
class TaskEndpointTest extends ApiEndpointTestAbstract
{
public function test_index_endpoint_fails_if_user_has_no_permission_to_view_tasks(): void
{
// Arrange
$data = $this->createUserWithPermission([
]);
Task::factory()->forOrganization($data->organization)->createMany(4);
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.tasks.index', [$data->organization->getKey()]));
// Assert
$response->assertForbidden();
}
public function test_index_endpoint_returns_list_of_all_tasks_of_organization(): void
{
// Arrange
$data = $this->createUserWithPermission([
'tasks:view',
]);
$tasks = Task::factory()->forOrganization($data->organization)->createMany(4);
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.tasks.index', [$data->organization->getKey()]));
// Assert
$response->assertStatus(200);
$response->assertJsonCount(4, 'data');
}
public function test_index_endpoint_returns_list_of_all_tasks_of_organization_filtered_by_project(): void
{
// Arrange
$data = $this->createUserWithPermission([
'tasks:view',
]);
$project = Project::factory()->forOrganization($data->organization)->create();
Task::factory()->forOrganization($data->organization)->createMany(4);
Task::factory()->forOrganization($data->organization)->forProject($project)->createMany(2);
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.tasks.index', [
$data->organization->getKey(),
'project_id' => $project->getKey(),
]));
// Assert
$response->assertStatus(200);
$response->assertJsonCount(2, 'data');
}
public function test_index_endpoint_validation_fails_if_project_id_does_not_belong_to_organization(): void
{
// Arrange
$data = $this->createUserWithPermission([
'tasks:view',
]);
$otherData = $this->createUserWithPermission([
'tasks:view',
]);
$project = Project::factory()->forOrganization($otherData->organization)->create();
Task::factory()->forOrganization($data->organization)->createMany(4);
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.tasks.index', [
$data->organization->getKey(),
'project_id' => $project->getKey(),
]));
// Assert
$response->assertStatus(422);
$response->assertInvalid([
'project_id',
]);
}
public function test_store_endpoint_fails_if_user_has_no_permission_to_create_tags()
{
// Arrange
$data = $this->createUserWithPermission([
]);
$project = Project::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.tasks.store', [$data->organization->getKey()]), [
'name' => 'Task 1',
'project_id' => $project->getKey(),
]);
// Assert
$response->assertForbidden();
$this->assertDatabaseMissing(Task::class, [
'name' => 'Task 1',
]);
}
public function test_store_endpoint_creates_new_task_if_user_has_permission_to_create_tasks()
{
// Arrange
$data = $this->createUserWithPermission([
'tasks:create',
]);
$project = Project::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.tasks.store', [$data->organization->getKey()]), [
'name' => 'Task 1',
'project_id' => $project->getKey(),
]);
// Assert
$response->assertStatus(201);
$this->assertDatabaseHas(Task::class, [
'name' => 'Task 1',
'project_id' => $project->getKey(),
'organization_id' => $data->organization->id,
]);
}
public function test_update_endpoint_fails_if_user_has_no_permission(): void
{
// Arrange
$data = $this->createUserWithPermission([
]);
$task = Task::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.tasks.update', [$data->organization->getKey(), $task->getKey()]), [
'name' => 'Updated Task',
]);
// Assert
$response->assertForbidden();
$this->assertDatabaseHas(Task::class, [
'id' => $task->getKey(),
'name' => $task->name,
]);
$this->assertDatabaseMissing(Task::class, [
'id' => $task->getKey(),
'name' => 'Updated Task',
]);
}
public function test_update_endpoint_updates_task_if_user_has_permission(): void
{
// Arrange
$data = $this->createUserWithPermission([
'tasks:update',
]);
$task = Task::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.tasks.update', [$data->organization->getKey(), $task->getKey()]), [
'name' => 'Updated Task',
]);
// Assert
$response->assertStatus(200);
$this->assertDatabaseHas(Task::class, [
'id' => $task->getKey(),
'name' => 'Updated Task',
]);
}
public function test_delete_endpoint_deletes_tasks_if_user_has_permission(): void
{
// Arrange
$data = $this->createUserWithPermission([
'tasks:delete',
]);
$task = Task::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.tasks.destroy', [$data->organization->getKey(), $task->getKey()]));
// Assert
$response->assertStatus(204);
$this->assertDatabaseMissing(Task::class, [
'id' => $task->getKey(),
]);
}
public function test_delete_endpoint_fails_if_user_has_no_permission_to_delete_tasks(): void
{
// Arrange
$data = $this->createUserWithPermission([
]);
$task = Task::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.tasks.destroy', [$data->organization->getKey(), $task->getKey()]));
// Assert
$response->assertForbidden();
$this->assertDatabaseHas(Task::class, [
'id' => $task->getKey(),
]);
}
public function test_delete_endpoint_fails_if_task_does_not_belong_to_organization(): void
{
// Arrange
$data = $this->createUserWithPermission([
'tasks:delete',
]);
$otherData = $this->createUserWithPermission([
'tasks:delete',
]);
$task = Task::factory()->forOrganization($otherData->organization)->create();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.tasks.destroy', [$data->organization->getKey(), $task->getKey()]));
// Assert
$response->assertForbidden();
$this->assertDatabaseHas(Task::class, [
'id' => $task->getKey(),
]);
}
}

View File

@@ -26,7 +26,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
$response = $this->getJson(route('api.v1.time-entries.index', [$data->organization->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_index_endpoint_fails_if_user_has_no_permission_to_view_time_entries_for_others_but_wants_all_entries(): void
@@ -41,7 +41,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
$response = $this->getJson(route('api.v1.time-entries.index', [$data->organization->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_index_endpoint_returns_time_entries_for_current_user(): void
@@ -323,7 +323,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_store_endpoint_fails_if_user_already_has_active_time_entry_and_tries_to_start_new_one(): void
@@ -463,7 +463,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_store_endpoint_creates_new_time_entry_for_other_user_in_organization(): void
@@ -520,7 +520,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_update_endpoint_fails_if_user_is_not_part_of_time_entry_organization(): void
@@ -547,7 +547,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_update_endpoint_fails_if_user_has_no_permission_to_update_time_entries_for_other_users_in_organization(): void
@@ -575,7 +575,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_update_endpoint_updates_time_entry_for_current_user(): void
@@ -656,7 +656,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.time-entries.destroy', [$data->organization->getKey(), $timeEntry->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_destroy_endpoint_fails_if_user_tries_to_delete_non_existing_time_entry(): void
@@ -686,7 +686,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.time-entries.destroy', [$data->organization->getKey(), $timeEntry->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_destroy_endpoint_fails_if_user_has_no_permission_to_delete_time_entries_for_other_users_in_organization(): void
@@ -706,7 +706,7 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
$response = $this->deleteJson(route('api.v1.time-entries.destroy', [$data->organization->getKey(), $timeEntry->getKey()]));
// Assert
$response->assertStatus(403);
$response->assertForbidden();
}
public function test_destroy_endpoint_deletes_own_time_entry(): void

View File

@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Endpoint\Web;
use App\Models\User;
class DashboardEndpointTest extends EndpointTestAbstract
{
public function test_showing_dashboard_succeeds_for_empty_user_with_no_data_entries(): void
{
// Arrange
$user = User::factory()->withPersonalOrganization()->create();
$this->actingAs($user);
// Act
$response = $this->get('/dashboard');
// Assert
$response->assertSuccessful();
}
}

View File

@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Endpoint\Web;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
abstract class EndpointTestAbstract extends TestCase
{
use RefreshDatabase;
}

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Service\Import;
use App\Models\Organization;
use App\Service\Import\ImportService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ImportServiceTest extends TestCase
{
use RefreshDatabase;
public function test_import_gets_importer_from_provider_runs_importer_and_returns_report(): void
{
// Arrange
$organization = Organization::factory()->create();
$data = file_get_contents(storage_path('tests/toggl_time_entries_import_test_1.csv'));
// Act
$importService = app(ImportService::class);
$report = $importService->import($organization, 'toggl_time_entries', $data);
// Assert
$this->assertSame(2, $report->timeEntriesCreated);
$this->assertSame(2, $report->tagsCreated);
$this->assertSame(1, $report->tasksCreated);
$this->assertSame(1, $report->usersCreated);
$this->assertSame(2, $report->projectsCreated);
$this->assertSame(1, $report->clientsCreated);
}
}

View File

@@ -18,7 +18,7 @@ class ClockifyProjectsImporterTest extends ImporterTestAbstract
$data = file_get_contents(storage_path('tests/clockify_projects_import_test_1.csv'));
// Act
$importer->importData($data, []);
$importer->importData($data);
// Assert
$this->checkTestScenarioProjectsOnlyAfterImport();
@@ -31,12 +31,12 @@ class ClockifyProjectsImporterTest extends ImporterTestAbstract
$importer = new ClockifyProjectsImporter();
$importer->init($organization);
$data = file_get_contents(storage_path('tests/clockify_projects_import_test_1.csv'));
$importer->importData($data, []);
$importer->importData($data);
$importer = new ClockifyProjectsImporter();
$importer->init($organization);
// Act
$importer->importData($data, []);
$importer->importData($data);
// Assert
$this->checkTestScenarioProjectsOnlyAfterImport();

View File

@@ -19,7 +19,7 @@ class ClockifyTimeEntriesImporterTest extends ImporterTestAbstract
$data = file_get_contents(storage_path('tests/clockify_time_entries_import_test_1.csv'));
// Act
$importer->importData($data, []);
$importer->importData($data);
// Assert
$testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries();
@@ -48,12 +48,12 @@ class ClockifyTimeEntriesImporterTest extends ImporterTestAbstract
$importer = new ClockifyTimeEntriesImporter();
$importer->init($organization);
$data = file_get_contents(storage_path('tests/clockify_time_entries_import_test_1.csv'));
$importer->importData($data, []);
$importer->importData($data);
$importer = new ClockifyTimeEntriesImporter();
$importer->init($organization);
// Act
$importer->importData($data, []);
$importer->importData($data);
// Assert
$testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries();

View File

@@ -38,9 +38,17 @@ class TogglDataImporterTest extends ImporterTestAbstract
// Act
$importer->importData($data);
$report = $importer->getReport();
// Assert
$this->checkTestScenarioAfterImportExcludingTimeEntries();
$this->assertSame(0, $report->timeEntriesCreated);
$this->assertSame(2, $report->tagsCreated);
$this->assertSame(1, $report->tasksCreated);
$this->assertSame(1, $report->usersCreated);
$this->assertSame(2, $report->projectsCreated);
$this->assertSame(1, $report->clientsCreated);
}
public function test_import_of_test_file_twice_succeeds(): void
@@ -57,8 +65,15 @@ class TogglDataImporterTest extends ImporterTestAbstract
// Act
$importer->importData($data);
$report = $importer->getReport();
// Assert
$this->checkTestScenarioAfterImportExcludingTimeEntries();
$this->assertSame(0, $report->timeEntriesCreated);
$this->assertSame(0, $report->tagsCreated);
$this->assertSame(0, $report->tasksCreated);
$this->assertSame(0, $report->usersCreated);
$this->assertSame(0, $report->projectsCreated);
$this->assertSame(0, $report->clientsCreated);
}
}

View File

@@ -19,7 +19,8 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract
$data = file_get_contents(storage_path('tests/toggl_time_entries_import_test_1.csv'));
// Act
$importer->importData($data, []);
$importer->importData($data);
$report = $importer->getReport();
// Assert
$testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries();
@@ -39,6 +40,12 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract
$this->assertSame('2024-03-04 11:23:01', $timeEntry2->end->toDateTimeString());
$this->assertTrue($timeEntry2->billable);
$this->assertSame([], $timeEntry2->tags);
$this->assertSame(2, $report->timeEntriesCreated);
$this->assertSame(2, $report->tagsCreated);
$this->assertSame(1, $report->tasksCreated);
$this->assertSame(1, $report->usersCreated);
$this->assertSame(2, $report->projectsCreated);
$this->assertSame(1, $report->clientsCreated);
}
public function test_import_of_test_file_twice_succeeds(): void
@@ -53,7 +60,8 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract
$importer->init($organization);
// Act
$importer->importData($data, []);
$importer->importData($data);
$report = $importer->getReport();
// Assert
$testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries();
@@ -73,5 +81,11 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract
$this->assertSame('2024-03-04 11:23:01', $timeEntry2->end->toDateTimeString());
$this->assertTrue($timeEntry2->billable);
$this->assertSame([], $timeEntry2->tags);
$this->assertSame(2, $report->timeEntriesCreated);
$this->assertSame(0, $report->tagsCreated);
$this->assertSame(0, $report->tasksCreated);
$this->assertSame(0, $report->usersCreated);
$this->assertSame(0, $report->projectsCreated);
$this->assertSame(0, $report->clientsCreated);
}
}

View File

@@ -4,14 +4,18 @@ declare(strict_types=1);
namespace Tests\Unit\Service;
use App\Models\User;
use App\Service\TimezoneService;
use Illuminate\Support\Facades\Log;
use Tests\TestCase;
use TiMacDonald\Log\LogEntry;
class TimezoneServiceTest extends TestCase
{
public function test_get_timezones_returns_all_available_timezones(): void
{
// Arrange
$service = new \App\Service\TimezoneService();
$service = app(TimezoneService::class);
// Act
$result = $service->getTimezones();
@@ -23,4 +27,42 @@ class TimezoneServiceTest extends TestCase
$this->assertContains('Europe/Berlin', $result);
$this->assertContains('Europe/London', $result);
}
public function test_get_timezone_from_user_returns_timezone_of_user_as_carbon_timezone(): void
{
// Arrange
$user = User::factory()->create([
'timezone' => 'Europe/Berlin',
]);
/** @var TimezoneService $service */
$service = app(TimezoneService::class);
// Act
$result = $service->getTimezoneFromUser($user);
// Assert
$this->assertEquals('Europe/Berlin', $result->getName());
}
public function test_get_timezone_from_user_falls_back_to_utc_and_logs_this_failure_if_timezone_in_db_is_corrupt(): void
{
// Arrange
$corruptTimezone = 'Invalid/Timezone';
$user = User::factory()->create([
'timezone' => $corruptTimezone,
]);
/** @var TimezoneService $service */
$service = app(TimezoneService::class);
// Act
$result = $service->getTimezoneFromUser($user);
// Assert
$this->assertEquals('UTC', $result->getName());
Log::assertLogged(fn (LogEntry $log) => $log->level === 'error'
&& $log->message === 'User has a invalid timezone'
);
}
}