Fakultas Ilmu Komputer UI

tests.py 119 KB
Newer Older
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
        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)
2013
        self.assertEqual(response['location'], '/login/')
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023

    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)

2024
2025
2026
2027
        response = self.client.post(self.url,
                         data={
                             'title': 'Requested Material'
                         })
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
2028
2029
2030
        self.assertEqual(ReqMaterial.objects.count(), 1)

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

2033
        self.assertIn('Permintaan materi berhasil dikirimkan', response.content.decode())
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
2034
2035
2036
2037
2038
2039
2040
2041
        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)

2042
        self.assertIn('Missing parameter', response.content.decode())
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
2043
        self.client.logout()
2044
2045
2046
2047


class RatingContributorTest(TransactionTestCase):
    def setUp(self):
2048
2049
2050
2051
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
        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())
2083

2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
    def test_average_rating_score_empty(self):
        url = f"/profil/{self.contributor.email}/"
        response = self.client.get(url)
        self.assertTemplateUsed(response=response, template_name="app/katalog_kontri.html")
        self.assertContains(response=response, text="Rating: 0", count=1)
        self.assertContains(response=response, text="oleh: 0 orang", count=1)

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

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

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

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

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

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

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


2147
2148
class UserDownloadHistoryTest(TestCase):
    def setUp(self):
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
        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()
        }
2165
2166
2167
2168
2169
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
        content = b"Test file"
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
        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()
2181
2182
2183
        self.materi1 = Materi.objects.first()
        self.download_url = f"/materi/{self.materi1.id}/unduh"
        self.history_url = "/download-history/"
2184
	
2185
2186
2187
2188
    def test_multiple_insert_download_statistic_with_user(self):
        DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
2189
		
2190
2191
2192
        DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 2)
2193
		
2194
2195
2196
2197
    def test_download_statistics_bound_to_specific_user(self):
        DownloadStatistics(materi=self.materi1, downloader=self.user1_anonim).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
2198
		
2199
2200
2201
        DownloadStatistics(materi=self.materi1).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
2202
		
2203
2204
2205
2206
2207
2208
2209
2210
2211
        DownloadStatistics(materi=self.materi1, downloader=self.user2_anonim).save()
        user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        user2_num_of_downloads = self.user2_anonim.riwayat_unduh.all().count()
        self.assertEqual(user1_num_of_downloads, 1)
        self.assertEqual(user2_num_of_downloads, 1)

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

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

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

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

class DownloadHistoryViewTest(TestCase):
    def setUp(self):
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
        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()
        }
2307
2308
2309
2310
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
2311
		
2312
2313
        content1 = b"Test file"
        content2 = b"File Test"
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
		
        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)
			   
2328
2329
2330
        self.download_url1 = f"/materi/{self.materi1.id}/unduh"
        self.download_url2 = f"/materi/{self.materi2.id}/unduh"
        self.history_url = "/download-history/"
2331
		
2332
2333
2334
2335
2336
2337
        # Login
        self.client.login(**self.user_credential)

    def tearDown(self):
        # Logout
        self.client.logout()
2338
		
2339
2340
2341
    def test_allow_registered_user(self):
        response = self.client.get(self.history_url)
        self.assertEqual(response.status_code, 200)
2342
	
2343
    def test_allow_unregistered_user(self):
2344
	    # Forced Logout
2345
        self.client.logout()
2346
		
2347
2348
2349
2350
2351
2352
2353
2354
2355
        response = self.client.get(self.history_url)
        self.assertEqual(response.status_code, 200)

    def test_download_history_using_correct_template(self):
        response = self.client.get(self.history_url)
        self.assertTemplateUsed(response, "download_history.html")

    def test_download_history_has_user_name(self):
        response = self.client.get(self.history_url)
2356
        resp_html = response.content.decode('utf8')
2357
        self.assertIn(self.user_anonim.name, resp_html)
2358
		
2359
2360
2361
2362
    def test_registered_user_download_history_correctly_displayed(self):
        self.client.get(self.download_url1)
        self.client.get(self.download_url2)
        self.client.get(self.download_url1)
2363
		
2364
        jkt_timezone = timezone(TIME_ZONE)
