Fakultas Ilmu Komputer UI

tests.py 167 KB
Newer Older
Moh Faisal's avatar
Moh Faisal committed
1
2
import mock
import pandas as pd
3
4
5
6
7
import base64
import datetime as dt
import json
import os
import random
8
import re
9
import tempfile
10
import time
11
12
import itertools
from django.test import override_settings
13
from datetime import datetime
Moh Faisal's avatar
Moh Faisal committed
14
from io import StringIO, BytesIO
15
from time import sleep
16

17
18
19
20
21
22
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
23
from bs4 import BeautifulSoup
24
from digipus.settings import TIME_ZONE
25
from django.conf import settings
26
from django.contrib import messages as dj_messages
27
from django.contrib.auth import get_user_model
28
from django.core import mail, serializers
29
from django.core.exceptions import PermissionDenied, ValidationError
Moh Faisal's avatar
Moh Faisal committed
30
from django.core.files.uploadedfile import SimpleUploadedFile, InMemoryUploadedFile
31
from django.core.files import File
32
from django.core.management import call_command
33
from django.db.utils import IntegrityError
34
from pytz import timezone, UTC
35
36
37
38
from django.test import (Client, RequestFactory, TestCase, TransactionTestCase,
                         override_settings)
from django.urls import resolve, reverse
from django.utils import timezone
39

40
from app.forms import SuntingProfilForm, year_choices
41
42
from app.utils.fileManagementUtil import (get_random_filename,
                                          remove_image_exifdata)
43
from app.utils.PasswordValidator import PasswordPolicyValidator
44
45
46
47
from app.views import UploadMateriHTML, add_rating_materi

from .models import (Category, Comment, DislikeComment, DownloadStatistics,
                     Like, LikeComment, Materi, Rating, RatingContributor,
48
                     ReadLater, ReqMaterial, Review, ViewStatistics, AdminNotification)
49
50
51
52
53
from .services import DetailMateriService
from .views import (DaftarKatalog, DashboardKontributorView, DetailMateri,
                    KatalogPerKontributorView, MateriFavorite,
                    PasswordChangeViews, PostsView, ProfilView, ReqMateriView,
                    RevisiMateriView, SuksesLoginAdminView,
Yusuf T Ardho's avatar
Yusuf T Ardho committed
54
                    LaporanMateri,
55
56
                    SuksesLoginKontributorView, SuntingProfilView,
                    UploadMateriExcelView, UploadMateriView, password_success)
57

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

60
61
62
from statistics import mean

import requests
63
64
from django.test import LiveServerTestCase
from selenium import webdriver
65
from selenium.common.exceptions import NoSuchElementException
66
67
68
69
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager

70

71
72
73
74
75
76
77
78
79
80
81
82
83
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__)
84

85
86
87
88
89
90
    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()
91

92
93
        resp = Materi.objects.get(id=materi.id)
        self.assertEqual(resp, materi)
94

95
96
97
98

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

100
101
102
103
        self.contributor_credential = {
        "email": "kontributor@gov.id",
        "password": "passwordtest"
            }
104

105
106
107
108
        self.contributor_credential_2 = {
                "email": "kontributor2@gov.id",
                "password": "passwordtest"
            }
109

110
111
112
113
        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)
114

115
116
117
        self.cover = SimpleUploadedFile(
            "Cherprang_Areekul40_nJM9dGt.jpg", b"Test file")
        self.content = SimpleUploadedFile("Bahan_PA_RKK.pdf", b"Test file")
118

119
120
121
122
123
124
125
        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()
126

127
        self.last_uploaded_material = Materi.objects.last()
128

129
130
        material_unduh_url = f"/materi/{self.last_uploaded_material.id}/unduh"
        self.client.get(material_unduh_url)
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
166
167
168
    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.*')
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
324
325
326

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])


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
365
366
367
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.*')

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
412
413
414
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__)

415
416
    # def test_katalog_per_kontributor_show_daftar_materi_kontributor(self):
    #     response = self.client.get(self.url)
