Fakultas Ilmu Komputer UI

tests.py 39.3 KB
Newer Older
1
2
import json

3
from django.contrib.auth import get_user_model
4
from django.core.exceptions import ValidationError
5
from django.core.files.uploadedfile import SimpleUploadedFile
6
7
from django.db import IntegrityError
from django.test import Client, TestCase
8
9
from django.urls import resolve

10
from administration.utils import id_generator
11
from app.views import UploadMateriView
12
from authentication.models import User
13
from .models import Category, Comment, Materi, Like, Rating
14
15
from .views import (DaftarKatalog, DashboardKontributorView, DetailMateri,
                    ProfilKontributorView, SuksesLoginAdminView,
16
                    SuksesLoginKontributorView, SuntingProfilView,
17
                    ProfilAdminView, CommentsView, SuntingProfilAdminView, RevisiMateriView)
18

19
20
21
22

class DaftarKatalogTest(TestCase):
    def test_daftar_katalog_url_exist(self):
        url = "/"
23
24
        response = Client().get(f"{url}")
        self.assertEqual(response.status_code, 200)
25
26

    def test_daftar_katalog_using_daftar_katalog_template(self):
27
28
29
        response = Client().get("/")
        self.assertTemplateUsed(response, "app/katalog_materi.html")

30
    def test_daftar_katalog_using_daftar_katalog_func(self):
31
        found = resolve("/")
32
33
34
35
        self.assertEqual(found.func.__name__, DaftarKatalog.as_view().__name__)

    def test_fields(self):
        materi = Materi()
36
37
38
        materi.title = "tes"
        materi.cover = "https://cache.umusic.com/_sites/billieeilish/v2/images/pic-red.jpg"
        materi.author = "input"
39
40
        materi.save()

41
42
43
44
        resp = Materi.objects.get(id=materi.id)
        self.assertEqual(resp, materi)


Saul Andre's avatar
Saul Andre committed
45
class DetailMateriTest(TestCase):
46
    def setUp(self):
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        self.client = Client()
        self.admin_credential = {
            "email": "admin@gov.id",
            "password": "passwordtest"
        }
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": "passwordtest"
        }
        self.anonymous_credential = {
            "email": "anonymous@gov.id",
            "password": "passwordtest"
        }
        self.admin = get_user_model().objects.create_user(
            **self.admin_credential, name="Admin", is_admin=True)
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True)
        self.anonymous = get_user_model().objects.create_user(
            **self.anonymous_credential, name="Anonymous"
        )
67
68
        self.cover = SimpleUploadedFile(
            "Cherprang_Areekul40_nJM9dGt.jpg", b"Test file")
69
70
71
72
        self.content = SimpleUploadedFile("Bahan_PA_RKK.pdf", b"Test file")

        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
73
               status="APPROVE", cover=self.cover, content=self.content).save()
74
        self.materi1 = Materi.objects.first()
75
        self.url = "/materi/" + str(self.materi1.id) + "/"
76
77

    def test_detail_materi_url_exist(self):
78
        response = Client().get(self.url)
79
        self.assertEqual(response.status_code, 200)
80
81
82
        self.assertNotEqual(response.status_code, 404)

    def test_detail_materi_using_detail_materi_template(self):
83
        response = Client().get(self.url)
84
        self.assertTemplateUsed(response, 'app/detail_materi.html')
85

Saul Andre's avatar
Saul Andre committed
86
    def test_detail_materi_using_detail_materi_func(self):
87
        found = resolve(self.url)
Saul Andre's avatar
Saul Andre committed
88
        self.assertEqual(found.func.__name__, DetailMateri.as_view().__name__)
89

Saul Andre's avatar
Saul Andre committed
90
    def test_category_models_can_create_new_object(self):
91
92
        test = Category.objects.create(
            id="1", name="medis", description="kategori medis")
Saul Andre's avatar
Saul Andre committed
93
94
95
96
97
        countData = Category.objects.all().count()
        self.assertEqual(1, countData)
        self.assertNotEqual(0, countData)
        self.assertEqual(test.__str__(), "medis")
        self.assertNotEqual(test.__str__(), "saul")
