Fakultas Ilmu Komputer UI

tests.py 125 KB
Newer Older
1
import json, tempfile, os, mock, base64
2
import pandas as pd
3
from io import StringIO
4
import time
5
from django.test import override_settings
6

7
8
from bs4 import BeautifulSoup
from datetime import datetime
9
from django.conf import settings
10
from django.contrib import messages as dj_messages
11
from django.contrib.auth import get_user_model
12
from django.core import serializers
13
from django.core.files import File
14
from django.core.exceptions import PermissionDenied, ValidationError
15
from django.core.files.uploadedfile import SimpleUploadedFile
16
from django.core.management import call_command
17
from django.test import Client, TestCase, TransactionTestCase
18
from django.urls import resolve, reverse
19
from django.db.utils import IntegrityError
20
21
22
from django.test import Client, RequestFactory, TestCase, TransactionTestCase
from pytz import timezone
from time import sleep
23
import datetime as dt
24

25
from administration.models import VerificationSetting, VerificationReport
26
from administration.utils import id_generator
27
from app.views import UploadMateriHTML, add_rating_materi
28
from authentication.models import User
29
from digipus.settings import TIME_ZONE
30
31
32
from .models import (
    Category,
    Comment,
33
    Review,
34
    DislikeComment,
35
36
37
    DownloadStatistics,
    Materi,
    Like,
38
    LikeComment,
39
40
41
42
43
44
45
46
47
48
    Rating,
    ReqMaterial,
    RatingContributor,
    ViewStatistics,
)

from .views import (
    DaftarKatalog,
    DashboardKontributorView,
    DetailMateri,
49
50
    ProfilView,
    SuntingProfilView,
51
52
53
54
55
56
57
58
    SuksesLoginAdminView,
    SuksesLoginKontributorView,
    PostsView,
    RevisiMateriView,
    ReqMateriView,
    KatalogPerKontributorView,
    UploadMateriView,
    UploadMateriExcelView,
Yaumi's avatar
Yaumi committed
59
    PasswordChangeViews,
Yaumi's avatar
Yaumi committed
60
    password_success,
61
    MateriFavorite,
62
)
63
from app.forms import SuntingProfilForm, year_choices
64
from app.utils.fileManagementUtil import get_random_filename, remove_image_exifdata
65

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

68
69
70
71
72
73
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException
74
import requests
75
from statistics import mean
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)
84

85
86
87
#     def test_daftar_katalog_using_daftar_katalog_template(self):
#         response = Client().get("/")
#         self.assertTemplateUsed(response, "app/katalog_materi.html")
88

89
90
91
#     def test_daftar_katalog_using_daftar_katalog_func(self):
#         found = resolve("/")
#         self.assertEqual(found.func.__name__, DaftarKatalog.as_view().__name__)
92

93
94
95
96
97
98
#     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()
99

100
101
#         resp = Materi.objects.get(id=materi.id)
#         self.assertEqual(resp, materi)
102

103
104
#     def test_materi_model_generate_search_vector_after_save(self):
#         Materi(title="Eating book").save()
105

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
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
#         search_vector_new_materi = list(Materi.objects.values_list("_search_vector", flat=True))
#         expected_search_vector = ["'book':2A 'eat':1A"]

#         self.assertSequenceEqual(search_vector_new_materi, expected_search_vector)

#     def test_search_text_on_empty_database(self):
#         search_query = "test"

#         search_result = list(Materi.objects.search(search_query))
#         expected_search_result = []

#         self.assertSequenceEqual(search_result, expected_search_result)

#     def test_search_text_on_unmatched_data(self):
#         Materi(title="test satu sekarang").save()
#         Materi(title="test dua nanti").save()

#         search_query = "besok"

#         search_result = list(Materi.objects.search(search_query))
#         expected_search_result = []

#         self.assertSequenceEqual(search_result, expected_search_result)

#     def test_search_text_return_list_matched_by_rank(self):
#         materi_2 = Materi(title="ini lumayan cocok lumayan cocok")
#         materi_2.save()

#         materi_1 = Materi(title="ini sangat cocok sangat cocok sangat cocok")
#         materi_1.save()

#         materi_4 = Materi(title="ini tidak")
#         materi_4.save()

#         materi_3 = Materi(title="ini sedikit cocok")
#         materi_3.save()

#         search_query = "ini cocok"

#         search_result = list(Materi.objects.search(search_query))
#         expected_search_result = [materi_1, materi_2, materi_3]

#         self.assertSequenceEqual(search_result, expected_search_result)

# class DaftarKatalogSortingByJumlahUnduhTest(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()

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

#     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.*')
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
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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# 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__)

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

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


# class DetailMateriTest(TestCase):
#     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")

#         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()
#         self.materi1 = Materi.objects.first()
#         self.url = "/materi/" + str(self.materi1.id) + "/"

#         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,
#                                                  date_modified=datetime.now(), date_created=datetime.now())
#         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}
#         ajax_response = self.client.post("/comment/dislike/", payload)
#         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}
#         ajax_response = self.client.post("/comment/like/", payload)
#         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"]
429
        
430
431
#         payload = {"comment": comment, "session_id": session_id}
#         ajax_response = self.client.post("/comment/dislike/", payload)
432
        
433
434
435
436
437
438
439
440
441
442
443
444
445
#         ajax_response = self.client.post("/comment/dislike/", payload)
#         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"]
446
        
447
448
#         payload = {"comment": comment, "session_id": session_id}
#         ajax_response = self.client.post("/comment/like/", payload)
449
        
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
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
#         ajax_response = self.client.post("/comment/like/", payload)
#         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)

#     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"})
#         deleteURL = "/delete/" + str(self.materi1.id) + "/" + str(
#             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)
#         response = self.client.get(deleteURL)
#         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)
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
#     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")
589
    
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
#     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)
#         expected = self.materi1.author + " . (n.d) . " + self.materi1.title + " . " + self.materi1.publisher	
#         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)
#         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	
#         )	
#         self.assertIn(expected, response.context["citationAPA"])
638
    
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
#     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)
#         current_date = datetime.now()
#         current_day = str(current_date.day)
#         current_month = current_date.strftime("%b")
#         current_year = str(current_date.year)

#         expected = (	
#             "Agas, "	
#             + "Materi 1. "	
#             + "Kelas SC, n.d. "	
#             + "Accessed on: "	
#             + current_month	
#             + ". "	
#             + current_day	
#             + ", "	
#             + current_year	
#             + ". [Online]. "	
#             + "Available: http://testserver"	
#             + self.url	
#         )
#         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)
#         current_date = datetime.now()
#         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)


# 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(
#                     timestamp=datetime.now(), 
#                     materi=post, 
#                     session_id=("dummysession-" + str(i) + '-' + str(j))
#                 )
735
            
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
#         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)

#     def test_upload_page_url_admin_doesnt_exist(self):        
#         self.client.login(email="admin@gov.id",
#                           password="admin")
#         response = self.client.get("/unggah/")
#         self.assertEqual(response.status_code, 403)

#     def test_upload_page_url_admin_cant_upload(self):        
#         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})
1021
        
1022
1023
#         messages = list(dj_messages.get_messages(response.wsgi_request))
#         msg_text = messages[0].message
1024

1025
#         self.assertIn('Title', msg_text)
1026

1027
1028
1029
#     def test_upload_excel_upload_file_author_error(self):
#         self.client.login(email="kontributor@gov.id",
#                           password="kontributor")
1030

1031
1032
1033
1034
1035
#         field_lengths = {
#             'title':50,
#             'publisher':30,
#         }
#         file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)
1036

1037
1038
#         with open(file_name, 'rb') as fp:
#             response = self.client.post("/unggah_excel/", {'excel': fp})
1039
        
1040
1041
#         messages = list(dj_messages.get_messages(response.wsgi_request))
#         msg_text = messages[0].message
1042

1043
#         self.assertIn('Author', msg_text)
1044

1045

1046
1047
1048
#     def test_upload_excel_upload_file_publisher_error(self):
#         self.client.login(email="kontributor@gov.id",
#                           password="kontributor")
1049

1050
1051
1052
1053
1054
#         field_lengths = {
#             'title':50,
#             'author':30,
#         }
#         file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)
1055

1056
1057
#         with open(file_name, 'rb') as fp:
#             response = self.client.post("/unggah_excel/", {'excel': fp})
1058
        
1059
1060
#         messages = list(dj_messages.get_messages(response.wsgi_request))
#         msg_text = messages[0].message
1061

1062
#         self.assertIn('Publisher', msg_text)
1063

1064
1065
1066
#     def test_upload_excel_upload_file_categories_error(self):
#         self.client.login(email="kontributor@gov.id",
#                           password="kontributor")
1067

1068
1069
1070
1071
1072
1073
#         field_lengths = {
#             'title':50,
#             'author':30,
#             'publisher':30,
#         }
#         file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)
1074

1075
1076
#         with open(file_name, 'rb') as fp:
#             response = self.client.post("/unggah_excel/", {'excel': fp})
1077
        
1078
1079
#         messages = list(dj_messages.get_messages(response.wsgi_request))
#         msg_text = messages[0].message
1080

1081
#         self.assertIn('Kategori', msg_text)
1082

1083
1084
1085
#     def test_upload_excel_upload_file_success(self):
#         self.client.login(email="kontributor@gov.id",
#                           password="kontributor")
1086

1087
1088
1089
#         Category(name='Computer Science').save()
#         Category(name='Machine Learning').save()
#         Category(name='Deep Learning').save()
1090

1091
1092
1093
1094
1095
#         field_lengths = {
#             'title':50,
#             'author':30,
#             'publisher':30,
#         }
1096

1097
#         categories = ['Computer Science','Machine Learning','Deep Learning']
1098
        
1099
#         file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths, categories=categories)
1100

1101
1102
#         with open(file_name, 'rb') as fp:
#             response = self.client.post("/unggah_excel/", {'excel': fp})
1103
        
1104
1105
#         title = data_frame['Title'][0]
#         self.assertTrue(Materi.objects.get(title=title))
1106

