-
-
Save kevinhowbrook/435d30ebd5b29098305398d1d6546324 to your computer and use it in GitHub Desktop.
KanyeTest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import json | |
import logging | |
import warnings | |
from unittest import mock | |
import requests | |
from django.conf import settings | |
from django.test import TestCase | |
from home.api_content import KanyeParse, KanyeRest | |
from home.models import HomePage | |
from requests.exceptions import Timeout | |
def mocked_fetch_data(): | |
data = json.dumps( | |
{ | |
"quote": "I want the world to be better! All I want is positive! All I want is dopeness!" | |
} | |
) | |
return data | |
class TestKanye(TestCase): | |
def setUp(self): | |
self.expected_api_data = {"quote": "All you have to be is yourself"} | |
self.expected_parsed_data = "I want the world to be better! All I want is positive! All I want is dopeness!" | |
self.default_data = [{"quote": "This is me, not Kayne"}] | |
def test_fetch(self): | |
url = KanyeRest().get_url() | |
response = requests.get(url, timeout=5) | |
self.assertEqual(response.status_code, 200) | |
# Data changes on each request so mock it | |
@mock.patch("home.api_content.KanyeRest.fetch_data", side_effect=mocked_fetch_data) | |
def test_fetch_with_example_data(self, mocked_fetch_data): | |
data = KanyeRest().get_data() | |
self.assertEqual(data, self.expected_parsed_data) | |
@mock.patch("home.api_content.requests.get") | |
def test_data_if_timeout(self, mock_get): | |
""" If a timeout is caught we should see the default data""" | |
mock_get.side_effect = Timeout | |
data = KanyeRest().get_data() | |
self.assertEqual(data, self.default_data) | |
@mock.patch("home.api_content.requests.get") | |
def test_page_renders_with_timeout(self, mock_get): | |
""" If there is a timeout for the request when the page loads, | |
ensure the page still renders with the default data""" | |
home_page = HomePage.objects.first() | |
mock_get.side_effect = Timeout | |
response = self.client.get("/") | |
self.assertTemplateUsed(response, "home/home_page.html") | |
self.assertEqual(response.render().status_code, 200) | |
@mock.patch("home.api_content.requests.get") | |
def test_page_renders_with_last_exception(self, mock_get): | |
""" If there is any other request for the request when the page loads, | |
ensure the page still renders with the default data""" | |
home_page = HomePage.objects.first() | |
mock_get.side_effect = Exception | |
response = self.client.get("/") | |
self.assertTemplateUsed(response, "home/home_page.html") | |
self.assertEqual(response.render().status_code, 200) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment