Fakultas Ilmu Komputer UI

tests.py 119 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
class DaftarKatalogTest(TestCase):
    def test_daftar_katalog_url_exist(self):
        url = "/"
82
83
        response = Client().get(f"{url}")
        self.assertEqual(response.status_code, 200)
84
85

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

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

    def test_fields(self):
        materi = Materi()
95
96
97
        materi.title = "tes"
        materi.cover = "https://cache.umusic.com/_sites/billieeilish/v2/images/pic-red.jpg"
        materi.author = "input"
98
99
        materi.save()

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

103
104
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
    def test_materi_model_generate_search_vector_after_save(self):
        Materi(title="Eating book").save()

        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)

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
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.*')
189

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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.*')
    
224
225
226
class DaftarKatalogPerKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
227

228
229
230
231
        self.contributor_credential = {
                "email": "kontributor@gov.id",
                "password": "passwordtest"
            }
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
232

233
234
235
236
        self.contributor_credential_2 = {
                "email": "kontributor2@gov.id",
                "password": "passwordtest"
            }
237
238

        self.contributor = get_user_model().objects.create_user(
239
            **self.contributor_credential, name="Kontributor 1", is_contributor=True)
240
        self.contributor2 = get_user_model().objects.create_user(
241
            **self.contributor_credential_2, name="Kontributor 2", is_contributor=True)
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
242

243
244
        self.cover = SimpleUploadedFile(
            "Cherprang_Areekul40_nJM9dGt.jpg", b"Test file")
245
246
        self.content = SimpleUploadedFile("Bahan_PA_RKK.pdf", b"Test file")

247
248
249
250
251
252
253
254
255
        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()
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
256

257
        self.url = f"/profil/{self.contributor.email}/"
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
258

259
260
261
262
263
264
    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)
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
265
        self.assertTemplateUsed(response, "app/katalog_kontri.html")
266
267
268
269
270
271
272

    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)
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
273
274

        list_materi = Materi.objects.filter(uploader=self.contributor)
275
        data = response.context_data["materi_list"]
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
276
        self.assertEqual(len(list_materi), len(data))
277

278

Saul Andre's avatar
Saul Andre committed
279
class DetailMateriTest(TestCase):
280
    def setUp(self):
281
        self.client = Client()
282
283
284
285
286
287
288
289
290
291
292
293
294
295
        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)
296
        self.contributor = get_user_model().objects.create_user(
297
298
299
            **self.contributor_credential, name="Kontributor", is_contributor=True)
        self.anonymous = get_user_model().objects.create_user(
            **self.anonymous_credential, name="Anonymous"
300
        )
301
302
        self.cover = SimpleUploadedFile(
            "ExampleCover921.jpg", b"Test file")
303
        self.content = SimpleUploadedFile("ExampleFile921.pdf", b"Test file")
304

305
306
307
        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()
308
        self.materi1 = Materi.objects.first()
309
        self.url = "/materi/" + str(self.materi1.id) + "/"
310

311
312
313
314
        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())
315
        self.materi_with_published_date_url = "/materi/" + str(self.materi_with_published_date.id) + "/"
316
317
318
319
        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)
320

321
    def test_detail_materi_url_exist(self):
322
        response = Client().get(self.url)
323
        self.assertEqual(response.status_code, 200)
324
325
326
        self.assertNotEqual(response.status_code, 404)

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

Saul Andre's avatar
Saul Andre committed
330
    def test_detail_materi_using_detail_materi_func(self):
331
        found = resolve(self.url)
Saul Andre's avatar
Saul Andre committed
332
        self.assertEqual(found.func.__name__, DetailMateri.as_view().__name__)
333

Saul Andre's avatar
Saul Andre committed
334
    def test_category_models_can_create_new_object(self):
335
336
        test = Category.objects.create(
            id="1", name="medis", description="kategori medis")
337
338
339
        count = Category.objects.all().count()
        self.assertEqual(1, count)
        self.assertNotEqual(0, count)
Saul Andre's avatar
Saul Andre committed
340
341
        self.assertEqual(test.__str__(), "medis")
        self.assertNotEqual(test.__str__(), "saul")
Samuel Dimas's avatar
Samuel Dimas committed
342

Saul Andre's avatar
Saul Andre committed
343
    def test_comment_models_can_create_new_object(self):
344
345
        test = Comment.objects.create(
            username="saul", profile="121212", comment="232323")
346
347
348
        count = Comment.objects.all().count()
        self.assertEqual(1, count)
        self.assertNotEqual(0, count)
Saul Andre's avatar
Saul Andre committed
349
350
        self.assertEqual(test.__str__(), "saul")
        self.assertNotEqual(test.__str__(), "userlain")
351

352
    def test_post_blank_comment(self):
353
354
355
356
        url = self.url
        self.client.login(**self.anonymous_credential)
        response = self.client.post(url, {"comment": ""})
        self.assertIn("error_message", response.context)