1107
1108
1109
#     def test_upload_excel_download_template(self):
#         self.client.login(email="kontributor@gov.id",
#                           password="kontributor")
1110

1111
#         response = self.client.get("/unggah_excel/?template=1")
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
1142
1143
1144
1145
1146
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
#         self.assertEquals(response['Content-Type'],'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
#         self.assertEquals(response['Content-Disposition'],'attachment; filename=template.xlsx')



# class DashboardKontributorViewTest(TestCase):
#     def setUp(self):
#         self.client = Client()
#         self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
#                                                            password="kontributor")
#         self.admin = User.objects.create_admin(email="admin@gov.id",
#                                                password="admin")
#         self.url = "/dashboard/"
#         self.view = DashboardKontributorView
#         self.template_name = "dashboard.html"

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

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

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

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

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

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

#         # Anonim
#         # Test
#         response = self.client.get(self.url)
#         self.assertEqual(response.status_code, 403)

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

# class DeleteMateriTest(TestCase):
#     def setUp(self):
#         self.client = Client()
#         self.admin_credential = {
#             "email": "admin@gov.id",
#             "password": id_generator()
#         }
#         self.superuser_credential = {
#             "email": "superuser@gov.id",
#             "password": id_generator()
#         }
#         self.contributor_credential = {
#             "email": "contributor@gov.id",
#             "password": id_generator()
#         }

#         self.admin = get_user_model().objects.create_user(
#             **self.admin_credential, name="Admin", is_admin=True)
#         self.superuser = get_user_model().objects.create_user(
#             **self.superuser_credential, name="Superuser", is_admin=True, is_superuser=True)

#         self.content = SimpleUploadedFile(
#             "content.txt", b"Test")
#         self.cover = SimpleUploadedFile(
#             "flower.jpg", b"Test file")
#         self.contributor = User.objects.create_contributor(**self.contributor_credential)
#         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()
#         self.materi1 = Materi.objects.first()
#         self.url = "/materi/" + str(self.materi1.id) + "/delete"

#     def test_url_delete_materi_is_success_as_contributor(self):
#         self.client.login(**self.contributor_credential)
#         response = self.client.get(self.url)
#         self.assertEqual(response.status_code, 302)
1221
    
1222
1223
1224
1225
1226
1227
#     def test_url_soft_delete_materi_is_success_as_admin(self):
#         self.client.login(**self.admin_credential)
#         response = self.client.get(self.url)
#         self.assertEqual(response.status_code, 302) 
#         self.materi1.refresh_from_db()
#         self.assertNotEqual(self.materi1.deleted_at, None)
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
1289
1290
1291
1292
1293
1294
1295
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
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
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
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
#     def test_url_soft_delete_materi_is_success_as_superuser(self):
#         self.client.login(**self.superuser_credential)
#         response = self.client.get(self.url)
#         self.assertEqual(response.status_code, 302)
#         self.materi1.refresh_from_db()
#         self.assertNotEqual(self.materi1.deleted_at, None)

# class ProfilViewTest(TestCase):
#     @classmethod
#     def setUpTestData(cls):
#         cls.client = Client()
#         cls.url = "/profil/"
#         cls.template_name = "profil.html"
#         cls.view = ProfilView

#         cls.contributor_credentials = {"email": "contributor@gov.id", "password": "justpass"}
#         cls.contributor = User.objects.create_contributor(**cls.contributor_credentials)

#         cls.admin_credentials = {"email": "admin@gov.id", "password": "justpass"}
#         cls.admin = User.objects.create_admin(**cls.admin_credentials)

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

#     def _request_as_user(self, credentials):
#         self.client = Client() 
#         self.client.login(**credentials)
#         return self.client.get(self.url)

#     def test_returns_correct_template(self):
#         response = self._request_as_user(self.contributor_credentials)
#         self.assertTemplateUsed(response, self.template_name)

#     def test_unauthenticated_access_blocked(self):
#         response = self._request_as_user({})
#         self.assertEqual(response.status_code, 403)

#     def test_authorized_access_success(self):
#         response = self._request_as_user(self.contributor_credentials)
#         self.assertEqual(response.status_code, 200)
#         self.assertIn("Profil Kontributor", response.content.decode())

#         response = self._request_as_user(self.admin_credentials)
#         self.assertEqual(response.status_code, 200)
#         self.assertIn("Profil Admin", response.content.decode())


# class SuntingProfilViewTest(TestCase):

#     @classmethod
#     def setUpTestData(cls):
#         cls.client = Client()
#         cls.url = "/sunting/"
#         cls.template_name = "sunting.html"
#         cls.view = SuntingProfilView

#         cls.contributor_credentials = {"email": "contributor@gov.id", "password": "justpass"}
#         cls.contributor = User.objects.create_contributor(**cls.contributor_credentials)

#         cls.admin_credentials = {"email": "admin@gov.id", "password": "justpass"}
#         cls.admin = User.objects.create_admin(**cls.admin_credentials)

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

#     def _request_as_user(self, credentials):
#         self.client = Client() 
#         self.client.login(**credentials)
#         return self.client.get(self.url)

