Fakultas Ilmu Komputer UI

tests.py 115 KB
Newer Older
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
    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)


2039
2040
class UserDownloadHistoryTest(TestCase):
    def setUp(self):
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
        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()
        }
2057
2058
2059
2060
2061
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
        content = b"Test file"
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
        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()
2073
2074
2075
        self.materi1 = Materi.objects.first()
        self.download_url = f"/materi/{self.materi1.id}/unduh"
        self.history_url = "/download-history/"
2076
	
2077
2078
2079
2080
    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)
2081
		
2082
2083
2084
        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)
2085
		
2086
2087
2088
2089
    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)
2090
		
2091
2092
2093
        DownloadStatistics(materi=self.materi1).save()
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
2094
		
2095
2096
2097
2098
2099
2100
2101
2102
2103
        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)
2104
		
2105
2106
2107
        self.client.get(self.download_url)
        num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
        self.assertEqual(num_of_downloads, 1)
2108
		
2109
2110
        # Logout
        self.client.logout()
2111
		
2112
2113
    def test_unregistered_user_download(self):
        self.client.get(self.download_url)
2114
2115
2116
        downloaded_materi = self.client.session['downloaded_materi']
        num_of_downloads = DownloadStatistics.objects.filter(
                            pk__in=downloaded_materi).count()
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
        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)
2129
		
2130
2131
        # Logout
        self.client.logout()
2132
		
2133
2134
    def test_unregistered_user_multiple_download(self):
        self.client.get(self.download_url)
2135
2136
2137
        downloaded_materi = self.client.session['downloaded_materi']
        num_of_downloads = DownloadStatistics.objects.filter(
                            pk__in=downloaded_materi).count()
2138
2139
2140
        self.assertEqual(num_of_downloads, 1)

        self.client.get(self.download_url)
2141
2142
2143
        downloaded_materi = self.client.session['downloaded_materi']
        num_of_downloads = DownloadStatistics.objects.filter(
                            pk__in=downloaded_materi).count()
2144
        self.assertEqual(num_of_downloads, 2)
2145
		
2146
2147
2148
    def test_registered_user_doesnt_use_session_when_download(self):
        # Login
        self.client.login(**self.user1_credential)
2149
		
2150
        self.client.get(self.download_url)
2151
2152
        self.assertFalse('downloaded_materi' in self.client.session)
		
2153
2154
        # Logout
        self.client.logout()
2155
	
2156
2157
2158
2159
2160
2161
    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)
2162
		
2163
2164
        # Logout Anonym 1
        self.client.logout()
2165
2166
		
		# Unregistered User download
2167
2168
        self.client.get(self.download_url)
        user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
2169
2170
2171
        downloaded_materi = self.client.session['downloaded_materi']
        guest_num_of_downloads = DownloadStatistics.objects.filter(
                            pk__in=downloaded_materi).count()
2172
2173
        self.assertEqual(user1_num_of_downloads, 1)
        self.assertEqual(guest_num_of_downloads, 1)
2174
2175
		
		# Login Anonym 2
2176
2177
2178
2179
2180
2181
2182
        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)
2183
		
2184
2185
2186
2187
2188
        # Logout Anonym 2
        self.client.logout()

class DownloadHistoryViewTest(TestCase):
    def setUp(self):
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
        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()
        }
2199
2200
2201
2202
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
2203
		
2204
2205
        content1 = b"Test file"
        content2 = b"File Test"
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
		
        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)
			   
2220
2221
2222
        self.download_url1 = f"/materi/{self.materi1.id}/unduh"
        self.download_url2 = f"/materi/{self.materi2.id}/unduh"
        self.history_url = "/download-history/"
2223
		
2224
2225
2226
2227
2228
2229
        # Login
        self.client.login(**self.user_credential)

    def tearDown(self):
        # Logout
        self.client.logout()
2230
		
2231
2232
2233
    def test_allow_registered_user(self):
        response = self.client.get(self.history_url)
        self.assertEqual(response.status_code, 200)
2234
	
2235
    def test_allow_unregistered_user(self):
2236
	    # Forced Logout
2237
        self.client.logout()
2238
		
2239
2240
2241
2242
2243
2244
2245
2246
2247
        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)
2248
        resp_html = response.content.decode('utf8')
2249
        self.assertIn(self.user_anonim.name, resp_html)
2250
		
2251
2252
2253
2254
    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)
2255
		
2256
        jkt_timezone = timezone(TIME_ZONE)
2257
		
2258
2259
        download_history = self.user_anonim.riwayat_unduh.all()
        response = self.client.get(self.history_url)
2260
        resp_html = response.content.decode('utf8')
2261
2262
2263
2264
        for riwayat in download_history:
            downloaded_materi = riwayat.materi
            self.assertIn(downloaded_materi.title, resp_html)
            self.assertIn(downloaded_materi.author, resp_html)