357
358
        self.assertIn("Anda belum menuliskan komentar",
                      response.context["error_message"])
359
360
361
362
363

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

367
    def test_comment_by_admin(self):
368
369
370
371
        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)
372
373
374
        self.assertContains(response, "Admin")

    def test_comment_by_kontributor(self):
375
376
        url = self.url
        self.client.login(**self.contributor_credential)
377
378
        self.client.post(
            url, {"comment": "This is new comment by Contributor"})
379
380
        response = self.client.get(url)
        self.assertContains(response, "Kontributor")
381
382

    def test_comment_by_anonymous(self):
383
384
385
386
387
        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)
388
        self.assertContains(response, "Anonymous")
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
    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"]
        
        payload = {"comment": comment, "session_id": session_id}
        ajax_response = self.client.post("/comment/dislike/", payload)
        
        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"]
        
        payload = {"comment": comment, "session_id": session_id}
        ajax_response = self.client.post("/comment/like/", payload)
        
        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)

480
481
482
483
484
485
486
487
488
489
490
491
492
493
    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)")

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

499
500
501
502
503
    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")

504
    def create_and_delete_comment(self, is_admin=False, is_contributor=False):
505
        url = self.url
506
        self.client.login(**self.admin_credential)
507
        self.client.post(url, {"comment": "This is new comment by Anonymous"})
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
        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
    
    def test_review_models_can_create_new_object(self):
        test = Review.objects.create(
            username="saul", profile="121212", review="232323")
546
547
548
        count = Review.objects.all().count()
        self.assertEqual(1, count)
        self.assertNotEqual(0, count)
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
589
590
591
592
        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")
    
    def test_detail_materi_contains_review_count(self):
        url = self.url
        self.client.login(**self.contributor_credential)
593
        review = "This is new review by Contributor"
594
595
596
597
        response = self.client.get(url)
        self.assertContains(response, "Review (0)")

        self.client.post(
598
            url, {"review": review })
599
        self.client.post(
600
            url, {"review": review})
601
602
603
604
605
606
607
608
609
610
611
612
613
        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")

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

618
    def test_hasil_citasi_APA_materi_has_no_published_date(self):
619
        response = self.client.get(self.url)
620
        expected = self.materi1.author + " . (n.d) . " + self.materi1.title + " . " + self.materi1.publisher	
621
        self.assertIn(expected, response.context["citationAPA"])
622
623
        self.assertIn(expected,
                      response.context["citationAPA"])
624

625
626
    def test_hasil_citasi_APA_materi_has_published_date(self):
        response = self.client.get(self.materi_with_published_date_url)
627
628
629
630
631
632
633
634
635
636
        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	
        )	
637
        self.assertIn(expected, response.context["citationAPA"])
638
    
639
640
641
642
643
644
645
646
647
648
649
    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)

650
651
652
653
654
655
656
657
658
659
660
661
662
        expected = (	
            "Agas, "	
            + "Materi 1. "	
            + "Kelas SC, n.d. "	
            + "Accessed on: "	
            + current_month	
            + ". "	
            + current_day	
            + ", "	
            + current_year	
            + ". [Online]. "	
            + "Available: http://testserver"	
            + self.url	
663
        )
664
665
666
667
668
669
670
671
        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)
672
673
674
675
676
677
678
679
        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
680
        self.assertIn(expected, response.context["citationIEEE"])
681

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

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

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

701

702
class PostsViewTest(TestCase):
703

704
705
706
707
    @classmethod
    def generate_posts_data(cls, user):
        POST_COUNT = 3
        COMMENTS_COUNT_PER_POST = [1, 0, 3]
708
        LIKES_COUNT_PER_POST = [5, 4, 2]
709
710
711
712
713
714
715

        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 = {}
716
        for i in range(POST_COUNT):
717
718
719
720
721
            post = Materi.objects.create(
                uploader=user,
                cover=sample_file,
                content=sample_file,
            )
722
723
724
725
726
727
728
            post.categories.add(sample_category)

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

729
            for j in range (LIKES_COUNT_PER_POST[i]):
730
                Like.objects.create(
731
732
733
                    timestamp=datetime.now(), 
                    materi=post, 
                    session_id=("dummysession-" + str(i) + '-' + str(j))
734
                )
735
            
736
737
738
739
740
741
742
743
744
745
746
747
748
749
        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):
750
751
752
753
754
        cls.url = '/posts/'
        cls.user_credentials = {
            "email": "user@email.com",
            "password": "justpass"
        }
755
756
757
758
759
760
761
762
        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):
763
        found = resolve(self.url)
764
        self.assertEqual(found.func.__name__, PostsView.as_view().__name__)
765

766
767
768
    def test_returns_200_on_authenticated_access(self):
        response = self._request_as_user()
        self.assertEqual(response.status_code, 200)
769

770
    def test_returns_403_on_unauthenticated_access(self):