417

418
419
420
    #     list_materi = Materi.objects.filter(uploader=self.contributor)
    #     data = response.context_data["materi_list"]
    #     self.assertEqual(len(list_materi), len(data))
421

422
423
424
425
426
    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))
427
428

class DetailMateriTest(TestCase):
429
430
431
432
433
434
435
436
437
438
439
440
441
442
    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))

443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
    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")

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

        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,
487
                                                 date_modified=timezone.now(), date_created=timezone.now())
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
        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"])

Yusuf T Ardho's avatar
Yusuf T Ardho committed
533
534
535
536
537
538
539
540
    def test_post_blank_report(self):
        url = self.url
        self.client.login(**self.anonymous_credential)
        response = self.client.post(url, {"report": ""})
        self.assertIn("error_message", response.context)
        self.assertIn("Anda belum menuliskan komentar",
                      response.context["error_message"])

541
542
543
544
545
546
547
    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")

Yusuf T Ardho's avatar
Yusuf T Ardho committed
548
549
550
551
552
553
554
    def test_report_rendered_to_template(self):
        url = self.url
        self.client.login(**self.contributor_credential)
        self.client.post(url, {"report": "This is my new comment"})
        response = Client().get(url)
        self.assertEqual(response.status_code, 200)

555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
    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}
589
        self.client.post("/comment/dislike/", payload)
590
591
592
593
594
595
596
597
598
599
600
601
602
603
        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}
604
        self.client.post("/comment/like/", payload)
605
606
607
608
609
610
611
612
613
614
615
616
        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"]
617
        
618
        payload = {"comment": comment, "session_id": session_id}
619
        self.client.post("/comment/dislike/", payload)
620
        
621
        self.client.post("/comment/dislike/", payload)
622
623
624
625
626
627
628
629
630
631
632
633
        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"]
634
        
635
        payload = {"comment": comment, "session_id": session_id}
636
        self.client.post("/comment/like/", payload)
637
        
638
        self.client.post("/comment/like/", payload)
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
        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)

668
669
670
671
672
673
674
675
676
    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
        )

677
678
679
        material = Materi.objects.create(title="Materi-subscribed", author="Tester", 
                                uploader=contributor_subscribed, publisher="Kelas PMPL", 
                                descriptions="Deskripsi Materi subscribed", status="APPROVE", 
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
                                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
        )

704
705
706
        material = Materi.objects.create(title="Materi-not-subscribed", author="Tester", 
                                uploader=contributor_not_subscribed, publisher="Kelas PMPL", 
                                descriptions="Deskripsi Materi non-subscribed", status="APPROVE", 
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
                                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
        )

734
735
736
        material = Materi.objects.create(title="Materi-subscribed", author="Tester", 
                                uploader=contributor_subscribed, publisher="Kelas PMPL", 
                                descriptions="Deskripsi Materi subscribed", status="APPROVE", 
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
                                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)

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
    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"})
780
        delete_url = "/delete/" + str(self.materi1.id) + "/" + str(
781
782
783
784
785
786
787
            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)
788
        response = self.client.get(delete_url)
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
        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)
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
    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")
861
    
862
863
864
865
866
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
    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)
892
        expected = self.materi1.author + " . (n.d) . " + self.materi1.title + " . " + self.materi1.publisher	
893
894
895
896
897
898
        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)
899
900
901
902
903
904
905
906
907
908
        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	
        )	
909
        self.assertIn(expected, response.context["citationAPA"])
910
    
911
912
913
914
915
916
    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)
917
        current_date = timezone.now()
918
919
920
921
        current_day = str(current_date.day)
        current_month = current_date.strftime("%b")
        current_year = str(current_date.year)

922
923
924
925
926
927
928
929
930
931
932
933
934
        expected = (	
            "Agas, "	
            + "Materi 1. "	
            + "Kelas SC, n.d. "	
            + "Accessed on: "	
            + current_month	
            + ". "	
            + current_day	
            + ", "	
            + current_year	
            + ". [Online]. "	
            + "Available: http://testserver"	
            + self.url	
935
936
937
938
939
        )
        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)
