Fakultas Ilmu Komputer UI

tests.py 86.1 KB
Newer Older
1
import json, tempfile, os, mock
2
import pandas as pd
3
from io import StringIO
4
import time
5

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

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

from .views import (
    DaftarKatalog,
    DashboardKontributorView,
    DetailMateri,
    ProfilKontributorView,
    SuksesLoginAdminView,
    SuksesLoginKontributorView,
    SuntingProfilView,
    ProfilAdminView,
    PostsView,
    SuntingProfilAdminView,
    RevisiMateriView,
    ReqMateriView,
    KatalogPerKontributorView,
    UploadMateriView,
    UploadMateriExcelView,
)
56
from app.forms import SuntingProfilForm
57
from app.utils.fileManagementUtil import get_random_filename, remove_image_exifdata
58

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

61
62
63
64
65
66
67
68
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


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

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

79
    def test_daftar_katalog_using_daftar_katalog_func(self):
80
        found = resolve("/")
81
82
83
84
        self.assertEqual(found.func.__name__, DaftarKatalog.as_view().__name__)

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

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

93
94
95
96
97
98
99
100
101
102
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
    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)

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

180
181
182
class DaftarKatalogPerKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
183

184
        self.contributor_credential = {"email": "kontributor@gov.id", "password": "passwordtest"}
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
185

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

        self.contributor = get_user_model().objects.create_user(
189
190
            **self.contributor_credential, name="Kontributor 1", is_contributor=True
        )
191
        self.contributor2 = get_user_model().objects.create_user(
192
193
            **self.contributor_credential_2, name="Kontributor 2", is_contributor=True
        )
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
194

195
        self.cover = SimpleUploadedFile("Cherprang_Areekul40_nJM9dGt.jpg", b"Test file")
196
197
        self.content = SimpleUploadedFile("Bahan_PA_RKK.pdf", b"Test file")

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
        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
228

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

231
232
233
234
235
236
    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
237
        self.assertTemplateUsed(response, "app/katalog_kontri.html")
238
239
240
241
242
243
244

    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
245
246

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

250

Saul Andre's avatar
Saul Andre committed
251
class DetailMateriTest(TestCase):
252
    def setUp(self):
253
        self.client = Client()
254
255
256
257
        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)
258
        self.contributor = get_user_model().objects.create_user(
259
            **self.contributor_credential, name="Kontributor", is_contributor=True
260
        )
261
262
        self.anonymous = get_user_model().objects.create_user(**self.anonymous_credential, name="Anonymous")
        self.cover = SimpleUploadedFile("ExampleCover921.jpg", b"Test file")
263
        self.content = SimpleUploadedFile("ExampleFile921.pdf", b"Test file")
264

265
266
267
268
269
270
271
272
273
274
        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()
275
        self.materi1 = Materi.objects.first()
276
        self.url = "/materi/" + str(self.materi1.id) + "/"
277

278
279
280
281
282
283
284
285
286
287
288
289
        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(),
        )
290
        self.materi_with_published_date_url = "/materi/" + str(self.materi_with_published_date.id) + "/"
291
292
293
294
295
296
297
298
        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,
        )
299

300
    def test_detail_materi_url_exist(self):
301
        response = Client().get(self.url)
302
        self.assertEqual(response.status_code, 200)
303
304
305
        self.assertNotEqual(response.status_code, 404)

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

Saul Andre's avatar
Saul Andre committed
309
    def test_detail_materi_using_detail_materi_func(self):
310
        found = resolve(self.url)
Saul Andre's avatar
Saul Andre committed
311
        self.assertEqual(found.func.__name__, DetailMateri.as_view().__name__)
312

Saul Andre's avatar
Saul Andre committed
313
    def test_category_models_can_create_new_object(self):
314
        test = Category.objects.create(id="1", name="medis", description="kategori medis")