Samuel Dimas's avatar
Samuel Dimas committed
98

Saul Andre's avatar
Saul Andre committed
99
    def test_comment_models_can_create_new_object(self):
100
        test = Comment.objects.create(
101
            username="saul", profile="121212", comment="232323")
Saul Andre's avatar
Saul Andre committed
102
103
104
105
106
        countData = Comment.objects.all().count()
        self.assertEqual(1, countData)
        self.assertNotEqual(0, countData)
        self.assertEqual(test.__str__(), "saul")
        self.assertNotEqual(test.__str__(), "userlain")
107

108
    def test_post_blank_comment(self):
109
110
111
112
        url = self.url
        self.client.login(**self.anonymous_credential)
        response = self.client.post(url, {"comment": ""})
        self.assertIn("error_message", response.context)
113
114
        self.assertIn("Anda belum menuliskan komentar",
                      response.context["error_message"])
115
116
117
118
119

    def test_comment_rendered_to_template(self):
        url = self.url
        self.client.login(**self.contributor_credential)
        self.client.post(url, {"comment": "This is my new comment"})
120
121
        response = Client().get(url)
        self.assertContains(response, "This is my new comment")
122

123
    def test_comment_by_admin(self):
124
125
126
127
        url = self.url
        self.client.login(**self.admin_credential)
        self.client.post(url, {"comment": "This is new comment by Admin"})
        response = self.client.get(url)
128
129
130
        self.assertContains(response, "Admin")

    def test_comment_by_kontributor(self):
131
132
        url = self.url
        self.client.login(**self.contributor_credential)
133
134
        self.client.post(
            url, {"comment": "This is new comment by Contributor"})
135
136
        response = self.client.get(url)
        self.assertContains(response, "Kontributor")
137
138

    def test_comment_by_anonymous(self):
139
140
141
142
143
        url = self.url
        self.client.get("/logout/")
        self.client.login(**self.anonymous_credential)
        self.client.post(url, {"comment": "This is new comment by Anonymous"})
        response = self.client.get(url)
144
        self.assertContains(response, "Anonymous")
145

146
    def test_detail_materi_contains_form_comment(self):
147
        response = self.client.get(self.url)
148
        self.assertContains(response, "Beri komentar...")
149

150
151
152
    def test_delete_comments_by_admin(self):
        url = self.url
        self.client.post(url, {"comment": "This is new comment by Anonymous"})
153
154
        deleteURL = "/delete/" + str(self.materi1.id) + "/" + str(
            Comment.objects.get(comment="This is new comment by Anonymous").id)
155
        self.client.get(deleteURL)
156
157
        self.assertEqual(Comment.objects.all().filter(
            comment="This is new comment by Anonymous").count(), 0)
158
159
160
161
162
163
164
165
        
class ViewCommentsTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": "passwordtest"
        }
166
167
168
169
        self.matt_damon_credential = {
            "email": "mattdamon@gov.id",
            "password": "passwordtest"
        }
170
171
172
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True)
        self.mattDamon = get_user_model().objects.create_user(
173
            **self.matt_damon_credential, name="Matt Damon", is_contributor=True)
174
175
176
177
178
179
        self.cover = SimpleUploadedFile(
            "Cherprang_Areekul40_nJM9dGt.jpg", b"Test file")
        self.content = SimpleUploadedFile("Bahan_PA_RKK.pdf", b"Test file")
        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="APPROVE", cover=self.cover, content=self.content).save()
180
181
182
        Materi(title="Materi 2", author="Matt", uploader=self.mattDamon,
               publisher="Kelas SC", descriptions="Deskripsi Materi 2",
               status="APPROVE", cover=self.cover, content=self.content).save()
183
        self.materi1 = Materi.objects.first()
184
185
186
        self.materi2 = Materi.objects.get(uploader=self.mattDamon)
        self.commentByKontributor = Comment.objects.create(username='saul', comment="this is contributor comment", materi=self.materi1, user=self.contributor)
        self.commentByMatt = Comment.objects.create(username='saul', comment="this is Matt Damon", materi=self.materi2, user=self.mattDamon)