940
        current_date = timezone.now()
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
        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)

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
    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)
1017
    
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
    def test_download_count_displayed_on_template_when_no_download(self):
        response = self.client.get(self.url)
        html = response.content.decode("utf-8")
        self.check_materi_info_in_html(self.dcount_info_name, 0, html)

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

        response = self.client.get(self.url)
        html = response.content.decode("utf-8")
        self.check_materi_info_in_html(self.dcount_info_name, 1, html)

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

        response = self.client.get(self.url)
        html = response.content.decode("utf-8")
        self.check_materi_info_in_html(self.dcount_info_name, 4, html)

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

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

        response = self.client.get(self.url)
        response2 = self.client.get(self.url2)

        html = response.content.decode("utf-8")
        html2 = response2.content.decode("utf-8")

        dcount_materi1 = self.materi1.unduh.all().count()
        dcount_materi2 = self.materi2.unduh.all().count()

        self.check_materi_info_in_html(self.dcount_info_name, dcount_materi1, html)
        self.check_materi_info_not_in_html(self.dcount_info_name, dcount_materi2, html)
        self.check_materi_info_in_html(self.dcount_info_name, dcount_materi2, html2)
        self.check_materi_info_not_in_html(self.dcount_info_name, dcount_materi1, html2)
1062
    
1063
1064
1065
1066
    def test_like_count_displayed_on_template_when_no_like(self):
        response = self.client.get(self.url)
        html = response.content.decode("utf-8")
        self.check_materi_info_in_html(self.lcount_info_name, 0, html)
1067
    
1068
1069
1070
1071
1072
1073
1074
1075
1076
    def test_like_count_displayed_on_template_when_single_like(self):
        payload = {
            'materi_id': self.materi1.id,
            'session_id': "dummysession"
        }
        self.client.post(self.like_url, payload)

        response = self.client.get(self.url)
        html = response.content.decode("utf-8")
1077
1078
        self.check_materi_info_in_html(self.lcount_info_name, 1, html)        
        
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
    def test_like_count_displayed_on_template_when_multiple_like(self):
        payload1 = {
            'materi_id': self.materi1.id,
            'session_id': "dummysession1"
        }
        payload2 = {
            'materi_id': self.materi1.id,
            'session_id': "dummysession2"
        }
        self.client.post(self.like_url, payload1)
        self.client.post(self.like_url, payload2)
1090
        
1091
1092
1093
        response = self.client.get(self.url)
        html = response.content.decode("utf-8")
        self.check_materi_info_in_html(self.lcount_info_name, 2, html)
1094
    
1095
1096
1097
1098
1099
    def test_like_count_displayed_on_template_when_unlike(self):
        payload = {
            'materi_id': self.materi1.id,
            'session_id': "dummysession"
        }
1100
        
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
        # Like materi once
        self.client.post(self.like_url, payload)
        response = self.client.get(self.url)
        html = response.content.decode("utf-8")
        self.check_materi_info_in_html(self.lcount_info_name, 1, html)

        # Like it again, resulting in unlike
        self.client.post(self.like_url, payload)
        response = self.client.get(self.url)
        html = response.content.decode("utf-8")
        self.check_materi_info_in_html(self.lcount_info_name, 0, html)
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141

class PostsViewTest(TestCase):

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

        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 i 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 j in range (LIKES_COUNT_PER_POST[i]):
                Like.objects.create(
1142
                    timestamp=timezone.now(), 
1143
                    materi=post, 
1144
1145
                    session_id=("dummysession-" + str(i) + '-' + str(j))
                )
1146
                time.sleep(0.1)