Saul Andre's avatar
Saul Andre committed
315
316
317
318
319
        countData = Category.objects.all().count()
        self.assertEqual(1, countData)
        self.assertNotEqual(0, countData)
        self.assertEqual(test.__str__(), "medis")
        self.assertNotEqual(test.__str__(), "saul")
Samuel Dimas's avatar
Samuel Dimas committed
320

Saul Andre's avatar
Saul Andre committed
321
    def test_comment_models_can_create_new_object(self):
322
        test = Comment.objects.create(username="saul", profile="121212", comment="232323")
Saul Andre's avatar
Saul Andre committed
323
324
325
326
327
        countData = Comment.objects.all().count()
        self.assertEqual(1, countData)
        self.assertNotEqual(0, countData)
        self.assertEqual(test.__str__(), "saul")
        self.assertNotEqual(test.__str__(), "userlain")
328

329
    def test_post_blank_comment(self):
330
331
332
333
        url = self.url
        self.client.login(**self.anonymous_credential)
        response = self.client.post(url, {"comment": ""})
        self.assertIn("error_message", response.context)
334
        self.assertIn("Anda belum menuliskan komentar", response.context["error_message"])
335
336
337
338
339

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

343
    def test_comment_by_admin(self):
344
345
346
347
        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)
348
349
350
        self.assertContains(response, "Admin")

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

    def test_comment_by_anonymous(self):
358
359
360
361
362
        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)
363
        self.assertContains(response, "Anonymous")
364

365
    def test_detail_materi_contains_form_comment(self):
366
        response = self.client.get(self.url)
367
        self.assertContains(response, "Beri komentar...")
368

369
370
371
    def test_delete_comments_by_admin(self):
        url = self.url
        self.client.post(url, {"comment": "This is new comment by Anonymous"})
372
373
374
375
376
377
        deleteURL = (
            "/delete/"
            + str(self.materi1.id)
            + "/"
            + str(Comment.objects.get(comment="This is new comment by Anonymous").id)
        )
378
        self.client.get(deleteURL)
379
        self.assertEqual(Comment.objects.all().filter(comment="This is new comment by Anonymous").count(), 0)
380

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

385
    def test_hasil_citasi_APA_materi_has_no_published_date(self):
386
        response = self.client.get(self.url)
387
388
        expected = self.materi1.author + " . (n.d) . " + self.materi1.title + " . " + self.materi1.publisher
        self.assertIn(expected, response.context["citationAPA"])
389

390
391
    def test_hasil_citasi_APA_materi_has_published_date(self):
        response = self.client.get(self.materi_with_published_date_url)
392
393
394
395
396
397
398
399
400
401
402
403
        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"])

404
405
406
407
408
409
410
411
412
413
414
    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)

415
416
417
418
419
420
421
422
423
424
425
426
427
428
        expected = (
            "Agas, "
            + "Materi 1. "
            + "Kelas SC, n.d. "
            + "Accessed on: "
            + current_month
            + ". "
            + current_day
            + ", "
            + current_year
            + ". [Online]. "
            + "Available: http://testserver"
            + self.url
        )
429
430
431
432
433
434
435
436
        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)
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
        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
        )
455
        self.assertIn(expected, response.context["citationIEEE"])
456

457
458
    def test_tombol_bagikan_google_drive(self):
        response = Client().get(self.url)
459
        self.assertContains(response, "Google Drive")
460

461
    @mock.patch("app.views.upload_to_gdrive")
462
    def test_save_to_gdrive_with_nonexistent_materi(self, mock_upload_to_gdrive):
463
        response = self.client.get("/materi/%s/save-to-gdrive/" % 0)
464
465
466
        mock_upload_to_gdrive.assert_not_called()
        self.assertEqual(response.status_code, 404)

467
    @mock.patch("app.views.upload_to_gdrive")
468
    def test_save_to_gdrive_with_valid_materi(self, mock_upload_to_gdrive):
469
        response = self.client.get("/materi/%s/save-to-gdrive/" % self.materi1.id, follow=True)