2365
		
2366
2367
        download_history = self.user_anonim.riwayat_unduh.all()
        response = self.client.get(self.history_url)
2368
        resp_html = response.content.decode('utf8')
2369
2370
2371
2372
        for riwayat in download_history:
            downloaded_materi = riwayat.materi
            self.assertIn(downloaded_materi.title, resp_html)
            self.assertIn(downloaded_materi.author, resp_html)
2373
			
2374
2375
            jkt_timestamp = riwayat.timestamp.astimezone(jkt_timezone)
            self.assertIn(jkt_timestamp.strftime("%d %B %Y %H:%M:%S"), resp_html)
2376
			
2377
2378
2379
2380
2381
2382
    def test_unregistered_user_download_history_correctly_displayed(self):
        self.client.logout()

        self.client.get(self.download_url1)
        self.client.get(self.download_url2)
        self.client.get(self.download_url1)
2383
		
2384
        jkt_timezone = timezone(TIME_ZONE)
2385
		
2386
        response = self.client.get(self.history_url)
2387
2388
        resp_html = response.content.decode('utf8')
        for riwayat_id in self.client.session['downloaded_materi']:
2389
2390
2391
2392
            riwayat = DownloadStatistics.objects.get(pk=riwayat_id)
            downloaded_materi = riwayat.materi
            self.assertIn(downloaded_materi.title, resp_html)
            self.assertIn(downloaded_materi.author, resp_html)
2393
			
2394
2395
            jkt_timestamp = riwayat.timestamp.astimezone(jkt_timezone)
            self.assertIn(jkt_timestamp.strftime("%d %B %Y %H:%M:%S"), resp_html)
2396
			
2397
2398
2399
2400
2401
2402
    def test_download_history_not_display_if_user_changed(self):
        self.client.get(self.download_url1)
        self.client.get(self.download_url2)
        self.client.get(self.download_url1)

        self.client.logout()
2403
		
2404
        jkt_timezone = timezone(TIME_ZONE)
2405
		
2406
2407
        download_history = self.user_anonim.riwayat_unduh.all()
        response = self.client.get(self.history_url)
2408
        resp_html = response.content.decode('utf8')
2409
2410
2411
2412
        for riwayat in download_history:
            downloaded_materi = riwayat.materi
            self.assertNotIn(downloaded_materi.title, resp_html)
            self.assertNotIn(downloaded_materi.author, resp_html)
2413
			
2414
2415
            jkt_timestamp = riwayat.timestamp.astimezone(jkt_timezone)
            self.assertNotIn(jkt_timestamp.strftime("%d %B %Y %H:%M:%S"), resp_html)
2416
			
2417
2418
2419
2420
2421
2422
    def test_unregistered_user_download_history_wont_be_saved_if_user_changes(self):
        self.client.logout()

        self.client.get(self.download_url1)
        self.client.get(self.download_url2)
        self.client.get(self.download_url1)
2423
		
2424
2425
2426
2427
        self.client.get(self.history_url)

        self.client.login(**self.user_credential)
        self.client.logout()
2428
2429
        self.assertFalse('downloaded_materi' in self.client.session)
			
2430
    def test_download_history_sorted_by_download_time(self):
2431
		# download with 1 second interval to differ download time
2432
2433
2434
2435
2436
2437
2438
        self.client.get(self.download_url1)
        sleep(1)
        self.client.get(self.download_url2)
        sleep(1)
        self.client.get(self.download_url1)
        sleep(1)
        self.client.get(self.download_url2)
2439
		
2440
        response = self.client.get(self.history_url)
2441
2442
        resp_html = response.content.decode('utf8')
		
2443
        table_html = ("<table" + resp_html.split("<table")[1]).split("</table>")[0] + "</table>"
2444
2445
        soup = BeautifulSoup(table_html, 'html.parser')
        histories_html = soup.find('tbody').find_all('tr')
2446
        prev_timestamp = None
2447
		
2448
2449
2450
2451
2452
2453
2454
        for riwayat_html in histories_html:
            materi_data = riwayat_html.find_all("td")
            date_format = "%d %B %Y %H:%M:%S"
            materi_timestamp = datetime.strptime(materi_data[2].get_text(), date_format)
            if prev_timestamp:
                self.assertTrue(prev_timestamp > materi_timestamp)
            prev_timestamp = materi_timestamp
