Passed
Push — main ( f3cfb1...17781b )
by Emil
04:34
created

BookControllerTest::testShowOne()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 45
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 16
nc 8
nop 0
dl 0
loc 45
rs 9.7333
c 1
b 1
f 0
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 = null;
17
    private ?int $createdBookId = null; // Store created book ID
18
19
    /**
20
     * testBookCreatePOST
21
     *
22
     * Test book_create_post route
23
     * @param  RouterInterface $router
24
     * @param  BookRepository $bookRepository
25
     * @return void
26
     */
27
    private function testBookCreatePOST(RouterInterface $router, BookRepository $bookRepository): void
28
    {
29
        // book_create_post
30
        $this->assertNotNull($this->client);
31
32
        // Generate URL from route name
33
        $url = $router->generate('book_create_post');
34
35
        // Create a mock UploadedFile
36
        $file = $this->createMock(UploadedFile::class);
37
        $file->method('isValid')->willReturn(true);
38
        $file->method('getMimeType')->willReturn('image/jpeg');
39
        $file->method('getClientOriginalName')->willReturn('test_image.jpg');
40
        $file->method('guessExtension')->willReturn('jpg');
41
42
        $formData = [
43
            'id' => 0,
44
            'title' => 'test book',
45
            'isbn' => '0000000000000',
46
            'author' => 'test author',
47
            'img' => $file,
48
        ];
49
50
        // Send POST request to the route
51
        $this->client->request('POST', $url, $formData);
0 ignored issues
show
Bug introduced by
The method request() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
        $this->client->/** @scrutinizer ignore-call */ 
52
                       request('POST', $url, $formData);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
52
53
        // Assert that response is a redirect (302 status)
54
        $response = $this->client->getResponse();
55
        $this->assertTrue($response->isRedirect());
56
57
        $data = $bookRepository->readOneBookISBN('0000000000000');
58
59
        $this->assertEquals('test book', $data['book']['title']);
60
        $this->assertEquals('0000000000000', $data['book']['isbn']);
61
        $this->assertEquals('test author', $data['book']['author']);
62
63
        // After creating the book, store its ID
64
        $this->createdBookId = $data['book']['id'];
65
66
        // Test if title is null
67
        $this->assertNotNull($this->client);
68
69
        $formData = [
70
            'id' => 0,
71
            'title' => '',
72
            'isbn' => '000000000001',
73
            'author' => 'test author',
74
            'img' => $file,
75
        ];
76
77
        // Send POST request to the route
78
        $this->client->request('POST', $url, $formData);
79
80
        $data = $bookRepository->readOneBookISBN('0000000000001');
81
82
        $this->assertNull($data['book']['author']);
83
    }
84
85
    /**
86
     * testBookUpdatePOST
87
     *
88
     * Test book_update_post route
89
     *
90
     * @param  RouterInterface $router
91
     * @param  BookRepository $bookRepository
92
     * @return void
93
     */
94
    private function testBookUpdatePOST(RouterInterface $router, BookRepository $bookRepository): void