470
471
        last_url, status_code = response.redirect_chain[-1]
        mock_upload_to_gdrive.assert_called_once()
472
        self.assertEqual(last_url, "/materi/%d/" % self.materi1.id)
473
474
        self.assertEqual(status_code, 302)

475

476
class PostsViewTest(TestCase):
477
478
479
480
    @classmethod
    def generate_posts_data(cls, user):
        POST_COUNT = 3
        COMMENTS_COUNT_PER_POST = [1, 0, 3]
481
        LIKES_COUNT_PER_POST = [5, 4, 2]
482
483
484
485
486
487
488

        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 = {}
489
        for i in range(POST_COUNT):
490
            post = Materi.objects.create(uploader=user, cover=sample_file, content=sample_file,)
491
492
493
494
495
496
497
            post.categories.add(sample_category)

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

498
            for j in range(LIKES_COUNT_PER_POST[i]):
499
                Like.objects.create(
500
                    timestamp=datetime.now(), materi=post, session_id=("dummysession-" + str(i) + "-" + str(j))
501
                )
502

503
504
505
506
507
508
509
510
511
512
513
514
515
516
        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):
517
518
        cls.url = "/posts/"
        cls.user_credentials = {"email": "user@email.com", "password": "justpass"}
519
520
521
522
523
524
525
526
        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):
527
        found = resolve(self.url)
528
        self.assertEqual(found.func.__name__, PostsView.as_view().__name__)
529

530
531
532
    def test_returns_200_on_authenticated_access(self):
        response = self._request_as_user()
        self.assertEqual(response.status_code, 200)
533

534
    def test_returns_403_on_unauthenticated_access(self):
535
        response = self.client.get(self.url)
536
        self.assertRaises(PermissionDenied)
537
        self.assertEqual(response.status_code, 403)
538

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

542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
    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())
562
        comments = {i: [comment.id for comment in self.data[post_id]["comments"]] for i, post_id in enumerate(posts)}
563
564

        self.assertRegex(
565
            str(response.content),
566
567
568
569
570
571
572
            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]}">)',
573
574
        )

575
576
577
578
579
580
581
    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(
582
                response, '<span id="post-like-count-' + str(post.id) + '">' + str(post.like_count) + "</span>",
583
            )
584

585

586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
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)
608
        self.assertEqual(response.status_code, 200)
609
        self.assertTemplateUsed(response, expected_template_name)
610

611

612
613
class UploadPageTest(TestCase):
    def setUp(self):
614
        self.client = Client()
615
616
        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")
617
618
619

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

Steven Kusuman's avatar
Steven Kusuman committed
622
    def test_upload_page_url_is_exist(self):
623
        # Positive test
624
        self.client.login(email="kontributor@gov.id", password="kontributor")
625
        response = self.client.get("/unggah/")
626
        self.assertEqual(response.status_code, 200)
627
628

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

633
634
    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
635
636
637
        response = self.client.get("/unggah/")
        self.assertEqual(response.status_code, 403)

638
639
    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
640
641
642
        response = self.client.post("/unggah/")
        self.assertEqual(response.status_code, 403)

643
644
    def test_upload_page_template(self):
        url = "/unggah/"
645
        self.client.login(email="kontributor@gov.id", password="kontributor")
646
647
        response = self.client.get(url)
        expected_template_name = "unggah.html"
648
        self.assertTemplateUsed(response, expected_template_name)
649
650

    def test_upload_page_title(self):
651
        self.client.login(email="kontributor@gov.id", password="kontributor")
652
653
654
655
656
657
658
659
660
        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):
661
        self.client.login(email="kontributor@gov.id", password="kontributor")
662
663
664
665
666
667
668
        response = self.client.get("/unggah/")

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

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

670

671
672
673
class UploadExcelPageTest(TestCase):
    def setUp(self):
        self.client = Client()
674
        self.user = User.objects._create_user(email="kontributor@gov.id", password="kontributor", is_contributor=True)
