Passed
Push — main ( f34b4e...e39b5c )
by Emil
05:23
created

BookControllerTest::testBookUpdatePOST()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 98
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
eloc 55
c 1
b 1
f 0
nc 3
nop 0
dl 0
loc 98
rs 8.9818

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Tests\Controller;
4
5
use App\Repository\BookRepository;
6
use Doctrine\Persistence\ManagerRegistry;
7
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
8
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\File\UploadedFile;
11
use Symfony\Component\HttpFoundation\Session\Session;
12
use Symfony\Component\Routing\RouterInterface;
13
14
class BookControllerTest extends WebTestCase
15
{
16
    private KernelBrowser $client;
17
    private RouterInterface $router;
18
    private ManagerRegistry $doctrine;
19
    private ?int $createdBookId = null; // Store created book ID
20
21
    /**
22
     * setUp
23
     *
24
     * @return void
25
     */
26
    protected function setUp(): void
27
    {
28
        parent::setUp();
29
30
        // Retrieve the client
31
        $this->client = static::createClient();
32
33
        // Retrieve the container
34
        $container = $this->client->getContainer();
35
36
        // Retrieve router service
37
        // @phpstan-ignore-next-line
38
        $this->router = $container->get('router');
39
40
        // Get the ManagerRegistry service from container
41
        // @phpstan-ignore-next-line
42
        $this->doctrine = $container->get('doctrine');
43
    }
44
45
    /**
46
     * tearDown
47
     *
48
     * @return void
49
     */
50
    protected function tearDown(): void
51
    {
52
        parent::tearDown();
53
54
        if ($this->createdBookId !== null) {
55
            // Generate delete URL
56
            $deleteUrl = $this->router->generate('book_delete_post', ['id' => $this->createdBookId]);
57
58
            // Send delete request
59
            $this->client->request('POST', $deleteUrl, ['id' => $this->createdBookId]);
60
61
            // Reset the ID to prevent repeated deletions
62
            $this->createdBookId = null;
63
        }
64
    }
65
66
    /**
67
     * testBookCreatePOST
68
     *
69
     * Test book_create_post route
70
     *
71
     * @return void
72
     */
73
    private function testBookCreatePOST(): void
74
    {
75
        $bookRepository = new BookRepository($this->doctrine);
76
77
        // book_create_post
78
79
        // Generate URL from route name
80
        $url = $this->router->generate('book_create_post');
81
82
        // Create a mock UploadedFile
83
        $file = $this->createMock(UploadedFile::class);
84
        $file->method('isValid')->willReturn(true);
85
        $file->method('getMimeType')->willReturn('image/jpeg');
86
        $file->method('getClientOriginalName')->willReturn('test_image.jpg');
87
        $file->method('guessExtension')->willReturn('jpg');
88
89
        $formData = [
90
            'id' => 0,
91
            'title' => 'test book',
92
            'isbn' => '0000000000000',
93
            'author' => 'test author',
94
            'img' => $file,
95
        ];
96
97
        // Send POST request to the route
98
        $this->client->request('POST', $url, $formData);
99
100
        // Assert that response is a redirect (302 status)
101
        $response = $this->client->getResponse();
102
        $this->assertTrue($response->isRedirect());
103
104
        $data = $bookRepository->readOneBookISBN('0000000000000');
105
106
        $this->assertEquals('test book', $data['book']['title']);
107
        $this->assertEquals('0000000000000', $data['book']['isbn']);
108
        $this->assertEquals('test author', $data['book']['author']);
109
110
        // After creating the book, store its ID
111
        $this->createdBookId = $data['book']['id'];
112
113
        // Test if title is null
114
115
        $formData = [
116
            'id' => 0,
117
            'title' => '',
118
            'isbn' => '000000000001',
119
            'author' => 'test author',
120
            'img' => $file,
121
        ];
122
123
        // Send POST request to the route
124
        $this->client->request('POST', $url, $formData);
125
126
        $data = $bookRepository->readOneBookISBN('0000000000001');
127
128
        $this->assertNull($data['book']['author']);
129
    }
130
131
    /**
132
     * testBookUpdatePOST
133
     *
134
     * Test book_update_post route
135
     *
136
     * @return void
137
     */
138
    private function testBookUpdatePOST(): void
139
    {
140
        $bookRepository = new BookRepository($this->doctrine);
141
142
        // Create a mock UploadedFile
143
        $file = $this->createMock(UploadedFile::class);
144
        $file->method('isValid')->willReturn(true);
145
        $file->method('getMimeType')->willReturn('image/jpeg');
146
        $file->method('getClientOriginalName')->willReturn('test_image1.jpg');
147
        $file->method('guessExtension')->willReturn('jpg');
148
149
        $formData = [
150
            'id' => $this->createdBookId,
151
            'title' => 'test book 2',
152
            'isbn' => '0000000000001',
153
            'author' => 'test author 2',
154
            'img' => $file,
155
        ];
156
157
        // Generate URL from route name
158
        $url = $this->router->generate('book_update_post', ['id' => (int) $this->createdBookId]);
159
160
        // Send POST request to the route
161
        $this->client->request('POST', $url, $formData);
162
163
        // Assert that response is a redirect (302 status)
164
        $response = $this->client->getResponse();
165
        $this->assertTrue($response->isRedirect());
166
167
        $data = $bookRepository->readOneBook((int) $this->createdBookId);
168
169
        $this->assertEquals('test book 2', $data['book']['title']);
170
        $this->assertEquals('0000000000001', $data['book']['isbn']);
171
        $this->assertEquals('test author 2', $data['book']['author']);
172
173
        //Test if book don't exist
174
        $data = $bookRepository->readAllBooks();
175
176
        // Extract all existing IDs
177
        $existingIds = array_map(function ($book) {
178
            return $book['id'];
179
        }, $data['books']);
180
181
        // Find the smallest missing integer starting from 1
182
        $missingId = null;
183
        for ($i = 1; ; $i++) {
184
            if (!in_array($i, $existingIds, true)) {
185
                $missingId = $i;
186
                break;
187
            }
188
        }
189
190
        $formData = [
191
            'id' => (int) $missingId,
192
            'title' => 'test book 1',
193
            'isbn' => '0000000000000',
194
            'author' => 'test author 1',
195
            'img' => $file,
196
        ];
197
198
        // Generate URL from route name
199
        $url = $this->router->generate('book_update_post', ['id' => (int) $missingId]);
200
201
        // Send POST request to the route
202
        $this->client->request('POST', $url, $formData);
203
204
        // Assert that response is a redirect (302 status)
205
        $response = $this->client->getResponse();
206
        $this->assertTrue($response->isRedirect());
207
208
        $data = $bookRepository->readOneBook((int) $missingId);
209
210
        $this->assertNull($data['book']['author']);
211
212
        // Test if title is null
213
        $formData = [
214
            'id' => $this->createdBookId,
215
            'title' => '',
216
            'isbn' => '0000000000000',
217
            'author' => 'test author 1',
218
            'img' => $file,
219
        ];
220
221
        // Generate URL from route name
222
        $url = $this->router->generate('book_update_post', ['id' => (int) $this->createdBookId]);
223
224
        // Send POST request to the route
225
        $this->client->request('POST', $url, $formData);
226
227
        // Assert that response is a redirect (302 status)
228
        $response = $this->client->getResponse();
229
        $this->assertTrue($response->isRedirect());
230
231
        $data = $bookRepository->readOneBook((int) $this->createdBookId);
232
233
        $this->assertEquals('test book 2', $data['book']['title']);
234
        $this->assertEquals('0000000000001', $data['book']['isbn']);
235
        $this->assertEquals('test author 2', $data['book']['author']);
236
    }
237
238
    /**
239
     * testBookDeletePOST
240
     *
241
     * Test book_delete_post route
242
     *
243
     * @return void
244
     */
245
    private function testBookDeletePOST(): void
246
    {
247
        $formData = [
248
            'id' => (int) $this->createdBookId,
249
        ];
250
251
        //book_delete_post
252
253
        // Generate URL from route name
254
        $url = $this->router->generate('book_delete_post', ['id' => (int)$this->createdBookId]);
255
256
        // Send POST request to the route
257
        $this->client->request('POST', $url, $formData);
258
259
        // Assert that response is a redirect (302 status)
260
        $response = $this->client->getResponse();
261
        $this->assertTrue($response->isRedirect());
262
263
        // Reset the ID to prevent repeated deletions
264
        $this->createdBookId = null;
265
266
        //Test to delete book that don't exists
267
268
        // Send POST request to the route
269
        $this->client->request('POST', $url, $formData);
270
271
        // Assert that response is a redirect (302 status)
272
        $response = $this->client->getResponse();
273
        $this->assertTrue($response->isRedirect());
274
    }
275
276
    /**
277
     * testCRUD
278
     *
279
     * @return void
280
     */
281
    public function testCRUD(): void
282
    {
283
        // Test Create Book
284
        $this->testBookCreatePOST();
285
286
        // Test Update Book
287
        $this->testBookUpdatePOST();
288
289
        // Test Delete Book
290
        $this->testBookDeletePOST();
291
    }
292
293
    /**
294
     * testLibrary
295
     *
296
     * Test library route
297
     *
298
     * @return void
299
     */
300
    public function testLibrary(): void
301
    {
302
        //library
303
304
        // Generate URL from route name
305
        $url = $this->router->generate('library');
306
307
        // Send a GET request to the route
308
        $crawler = $this->client->request('GET', $url);
309
310
        // Assert the response status code
311
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
312
313
        // Assert that certain content exists in the response
314
        $this->assertStringContainsString('Book: Library', $crawler->filter('title')->text());
315
    }
316
317
    /**
318
     * testBookCreateGET
319
     *
320
     * Test book_create_get route
321
     *
322
     * @return void
323
     */
324
    public function testBookCreateGET(): void
325
    {
326
        //book_create_get
327
328
        // Generate URL from route name
329
        $url = $this->router->generate('book_create_get');
330
331
        // Send a GET request to the route
332
        $crawler = $this->client->request('GET', $url);
333
334
        // Assert the response status code
335
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
336
337
        // Assert that certain content exists in the response
338
        $this->assertStringContainsString('Book: Create', $crawler->filter('title')->text());
339
    }
340
341
    /**
342
     * testShowAll
343
     *
344
     * Test book_show_all route
345
     *
346
     * @return void
347
     */
348
    public function testShowAll(): void
349
    {
350
        //book_show_all
351
352
        // Generate URL from route name
353
        $url = $this->router->generate('book_show_all');
354
355
        // Send a GET request to the route
356
        $crawler = $this->client->request('GET', $url);
357
358
        // Assert the response status code
359
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
360
361
        // Assert that certain content exists in the response
362
        $this->assertStringContainsString('Book: Show Library', $crawler->filter('title')->text());
363
    }
364
365
    /**
366
     * testShowOne
367
     *
368
     * Test book_show_one route
369
     *
370
     * @return void
371
     */
372
    public function testShowOne(): void
373
    {
374
        // Retrieve the container
375
        $container = $this->client->getContainer();
376
377
        // Get the ManagerRegistry service from container
378
        /** @var ManagerRegistry $doctrine */
379
        $doctrine = $container->get('doctrine');
380
381
        $bookRepository = new BookRepository($doctrine);
382
383
        $data = $bookRepository->readAllBooks();
384
385
        //If there is books in the library
386
        $id = null;
387
388
        if (count($data['books']) > 0) {
389
            $id = $data['books'][0]['id'];
390
        }
391
392
        if (null === $id) {
393
            $id = '0';
394
        }
395
396
        //book_show_one
397
398
        // Generate URL from route name
399
        $url = $this->router->generate('book_show_one', ['id' => $id]);
400
401
        // Send a GET request to the route
402
        $crawler = $this->client->request('GET', $url);
403
404
        // Assert the response status code
405
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
406
407
        // Assert that certain content exists in the response
408
        $this->assertStringContainsString('Book: Show Book', $crawler->filter('title')->text());
409
    }
410
411
    /**
412
     * testShowAllUpdate
413
     *
414
     * Test book_show_all_update route
415
     *
416
     * @return void
417
     */
418
    public function testShowAllUpdate(): void
419
    {
420
        //book_show_all_update
421
422
        // Generate URL from route name
423
        $url = $this->router->generate('book_show_all_update');
424
425
        // Send a GET request to the route
426
        $crawler = $this->client->request('GET', $url);
427
428
        // Assert the response status code
429
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
430
431
        // Assert that certain content exists in the response
432
        $this->assertStringContainsString('Book: Show Library Update', $crawler->filter('title')->text());
433
    }
434
435
    /**
436
     * testBookUpdateGET
437
     *
438
     * Test book_update_get route
439
     *
440
     * @return void
441
     */
442
    public function testBookUpdateGET(): void
443
    {
444
        $bookRepository = new BookRepository($this->doctrine);
445
446
        $data = $bookRepository->readAllBooks();
447
448
        //If there is books in the library
449
        $id = null;
450
451
        if (count($data['books']) > 0) {
452
            $id = $data['books'][0]['id'];
453
        }
454
455
        if (null === $id) {
456
            $id = '0';
457
        }
458
459
        //book_update_get
460
461
        // Generate URL from route name
462
        $url = $this->router->generate('book_update_get', ['id' => $id]);
463
464
        // Send a GET request to the route
465
        $crawler = $this->client->request('GET', $url);
466
467
        // Assert the response status code
468
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
469
470
        // Assert that certain content exists in the response
471
        $this->assertStringContainsString('Book: Update book', $crawler->filter('title')->text());
472
    }
473
474
    /**
475
     * testBookShowAllDeleteGET
476
     *
477
     * Test book_show_all_delete_get route
478
     *
479
     * @return void
480
     */
481
    public function testBookShowAllDeleteGET(): void
482
    {
483
        //book_show_all_delete_get
484
485
        // Generate URL from route name
486
        $url = $this->router->generate('book_show_all_delete_get');
487
488
        // Send a GET request to the route
489
        $crawler = $this->client->request('GET', $url);
490
491
        // Assert the response status code
492
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
493
494
        // Assert that certain content exists in the response
495
        $this->assertStringContainsString('Book: Show Library Delete', $crawler->filter('title')->text());
496
    }
497
}
498