Fakultas Ilmu Komputer UI

tests.py 84.6 KB
Newer Older
1001
        self.client.login(email="kontributor@gov.id", password="kontributor")
1002
1003
1004
1005
1006
1007
1008
1009
1010
        # 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
1011
        self.client.login(email="kontributor@gov.id", password="kontributor")
1012
1013
1014
1015
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
1016
1017
        self.client.logout()

1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
    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",
1032
            "instagram": "https://instagram.com/test_ig",
1033
1034
1035
1036
1037
1038
1039
1040
        }
        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)


1041
1042
1043
class SuntingProfilAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
1044
1045
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id", password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id", password="admin")
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
        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
1056
        self.client.login(email="admin@gov.id", password="admin")
1057
1058
1059
1060
1061
1062
1063
1064
        # 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
1065
        self.client.login(email="admin@gov.id", password="admin")
1066
1067
1068
1069
1070
1071
1072
1073
1074
        # 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
1075
        self.client.login(email="admin@gov.id", password="admin")
1076
1077
1078
1079
1080
1081
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

1082

1083
1084
1085
class SuksesLoginKontributorTest(TestCase):
    def setUp(self):
        self.client = Client()
1086
1087
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id", password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id", password="admin")
1088
1089
1090
        self.url = "/sukses-kontributor/"
        self.view = SuksesLoginKontributorView
        self.template_name = "sukses_kontri.html"
1091

1092
1093
1094
1095
1096
1097
    def test_sukses_login_kontributor_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_sukses_login_kontributor_template(self):
        # Login
1098
        self.client.login(email="kontributor@gov.id", password="kontributor")
1099
1100
1101
1102
1103
1104
1105
1106
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_sukses_login_kontributor_url(self):
        # Login
1107
        self.client.login(email="kontributor@gov.id", password="kontributor")
1108
1109
1110
1111
1112
1113
1114
1115
1116
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

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

1124

1125
1126
1127
class SuksesLoginAdminTest(TestCase):
    def setUp(self):
        self.client = Client()
1128
1129
        self.kontributor = User.objects.create_contributor(email="kontributor@gov.id", password="kontributor")
        self.admin = User.objects.create_admin(email="admin@gov.id", password="admin")
1130
1131
1132
        self.url = "/sukses-admin/"
        self.view = SuksesLoginAdminView
        self.template_name = "sukses_admin.html"
1133

1134
1135
1136
1137
1138
1139
    def test_sukses_login_admin_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, self.view.as_view().__name__)

    def test_sukses_login_admin_template(self):
        # Login
1140
        self.client.login(email="admin@gov.id", password="admin")
1141
1142
1143
1144
1145
1146
1147
1148
        # Test
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, self.template_name)
        # Logout
        self.client.logout()

    def test_sukses_login_admin_url(self):
        # Login
1149
        self.client.login(email="admin@gov.id", password="admin")
1150
1151
1152
1153
1154
1155
1156
1157
1158
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()

    def test_sukses_login_admin_access(self):
        # Kontributor
        # Login
1159
        self.client.login(email="admin@gov.id", password="admin")
1160
1161
1162
1163
1164
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
        self.client.logout()
1165
1166
1167
1168


class LikeMateriTest(TestCase):
    def setUp(self):
1169
        self.contributor_credential = {"email": "kontributor@gov.id", "password": id_generator()}
1170
1171
1172
1173
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
1174
        self.url_like = "/materi/like/"
1175
        content = b"Test file"
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
        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()
1188
        self.materi1 = Materi.objects.first()
1189
        self.url_materi = f"/materi/{self.materi1.id}/"
1190
1191
1192
1193
1194
1195
1196
1197

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

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

1201
        # Like a materi
1202
1203
1204
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
1205
        payload = {"materi_id": materi_id, "session_id": session_id}
1206
        ajax_response = Client().post(self.url_like, payload)
1207
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
1208
1209
1210
1211
        self.assertEqual(num_of_likes, 1)

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

1215
        # Like a materi