187
        self.url = '/kontributor/' + str(self.contributor.id) + '/comments/'
188
189

    def test_comments_url_exist(self):
190
191
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.url)
192
193
194
195
        self.assertEqual(response.status_code, 200)
        self.assertNotEqual(response.status_code, 404)

    def test_comments_using_comments_template(self):
196
197
198
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, 'comments.html')
199

200
    def test_comments_using_comments_func(self):
201
        self.client.login(**self.contributor_credential)
202
        found = resolve(self.url)
203
        self.assertEqual(found.func.__name__, CommentsView.as_view().__name__)
204
205

    def test_comments_page_render_comments(self):
206
        self.client.login(**self.contributor_credential)
207
        response = self.client.get(self.url)
208
        self.assertContains(response, "this is contributor comment")
209
210
211
212
213
        self.assertNotContains(response, 'bukan comment')
    
    def test_comments_page_only_render_specific_user_comments(self):
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.url)
214
        self.assertContains(response, "this is contributor comment")
215
        self.assertNotContains(response, "this is Matt Damon")
216
217
218
219
220
221

    def test_comments_page_only_for_specific_contributor(self):
        self.client.login(**self.matt_damon_credential)
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
        self.assertNotEqual(response.status_code, 200)
222
        
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
class TemplateLoaderTest(TestCase):
    def test_template_loader_url_exist(self):
        url = "/test-page.html"
        response = Client().get(url)
        self.assertEqual(response.status_code, 200)

    def test_template_loader_using_template_loader_template(self):
        url = "/test-page.html"
        response = Client().get(url)
        expected_template_name = "test-page.html"
        self.assertTemplateUsed(response, expected_template_name)

    def test_template_loader_using_template_loader_func(self):
        url = "/test-page.html"
        found = resolve(url)
        expected_view_name = "pages"
        self.assertEqual(found.func.__name__, expected_view_name)

    def test_template_loader_handle_non_existent_html(self):
        url = "/test.html"
        expected_template_name = "error-404.html"
        response = Client().get(url)
245
        self.assertEqual(response.status_code, 200)
246
        self.assertTemplateUsed(response, expected_template_name)
247

248

249
250
class UploadPageTest(TestCase):
    def setUp(self):
251
        self.client = Client()
252
253
254
255
256
        self.user = User.objects._create_user(email="kontributor@gov.id",
                                              password="kontributor", is_contributor=True)

    def test_upload_page_using_login_func(self):
        found = resolve("/unggah/")
257
258
        self.assertEqual(found.func.__name__,
                         UploadMateriView.as_view().__name__)
259
260

    def test_uplaod_page_url_is_exist(self):
261
        # Positive test
262
263
264
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get("/unggah/")
265
        self.assertEqual(response.status_code, 200)
266
267
268

        # Negative tests
        self.client.login(email="kontributor@gov.id",
269
                          password="kontributor")
270
271
272
273
274
275
        response = Client().get("/fake/")
        self.assertEqual(response.status_code, 404)

    def test_upload_page_template(self):
        url = "/unggah/"
        self.client.login(email="kontributor@gov.id",
276
                          password="kontributor")
277
278
        response = self.client.get(url)
        expected_template_name = "unggah.html"
279
        self.assertTemplateUsed(response, expected_template_name)
280
281
282

    def test_upload_page_title(self):
        self.client.login(email="kontributor@gov.id",
283
                          password="kontributor")
284
285
286
287
288
289
290
291
292
293
        response = self.client.get("/unggah/")

        # Positive tests
        self.assertContains(response, "Unggah Materi")

        # Negative tests
        self.assertNotContains(response, "Anything")

    def test_upload_page_form_field(self):
        self.client.login(email="kontributor@gov.id",
294
                          password="kontributor")
295
296
297
298
299
300
301
        response = self.client.get("/unggah/")

        # Positive tests
        self.assertContains(response, "title")

        # Negative tests
        self.assertNotContains(response, "anything")
302
303
304
305
306

class DashboardKontributorViewTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
307
                                                           password="kontributor")
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/dashboard/"
        self.view = DashboardKontributorView
        self.template_name = "dashboard.html"

    def test_dashboard_kontributor_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_dashboard_kontributor_template(self):
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_dashboard_kontributor_url(self):
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_dashboard_kontributor_access(self):
        # Kontributor
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

        # Admin
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
        # Logout
        self.client.logout()
358

359
360
361
362
        # Anonim
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
363

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
class ProfilAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
                                                           password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/profil-admin/"
        self.view = ProfilAdminView
        self.template_name = "profil-admin.html"

    def test_profil_Admin_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_profil_admin_template(self):
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_profil_admin_url(self):
        # Login
        response = self.client.get(self.url)
        self.assertNotEqual(response.status_code, 200)

        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()
401

402
403
404
405
class ProfilKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
406
                                                           password="kontributor")
407
408
409
410
411
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/profil/"
        self.view = ProfilKontributorView
        self.template_name = "profil.html"
412

413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    def test_profil_kontributor_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_profil_kontributor_template(self):
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_profil_kontributor_url(self):
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_profil_kontributor_access(self):
        # Kontributor
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

        # Admin
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
        # Logout
        self.client.logout()
457

458
459
460
461
        # Anonim
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
462
463


464
465
466
467
class SuntingProfilTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
468
                                                           password="kontributor")
469
470
471
472
473
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/sunting/"
        self.view = SuntingProfilView
        self.template_name = "sunting.html"
474

475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
    def test_sunting_profile_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_sunting_profile_template(self):
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_sunting_profile_url(self):
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_sunting_profile_access(self):
        # Kontributor
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
508
509
        self.client.logout()

510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
class SuntingProfilAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
                                                           password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/sunting-admin/"
        self.view = SuntingProfilAdminView
        self.template_name = "sunting_admin.html"

    def test_sunting_profile_admin_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_sunting_profile_admin_template(self):
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_sunting_profile_admin_url(self):
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_sunting_profile_admin_access(self):
        # Kontributor
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

556

557
558
559
560
class SuksesLoginKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
561
                                                           password="kontributor")
562
563
564
565
566
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/sukses-kontributor/"
        self.view = SuksesLoginKontributorView
        self.template_name = "sukses_kontri.html"
567

568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
    def test_sukses_login_kontributor_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_sukses_login_kontributor_template(self):
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_sukses_login_kontributor_url(self):
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_sukses_login_kontributor_access(self):
        # Kontributor
        # Login
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

603

604
605
606
607
class SuksesLoginAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
608
                                                           password="kontributor")
609
610
611
612
613
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/sukses-admin/"
        self.view = SuksesLoginAdminView
        self.template_name = "sukses_admin.html"
614

615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
    def test_sukses_login_admin_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_sukses_login_admin_template(self):
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_sukses_login_admin_url(self):
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_sukses_login_admin_access(self):
        # Kontributor
        # Login
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866