95
    {
96
        $this->assertNotNull($this->client);
97
98
        // Create a mock UploadedFile
99
        $file = $this->createMock(UploadedFile::class);
100
        $file->method('isValid')->willReturn(true);
101
        $file->method('getMimeType')->willReturn('image/jpeg');
102
        $file->method('getClientOriginalName')->willReturn('test_image1.jpg');
103
        $file->method('guessExtension')->willReturn('jpg');
104
105
        $formData = [
106
            'id' => $this->createdBookId,
107
            'title' => 'test book 2',
108
            'isbn' => '0000000000001',
109
            'author' => 'test author 2',
110
            'img' => $file,
111
        ];
112
113
        // Generate URL from route name
114
        $url = $router->generate('book_update_post', ['id' => (int) $this->createdBookId]);
115
116
        // Send POST request to the route
117
        $this->client->request('POST', $url, $formData);
118
119
        // Assert that response is a redirect (302 status)
120
        $response = $this->client->getResponse();
121
        $this->assertTrue($response->isRedirect());
122
123
        $data = $bookRepository->readOneBook((int) $this->createdBookId);
124
125
        $this->assertEquals('test book 2', $data['book']['title']);
126
127
        //Test if book don't exist
128
        $this->assertNotNull($this->client);
129
130
        $data = $bookRepository->readAllBooks();
131
132
        // Extract all existing IDs
133
        $existingIds = array_map(function ($book) {
134
            return $book['id'];
135
        }, $data['books']);
136
137
        // Find the smallest missing integer starting from 1
138
        $missingId = null;
139
        for ($i = 1; ; $i++) {
140
            if (!in_array($i, $existingIds, true)) {
141
                $missingId = $i;
142
                break;
143
            }
144
        }
145
146
        $formData = [
147
            'id' => (int) $missingId,
148
            'title' => 'test book 1',
149
            'isbn' => '0000000000000',
150
            'author' => 'test author 1',
151
            'img' => $file,
152
        ];
153
154
        // Generate URL from route name
155
        $url = $router->generate('book_update_post', ['id' => (int) $missingId]);
156
157
        // Send POST request to the route
158
        $this->client->request('POST', $url, $formData);
159
160
        // Assert that response is a redirect (302 status)
161
        $response = $this->client->getResponse();
162
        $this->assertTrue($response->isRedirect());
163
164
        $data = $bookRepository->readOneBook((int) $missingId);
165
166
        $this->assertNull($data['book']['author']);
167
168
        // Test if title is null
169
        $this->assertNotNull($this->client);
170
171
        $formData = [
172
            'id' => $this->createdBookId,
173
            'title' => '',
174
            'isbn' => '0000000000000',
175
            'author' => 'test author 1',
176
            'img' => $file,
177
        ];
178
179
        // Generate URL from route name
180
        $url = $router->generate('book_update_post', ['id' => (int) $this->createdBookId]);
181
182
        // Send POST request to the route
183
        $this->client->request('POST', $url, $formData);
184
185
        // Assert that response is a redirect (302 status)
186
        $response = $this->client->getResponse();
187
        $this->assertTrue($response->isRedirect());
188
189
        $data = $bookRepository->readOneBook((int) $this->createdBookId);
190
191
        $this->assertEquals('test book 2', $data['book']['title']);
192
    }
193
194
    /**
195
     * testBookDeletePOST
196
     *
197
     * Test book_delete_post route
198
     *
199
     * @param  RouterInterface $router
200
     * @return void
201
     */
202
    private function testBookDeletePOST(RouterInterface $router): void
203
    {
204
        $this->assertNotNull($this->client);
205
206
        $formData = [
207
            'id' => (int) $this->createdBookId,
208
        ];
209
210
        //book_delete_post
211
212
        // Generate URL from route name
213
        $url = $router->generate('book_delete_post', ['id' => (int)$this->createdBookId]);
214
215
        // Send POST request to the route
216
        $this->client->request('POST', $url, $formData);
217
218
        // Assert that response is a redirect (302 status)
219
        $response = $this->client->getResponse();
220
        $this->assertTrue($response->isRedirect());
221
222
        // Reset the ID to prevent repeated deletions
223
        $this->createdBookId = null;
224
225
        //Test to delete book that don't exists
226
        $this->assertNotNull($this->client);
227
228
        // Send POST request to the route
229
        $this->client->request('POST', $url, $formData);
230
231
        // Assert that response is a redirect (302 status)
232
        $response = $this->client->getResponse();
233
        $this->assertTrue($response->isRedirect());
234
    }
235
236
    /**
237
     * tearDown
238
     *
239
     * @return void
240
     */
241
    protected function tearDown(): void
242
    {
243
        parent::tearDown();
244
245
        if ($this->createdBookId !== null) {
246
            if (null === $this->client) {
247
                // Create a client to browse the application
248
                $this->client = static::createClient();
249
            }
250
251
            // Get the router
252
            /** @var RouterInterface $router */
253
            $router = static::getContainer()->get('router');
254
255
            // Generate delete URL
256
            $deleteUrl = $router->generate('book_delete_post', ['id' => $this->createdBookId]);
257
258
            // Send delete request
259
            $this->client->request('POST', $deleteUrl, ['id' => $this->createdBookId]);
260
261
            // Reset the ID to prevent repeated deletions
262
            $this->createdBookId = null;
263
        }
264
    }
