def test_blog_posts(self, client, site, homepage, blog_posts): """homepage should display featured blog posts in carousel""" response = client.get(homepage.relative_url(site)) assertTemplateUsed(response, "snippets/carousel.html") # no posts featured, so most recent ones should be in context assert len(response.context["updates"]) == 3 # feature some posts; only those should be displayed announcement = blog_posts["announcement"] project_feature = blog_posts["project_feature"] announcement.featured = True project_feature.featured = True announcement.save() project_feature.save() response = client.get(homepage.relative_url(site)) assert len(response.context["updates"]) == 2 assert announcement in response.context["updates"] assert project_feature in response.context["updates"] # should display short title, short description, and link assertContains(response, "A Big Announcement!") assertContains(response, "We're making a big digital humanities announcement.") assertContains(response, announcement.get_url()) # unpublished posts shouldn't be displayed announcement.unpublish() response = client.get(homepage.relative_url(site)) assert announcement not in response.context["updates"]
def test_owner_can_make_bookmark_homepage(client, db_setup): """A bookmark owner can updated the status of a bookmark to his or her homepage using the bookmark_make_homepage view. Arguments: - `client`: - `db_setup`: """ user = db_setup.get("homer") bm = db_setup.get("bm2") assert bm.homepage is False login = client.login(username=user.email, password=USER_PASSWORD) assert login is True url = reverse("bookmark_it:bookmark_make_homepage", args=[bm.id]) response = client.get(url, follow=True) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_detail.html") # verify that the homepage is our bookmark. homepage = Bookmark.objects.get(user=user, homepage=True) assert homepage.id == bm.id
def test_make_homepage_link_appears_if_homepage_is_false(client, db_setup): """The bookmark detail pages should include a linke to the make homepage view if the bookmark is not currently the homepage for this user. Arguments: - `client`: - `db_setup`: """ user = db_setup.get("homer") # homer's second bookmark is NOT his homepage. bm = db_setup.get("bm2") login = client.login(username=user.email, password=USER_PASSWORD) assert login is True url = reverse("bookmark_it:bookmark_detail", args=[bm.id]) response = client.get(url) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_detail.html") link = reverse("bookmark_it:bookmark_make_homepage", args=[bm.pk]) assertContains(response, link)
def test_unique_urls_within_user(client, db_setup): """Each user can only bookmark a url once - this test ensure that if a user tries to create a second bookmark for the same url, an error message is incldued in the response and a duplicate bookmark is not created. """ # homer already has already bookmarked 'http://www.thesimpsons.com' user = db_setup.get("homer") login = client.login(username=user.email, password=USER_PASSWORD) assert login is True payload = { "url": "http://www.thesimpsons.com", "title": "Homers first Bookmark", "description": "the bars of the world", } url = reverse("bookmark_it:bookmark_new") response = client.post(url, data=payload, follow=True) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_form.html") msg = "You already have a bookmark for that url." assertContains(response, msg)
def test_owner_can_update_bookmark(client, db_setup): """The bookmark owner should be able to update an bookmark they created. The url field has now been made readonly for existing bookmarks so this test fails. """ user = db_setup.get("homer") bm = db_setup.get("bm1") login = client.login(username=user.email, password=USER_PASSWORD) assert login is True payload = { "title": "New Title", "description": "New Description", "url": "http://simpsons.com", } url = reverse("bookmark_it:bookmark_edit", args=[bm.id]) response = client.post(url, data=payload, follow=True) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_detail.html") bookmark = Bookmark.objects.get(pk=bm.id) assert bookmark.title == payload["title"] assert bookmark.description == payload["description"] assert bookmark.url == payload["url"]
def test_order_create_form_valid(client, product): form_data = { "cpf": "401.142.450-10", "name": "Fulano", "email": "*****@*****.**", "postal_code": "76900-649", "address": "Rua Castro Alves", "number": "123", "district": "Jardim dos Migrantes", "state": "RO", "city": "Ji-Paraná", } response = client.post(reverse("orders:create"), data=form_data, follow=True) assertTemplateUsed(response, "home.html") client.post( reverse("cart:add", kwargs={"product_id": product.id}), data={ "quantity": 1, "override": False }, ) response = client.post(reverse("orders:create"), form_data, follow=True) assertTemplateUsed(response, "orders/order_created.html")
def test_user_is_bookmark_owner(client, db_setup): """When the user creates a new bookmark - they should automacally be the user associated with it. """ user = db_setup.get("barney") login = client.login(username=user.email, password=USER_PASSWORD) assert login is True payload = { "title": "Barneys Bookmark", "description": "the bars of the world", "url": "http://thebows.com", } url = reverse("bookmark_it:bookmark_new") response = client.post(url, data=payload, follow=True) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_detail.html") bookmark = Bookmark.objects.get(title=payload["title"]) assert bookmark.user == user
def test_view_search_results_page_uses_correct_template( self, client, proto_post): """search_results page should use search_results.html template.""" response = client.get(reverse("search_results"), {"q": f"{proto_post[1].title}"}) assert response.status_code == 200 assertTemplateUsed(response, "search_results.html")
def test_cwt_sequence_duplicate_cwt_numbers(client, cwt_stocking_events): """If the cwt has been used more than once - ie. there is more than a single cwt object with the same cwt number, two summary cards should be presented on the page - one for each tag. The micromark card will include a warnng. """ # create a cwt with the same number as an existing cwt: cwt_number = "111111" cwtMicroMark = CWTFactory(cwt_number=cwt_number, manufacturer="mm") CWTsequenceFactory(cwt=cwtMicroMark) url = reverse("stocking:cwt-detail", kwargs={"cwt_number": cwt_number}) response = client.get(url) assert response.status_code == 200 assertTemplateUsed("stocking/cwt_detail.html") # the header should appear twice: header = '<div class="header">CWT Number: 11-11-11</div>' assertContains(response, header, count=2, html=True) nmt = "<p ><strong>Manufacturer:</strong> Northwest Marine Technology</p>" assertContains(response, header, html=True) # micromark includes a warning: mm = '<p class="cwt-warning"><strong>Manufacturer:</strong> Micro Mark</p>' assertContains(response, header, html=True)
def test_player_view_get_proper_behavior_in_round_4_when_user_has_made_trade_in_this_and_last_round( client, db): """ User has traded in round 4, and in round 3. """ # some market is in round 4 market = MarketFactory(round=4) # a user has joined properly trader = TraderFactory(market=market) session = client.session session['trader_id'] = trader.pk session['username'] = '******' session.save() # the user has made a trade in_last_round TradeFactory(trader=trader, round=3, unit_price=Decimal('134.98')) # user goes to play url response = client.get(reverse('market:play', args=(market.market_id, ))) # The user has not traded in this round so he should get back play template with wait=false in context assert (response.status_code == 200) assertTemplateUsed(response, 'market/play/play.html'), assert not (response.context.get('wait')) # template should contain data from last round assertContains(response, "134.98") # template should contain a submit button assertContains(response, "submit") # template should not contain a link to the monitor view, since game is not over assertNotContains(response, f"/{market.market_id}/monitor")
def test_market_edit_invalid_post_data_does_not_update_market( client, logged_in_user): """ alpha is negative, so form is invalid. No values should be updated in this case """ market = MarketFactory(created_by=logged_in_user, alpha=105.5) client.login(username='******', password='******') data = { 'product_name_singular': 'surdejsbolle', 'product_name_plural': 'surdejsboller', 'alpha': -14, 'gamma': 3.34, 'theta': 32, 'endless': True, 'initial_balance': 53, 'max_rounds': 12, 'min_cost': 35, 'max_cost': 3565 } url = reverse('market:market_edit', args=(market.market_id, )) response = client.post(url, data=data) market.refresh_from_db() # alpha has not changed assert (float(market.alpha) == 105.5) # product name has not changed assert (market.product_name_singular == 'baguette') assert (response.status_code == 200) # return template assertTemplateUsed(response, 'market/market_edit.html')
def test_player_view_get_if_no_errors_and_time_to_wait_return_play_template_with_wait_content( client, db): # some market is in round 0 market = MarketFactory(round=0) # a user has joined properly trader = TraderFactory(market=market) session = client.session session['trader_id'] = trader.pk session['username'] = '******' session.save() # the user has made a trade in this round (and should now be waiting) TradeFactory(trader=trader, round=0) assert (Trade.objects.filter(trader=trader, round=0).count() == 1) # user goes to play url and should get play-template shown with wait equal true in context response = client.get(reverse('market:play', args=(market.market_id, ))) assert (response.status_code == 200) assertTemplateUsed(response, 'market/play/play.html'), assert (response.context.get('wait')) # there should now be a message saying that the user is waiting assertContains(response, "wait") # This is round 0, so no data from last round should be shown assertNotContains(response, 'Text with info about last round choices and results') # Template should not contain a submit button assertNotContains(response, 'submit')
def test_file_upload_invalid_spreadsheet(client, glsc, huron, mnrf, xlsfile, message): """Before the data in the spreadsheet can be validated on a row-by-row basis, the basic assimptions and shape of the data must be confirmed. If any of the basic tests fail, we need to return to upload form and provide a meaningful message. This test is paramaeterized and takes a list of two element tuples covering the cases verifying that the uploaded data has between 1 and the max number of rows, that all of the required fields are included, but no more, and that the upload is limited to a single, agency and lake. If any of these criteria fail, the events are considered invalid (valid=False), and a meaningful message should be returned in the response. NOTE - this test verifies that the response contains the expected message. If it is failing, check test_utils.py::test_validate_upload() first. It is a lower level function that verifies that the upload validation is working as expected. """ login = client.login(email=glsc.email, password="******") assert login is True url = reverse("stocking:upload-stocking-events") with open(xlsfile, "rb") as fp: response = client.post(url, {"data_file": fp}, follow=True) assert response.status_code == 200 assertTemplateUsed("stocking/upload_stocking_events.html") assertContains(response, message, html=True)
def test_authorized_users_can_upload(client, user): """If an authorized user accesses the upload url, they will be presented with a form. Arguments: - `self`: """ login = client.login(email=user.email, password="******") assert login is True url = reverse("stocking:upload-stocking-events") response = client.get(url) assert response.status_code == 200 assertTemplateUsed("stocking/upload_stocking_events.html") assertContains(response, "<h1>Upload Stocking Events</h1>", html=True) assertContains(response, '<label for="upload_comment">Comment (optional):</label>', html=True) assertContains(response, '<label for="data_file">File: </label>', html=True) assertContains( response, ('<input type="file" name="data_file" accept=".xlsx, .xls"' + ' id="data_file" name="data_file" required>'), html=True, )
def test_rendering_toggle_like_from_valid_referrers(client, valid_referrer, valid_template): response = client.get('/like/2/5/', HTTP_REFERER=valid_referrer) assert response.status_code == 302 response = client.get(response.url) assert response.status_code == 200 assertTemplateUsed(response, valid_template)
def test_existing_movie(self, client): movie = Movie.objects.first() assert movie is not None response = client.get( reverse('movies.movie_page', kwargs=dict(movie_id=movie.id))) assertTemplateUsed(response, 'movies/movie_page.html') assert response.status_code == 200
def test_rendering_toggle_like_invalid_data_in_path(client, invalid_data_path): response = client.get(invalid_data_path, HTTP_REFERER='/reviews/') # valid referrer assert response.status_code == 302 response = client.get(response.url) assert response.status_code == 200 assertTemplateUsed(response, 'homepage/landing/landing.html')
def test_render_delete_account_template(client, valid_user_1): user = create_activated_test_user(valid_user_1) client.force_login(user) url = reverse('users:delete-account') response = client.get(url) assert response.status_code == 200 assertTemplateUsed(response, 'users/delete_account.html')
def test_user_sees_filtered_bookmarks(client, db_setup, criteria): """When a user views the bookmark list that includes "contains" filter, they should only see their bookmarks that contain that tag in their title or description, and not bookmarks that do not have that phrase in their title or description, or bookmarks where created by any other user. The search criteria is not case sensitve and should be included in the response. """ user = db_setup.get("homer") login = client.login(username=user.email, password=USER_PASSWORD) assert login is True url = reverse("bookmark_it:bookmark_list") response = client.get(url, {"contains": criteria}) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_list.html") assertContains(response, criteria) assertContains(response, "Homers second bookmark") assertNotContains(response, "Homers first bookmark")
def test_question_form_and_template_displayed(self, client, authenticated_user): response = client.get('/explore/new_question') assert response.status_code == 200 assert isinstance(response.context['form'], type(QuestionForm)) assertTemplateUsed(response, 'home/questions/new_question.html')
def test_new_bookmarktags_created_from_keywords(client, db_setup): """When a bookmark is create or edited and a new keyword is added to the list of keywords a new bookmark tag is created. """ user = db_setup.get("barney") keywords = ["alpha", "beta", "theta"] # make sure they are not in the database yet: db_keywords = [x.tag for x in BookmarkTag.objects.filter(user=user)] for kw in keywords: assert kw not in db_keywords login = client.login(username=user.email, password=USER_PASSWORD) assert login is True payload = { "title": "Barneys Bookmark", "description": "the bars of the world", "url": "http://thebows.com", "keywords": ", ".join(keywords), } url = reverse("bookmark_it:bookmark_new") response = client.post(url, data=payload, follow=True) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_detail.html") db_keywords = [x.tag for x in BookmarkTag.objects.filter(user=user)] for kw in keywords: assert kw in db_keywords
def test_valid_token_user_banned_until_expired(client, valid_user_1): user = create_test_user_reset_password(valid_user_1, banned_seconds=1) url = re.findall('(?<=href=").+?(?=")', user.emails.first().body)[0] sleep(1) response = client.get(url) assert response.status_code == 200 assertTemplateUsed(response, 'users/reset_password_token.html')
def test_duplicate_urls_allowed_different_users(client, db_setup): """Different users should be able to create bookmarks to the same url.""" # bart does not have the url 'http://www.thesimpsons.com' so he # should be able to create a new bookmark. user = db_setup.get("bart") login = client.login(username=user.email, password=USER_PASSWORD) assert login is True payload = { "url": "http://www.thesimpsons.com", "title": "Homers first Bookmark", "description": "the bars of the world", } url = reverse("bookmark_it:bookmark_new") response = client.post(url, data=payload, follow=True) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_detail.html") msg = "You already have a bookmark for that url." assertNotContains(response, msg)
def test_profile_view(login_user, test_student): # test without a logged in user # it should redirect to the login page anonymous_client = Client() response = anonymous_client.get(reverse('users:profile')) assert response.status_code == 302 # test if it redirects to the correct page response = anonymous_client.get(reverse('users:profile'), follow=True) assert response.status_code == 200 assert response.redirect_chain[0][1] == 302 assert "login" in response.redirect_chain[0][0] # test with a logged in user client = login_user response = client.get(reverse('users:profile')) assert response.status_code == 200 assertTemplateUsed(response, "users/profile.html") view = Profile() view.object = test_student # Test if there is a title in the context_data which is our custom code assert "title" in view.get_context_data().keys() # if there is a title, it should have the following value assert view.get_context_data()["title"] == _("Profile")
def test_owner_cannot_update_bookmark_with_duplicate_url(client, db_setup): """If the user accidentally update the url of a bookmark to match and existing url, they will should recieve an appropriate error message. The url field has now been made readonly for existing bookmarks so this test fails. """ user = db_setup.get("homer") bm1 = db_setup.get("bm1") bm2 = db_setup.get("bm2") login = client.login(username=user.email, password=USER_PASSWORD) assert login is True payload = { "title": bm1.title, "description": bm1.description, "url": bm1.url } url = reverse("bookmark_it:bookmark_edit", args=[bm2.id]) response = client.post(url, data=payload) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_form.html") msg = "You already have a bookmark for that url." assertContains(response, msg)
def test_reset_password_view_without_login(): # test without a logged in user # it should redirect to the login page anonymous_client = Client() response = anonymous_client.get(reverse('users:forgot_pass')) assert response.status_code == 200 assertTemplateUsed(response, "users/forgot_password.html")
def test_owner_cannot_make_bookmark_homepage_twice(client, db_setup): """If a user tries to make the bookmark that is their homepage, their homepage again, nothing should happen. Arguments: - `client`: - `db_setup`: """ user = db_setup.get("homer") # bm1 is already homer's homepage bm = db_setup.get("bm1") assert bm.homepage is True login = client.login(username=user.email, password=USER_PASSWORD) assert login is True url = reverse("bookmark_it:bookmark_make_homepage", args=[bm.id]) response = client.get(url, follow=True) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_detail.html") # verify that the status of the bookmark did not change: bm = Bookmark.objects.get(id=bm.id) assert bm.homepage is True
def test_edit_view_success_template(db_keys): clients = ("*****@*****.**", "*****@*****.**") for client in clients: c = Client() assert c.login(email=client, password="******") is True # django template views for view in ("assessment:update", "assessment:delete"): for pk in db_keys.assessment_keys: response = c.get(reverse(view, kwargs={"pk": pk})) assert response.status_code == 200 # check post updates response = c.post( reverse( "assessment:update", kwargs={"pk": db_keys.assessment_working}, ), {"name": "foo manchu"}, ) assertTemplateUsed("assessment/assessment_detail.html") assert response.status_code == 200 response = c.post( reverse( "assessment:update", kwargs={"pk": db_keys.assessment_final}, ), {"name": "foo manchu"}, ) assertTemplateUsed("assessment/assessment_detail.html") assert response.status_code == 200
def test_nonowner_cannot_make_bookmark_homepage(client, db_setup): """If a user who is not the bookmark owner tries to access the bookmark_make_homepage view, they should be returned to the bookmark list and the status of the bookmark should not change. Arguments: - `client`: - `db_setup`: """ user = db_setup.get("barney") bm = db_setup.get("bm2") assert bm.homepage is False login = client.login(username=user.email, password=USER_PASSWORD) assert login is True url = reverse("bookmark_it:bookmark_make_homepage", args=[bm.id]) response = client.get(url, follow=True) assert response.status_code == 200 assertTemplateUsed(response, "bookmark_it/bookmark_list.html") link = reverse("bookmark_it:bookmark_make_homepage", args=[bm.pk]) assertNotContains(response, link) # verify that the status of the bookmark did not change: bm = Bookmark.objects.get(id=bm.id) assert bm.homepage is False
def test_index(client, admin_client): url = reverse('webapp.index') resp = client.get(url) assertRedirects(resp, reverse('webapp.login')+'?next='+url) resp = admin_client.get(url) assertTemplateUsed('index.html')