2265
			
2266
2267
            jkt_timestamp = riwayat.timestamp.astimezone(jkt_timezone)
            self.assertIn(jkt_timestamp.strftime("%d %B %Y %H:%M:%S"), resp_html)
2268
			
2269
2270
2271
2272
2273
2274
    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)
2275
		
2276
        jkt_timezone = timezone(TIME_ZONE)
2277
		
2278
        response = self.client.get(self.history_url)
2279
2280
        resp_html = response.content.decode('utf8')
        for riwayat_id in self.client.session['downloaded_materi']:
2281
2282
2283
2284
            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)
2285
			
2286
2287
            jkt_timestamp = riwayat.timestamp.astimezone(jkt_timezone)
            self.assertIn(jkt_timestamp.strftime("%d %B %Y %H:%M:%S"), resp_html)
2288
			
2289
2290
2291
2292
2293
2294
    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()
2295
		
2296
        jkt_timezone = timezone(TIME_ZONE)
2297
		
2298
2299
        download_history = self.user_anonim.riwayat_unduh.all()
        response = self.client.get(self.history_url)
2300
        resp_html = response.content.decode('utf8')
2301
2302
2303
2304
        for riwayat in download_history:
            downloaded_materi = riwayat.materi
            self.assertNotIn(downloaded_materi.title, resp_html)
            self.assertNotIn(downloaded_materi.author, resp_html)
2305
			
2306
2307
            jkt_timestamp = riwayat.timestamp.astimezone(jkt_timezone)
            self.assertNotIn(jkt_timestamp.strftime("%d %B %Y %H:%M:%S"), resp_html)
2308
			
2309
2310
2311
2312
2313
2314
    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)
2315
		
2316
2317
2318
2319
        self.client.get(self.history_url)

        self.client.login(**self.user_credential)
        self.client.logout()
2320
2321
        self.assertFalse('downloaded_materi' in self.client.session)
			
2322
    def test_download_history_sorted_by_download_time(self):
2323
		# download with 1 second interval to differ download time
2324
2325
2326
2327
2328
2329
2330
        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)
2331
		
2332
        response = self.client.get(self.history_url)
2333
2334
        resp_html = response.content.decode('utf8')
		
2335
        table_html = ("<table" + resp_html.split("<table")[1]).split("</table>")[0] + "</table>"
2336
2337
        soup = BeautifulSoup(table_html, 'html.parser')
        histories_html = soup.find('tbody').find_all('tr')
2338
        prev_timestamp = None
2339
		
2340
2341
2342
2343
2344
2345
2346
        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
2347
			
2348
2349
2350
    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)
2351
        resp_html = response.content.decode('utf8')
2352
2353
2354
2355
        self.assertIn(no_history_msg, resp_html)


class MateriModelTest(TestCase):
2356
    
2357
    def setUp(self):
2358
2359
2360
2361
2362
        self.contributor = User.objects.create( 
            email="kontributor@gov.id",
            password="passwordtest",
            name="kontributor",
            is_contributor=True
2363
2364
        )

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

2369
2370
2371
2372
        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())
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382

    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)
2383

2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
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__)

2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
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())
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
    
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
2457
        self.assertEqual((2000, 2000), choices[0])
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
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
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573

TEST_IMAGE = '''
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI
WXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAABfElEQVQ4y52TvUuCURTGf5Zg
9goR9AVlUZJ9KURuUkhIUEPQUIubRFtIJTk0NTkUFfgntAUt0eBSQwRKRFSYBYFl1GAt901eUYuw
QTLM1yLPds/zPD/uPYereYjHcwD+tQ3+Uys+LwCah3g851la/lf4qwKb61Sn3z5WFUWpCHB+GUGb
SCRIpVKqBkmSAMrqsViMqnIiwLx7HO/U+6+30GYyaVXBP1uHrfUAWvWMWiF4+qoOUJLJkubYcDs2
S03hvODSE7564ek5W+Kt+tloa9ax6v4OZ++jZO+jbM+pD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F8jcqWwRgwpWOjKiLkQkOhv5+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
2574
class ChangePasswordTest(TestCase):
Yaumi's avatar
Yaumi committed
2575
2576
2577
2578
2579
    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
2580
        self.view = PasswordChangeViews
Yaumi's avatar
Yaumi committed
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
        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()

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
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]
2651
        time.sleep(5)
2652
        self.rating_test_1 = Rating(materi=self.materi1, user=self.kontributor, score=5)
2653
        time.sleep(5)
2654
        self.rating_test_2 = Rating(materi=self.materi2, user=self.kontributor, score=4)
2655
        time.sleep(5)
2656
        self.rating_test_3 = Rating(materi=self.materi3, user=self.kontributor, score=3)
2657
        time.sleep(5)
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
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
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
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
        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