Fakultas Ilmu Komputer UI

tests.py 100 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
        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)


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

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

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

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

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


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

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

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

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

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

2400
2401
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
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())
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
    
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
2455
        self.assertEqual((2000, 2000), choices[0])
Yaumi's avatar
Yaumi committed
2456
class ChangePasswordTest(TestCase):
Yaumi's avatar
Yaumi committed
2457
2458
2459
2460
2461
    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
2462
        self.view = PasswordChangeViews
Yaumi's avatar
Yaumi committed
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
        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()

2497
    
For faster browsing, not all history is shown. View entire blame