675
676
677

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

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

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

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

    def test_upload_excel_page_title(self):
699
        self.client.login(email="kontributor@gov.id", password="kontributor")
700
701
702
703
704
705
706
707
708
        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):
709
        self.client.login(email="kontributor@gov.id", password="kontributor")
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
        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."

725
726
        if "title" in field_lengths:
            title1 = title1[: field_lengths["title"]]
727

728
729
        if "author" in field_lengths:
            author1 = author1[: field_lengths["author"]]
730

731
732
        if "publisher" in field_lengths:
            publisher1 = publisher1[: field_lengths["publisher"]]
733
734

        if len(categories) > 0:
735
736
737
738
739
740
741
742
743
744
745
            categories1 = ",".join(categories)

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

747
        file_path = os.path.join(settings.MEDIA_ROOT, "dummy.xlsx")
748

749
        writer = pd.ExcelWriter(file_path, engine="xlsxwriter")  # pylint: disable=abstract-class-instantiated
750
751
752
753
754
755
        data_frame.to_excel(writer, index=0)
        writer.save()

        return file_path, data_frame

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

        field_lengths = {
759
760
            "author": 30,
            "publisher": 30,
761
762
763
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)

764
765
766
        with open(file_name, "rb") as fp:
            response = self.client.post("/unggah_excel/", {"excel": fp})

767
768
769
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message

770
        self.assertIn("Title", msg_text)
771
772

    def test_upload_excel_upload_file_author_error(self):
773
        self.client.login(email="kontributor@gov.id", password="kontributor")
774
775

        field_lengths = {
776
777
            "title": 50,
            "publisher": 30,
778
779
780
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)

781
782
783
        with open(file_name, "rb") as fp:
            response = self.client.post("/unggah_excel/", {"excel": fp})

784
785
786
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message

787
        self.assertIn("Author", msg_text)
788
789

    def test_upload_excel_upload_file_publisher_error(self):
790
        self.client.login(email="kontributor@gov.id", password="kontributor")
791
792

        field_lengths = {
793
794
            "title": 50,
            "author": 30,
795
796
797
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)

798
799
800
        with open(file_name, "rb") as fp:
            response = self.client.post("/unggah_excel/", {"excel": fp})

801
802
803
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message

804
        self.assertIn("Publisher", msg_text)
805
806

    def test_upload_excel_upload_file_categories_error(self):
807
        self.client.login(email="kontributor@gov.id", password="kontributor")
808
809

        field_lengths = {
810
811
812
            "title": 50,
            "author": 30,
            "publisher": 30,
813
814
815
        }
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths)

816
817
818
        with open(file_name, "rb") as fp:
            response = self.client.post("/unggah_excel/", {"excel": fp})

819
820
821
        messages = list(dj_messages.get_messages(response.wsgi_request))
        msg_text = messages[0].message

822
        self.assertIn("Kategori", msg_text)
823
824

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

827
828
829
        Category(name="Computer Science").save()
        Category(name="Machine Learning").save()
        Category(name="Deep Learning").save()
830
831

        field_lengths = {
832
833
834
            "title": 50,
            "author": 30,
            "publisher": 30,
835
836
        }

837
838
        categories = ["Computer Science", "Machine Learning", "Deep Learning"]

839
840
        file_name, data_frame = self.create_dummy_excel(field_lengths=field_lengths, categories=categories)

841
842
843
844
        with open(file_name, "rb") as fp:
            response = self.client.post("/unggah_excel/", {"excel": fp})

        title = data_frame["Title"][0]
845
846
847
        self.assertTrue(Materi.objects.get(title=title))

    def test_upload_excel_download_template(self):
848
        self.client.login(email="kontributor@gov.id", password="kontributor")
849
850
851

        response = self.client.get("/unggah_excel/?template=1")

