Fakultas Ilmu Komputer UI

tests.py 163 KB
Newer Older
1
2
3
4
5
import base64
import datetime as dt
import json
import os
import random
6
import re
7
import tempfile
8
import time
9
10
import itertools
from django.test import override_settings
11
12
13
from datetime import datetime
from io import StringIO
from time import sleep
14

15
16
17
18
19
20
import mock
import pandas as pd
import pytz
from administration.models import VerificationReport, VerificationSetting
from administration.utils import id_generator
from authentication.models import User
21
from bs4 import BeautifulSoup
22
from digipus.settings import TIME_ZONE
23
from django.conf import settings
24
from django.contrib import messages as dj_messages
25
from django.contrib.auth import get_user_model
26
from django.core import mail, serializers
27
from django.core.exceptions import PermissionDenied, ValidationError
28
from django.core.files import File
29
from django.core.files.uploadedfile import SimpleUploadedFile
30
from django.core.management import call_command
31
from django.db.utils import IntegrityError
32
from pytz import timezone, UTC
33
34
35
36
from django.test import (Client, RequestFactory, TestCase, TransactionTestCase,
                         override_settings)
from django.urls import resolve, reverse
from django.utils import timezone
37

38
from app.forms import SuntingProfilForm, year_choices
39
40
from app.utils.fileManagementUtil import (get_random_filename,
                                          remove_image_exifdata)
41
from app.utils.PasswordValidator import PasswordPolicyValidator
42
43
44
45
46
47
48
49
50
51
52
53
from app.views import UploadMateriHTML, add_rating_materi

from .models import (Category, Comment, DislikeComment, DownloadStatistics,
                     Like, LikeComment, Materi, Rating, RatingContributor,
                     ReadLater, ReqMaterial, Review, ViewStatistics)
from .services import DetailMateriService
from .views import (DaftarKatalog, DashboardKontributorView, DetailMateri,
                    KatalogPerKontributorView, MateriFavorite,
                    PasswordChangeViews, PostsView, ProfilView, ReqMateriView,
                    RevisiMateriView, SuksesLoginAdminView,
                    SuksesLoginKontributorView, SuntingProfilView,
                    UploadMateriExcelView, UploadMateriView, password_success)
54

55
ERROR_403_MESSAGE = "Kamu harus login untuk mengakses halaman ini"
Saul Andre's avatar
Saul Andre committed
56

57
58
59
from statistics import mean

import requests
60
61
from django.test import LiveServerTestCase
from selenium import webdriver
62
from selenium.common.exceptions import NoSuchElementException
63
64
65
66
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager

67

68
69
70
71
72
73
74
75
76
77
78
79
80
class DaftarKatalogTest(TestCase):
    def test_daftar_katalog_url_exist(self):
        url = "/"
        response = Client().get(f"{url}")
        self.assertEqual(response.status_code, 200)

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

    def test_daftar_katalog_using_daftar_katalog_func(self):
        found = resolve("/")
        self.assertEqual(found.func.__name__, DaftarKatalog.as_view().__name__)
81

82
83
84
85
86
87
    def test_fields(self):
        materi = Materi()
        materi.title = "tes"
        materi.cover = "https://cache.umusic.com/_sites/billieeilish/v2/images/pic-red.jpg"
        materi.author = "input"
        materi.save()
88

89
90
        resp = Materi.objects.get(id=materi.id)
        self.assertEqual(resp, materi)
91

92
93
94
95

class DaftarKatalogSortingByJumlahUnduhTest(TestCase):
    def setUp(self):
        self.client = Client()
96

97
98
99
100
        self.contributor_credential = {
        "email": "kontributor@gov.id",
        "password": "passwordtest"
            }
101

102
103
104
105
        self.contributor_credential_2 = {
                "email": "kontributor2@gov.id",
                "password": "passwordtest"
            }
106

107
108
109
110
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor 1", is_contributor=True)
        self.contributor2 = get_user_model().objects.create_user(
            **self.contributor_credential_2, name="Kontributor 2", is_contributor=True)
111

112
113
114
        self.cover = SimpleUploadedFile(
            "Cherprang_Areekul40_nJM9dGt.jpg", b"Test file")
        self.content = SimpleUploadedFile("Bahan_PA_RKK.pdf", b"Test file")
115