1216
1217
1218
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
1219
        payload = {"materi_id": materi_id, "session_id": session_id}
1220
        ajax_response = Client().post(self.url_like, payload)
1221
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
1222
1223
        self.assertEqual(num_of_likes, 1)

1224
        # Unlike a materi
1225
1226
1227
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
1228
        payload = {"materi_id": materi_id, "session_id": session_id}
1229
        ajax_response = Client().post(self.url_like, payload)
1230
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
1231
1232
1233
1234
        self.assertEqual(num_of_likes, 0)

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

1238
        # Client 1 like a materi
1239
1240
1241
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
1242
        payload = {"materi_id": materi_id, "session_id": session_id}
1243
        ajax_response = Client().post(self.url_like, payload)
1244
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
1245
1246
        self.assertEqual(num_of_likes, 1)

1247
        # Client 2 like a materi
1248
1249
1250
        response = Client().get(self.url_materi)
        session_id = response.context["session_id"]
        materi_id = response.context["materi_data"].id
1251
        payload = {"materi_id": materi_id, "session_id": session_id}
1252
        ajax_response = Client().post(self.url_like, payload)
1253
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
1254
1255
1256
1257
        self.assertEqual(num_of_likes, 2)

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

1261
        # missing session id
1262
1263
1264
        response = self.client.get(self.url_materi)
        materi_id = response.context["materi_data"].id
        payload = {
1265
            "materi_id": materi_id,
1266
1267
        }
        ajax_response = Client().post(self.url_like, payload)
1268
        ajax_response = json.loads(ajax_response.content)
1269
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
1270
1271
        self.assertEqual(num_of_likes, 0)
        self.assertEqual(ajax_response.get("success", None), False)
1272
1273

        # missing materi id
1274
1275
        response = self.client.get(self.url_materi)
        session_id = response.context["session_id"]
1276
        payload = {"session_id": session_id}
1277
        ajax_response = Client().post(self.url_like, payload)
1278
        ajax_response = json.loads(ajax_response.content)
1279
        num_of_likes = Like.objects.filter(materi=self.materi1).count()
1280
1281
1282
1283
1284
1285
        self.assertEqual(num_of_likes, 0)
        self.assertEqual(ajax_response.get("success", None), False)


class ViewMateriStatissticsTest(TestCase):
    def setUp(self):
1286
        self.contributor_credential = {"email": "kontributor@gov.id", "password": id_generator()}
1287
1288
1289
1290
1291
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
        content = b"Test file"
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
        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()
1304
1305
1306
        self.materi1 = Materi.objects.first()
        self.url = f"/materi/{self.materi1.id}/view"

1307
    # Test single view
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
    def test_count_one_materi_view(self):
        response = self.client.get(self.url)
        num_of_views = self.materi1.baca.all().count()
        self.assertEqual(num_of_views, 1)

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

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

1323

1324
1325
class DownloadMateriStatissticsTest(TestCase):
    def setUp(self):
1326
        self.contributor_credential = {"email": "kontributor@gov.id", "password": id_generator()}
1327
1328
1329
1330
1331
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
        content = b"Test file"
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
        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()
1344
1345
1346
        self.materi1 = Materi.objects.first()
        self.url = f"/materi/{self.materi1.id}/unduh"

1347
    # Test single download
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
    def test_count_one_materi_download(self):
        response = self.client.get(self.url)
        num_of_downloads = self.materi1.unduh.all().count()
        self.assertEqual(num_of_downloads, 1)

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

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

1363

1364
1365
1366
1367
1368
1369
class RevisiMateriTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.view = RevisiMateriView
        self.template_name = "revisi.html"

1370
        self.contributor_credential = {"email": "kontributor@gov.id", "password": id_generator()}
1371
1372
1373
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
        self.cover = SimpleUploadedFile("cover.jpg", b"Test file")
        self.content = SimpleUploadedFile("content.txt", b"Test file")
        Materi(
            title="Materi 1",
            author="Agas",
            uploader=self.contributor,
            publisher="Kelas SC",
            descriptions="Deskripsi Materi 1",
            status="REVISION",
            cover=self.cover,
            content=self.content,
        ).save()
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419

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

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

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

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

    def test_revisi_materi_access(self):
        # Kontributor
        # Login
        self.client.login(**self.contributor_credential)
        # Test
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        # Logout
1420
        self.client.logout()
