Fakultas Ilmu Komputer UI

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

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

21
from administration.models import VerificationSetting, VerificationReport
22
from administration.utils import id_generator
23
from app.views import UploadMateriHTML, add_rating_materi
24
from authentication.models import User
25
26
27
from digipus.settings import TIME_ZONE
from .models import (Category, Comment, DownloadStatistics, Materi, Like, 
                    Rating, ReqMaterial, RatingContributor, ViewStatistics)
28
29
30

from .views import (DaftarKatalog, DashboardKontributorView, DetailMateri,
                    ProfilKontributorView, SuksesLoginAdminView,
31
                    SuksesLoginKontributorView, SuntingProfilView,
32
33
                    ProfilAdminView, PostsView, SuntingProfilAdminView, 
                    RevisiMateriView, ReqMateriView, KatalogPerKontributorView,
34
                    UploadMateriView, UploadMateriExcelView)
35
from app.forms import SuntingProfilForm
36
from app.utils.fileManagementUtil import get_random_filename, remove_image_exifdata
37

38
ERROR_403_MESSAGE = 'Kamu harus login untuk mengakses halaman ini'
Saul Andre's avatar
Saul Andre committed
39

40
41
42
43
44
45
46
47
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


48
49
50
51

class DaftarKatalogTest(TestCase):
    def test_daftar_katalog_url_exist(self):
        url = "/"
52
53
        response = Client().get(f"{url}")
        self.assertEqual(response.status_code, 200)
54
55

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

59
    def test_daftar_katalog_using_daftar_katalog_func(self):
60
        found = resolve("/")
61
62
63
64
        self.assertEqual(found.func.__name__, DaftarKatalog.as_view().__name__)

    def test_fields(self):
        materi = Materi()
65
66
67
        materi.title = "tes"
        materi.cover = "https://cache.umusic.com/_sites/billieeilish/v2/images/pic-red.jpg"
        materi.author = "input"
68
69
        materi.save()

70
71
72
        resp = Materi.objects.get(id=materi.id)
        self.assertEqual(resp, materi)

73
74
75
class DaftarKatalogPerKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
76

77
78
79
80
        self.contributor_credential = {
                "email": "kontributor@gov.id",
                "password": "passwordtest"
            }
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
81

82
83
84
85
86
87
88
89
90
        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)
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
91

92
93
94
95
96
97
98
99
100
101
102
103
104
        self.cover = SimpleUploadedFile(
            "Cherprang_Areekul40_nJM9dGt.jpg", b"Test file")
        self.content = SimpleUploadedFile("Bahan_PA_RKK.pdf", b"Test file")

        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="APPROVE", cover=self.cover, content=self.content).save()
        Materi(title="Materi 2", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 2",
               status="APPROVE", cover=self.cover, content=self.content).save()
        Materi(title="Materi 3", author="Agas", uploader=self.contributor2,
               publisher="Kelas SC", descriptions="Deskripsi Materi 3",
               status="APPROVE", cover=self.cover, content=self.content).save()
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
105

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

108
109
110
111
112
113
    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
114
        self.assertTemplateUsed(response, "app/katalog_kontri.html")
115
116
117
118
119
120
121

    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
122
123

        list_materi = Materi.objects.filter(uploader=self.contributor)
124
        data = response.context_data['materi_list']
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
125
        self.assertEqual(len(list_materi), len(data))
126

127

Saul Andre's avatar
Saul Andre committed
128
class DetailMateriTest(TestCase):
129
    def setUp(self):
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
        self.client = Client()
        self.admin_credential = {
            "email": "admin@gov.id",
            "password": "passwordtest"
        }
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": "passwordtest"
        }
        self.anonymous_credential = {
            "email": "anonymous@gov.id",
            "password": "passwordtest"
        }
        self.admin = get_user_model().objects.create_user(
            **self.admin_credential, name="Admin", is_admin=True)
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True)
        self.anonymous = get_user_model().objects.create_user(
            **self.anonymous_credential, name="Anonymous"
        )
150
        self.cover = SimpleUploadedFile(
151
152
            "ExampleCover921.jpg", b"Test file")
        self.content = SimpleUploadedFile("ExampleFile921.pdf", b"Test file")
153
154
155

        Materi(title="Materi 1", author="Agas", uploader=self.contributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
156
               status="APPROVE", cover=self.cover, content=self.content).save()
