Fakultas Ilmu Komputer UI

tests.py 49.2 KB
Newer Older
1
import json, tempfile, os
2
from io import StringIO
3

4
from django.conf import settings
5
from django.contrib.auth import get_user_model
6
from django.core.exceptions import PermissionDenied, ValidationError
7
from django.core.files.uploadedfile import SimpleUploadedFile
8
from django.core.management import call_command
9
from django.db import IntegrityError
10
from django.test import Client, TestCase
11
12
from django.urls import resolve

13
from administration.models import VerificationSetting, VerificationReport
14
from administration.utils import id_generator
15
16
from app.forms import SuntingProfilForm
from app.views import UploadMateriView, add_rating_materi
17
from authentication.models import User
18
from .models import Category, Comment, Materi, Like, Rating
19
20
from .views import (DaftarKatalog, DashboardKontributorView, DetailMateri,
                    ProfilKontributorView, SuksesLoginAdminView,
21
                    SuksesLoginKontributorView, SuntingProfilView,
22
                    ProfilAdminView, PostsView, SuntingProfilAdminView, RevisiMateriView)
23
from app.forms import SuntingProfilForm
24
from app.utils.fileManagementUtil import get_random_filename, remove_image_exifdata
25

26
27
28
29

class DaftarKatalogTest(TestCase):
    def test_daftar_katalog_url_exist(self):
        url = "/"
30
31
        response = Client().get(f"{url}")
        self.assertEqual(response.status_code, 200)
32
33

    def test_daftar_katalog_using_daftar_katalog_template(self):
34
35
36
        response = Client().get("/")
        self.assertTemplateUsed(response, "app/katalog_materi.html")

37
    def test_daftar_katalog_using_daftar_katalog_func(self):
38
        found = resolve("/")
39
40
41
42
        self.assertEqual(found.func.__name__, DaftarKatalog.as_view().__name__)

    def test_fields(self):
        materi = Materi()
43
44
45
        materi.title = "tes"
        materi.cover = "https://cache.umusic.com/_sites/billieeilish/v2/images/pic-red.jpg"
        materi.author = "input"
46
47
        materi.save()

48
49
50
51
        resp = Materi.objects.get(id=materi.id)
        self.assertEqual(resp, materi)


Saul Andre's avatar
Saul Andre committed
52
class DetailMateriTest(TestCase):
53
    def setUp(self):
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
        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"
        )
74
75
        self.cover = SimpleUploadedFile(
            "Cherprang_Areekul40_nJM9dGt.jpg", b"Test file")
76
77
78
79
        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",
80
               status="APPROVE", cover=self.cover, content=self.content).save()
81
        self.materi1 = Materi.objects.first()
82
        self.url = "/materi/" + str(self.materi1.id) + "/"
83
84

    def test_detail_materi_url_exist(self):
85
        response = Client().get(self.url)
86
        self.assertEqual(response.status_code, 200)
87
88
89
        self.assertNotEqual(response.status_code, 404)

    def test_detail_materi_using_detail_materi_template(self):
90
        response = Client().get(self.url)
91
        self.assertTemplateUsed(response, 'app/detail_materi.html')
92

Saul Andre's avatar
Saul Andre committed
93
    def test_detail_materi_using_detail_materi_func(self):
94
        found = resolve(self.url)
Saul Andre's avatar
Saul Andre committed
95
        self.assertEqual(found.func.__name__, DetailMateri.as_view().__name__)
96

Saul Andre's avatar
Saul Andre committed
97
    def test_category_models_can_create_new_object(self):
98
99
        test = Category.objects.create(
            id="1", name="medis", description="kategori medis")
Saul Andre's avatar
Saul Andre committed
100
101
102
103
104
        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
105

Saul Andre's avatar
Saul Andre committed
106
    def test_comment_models_can_create_new_object(self):
107
        test = Comment.objects.create(
108
            username="saul", profile="121212", comment="232323")
Saul Andre's avatar
Saul Andre committed
109
110
111
112
113
        countData = Comment.objects.all().count()
        self.assertEqual(1, countData)
        self.assertNotEqual(0, countData)
        self.assertEqual(test.__str__(), "saul")
        self.assertNotEqual(test.__str__(), "userlain")
114

115
    def test_post_blank_comment(self):
116
117
118
119
        url = self.url
        self.client.login(**self.anonymous_credential)
        response = self.client.post(url, {"comment": ""})
        self.assertIn("error_message", response.context)
120
121
        self.assertIn("Anda belum menuliskan komentar",
                      response.context["error_message"])
122
123
124
125
126

    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"})
127
128
        response = Client().get(url)
        self.assertContains(response, "This is my new comment")
129

130
    def test_comment_by_admin(self):