1421
1422


1423
1424
1425
1426
1427
1428
1429
class NameBannerFunctionalTest(LiveServerTestCase):
    selenium = None

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        options = Options()
1430
        options.add_argument("--headless")
1431
1432
1433
1434
1435
1436
        options.add_argument("start-maximized")
        options.add_argument("disable-infobars")
        options.add_argument("--disable-extensions")
        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--no-sandbox")
        options.add_argument("--no-sandbox")
1437
        cls.selenium = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options)
1438
        cls.selenium.implicitly_wait(10)
1439

1440
1441
1442
1443
1444
1445
    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        super().tearDownClass()

    def test_list_todo_available(self):
1446
        self.selenium.get(f"{self.live_server_url}")
1447
        try:
1448
            self.assertIn("Digipus", self.selenium.find_element_by_css_selector("nav.katalog-navbar").text)
1449
        except NoSuchElementException:
1450
            self.fail("No such element: Katalog Brand")
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461


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

    def test_command_output_with_given_num_of_materi(self):
        for num_of_materi in self.material_numbers:
            call_command("generatedummy", num_of_materi, stdout=self.stdout)
1462
            self.assertIn(f"Successfully created {num_of_materi} materi", self.stdout.getvalue())
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482

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

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


class RemoveDummyCommandTest(TestCase):
    def test_calling_remove_dummy_command_should_remove_generated_dummy_objects(self):
        stdout = StringIO()
        call_command("generatedummy", 50)

        call_command("removedummy", stdout=stdout)

Steven Kusuman's avatar
Steven Kusuman committed
1483
        self.assertIn("Successfully remove all dummy object", stdout.getvalue())
1484
1485
1486
1487
1488
1489
1490
1491
1492
        self.assertEqual(User.objects.count(), 0)
        self.assertEqual(Category.objects.count(), 0)
        self.assertEqual(Materi.objects.count(), 0)
        self.assertEqual(VerificationSetting.objects.count(), 0)
        self.assertEqual(VerificationReport.objects.count(), 0)


class RatingMateriTest(TestCase):
    def setUp(self):
1493
1494
1495
        self.contributor_credential = {"email": "kontributor@gov.id", "password": id_generator()}
        self.user_one_credential = {"email": "user_one@user.id", "password": id_generator()}
        self.user_two_credential = {"email": "user_two@user.id", "password": id_generator()}
1496
1497
1498
1499
1500
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.user_one = get_user_model().objects.create_user(**self.user_one_credential, name="User One")
        self.user_two = get_user_model().objects.create_user(**self.user_two_credential, name="User Two")
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
        self.cover = SimpleUploadedFile("cover.jpg", b"Test file")
        self.content = SimpleUploadedFile("content.txt", b"Test file")
        Materi(
            title="Materi 1",
            author="Agas",
            uploader=self.contributor,
            publisher="Kelas SC",
            descriptions="Deskripsi Materi 1",
            status="PENDING",
            cover=self.cover,
            content=self.content,
        ).save()
        Materi(
            title="Materi Dua",
            author="Author",
            uploader=self.contributor,
            publisher="Publisher",
            descriptions="Deskripsi Materi Dua",
            status="APPROVE",
            cover=self.cover,
            content=self.content,
        ).save()
1523
1524
        self.materi1 = Materi.objects.all()[0]
        self.materi2 = Materi.objects.all()[1]
1525
1526
        self.url_rate = "/materi/rate/"
        self.url_materi = "/materi/{}/".format(self.materi1.id)
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538

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

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

    def test_rating_model_should_not_be_created_with_rating_less_than_1(self):
        with self.assertRaises(ValidationError) as context:
            Rating(materi=self.materi1, user=self.user_one, score=0).save()