157
        self.materi1 = Materi.objects.first()
158
        self.url = "/materi/" + str(self.materi1.id) + "/"
159

160
161
162
163
164
165
166
167
168
169
        self.materi_with_published_date = Materi.objects.create(title="Materi 1", author="Agas", uploader=self.contributor,
                                                 publisher="Kelas SC", descriptions="Deskripsi Materi 1",
                                                 status="APPROVE", cover=self.cover, content=self.content,
                                                 date_modified=datetime.now(), date_created=datetime.now())
        self.materi_with_published_date_url = "/materi/" + str(self.materi_with_published_date.id) + "/"
        VerificationReport.objects.create(report='{"feedback": "Something", "kriteria": [{"title": "Kriteria 1", "status": true},' + \
            ' {"title": "Kriteria 2", "status": true}, {"title": "Kriteria 3", "status": true}]}', \
            timestamp="2020-10-09 06:21:33", status="Diterima", materi= self.materi_with_published_date, \
            user=self.materi_with_published_date.uploader)

170
    def test_detail_materi_url_exist(self):
171
        response = Client().get(self.url)
172
        self.assertEqual(response.status_code, 200)
173
174
175
        self.assertNotEqual(response.status_code, 404)

    def test_detail_materi_using_detail_materi_template(self):
176
        response = Client().get(self.url)
177
        self.assertTemplateUsed(response, 'app/detail_materi.html')
178

Saul Andre's avatar
Saul Andre committed
179
    def test_detail_materi_using_detail_materi_func(self):
180
        found = resolve(self.url)
Saul Andre's avatar
Saul Andre committed
181
        self.assertEqual(found.func.__name__, DetailMateri.as_view().__name__)
182

Saul Andre's avatar
Saul Andre committed
183
    def test_category_models_can_create_new_object(self):
184
185
        test = Category.objects.create(
            id="1", name="medis", description="kategori medis")
Saul Andre's avatar
Saul Andre committed
186
187
188
189
190
        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
191

Saul Andre's avatar
Saul Andre committed
192
    def test_comment_models_can_create_new_object(self):
193
        test = Comment.objects.create(
194
            username="saul", profile="121212", comment="232323")
Saul Andre's avatar
Saul Andre committed
195
196
197
198
199
        countData = Comment.objects.all().count()
        self.assertEqual(1, countData)
        self.assertNotEqual(0, countData)
        self.assertEqual(test.__str__(), "saul")
        self.assertNotEqual(test.__str__(), "userlain")
200

201
    def test_post_blank_comment(self):
202
203
204
205
        url = self.url
        self.client.login(**self.anonymous_credential)
        response = self.client.post(url, {"comment": ""})
        self.assertIn("error_message", response.context)
206
207
        self.assertIn("Anda belum menuliskan komentar",
                      response.context["error_message"])
208
209
210
211
212

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

216
    def test_comment_by_admin(self):
217
218
219
220
        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)
221
222
223
        self.assertContains(response, "Admin")

    def test_comment_by_kontributor(self):
224
225
        url = self.url
        self.client.login(**self.contributor_credential)
226
227
        self.client.post(
            url, {"comment": "This is new comment by Contributor"})
228
229
        response = self.client.get(url)
        self.assertContains(response, "Kontributor")
230
231

    def test_comment_by_anonymous(self):
232
233
234
235
236
        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)
237
        self.assertContains(response, "Anonymous")
238

239
    def test_detail_materi_contains_form_comment(self):
240
        response = self.client.get(self.url)
241
        self.assertContains(response, "Beri komentar...")
242

243
244
245
    def test_delete_comments_by_admin(self):
        url = self.url
        self.client.post(url, {"comment": "This is new comment by Anonymous"})
246
247
        deleteURL = "/delete/" + str(self.materi1.id) + "/" + str(
            Comment.objects.get(comment="This is new comment by Anonymous").id)
248
        self.client.get(deleteURL)
249
250
        self.assertEqual(Comment.objects.all().filter(
            comment="This is new comment by Anonymous").count(), 0)
251

252
    def test_tombol_citasiAPA(self):
253
        response = self.client.get(self.url)
254
        self.assertContains(response, 'Citate APA')
255

256
    def test_hasil_citasi_APA_materi_has_no_published_date(self):