#     def test_returns_correct_template(self):
#         self.client.login(**self.contributor_credentials)
#         response = self.client.get(self.url)
#         self.assertTemplateUsed(response, self.template_name)

#     def test_unauthenticated_access_blocked(self):
#         response = self._request_as_user({})
#         self.assertEqual(response.status_code, 403)

#     def test_authorized_access_success(self):
#         response = self._request_as_user(self.contributor_credentials)
#         self.assertEqual(response.status_code, 200)
#         self.assertIn("Sunting Profil Kontributor", response.content.decode())

#         response = self._request_as_user(self.admin_credentials)
#         self.assertEqual(response.status_code, 200)
#         self.assertIn("Sunting Profil Admin", response.content.decode())

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

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


# class SuksesLoginKontributorTest(TestCase):
#     def setUp(self):
#         self.client = Client()
#         self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
#                                                            password="kontributor")
#         self.admin = User.objects.create_admin(email="admin@gov.id",
#                                                password="admin")
#         self.url = "/sukses-kontributor/"
#         self.view = SuksesLoginKontributorView
#         self.template_name = "sukses_kontri.html"

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

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

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

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


# class SuksesLoginAdminTest(TestCase):
#     def setUp(self):
#         self.client = Client()
#         self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
#                                                            password="kontributor")
#         self.admin = User.objects.create_admin(email="admin@gov.id",
#                                                password="admin")
#         self.url = "/sukses-admin/"
#         self.view = SuksesLoginAdminView
#         self.template_name = "sukses_admin.html"

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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


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

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

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

#         response = Client().get(self.url)
#         num_of_downloads = self.materi1.unduh.all().count()
#         self.assertEqual(num_of_downloads, 2)


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

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

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

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

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

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

#     def test_revisi_materi_access(self):
#         # Kontributor
#         # Login
#         self.client.login(**self.contributor_credential)
#         # Test
#         response = self.client.get(self.url)
#         self.assertEqual(response.status_code, 200)
#         # Logout
#         self.client.logout()
1709
    
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
# class GenerateDummyCommandTest(TestCase):

#     def setUp(self):
#         self.material_numbers = [5, 10, 25, 100]
#         self.invalid_material_numbers = [-100, -10, -1, 0, 1, 2, 3, 4]
#         self.stdout = StringIO()

#     def test_command_output_with_given_num_of_materi(self):
#         for num_of_materi in self.material_numbers:
#             call_command("generatedummy", num_of_materi, stdout=self.stdout)
#             self.assertIn(
#                 f"Successfully created {num_of_materi} materi",
#                 self.stdout.getvalue()
#             )

#     def test_command_should_generate_materi_objects(self):
#         for num_of_materi in self.material_numbers:
#             call_command("generatedummy", num_of_materi, stdout=self.stdout)
#             self.assertEqual(Materi.objects.count(), num_of_materi)
#             Materi.objects.all().delete()

#     def test_command_should_raise_exception_if_invalid_values_are_given(self):
#         with self.assertRaises(IndexError):
#             for num_of_materi in self.invalid_material_numbers:
#                 call_command("generatedummy", num_of_materi)


# class RemoveDummyCommandTest(TestCase):

#     def test_calling_remove_dummy_command_should_remove_generated_dummy_objects(self):
#         stdout = StringIO()
#         call_command("generatedummy", 50)

#         call_command("removedummy", stdout=stdout)

#         self.assertIn("Successfully remove all dummy object", stdout.getvalue())
#         self.assertEqual(User.objects.count(), 0)
#         self.assertEqual(Category.objects.count(), 0)
#         self.assertEqual(Materi.objects.count(), 0)
#         self.assertEqual(VerificationSetting.objects.count(), 0)
#         self.assertEqual(VerificationReport.objects.count(), 0)


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

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

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

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

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

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

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

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

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

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

#     def test_rating_materi_url_use_add_rating_materi_function(self):
#         found = resolve(self.url_rate)
#         self.assertEqual(found.func, add_rating_materi)

#     def test_rating_materi_get_method_should_return_403_forbidden(self):
#         response = self.client.get(self.url_rate)
#         response_json = json.loads(response.content)
#         self.assertEqual(response_json.get("success", None), False)
#         self.assertEqual(response_json.get("msg", None), "Forbidden")
#         self.assertEqual(response.status_code, 403)

#     def test_rating_materi_post_not_authenticated_should_return_403_forbidden(self):
#         response = self.client.post(self.url_rate, {'materi_id': 1, 'rating_score': 5})
#         response_json = json.loads(response.content)
#         self.assertEqual(response_json.get("success", None), False)
#         self.assertEqual(response_json.get("msg", None), "Forbidden")
#         self.assertEqual(response.status_code, 403)

#     def test_rating_materi_not_authenticated_post_wrong_param_should_return_403_forbidden(self):
#         for data in [{}, {'materi_id': 1}, {'rating_score': 1}, {'rating_score': 'STRING', 'materi_id': 'STRING'}]:
#             response = self.client.post(self.url_rate, data)
#             response_json = json.loads(response.content)
#             self.assertEqual(response_json.get("success", None), False)
#             self.assertEqual(response_json.get("msg", None), "Forbidden")
#             self.assertEqual(response.status_code, 403)

