Skip to content

Commit 82e6b4a

Browse files
committed
add exceptions and tests mockup notifications mails
1 parent a5cd519 commit 82e6b4a

File tree

8 files changed

+93
-9
lines changed

8 files changed

+93
-9
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace App\Exceptions;
4+
5+
use Exception;
6+
use Illuminate\Http\Request;
7+
use Symfony\Component\HttpFoundation\Response;
8+
use Throwable;
9+
10+
class RecoveryPasswordException extends Exception
11+
{
12+
public function __construct(
13+
string $message = "The password could not be reset at this time, please try again later",
14+
int $code = Response::HTTP_INTERNAL_SERVER_ERROR,
15+
?Throwable $previous = null
16+
) {
17+
parent::__construct($message, $code, $previous);
18+
}
19+
20+
public function render(Request $request)
21+
{
22+
if ($request->isJson())
23+
return response()->json(['message' => __($this->message)], $this->code);
24+
}
25+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace App\Exceptions;
4+
5+
use Exception;
6+
use Illuminate\Http\Request;
7+
use Symfony\Component\HttpFoundation\Response;
8+
use Throwable;
9+
10+
class RegisteredException extends Exception
11+
{
12+
public function __construct(
13+
string $message,
14+
int $code = Response::HTTP_INTERNAL_SERVER_ERROR,
15+
?Throwable $previous = null
16+
) {
17+
parent::__construct($message, $code, $previous);
18+
}
19+
20+
public function render(Request $request)
21+
{
22+
if ($request->isJson())
23+
return response()->json(['message' => __($this->message)], $this->code);
24+
}
25+
}

app/Http/Controllers/AuthController.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace App\Http\Controllers;
44

5+
use App\Exceptions\RecoveryPasswordException;
56
use App\Http\Requests\User\ChangePasswordRequest;
67
use App\Http\Requests\User\LoginRequest;
78
use App\Http\Requests\User\RecoveryPasswordRequest;
@@ -50,7 +51,7 @@ public function recoveryPassword(RecoveryPasswordRequest $request): JsonResponse
5051
try {
5152
$user->notify(new RecoveryPasswordNotification());
5253
} catch (\Exception $e) {
53-
return response()->json(['message' => __('The password could not be reset at this time, please try again later')], 500);
54+
throw new RecoveryPasswordException();
5455
}
5556

5657
return response()->json(['message' => __('In a few moments you will receive an email to reset your password. Check your mailbox')], 200);

app/Http/Controllers/UserController.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace App\Http\Controllers;
44

5+
use App\Exceptions\RegisteredException;
56
use App\Exports\UsersExport;
67
use App\Http\Requests\User\UserAddRequest;
78
use App\Http\Requests\User\UserUpdateRequest;
@@ -49,7 +50,7 @@ public function store(UserAddRequest $request): JsonResponse
4950
$mediaService->deleteFile();
5051

5152
DB::rollBack();
52-
return response()->json(['message' => $e->getMessage()], 500);
53+
throw new RegisteredException($e->getMessage());
5354
}
5455

5556
DB::commit();

app/Models/User.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ public static function countAdmins(): int
129129