771
        response = self.client.get(self.url)
772
        self.assertRaises(PermissionDenied)
773
        self.assertEqual(response.status_code, 403)
774

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

778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
    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())
798
799
800
801
        comments = {
            i: [comment.id for comment in self.data[post_id]["comments"]]
            for i, post_id in enumerate(posts)
        }
802
803

        self.assertRegex(
804
            str(response.content),
805
806
807
808
809
810
811
            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]}">)'
812
813
        )

814
815
816
817
818
819
820
    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(
821
822
                response,
                '<span id="post-like-count-' + str(post.id) + '">' +  str(post.like_count) + '</span>',
823
            )
824

825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
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)
847
        self.assertEqual(response.status_code, 200)
848
        self.assertTemplateUsed(response, expected_template_name)
849

850

851
852
class UploadPageTest(TestCase):
    def setUp(self):
853
        self.client = Client()
854
855
856
857
        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")
858
859
860

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

Steven Kusuman's avatar
Steven Kusuman committed
864
    def test_upload_page_url_is_exist(self):
865
        # Positive test
866
867
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
868
        response = self.client.get("/unggah/")
869
        self.assertEqual(response.status_code, 200)
870
871

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

877
878
879
    def test_upload_page_url_admin_doesnt_exist(self):        
        self.client.login(email="admin@gov.id",
                          password="admin")
Steven Kusuman's avatar
Steven Kusuman committed
880
881
882
        response = self.client.get("/unggah/")
        self.assertEqual(response.status_code, 403)

883
884
885
    def test_upload_page_url_admin_cant_upload(self):        
        self.client.login(email="admin@gov.id",
                          password="admin")
Steven Kusuman's avatar
Steven Kusuman committed
886
887
888
        response = self.client.post("/unggah/")
        self.assertEqual(response.status_code, 403)

889
890
    def test_upload_page_template(self):
        url = "/unggah/"
891
892
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
893
894
        response = self.client.get(url)
        expected_template_name = "unggah.html"
895
        self.assertTemplateUsed(response, expected_template_name)
896
897

    def test_upload_page_title(self):
898
899
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
900
901
902
903
904
905
906
907
908
        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):
909
910
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
911
912
913
914
915
916
917
        response = self.client.get("/unggah/")

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

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

919

920
921
922
class UploadExcelPageTest(TestCase):
    def setUp(self):
        self.client = Client()
923
924
        self.user = User.objects._create_user(email="kontributor@gov.id",
                                              password="kontributor", is_contributor=True)
925
926
927

    def test_upload_excel_page_using_login_func(self):
        found = resolve("/unggah_excel/")
928
929
        self.assertEqual(found.func.__name__,
                         UploadMateriExcelView.as_view().__name__)
930
931
932

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

        # Negative tests
939
940
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
941
942
943
944
945
        response = Client().get("/fake/")
        self.assertEqual(response.status_code, 404)

    def test_upload_excel_page_template(self):
        url = "/unggah_excel/"
946
947
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
948
949
950
951
952
        response = self.client.get(url)
        expected_template_name = "unggah_excel.html"
        self.assertTemplateUsed(response, expected_template_name)

    def test_upload_excel_page_title(self):
953
954
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
955
956
957
958
959
960
961
962
963
        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):
964
965
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
        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."

981
982
        if 'title' in field_lengths:
            title1 = title1[:field_lengths['title']]
983

984
985
        if 'author' in field_lengths:
            author1 = author1[:field_lengths['author']]
986

987
988
        if 'publisher' in field_lengths:
            publisher1 = publisher1[:field_lengths['publisher']]
989
990

        if len(categories) > 0:
991
992
993
994
995
996
997
998
999
            categories1 = ','.join(categories)

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

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

1003
        writer = pd.ExcelWriter(file_path, engine='xlsxwriter') #pylint: disable=abstract-class-instantiated
1004
1005
1006
1007
1008
1009
        data_frame.to_excel(writer, index=0)
        writer.save()

        return file_path, data_frame

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

        field_lengths = {
1014
1015
            'author':30,
            'publisher':30,
1016
1017
1018
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)

1019
1020
1021
        with open(file_name, 'rb') as fp:
            response = self.client.post("/unggah_excel/", {'excel': fp})
        
1022
1023
1024
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message

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

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

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

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

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

1045
1046

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

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

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

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

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

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

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

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

    def test_upload_excel_upload_file_success(self):
1084
1085
        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

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

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

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

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

        response = self.client.get("/unggah_excel/?template=1")
1112
1113
1114
        
        self.assertEquals(response['Content-Type'],'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        self.assertEquals(response['Content-Disposition'],'attachment; filename=template.xlsx')
1115
1116
1117



1118
1119
1120
class DashboardKontributorViewTest(TestCase):
    def setUp(self):
        self.client = Client()
1121
1122
1123
1124
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
                                                           password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
        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