1544
        self.assertTrue("Rating score must be integer between 1-5" in str(context.exception))
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569

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

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

    def test_two_rating_should_not_have_same_user_and_materi(self):
        with self.assertRaises(IntegrityError) as context:
            Rating(materi=self.materi1, user=self.user_one, score=1).save()
            Rating(materi=self.materi1, user=self.user_one, score=2).save()
1570
        self.assertTrue("already exists" in str(context.exception))
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582

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

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

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

1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
    def test_rating_materi_url_use_add_rating_materi_function(self):
        found = resolve(self.url_rate)
        self.assertEqual(found.func, add_rating_materi)

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

    def test_rating_materi_post_not_authenticated_should_return_403_forbidden(self):
1596
        response = self.client.post(self.url_rate, {"materi_id": 1, "rating_score": 5})
1597
1598
1599
1600
1601
1602
        response_json = json.loads(response.content)
        self.assertEqual(response_json.get("success", None), False)
        self.assertEqual(response_json.get("msg", None), "Forbidden")
        self.assertEqual(response.status_code, 403)

    def test_rating_materi_not_authenticated_post_wrong_param_should_return_403_forbidden(self):
1603
        for data in [{}, {"materi_id": 1}, {"rating_score": 1}, {"rating_score": "STRING", "materi_id": "STRING"}]:
1604
1605
1606
1607
1608
1609
1610
1611
            response = self.client.post(self.url_rate, data)
            response_json = json.loads(response.content)
            self.assertEqual(response_json.get("success", None), False)
            self.assertEqual(response_json.get("msg", None), "Forbidden")
            self.assertEqual(response.status_code, 403)

    def test_rating_materi_authenticated_post_missing_param(self):
        self.client.login(**self.user_one_credential)
1612
        for data in [{"rating_score": 1}, {"materi_id": 1}, {}]:
1613
1614
1615
1616
1617
1618
1619
1620
            response = self.client.post(self.url_rate, data)
            response_json = json.loads(response.content)
            self.assertEqual(response_json.get("success", None), False)
            self.assertEqual(response_json.get("msg", None), "Missing param")
            self.assertEqual(response.status_code, 422)

    def test_rating_materi_authenticated_materi_id_doesnt_exist_should_return_422(self):
        self.client.login(**self.user_one_credential)
1621
        response = self.client.post(self.url_rate, {"materi_id": 123456, "rating_score": 5})
1622
1623
1624
1625
1626
1627
1628
        response_json = json.loads(response.content)
        self.assertEqual(response_json.get("success", None), False)
        self.assertEqual(response_json.get("msg", None), "Materi does not exist")
        self.assertEqual(response.status_code, 422)

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

1635
        response = self.client.post(self.url_rate, {"materi_id": 1, "rating_score": "STRING"})
1636
1637
1638
1639
1640
1641
1642
1643
1644
        response_json = json.loads(response.content)
        self.assertEqual(response_json.get("success", None), False)
        self.assertEqual(response_json.get("msg", None), "rating_score must be an integer")
        self.assertEqual(response.status_code, 422)

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

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

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

    def test_user_authenticated_visit_unrated_should_get_0_materi_rating_score_context(self):
        self.client.login(**self.user_one_credential)
        response = self.client.get(self.url_materi)
1672
        self.assertEqual(0, response.context.get("materi_rating_score"))
1673
1674
1675

    def test_user_not_authenticated_visit_unrated_should_get_0_materi_rating_score_context(self):
        response = self.client.get(self.url_materi)
1676
        self.assertEqual(0, response.context.get("materi_rating_score"))
1677
1678
1679
1680
1681

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

1684
1685
1686
1687

class fileManagementUtilTest(TestCase):
    def setUp(self):
        self.filename = "image_with_exif_data.gif"
1688
        self.file_content = open(settings.BASE_DIR + "/app/test_files/" + self.filename, "rb").read()
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708

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

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

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

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

            self.assertTrue(len(sanitized_img) < len(self.file_content))
1709
1710
            self.assertTrue(b"<exif:" not in sanitized_img)

Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1711
1712
1713
1714