2455
			
2456
2457
2458
    def test_no_history_display_message(self):
        no_history_msg = "Anda belum mengunduh materi. Silahkan unduh materi yang anda butuhkan"
        response = self.client.get(self.history_url)
2459
        resp_html = response.content.decode('utf8')
2460
2461
2462
2463
        self.assertIn(no_history_msg, resp_html)


class MateriModelTest(TestCase):
2464
    
2465
    def setUp(self):
2466
2467
2468
2469
2470
        self.contributor = User.objects.create( 
            email="kontributor@gov.id",
            password="passwordtest",
            name="kontributor",
            is_contributor=True
2471
2472
        )

2473
2474
        self.cover = SimpleUploadedFile(
            "ExampleCover221.jpg", b"Test file")
2475
2476
        self.content = SimpleUploadedFile("ExampleFile221.pdf", b"Test file")

2477
2478
2479
2480
        self.materi = 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())
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490

    def test_like_count_return_zero_when_there_is_no_like(self):
        self.assertEqual(0, self.materi.like_count)

    def test_like_count_return_right_value_when_there_is_like(self):
        Like.objects.create(timestamp=datetime.now(), materi=self.materi, session_id="dummysessionid1")
        self.assertEqual(1, self.materi.like_count)

        Like.objects.create(timestamp=datetime.now(), materi=self.materi, session_id="dummysessionid2")
        self.assertEqual(2, self.materi.like_count)
2491

2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
class MateriFavoriteTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.url = '/favorite/'
        cls.user_credentials = {
            "email": "user@email.com",
            "password": "justpass"
        }
        cls.user = User.objects.create_user(**cls.user_credentials, is_contributor=True)

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

    def test_url_resolves_to_favorite_view(self):
        found = resolve(self.url)
        self.assertEqual(found.func.__name__, MateriFavorite.as_view().__name__)