265
266
    /**
267
     * testCRUD
268
     *
269
     * @return void
270
     */
271
    public function testCRUD(): void
272
    {
273
        if (null === $this->client) {
274
            // Create a client to browse the application
275
            $this->client = static::createClient();
276
        }
277
278
        // Retrieve the container
279
        $container = $this->client->getContainer();
280
281
        // Retrieve router service
282
        /** @var RouterInterface $router */
283
        $router = $container->get('router');
284
285
        // Get the ManagerRegistry service from container
286
        /** @var ManagerRegistry $doctrine */
287
        $doctrine = $container->get('doctrine');
288
289
        $bookRepository = new BookRepository($doctrine);
290
291
        // Test Create Book
292
        $this->testBookCreatePOST($router, $bookRepository);
293
294
        // Test Update Book
295
        $this->testBookUpdatePOST($router, $bookRepository);
296
297
        // Test Delete Book
298
        $this->testBookDeletePOST($router);
299
    }
300
301
    /**
302
     * testLibrary
303
     *
304
     * Test library route
305
     *
306
     * @return void
307
     */
308
    public function testLibrary(): void
309
    {
310
        if (null === $this->client) {
311
            // Create a client to browse the application
312
            $this->client = static::createClient();
313
        }
314
315
        // Retrieve router service
316
        /** @var RouterInterface $router */
317
        $router = static::getContainer()->get('router');
318
319
        //library
320
321
        // Generate URL from route name
322
        $url = $router->generate('library');
323
324
        // Send a GET request to the route
325
        $crawler = $this->client->request('GET', $url);
326
327
        // Assert the response status code
328
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
329
330
        // Assert that certain content exists in the response
331
        $this->assertStringContainsString('Book: Library', $crawler->filter('title')->text());
332
    }
333
334
    /**
335
     * testBookCreateGET
336
     *
337
     * Test book_create_get route
338
     *
339
     * @return void
340
     */
341
    public function testBookCreateGET(): void
342
    {
343
        if (null === $this->client) {
344
            // Create a client to browse the application
345
            $this->client = static::createClient();
346
        }
347
348
        // Retrieve router service
349
        /** @var RouterInterface $router */
350
        $router = static::getContainer()->get('router');
351
352
        //book_create_get
353
354
        // Generate URL from route name
355
        $url = $router->generate('book_create_get');
356
357
        // Send a GET request to the route
358
        $crawler = $this->client->request('GET', $url);
359
360
        // Assert the response status code
361
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
362
363
        // Assert that certain content exists in the response
364
        $this->assertStringContainsString('Book: Create', $crawler->filter('title')->text());
365
    }
366
367
    /**
368
     * testShowAll
369
     *
370
     * Test book_show_all route
371
     *
372
     * @return void
373
     */
374
    public function testShowAll(): void
375
    {
376
        if (null === $this->client) {
377
            // Create a client to browse the application
378
            $this->client = static::createClient();
379
        }
380
381
        // Retrieve router service
382
        /** @var RouterInterface $router */
383
        $router = static::getContainer()->get('router');
384
385
        //book_show_all
386
387
        // Generate URL from route name
388
        $url = $router->generate('book_show_all');
389
390
        // Send a GET request to the route
391
        $crawler = $this->client->request('GET', $url);
392
393
        // Assert the response status code
394
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
395
396
        // Assert that certain content exists in the response
397
        $this->assertStringContainsString('Book: Show Library', $crawler->filter('title')->text());
398
    }
399
400
    /**
401
     * testShowOne
402
     *
403
     * Test book_show_one route
404
     *
405
     * @return void
406
     */
407
    public function testShowOne(): void
