Fakultas Ilmu Komputer UI

tests.py 98.9 KB
Newer Older
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
2001

2002
        self.assertIn('Permintaan materi berhasil dikirimkan', response.content.decode())
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
2003
2004
2005
2006
2007
2008
2009
2010
        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)

2011
        self.assertIn('Missing parameter', response.content.decode())
Muhamad Lutfi Arif's avatar
Muhamad Lutfi Arif committed
2012
        self.client.logout()
2013
2014
2015
2016


class RatingContributorTest(TransactionTestCase):
    def setUp(self):
2017
2018
2019
2020
        self.contributor_credential = {
            "email": "kontributor@gov.id",
            "password": id_generator()
        }
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
        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())
2052
2053
2054

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

        self.client.get(self.download_url)
2155
2156
2157
        downloaded_materi = self.client.session['downloaded_materi']
        num_of_downloads = DownloadStatistics.objects.filter(
                            pk__in=downloaded_materi).count()
2158
        self.assertEqual(num_of_downloads, 2)
2159
		
2160
2161
2162
    def test_registered_user_doesnt_use_session_when_download(self):
        # Login
        self.client.login(**self.user1_credential)
2163
		
2164
        self.client.get(self.download_url)
2165
2166
        self.assertFalse('downloaded_materi' in self.client.session)
		
2167
2168
        # Logout
        self.client.logout()
2169
	
2170
2171
2172
2173
2174
2175
    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)
2176
		
2177
2178
        # Logout Anonym 1
        self.client.logout()
2179
2180
		
		# Unregistered User download
2181
2182
        self.client.get(self.download_url)
        user1_num_of_downloads = self.user1_anonim.riwayat_unduh.all().count()
2183
2184
2185
        downloaded_materi = self.client.session['downloaded_materi']
        guest_num_of_downloads = DownloadStatistics.objects.filter(
                            pk__in=downloaded_materi).count()
2186
2187
        self.assertEqual(user1_num_of_downloads, 1)
        self.assertEqual(guest_num_of_downloads, 1)
2188
2189
		
		# Login Anonym 2
2190
2191
2192
2193
2194
2195
2196
        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)
2197
		
2198
2199
2200
2201
2202
        # Logout Anonym 2
        self.client.logout()

class DownloadHistoryViewTest(TestCase):
    def setUp(self):
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
        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()
        }
2213
2214
2215
2216
        self.contributor = get_user_model().objects.create_user(
            **self.contributor_credential, name="Kontributor", is_contributor=True
        )
        self.client = Client()
2217
		
2218
2219
        content1 = b"Test file"
        content2 = b"File Test"
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
		
        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)
			   
2234
2235
2236
        self.download_url1 = f"/materi/{self.materi1.id}/unduh"
        self.download_url2 = f"/materi/{self.materi2.id}/unduh"
        self.history_url = "/download-history/"
2237
		
2238
2239
2240
2241
2242
2243
        # Login
        self.client.login(**self.user_credential)

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

        self.client.login(**self.user_credential)
        self.client.logout()
2334
2335
        self.assertFalse('downloaded_materi' in self.client.session)
			
2336
    def test_download_history_sorted_by_download_time(self):
2337
		# download with 1 second interval to differ download time
2338
2339
2340
2341
2342
2343
2344
        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)
2345
		
2346
        response = self.client.get(self.history_url)
2347
2348
        resp_html = response.content.decode('utf8')
		
2349
        table_html = ("<table" + resp_html.split("<table")[1]).split("</table>")[0] + "</table>"
2350
2351
        soup = BeautifulSoup(table_html, 'html.parser')
        histories_html = soup.find('tbody').find_all('tr')
2352
        prev_timestamp = None
2353
		
2354
2355
2356
2357
2358
2359
2360
        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
2361
			
2362
2363
2364
    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)
2365
        resp_html = response.content.decode('utf8')
2366
2367
2368
2369
        self.assertIn(no_history_msg, resp_html)


class MateriModelTest(TestCase):
2370
    
2371
    def setUp(self):
2372
2373
2374
2375
2376
        self.contributor = User.objects.create( 
            email="kontributor@gov.id",
            password="passwordtest",
            name="kontributor",
            is_contributor=True
2377
2378
        )

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

2383
2384
2385
2386
        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())
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396

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

2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
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__)

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
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
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())
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
    
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
2471
        self.assertEqual((2000, 2000), choices[0])
Yaumi's avatar
Yaumi committed
2472
class ChangePasswordTest(TestCase):
Yaumi's avatar
Yaumi committed
2473
2474
2475
2476
2477
    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
2478
        self.view = PasswordChangeViews
Yaumi's avatar
Yaumi committed
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
        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()

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