852
853
854
855
        self.assertEquals(
            response["Content-Type"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
        self.assertEquals(response["Content-Disposition"], "attachment; filename=template.xlsx")
856
857


858
859
860
class DashboardKontributorViewTest(TestCase):
    def setUp(self):
        self.client = Client()
861
862
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id", password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id", password="admin")
863
864
865
866
867
868
869
870
871
872
        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
873
        self.client.login(email="kontributor@gov.id", password="kontributor")
874
875
876
877
878
879
880
881
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_dashboard_kontributor_url(self):
        # Login
882
        self.client.login(email="kontributor@gov.id", password="kontributor")
883
884
885
886
887
888
889
890
891
        # 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
892
        self.client.login(email="kontributor@gov.id", password="kontributor")
893
894
895
896
897
898
899
900
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

        # Admin
        # Login
901
        self.client.login(email="admin@gov.id", password="admin")
902
903
904
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
905
906
907

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

911
912
913
914
        # Anonim
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
915

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

919

Selvy Fitriani's avatar
Selvy Fitriani committed
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
class DeleteMateriTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.content = SimpleUploadedFile(
            "content.txt", b"Test")
        self.cover = SimpleUploadedFile(
            "flower.jpg", b"Test file")
        self.contributor = User.objects.create_contributor(email="kontributor@gov.id",
                                                           password="kontributor")
        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(self):
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 302) 
        
939
940
941
class ProfilAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
942
943
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id", password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id", password="admin")
944
945
946
947
948
949
950
951
952
953
        self.url = "/profil-admin/"
        self.view = ProfilAdminView
        self.template_name = "profil-admin.html"

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

    def test_profil_admin_template(self):
        # Login
954
        self.client.login(email="admin@gov.id", password="admin")
955
956
957
958
959
960
961
962
963
964
965
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_profil_admin_url(self):
        # Login
        response = self.client.get(self.url)
        self.assertNotEqual(response.status_code, 200)

966
        self.client.login(email="admin@gov.id", password="admin")
967
968
969
970
971
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()
972

973

974
975
976
class ProfilKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
977
978
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id", password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id", password="admin")
979
980
981
        self.url = "/profil/"
        self.view = ProfilKontributorView
        self.template_name = "profil.html"
982

983
984
985
986
987
988
    def test_profil_kontributor_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_profil_kontributor_template(self):
        # Login
989
        self.client.login(email="kontributor@gov.id", password="kontributor")
990
991
992
993
994
995
996
997
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_profil_kontributor_url(self):
        # Login
998
        self.client.login(email="kontributor@gov.id", password="kontributor")
999
1000
1001
1002
1003
1004
1005
1006
1007
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_profil_kontributor_access(self):
        # Kontributor
        # Login
1008
        self.client.login(email="kontributor@gov.id", password="kontributor")
1009
1010
1011
1012
1013
1014
1015
1016
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

        # Admin
        # Login
1017
        self.client.login(email="admin@gov.id", password="admin")
1018
1019
1020
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
1021
1022
1023

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

1027
1028
1029
1030
        # Anonim
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
1031

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

1035

1036
1037
1038
class SuntingProfilTest(TestCase):
    def setUp(self):
        self.client = Client()
1039
1040
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id", password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id", password="admin")
1041
1042
1043
        self.url = "/sunting/"
        self.view = SuntingProfilView
        self.template_name = "sunting.html"
1044

1045
1046
1047
1048
1049
1050
    def test_sunting_profile_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_sunting_profile_template(self):
        # Login
1051
        self.client.login(email="kontributor@gov.id", password="kontributor")
1052
1053
1054
1055
1056
1057
1058
1059
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_sunting_profile_url(self):
        # Login
1060
        self.client.login(email="kontributor@gov.id", password="kontributor")
1061
1062
1063
1064
1065
1066
1067
1068
1069
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_sunting_profile_access(self):
        # Kontributor
        # Login
1070
        self.client.login(email="kontributor@gov.id", password="kontributor")
1071
1072
1073
1074
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
1075
1076
        self.client.logout()

1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
    def test_sunting_profile_access_anonymous(self):
        # Tes