131
132
133
134
        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)
135
136
137
        self.assertContains(response, "Admin")

    def test_comment_by_kontributor(self):
138
139
        url = self.url
        self.client.login(**self.contributor_credential)
140
141
        self.client.post(
            url, {"comment": "This is new comment by Contributor"})
142
143
        response = self.client.get(url)
        self.assertContains(response, "Kontributor")
144
145

    def test_comment_by_anonymous(self):
146
147
148
149
150
        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)
151
        self.assertContains(response, "Anonymous")
152

153
    def test_detail_materi_contains_form_comment(self):
154
        response = self.client.get(self.url)
155
        self.assertContains(response, "Beri komentar...")
156

157
158
159
    def test_delete_comments_by_admin(self):
        url = self.url
        self.client.post(url, {"comment": "This is new comment by Anonymous"})
160
161
        deleteURL = "/delete/" + str(self.materi1.id) + "/" + str(
            Comment.objects.get(comment="This is new comment by Anonymous").id)
162
        self.client.get(deleteURL)
163
164
        self.assertEqual(Comment.objects.all().filter(
            comment="This is new comment by Anonymous").count(), 0)
165

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210

class PostsViewTest(TestCase):

    @classmethod
    def generate_posts_data(cls, user):
        POST_COUNT = 3
        COMMENTS_COUNT_PER_POST = [1, 0, 3]

        assert POST_COUNT == len(COMMENTS_COUNT_PER_POST)

        sample_file = SimpleUploadedFile("Test.jpg", b"Test file")
        sample_category = Category.objects.create(name="Test Category")

        post_comment_group_dict = {}
        for _ in range(POST_COUNT):
            post = Materi.objects.create(
                uploader=user,
                cover=sample_file,
                content=sample_file,
            )
            post.categories.add(sample_category)

            post_comment_group_dict[post.id] = {
                "data": post,
                "comments": [],
            }

        for i, post_id in enumerate(post_comment_group_dict):
            post = post_comment_group_dict[post_id]["data"]

            for _ in range(COMMENTS_COUNT_PER_POST[i]):
                comment = Comment.objects.create(materi=post)
                post_comment_group_dict[post_id]["comments"].append(comment)

            # order by latest (-timestamp)
            post_comment_group_dict[post_id]["comments"].reverse()

        return post_comment_group_dict

    @classmethod
    def setUpTestData(cls):
        cls.url = '/posts/'
        cls.user_credentials = {
            "email": "user@email.com",
            "password": "justpass"
211
        }
212
213
        cls.user = User.objects.create_user(**cls.user_credentials, is_contributor=True)
        cls.data = cls.generate_posts_data(cls.user)
214

215
216
217
218
219
220
221
    def _request_as_user(self):
        self.client.login(**self.user_credentials)
        return self.client.get(self.url)

    def test_url_resolves_to_posts_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, PostsView.as_view().__name__)
222

223
224
    def test_returns_200_on_authenticated_access(self):
        response = self._request_as_user()
225
226
        self.assertEqual(response.status_code, 200)

227
    def test_returns_403_on_unauthenticated_access(self):
228
        response = self.client.get(self.url)
229
230
        self.assertRaises(PermissionDenied)
        self.assertEqual(response.status_code, 403)
231

232
233
234
    def test_returns_correct_template(self):
        response = self._request_as_user()
        self.assertTemplateUsed(response, "user_uploaded_posts.html")
235

236
237
    def test_success_returns_correct_comment_post_groupings_by_context(self):
        post_comment_group_dict = self.data
238

239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
        response = self._request_as_user()

        response_user = response.context_data["user"]
        self.assertEqual(response_user, self.user)

        response_data = response.context_data["posts"]
        actual_data = post_comment_group_dict
        self.assertDictEqual(response_data, actual_data)

    def test_html_contains_grouped_posts_and_comments(self):
        response = self._request_as_user()

        posts = list(self.data.keys())
        comments = {
            i: [comment.id for comment in self.data[post_id]["comments"]]
            for i, post_id in enumerate(posts)
        }

        self.assertRegex(
258
            str(response.content),
259
            rf'.*(<div id="post-{posts[2]}">)' + \
260
261
262
            rf'.*(<div id="post-{posts[2]}-comment-{comments[2][0]}">)' + \
            rf'.*(<div id="post-{posts[2]}-comment-{comments[2][1]}">)' + \
            rf'.*(<div id="post-{posts[2]}-comment-{comments[2][2]}">)' + \
263
264
            rf'.*(<div id="post-{posts[1]}">)' + \
            rf'.*(<div id="post-{posts[0]}">)' + \
265
            rf'.*(<div id="post-{posts[0]}-comment-{comments[0][0]}">)'
266
        )