116
117
118
119
120
121
122
        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()
        time.sleep(1)
        Materi(title="Materi 2", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 2",
               status="APPROVE", cover=self.cover, content=self.content).save()
123

124
        self.last_uploaded_material = Materi.objects.last()
125

126
127
        material_unduh_url = f"/materi/{self.last_uploaded_material.id}/unduh"
        self.client.get(material_unduh_url)
128

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    def test_sorting_by_jumlah_unduh(self):
        response = self.client.get("/?sort=jumlah_unduh")
        self.assertRegex(str(response.content), rf'.*Materi 2.*Materi 1.*')

class DaftarKatalogSortingByJumlahTampilanTest(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()

        Materi(title="Materi 2", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="PENDING", cover=self.cover, content=self.content).save()
        self.materi2 = Materi.objects.last()
        self.url = f"/materi/{self.materi2.id}/view"

    def sorting_by_jumlah_tampilan(self):
        self.client.get(self.url)
        response = self.client.get("/?sort=jumlah_tampilan")
        self.assertRegex(str(response.content), rf'.*Materi 2.*Materi 1.*')
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

class DaftarKatalogSortingByTerhangatTest(TestCase):
    @classmethod
    def generate_view_materi(cls, materi, view_count):
        for _ in itertools.repeat(None, view_count):
            ViewStatistics.objects.create(materi=materi)

    def get_displayed_materi_in_number(self):
        response = self.client.get("/?sort=terhangat")
        lst = [int(id) for id in re.findall(r"Materi\s(\d+)[^\d]", 
                                            response.content.decode())]
        return lst

    def setUp(self):
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
        self.contributor = get_user_model().objects.create_user(
            name="Kontributor",
            is_contributor=True,
            **self.contributor_credential, 
        )
        self.client = Client()
        content = b"Test file"
        self.cover = SimpleUploadedFile(
            "cover.jpg",
            content
        )
        self.content = SimpleUploadedFile(
            "content.txt",
            content
        )

        self.materi_data = {
            "author": "Reyhan",
            "uploader": self.contributor,
            "publisher": "Publisher",
            "descriptions": "Deskripsi Materi",
            "status": "APPROVE",
            "cover": self.cover,
            "content": self.content,
        }

    def test_1_week_difference_give_1_hot_score_difference(self):
        materi1 = Materi.objects.create(
            title='Materi 1',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi2 = Materi.objects.create(
            title='Materi 2',
            date_created=datetime(2020, 10, 8, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi3 = Materi.objects.create(
            title='Materi 3',
            date_created=datetime(2020, 10, 15, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        self.generate_view_materi(materi1, 1)
        self.generate_view_materi(materi2, 1)
        self.generate_view_materi(materi3, 1)

        self.assertAlmostEqual(materi3.hot_score - materi2.hot_score, 1)
        self.assertAlmostEqual(materi2.hot_score - materi1.hot_score, 1)

    def test_10_exponential_view_count_difference_give_1_hot_score_difference(self):
        materi1 = Materi.objects.create(
            title='Materi 1',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi2 = Materi.objects.create(
            title='Materi 2',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi3 = Materi.objects.create(
            title='Materi 3',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        self.generate_view_materi(materi1, 1)
        self.generate_view_materi(materi2, 10)
        self.generate_view_materi(materi3, 100)

        self.assertAlmostEqual(materi3.hot_score - materi2.hot_score, 1)
        self.assertAlmostEqual(materi2.hot_score - materi1.hot_score, 1)

    def test_0_and_1_views_has_the_same_hot_score(self):
        materi1 = Materi.objects.create(
            title='Materi 1',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi2 = Materi.objects.create(
            title='Materi 2',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        self.generate_view_materi(materi1, 0)
        self.generate_view_materi(materi2, 1)

        self.assertAlmostEqual(materi1.hot_score, materi2.hot_score)
        
    def test_page_has_option_sort_by_hottest(self):
        response = self.client.get("/")
        self.assertIn("terhangat", response.content.decode())

    def test_page_display_sort_by_hottest(self):
        materi1 = Materi.objects.create(
            title='Materi 1',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi2 = Materi.objects.create(
            title='Materi 2',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi3 = Materi.objects.create(
            title='Materi 3',
            date_created=datetime(2020, 10, 8, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi4 = Materi.objects.create(
            title='Materi 4',
            date_created=datetime(2020, 10, 9, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        self.generate_view_materi(materi1, 11)
        self.generate_view_materi(materi2, 10)
        self.generate_view_materi(materi3, 1)
        self.generate_view_materi(materi4, 1)

        lst = self.get_displayed_materi_in_number()
        self.assertEqual(lst, [4, 1, 3, 2])

    def test_prefer_newest_materi_if_hot_score_is_same(self):
        materi1 = Materi.objects.create(
            title='Materi 1',
            date_created=datetime(2020, 10, 1, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        materi2 = Materi.objects.create(
            title='Materi 2',
            date_created=datetime(2020, 10, 8, 7, 0, 0, tzinfo=UTC),
            **self.materi_data
        )
        self.generate_view_materi(materi1, 10)
        self.generate_view_materi(materi2, 1)

        lst = self.get_displayed_materi_in_number()
        self.assertEqual(lst, [2, 1])


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
358
359
360
361
362
363
364
class DaftarKatalogSortingByJumlahKomentarTest(TestCase):
    def setUp(self):
        self.client = Client()

        self.contributor_credential = {
        "email": "kontributor@gov.id",
        "password": "passwordtest"
            }

        self.contributor_credential_2 = {
            "email": "kontributor2@gov.id",
            "password": "passwordtest"
        }

        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor 1", is_contributor=True)
        self.contributor2 = get_user_model().objects.create_user(
            **self.contributor_credential_2, name="Kontributor 2", is_contributor=True)

        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()
        time.sleep(1)
        Materi(title="Materi 2", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 2",
               status="APPROVE", cover=self.cover, content=self.content).save()

        self.last_uploaded_material = Materi.objects.last()

        url = f"/materi/{self.last_uploaded_material.id}/"
        self.client.login(**self.contributor_credential_2)
        self.client.post(url, {"comment": "This is new comment by Kontributor 2"})

    def test_sorting_by_jumlah_komentar(self):
        response = self.client.get("/?sort=jumlah_komentar")
        self.assertRegex(str(response.content), rf'.*Materi 2.*Materi 1.*')

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
405
406
407
408
409
410
411
class DaftarKatalogPerKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()

        self.contributor_credential = {
                "email": "kontributor@gov.id",
                "password": "passwordtest"
            }

        self.contributor_credential_2 = {
                "email": "kontributor2@gov.id",
                "password": "passwordtest"
            }

        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor 1", is_contributor=True)
        self.contributor2 = get_user_model().objects.create_user(
            **self.contributor_credential_2, name="Kontributor 2", is_contributor=True)

        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()
        Materi(title="Materi 2", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 2",
               status="APPROVE", cover=self.cover, content=self.content).save()
        Materi(title="Materi 3", author="Agas", uploader=self.contributor2,
               publisher="Kelas SC", descriptions="Deskripsi Materi 3",
               status="APPROVE", cover=self.cover, content=self.content).save()

        self.url = f"/profil/{self.contributor.email}/"

    def test_katalog_per_kontributor_url_exist(self):
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)

    def test_katalog_per_kontributor_using_katalog_kontri_template(self):
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, "app/katalog_kontri.html")

    def test_katalog_per_kontributor_using_katalog_per_kontributor_func(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, KatalogPerKontributorView.as_view().__name__)

412
413
    # def test_katalog_per_kontributor_show_daftar_materi_kontributor(self):
    #     response = self.client.get(self.url)
414

415
416
417
    #     list_materi = Materi.objects.filter(uploader=self.contributor)
    #     data = response.context_data["materi_list"]
    #     self.assertEqual(len(list_materi), len(data))
418

419
420
421
422
423
    def test_count_materi_per_contributor(self):
        response = self.client.get(self.url)
        list_materi = Materi.objects.filter(uploader=self.contributor)
        jumlah = response.context_data["materi_list"]
        self.assertEqual(len(list_materi), len(jumlah))
424
425

class DetailMateriTest(TestCase):
426
427
428
429
430
431
432
433
434
435
436
437
438
439
    def _get_materi_info_html(self, info_name, info_value):
        info_html = '<div class="info" id="1"><dl class="col col-4">'
        info_html += f'<dt class="info-name">{info_name}</dt>' + '</dl><dd>'
        info_html += f'<p class="info-content">{info_value}</p>' + '</dd></div>'
        return info_html

    def check_materi_info_in_html(self, info_name, info_value, html_content):
        expected_content = self._get_materi_info_html(info_name, info_value)
        self.assertIn(expected_content, re.sub(">\s*<","><", html_content))

    def check_materi_info_not_in_html(self, info_name, info_value, html_content):
        expected_content = self._get_materi_info_html(info_name, info_value)
        self.assertNotIn(expected_content, re.sub(">\s*<","><", html_content))

440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
    def setUp(self):
        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"
        )
        self.cover = SimpleUploadedFile(
            "ExampleCover921.jpg", b"Test file")
        self.content = SimpleUploadedFile("ExampleFile921.pdf", b"Test file")

465
466
467
        self.materi1 = Materi.objects.create(title="Materi 1", author="Agas", 
                        uploader=self.contributor, publisher="Kelas SC", 
                        descriptions="Deskripsi Materi 1", status="APPROVE", 
468
                        cover=self.cover, content=self.content)
469
470
471
        self.materi2 = Materi.objects.create(title="Materi 2", author="Agad", 
                        uploader=self.contributor, publisher="Kelas SM", 
                        descriptions="Deskripsi Materi 2", status="APPROVE", 
472
                        cover=self.cover, content=self.content)
473
        self.url = "/materi/" + str(self.materi1.id) + "/"
474
475
476
        self.download_url1 = self.url + "unduh"
        self.url2 = "/materi/" + str(self.materi2.id) + "/"
        self.download_url2 = self.url2 + "unduh"
477
        self.like_url = '/materi/like/'
478
        self.dcount_info_name = "Jumlah Download"
479
        self.lcount_info_name = "Jumlah Like"
480
481
482
483

        self.materi_with_published_date = Materi.objects.create(title="Materi 1", author="Agas", uploader=self.contributor,
                                                 publisher="Kelas SC", descriptions="Deskripsi Materi 1",
                                                 status="APPROVE", cover=self.cover, content=self.content,
484
                                                 date_modified=timezone.now(), date_created=timezone.now())
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
        self.materi_with_published_date_url = "/materi/" + str(self.materi_with_published_date.id) + "/"
        VerificationReport.objects.create(report='{"feedback": "Something", "kriteria": [{"title": "Kriteria 1", "status": true},' + \
            ' {"title": "Kriteria 2", "status": true}, {"title": "Kriteria 3", "status": true}]}', \
            timestamp="2020-10-09 06:21:33", status="Diterima", materi= self.materi_with_published_date, \
            user=self.materi_with_published_date.uploader)

    def test_detail_materi_url_exist(self):
        response = Client().get(self.url)
        self.assertEqual(response.status_code, 200)
        self.assertNotEqual(response.status_code, 404)

    def test_detail_materi_using_detail_materi_template(self):
        response = Client().get(self.url)
        self.assertTemplateUsed(response, "app/detail_materi.html")

    def test_detail_materi_using_detail_materi_func(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, DetailMateri.as_view().__name__)

    def test_category_models_can_create_new_object(self):
        test = Category.objects.create(
            id="1", name="medis", description="kategori medis")
        count = Category.objects.all().count()
        self.assertEqual(1, count)
        self.assertNotEqual(0, count)
        self.assertEqual(test.__str__(), "medis")
        self.assertNotEqual(test.__str__(), "saul")

    def test_comment_models_can_create_new_object(self):
        test = Comment.objects.create(
            username="saul", profile="121212", comment="232323")
        count = Comment.objects.all().count()
        self.assertEqual(1, count)
        self.assertNotEqual(0, count)
        self.assertEqual(test.__str__(), "saul")
        self.assertNotEqual(test.__str__(), "userlain")

    def test_post_blank_comment(self):
        url = self.url
        self.client.login(**self.anonymous_credential)
        response = self.client.post(url, {"comment": ""})
        self.assertIn("error_message", response.context)
        self.assertIn("Anda belum menuliskan komentar",
                      response.context["error_message"])

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

    def test_comment_by_admin(self):
        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)
        self.assertContains(response, "Admin")

    def test_comment_by_kontributor(self):
        url = self.url
        self.client.login(**self.contributor_credential)
        self.client.post(
            url, {"comment": "This is new comment by Contributor"})
        response = self.client.get(url)
        self.assertContains(response, "Kontributor")

    def test_comment_by_anonymous(self):
        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)
        self.assertContains(response, "Anonymous")

    def test_comment_disliked_by_anonymous(self):
        url_materi = self.url
        self.client.get("/logout/")
        self.client.login(**self.anonymous_credential)

        self.client.post(url_materi, {"comment": "This is new comment by Anonymous"})
        comment = Comment.objects.get(comment="This is new comment by Anonymous").id
        response = self.client.get(url_materi)
        session_id = response.context["session_id"]

        payload = {"comment": comment, "session_id": session_id}
571
        self.client.post("/comment/dislike/", payload)
572
573
574
575
576
577
578
579
580
581
582
583
584
585
        num_of_comment_dislikes = DislikeComment.objects.filter(comment=comment).count()
        self.assertEqual(num_of_comment_dislikes, 0)

    def test_comment_liked_by_anonymous(self):
        url_materi = self.url
        self.client.get("/logout/")
        self.client.login(**self.anonymous_credential)

        self.client.post(url_materi, {"comment": "This is new comment by Anonymous"})
        comment = Comment.objects.get(comment="This is new comment by Anonymous").id
        response = self.client.get(url_materi)
        session_id = response.context["session_id"]

        payload = {"comment": comment, "session_id": session_id}
586
        self.client.post("/comment/like/", payload)
587
588
589
590
591
592
593
594
595
596
597
598
        num_of_comment_likes = LikeComment.objects.filter(comment=comment).count()
        self.assertEqual(num_of_comment_likes, 0)

    def test_comment_undisliked_by_anonymous(self):
        url_materi = self.url
        self.client.get("/logout/")
        self.client.login(**self.anonymous_credential)

        self.client.post(url_materi, {"comment": "This is new comment by Anonymous"})
        comment = Comment.objects.get(comment="This is new comment by Anonymous")
        response = self.client.get(url_materi)
        session_id = response.context["session_id"]
599
        
600
        payload = {"comment": comment, "session_id": session_id}
601
        self.client.post("/comment/dislike/", payload)
602
        
603
        self.client.post("/comment/dislike/", payload)
604
605
606
607
608
609
610
611
612
613
614
615
        num_of_comment_dislikes = DislikeComment.objects.filter(comment=comment, session_id=session_id).count()
        self.assertEqual(num_of_comment_dislikes, 0)

    def test_comment_unliked_by_anonymous(self):
        url_materi = self.url
        self.client.get("/logout/")
        self.client.login(**self.anonymous_credential)

        self.client.post(url_materi, {"comment": "This is new comment by Anonymous"})
        comment = Comment.objects.get(comment="This is new comment by Anonymous")
        response = self.client.get(url_materi)
        session_id = response.context["session_id"]
616
        
617
        payload = {"comment": comment, "session_id": session_id}
618
        self.client.post("/comment/like/", payload)
619
        
620
        self.client.post("/comment/like/", payload)
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
649
        num_of_comment_likes = LikeComment.objects.filter(comment=comment, session_id=session_id).count()
        self.assertEqual(num_of_comment_likes, 0)

    def test_comment_new_does_not_have_dislike(self):
        url_materi = self.url
        self.client.get("/logout/")
        self.client.login(**self.anonymous_credential)

        response = self.client.get(url_materi)
        session_id = response.context["session_id"]
        self.client.post(url_materi, {"comment": "This is new comment by Anonymous"})

        comment = Comment.objects.get(comment="This is new comment by Anonymous")
        comment_dislike_counter = DislikeComment.objects.filter(comment=comment, session_id=session_id).count()
        self.assertEqual(comment_dislike_counter, 0)

    def test_comment_new_does_not_have_like(self):
        url_materi = self.url
        self.client.get("/logout/")
        self.client.login(**self.anonymous_credential)

        response = self.client.get(url_materi)
        session_id = response.context["session_id"]
        self.client.post(url_materi, {"comment": "This is new comment by Anonymous"})

        comment = Comment.objects.get(comment="This is new comment by Anonymous")
        comment_like_counter = LikeComment.objects.filter(comment=comment, session_id=session_id).count()
        self.assertEqual(comment_like_counter, 0)

650
651
652
653
654
655
656
657
658
    def test_comment_sends_email_to_contributor_that_subscribes(self):
        contributor_subscribed = get_user_model().objects.create_user(
            email="contributor_subscribing@gov.id",
            password="passwordtest",
            name="Kontributor-subscribed",
            is_contributor=True,
            is_subscribing_to_material_comments=True
        )

659
660
661
        material = Materi.objects.create(title="Materi-subscribed", author="Tester", 
                                uploader=contributor_subscribed, publisher="Kelas PMPL", 
                                descriptions="Deskripsi Materi subscribed", status="APPROVE", 
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
                                cover=self.cover, content=self.content)
        url = "/materi/" + str(material.id) + "/"
        self.client.login(**self.contributor_credential) # comment with other user

        prev_outbox_count = len(mail.outbox)

        comment_content = "Test comment should send email"
        self.client.post(
            url, {"comment": comment_content})

        current_outbox_count = len(mail.outbox)

        # Comment notification email sent
        self.assertEqual(current_outbox_count, prev_outbox_count + 1)

    def test_comment_doesnt_send_email_to_contributor_that_not_subscribes(self):
        contributor_not_subscribed = get_user_model().objects.create_user(
            email="contributor_not_subscribing@gov.id",
            password="passwordtest",
            name="Kontributor-not-subscribed",
            is_contributor=True,
            is_subscribing_to_material_comments=False
        )

686
687
688
        material = Materi.objects.create(title="Materi-not-subscribed", author="Tester", 
                                uploader=contributor_not_subscribed, publisher="Kelas PMPL", 
                                descriptions="Deskripsi Materi non-subscribed", status="APPROVE", 
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
                                cover=self.cover, content=self.content)
        url = "/materi/" + str(material.id) + "/"
        self.client.login(**self.contributor_credential) # comment with other user

        prev_outbox_count = len(mail.outbox)

        comment_content = "Test comment should not send email"
        self.client.post(
            url, {"comment": comment_content})

        current_outbox_count = len(mail.outbox)

        # Comment notification email not sent
        self.assertEqual(current_outbox_count, prev_outbox_count)

    def test_comment_doesnt_send_email_to_contributor_that_self_commenting(self):
        contributor_subscribed_credentials = {
            "email": "contributor_subscribing@gov.id",
            "password": "passwordtest"
        }
        contributor_subscribed = get_user_model().objects.create_user(
            **contributor_subscribed_credentials,
            name="Kontributor-subscribed",
            is_contributor=True,
            is_subscribing_to_material_comments=True
        )

716
717
718
        material = Materi.objects.create(title="Materi-subscribed", author="Tester", 
                                uploader=contributor_subscribed, publisher="Kelas PMPL", 
                                descriptions="Deskripsi Materi subscribed", status="APPROVE", 
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
                                cover=self.cover, content=self.content)
        url = "/materi/" + str(material.id) + "/"
        self.client.login(**contributor_subscribed_credentials) # comment with the same user

        prev_outbox_count = len(mail.outbox)

        comment_content = "Test comment should not send email for self-comments"
        self.client.post(
            url, {"comment": comment_content})

        current_outbox_count = len(mail.outbox)

        # Comment notification email not sent
        self.assertEqual(current_outbox_count, prev_outbox_count)

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
    def test_detail_materi_contains_comment_count(self):
        url = self.url
        self.client.login(**self.contributor_credential)

        response = self.client.get(url)
        self.assertContains(response, "Komentar (0)")

        self.client.post(
            url, {"comment": "This is new comment by Contributor"})
        self.client.post(
            url, {"comment": "This is new comment by Contributor"})
        response = self.client.get(url)
        self.assertContains(response, "Komentar (2)")

    def test_detail_materi_contains_form_comment(self):
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.url)
        self.assertContains(response, "Beri komentar...")

    def test_detail_materi_not_contains_form_comment(self):
        response = self.client.get(self.url)
        self.assertNotContains(response, "Beri komentar...")
        self.assertContains(response, "Login terlebih dahulu untuk berkomentar")

    def create_and_delete_comment(self, is_admin=False, is_contributor=False):
        url = self.url
        self.client.login(**self.admin_credential)
        self.client.post(url, {"comment": "This is new comment by Anonymous"})
762
        delete_url = "/delete/" + str(self.materi1.id) + "/" + str(
763
764
765
766
767
768
769
            Comment.objects.get(comment="This is new comment by Anonymous").id)
        if is_admin:
            self.client.login(**self.admin_credential)
        if is_contributor:
            self.client.login(**self.contributor_credential)
        if not is_admin and not is_contributor:
            self.client.login(**self.anonymous_credential)
770
        response = self.client.get(delete_url)
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
        return response

    def test_delete_comments_by_admin(self):
        self.create_and_delete_comment(is_admin=True)
        count = Comment.objects.all().filter(comment="This is new comment by Anonymous").count()
        self.assertEqual(count, 0)

    def test_delete_comments_by_contributor(self):
        response = self.create_and_delete_comment(is_contributor=True)

        self.assertRaises(PermissionDenied)
        self.assertEqual(response.status_code, 403)

        count = Comment.objects.all().filter(comment="This is new comment by Anonymous").count()
        self.assertEqual(count, 1)

    def test_delete_comments_by_anonymous(self):
        response = self.create_and_delete_comment()

        self.assertRaises(PermissionDenied)
        self.assertEqual(response.status_code, 403)

        count = Comment.objects.all().filter(comment="This is new comment by Anonymous").count()
        self.assertEqual(count, 1)
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
    def test_review_models_can_create_new_object(self):
        test = Review.objects.create(
            username="saul", profile="121212", review="232323")
        count = Review.objects.all().count()
        self.assertEqual(1, count)
        self.assertNotEqual(0, count)
        self.assertEqual(test.__str__(), "saul")
        self.assertNotEqual(test.__str__(), "userlain")

    def test_post_blank_review(self):
        url = self.url
        self.client.login(**self.anonymous_credential)
        response = self.client.post(url, {"review": ""})
        self.assertIn("error_message", response.context)
        self.assertIn("Anda belum menuliskan komentar",
                      response.context["error_message"])

    def test_review_rendered_to_template(self):
        url = self.url
        self.client.login(**self.contributor_credential)
        self.client.post(url, {"review": "This is my new review"})
        response = Client().get(url)
        self.assertContains(response, "This is my new review")

    def test_review_by_admin(self):
        url = self.url
        self.client.login(**self.admin_credential)
        self.client.post(url, {"review": "This is new review by Admin"})
        response = self.client.get(url)
        self.assertContains(response, "Admin")

    def test_review_by_kontributor(self):
        url = self.url
        self.client.login(**self.contributor_credential)
        self.client.post(
            url, {"review": "This is new review by Contributor"})
        response = self.client.get(url)
        self.assertContains(response, "Kontributor")

    def test_review_by_anonymous(self):
        url = self.url
        self.client.get("/logout/")
        self.client.login(**self.anonymous_credential)
        self.client.post(url, {"review": "This is new review by Anonymous"})
        response = self.client.get(url)
        self.assertContains(response, "Anonymous")
843
    
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
    def test_detail_materi_contains_review_count(self):
        url = self.url
        self.client.login(**self.contributor_credential)
        review = "This is new review by Contributor"
        response = self.client.get(url)
        self.assertContains(response, "Review (0)")

        self.client.post(
            url, {"review": review })
        self.client.post(
            url, {"review": review})
        response = self.client.get(url)
        self.assertContains(response, "Review (2)")

    def test_detail_materi_contains_form_review(self):
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.url)
        self.assertContains(response, "Beri Review")

    def test_detail_materi_not_contains_form_review(self):
        response = self.client.get(self.url)
        self.assertNotContains(response, "Beri Review")
        self.assertContains(response, "Login terlebih dahulu untuk Membuat review")

    def test_tombol_citasiAPA(self):
        response = self.client.get(self.url)
        self.assertContains(response, "Citate APA")

    def test_hasil_citasi_APA_materi_has_no_published_date(self):
        response = self.client.get(self.url)
874
        expected = self.materi1.author + " . (n.d) . " + self.materi1.title + " . " + self.materi1.publisher	
875
876
877
878
879
880
        self.assertIn(expected, response.context["citationAPA"])
        self.assertIn(expected,
                      response.context["citationAPA"])

    def test_hasil_citasi_APA_materi_has_published_date(self):
        response = self.client.get(self.materi_with_published_date_url)
881
882
883
884
885
886
887
888
889
890
        published_date = self.materi_with_published_date.published_date.strftime("%Y-%m-%d %H:%M")	
        expected = (	
            self.materi_with_published_date.author	
            + " . ("	
            + published_date	
            + ") . "	
            + self.materi_with_published_date.title	
            + " . "	
            + self.materi_with_published_date.publisher	
        )	
891
        self.assertIn(expected, response.context["citationAPA"])
892
    
893
894
895
896
897
898
    def test_citation_IEEE_button(self):
        response = self.client.get(self.url)
        self.assertContains(response, "Citate IEEE")

    def test_citation_IEEE_materi_has_no_published_date(self):
        response = self.client.get(self.url)
899
        current_date = timezone.now()
900
901
902
903
        current_day = str(current_date.day)
        current_month = current_date.strftime("%b")
        current_year = str(current_date.year)

904
905
906
907
908
909
910
911
912
913
914
915
916
        expected = (	
            "Agas, "	
            + "Materi 1. "	
            + "Kelas SC, n.d. "	
            + "Accessed on: "	
            + current_month	
            + ". "	
            + current_day	
            + ", "	
            + current_year	
            + ". [Online]. "	
            + "Available: http://testserver"	
            + self.url	
917
918
919
920
921
        )
        self.assertIn(expected, response.context["citationIEEE"])

    def test_citation_IEEE_materi_has_published_date(self):
        response = self.client.get(self.materi_with_published_date_url)
922
        current_date = timezone.now()
923
924
925
926
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
        current_day = str(current_date.day)
        current_month = current_date.strftime("%b")
        current_year = str(current_date.year)
        published_date = self.materi_with_published_date.published_date.strftime('%Y')

        expected = "Agas, " + \
                   "Materi 1. " + \
                   "Kelas SC, " + published_date + ". " +\
                   "Accessed on: " + current_month + ". " + current_day + ", " + current_year + \
                   ". [Online]. " + \
                   "Available: http://testserver" + self.materi_with_published_date_url
        self.assertIn(expected, response.context["citationIEEE"])

    def test_tombol_bagikan_google_drive(self):
        response = Client().get(self.url)
        self.assertContains(response, 'Google Drive')

    @mock.patch("app.services.GoogleDriveUploadService.upload_to_gdrive")
    def test_save_to_gdrive_with_nonexistent_materi(self, mock_upload_to_gdrive):
        response = self.client.get('/materi/%s/save-to-gdrive/' % 0)
        mock_upload_to_gdrive.assert_not_called()
        self.assertEqual(response.status_code, 404)

    @mock.patch("app.services.GoogleDriveUploadService.upload_to_gdrive")
    def test_save_to_gdrive_with_valid_materi(self, mock_upload_to_gdrive):
        response = self.client.get(
            '/materi/%s/save-to-gdrive/' % self.materi1.id, follow=True)
        last_url, status_code = response.redirect_chain[-1]
        mock_upload_to_gdrive.assert_called_once()
        self.assertEqual(last_url, '/materi/%d/' % self.materi1.id)
        self.assertEqual(status_code, 302)

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
    def test_download_count_is_in_init_context(self):
        context = {}
        DetailMateriService.init_materi_download_count(context, self.materi1)
        self.assertIn('materi_download_count', context.keys())

    def test_download_count_is_integer(self):
        context = {}
        DetailMateriService.init_materi_download_count(context, self.materi1)
        self.assertEqual(type(context['materi_download_count']), int)

    def test_download_count_when_no_download(self):
        context = {}
        DetailMateriService.init_materi_download_count(context, self.materi1)
        self.assertEqual(context['materi_download_count'], 0)

    def test_download_count_when_single_download(self):
        self.client.get(self.download_url1)
        context = {}
        DetailMateriService.init_materi_download_count(context, self.materi1)
        self.assertEqual(context['materi_download_count'], 1)

    def test_download_count_when_multiple_download(self):
        self.client.get(self.download_url1)
        self.client.get(self.download_url1)
        self.client.get(self.download_url1)
        context = {}
        DetailMateriService.init_materi_download_count(context, self.materi1)
        self.assertEqual(context['materi_download_count'], 3)

    def test_different_material_has_different_download_count(self):
        self.client.get(self.download_url1)
        self.client.get(self.download_url1)
        self.client.get(self.download_url1)

        self.client.get(self.download_url2)
        self.client.get(self.download_url2)

        context1 = {}
        context2 = {}
        DetailMateriService.init_materi_download_count(context1, self.materi1)
        DetailMateriService.init_materi_download_count(context2, self.materi2)
        self.assertNotEqual(context1['materi_download_count'], context2['materi_download_count'])
        self.assertEqual(context1['materi_download_count'], 3)
        self.assertEqual(context2['materi_download_count'], 2)
999
    
1000
    def test_download_count_displayed_on_template_when_no_download(self):