1147
            
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
        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"
        }
        cls.user = User.objects.create_user(**cls.user_credentials, is_contributor=True)
        cls.data = cls.generate_posts_data(cls.user)

    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__)

    def test_returns_200_on_authenticated_access(self):
        response = self._request_as_user()
        self.assertEqual(response.status_code, 200)

    def test_returns_403_on_unauthenticated_access(self):
        response = self.client.get(self.url)
        self.assertRaises(PermissionDenied)
        self.assertEqual(response.status_code, 403)

        html = response.content.decode("utf-8")
        self.assertIn(ERROR_403_MESSAGE, html)

    def test_returns_correct_template(self):
        response = self._request_as_user()
        self.assertTemplateUsed(response, "user_uploaded_posts.html")

    def test_success_returns_correct_comment_post_groupings_by_context(self):
        post_comment_group_dict = self.data

        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(
            str(response.content),
            rf'.*(<div id="post-{posts[2]}">)' + \
            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]}">)' + \
            rf'.*(<div id="post-{posts[1]}">)' + \
            rf'.*(<div id="post-{posts[0]}">)' + \
            rf'.*(<div id="post-{posts[0]}-comment-{comments[0][0]}">)'
        )

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

        for _, post_id in enumerate(self.data):
            post = self.data[post_id]["data"]

            self.assertContains(
                response,
                '<span id="post-like-count-' + str(post.id) + '">' +  str(post.like_count) + '</span>',
            )

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)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, expected_template_name)


class UploadPageTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects._create_user(email="kontributor@gov.id",
                                              password="kontributor", is_contributor=True)
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")

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

    def test_upload_page_url_is_exist(self):
        # Positive test
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get("/unggah/")
        self.assertEqual(response.status_code, 200)

        # Negative tests
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = Client().get("/fake/")
        self.assertEqual(response.status_code, 404)

1289
    def test_upload_page_url_admin_doesnt_exist(self):        
1290
1291
1292
1293
1294
        self.client.login(email="admin@gov.id",
                          password="admin")
        response = self.client.get("/unggah/")
        self.assertEqual(response.status_code, 403)

1295
    def test_upload_page_url_admin_cant_upload(self):        
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
        self.client.login(email="admin@gov.id",
                          password="admin")
        response = self.client.post("/unggah/")
        self.assertEqual(response.status_code, 403)

    def test_upload_page_template(self):
        url = "/unggah/"
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get(url)
        expected_template_name = "unggah.html"
        self.assertTemplateUsed(response, expected_template_name)

    def test_upload_page_title(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        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",
                          password="kontributor")
        response = self.client.get("/unggah/")

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

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

class UploadExcelPageTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects._create_user(email="kontributor@gov.id",
                                              password="kontributor", is_contributor=True)

    def test_upload_excel_page_using_login_func(self):
        found = resolve("/unggah_excel/")
        self.assertEqual(found.func.__name__,
                         UploadMateriExcelView.as_view().__name__)

    def test_uplaod_excel_page_url_is_exist(self):
        # Positive test
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get("/unggah_excel/")
        self.assertEqual(response.status_code, 200)

        # Negative tests
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = Client().get("/fake/")
        self.assertEqual(response.status_code, 404)

    def test_upload_excel_page_template(self):
        url = "/unggah_excel/"
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get(url)
        expected_template_name = "unggah_excel.html"
        self.assertTemplateUsed(response, expected_template_name)

    def test_upload_excel_page_title(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get("/unggah_excel/")

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

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

    def test_upload_excel_page_form_field(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get("/unggah_excel/")

        # Positive tests
        self.assertContains(response, "File (*.xlsx)")

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

    def create_dummy_excel(self, field_lengths={}, categories=[]):
        title1 = "Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems"
        author1 = "Aurelien Geron, Aurelien Geron, Aurelien Geron"
        publisher1 = "O'Reilly Media, O'Reilly Media, O'Reilly Media"
        categories1 = "Machine Learning,Deep Learning,Computer Science"
        description1 = "A series of Deep Learning breakthroughs have boosted the whole field of machine learning over the last decade. Now that machine learning is thriving, even programmers who know close to nothing about this technology can use simple, efficient tools to implement programs capable of learning from data. This practical book shows you how."

        if 'title' in field_lengths:
            title1 = title1[:field_lengths['title']]

        if 'author' in field_lengths:
            author1 = author1[:field_lengths['author']]

        if 'publisher' in field_lengths:
            publisher1 = publisher1[:field_lengths['publisher']]

        if len(categories) > 0:
            categories1 = ','.join(categories)

        data_frame = pd.DataFrame({
            'Title': [title1],
            'Author': [author1],
            'Publisher': [publisher1],
            'Categories': [categories1],
            'Description': [description1],
        })

        file_path = os.path.join(settings.MEDIA_ROOT, 'dummy.xlsx')

        writer = pd.ExcelWriter(file_path, engine='xlsxwriter') #pylint: disable=abstract-class-instantiated
        data_frame.to_excel(writer, index=0)
        writer.save()

        return file_path, data_frame

    def test_upload_excel_upload_file_title_error(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")

        field_lengths = {
            'author':30,
            'publisher':30,
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)

        with open(file_name, 'rb') as fp:
            response = self.client.post("/unggah_excel/", {'excel': fp})
1432
        
1433
1434
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message
1435

1436
        self.assertIn('Title', msg_text)
1437

1438
1439
1440
    def test_upload_excel_upload_file_author_error(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
1441

1442
1443
1444
1445
1446
        field_lengths = {
            'title':50,
            'publisher':30,
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)
1447

1448
1449
        with open(file_name, 'rb') as fp:
            response = self.client.post("/unggah_excel/", {'excel': fp})
1450
        
1451
1452
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message
1453

1454
        self.assertIn('Author', msg_text)
1455

1456

1457
1458
1459
    def test_upload_excel_upload_file_publisher_error(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
1460

1461
1462
1463
1464
1465
        field_lengths = {
            'title':50,
            'author':30,
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)
1466

1467
1468
        with open(file_name, 'rb') as fp:
            response = self.client.post("/unggah_excel/", {'excel': fp})
1469
        
1470
1471
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message
1472

1473
        self.assertIn('Publisher', msg_text)
1474

1475
1476
1477
    def test_upload_excel_upload_file_categories_error(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
1478

1479
1480
1481
1482
1483
1484
        field_lengths = {
            'title':50,
            'author':30,
            'publisher':30,
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)
1485

1486
1487
        with open(file_name, 'rb') as fp:
            response = self.client.post("/unggah_excel/", {'excel': fp})
1488
        
1489
1490
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message
1491

1492
        self.assertIn('Kategori', msg_text)
1493

1494
1495
1496
    def test_upload_excel_upload_file_success(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
1497

1498
1499
1500
        Category(name='Computer Science').save()
        Category(name='Machine Learning').save()
        Category(name='Deep Learning').save()
1501

1502
1503
1504
1505
1506
        field_lengths = {
            'title':50,
            'author':30,
            'publisher':30,
        }
1507

1508
        categories = ['Computer Science','Machine Learning','Deep Learning']
1509
        
1510
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths, categories=categories)
1511

1512
        with open(file_name, 'rb') as fp:
1513
            self.client.post("/unggah_excel/", {'excel': fp})
1514
        
1515
        title = data_frame['Title'][0]
Arief Pratama's avatar
Arief Pratama committed
1516
1517
1518
1519
1520
1521
        materi = Materi.objects.get(title=title)
        default_path = 'book-cover-placeholder.png'

        self.assertTrue(materi)
        self.assertEquals(materi.cover.name, default_path)
        self.assertTrue(os.path.exists(os.path.join(settings.MEDIA_ROOT, default_path)))
1522

1523
1524
1525
    def test_upload_excel_download_template(self):
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
1526

1527
        response = self.client.get("/unggah_excel/?template=1")
1528
        
1529
1530
1531
        self.assertEquals(response['Content-Type'],'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        self.assertEquals(response['Content-Disposition'],'attachment; filename=template.xlsx')

1532
        
Arief Pratama's avatar
Arief Pratama committed
1533

1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620