2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
class RandomizedMateriTest(TestCase):
    def setUp(self):
        self.contributor = User.objects.create(
            email="kontributor@gov.id", password="passwordtest", name="kontributor", is_contributor=True
        )

        self.cover = SimpleUploadedFile("ExampleCover221.jpg", b"Test file")
        self.content = SimpleUploadedFile("ExampleFile221.pdf", b"Test file")

        self.materi = Materi.objects.create(
            title="Materi 1",
            author="Nandhika",
            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 = Materi.objects.create(
            title="Materi 2",
            author="Prayoga",
            uploader=self.contributor,
            publisher="Kelas SC",
            descriptions="Deskripsi Materi 2",
            status="APPROVE",
            cover=self.cover,
            content=self.content,
            date_modified=datetime.now(),
            date_created=datetime.now(),
        )

    def test_randomized_materi_returns_200(self):
        response = Client().get("/?random=1")
        self.assertEqual(response.status_code, 200)

    def test_randomized_materi_remains_same_materi(self):
        response = Client().get("/?random=1")
        self.assertIn("Materi 1", response.content.decode())
        self.assertIn("Materi 2", response.content.decode())
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
    
class YearChoicesTest(TestCase):
    def test_release_year_contains_the_right_current_year(self):
        now = dt.date.today().year

        choices = year_choices()

        self.assertEqual((now, now), choices[-1])

    def test_min_release_year_is_2000(self):
        choices = year_choices()

Yaumi's avatar
Yaumi committed
2565
        self.assertEqual((2000, 2000), choices[0])
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681

TEST_IMAGE = '''
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9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P78BWmadmnNVKgqI0cOkiRtNrc9Zt9H
x9fK6iphs/keVflAoqpSHOzjh+8maL59yk83WzRa8G8OwzRxiHQIFOjJBXw7O8b0qV50K2H1tWf+
riCiHRbNFIUucYgoZu/Yqlz44iiXzh3EpJuE0uLKl57lNc/93wVjOyYyApeguwpElTOf9HH1YkSU
e0O72cC/b1DMK9/PGP5c97zaUGwXg01cjHMxcRwz0Cf8ePkAJ47U0eRvSLehtYM06pw+1OTauZje
wBG7mCTJEDqX3eCjvOXqxQGmTwXUmwlxmmdrpw+z0ybiHXnbYqasvDgbcGPJEvvsHKFzDp96Tgz3
cvjwMM/efsaBwZP0D39KabKEpgnbG3/wrvaU5psnHD/6mMF8jcqWwRgwpWOjKiLkQkOhv5+xsTLl
cpnR0WOUSiVEhLVKhbXXa7xcXqHyaoV6o0Hqd1MxUjqu7XYLMFkaNXtXYC09+R5UwbkYEcVaizFm
P/LWGsLJydMs3VvCWkP3gzxK7OKu7Bl81/tEhKmpKVhYWNCJiQkNglDDMKdhLpf1/0AQhDo+Pq5z
c3NKmqa6uLios7MXtFgsahRFGhUKHUS7KBQ0iiIdGhrS8+dndH5+XpMk0X8AMTVx/inpU4cAAAAl
dEVYdGNyZWF0ZS1kYXRlADIwMTAtMTItMjZUMTQ6NDk6MjErMDk6MDAHHBB1AAAAJXRFWHRtb2Rp
ZnktZGF0ZQAyMDEwLTEyLTI2VDE0OjQ5OjIxKzA5OjAwWK1mQQAAAABJRU5ErkJggg==
'''.strip()
class YTUrlVideoTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.contributor_credential = {"email": "kontributor@gov.id", "password": "passwordtest"}
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )

        self.setUpImage()
        self.content = SimpleUploadedFile("ExampleFile221.pdf", b"Test file")
        self.category = Category.objects.create(id="1", name="medis", description="kategori medis")
    
    @override_settings(MEDIA_ROOT=tempfile.gettempdir())
    def setUpImage(self):
        from django.core.files.uploadedfile import InMemoryUploadedFile
        from io import BytesIO
        self.cover = InMemoryUploadedFile(
            BytesIO(base64.b64decode(TEST_IMAGE)),
            field_name='tempfile',
            name='tempfile.png',
            content_type='image/png',
            size=len(TEST_IMAGE),
            charset='utf-8',
        )

    def test_yt_video_id_exists_in_Materi(self):
        materiTemp = Materi.objects.create()
        self.assertEqual(hasattr(materiTemp, 'yt_video_id'), True)

    def test_yt_video_id_exists_in_UploadMateri_page(self):
        self.client.login(**self.contributor_credential)
        response = self.client.get("/unggah/")
        html = response.content.decode("utf-8")
        self.assertIn('Youtube Video Id', html)

    def test_upload_materi_with_valid_yt_video_id(self):
        self.client.login(**self.contributor_credential)
        response = self.client.post(
            "/unggah/", data={"title":"Materi 1", "author":"Agas", "publisher":"Kelas SC", "release_year":"2000",
                                "descriptions":"Deskripsi Materi 1", 'categories':"1",
                                "cover":self.cover, "content":self.content,
                                "yt_video_id":"jNwz4L9MGVY"}
        )
        self.assertTrue(Materi.objects.get(title="Materi 1"))
    
    def test_upload_materi_with_invalid_yt_video_id(self):
        self.client.login(**self.contributor_credential)
        response = self.client.post(
            "/unggah/", data={"title":"Materi 2", "author":"Agas", "publisher":"Kelas SC", "release_year":"2000",
                                "descriptions":"Deskripsi Materi 1", 'categories':"1",
                                "cover":self.cover, "content":self.content,
                                "yt_video_id":"randomId"}
        )
        self.assertEqual(Materi.objects.filter(title="Materi 2").count(), 0)
    
    def test_detail_materi_has_video_if_yt_video_id_not_empty(self):
        self.test_upload_materi_with_valid_yt_video_id()
        pk = Materi.objects.get(title="Materi 1").pk
        response = self.client.get("/materi/"+str(pk)+"/")
        html = response.content.decode("utf-8")
        self.assertIn("Video", html)

    def test_detail_materi_has_no_video_if_yt_video_id_empty(self):
        self.client.login(**self.contributor_credential)
        response = self.client.post(
            "/unggah/", data={"title":"Materi 2", "author":"Agas", "publisher":"Kelas SC", "release_year":"2000",
                                "descriptions":"Deskripsi Materi 1", 'categories':"1",
                                "cover":self.cover, "content":self.content,}
        )
        pk = Materi.objects.get(title="Materi 2").pk
        response = self.client.get("/materi/"+str(pk)+"/")
        html = response.content.decode("utf-8")
        self.assertNotIn("Video", html)