class RequestMateriTest(TestCase):
    def setUp(self):
        self.client = Client()
1715
1716
1717
1718
        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)
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1719
        self.contributor = get_user_model().objects.create_user(
1720
            **self.contributor_credential, name="Kontributor", is_contributor=True
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1721
        )
1722
        self.anonymous = get_user_model().objects.create_user(**self.anonymous_credential, name="Anonymous")
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
        self.url = "/req-materi/"
        self.template_name = "req_materi.html"

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

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

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

        self.assertEqual(response.status_code, 302)
1740
        self.assertEqual(response["location"], "/login/")
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750

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

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

1751
        response = self.client.post(self.url, data={"title": "Requested Material"})
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1752
1753
1754
        self.assertEqual(ReqMaterial.objects.count(), 1)

        new_material_request = ReqMaterial.objects.first()
1755
        self.assertEqual(new_material_request.title, "Requested Material")
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1756

1757
        self.assertIn("Permintaan materi berhasil dikirimkan", response.content.decode())
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1758
1759
1760
1761
1762
1763
1764
1765
        self.client.logout()

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

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

1766
        self.assertIn("Missing parameter", response.content.decode())
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
1767
        self.client.logout()
1768
1769
1770
1771


class RatingContributorTest(TransactionTestCase):
    def setUp(self):
1772
        self.contributor_credential = {"email": "kontributor@gov.id", "password": id_generator()}
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )

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

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

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

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

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

1805

1806
1807
class UserDownloadHistoryTest(TestCase):
    def setUp(self):
1808
1809
1810
1811
1812
        self.user1_credential = {"email": "anonim1@gov.id", "password": id_generator()}
        self.user1_anonim = get_user_model().objects.create_user(**self.user1_credential, name="Anonim1")
        self.user2_credential = {"email": "anonim2@gov.id", "password": id_generator()}
        self.user2_anonim = get_user_model().objects.create_user(**self.user2_credential, name="Anonim2")
        self.contributor_credential = {"email": "kontributor@gov.id", "password": id_generator()}
1813
1814
1815
1816
1817
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
        content = b"Test file"
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
        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()
1830
1831
1832
        self.materi1 = Materi.objects.first()
        self.download_url = f"/materi/{self.materi1.id}/unduh"
        self.history_url = "/download-history/"
1833

1834
1835
1836
1837
    def test_multiple_insert_download_statistic_with_user(self):
        DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
1838

1839
1840
1841
        DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 2)
1842

1843
1844
1845
1846
    def test_download_statistics_bound_to_specific_user(self):
        DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
1847

1848
1849
1850
        DownloadStatistics(materi=self.materi1).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
1851

1852
1853
1854
1855
1856
1857
1858
1859
1860
        DownloadStatistics(materi=self.materi1, downloader=self.user2_anonim).save()
        user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        user2_num_of_downloads = self.user2_anonim.riwayat_unduh.all().count()
        self.assertEqual(user1_num_of_downloads, 1)
        self.assertEqual(user2_num_of_downloads, 1)

    def test_registered_user_download(self):
        # Login
        self.client.login(**self.user1_credential)
1861

1862
1863
1864
        self.client.get(self.download_url)
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
1865

1866
1867
        # Logout
        self.client.logout()
1868

1869
1870
    def test_unregistered_user_download(self):
        self.client.get(self.download_url)
1871
1872
        downloaded_materi = self.client.session["downloaded_materi"]
        num_of_downloads = DownloadStatistics.objects.filter(pk__in=downloaded_materi).count()
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
        self.assertEqual(num_of_downloads, 1)

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

        self.client.get(self.download_url)
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 2)
1885

1886
1887
        # Logout
        self.client.logout()
1888

1889
1890
    def test_unregistered_user_multiple_download(self):
        self.client.get(self.download_url)
1891
1892
        downloaded_materi = self.client.session["downloaded_materi"]
        num_of_downloads = DownloadStatistics.objects.filter(pk__in=downloaded_materi).count()