#     def test_rating_materi_authenticated_post_missing_param(self):
#         self.client.login(**self.user_one_credential)
#         for data in [{'rating_score': 1}, {'materi_id': 1}, {}]:
#             response = self.client.post(self.url_rate, data)
#             response_json = json.loads(response.content)
#             self.assertEqual(response_json.get("success", None), False)
#             self.assertEqual(response_json.get("msg", None), "Missing param")
#             self.assertEqual(response.status_code, 422)

#     def test_rating_materi_authenticated_materi_id_doesnt_exist_should_return_422(self):
#         self.client.login(**self.user_one_credential)
#         response = self.client.post(self.url_rate, {'materi_id': 123456, 'rating_score': 5})
#         response_json = json.loads(response.content)
#         self.assertEqual(response_json.get("success", None), False)
#         self.assertEqual(response_json.get("msg", None), "Materi does not exist")
#         self.assertEqual(response.status_code, 422)

#     def test_rating_materi_authenticated_param_wrong_data_type_should_return_422(self):
#         self.client.login(**self.user_one_credential)
#         response = self.client.post(self.url_rate, {'materi_id': "STRING", 'rating_score': 5})
#         response_json = json.loads(response.content)
#         self.assertEqual(response_json.get("success", None), False)
#         self.assertEqual(response_json.get("msg", None), "materi_id must be an integer")
#         self.assertEqual(response.status_code, 422)

#         response = self.client.post(self.url_rate, {'materi_id': 1, 'rating_score': "STRING"})
#         response_json = json.loads(response.content)
#         self.assertEqual(response_json.get("success", None), False)
#         self.assertEqual(response_json.get("msg", None), "rating_score must be an integer")
#         self.assertEqual(response.status_code, 422)

#     def test_rating_score_should_be_between_1_and_5(self):
#         self.client.login(**self.user_one_credential)
#         for i in range(1, 6):
#             Rating.objects.all().delete()
#             response = self.client.post(self.url_rate, {'materi_id': self.materi1.id, 'rating_score': i})
#             response_json = json.loads(response.content)
#             # self.assertEqual(response_json.get("success", None), True)
#             self.assertEqual(response_json.get("msg", None), "Rating successfully created")
#             self.assertEqual(response.status_code, 201)

#         for i in [-100, -7, -6, -1, 0, 6, 7, 100]:
#             Rating.objects.all().delete()
#             response = self.client.post(self.url_rate, {'materi_id': self.materi1.id, 'rating_score': i})
#             response_json = json.loads(response.content)
#             # self.assertEqual(response_json.get("success", None), False)
#             self.assertEqual(response_json.get("msg", None), "Rating must be an integer from 1 to 5")
#             self.assertEqual(response.status_code, 422)

#     def test_user_should_not_able_to_rate_materi_twice(self):
#         self.client.login(**self.user_one_credential)
#         Rating.objects.all().delete()
#         self.client.post(self.url_rate, {'materi_id': self.materi1.id, 'rating_score': 1})
#         response = self.client.post(self.url_rate, {'materi_id': self.materi1.id, 'rating_score': 2})
#         response_json = json.loads(response.content)
#         # self.assertEqual(response_json.get("success", None), False)
#         self.assertEqual(response_json.get("msg", None), "Rating already exist")
#         self.assertEqual(response.status_code, 409)

#     def test_user_authenticated_visit_unrated_should_get_0_materi_rating_score_context(self):
#         self.client.login(**self.user_one_credential)
#         response = self.client.get(self.url_materi)
#         self.assertEqual(0, response.context.get('materi_rating_score'))

#     def test_user_not_authenticated_visit_unrated_should_get_0_materi_rating_score_context(self):
#         response = self.client.get(self.url_materi)
#         self.assertEqual(0, response.context.get('materi_rating_score'))

#     def test_user_authenticated_visit_rated_should_get_correct_materi_rating_score_context(self):
#         self.client.login(**self.user_one_credential)
#         Rating(materi=self.materi1, user=self.user_one, score=1).save()
#         response = self.client.get(self.url_materi)
#         self.assertEqual(1, response.context.get('materi_rating_score'))

# class fileManagementUtilTest(TestCase):
#     def setUp(self):
#         self.filename = "image_with_exif_data.gif"
#         self.file_content = open(settings.BASE_DIR + "/app/test_files/" +
#                 self.filename, "rb").read()

#     def test_get_random_filename_isCorrect(self):
#         generated_name = get_random_filename(self.filename)

#         self.assertTrue(generated_name != self.filename)
#         # 40 from 36 expected name length + 4 from extension
#         self.assertEqual(len(generated_name), 40)
#         self.assertTrue(generated_name[-4:] == ".gif")

#     def test_remove_image_exifdata_isCorrect(self):
#         with tempfile.TemporaryDirectory() as d:
#             image_with_exif_data_path = os.path.join(d, self.filename)
#             img = open(image_with_exif_data_path, "wb")
#             img.write(self.file_content)
#             img.close()

#             remove_image_exifdata(image_with_exif_data_path)
#             sanitized_img = open(image_with_exif_data_path, "rb").read()