Yaumi's avatar
Yaumi committed
2682
class ChangePasswordTest(TestCase):
Yaumi's avatar
Yaumi committed
2683
2684
2685
2686
2687
    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 = "/change-password/"
Yaumi's avatar
Yaumi committed
2688
        self.view = PasswordChangeViews
Yaumi's avatar
Yaumi committed
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
        self.template_name = "change-password.html"

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

    def test_change_password_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_change_password_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_change_password_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()

2723
    
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
class SeeRatedMateriByUser(TestCase):
    def setUp(self):
        self.client = Client()
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
        self.admin_credential = {
            "email": "admin@gov.id",
            "password": id_generator()
        }
        self.kontributor = User.objects.create_contributor(**self.contributor_credential)
        self.admin = User.objects.create_admin(**self.admin_credential)
        self.given_rating_url = "/given-rating/"

        self.cover = SimpleUploadedFile(
            "cover.jpg",
            b"Test file"
        )
        self.content = SimpleUploadedFile(
            "content.txt",
            b"Test file"
        )
        Materi(title="Materi 2", author="Agas", uploader=self.kontributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="PENDING", cover=self.cover, content=self.content).save()
        Materi(title="Materi 3", author="Agas", uploader=self.kontributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="PENDING", cover=self.cover, content=self.content).save()
        Materi(title="Materi 1", author="Agas", uploader=self.kontributor,
               publisher="Kelas SC", descriptions="Deskripsi Materi 1",
               status="PENDING", cover=self.cover, content=self.content).save()
        self.materi1 = Materi.objects.all()[0]
        self.materi2 = Materi.objects.all()[1]
        self.materi3 = Materi.objects.all()[2]
2759
        time.sleep(5)
2760
        self.rating_test_1 = Rating(materi=self.materi1, user=self.kontributor, score=5)
2761
        time.sleep(5)
2762
        self.rating_test_2 = Rating(materi=self.materi2, user=self.kontributor, score=4)
2763
        time.sleep(5)
2764
        self.rating_test_3 = Rating(materi=self.materi3, user=self.kontributor, score=3)
