Skip to content

Commit

Permalink
add unhappy paths tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JakubKermes committed Apr 25, 2024
1 parent 153b985 commit ad387af
Show file tree
Hide file tree
Showing 15 changed files with 243 additions and 51 deletions.
11 changes: 6 additions & 5 deletions app/Http/Controllers/Api/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ public function login(LoginRequest $request): JsonResponse
"password" => $request->password,
], $remember)) {
$user = Auth::user();
$user_id = (string)Auth::id();
$userId = (string)Auth::id();

$token_abilities = $this->getUserAbilities($user);

$token = $user->createToken($user_id, $token_abilities)->plainTextToken;
$token = $user->createToken($userId, $token_abilities)->plainTextToken;

return response()->json([
"abilities" => $token_abilities,
"user" => $user,
"userId" => $userId,
"access_token" => $token,
]);
}
Expand Down Expand Up @@ -91,11 +91,12 @@ public function handleProviderRedirect(string $provider): JsonResponse
]);
$token_abilities = $this->getUserAbilities($user);

$user_id = (string)$user->id;
$token = $user->createToken($user_id, $token_abilities)->plainTextToken;
$userId = (string)$user->id;
$token = $user->createToken($userId, $token_abilities)->plainTextToken;

return response()->json([
"access_token" => $token,
"userId" => $userId,
]);
} catch (Exception $e) {
return response()->json([
Expand Down
3 changes: 2 additions & 1 deletion app/Http/Controllers/Api/ChangeLocaleController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ChangeLocaleController extends Controller
{
Expand All @@ -22,6 +23,6 @@ public function __invoke(Request $request, string $locale): JsonResponse

return response()->json([
"message" => __("Error changing the language."),
]);
], Response::HTTP_UNPROCESSABLE_ENTITY);
}
}
8 changes: 8 additions & 0 deletions app/Http/Controllers/Api/CityProviderController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use App\Services\DataImporterService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class CityProviderController extends Controller
{
Expand Down Expand Up @@ -47,6 +48,13 @@ public function index(): JsonResponse

public function update(CityProviderService $service, CityProviderRequest $request, City $city): JsonResponse
{
foreach ($request->providerNames as $providerName) {
if (Provider::query()->where("name", $providerName)->doesntExist()) {
return response()->json([
"message" => __("Provider does not exist."),
], Response::HTTP_UNPROCESSABLE_ENTITY);
}
}
$service->updateProvider($request->providerNames, $city);

return response()->json([
Expand Down
8 changes: 8 additions & 0 deletions app/Http/Controllers/Api/FavoritesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
use App\Http\Controllers\Controller;
use App\Http\Resources\CityResource;
use App\Http\Resources\ProviderResource;
use App\Models\City;
use App\Models\Favorites;
use App\Models\Provider;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class FavoritesController extends Controller
{
Expand All @@ -35,6 +37,12 @@ public function store(Request $request): JsonResponse
$cityId = $request->input("city_id");
$userId = $request->user()?->id;

if (City::query()->where("id", $cityId)->doesntExist() || !$cityId) {
return response()->json([
"message" => "City not found.",
], Response::HTTP_BAD_REQUEST);
}

$favorite = Favorites::firstOrCreate([
"user_id" => $userId,
"city_id" => $cityId,
Expand Down
2 changes: 1 addition & 1 deletion lang/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"to": "do",
"results": "wyników",
"Language has been changed.": "Język został zmieniony.",
"Error changing language.": "Błąd podczas zmiany języka.",
"Error changing the language.": "Błąd podczas zmiany języka.",
"Alternative name": "Alternatywna nazwa",
"Filling map with providers...": "Wypełnianie mapy dostawcami...",
"Didn't find any providers.": "Nie znaleziono dostawców.",
Expand Down
23 changes: 22 additions & 1 deletion tests/Feature/Api/AdminTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\Sanctum;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class AdminTest extends TestCase
Expand Down Expand Up @@ -44,7 +45,27 @@ public function testAdminCanEnterAdminDashboardCountries(): void
{
Sanctum::actingAs($this->adminUser, ["HasAdminRole"]);

$this->getJson("/api/admin/countries");
$response = $this->getJson("/api/admin/countries");
$response->assertOk()
->assertJsonStructure([
"countries" => [
"*" => [
"id",
"name",
"created_at",
"updated_at",
],
],
]);
$this->assertAuthenticatedAs(User::first());
}

public function testUserCannotAccessAdminRoutes(): void
{
$user = User::factory()->create();
Sanctum::actingAs($user);

$response = $this->getJson("/api/admin/countries");
$response->assertStatus(Response::HTTP_NOT_FOUND);
}
}
17 changes: 16 additions & 1 deletion tests/Feature/Api/ChangeLocaleControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@

namespace Tests\Feature\Api;

use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class ChangeLocaleControllerTest extends TestCase
{
public function testLanguageChangeHappens(): void
public function testUserCanChangeLanguageToSupportedLanguage(): void
{
$response = $this->postJson("/api/language/en");

Expand All @@ -20,4 +21,18 @@ public function testLanguageChangeHappens(): void
$response->assertOk()
->assertJson(["message" => "Język został zmieniony."]);
}

public function testUserCannotChangeLanguageToUnsupportedLanguage(): void
{
$response = $this->postJson("/api/language/unsupported");

$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJson(["message" => "Error changing the language."]);

$this->postJson("/api/language/pl");

$response = $this->postJson("/api/language/unsupported");
$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJson(["message" => "Błąd podczas zmiany języka."]);
}
}
29 changes: 29 additions & 0 deletions tests/Feature/Api/CityAlternativeNameController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Models\CityAlternativeName;
use App\Models\User;
use Laravel\Sanctum\Sanctum;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class CityAlternativeNameController extends TestCase
Expand Down Expand Up @@ -38,4 +39,32 @@ public function testCityAlternativeNameCanBeDeleted(): void
$response->assertOk()
->assertJson(["message" => __("City alternative name deleted successfully.")]);
}

public function testCityAlternativeNamesDuplicatesAreNotCreated(): void
{
$cityAlternativeName = CityAlternativeName::factory()->create();
$response = $this->postJson(route("city-alternative-names.store"), [
"city_id" => $cityAlternativeName->city_id,
"name" => $cityAlternativeName->name,
]);

$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors(["name"]);
}

public function testNonAdminUserCannotAddOrDeleteAlternativeNames(): void
{
Sanctum::actingAs(User::factory()->create());

$response = $this->postJson(route("city-alternative-names.store"), [
"city_id" => 1,
"name" => "Test City Alternative Name",
]);
$response->assertStatus(Response::HTTP_FORBIDDEN);

$cityAlternativeName = CityAlternativeName::factory()->create();

$response = $this->deleteJson(route("city-alternative-names.destroy", $cityAlternativeName->id));
$response->assertStatus(Response::HTTP_FORBIDDEN);
}
}
62 changes: 30 additions & 32 deletions tests/Feature/Api/CityControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use App\Models\City;
use App\Models\Country;
use App\Models\User;
use Generator;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

Expand Down Expand Up @@ -96,42 +95,41 @@ public function testCityCannotBeUpdatedWithInvalidData(array $data, array $expec
$response->assertJsonValidationErrors($expectedErrors);
}

public static function invalidCityDataProvider(): Generator
public static function invalidCityDataProvider(): array
{
yield "city with empty credentials" => [
"data" => [
"name" => null,
"longitude" => null,
"latitude" => null,
return [
"city with empty credentials" => [
"data" => [
"name" => null,
"longitude" => null,
"latitude" => null,
],
"expectedErrors" => ["name", "latitude", "longitude"],
],
"expectedErrors" => ["name", "latitude", "longitude"],
];

yield "city with incorrect name" => [
"data" => [
"name" => "legnica",
"longitude" => 21.555,
"latitude" => 55.234,
"city with incorrect name" => [
"data" => [
"name" => "legnica",
"longitude" => 21.555,
"latitude" => 55.234,
],
"expectedErrors" => ["name"],
],
"expectedErrors" => ["name"],
];

yield "city with incorrect longitude" => [
"data" => [
"name" => "Legnica",
"longitude" => "21string",
"latitude" => 55.234,
"city with incorrect longitude" => [
"data" => [
"name" => "Legnica",
"longitude" => "21string",
"latitude" => 55.234,
],
"expectedErrors" => ["longitude"],
],
"expectedErrors" => ["longitude"],
];

yield "city with incorrect latitude" => [
"data" => [
"name" => "Legnica",
"longitude" => 21.555,
"latitude" => "55.234string",
"city with incorrect latitude" => [
"data" => [
"name" => "Legnica",
"longitude" => 21.555,
"latitude" => "55.234string",
],
"expectedErrors" => ["latitude"],
],
"expectedErrors" => ["latitude"],
];
}

Expand Down
11 changes: 11 additions & 0 deletions tests/Feature/Api/CityOpinionControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use App\Models\CityOpinion;
use App\Models\User;
use Laravel\Sanctum\Sanctum;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class CityOpinionControllerTest extends TestCase
Expand Down Expand Up @@ -109,4 +110,14 @@ public function testUnauthorizedUserCannotEditOrDeleteOpinion(): void
$response = $this->deleteJson("/api/opinions/$opinion_id");
$response->assertNotFound();
}

public function testUserCannotAddOpinionForNonexistentCity(): void
{
$response = $this->postJson("/api/opinions", [
"rating" => 5,
"content" => "Great city!",
"city_id" => 999,
]);
$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
}
}
42 changes: 39 additions & 3 deletions tests/Feature/Api/CityProviderControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,18 @@
use App\Models\Provider;
use App\Models\User;
use Laravel\Sanctum\Sanctum;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class CityProviderControllerTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$adminUser = User::factory()->create();
Sanctum::actingAs($adminUser, ["HasAdminRole"]);
}

public function testCityProviderDataIsReturned(): void
{
$response = $this->getJson("/api/providers");
Expand All @@ -26,11 +34,9 @@ public function testCityProviderDataIsReturned(): void

public function testCityProviderDataIsUpdated(): void
{
$adminUser = User::factory()->create();
Sanctum::actingAs($adminUser, ["HasAdminRole"]);
Provider::query()->create([
"name" => "provider1",
"url" => "http://provider1.com",
"url" => "https://provider1.com",
"color" => "#000000",
]);
$city = City::factory()->create();
Expand All @@ -50,4 +56,34 @@ public function testCityProviderDataIsUpdated(): void
"created_by" => "admin",
]);
}

public function testCityProviderCannotBeUpdatedWithInvalidData(): void
{
$city = City::factory()->create();
$response = $this->patchJson("/api/update-city-providers/$city->id", [
"providerNames" => ["provider1"],
"city" => $city,
]);
$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJson([
"message" => "Provider does not exist.",
]);
}

public function testCityProviderCannotBeUpdatedByUnauthorisedUser(): void
{
$user = User::factory()->create();
Sanctum::actingAs($user);
$city = City::factory()->create();
$provider = Provider::query()->create([
"name" => "provider1",
"url" => "https://provider1.com",
"color" => "#000000",
]);
$response = $this->patchJson("/api/update-city-providers/$city->id", [
"providerNames" => [$provider->name],
"city" => $city,
]);
$response->assertStatus(Response::HTTP_NOT_FOUND);
}
}
Loading

0 comments on commit ad387af

Please sign in to comment.