#             self.assertTrue(len(sanitized_img) < len(self.file_content))
#             self.assertTrue(b'<exif:' not in sanitized_img)

# class RequestMateriTest(TestCase):
#     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.url = "/req-materi/"
#         self.template_name = "req_materi.html"

#     def test_req_materi_url_resolves_to_get_req_materi_view(self):
#         found = resolve(self.url)
#         self.assertEqual(found.func.__name__, ReqMateriView.as_view().__name__)

#     def test_uses_req_material_template(self):
#         self.client.login(**self.contributor_credential)
#         response = self.client.get(self.url)
#         self.assertTemplateUsed(response, self.template_name)
#         self.client.logout()

#     def test_redirect_to_login_page_is_not_authenticated(self):
#         response = self.client.get(self.url)

#         self.assertEqual(response.status_code, 302)
#         self.assertEqual(response['location'], '/login/')

#     def test_saving_and_retrieving_material_requests(self):
#         first_material_request = ReqMaterial(title="Material 1").save()
#         second_material_request = ReqMaterial(title="Material 2").save()
#         saved_material_request = ReqMaterial.objects.all()
#         self.assertEqual(saved_material_request.count(), 2)

#     def test_can_save_a_POST_request_and_return_correct_response_message(self):
#         self.client.login(**self.contributor_credential)

#         response = self.client.post(self.url,
#                          data={
#                              'title': 'Requested Material'
#                          })
#         self.assertEqual(ReqMaterial.objects.count(), 1)

#         new_material_request = ReqMaterial.objects.first()
#         self.assertEqual(new_material_request.title, 'Requested Material')

#         self.assertIn('Permintaan materi berhasil dikirimkan', response.content.decode())
#         self.client.logout()

#     def test_given_no_title_should_not_save_request_and_return_correct_response_message(self):
#         self.client.login(**self.contributor_credential)

#         response = self.client.post(self.url)
#         self.assertEqual(ReqMaterial.objects.count(), 0)

#         self.assertIn('Missing parameter', response.content.decode())
#         self.client.logout()


# class RatingContributorTest(TransactionTestCase):
#     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
#         )

#     def test_add_rating_contributor(self):
#         RatingContributor.objects.create(score=3, user=self.contributor)
#         self.assertEqual(1, RatingContributor.objects.count())

#     def test_add_rating_contributor_should_failed_when_negative(self):
#         with self.assertRaises(ValidationError):
#             RatingContributor.objects.create(score=-1, user=self.contributor)
#         self.assertEqual(0, RatingContributor.objects.count())

#     def test_add_rating_contributor_should_failed_when_bigger_than_five(self):
#         with self.assertRaises(ValidationError):
#             RatingContributor.objects.create(score=6, user=self.contributor)
#         self.assertEqual(0, RatingContributor.objects.count())

#     def test_submit_form_correct_rating_contributor_should_added(self):
#         url = f"/profil/{self.contributor.email}/"
#         self.client.post(url, data={"user": self.contributor.id, "score": 5})
#         self.assertEqual(1, RatingContributor.objects.filter(user=self.contributor.id).count())
#         self.client.post(url, data={"user": self.contributor.id, "score": 1})
#         self.assertEqual(2, RatingContributor.objects.filter(user=self.contributor.id).count())

#     def test_submit_form_not_correct_rating_contributor_should__not_added(self):
#         url = f"/profil/{self.contributor.email}/"
#         self.client.post(url, data={"user": self.contributor.id, "score": 6})
#         self.assertEqual(0, RatingContributor.objects.filter(user=self.contributor.id).count())
#         self.client.post(url, data={"user": self.contributor.id, "score": 0})
#         self.assertEqual(0, RatingContributor.objects.filter(user=self.contributor.id).count())

#     def test_average_rating_score_empty(self):
#         url = f"/profil/{self.contributor.email}/"
#         response = self.client.get(url)
#         self.assertTemplateUsed(response=response, template_name="app/katalog_kontri.html")
#         self.assertContains(response=response, text="Rating: 0", count=1)
#         self.assertContains(response=response, text="oleh: 0 orang", count=1)

#     def test_average_rating_correct(self):
#         url = f"/profil/{self.contributor.email}/"
#         self.client.post(url, data={"user": self.contributor.id, "score": 5})
#         response = self.client.get(url)
#         self.assertContains(response=response, text="Rating: 5", count=1)
#         self.assertContains(response=response, text="oleh: 1 orang", count=1)

#     def test_average_rating_form_incorrect_correct(self):
#         url = f"/profil/{self.contributor.email}/"
#         self.client.post(url, data={"user": self.contributor.id, "score": 6})
#         response = self.client.get(url)
#         self.assertContains(response=response, text="Rating: 0", count=1)
#         self.assertContains(response=response, text="oleh: 0 orang", count=1)
#         self.client.post(url, data={"user": self.contributor.id, "score": -1})
#         response = self.client.get(url)
#         self.assertContains(response=response, text="Rating: 0", count=1)
#         self.assertContains(response=response, text="oleh: 0 orang", count=1)