2765
        time.sleep(5)
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
        self.rating_test_4 = Rating(materi=self.materi3, user=self.admin, score=3)

        self.rating_test_1.save()
        self.rating_test_2.save()
        self.rating_test_3.save()
        self.rating_test_4.save()

    def test_authorize_template_used(self):
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.given_rating_url)
        self.assertTemplateUsed(response, "given-rating.html")

    def test_unauthorized_user_shouldnt_be_able_to_access_see_rating_page(self):
        response = self.client.get(self.given_rating_url)
        self.assertEqual(response.status_code, 403)
        self.assertTemplateUsed(response, "error_403.html")

    def test_authorized_should_be_able_to_access_given_rating_page(self):
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.given_rating_url)
        self.assertEqual(response.status_code, 200)

        self.client.login(**self.admin_credential)
        response = self.client.get(self.given_rating_url)
        self.assertEqual(response.status_code, 200)

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

        response = self.client.get(self.given_rating_url)
        self.assertIn(self.rating_test_1, response.context['rating_list'])
        self.assertIn(self.rating_test_2, response.context['rating_list'])
        self.assertIn(self.rating_test_3, response.context['rating_list'])

    def test_given_rating_page_should_not_show_others_rating(self):
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.given_rating_url)
        self.assertNotIn(self.rating_test_4, response.context['rating_list'])

    def test_given_rating_page_no_rating_should_display_message(self):
        user_credential = {"email": "user@mail.com", "password": id_generator()}
        User.objects.create_contributor(**user_credential)
        self.client.login(**user_credential)
        response = self.client.get(self.given_rating_url)
        self.assertEqual(len(response.context['rating_list']), 0)
        self.assertIn("Anda belum pernah memberikan rating ke materi", response.content.decode("utf-8"))
        self.assertNotIn(self.materi1.title, response.content.decode("utf-8"))

    def test_given_rating_page_order_should_give_default_parameter(self):
        # No parameters order_by_key = timestamp and order_by : ascending
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.given_rating_url)
        self.assertEqual(response.context['order_by'], 'dsc')
        self.assertEqual(response.context['order_by_key'], 'timestamp')

        # No order_by_key parameter, should default to timestamp
        response = self.client.get(self.given_rating_url + '?order=asc')
        self.assertEqual(response.context['order_by'], 'asc')
        self.assertEqual(response.context['order_by_key'], 'timestamp')

        # No order_by parameter, should default to asc
        response = self.client.get(self.given_rating_url + '?order_by_key=score')
        self.assertEqual(response.context['order_by'], 'dsc')
        self.assertEqual(response.context['order_by_key'], 'score')

        # INVALID PARAMETERS
        # Starts with negative
        response = self.client.get(self.given_rating_url + '?order_by_key=-score')
        self.assertEqual(response.context['order_by'], 'dsc')
        self.assertEqual(response.context['order_by_key'], 'score')

        # Invalid params
        response = self.client.get(self.given_rating_url + '?order_by_key=halohalohalo&order=haihaihaihai')
        self.assertEqual(response.context['order_by'], 'dsc')
        self.assertEqual(response.context['order_by_key'], 'timestamp')

    def test_given_rating_page_order_ascending_should_be_correct(self):
        self.client.login(**self.contributor_credential)
        response = self.client.get(self.given_rating_url + '?order_by_key=score&order=asc')

        # From Low to High
        # order key score
        self.assertEqual(response.context['order_by'], 'asc')
        self.assertEqual(response.context['order_by_key'], 'score')
        self.assertEqual(list(response.context['rating_list']),
                         [self.rating_test_3, self.rating_test_2, self.rating_test_1])
        # order key timestamp
        response = self.client.get(self.given_rating_url + '?order_by_key=timestamp&order=asc')
        self.assertEqual(response.context['order_by'], 'asc')
        self.assertEqual(response.context['order_by_key'], 'timestamp')
        self.assertEqual(list(response.context['rating_list']),
                         [self.rating_test_1, self.rating_test_2, self.rating_test_3])
        # order key materi title
        response = self.client.get(self.given_rating_url + '?order_by_key=materi__title&order=asc')
        self.assertEqual(response.context['order_by'], 'asc')
        self.assertEqual(response.context['order_by_key'], 'materi__title')
        self.assertEqual(list(response.context['rating_list']),
                         [self.rating_test_3, self.rating_test_1, self.rating_test_2])

    def test_given_rating_page_order_descending_should_be_correct(self):
        self.client.login(**self.contributor_credential)
        # From High to Low
        # order key score
        response = self.client.get(self.given_rating_url + '?order_by_key=score&order=dsc')
        self.assertEqual(response.context['order_by'], 'dsc')
        self.assertEqual(response.context['order_by_key'], 'score')
        self.assertEqual(list(response.context['rating_list']),
                         [self.rating_test_1, self.rating_test_2, self.rating_test_3])

        # order key timestamp
        response = self.client.get(self.given_rating_url + '?order_by_key=timestamp&order=dsc')
        self.assertEqual(response.context['order_by'], 'dsc')
        self.assertEqual(response.context['order_by_key'], 'timestamp')
        self.assertEqual(list(response.context['rating_list']),
                         [self.rating_test_3, self.rating_test_2, self.rating_test_1])

        # order key materi title
        response = self.client.get(self.given_rating_url + '?order_by_key=materi__title&order=dsc')
        self.assertEqual(response.context['order_by'], 'dsc')
        self.assertEqual(response.context['order_by_key'], 'materi__title')
        self.assertEqual(list(response.context['rating_list']),
                         [self.rating_test_2, self.rating_test_1, self.rating_test_3])
For faster browsing, not all history is shown. View entire blame