257
        response = self.client.get(self.url)
258
259
260
261
262
        expected = self.materi1.author + \
                   ' . (n.d) . ' + \
                   self.materi1.title + \
                   ' . ' + \
                   self.materi1.publisher
263
        self.assertIn(expected,
264
                      response.context["citationAPA"])
265

266
267
268
269
270
271
272
273
274
275
276
277
    def test_hasil_citasi_APA_materi_has_published_date(self):
        response = self.client.get(self.materi_with_published_date_url)
        published_date = self.materi_with_published_date.published_date.strftime('%Y-%m-%d %H:%M')
        expected = self.materi_with_published_date.author + \
                   ' . ('  + \
                   published_date + \
                   ') . ' + \
                   self.materi_with_published_date.title + \
                   ' . ' + \
                   self.materi_with_published_date.publisher
        self.assertIn(expected,
                      response.context["citationAPA"])
278
279

class PostsViewTest(TestCase):
280

281
282
283
284
    @classmethod
    def generate_posts_data(cls, user):
        POST_COUNT = 3
        COMMENTS_COUNT_PER_POST = [1, 0, 3]
285
        LIKES_COUNT_PER_POST = [5, 4, 2]
286
287
288
289
290
291
292

        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 = {}
293
        for i in range(POST_COUNT):
294
295
296
297
298
299
300
301
302
303
304
305
            post = Materi.objects.create(
                uploader=user,
                cover=sample_file,
                content=sample_file,
            )
            post.categories.add(sample_category)

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

306
307
308
309
310
311
312
            for j in range (LIKES_COUNT_PER_POST[i]):
                Like.objects.create(
                    timestamp=datetime.now(), 
                    materi=post, 
                    session_id=("dummysession-" + str(i) + '-' + str(j))
                )
            
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
        for i, post_id in enumerate(post_comment_group_dict):
            post = post_comment_group_dict[post_id]["data"]

            for _ in range(COMMENTS_COUNT_PER_POST[i]):
                comment = Comment.objects.create(materi=post)
                post_comment_group_dict[post_id]["comments"].append(comment)

            # order by latest (-timestamp)
            post_comment_group_dict[post_id]["comments"].reverse()

        return post_comment_group_dict

    @classmethod
    def setUpTestData(cls):
        cls.url = '/posts/'
        cls.user_credentials = {
            "email": "user@email.com",
            "password": "justpass"
        }
        cls.user = User.objects.create_user(**cls.user_credentials, is_contributor=True)
        cls.data = cls.generate_posts_data(cls.user)

    def _request_as_user(self):
        self.client.login(**self.user_credentials)
        return self.client.get(self.url)

    def test_url_resolves_to_posts_view(self):
340
        found = resolve(self.url)
341
        self.assertEqual(found.func.__name__, PostsView.as_view().__name__)
342

343
344
345
    def test_returns_200_on_authenticated_access(self):
        response = self._request_as_user()
        self.assertEqual(response.status_code, 200)
346

347
    def test_returns_403_on_unauthenticated_access(self):
348
        response = self.client.get(self.url)
349
        self.assertRaises(PermissionDenied)
350
        self.assertEqual(response.status_code, 403)
351

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

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
    def test_returns_correct_template(self):
        response = self._request_as_user()
        self.assertTemplateUsed(response, "user_uploaded_posts.html")

    def test_success_returns_correct_comment_post_groupings_by_context(self):
        post_comment_group_dict = self.data

        response = self._request_as_user()

        response_user = response.context_data["user"]
        self.assertEqual(response_user, self.user)

        response_data = response.context_data["posts"]
        actual_data = post_comment_group_dict
        self.assertDictEqual(response_data, actual_data)

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

        posts = list(self.data.keys())
        comments = {
            i: [comment.id for comment in self.data[post_id]["comments"]]
            for i, post_id in enumerate(posts)
        }

        self.assertRegex(
381
            str(response.content),
382
            rf'.*(<div id="post-{posts[2]}">)' + \
383
384
385
            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]}">)' + \
386
387
            rf'.*(<div id="post-{posts[1]}">)' + \
            rf'.*(<div id="post-{posts[0]}">)' + \
388
            rf'.*(<div id="post-{posts[0]}-comment-{comments[0][0]}">)'
389
390
        )