class LikeMateriTest(TestCase):
    def setUp(self):
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
        self.url_like = '/materi/like/'
        content = b"Test file"
        self.cover = SimpleUploadedFile(
            "cover.jpg",
            content
        )
        self.content = SimpleUploadedFile(
            "content.txt",
            content
        )
        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="PENDING", cover=self.cover, content=self.content).save()
        self.materi1 = Materi.objects.first()
        self.url_materi = f'/materi/{self.materi1.id}/'

    def test_get_method(self):
        response = self.client.get(self.url_like)
        response = json.loads(response.content)
        self.assertEqual(response.get("success", None), False)

    def test_like_materi(self):
        # Verify that materi doesn't have any like to start with
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 0)

        # Like a materi 
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
        payload = {
            'materi_id': materi_id,
            'session_id': session_id
        }
        ajax_response = Client().post(self.url_like, payload)
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 1)

    def test_unlike_materi(self):
        # Verify that materi doesn't have any like to start with
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 0)

        # Like a materi 
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
        payload = {
            'materi_id': materi_id,
            'session_id': session_id
        }
        ajax_response = Client().post(self.url_like, payload)
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 1)

        # Unlike a materi 
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
        payload = {
            'materi_id': materi_id,
            'session_id': session_id
        }
        ajax_response = Client().post(self.url_like, payload)
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 0)

    def test_2_client_like_materi(self):
        # Verify that materi doesn't have any like to start with
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 0)

        # Client 1 like a materi 
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
        payload = {
            'materi_id': materi_id,
            'session_id': session_id
        }
        ajax_response = Client().post(self.url_like, payload)
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 1)

        # Client 2 like a materi 
        response = Client().get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
        payload = {
            'materi_id': materi_id,
            'session_id': session_id
        }
        ajax_response = Client().post(self.url_like, payload)
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 2)

    def test_incomplete_like_parameter(self):
        # Verify that materi doesn't have any like to start with
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 0)

        # missing session id 
        response = self.client.get(self.url_materi)
        materi_id = response.context["materi_data"].id
        payload = {
            'materi_id': materi_id,
        }
        ajax_response = Client().post(self.url_like, payload)
        ajax_response = json.loads(ajax_response.content) 
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 0)
        self.assertEqual(ajax_response.get("success", None), False)
        
        # missing materi id 
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        payload = {
            'session_id': session_id
        }
        ajax_response = Client().post(self.url_like, payload)
        ajax_response = json.loads(ajax_response.content) 
        num_of_likes = Like.objects.filter(materi = self.materi1).count()
        self.assertEqual(num_of_likes, 0)
        self.assertEqual(ajax_response.get("success", None), False)


class ViewMateriStatissticsTest(TestCase):
    def setUp(self):
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
        content = b"Test file"
        self.cover = SimpleUploadedFile(
            "cover.jpg",
            content
        )
        self.content = SimpleUploadedFile(
            "content.txt",
            content
        )
        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="PENDING", cover=self.cover, content=self.content).save()
        self.materi1 = Materi.objects.first()
        self.url = f"/materi/{self.materi1.id}/view"

    # Test single view 
    def test_count_one_materi_view(self):
        response = self.client.get(self.url)
        num_of_views = self.materi1.baca.all().count()
        self.assertEqual(num_of_views, 1)

    # Test more than one view
    def test_count_more_than_one_materi_view(self):
        response = self.client.get(self.url)
        num_of_views = self.materi1.baca.all().count()
        self.assertEqual(num_of_views, 1)

        response = Client().get(self.url)
        num_of_views = self.materi1.baca.all().count()
        self.assertEqual(num_of_views, 2)

class DownloadMateriStatissticsTest(TestCase):
    def setUp(self):
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
        content = b"Test file"
        self.cover = SimpleUploadedFile(
            "cover.jpg",
            content
        )
        self.content = SimpleUploadedFile(
            "content.txt",
            content
        )
        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="PENDING", cover=self.cover, content=self.content).save()
        self.materi1 = Materi.objects.first()
        self.url = f"/materi/{self.materi1.id}/unduh"

    # Test single download 
    def test_count_one_materi_download(self):
        response = self.client.get(self.url)
        num_of_downloads = self.materi1.unduh.all().count()
        self.assertEqual(num_of_downloads, 1)

    # Test more than one download
    def test_count_more_than_one_materi_download(self):
        response = self.client.get(self.url)
        num_of_downloads = self.materi1.unduh.all().count()
        self.assertEqual(num_of_downloads, 1)

        response = Client().get(self.url)
        num_of_downloads = self.materi1.unduh.all().count()
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
        self.assertEqual(num_of_downloads, 2)

class RevisiMateriTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.view = RevisiMateriView
        self.template_name = "revisi.html"

        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.cover = SimpleUploadedFile(
            "cover.jpg",
            b"Test file"
        )
        self.content = SimpleUploadedFile(
            "content.txt",
            b"Test file"
        )
        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="REVISION", cover=self.cover, content=self.content).save()

        self.materi1 = Materi.objects.first()
        self.url = "/revisi/materi/" + str(self.materi1.id) + "/"

    def test_revisi_materi_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_revisi_materi_template(self):
        # Login
        self.client.login(**self.contributor_credential)
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_revisi_materi_url(self):
        # Login
        self.client.login(**self.contributor_credential)
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_revisi_materi_access(self):
        # Kontributor
        # Login
        self.client.login(**self.contributor_credential)
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
        self.client.logout()