130130
public static function getAllUsers(): Collection
131131
{
132-
return Cache::remember(User::CACHE_KEY, now()->addDay(), function () {
132+
return Cache::remember(User::CACHE_KEY, (int)now()->addDay()->diffInSeconds(), function () {
133133
return User::With(['rol'])->orderBy('nombre')->get();
134134
});
135135
}

app/Notifications/VerifiedNotification.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class VerifiedNotification extends Notification implements ShouldQueue
1515
/**
1616
* Create a new notification instance.
1717
*/
18-
public function __construct(private bool $isVerified)
18+
public function __construct(public bool $isVerified)
1919
{
2020
}
2121

tests/Feature/AuthTest.php

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,13 @@
55
use App\Mail\RecoveryPasswordMail;
66
use App\Mail\VerifiedMail;
77
use App\Models\User;
8+
use App\Notifications\RecoveryPasswordNotification;
9+
use App\Notifications\VerifiedNotification;
10+
use Illuminate\Auth\Events\Verified;
811
use Illuminate\Foundation\Testing\DatabaseMigrations;
12+
use Illuminate\Support\Facades\Event;
13+
use Illuminate\Support\Facades\Mail;
14+
use Illuminate\Support\Facades\Notification;
915
use Illuminate\Support\Str;
1016
use Laravel\Sanctum\Sanctum;
1117
use Tests\TestCase;
@@ -76,17 +82,21 @@ public function test_cambiar_el_password_del_user(): void
7682

7783
public function test_llamar_al_endpoint_restablecer_password(): void
7884
{
85+
Notification::fake();
7986
$data = ['email' => 'user@email.com'];
80-
Sanctum::actingAs($this->createNewUser());
87+
$user = $this->createNewUser();
88+
Sanctum::actingAs($user);
8189

8290
$res = $this->postJson(self::PATH . 'recovery/password', $data);
8391

92+
Notification::assertSentTo([$user], RecoveryPasswordNotification::class, fn ($notification, $channels, $notifiable) => (in_array('mail', $channels)));
8493
$res->assertStatus(200);
8594
$res->assertExactJson(['message' => __('In a few moments you will receive an email to reset your password. Check your mailbox')]);
8695
}
8796

8897
public function test_email_restablecer_password(): void
8998
{
99+
Mail::fake();
90100
$data = ['email' => 'user@email.com'];
91101
$user = $this->createNewUser();
92102

@@ -99,26 +109,33 @@ public function test_email_restablecer_password(): void
99109

100110
public function test_llamar_al_endpoint_verificacion_usuario_ya_verificado(): void
101111
{
102-
Sanctum::actingAs($this->createNewUser());
112+
Notification::fake();
113+
$user = $this->createNewUser();
114+
Sanctum::actingAs($user);
103115

104116
$res = $this->postJson(self::PATH_USER . 'verification/email/notification');
105117

118+
Notification::assertSentTo([$user], VerifiedNotification::class, fn ($notification, $channels, $notifiable) => (in_array('broadcast', $channels) && $notification->isVerified));
106119
$res->assertStatus(200);
107120
$res->assertExactJson(['message' => __('Email already verified')]);
108121
}
109122

110123
public function test_llamar_al_endpoint_verificacion_usuario_no_verificado(): void
111124
{
112-
Sanctum::actingAs($this->createNewUser(false, false));
125+
Notification::fake();
126+
$user = $this->createNewUser(false, false);
127+
Sanctum::actingAs($user);
113128

114129
$res = $this->postJson(self::PATH_USER . 'verification/email/notification');
115130

131+
Notification::assertNotSentTo([$user], VerifiedNotification::class);
116132
$res->assertStatus(200);
117133
$res->assertExactJson(['message' => __('Email forwarded successfully')]);
118134
}
119135

120136
public function test_email_verificar_usuario(): void
121137
{
138+
Mail::fake();
122139
$data = ['email' => 'user@email.com'];
123140
$url = config('app.DOMAIN_FRONTEND') . "/auth/verification/email" . Str::random(10) . "&token=" . Str::random(10);
124141
$user = $this->createNewUser(false, false);
@@ -133,26 +150,34 @@ public function test_email_verificar_usuario(): void
133150

134151
public function test_verificar_usuario(): void
135152
{
153+
Notification::fake();
154+
Event::fake();
136155
$data = ['email' => 'user@email.com'];
137156
$user = $this->createNewUser(false, false);
138157
Sanctum::actingAs($user);
139158

140159
$res = $this->getJson(self::PATH_USER . 'verification/email/' . $user->id . '/' . sha1($data['email']));
141160

161+
Notification::assertSentTo([$user], VerifiedNotification::class, fn ($notification, $channels, $notifiable) => (in_array('broadcast', $channels) && $notification->isVerified));
162+
Event::assertDispatched(Verified::class);
142163
$this->assertNotNull($user->email_verified_at);
143164
$res->assertStatus(200);
144165
$res->assertExactJson(['message' => __('Email has been verified')]);
145166
}
146167

147168
public function test_verificar_usuario_ya_verificado(): void
148169
{
170+
Notification::fake();
171+
Event::fake();
149172
$data = ['email' => 'user@email.com'];
150173
$user = $this->createNewUser(false);
151174
$emailVerifiedAt = $user->email_verified_at;
152175
Sanctum::actingAs($user);
153176

154177
$res = $this->getJson(self::PATH_USER . 'verification/email/' . $user->id . '/' . sha1($data['email']));
155178

179+
Notification::assertSentTo([$user], VerifiedNotification::class, fn ($notification, $channels, $notifiable) => (in_array('broadcast', $channels) && $notification->isVerified));
180+
Event::assertNotDispatched(Verified::class);
156181
$this->assertEquals($emailVerifiedAt, $user->email_verified_at);
157182
$res->assertStatus(200);
158183
$res->assertExactJson(['message' => __('Email already verified')]);

tests/Feature/UserTest.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,15 @@
44

55
use App\Exports\UsersExport;
66
use App\Models\User;
7+
use Closure;
8+
use Illuminate\Auth\Events\Registered;
79
use Illuminate\Database\Eloquent\Collection;
810
use Illuminate\Foundation\Testing\DatabaseMigrations;
911
use Illuminate\Foundation\Testing\RefreshDatabase;
1012
use Illuminate\Foundation\Testing\WithFaker;
1113
use Illuminate\Http\UploadedFile;
14+
use Illuminate\Support\Facades\Cache;
15+
use Illuminate\Support\Facades\Event;
1216
use Illuminate\Support\Facades\Storage;
1317
use Laravel\Sanctum\Sanctum;
1418
use Maatwebsite\Excel\Facades\Excel;
@@ -28,10 +32,11 @@ public function test_obtener_todos_los_users(): void
2832
$userAuth = $this->createNewUser(true);
2933
$this->createMutipleUser(5);
3034
$users = User::With(['rol'])->orderBy('nombre')->get();
35+
Cache::shouldReceive('remember')->once()->with('users', (int)now()->addDay()->diffInSeconds(), Closure::class)->andReturn($users);
3136
Sanctum::actingAs($userAuth);
32-
37+
3338
$res = $this->getJson(self::PATH);
34-
39+
3540
$res->assertStatus(200);
3641
$res->assertExactJson($this->getResourceCollectionUsers($users));
3742
}
@@ -51,6 +56,7 @@ public function test_obtener_user_mediante_id(): void
5156

5257
public function test_crear_user(): void
5358
{
59+
Event::fake();
5460
Storage::fake(self::FAKE_STORAGE);
5561
Sanctum::actingAs($this->createNewUser(true));
5662
$data = [
@@ -66,6 +72,7 @@ public function test_crear_user(): void
6672
$res = $this->postJson(self::PATH, $data);
6773
$user = User::Where('email', 'test@laravel.com')->first();
6874

75+
Event::assertDispatched(Registered::class);
6976
$this->assertEquals($data['nombre'], $user->nombre);
7077
$this->assertEquals($data['apellidos'], $user->apellidos);
7178
$this->assertEquals($data['email'], $user->email);

0 commit comments

Comments
 (0)