#     def test_average_with_multiple_score_correct(self):
#         score = 5
#         avg = [score]
#         url = f"/profil/{self.contributor.email}/"
#         self.client.post(url, data={"user": self.contributor.id, "score": score})
#         response = self.client.get(url)
#         self.assertContains(response=response, text=f"Rating: {mean(avg)}", count=1)
#         self.assertContains(response=response, text=f"oleh: {len(avg)} orang", count=1)

#         score = 4
#         avg.append(score)
#         self.client.post(url, data={"user": self.contributor.id, "score": score})
#         response = self.client.get(url)
#         self.assertContains(response=response, text=f"Rating: {mean(avg)}", count=1)
#         self.assertContains(response=response, text=f"oleh: {len(avg)} orang", count=1)

#         score = 3
#         avg.append(score)
#         self.client.post(url, data={"user": self.contributor.id, "score": score})
#         response = self.client.get(url)
#         self.assertContains(response=response, text=f"Rating: {mean(avg)}", count=1)
#         self.assertContains(response=response, text=f"oleh: {len(avg)} orang", count=1)

#         score = 2
#         avg.append(score)
#         self.client.post(url, data={"user": self.contributor.id, "score": score})
#         response = self.client.get(url)
#         self.assertContains(response=response, text=f"Rating: {mean(avg)}", count=1)
#         self.assertContains(response=response, text=f"oleh: {len(avg)} orang", count=1)

#         score = 1
#         avg.append(score)
#         self.client.post(url, data={"user": self.contributor.id, "score": score})
#         response = self.client.get(url)
#         self.assertContains(response=response, text=f"Rating: {mean(avg)}", count=1)
#         self.assertContains(response=response, text=f"oleh: {len(avg)} orang", count=1)


# class UserDownloadHistoryTest(TestCase):
#     def setUp(self):
#         self.user1_credential = {
#             "email": "anonim1@gov.id",
#             "password": id_generator()
#         }
#         self.user1_anonim = get_user_model().objects.create_user(
#             **self.user1_credential, name="Anonim1")
#         self.user2_credential = {
#             "email": "anonim2@gov.id",
#             "password": id_generator()
#         }
#         self.user2_anonim = get_user_model().objects.create_user(
#             **self.user2_credential, name="Anonim2")
#         self.contributor_credential = {
#             "email": "kontributor@gov.id",
#             "password": id_generator()
#         }
#         self.contributor = get_user_model().objects.create_user(
#             **self.contributor_credential, name="Kontributor", is_contributor=True
#         )
#         self.client = Client()
#         content = b"Test file"
#         self.cover = SimpleUploadedFile(
#             "cover.jpg",
#             content
#         )
#         self.content = SimpleUploadedFile(
#             "content.txt",
#             content
#         )
#         Materi(title="Materi 1", author="Agas", uploader=self.contributor,
#                publisher="Kelas SC", descriptions="Deskripsi Materi 1",
#                status="PENDING", cover=self.cover, content=self.content).save()
#         self.materi1 = Materi.objects.first()
#         self.download_url = f"/materi/{self.materi1.id}/unduh"
#         self.history_url = "/download-history/"
2184
	
2185
2186
2187
2188
#     def test_multiple_insert_download_statistic_with_user(self):
#         DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
#         num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         self.assertEqual(num_of_downloads, 1)
2189
		
2190
2191
2192
#         DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
#         num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         self.assertEqual(num_of_downloads, 2)
2193
		
2194
2195
2196
2197
#     def test_download_statistics_bound_to_specific_user(self):
#         DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
#         num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         self.assertEqual(num_of_downloads, 1)
2198
		
2199
2200
2201
#         DownloadStatistics(materi=self.materi1).save()
#         num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         self.assertEqual(num_of_downloads, 1)
2202
		
2203
2204
2205
2206
2207
2208
2209
2210
2211
#         DownloadStatistics(materi=self.materi1, downloader=self.user2_anonim).save()
#         user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         user2_num_of_downloads = self.user2_anonim.riwayat_unduh.all().count()
#         self.assertEqual(user1_num_of_downloads, 1)
#         self.assertEqual(user2_num_of_downloads, 1)

#     def test_registered_user_download(self):
#         # Login
#         self.client.login(**self.user1_credential)
2212
		
2213
2214
2215
#         self.client.get(self.download_url)
#         num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         self.assertEqual(num_of_downloads, 1)
2216
		
2217
2218
#         # Logout
#         self.client.logout()
2219
		
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
#     def test_unregistered_user_download(self):
#         self.client.get(self.download_url)
#         downloaded_materi = self.client.session['downloaded_materi']
#         num_of_downloads = DownloadStatistics.objects.filter(
#                             pk__in=downloaded_materi).count()
#         self.assertEqual(num_of_downloads, 1)

#     def test_registered_user_multiple_download(self):
#         # Login
#         self.client.login(**self.user1_credential)
#         self.client.get(self.download_url)
#         num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         self.assertEqual(num_of_downloads, 1)

#         self.client.get(self.download_url)
#         num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         self.assertEqual(num_of_downloads, 2)
2237
		