class RatingMateriTest(TestCase):
    def setUp(self):
        self.url = '/administration/'
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
        self.user_one_credential = {
            "email": "user_one@user.id",
            "password": id_generator()
        }
        self.user_two_credential = {
            "email": "user_two@user.id",
            "password": id_generator()
        }
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.user_one = get_user_model().objects.create_user(**self.user_one_credential, name="User One")
        self.user_two = get_user_model().objects.create_user(**self.user_two_credential, name="User Two")
        self.cover = SimpleUploadedFile(
            "cover.jpg",
            b"Test file"
        )
        self.content = SimpleUploadedFile(
            "content.txt",
            b"Test file"
        )
        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="PENDING", cover=self.cover, content=self.content).save()
        Materi(title="Materi Dua", author="Author", uploader=self.contributor,
               publisher="Publisher", descriptions="Deskripsi Materi Dua",
               status="APPROVE", cover=self.cover, content=self.content).save()
        self.materi1 = Materi.objects.all()[0]
        self.materi2 = Materi.objects.all()[1]

    def test_rating_model_can_be_created_with_proper_parameter(self):
        Rating(materi=self.materi1, user=self.user_one, score=5).save()
        rating = Rating.objects.first()
        self.assertEqual(rating.materi, self.materi1)
        self.assertEqual(rating.user, self.user_one)
        self.assertTrue(0 < rating.score < 6)
        self.assertEqual(rating.__str__(), "Material:Materi 1 | User:User One | Rating:5")

    def test_rating_model_should_not_be_created_with_rating_more_than_5(self):
        with self.assertRaises(ValidationError) as context:
            Rating(materi=self.materi1, user=self.user_one, score=6).save()
        self.assertTrue('Rating score must be integer between 1-5' in str(context.exception))

    def test_rating_model_should_not_be_created_with_rating_less_than_1(self):
        with self.assertRaises(ValidationError) as context:
            Rating(materi=self.materi1, user=self.user_one, score=0).save()
        self.assertTrue('Rating score must be integer between 1-5' in str(context.exception))

    def test_one_materi_should_be_able_to_be_related_to_multiple_rating(self):
        Rating(materi=self.materi1, user=self.user_one, score=1).save()
        Rating(materi=self.materi1, user=self.user_two, score=2).save()
        rating_one = Rating.objects.get(user=self.user_one)
        rating_two = Rating.objects.get(user=self.user_two)
        self.assertEqual(rating_one.materi, self.materi1)
        self.assertEqual(rating_two.materi, self.materi1)
        self.assertEqual(rating_one.user, self.user_one)
        self.assertEqual(rating_two.user, self.user_two)

    def test_one_user_should_be_able_to_be_related_to_two_rating(self):
        Rating(materi=self.materi1, user=self.user_one, score=3).save()
        Rating(materi=self.materi2, user=self.user_one, score=3).save()
        rating_one = Rating.objects.filter(materi=self.materi1).first()
        rating_two = Rating.objects.filter(materi=self.materi2).first()
        self.assertEqual(rating_one.materi, self.materi1)
        self.assertEqual(rating_two.materi, self.materi2)
        self.assertEqual(rating_one.user, self.user_one)
        self.assertEqual(rating_two.user, self.user_one)

    def test_two_rating_should_not_have_same_user_and_materi(self):
        with self.assertRaises(IntegrityError) as context:
            Rating(materi=self.materi1, user=self.user_one, score=1).save()
            Rating(materi=self.materi1, user=self.user_one, score=2).save()
        self.assertTrue('already exists' in str(context.exception))

    def test_materi_in_rating_should_not_be_null(self):
        with self.assertRaises(IntegrityError):
            Rating(user=self.user_one, score=1).save()

    def test_user_in_rating_should_not_be_null(self):
        with self.assertRaises(IntegrityError):
            Rating(materi=self.materi1, score=1).save()

    def test_score_in_rating_should_not_be_null(self):
        with self.assertRaises(TypeError):
            Rating(materi=self.materi1, user=self.user_one).save()