408
    {
409
        if (null === $this->client) {
410
            // Create a client to browse the application
411
            $this->client = static::createClient();
412
        }
413
414
        // Retrieve router service
415
        /** @var RouterInterface $router */
416
        $router = static::getContainer()->get('router');
417
418
        // Boot the kernel
419
        $kernel = self::bootKernel();
420
421
        // Get the ManagerRegistry service from container
422
        /** @var ManagerRegistry $doctrine */
423
        $doctrine = $kernel->getContainer()->get('doctrine');
424
        $bookRepository = new BookRepository($doctrine);
425
426
        $data = $bookRepository->readAllBooks();
427
428
        //If there is books in the library
429
        $id = null;
430
431
        if (count($data['books']) > 0) {
432
            $id = $data['books'][0]['id'];
433
        }
434
435
        if (null === $id) {
436
            $id = '0';
437
        }
438
439
        //book_show_one
440
441
        // Generate URL from route name
442
        $url = $router->generate('book_show_one', ['id' => $id]);
443
444
        // Send a GET request to the route
445
        $crawler = $this->client->request('GET', $url);
446
447
        // Assert the response status code
448
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
449
450
        // Assert that certain content exists in the response
451
        $this->assertStringContainsString('Book: Show Book', $crawler->filter('title')->text());
452
    }
453
454
    /**
455
     * testShowAllUpdate
456
     *
457
     * Test book_show_all_update route
458
     *
459
     * @return void
460
     */
461
    public function testShowAllUpdate(): void
462
    {
463
        if (null === $this->client) {
464
            // Create a client to browse the application
465
            $this->client = static::createClient();
466
        }
467
468
        // Retrieve router service
469
        /** @var RouterInterface $router */
470
        $router = static::getContainer()->get('router');
471
472
        //book_show_all_update
473
474
        // Generate URL from route name
475
        $url = $router->generate('book_show_all_update');
476
477
        // Send a GET request to the route
478
        $crawler = $this->client->request('GET', $url);
479
480
        // Assert the response status code
481
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
482
483
        // Assert that certain content exists in the response
484
        $this->assertStringContainsString('Book: Show Library Update', $crawler->filter('title')->text());
485
    }
486
487
    /**
488
     * testBookUpdateGET
489
     *
490
     * Test book_update_get route
491
     *
492
     * @return void
493
     */
494
    public function testBookUpdateGET(): void
495
    {
496
        if (null === $this->client) {
497
            // Create a client to browse the application
498
            $this->client = static::createClient();
499
        }
500
501
        // Retrieve router service
502
        /** @var RouterInterface $router */
503
        $router = static::getContainer()->get('router');
504
505
        // Boot the kernel
506
        $kernel = self::bootKernel();
507
508
        // Get the ManagerRegistry service from container
509
        /** @var ManagerRegistry $doctrine */
510
        $doctrine = $kernel->getContainer()->get('doctrine');
511
        $bookRepository = new BookRepository($doctrine);
512
513
        $data = $bookRepository->readAllBooks();
514
515
        //If there is books in the library
516
        $id = null;
517
518
        if (count($data['books']) > 0) {
519
            $id = $data['books'][0]['id'];
520
        }
521
522
        if (null === $id) {
523
            $id = '0';
524
        }
525
526
        //book_update_get
527
528
        // Generate URL from route name
529
        $url = $router->generate('book_update_get', ['id' => $id]);
530
531
        // Send a GET request to the route
532
        $crawler = $this->client->request('GET', $url);
533
534
        // Assert the response status code
535
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
536
537
        // Assert that certain content exists in the response
538
        $this->assertStringContainsString('Book: Update book', $crawler->filter('title')->text());
539
    }
540
541
    /**
542
     * testBookShowAllDeleteGET
543
     *
544
     * Test book_show_all_delete_get route
545
     *
546
     * @return void
547
     */
548
    public function testBookShowAllDeleteGET(): void
549
    {
550
        if (null === $this->client) {
551
            // Create a client to browse the application
552
            $this->client = static::createClient();
553
        }
554
555
        // Retrieve router service
556
        /** @var RouterInterface $router */
557
        $router = static::getContainer()->get('router');
558
559
        //book_show_all_delete_get
560
561
        // Generate URL from route name
562
        $url = $router->generate('book_show_all_delete_get');
563
564
        // Send a GET request to the route
565
        $crawler = $this->client->request('GET', $url);
566
567
        // Assert the response status code
568
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
569
570
        // Assert that certain content exists in the response
571
        $this->assertStringContainsString('Book: Show Library Delete', $crawler->filter('title')->text());
572
    }
573
}
574