267

268

269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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)
291
        self.assertEqual(response.status_code, 200)
292
        self.assertTemplateUsed(response, expected_template_name)
293

294

295
296
class UploadPageTest(TestCase):
    def setUp(self):
297
        self.client = Client()
298
299
300
301
302
        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/")
303
304
        self.assertEqual(found.func.__name__,
                         UploadMateriView.as_view().__name__)
305
306

    def test_uplaod_page_url_is_exist(self):
307
        # Positive test
308
309
310
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get("/unggah/")
311
        self.assertEqual(response.status_code, 200)
312
313
314

        # Negative tests
        self.client.login(email="kontributor@gov.id",
315
                          password="kontributor")
316
317
318
319
320
321
        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",
322
                          password="kontributor")
323
324
        response = self.client.get(url)
        expected_template_name = "unggah.html"
325
        self.assertTemplateUsed(response, expected_template_name)
326
327
328

    def test_upload_page_title(self):
        self.client.login(email="kontributor@gov.id",
329
                          password="kontributor")
330
331
332
333
334
335
336
337
338
339
        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",
340
                          password="kontributor")
341
342
343
344
345
346
347
        response = self.client.get("/unggah/")

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

        # Negative tests
        self.assertNotContains(response, "anything")
348

349

350
351
352
353
class DashboardKontributorViewTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
354
                                                           password="kontributor")
355
356
357
358
359
360
361
362
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
401
402
403
404
        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()
405

406
407
408
409
        # Anonim
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
410

411

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
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()
449

450

451
452
453
454
class ProfilKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
455
                                                           password="kontributor")
456
457
458
459
460
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/profil/"
        self.view = ProfilKontributorView
        self.template_name = "profil.html"
461

462
463
464
465
466
467
468
469
470
471
472
473
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
    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()
506

507
508
509
510
        # Anonim
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
511
512


513
514
515
516
class SuntingProfilTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
517
                                                           password="kontributor")
518
519
520
521
522
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/sunting/"
        self.view = SuntingProfilView
        self.template_name = "sunting.html"
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
556
    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
557
558
        self.client.logout()

559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
    def test_sunting_profile_access_anonymous(self):
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)

    def test_sunting_profile_autofocus(self):
        form_data = {
            "email": "kontributor@gov.id",
            "name": "kontributor",
            "instansi": "instansi",
            "nik": "nik",
            "alamat": "alamat",
            "nomor_telpon": "123456789",
            "twitter": "Twit",
            "instagram": "https://instagram.com/test_ig"
        }
        form = SuntingProfilForm(data=form_data)

        # Test
        self.assertEqual(form.fields["twitter"].widget.attrs.get("autofocus"), "")
        self.assertEqual(form.fields["instagram"].widget.attrs.get("autofocus"), None)


582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
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()

628

629
630
631
632
class SuksesLoginKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
633
                                                           password="kontributor")
634
635
636
637
638
        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"
639

640
641
642
643
644
645
646
647
648
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
    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()

675

676
677
678
679
class SuksesLoginAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
680
                                                           password="kontributor")
681
682
683
684
685
        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"
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
    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()
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


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
756
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
757
758
        self.assertEqual(num_of_likes, 0)

759
        # Like a materi
760
761
762
763
764
765
766
767
        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)
768
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
769
770
771
772
        self.assertEqual(num_of_likes, 1)

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

776
        # Like a materi
777
778
779
780
781
782
783
784
        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)
785
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
786
787
        self.assertEqual(num_of_likes, 1)

788
        # Unlike a materi
789
790
791
792
793
794
795
796
        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)
797
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
798
799
800
801
        self.assertEqual(num_of_likes, 0)

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

805
        # Client 1 like a materi
806
807
808
809
810
811
812
813
        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)
814
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
815
816
        self.assertEqual(num_of_likes, 1)

817
        # Client 2 like a materi
818
819
820
821
822
823
824
825
        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)
826
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
827
828
829
830
        self.assertEqual(num_of_likes, 2)

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

834
        # missing session id
835
836
837
838
839
840
        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)
841
        ajax_response = json.loads(ajax_response.content)
842
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
843
844
        self.assertEqual(num_of_likes, 0)
        self.assertEqual(ajax_response.get("success", None), False)
845
846

        # missing materi id
847
848
849
850
851
852
        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)
853
        ajax_response = json.loads(ajax_response.content)
854
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
        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"

884
    # Test single view
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
    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)

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
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"

926
    # Test single download
927
928
929
930
931
932
933
934
935
936
937
938
939
    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()
940
941
        self.assertEqual(num_of_downloads, 2)

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
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
For faster browsing, not all history is shown. View entire blame