2238
2239
#         # Logout
#         self.client.logout()
2240
		
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
#     def test_unregistered_user_multiple_download(self):
#         self.client.get(self.download_url)
#         downloaded_materi = self.client.session['downloaded_materi']
#         num_of_downloads = DownloadStatistics.objects.filter(
#                             pk__in=downloaded_materi).count()
#         self.assertEqual(num_of_downloads, 1)

#         self.client.get(self.download_url)
#         downloaded_materi = self.client.session['downloaded_materi']
#         num_of_downloads = DownloadStatistics.objects.filter(
#                             pk__in=downloaded_materi).count()
#         self.assertEqual(num_of_downloads, 2)
2253
		
2254
2255
2256
#     def test_registered_user_doesnt_use_session_when_download(self):
#         # Login
#         self.client.login(**self.user1_credential)
2257
		
2258
2259
#         self.client.get(self.download_url)
#         self.assertFalse('downloaded_materi' in self.client.session)
2260
		
2261
2262
#         # Logout
#         self.client.logout()
2263
	
2264
2265
2266
2267
2268
2269
#     def test_download_history_bound_to_specific_user(self):
#         # Login Anonym 1
#         self.client.login(**self.user1_credential)
#         self.client.get(self.download_url)
#         num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         self.assertEqual(num_of_downloads, 1)
2270
		
2271
2272
#         # Logout Anonym 1
#         self.client.logout()
2273
		
2274
2275
2276
2277
2278
2279
2280
2281
# 		# Unregistered User download
#         self.client.get(self.download_url)
#         user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         downloaded_materi = self.client.session['downloaded_materi']
#         guest_num_of_downloads = DownloadStatistics.objects.filter(
#                             pk__in=downloaded_materi).count()
#         self.assertEqual(user1_num_of_downloads, 1)
#         self.assertEqual(guest_num_of_downloads, 1)
2282
		
2283
2284
2285
2286
2287
2288
2289
2290
# 		# Login Anonym 2
#         self.client.login(**self.user2_credential)
#         self.client.get(self.download_url)
#         user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
#         user2_num_of_downloads = self.user2_anonim.riwayat_unduh.all().count()
#         self.assertEqual(user1_num_of_downloads, 1)
#         self.assertEqual(guest_num_of_downloads, 1)
#         self.assertEqual(user2_num_of_downloads, 1)
2291
		
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
#         # Logout Anonym 2
#         self.client.logout()

# class DownloadHistoryViewTest(TestCase):
#     def setUp(self):
#         self.user_credential = {
#             "email": "anonim1@gov.id",
#             "password": id_generator()
#         }
#         self.user_anonim = get_user_model().objects.create_user(
#             **self.user_credential, name="Anonim")
#         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()
2311
		
2312
2313
#         content1 = b"Test file"
#         content2 = b"File Test"
2314
		
2315
2316
#         self.cover1 = SimpleUploadedFile("cover1.jpg",content1)
#         self.content1 = SimpleUploadedFile("content1.txt",content1)
2317
		
2318
2319
#         self.cover2 = SimpleUploadedFile("cover2.jpg",content2)
#         self.content2 = SimpleUploadedFile("content2.txt",content2)
2320
		
2321
2322
2323
2324
2325
2326
#         self.materi1 = Materi.objects.create(title="Materi 1", author="Agas", uploader=self.contributor,
#                publisher="Kelas SC", descriptions="Deskripsi Materi 1",
#                status="PENDING", cover=self.cover1, content=self.content1)
#         self.materi2 = Materi.objects.create(title="Materi 2", author="Danin", uploader=self.contributor,
#                publisher="Kelas DDP", descriptions="Deskripsi Materi 2",
#                status="PENDING", cover=self.cover2, content=self.content2)
2327
			   
2328
2329
2330
#         self.download_url1 = f"/materi/{self.materi1.id}/unduh"
#         self.download_url2 = f"/materi/{self.materi2.id}/unduh"
#         self.history_url = "/download-history/"
2331
		
2332
2333
#         # Login
#         self.client.login(**self.user_credential)
2334

2335
2336
2337
#     def tearDown(self):
#         # Logout
#         self.client.logout()
2338
		
2339
2340
2341
#     def test_allow_registered_user(self):
#         response = self.client.get(self.history_url)
#         self.assertEqual(response.status_code, 200)
2342
	
2343
2344
2345
#     def test_allow_unregistered_user(self):
# 	    # Forced Logout
#         self.client.logout()
2346
		
2347
2348
#         response = self.client.get(self.history_url)
#         self.assertEqual(response.status_code, 200)
2349

2350
2351
2352
#     def test_download_history_using_correct_template(self):
#         response = self.client.get(self.history_url)
#         self.assertTemplateUsed(response, "download_history.html")
2353

2354
2355
2356
2357
#     def test_download_history_has_user_name(self):
#         response = self.client.get(self.history_url)
#         resp_html = response.content.decode('utf8')
#         self.assertIn(self.user_anonim.name, resp_html)
2358
		
2359
2360
2361
2362
#     def test_registered_user_download_history_correctly_displayed(self):
#         self.client.get(self.download_url1)