1893
1894
1895
        self.assertEqual(num_of_downloads, 1)

        self.client.get(self.download_url)
1896
1897
        downloaded_materi = self.client.session["downloaded_materi"]
        num_of_downloads = DownloadStatistics.objects.filter(pk__in=downloaded_materi).count()
1898
        self.assertEqual(num_of_downloads, 2)
1899

1900
1901
1902
    def test_registered_user_doesnt_use_session_when_download(self):
        # Login
        self.client.login(**self.user1_credential)
1903

1904
        self.client.get(self.download_url)
1905
1906
        self.assertFalse("downloaded_materi" in self.client.session)

1907
1908
        # Logout
        self.client.logout()
1909

1910
1911
1912
1913
1914
1915
    def test_download_history_bound_to_specific_user(self):
        # Login Anonym 1
        self.client.login(**self.user1_credential)
        self.client.get(self.download_url)
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
1916

1917
1918
        # Logout Anonym 1
        self.client.logout()
1919
1920

        # Unregistered User download
1921
1922
        self.client.get(self.download_url)
        user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
1923
1924
        downloaded_materi = self.client.session["downloaded_materi"]
        guest_num_of_downloads = DownloadStatistics.objects.filter(pk__in=downloaded_materi).count()
1925
1926
        self.assertEqual(user1_num_of_downloads, 1)
        self.assertEqual(guest_num_of_downloads, 1)
1927
1928

        # Login Anonym 2
1929
1930
1931
1932
1933
1934
1935
        self.client.login(**self.user2_credential)
        self.client.get(self.download_url)
        user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        user2_num_of_downloads = self.user2_anonim.riwayat_unduh.all().count()
        self.assertEqual(user1_num_of_downloads, 1)
        self.assertEqual(guest_num_of_downloads, 1)
        self.assertEqual(user2_num_of_downloads, 1)
1936

1937
1938
1939
        # Logout Anonym 2
        self.client.logout()

1940

1941
1942
class DownloadHistoryViewTest(TestCase):
    def setUp(self):
1943
1944
1945
        self.user_credential = {"email": "anonim1@gov.id", "password": id_generator()}
        self.user_anonim = get_user_model().objects.create_user(**self.user_credential, name="Anonim")
        self.contributor_credential = {"email": "kontributor@gov.id", "password": id_generator()}
1946
1947
1948
1949
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
1950

1951
1952
        content1 = b"Test file"
        content2 = b"File Test"
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980

        self.cover1 = SimpleUploadedFile("cover1.jpg", content1)
        self.content1 = SimpleUploadedFile("content1.txt", content1)

        self.cover2 = SimpleUploadedFile("cover2.jpg", content2)
        self.content2 = SimpleUploadedFile("content2.txt", content2)

        self.materi1 = Materi.objects.create(
            title="Materi 1",
            author="Agas",
            uploader=self.contributor,
            publisher="Kelas SC",
            descriptions="Deskripsi Materi 1",
            status="PENDING",
            cover=self.cover1,
            content=self.content1,
        )
        self.materi2 = Materi.objects.create(
            title="Materi 2",
            author="Danin",
            uploader=self.contributor,
            publisher="Kelas DDP",
            descriptions="Deskripsi Materi 2",
            status="PENDING",
            cover=self.cover2,
            content=self.content2,
        )

1981
1982
1983
        self.download_url1 = f"/materi/{self.materi1.id}/unduh"
        self.download_url2 = f"/materi/{self.materi2.id}/unduh"
        self.history_url = "/download-history/"
1984

1985
1986
1987
1988
1989
1990
        # Login
        self.client.login(**self.user_credential)

    def tearDown(self):
        # Logout
        self.client.logout()
1991

1992
1993
1994
    def test_allow_registered_user(self):
        response = self.client.get(self.history_url)
        self.assertEqual(response.status_code, 200)
1995

1996
    def test_allow_unregistered_user(self):
1997
        # Forced Logout
1998
        self.client.logout()
1999

2000
        response = self.client.get(self.history_url)
For faster browsing, not all history is shown. View entire blame