391
392
393
394
395
396
397
398
399
400
    def test_like_count_written_correctly_on_template(self):
        response = self._request_as_user()

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

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

402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
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)
424
        self.assertEqual(response.status_code, 200)
425
        self.assertTemplateUsed(response, expected_template_name)
426

427

428
429
class UploadPageTest(TestCase):
    def setUp(self):
430
        self.client = Client()
431
432
        self.user = User.objects._create_user(email="kontributor@gov.id",
                                              password="kontributor", is_contributor=True)
Steven Kusuman's avatar
Steven Kusuman committed
433
434
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
435
436
437

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

Steven Kusuman's avatar
Steven Kusuman committed
441
    def test_upload_page_url_is_exist(self):
442
        # Positive test
443
444
445
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        response = self.client.get("/unggah/")
446
        self.assertEqual(response.status_code, 200)
447
448
449

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

Steven Kusuman's avatar
Steven Kusuman committed
454
455
456
457
458
459
460
461
462
463
464
465
    def test_upload_page_url_admin_doesnt_exist(self):        
        self.client.login(email="admin@gov.id",
                          password="admin")
        response = self.client.get("/unggah/")
        self.assertEqual(response.status_code, 403)

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

466
467
468
    def test_upload_page_template(self):
        url = "/unggah/"
        self.client.login(email="kontributor@gov.id",
469
                          password="kontributor")
470
471
        response = self.client.get(url)
        expected_template_name = "unggah.html"
472
        self.assertTemplateUsed(response, expected_template_name)
473
474
475

    def test_upload_page_title(self):
        self.client.login(email="kontributor@gov.id",
476
                          password="kontributor")
477
478
479
480
481
482
483
484
485
486
        response = self.client.get("/unggah/")

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

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

    def test_upload_page_form_field(self):
        self.client.login(email="kontributor@gov.id",
487
                          password="kontributor")
488
489
490
491
492
493
494
        response = self.client.get("/unggah/")

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

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

496

497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
class UploadExcelPageTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects._create_user(email="kontributor@gov.id",
                                              password="kontributor", is_contributor=True)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return file_path, data_frame

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

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

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

        self.assertIn('Title', msg_text)

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

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

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

        self.assertIn('Author', msg_text)


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

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

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

        self.assertIn('Publisher', msg_text)

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

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

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

        self.assertIn('Kategori', msg_text)

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

        Category(name='Computer Science').save()
        Category(name='Machine Learning').save()
        Category(name='Deep Learning').save()

        field_lengths = {
            'title':50,
            'author':30,
            'publisher':30,
        }

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

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

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

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



695
696
697
698
class DashboardKontributorViewTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
699
                                                           password="kontributor")
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/dashboard/"
        self.view = DashboardKontributorView
        self.template_name = "dashboard.html"

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

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

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

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

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

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

754
755
756
757
        # Anonim
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
758

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

762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
class ProfilAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
                                                           password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/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
        self.client.login(email="admin@gov.id",
                          password="admin")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

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

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

800

801
802
803
804
class ProfilKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
805
                                                           password="kontributor")
806
807
808
809
810
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/profil/"
        self.view = ProfilKontributorView
        self.template_name = "profil.html"
811

812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
    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
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

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

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

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

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

860
861
862
863
        # Anonim
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)
864

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

868

869
870
871
872
class SuntingProfilTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
873
                                                           password="kontributor")
874
875
876
877
878
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/sunting/"
        self.view = SuntingProfilView
        self.template_name = "sunting.html"
879

880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
    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
        self.client.login(email="kontributor@gov.id",
                          password="kontributor")
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

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

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

915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
    def test_sunting_profile_access_anonymous(self):
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)

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

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


938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
class SuntingProfilAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
                                                           password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/sunting-admin/"
        self.view = SuntingProfilAdminView
        self.template_name = "sunting_admin.html"

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

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

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

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

984

985
986
987
988
class SuksesLoginKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id",
989
                                                           password="kontributor")
990
991
992
993
994
        self.admin = User.objects.create_admin(email="admin@gov.id",
                                               password="admin")
        self.url = "/sukses-kontributor/"
        self.view = SuksesLoginKontributorView
        self.template_name = "sukses_kontri.html"
995

996
997
998
999
1000
    def test_sukses_login_kontributor_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_sukses_login_kontributor_template(self):
For faster browsing, not all history is shown. View entire blame