def test_decode_2(self): c = SimpleCookie() c['test'] = b"\xf0" c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test'])
def test_decode(self): """Semicolons and commas are decoded.""" c = SimpleCookie() c['test'] = "An,awkward;value" c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test'])
def test_decode(self): """ Test that we can still preserve semi-colons and commas """ c = SimpleCookie() c["test"] = "An,awkward;value" c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c["test"].value, c2["test"].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c["test"].value, c3["test"])
def test_decode(self): """ Test that we can still preserve semi-colons and commas """ c = SimpleCookie() c['test'] = "An,awkward;value" c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test'])
def test_decode_2(self): """ Test that we haven't broken normal encoding """ c = SimpleCookie() c["test"] = b"\xf0" c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c["test"].value, c2["test"].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c["test"].value, c3["test"])
def test_decode_2(self): """ Test that we haven't broken normal encoding """ c = SimpleCookie() c['test'] = b"\xf0" c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test'])
def construct_request_json(request): result = { "GET": {}, "POST": {}, "FILES": {}, "META": {}, "COOKIES": {} } for var in request.GET.items(): result["GET"][var[0]] = repr(var[1]) for var in request.POST.items(): result["POST"][var[0]] = repr(var[1]) for var in request.FILES.items(): result["FILES"][var[0]] = repr(var[1]) whitelisted_cookie = SimpleCookie() for name, value in request.COOKIES.items(): if name in COOKIE_BLACKLIST: continue whitelisted_cookie[name] = value result["COOKIES"][name] = repr(value) for meta_name, meta_value in sorted(request.META.items()): if meta_name == 'HTTP_COOKIE': meta_value = whitelisted_cookie.output(header='', sep='; ') result["META"][meta_name] = repr(meta_value) return json.dumps(result)
async def _login(self, user, backend=None): from django.contrib.auth import login engine = import_module(settings.SESSION_ENGINE) # Create a fake request to store login details. request = HttpRequest() request.session = engine.SessionStore() await database_sync_to_async(login)(request, user, backend) # Save the session values. await database_sync_to_async(request.session.save)() # Create a cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME cookies = SimpleCookie() cookies[session_cookie] = request.session.session_key cookie_data = { 'max-age': None, 'path': '/', 'domain': settings.SESSION_COOKIE_DOMAIN, 'secure': settings.SESSION_COOKIE_SECURE or None, 'expires': None, } cookies[session_cookie].update(cookie_data) self.session = request.session self._session_cookie = bytes( cookies.output(header=''), encoding="utf-8", )
def test_encode(self): """ Test that we don't output tricky characters in encoded value """ c = SimpleCookie() c["test"] = "An,awkward;value" self.assertNotIn(";", c.output().rstrip(";")) # IE compat self.assertNotIn(",", c.output().rstrip(";")) # Safari compat
def test_encode(self): """ Test that we don't output tricky characters in encoded value """ c = SimpleCookie() c['test'] = "An,awkward;value" self.assertTrue(";" not in c.output().rstrip(';')) # IE compat self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
def test_decode(self): """ Test that we can still preserve semi-colons and commas """ c = SimpleCookie() c['test'] = "An,awkward;value" c2 = SimpleCookie() c2.load(c.output()) self.assertEqual(c['test'].value, c2['test'].value)
def test_decode_2(self): """ Test that we haven't broken normal encoding """ c = SimpleCookie() c['test'] = b"\xf0" c2 = SimpleCookie() c2.load(c.output()) self.assertEqual(c['test'].value, c2['test'].value)
def test_encode(self): """ Test that we don't output tricky characters in encoded value """ # Python 2.4 compatibility note: Python 2.4's cookie implementation # always returns Set-Cookie headers terminating in semi-colons. # That's not the bug this test is looking for, so ignore it. c = SimpleCookie() c['test'] = "An,awkward;value" self.assertTrue(";" not in c.output().rstrip(';')) # IE compat self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
def test_pickle(self): rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1' expected_output = 'Set-Cookie: %s' % rawdata C = SimpleCookie() C.load(rawdata) self.assertEqual(C.output(), expected_output) for proto in range(pickle.HIGHEST_PROTOCOL + 1): C1 = pickle.loads(pickle.dumps(C, protocol=proto)) self.assertEqual(C1.output(), expected_output)
def test_create_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Test for status: VOTER_CREATED response2 = self.client.get(self.voter_create_url) json_data2 = json.loads(response2.content) self.assertEqual('status' in json_data2, True, "status expected in the voterCreateView json response but not found") self.assertEqual('voter_device_id' in json_data2, True, "voter_device_id expected in the voterCreateView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data2['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format( status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Test for status: VOTER_ALREADY_EXISTS response3 = self.client.get(self.voter_create_url) json_data3 = json.loads(response3.content) self.assertEqual('status' in json_data3, True, "status expected in the voterCreateView json response but not found") self.assertEqual('voter_device_id' in json_data3, True, "voter_device_id expected in the voterCreateView json response but not found") # Try reusing the same voter_device_id self.assertEqual( json_data3['status'], 'VOTER_ALREADY_EXISTS', "status: {status} (VOTER_ALREADY_EXISTS expected), voter_device_id: {voter_device_id}".format( status=json_data3['status'], voter_device_id=json_data3['voter_device_id']))
def test_retrieve_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url) json_data2 = json.loads(response2.content) self.assertEqual('status' in json_data2, True, "status expected in the voterCreateView json response but not found") self.assertEqual('voter_device_id' in json_data2, True, "voter_device_id expected in the voterCreateView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data2['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format( status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Test for id, first_name, last_name, email response3 = self.client.get(self.voter_retrieve_url) json_data3 = json.loads(response3.content) for one_voter in json_data3: self.assertEqual('id' in one_voter, True, "id expected in the voterRetrieveView json response but not found") self.assertEqual('first_name' in one_voter, True, "first_name expected in the voterRetrieveView json response but not found") self.assertEqual('last_name' in one_voter, True, "last_name expected in the voterRetrieveView json response but not found") self.assertEqual('email' in one_voter, True, "email expected in the voterRetrieveView json response but not found")
def artificial_login(**credentials): from django.contrib.auth import authenticate, login cookies = SimpleCookie() user = authenticate(**credentials) engine = import_module(settings.SESSION_ENGINE) # Create a fake request that goes through request middleware request = WSGIRequest({ 'HTTP_COOKIE': cookies.output(header='', sep=';'), 'PATH_INFO': str('/'), 'REMOTE_ADDR': str('127.0.0.1'), 'REQUEST_METHOD': str('GET'), 'SCRIPT_NAME': str(''), 'SERVER_NAME': str('testserver'), 'SERVER_PORT': str('80'), 'SERVER_PROTOCOL': str('HTTP/1.1'), 'wsgi.version': (1, 0), 'wsgi.url_scheme': str('http'), 'wsgi.input': BytesIO(), 'wsgi.errors': BytesIO(), 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, }) request.session = engine.SessionStore() login(request, user) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME cookies[session_cookie] = request.session.session_key cookie_data = { 'max-age': None, 'path': '/', 'domain': settings.SESSION_COOKIE_DOMAIN, 'secure': settings.SESSION_COOKIE_SECURE or None, 'expires': None, } cookies[session_cookie].update(cookie_data) return { session_cookie: cookies[session_cookie].value, settings.CSRF_COOKIE_NAME: csrf._get_new_csrf_key(), }
def artificial_login(**credentials): from django.contrib.auth import authenticate, login cookies = SimpleCookie() user = authenticate(**credentials) engine = import_module(settings.SESSION_ENGINE) # Create a fake request that goes through request middleware request = WSGIRequest({ "HTTP_COOKIE": cookies.output(header="", sep=";"), "PATH_INFO": "/", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": BytesIO(), "wsgi.errors": BytesIO(), "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, }) request.session = engine.SessionStore() login(request, user) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME cookies[session_cookie] = request.session.session_key cookie_data = { "max-age": None, "path": "/", "domain": settings.SESSION_COOKIE_DOMAIN, "secure": settings.SESSION_COOKIE_SECURE or None, "expires": None, } cookies[session_cookie].update(cookie_data) return { session_cookie: cookies[session_cookie].value, settings.CSRF_COOKIE_NAME: csrf._get_new_csrf_key(), }
def artificial_login(**credentials): from django.contrib.auth import authenticate, login cookies = SimpleCookie() user = authenticate(**credentials) engine = import_module(settings.SESSION_ENGINE) # Create a fake request that goes through request middleware request = WSGIRequest( { "HTTP_COOKIE": cookies.output(header="", sep=";"), "PATH_INFO": str("/"), "REMOTE_ADDR": str("127.0.0.1"), "REQUEST_METHOD": str("GET"), "SCRIPT_NAME": str(""), "SERVER_NAME": str("testserver"), "SERVER_PORT": str("80"), "SERVER_PROTOCOL": str("HTTP/1.1"), "wsgi.version": (1, 0), "wsgi.url_scheme": str("http"), "wsgi.input": BytesIO(), "wsgi.errors": BytesIO(), "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, } ) request.session = engine.SessionStore() login(request, user) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME cookies[session_cookie] = request.session.session_key cookie_data = { "max-age": None, "path": "/", "domain": settings.SESSION_COOKIE_DOMAIN, "secure": settings.SESSION_COOKIE_SECURE or None, "expires": None, } cookies[session_cookie].update(cookie_data) return {session_cookie: cookies[session_cookie].value, settings.CSRF_COOKIE_NAME: csrf._get_new_csrf_key()}
def test_follow_with_cookie(self): ####################################### # Generate the voter_device_id cookie response10 = self.client.get(self.generate_voter_device_id_url) json_data10 = json.loads(response10.content.decode()) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data10, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data10['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Create a voter so we can test retrieve response11 = self.client.get(self.voter_create_url) json_data11 = json.loads(response11.content.decode()) self.assertEqual('status' in json_data11, True, "status expected in the voterOrganizationFollowView json response but not found") self.assertEqual('voter_device_id' in json_data11, True, "voter_device_id expected in the voterOrganizationFollowView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data11['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected in voterOrganizationFollowView), " "voter_device_id: {voter_device_id}".format( status=json_data11['status'], voter_device_id=json_data11['voter_device_id'])) ####################################### # Make sure the correct errors are thrown when an organization_id isn't passed in response12 = self.client.get(self.organization_follow_url) json_data12 = json.loads(response12.content.decode()) self.assertEqual('status' in json_data12, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data12, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data12, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data12, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data12['status'], 'VALID_ORGANIZATION_ID_MISSING', "status: {status} (VALID_ORGANIZATION_ID_MISSING expected), " "voter_device_id: {voter_device_id}".format( status=json_data12['status'], voter_device_id=json_data12['voter_device_id'])) self.assertEqual(json_data12['success'], False, "success 'False' expected, True returned") self.assertEqual(json_data12['organization_id'], 0, "organization_id == 0 expected, organization_id: {organization_id} returned".format( organization_id=json_data12['organization_id'])) ####################################### # Make sure the correct errors are thrown when an organization_id isn't passed in response13 = self.client.get(self.organization_follow_ignore_url) json_data13 = json.loads(response13.content.decode()) self.assertEqual('status' in json_data13, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data13, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data13, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data13, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data13['status'], 'VALID_ORGANIZATION_ID_MISSING', "status: {status} (VALID_ORGANIZATION_ID_MISSING expected), voter_device_id: {voter_device_id}".format( status=json_data13['status'], voter_device_id=json_data13['voter_device_id'])) self.assertEqual(json_data13['success'], False, "success 'False' expected, True returned") self.assertEqual(json_data13['organization_id'], 0, "organization_id == 0 expected, organization_id: {organization_id} returned".format( organization_id=json_data13['organization_id'])) ####################################### # Make sure the correct errors are thrown when an organization_id isn't passed in response14 = self.client.get(self.organization_stop_following_url) json_data14 = json.loads(response14.content.decode()) self.assertEqual('status' in json_data14, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data14, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data14, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data14, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data14['status'], 'VALID_ORGANIZATION_ID_MISSING', "status: {status} (VALID_ORGANIZATION_ID_MISSING expected), voter_device_id: {voter_device_id}".format( status=json_data14['status'], voter_device_id=json_data14['voter_device_id'])) self.assertEqual(json_data14['success'], False, "success 'False' expected, True returned") self.assertEqual(json_data14['organization_id'], 0, "organization_id == 0 expected, organization_id: {organization_id} returned".format( organization_id=json_data14['organization_id'])) ####################################### # Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist response15 = self.client.get(self.organization_follow_url, {'organization_id': 1}) json_data15 = json.loads(response15.content.decode()) self.assertEqual('status' in json_data15, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data15, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data15, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data15, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data15['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOWING', "status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOWING expected), " "voter_device_id: {voter_device_id}".format( status=json_data15['status'], voter_device_id=json_data15['voter_device_id'])) self.assertEqual(json_data15['success'], False, "success 'False' expected, True returned") self.assertEqual(json_data15['organization_id'], 1, "organization_id == 1 expected, organization_id: {organization_id} returned".format( organization_id=json_data15['organization_id'])) ####################################### # Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist response16 = self.client.get(self.organization_follow_ignore_url, {'organization_id': 1}) json_data16 = json.loads(response16.content.decode()) self.assertEqual('status' in json_data16, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data16, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data16, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data16, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data16['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOW_IGNORE', "status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOW_IGNORE expected), " "voter_device_id: {voter_device_id}".format( status=json_data16['status'], voter_device_id=json_data16['voter_device_id'])) self.assertEqual(json_data16['success'], False, "success 'False' expected, True returned") self.assertEqual(json_data16['organization_id'], 1, "organization_id == 1 expected, organization_id: {organization_id} returned".format( organization_id=json_data16['organization_id'])) ####################################### # Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist response17 = self.client.get(self.organization_stop_following_url, {'organization_id': 1}) json_data17 = json.loads(response17.content.decode()) self.assertEqual('status' in json_data17, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data17, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data17, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data17, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data17['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE STOP_FOLLOWING', "status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE STOP_FOLLOWING expected), " "voter_device_id: {voter_device_id}".format( status=json_data17['status'], voter_device_id=json_data17['voter_device_id'])) self.assertEqual(json_data17['success'], False, "success 'False' expected, True returned") self.assertEqual(json_data17['organization_id'], 1, "organization_id == 1 expected, organization_id: {organization_id} returned".format( organization_id=json_data17['organization_id'])) ####################################### # Add an organization so we can test all of the 'follow' states organization1 = Organization.objects.create_organization_simple( organization_name="Org1", organization_website="www.org1.org", organization_twitter_handle="org1", ) ####################################### # Make sure the correct results are given when saved successfully response18 = self.client.get(self.organization_follow_url, {'organization_id': organization1.id}) json_data18 = json.loads(response18.content.decode()) self.assertEqual('status' in json_data18, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data18, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data18, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data18, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data18['status'], 'FOLLOWING', "status: {status} (FOLLOWING expected), " "voter_device_id: {voter_device_id}".format( status=json_data18['status'], voter_device_id=json_data18['voter_device_id'])) self.assertEqual(json_data18['success'], True, "success 'True' expected, False returned") self.assertEqual(json_data18['organization_id'], organization1.id, "organization_id returned (organization_id: {organization_id}) didn't match" "original passed in".format( organization_id=json_data18['organization_id'])) ####################################### # Make sure the correct results are given when saved successfully response19 = self.client.get(self.organization_follow_ignore_url, {'organization_id': organization1.id}) json_data19 = json.loads(response19.content.decode()) self.assertEqual('status' in json_data19, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data19, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data19, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data19, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data19['status'], 'IGNORING', "status: {status} (IGNORING expected), " "voter_device_id: {voter_device_id}".format( status=json_data19['status'], voter_device_id=json_data19['voter_device_id'])) self.assertEqual(json_data19['success'], True, "success 'True' expected, False returned") self.assertEqual(json_data19['organization_id'], organization1.id, "organization_id returned (organization_id: {organization_id}) didn't match" "original passed in".format( organization_id=json_data19['organization_id'])) ####################################### # Make sure the correct results are given when saved successfully response20 = self.client.get(self.organization_stop_following_url, {'organization_id': organization1.id}) json_data20 = json.loads(response20.content.decode()) self.assertEqual('status' in json_data20, True, "'status' expected in the json response, and not found") self.assertEqual('success' in json_data20, True, "'success' expected in the json response, and not found") self.assertEqual('organization_id' in json_data20, True, "'organization_id' expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data20, True, "'voter_device_id' expected in the json response, and not found") self.assertEqual( json_data20['status'], 'STOPPED_FOLLOWING', "status: {status} (STOPPED_FOLLOWING expected), " "voter_device_id: {voter_device_id}".format( status=json_data20['status'], voter_device_id=json_data20['voter_device_id'])) self.assertEqual(json_data20['success'], True, "success 'True' expected, False returned") self.assertEqual(json_data20['organization_id'], organization1.id, "organization_id returned (organization_id: {organization_id}) didn't match" "original passed in".format( organization_id=json_data20['organization_id']))
def test_retrieve_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response01 = self.client.get(self.generate_voter_device_id_url) json_data01 = json.loads(response01.content) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data01, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data01['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # With a cookie, but without a voter_id in the database, we don't expect valid response response02 = self.client.get(self.voter_guides_to_follow_retrieve_url) json_data02 = json.loads(response02.content) self.assertEqual('status' in json_data02, True, "status expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data02, True, "voter_device_id expected in the voterGuidesToFollowRetrieveView json response, and not found") self.assertEqual( json_data02['status'], 'ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID', "status: {status} (ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID expected), " "voter_device_id: {voter_device_id}".format( status=json_data02['status'], voter_device_id=json_data02['voter_device_id'])) ####################################### # Create a voter so we can test retrieve response03 = self.client.get(self.voter_create_url) json_data03 = json.loads(response03.content) self.assertEqual('status' in json_data03, True, "status expected in the voterCreateView json response but not found") self.assertEqual('voter_device_id' in json_data03, True, "voter_device_id expected in the voterCreateView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data03['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format( status=json_data03['status'], voter_device_id=json_data03['voter_device_id'])) ####################################### # Test the response before any voter guides exist response04 = self.client.get(self.voter_guides_to_follow_retrieve_url) json_data04 = json.loads(response04.content) self.assertEqual('status' in json_data04, True, "status expected in the voterGuidesToFollowRetrieveView json response but not found") self.assertEqual('success' in json_data04, True, "success expected in the voterGuidesToFollowRetrieveView json response but not found") self.assertEqual('voter_device_id' in json_data04, True, "voter_device_id expected in the voterGuidesToFollowRetrieveView json response but not found") self.assertEqual('voter_guides' in json_data04, True, "voter_guides expected in the voterGuidesToFollowRetrieveView json response but not found") self.assertEqual( json_data04['status'], 'NO_VOTER_GUIDES_FOUND', "status: {status} (NO_VOTER_GUIDES_FOUND expected), voter_device_id: {voter_device_id}".format( status=json_data04['status'], voter_device_id=json_data04['voter_device_id'])) ####################################### # Create organization organization1 = Organization.objects.create_organization( organization_name="Org1", organization_website="www.org1.org", organization_twitter="org1", ) ####################################### # Check to make sure there is 1 organization response10 = self.client.get(self.organization_count_url) json_data10 = json.loads(response10.content) self.assertEqual('success' in json_data10, True, "'success' expected in the json response, and not found") self.assertEqual('organization_count' in json_data10, True, "'organization_count' expected in the organizationRetrieve json response") self.assertEqual( json_data10['organization_count'], 1, "success: {success} (organization_count '1' expected), organization_count: {organization_count}".format( success=json_data10['success'], organization_count=json_data10['organization_count'])) ####################################### # Create candidate_campaign ####################################### # Create position where organization is supporting candidate ####################################### # Test the response with one voter guide response40 = self.client.get(self.voter_guides_to_follow_retrieve_url) json_data40 = json.loads(response40.content) self.assertEqual('status' in json_data40, True, "status expected in the voterGuidesToFollowRetrieveView json response but not found") self.assertEqual('success' in json_data40, True, "success expected in the voterGuidesToFollowRetrieveView json response but not found") self.assertEqual('voter_device_id' in json_data40, True, "voter_device_id expected in the voterGuidesToFollowRetrieveView json response but not found") self.assertEqual('voter_guides' in json_data40, True, "voter_guides expected in the voterGuidesToFollowRetrieveView json response but not found") # Make sure all voter guides returned have the expected array keys for one_voter_guide in json_data40['voter_guides']: self.assertEqual('google_civic_election_id' in one_voter_guide, True, "google_civic_election_id expected in voterGuidesToFollowRetrieveView json but not found") self.assertEqual('voter_guide_owner_type' in one_voter_guide, True, "voter_guide_owner_type expected in voterGuidesToFollowRetrieveView json but not found") self.assertEqual('organization_we_vote_id' in one_voter_guide, True, "organization_we_vote_id expected in voterGuidesToFollowRetrieveView json but not found") self.assertEqual('public_figure_we_vote_id' in one_voter_guide, True, "public_figure_we_vote_id expected in voterGuidesToFollowRetrieveView json but not found") self.assertEqual('owner_voter_id' in one_voter_guide, True, "owner_voter_id expected in voterGuidesToFollowRetrieveView json but not found") self.assertEqual('last_updated' in one_voter_guide, True, "last_updated expected in voterGuidesToFollowRetrieveView json but not found")
class ConvertedRequest(object): """ Class that takes a QNetworkRequest and converts it to a request type django understands """ def __init__(self, cookiejar): d={} for cookie in cookiejar.cookiesForUrl(QtCore.QUrl('http://127.0.0.1')): d[str(cookie.name())] = str(cookie.value()) self.cookies = SimpleCookie(d) def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www.python.org/dev/peps/pep-3333/#environ-variables environ = { 'HTTP_COOKIE': self.cookies.output(header='', sep='; '), # these need retrieving from the cookiejar 'PATH_INFO': '/', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1,0), 'wsgi.url_scheme': 'http', 'wsgi.input': django.test.client.FakePayload(''), 'wsgi.errors': '',#self.errors, # these need retreiving properly 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, } #environ.update(self.defaults) environ.update(request) return environ def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def get(self, path, data={}, **extra): "Construct a GET request" parsed = urlparse.urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': django.utils.http.urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'GET', } r.update(extra) return self.request(**r) def post(self, path, data='', content_type=None, **extra): "Construct a POST request." if content_type is None: raise Exception() post_data = data parsed = urlparse.urlparse(path) r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': django.test.client.FakePayload(post_data), '_body': post_data } r.update(extra) return self.request(**r) def _get_path(self, parsed): # If there are parameters, add them if parsed[3]: return urllib.unquote(parsed[2] + ";" + parsed[3]) else: return urllib.unquote(parsed[2]) def _encode_data(self, data, content_type, ): if content_type is django.test.client.MULTIPART_CONTENT: dataencode = django.test.client.encode_multipart(django.test.client.BOUNDARY, data) return dataencode else: # Encode the content so that the byte representation is correct. match = django.test.client.CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET return django.test.client.smart_str(data, encoding=charset) def login(self, **credentials): """ Sets the Factory to appear as if it has successfully logged into a site. Returns True if login is possible; False if the provided credentials are incorrect, or the user is inactive, or if the sessions framework is not available. """ self.session = None user = authenticate(**credentials) if user and user.is_active\ and 'django.contrib.sessions' in settings.INSTALLED_APPS: engine = import_module(settings.SESSION_ENGINE) # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: request.session = engine.SessionStore() login(request, user) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME self.cookies[session_cookie] = request.session.session_key cookie_data = { 'max-age': None, 'path': '/', 'domain': settings.SESSION_COOKIE_DOMAIN, 'secure': settings.SESSION_COOKIE_SECURE or None, 'expires': None, } self.cookies[session_cookie].update(cookie_data) return True else: return False
def test_saves_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content) # Make sure we got back a voter_device_id we can use self.assertEqual( 'voter_device_id' in json_data, True, "voter_device_id expected in the deviceIdGenerateView json response" ) # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url) json_data2 = json.loads(response2.content) self.assertEqual( 'status' in json_data2, True, "status expected in the voterAddressSaveView json response but not found" ) self.assertEqual( 'voter_device_id' in json_data2, True, "voter_device_id expected in the voterAddressSaveView json response but not found" ) # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data2['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Create a voter address so we can test retrieve response2 = self.client.post( self.voter_address_save_url, {'address': '123 Main Street, Oakland CA 94602'}) json_data2 = json.loads(response2.content) self.assertEqual( 'status' in json_data2, True, "status expected in the voterAddressSaveView json response but not found" ) self.assertEqual( 'voter_device_id' in json_data2, True, "voter_device_id expected in the voterAddressSaveView json response but not found" ) self.assertEqual( 'success' in json_data2, True, "success expected in the voterAddressSaveView json response but not found" ) self.assertEqual( 'address' in json_data2, True, "address expected in the voterAddressSaveView json response but not found" ) # First address save self.assertEqual( json_data2['status'], 'VOTER_ADDRESS_SAVED', "status: {status} (VOTER_ADDRESS_SAVED expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Try and save the voter address again response3 = self.client.post( self.voter_address_save_url, {'address': '321 Main Street, Oakland CA 94602'}) json_data3 = json.loads(response3.content) # First address update self.assertEqual( json_data3['status'], 'VOTER_ADDRESS_SAVED', "status: {status} (VOTER_ADDRESS_SAVED expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( status=json_data3['status'], voter_device_id=json_data3['voter_device_id'])) ####################################### # Try and save the voter address without a post variable response4 = self.client.get(self.voter_address_save_url) json_data4 = json.loads(response4.content) self.assertEqual( 'status' in json_data4, True, "status expected in the voterAddressSaveView json response but not found (no POST var)" ) self.assertEqual( 'voter_device_id' in json_data4, True, "voter_device_id expected in the voterAddressSaveView json response but not found" " (no POST var)") # Test error condition, missing address POST variable self.assertEqual( json_data4['status'], 'MISSING_POST_VARIABLE-ADDRESS', "status: {status} (MISSING_POST_VARIABLE-ADDRESS expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( status=json_data4['status'], voter_device_id=json_data4['voter_device_id'])) ####################################### # Test to make sure the address has been saved in the database response4 = self.client.get(self.voter_address_retrieve_url) json_data4 = json.loads(response4.content) # Are any expected fields missing? self.assertEqual( 'success' in json_data4, True, "success expected in the voterAddressSaveView json response but not found" ) self.assertEqual( 'address' in json_data4, True, "address expected in the voterAddressSaveView json response but not found" ) # A more thorough testing of expected variables is done in test_views_voter_address_retrieve.py # Does address match the value inserted last? self.assertEqual( json_data4['address'], '321 Main Street, Oakland CA 94602', "address: {address} ('321 Main Street, Oakland CA 94602' expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( address=json_data4['address'], voter_device_id=json_data4['voter_device_id']))
class RequestFactory: """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, **defaults): self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www.python.org/dev/peps/pep-3333/#environ-variables environ = { "HTTP_COOKIE": self.cookies.output(header="", sep="; "), "PATH_INFO": "/", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": FakePayload(b""), "wsgi.errors": self.errors, "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, } environ.update(self.defaults) environ.update(request) return environ def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _get_path(self, parsed): path = parsed.path # If there are parameters, add them if parsed.params: path += ";" + parsed.params path = unquote_to_bytes(path) # Replace the behavior where non-ASCII values in the WSGI environ are # arbitrarily decoded with ISO-8859-1. # Refs comment in `get_bytes_from_wsgi()`. return path.decode("iso-8859-1") def get(self, path, data=None, secure=False, **extra): """Construct a GET request.""" data = {} if data is None else data r = { "QUERY_STRING": urlencode(data, doseq=True), } r.update(extra) return self.generic("GET", path, secure=secure, **r) def post(self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, **extra): """Construct a POST request.""" data = {} if data is None else data post_data = self._encode_data(data, content_type) return self.generic("POST", path, post_data, content_type, secure=secure, **extra) def head(self, path, data=None, secure=False, **extra): """Construct a HEAD request.""" data = {} if data is None else data r = { "QUERY_STRING": urlencode(data, doseq=True), } r.update(extra) return self.generic("HEAD", path, secure=secure, **r) def trace(self, path, secure=False, **extra): """Construct a TRACE request.""" return self.generic("TRACE", path, secure=secure, **extra) def options(self, path, data="", content_type="application/octet-stream", secure=False, **extra): "Construct an OPTIONS request." return self.generic("OPTIONS", path, data, content_type, secure=secure, **extra) def put(self, path, data="", content_type="application/octet-stream", secure=False, **extra): """Construct a PUT request.""" return self.generic("PUT", path, data, content_type, secure=secure, **extra) def patch(self, path, data="", content_type="application/octet-stream", secure=False, **extra): """Construct a PATCH request.""" return self.generic("PATCH", path, data, content_type, secure=secure, **extra) def delete(self, path, data="", content_type="application/octet-stream", secure=False, **extra): """Construct a DELETE request.""" return self.generic("DELETE", path, data, content_type, secure=secure, **extra) def generic(self, method, path, data="", content_type="application/octet-stream", secure=False, **extra): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy data = force_bytes(data, settings.DEFAULT_CHARSET) r = { "PATH_INFO": self._get_path(parsed), "REQUEST_METHOD": method, "SERVER_PORT": "443" if secure else "80", "wsgi.url_scheme": "https" if secure else "http", } if data: r.update({ "CONTENT_LENGTH": len(data), "CONTENT_TYPE": content_type, "wsgi.input": FakePayload(data), }) r.update(extra) # If QUERY_STRING is absent or empty, we want to extract it from the URL. if not r.get("QUERY_STRING"): # WSGI requires latin-1 encoded strings. See get_path_info(). query_string = force_bytes(parsed[4]).decode("iso-8859-1") r["QUERY_STRING"] = query_string return self.request(**r)
def test_count_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response0 = self.client.get(self.generate_voter_device_id_url) json_data0 = json.loads(response0.content.decode()) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data0, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data0['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Test for status: VOTER_CREATED response02 = self.client.get(self.voter_create_url) json_data02 = json.loads(response02.content.decode()) self.assertEqual('status' in json_data02, True, "status expected in the voterCreateView json response but not found") self.assertEqual('voter_device_id' in json_data02, True, "voter_device_id expected in the voterCreateView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data02['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format( status=json_data02['status'], voter_device_id=json_data02['voter_device_id'])) ####################################### # Check to see if there is 1 voter - i.e., the viewer response11 = self.client.get(self.voter_count_url) json_data11 = json.loads(response11.content.decode()) self.assertEqual('success' in json_data11, True, "'success' expected in the json response, and not found") self.assertEqual('voter_count' in json_data11, True, "'voter_count' expected in the voterCount json response") self.assertEqual( json_data11['voter_count'], 1, "success: {success} (voter_count '1' expected), voter_count: {voter_count}".format( success=json_data11['success'], voter_count=json_data11['voter_count'])) ####################################### # Add 3 voters so we can check count again voter_manager = VoterManager() email1 = "*****@*****.**" voter_manager.create_voter( email=email1, password="******", ) email2 = "*****@*****.**" voter_manager.create_voter( email=email2, password="******", ) email3 = "*****@*****.**" voter_manager.create_voter( email=email3, password="******", ) ####################################### # Check to see if there are 4 voters response12 = self.client.get(self.voter_count_url) json_data12 = json.loads(response12.content.decode()) self.assertEqual('success' in json_data12, True, "'success' expected in the json response, and not found") self.assertEqual('voter_count' in json_data12, True, "'voter_count' expected in the voterCount json response") self.assertEqual( json_data12['voter_count'], 4, "success: {success} (voter_count '4' expected), voter_count: {voter_count}".format( success=json_data12['success'], voter_count=json_data12['voter_count']))
def test_retrieve_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response01 = self.client.get(self.generate_voter_device_id_url) json_data01 = json.loads(response01.content.decode()) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data01, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data01['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # With a cookie, but without a voter_id in the database, we don't expect valid response response02 = self.client.get(self.voter_ballot_items_retrieve_url) json_data02 = json.loads(response02.content.decode()) self.assertEqual('status' in json_data02, True, "status expected in the json response, and not found") self.assertEqual('voter_device_id' in json_data02, True, "voter_device_id expected in the voterBallotItemsRetrieve json response, and not found") self.assertEqual( json_data02['status'], 'VALID_VOTER_ID_MISSING', "status: {status} (VALID_VOTER_ID_MISSING expected), " "voter_device_id: {voter_device_id}".format( status=json_data02['status'], voter_device_id=json_data02['voter_device_id'])) ####################################### # Create a voter so we can test retrieve response03 = self.client.get(self.voter_create_url) json_data03 = json.loads(response03.content.decode()) self.assertEqual('status' in json_data03, True, "status expected in the voterCreateView json response but not found") self.assertEqual('voter_device_id' in json_data03, True, "voter_device_id expected in the voterCreateView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data03['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format( status=json_data03['status'], voter_device_id=json_data03['voter_device_id'])) ####################################### # Test the response with google_civic_election_id in cookie cookies["google_civic_election_id"] = 4162 self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Test the response before any ballot_items exist response05 = self.client.get(self.voter_ballot_items_retrieve_url) json_data05 = json.loads(response05.content.decode()) self.assertEqual('status' in json_data05, True, "status expected in the voterBallotItemsRetrieve json response but not found") self.assertEqual('success' in json_data05, True, "success expected in the voterBallotItemsRetrieve json response but not found") self.assertEqual('voter_device_id' in json_data05, True, "voter_device_id expected in the voterBallotItemsRetrieve json response but not found") self.assertEqual('ballot_item_list' in json_data05, True, "ballot_item_list expected in the voterBallotItemsRetrieve json response but not found") self.assertEqual( json_data05['status'], 'NO_BALLOT_ITEMS_FOUND_0', "status: {status} (NO_BALLOT_ITEMS_FOUND_0 expected), voter_device_id: {voter_device_id}".format( status=json_data05['status'], voter_device_id=json_data05['voter_device_id']))
def test_samesite(self): c = SimpleCookie('name=value; samesite=lax; httponly') self.assertEqual(c['name']['samesite'], 'lax') self.assertIn('SameSite=lax', c.output())
def translate_request_args(self, request): #pylint:disable=too-many-statements requests_args = {'allow_redirects': False, 'headers': {}} cookies = SimpleCookie() try: for key, value in six.iteritems(request.COOKIES): cookies[key] = value if (self.app.session_backend and self.app.session_backend != self.app.JWT_SESSION_BACKEND): cookies[SESSION_COOKIE_NAME] = self.session_cookie_string else: # Cookies, as opposed to Authorization header have multiple # purposes, so we keep the SESSION_COOKIE_NAME (if exists) # regardless of the backend used to transport the proxy session. pass except http_cookies.CookieError as err: # Some is messing up with the 'Cookie' header. This sometimes # happen with bots trying to set 'Max-Age' or other reserved words. raise DisallowedCookieName(str(err)) #pylint: disable=maybe-no-member # Something changed in `SimpleCookie.output` that creates an invalid # cookie string starting with a spacel or there are more strident # checks in the requests module (2.11.1) that prevents passing # a cookie string starting with a space. cookie_string = cookies.output(header='', sep=';').strip() # Retrieve the HTTP headers from a WSGI environment dictionary. See # https://docs.djangoapp.com/en/dev/ref/request-response/\ # #django.http.HttpRequest.META headers = {} for key, value in six.iteritems(request.META): key_upper = key.upper() if key_upper.startswith('HTTP_'): key_upper = key_upper[5:].replace('_', '-') if key_upper == 'AUTHORIZATION': # We donot want to inadvertently forward the credentials # to connect to the proxy when the session backend is # using cookies. pass if key_upper == 'COOKIE': headers[key_upper] = cookie_string else: # Some servers don't like when you send the requesting host # through but we do anyway. That's how the nginx reverse # proxy is configured as well. headers[key_upper] = value elif key_upper in ('CONTENT_TYPE', 'CONTENT_LENGTH'): headers[key.replace('_', '-')] = value site = RequestSite(request) if 'HOST' not in headers: headers.update({'HOST': site.domain}) if 'X-FORWARDED-FOR' not in headers: headers.update({'X-FORWARDED-FOR': site.domain}) if 'X-REAL-IP' not in headers: headers.update( {'X-REAL-IP': request.META.get('REMOTE_ADDR', None)}) if 'COOKIE' not in headers: headers.update({'COOKIE': cookie_string}) if self.app.session_backend and \ self.app.session_backend == self.app.JWT_SESSION_BACKEND: jwt_token = self.session_jwt_string headers.update({'AUTHORIZATION': 'Bearer %s' % jwt_token}) if request.META.get('CONTENT_TYPE', '').startswith('multipart/form-data'): if request.FILES: requests_args['files'] = request.FILES data = {} for key, val in six.iteritems(request.POST): data.update({key: val}) requests_args['data'] = data else: requests_args['data'] = request.body params = request.GET.copy() # If there's a content-length header from Django, it's probably # in all-caps and requests might not notice it, so just remove it. for key in list(headers.keys()): if key.lower() == 'content-length': del headers[key] elif key.lower() == 'content-type' and request.META.get( 'CONTENT_TYPE', '').startswith('multipart/form-data'): del headers[key] requests_args['headers'] = headers requests_args['params'] = params return requests_args
def test_encode(self): """Semicolons and commas are encoded.""" c = SimpleCookie() c['test'] = "An,awkward;value" self.assertNotIn(";", c.output().rstrip(';')) # IE compat self.assertNotIn(",", c.output().rstrip(';')) # Safari compat
class RequestFactory(object): """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, **defaults): self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www.python.org/dev/peps/pep-3333/#environ-variables environ = { 'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': '/', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.input': FakePayload(b''), 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, } environ.update(self.defaults) environ.update(request) return environ def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data( self, data, content_type, ): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET return smart_bytes(data, encoding=charset) def _get_path(self, parsed): # If there are parameters, add them if parsed[3]: return unquote(parsed[2] + ";" + parsed[3]) else: return unquote(parsed[2]) def get(self, path, data={}, **extra): "Construct a GET request." parsed = urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'GET', } r.update(extra) return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Construct a POST request." post_data = self._encode_data(data, content_type) parsed = urlparse(path) r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(post_data), } r.update(extra) return self.request(**r) def head(self, path, data={}, **extra): "Construct a HEAD request." parsed = urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'HEAD', } r.update(extra) return self.request(**r) def options(self, path, data='', content_type='application/octet-stream', **extra): "Construct an OPTIONS request." return self.generic('OPTIONS', path, data, content_type, **extra) def put(self, path, data='', content_type='application/octet-stream', **extra): "Construct a PUT request." return self.generic('PUT', path, data, content_type, **extra) def delete(self, path, data='', content_type='application/octet-stream', **extra): "Construct a DELETE request." return self.generic('DELETE', path, data, content_type, **extra) def generic(self, method, path, data='', content_type='application/octet-stream', **extra): parsed = urlparse(path) data = smart_bytes(data, settings.DEFAULT_CHARSET) r = { 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': method, } if data: r.update({ 'CONTENT_LENGTH': len(data), 'CONTENT_TYPE': content_type, 'wsgi.input': FakePayload(data), }) r.update(extra) return self.request(**r)
def test_retrieve_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content) # Make sure we got back a voter_device_id we can use self.assertEqual( 'voter_device_id' in json_data, True, "voter_device_id expected in the deviceIdGenerateView json response" ) # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url) json_data2 = json.loads(response2.content) self.assertEqual( 'status' in json_data2, True, "status expected in the voterCreateView json response but not found" ) self.assertEqual( 'voter_device_id' in json_data2, True, "voter_device_id expected in the voterCreateView json response but not found" ) # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data2['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}" .format(status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Test for id, first_name, last_name, email response3 = self.client.get(self.voter_retrieve_url) json_data3 = json.loads(response3.content) for one_voter in json_data3: self.assertEqual( 'id' in one_voter, True, "id expected in the voterRetrieveView json response but not found" ) self.assertEqual( 'first_name' in one_voter, True, "first_name expected in the voterRetrieveView json response but not found" ) self.assertEqual( 'last_name' in one_voter, True, "last_name expected in the voterRetrieveView json response but not found" ) self.assertEqual( 'email' in one_voter, True, "email expected in the voterRetrieveView json response but not found" )
class RequestFactory(object): """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, **defaults): self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www.python.org/dev/peps/pep-3333/#environ-variables environ = { 'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': str('/'), 'REMOTE_ADDR': str('127.0.0.1'), 'REQUEST_METHOD': str('GET'), 'SCRIPT_NAME': str(''), 'SERVER_NAME': str('testserver'), 'SERVER_PORT': str('80'), 'SERVER_PROTOCOL': str('HTTP/1.1'), 'wsgi.version': (1, 0), 'wsgi.url_scheme': str('http'), 'wsgi.input': FakePayload(b''), 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, } environ.update(self.defaults) environ.update(request) return environ def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _get_path(self, parsed): path = force_str(parsed[2]) # If there are parameters, add them if parsed[3]: path += str(";") + force_str(parsed[3]) path = uri_to_iri(path).encode(UTF_8) # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily # decoded with ISO-8859-1. We replicate this behavior here. # Refs comment in `get_bytes_from_wsgi()`. return path.decode(ISO_8859_1) if six.PY3 else path def get(self, path, data=None, secure=False, **extra): "Construct a GET request." data = {} if data is None else data r = { 'QUERY_STRING': urlencode(data, doseq=True), } r.update(extra) return self.generic('GET', path, secure=secure, **r) def post(self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, **extra): "Construct a POST request." data = {} if data is None else data post_data = self._encode_data(data, content_type) return self.generic('POST', path, post_data, content_type, secure=secure, **extra) def head(self, path, data=None, secure=False, **extra): "Construct a HEAD request." data = {} if data is None else data r = { 'QUERY_STRING': urlencode(data, doseq=True), } r.update(extra) return self.generic('HEAD', path, secure=secure, **r) def trace(self, path, secure=False, **extra): "Construct a TRACE request." return self.generic('TRACE', path, secure=secure, **extra) def options(self, path, data='', content_type='application/octet-stream', secure=False, **extra): "Construct an OPTIONS request." return self.generic('OPTIONS', path, data, content_type, secure=secure, **extra) def put(self, path, data='', content_type='application/octet-stream', secure=False, **extra): "Construct a PUT request." return self.generic('PUT', path, data, content_type, secure=secure, **extra) def patch(self, path, data='', content_type='application/octet-stream', secure=False, **extra): "Construct a PATCH request." return self.generic('PATCH', path, data, content_type, secure=secure, **extra) def delete(self, path, data='', content_type='application/octet-stream', secure=False, **extra): "Construct a DELETE request." return self.generic('DELETE', path, data, content_type, secure=secure, **extra) def generic(self, method, path, data='', content_type='application/octet-stream', secure=False, **extra): """Constructs an arbitrary HTTP request.""" parsed = urlparse(force_str(path)) data = force_bytes(data, settings.DEFAULT_CHARSET) r = { 'PATH_INFO': self._get_path(parsed), 'REQUEST_METHOD': str(method), 'SERVER_PORT': str('443') if secure else str('80'), 'wsgi.url_scheme': str('https') if secure else str('http'), } if data: r.update({ 'CONTENT_LENGTH': len(data), 'CONTENT_TYPE': str(content_type), 'wsgi.input': FakePayload(data), }) r.update(extra) # If QUERY_STRING is absent or empty, we want to extract it from the URL. if not r.get('QUERY_STRING'): query_string = force_bytes(parsed[4]) # WSGI requires latin-1 encoded strings. See get_path_info(). if six.PY3: query_string = query_string.decode('iso-8859-1') r['QUERY_STRING'] = query_string return self.request(**r)
def test_create_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content) # Make sure we got back a voter_device_id we can use self.assertEqual( 'voter_device_id' in json_data, True, "voter_device_id expected in the deviceIdGenerateView json response" ) # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Test for status: VOTER_CREATED response2 = self.client.get(self.voter_create_url) json_data2 = json.loads(response2.content) self.assertEqual( 'status' in json_data2, True, "status expected in the voterCreateView json response but not found" ) self.assertEqual( 'voter_device_id' in json_data2, True, "voter_device_id expected in the voterCreateView json response but not found" ) # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data2['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}" .format(status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Test for status: VOTER_ALREADY_EXISTS response3 = self.client.get(self.voter_create_url) json_data3 = json.loads(response3.content) self.assertEqual( 'status' in json_data3, True, "status expected in the voterCreateView json response but not found" ) self.assertEqual( 'voter_device_id' in json_data3, True, "voter_device_id expected in the voterCreateView json response but not found" ) # Try reusing the same voter_device_id self.assertEqual( json_data3['status'], 'VOTER_ALREADY_EXISTS', "status: {status} (VOTER_ALREADY_EXISTS expected), voter_device_id: {voter_device_id}" .format(status=json_data3['status'], voter_device_id=json_data3['voter_device_id']))
def test_samesite(self): c = SimpleCookie("name=value; samesite=lax; httponly") self.assertEqual(c["name"]["samesite"], "lax") self.assertIn("SameSite=lax", c.output())
class RequestFactory(object): """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, **defaults): self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www.python.org/dev/peps/pep-3333/#environ-variables environ = { 'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': '/', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.input': FakePayload(b''), 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, } environ.update(self.defaults) environ.update(request) return environ def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type, ): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _get_path(self, parsed): # If there are parameters, add them if parsed[3]: return unquote(parsed[2] + ";" + parsed[3]) else: return unquote(parsed[2]) def get(self, path, data={}, **extra): "Construct a GET request." parsed = urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'GET', } r.update(extra) return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Construct a POST request." post_data = self._encode_data(data, content_type) parsed = urlparse(path) r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(post_data), } r.update(extra) return self.request(**r) def head(self, path, data={}, **extra): "Construct a HEAD request." parsed = urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'HEAD', } r.update(extra) return self.request(**r) def options(self, path, data='', content_type='application/octet-stream', **extra): "Construct an OPTIONS request." return self.generic('OPTIONS', path, data, content_type, **extra) def put(self, path, data='', content_type='application/octet-stream', **extra): "Construct a PUT request." return self.generic('PUT', path, data, content_type, **extra) def delete(self, path, data='', content_type='application/octet-stream', **extra): "Construct a DELETE request." return self.generic('DELETE', path, data, content_type, **extra) def generic(self, method, path, data='', content_type='application/octet-stream', **extra): parsed = urlparse(path) data = force_bytes(data, settings.DEFAULT_CHARSET) r = { 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': method, } if data: r.update({ 'CONTENT_LENGTH': len(data), 'CONTENT_TYPE': content_type, 'wsgi.input': FakePayload(data), }) r.update(extra) return self.request(**r)
def test_count_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response0 = self.client.get(self.generate_voter_device_id_url) json_data0 = json.loads(response0.content) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data0, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data0['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Test for status: VOTER_CREATED response02 = self.client.get(self.voter_create_url) json_data02 = json.loads(response02.content) self.assertEqual('status' in json_data02, True, "status expected in the voterCreateView json response but not found") self.assertEqual('voter_device_id' in json_data02, True, "voter_device_id expected in the voterCreateView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data02['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format( status=json_data02['status'], voter_device_id=json_data02['voter_device_id'])) ####################################### # Check to see if there is 1 voter - i.e., the viewer response11 = self.client.get(self.voter_count_url) json_data11 = json.loads(response11.content) self.assertEqual('success' in json_data11, True, "'success' expected in the json response, and not found") self.assertEqual('voter_count' in json_data11, True, "'voter_count' expected in the organizationCount json response") self.assertEqual( json_data11['voter_count'], 1, "success: {success} (voter_count '1' expected), voter_count: {voter_count}".format( success=json_data11['success'], voter_count=json_data11['voter_count'])) ####################################### # Check to see if there are 0 organizations response12 = self.client.get(self.organization_count_url) json_data12 = json.loads(response12.content) self.assertEqual('success' in json_data12, True, "'success' expected in the json response, and not found") self.assertEqual('organization_count' in json_data12, True, "'organization_count' expected in the organizationCount json response") self.assertEqual( json_data12['organization_count'], 0, "success: {success} (organization_count '0' expected), organization_count: {organization_count}".format( success=json_data12['success'], organization_count=json_data12['organization_count'])) ####################################### # Add 3 organizations so we can check count again organization1 = Organization.objects.create_organization( organization_name="Org1", organization_website="www.org1.org", organization_twitter="org1", ) organization2 = Organization.objects.create_organization( organization_name="Org2", organization_website="www.org2.org", organization_twitter="org2", ) organization3 = Organization.objects.create_organization( organization_name="Org3", organization_website="www.org3.org", organization_twitter="org3", ) ####################################### # Check to see if there are 3 organizations response22 = self.client.get(self.organization_count_url) json_data22 = json.loads(response22.content) self.assertEqual('success' in json_data22, True, "'success' expected in the json response, and not found") self.assertEqual('organization_count' in json_data22, True, "'organization_count' expected in the organizationCount json response") self.assertEqual( json_data22['organization_count'], 3, "success: {success} (organization_count '3' expected), organization_count: {organization_count}".format( success=json_data22['success'], organization_count=json_data22['organization_count'])) ####################################### # Remove data for 3 organizations Organization.objects.delete_organization(organization_id=organization1.id) Organization.objects.delete_organization(organization_id=organization2.id) Organization.objects.delete_organization(organization_id=organization3.id) ####################################### # Check to see if there are 0 organizations response23 = self.client.get(self.organization_count_url) json_data23 = json.loads(response23.content) self.assertEqual('success' in json_data23, True, "'success' expected in the json response, and not found") self.assertEqual('organization_count' in json_data23, True, "'organization_count' expected in the organizationCount json response") self.assertEqual( json_data23['organization_count'], 0, "success: {success} (organization_count '0' expected - 2nd pass), " "organization_count: {organization_count}".format( success=json_data23['success'], organization_count=json_data23['organization_count']))
def translate_request_args(self, request): requests_args = {'allow_redirects': False, 'headers': {}} cookies = SimpleCookie() try: for key, value in six.iteritems(request.COOKIES): cookies[key] = value if (self.app.session_backend and self.app.session_backend != self.app.JWT_SESSION_BACKEND): cookies[SESSION_COOKIE_NAME] = self.session_cookie_string except http_cookies.CookieError as err: # Some is messing up with the 'Cookie' header. This sometimes # happen with bots trying to set 'Max-Age' or other reserved words. raise DisallowedCookieName(str(err)) #pylint: disable=maybe-no-member # Something changed in `SimpleCookie.output` that creates an invalid # cookie string starting with a spacel or there are more strident # checks in the requests module (2.11.1) that prevents passing # a cookie string starting with a space. cookie_string = cookies.output(header='', sep=';').strip() # Retrieve the HTTP headers from a WSGI environment dictionary. See # https://docs.djangoapp.com/en/dev/ref/request-response/\ # #django.http.HttpRequest.META headers = {} for key, value in six.iteritems(request.META): key_upper = key.upper() if key_upper.startswith('HTTP_'): key_upper = key_upper[5:].replace('_', '-') if key_upper == 'COOKIE': headers[key_upper] = cookie_string else: # Some servers don't like when you send the requesting host # through but we do anyway. That's how the nginx reverse # proxy is configured as well. headers[key_upper] = value elif key_upper in ('CONTENT_TYPE', 'CONTENT_LENGTH'): headers[key.replace('_', '-')] = value site = RequestSite(request) if 'HOST' not in headers: headers.update({'HOST': site.domain}) if 'X-FORWARDED-FOR' not in headers: headers.update({'X-FORWARDED-FOR': site.domain}) if 'X-REAL-IP' not in headers: headers.update({'X-REAL-IP': request.META.get('REMOTE_ADDR', None)}) if 'COOKIE' not in headers: headers.update({'COOKIE': cookie_string}) if self.app.session_backend and \ self.app.session_backend == self.app.JWT_SESSION_BACKEND: jwt_token = self.session_jwt_string headers.update({'AUTHORIZATION': 'Bearer %s' % jwt_token}) if request.META.get( 'CONTENT_TYPE', '').startswith('multipart/form-data'): if request.FILES: requests_args['files'] = request.FILES data = {} for key, val in six.iteritems(request.POST): data.update({key:val}) requests_args['data'] = data else: requests_args['data'] = request.body params = request.GET.copy() # If there's a content-length header from Django, it's probably # in all-caps and requests might not notice it, so just remove it. for key in list(headers.keys()): if key.lower() == 'content-length': del headers[key] elif key.lower() == 'content-type' and request.META.get( 'CONTENT_TYPE', '').startswith('multipart/form-data'): del headers[key] requests_args['headers'] = headers requests_args['params'] = params return requests_args
def test_retrieve_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url) json_data2 = json.loads(response2.content) self.assertEqual('status' in json_data2, True, "status expected in the voterAddressRetrieveView json response but not found") self.assertEqual('voter_device_id' in json_data2, True, "voter_device_id expected in the voterAddressRetrieveView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data2['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected in voterAddressRetrieveView), " "voter_device_id: {voter_device_id}".format( status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Create a voter address so we can test retrieve response3 = self.client.post(self.voter_address_save_url, {'address': '123 Main Street, Oakland CA 94602'}) json_data3 = json.loads(response3.content) self.assertEqual('status' in json_data3, True, "status expected in the voterAddressRetrieveView json response but not found") self.assertEqual('voter_device_id' in json_data3, True, "voter_device_id expected in the voterAddressRetrieveView json response but not found") # First address save self.assertEqual( json_data3['status'], 'VOTER_ADDRESS_SAVED', "status: {status} (VOTER_ADDRESS_SAVED expected in voterAddressRetrieveView), " "voter_device_id: {voter_device_id}".format( status=json_data3['status'], voter_device_id=json_data3['voter_device_id'])) ####################################### # Test for expected response variables response4 = self.client.get(self.voter_address_retrieve_url) json_data4 = json.loads(response4.content) # Are any expected fields missing? self.assertEqual('success' in json_data4, True, "success expected in the voterAddressRetrieveView json response but not found") self.assertEqual('address' in json_data4, True, "address expected in the voterAddressRetrieveView json response but not found") self.assertEqual('address_type' in json_data4, True, "address_type expected in the voterAddressRetrieveView json response but not found") self.assertEqual('latitude' in json_data4, True, "latitude expected in the voterAddressRetrieveView json response but not found") self.assertEqual('longitude' in json_data4, True, "longitude expected in the voterAddressRetrieveView json response but not found") self.assertEqual('normalized_line1' in json_data4, True, "normalized_line1 expected in the voterAddressRetrieveView json response but not found") self.assertEqual('normalized_line2' in json_data4, True, "normalized_line2 expected in the voterAddressRetrieveView json response but not found") self.assertEqual('normalized_city' in json_data4, True, "normalized_city expected in the voterAddressRetrieveView json response but not found") self.assertEqual('normalized_state' in json_data4, True, "normalized_state expected in the voterAddressRetrieveView json response but not found") self.assertEqual('normalized_zip' in json_data4, True, "normalized_zip expected in the voterAddressRetrieveView json response but not found") # Does address match the value inserted last? self.assertEqual( json_data4['address'], '123 Main Street, Oakland CA 94602', "address: {address} ('123 Main Street, Oakland CA 94602' expected in voterAddressRetrieveView), " "voter_device_id: {voter_device_id}".format( address=json_data4['address'], voter_device_id=json_data4['voter_device_id']))
class RequestFactory(object): """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, **defaults): self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www.python.org/dev/peps/pep-3333/#environ-variables environ = { "HTTP_COOKIE": self.cookies.output(header="", sep="; "), "PATH_INFO": str("/"), "REMOTE_ADDR": str("127.0.0.1"), "REQUEST_METHOD": str("GET"), "SCRIPT_NAME": str(""), "SERVER_NAME": str("testserver"), "SERVER_PORT": str("80"), "SERVER_PROTOCOL": str("HTTP/1.1"), "wsgi.version": (1, 0), "wsgi.url_scheme": str("http"), "wsgi.input": FakePayload(b""), "wsgi.errors": self.errors, "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, } environ.update(self.defaults) environ.update(request) return environ def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _get_path(self, parsed): path = force_str(parsed[2]) # If there are parameters, add them if parsed[3]: path += str(";") + force_str(parsed[3]) path = unquote(path) # WSGI requires latin-1 encoded strings. See get_path_info(). if six.PY3: path = path.encode("utf-8").decode("iso-8859-1") return path def get(self, path, data={}, **extra): "Construct a GET request." parsed = urlparse(path) query_string = urlencode(data, doseq=True) or force_str(parsed[4]) if six.PY3: query_string = query_string.encode("utf-8").decode("iso-8859-1") r = {"PATH_INFO": self._get_path(parsed), "QUERY_STRING": query_string, "REQUEST_METHOD": str("GET")} r.update(extra) return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Construct a POST request." post_data = self._encode_data(data, content_type) parsed = urlparse(path) query_string = force_str(parsed[4]) if six.PY3: query_string = query_string.encode("utf-8").decode("iso-8859-1") r = { "CONTENT_LENGTH": len(post_data), "CONTENT_TYPE": content_type, "PATH_INFO": self._get_path(parsed), "QUERY_STRING": query_string, "REQUEST_METHOD": str("POST"), "wsgi.input": FakePayload(post_data), } r.update(extra) return self.request(**r) def head(self, path, data={}, **extra): "Construct a HEAD request." parsed = urlparse(path) query_string = urlencode(data, doseq=True) or force_str(parsed[4]) if six.PY3: query_string = query_string.encode("utf-8").decode("iso-8859-1") r = {"PATH_INFO": self._get_path(parsed), "QUERY_STRING": query_string, "REQUEST_METHOD": str("HEAD")} r.update(extra) return self.request(**r) def options(self, path, data="", content_type="application/octet-stream", **extra): "Construct an OPTIONS request." return self.generic("OPTIONS", path, data, content_type, **extra) def put(self, path, data="", content_type="application/octet-stream", **extra): "Construct a PUT request." return self.generic("PUT", path, data, content_type, **extra) def patch(self, path, data="", content_type="application/octet-stream", **extra): "Construct a PATCH request." return self.generic("PATCH", path, data, content_type, **extra) def delete(self, path, data="", content_type="application/octet-stream", **extra): "Construct a DELETE request." return self.generic("DELETE", path, data, content_type, **extra) def generic(self, method, path, data="", content_type="application/octet-stream", **extra): parsed = urlparse(path) data = force_bytes(data, settings.DEFAULT_CHARSET) r = {"PATH_INFO": self._get_path(parsed), "REQUEST_METHOD": str(method)} if data: r.update({"CONTENT_LENGTH": len(data), "CONTENT_TYPE": str(content_type), "wsgi.input": FakePayload(data)}) r.update(extra) # If QUERY_STRING is absent or empty, we want to extract it from the URL. if not r.get("QUERY_STRING"): query_string = force_bytes(parsed[4]) # WSGI requires latin-1 encoded strings. See get_path_info(). if six.PY3: query_string = query_string.decode("iso-8859-1") r["QUERY_STRING"] = query_string return self.request(**r)
def test_retrieve_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content) # Make sure we got back a voter_device_id we can use self.assertEqual( 'voter_device_id' in json_data, True, "voter_device_id expected in the deviceIdGenerateView json response" ) # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url) json_data2 = json.loads(response2.content) self.assertEqual( 'status' in json_data2, True, "status expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'voter_device_id' in json_data2, True, "voter_device_id expected in the voterAddressRetrieveView json response but not found" ) # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data2['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected in voterAddressRetrieveView), " "voter_device_id: {voter_device_id}".format( status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Create a voter address so we can test retrieve response3 = self.client.post( self.voter_address_save_url, {'address': '123 Main Street, Oakland CA 94602'}) json_data3 = json.loads(response3.content) self.assertEqual( 'status' in json_data3, True, "status expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'voter_device_id' in json_data3, True, "voter_device_id expected in the voterAddressRetrieveView json response but not found" ) # First address save self.assertEqual( json_data3['status'], 'VOTER_ADDRESS_SAVED', "status: {status} (VOTER_ADDRESS_SAVED expected in voterAddressRetrieveView), " "voter_device_id: {voter_device_id}".format( status=json_data3['status'], voter_device_id=json_data3['voter_device_id'])) ####################################### # Test for expected response variables response4 = self.client.get(self.voter_address_retrieve_url) json_data4 = json.loads(response4.content) # Are any expected fields missing? self.assertEqual( 'success' in json_data4, True, "success expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'address' in json_data4, True, "address expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'address_type' in json_data4, True, "address_type expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'latitude' in json_data4, True, "latitude expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'longitude' in json_data4, True, "longitude expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'normalized_line1' in json_data4, True, "normalized_line1 expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'normalized_line2' in json_data4, True, "normalized_line2 expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'normalized_city' in json_data4, True, "normalized_city expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'normalized_state' in json_data4, True, "normalized_state expected in the voterAddressRetrieveView json response but not found" ) self.assertEqual( 'normalized_zip' in json_data4, True, "normalized_zip expected in the voterAddressRetrieveView json response but not found" ) # Does address match the value inserted last? self.assertEqual( json_data4['address'], '123 Main Street, Oakland CA 94602', "address: {address} ('123 Main Street, Oakland CA 94602' expected in voterAddressRetrieveView), " "voter_device_id: {voter_device_id}".format( address=json_data4['address'], voter_device_id=json_data4['voter_device_id']))
class RequestFactory(object): """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, **defaults): self.defaults = defaults self.cookies = SimpleCookie() self.errors = StringIO() def _base_environ(self, **request): """ The base environment for a request. """ environ = { 'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': '/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, } environ.update(self.defaults) environ.update(request) return environ def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _get_path(self, parsed): # If there are parameters, add them if parsed[3]: return urllib.unquote(parsed[2] + ";" + parsed[3]) else: return urllib.unquote(parsed[2]) def get(self, path, data={}, **extra): "Construct a GET request" parsed = urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'GET', 'wsgi.input': FakePayload('') } r.update(extra) return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Construct a POST request." if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET post_data = smart_str(data, encoding=charset) parsed = urlparse(path) r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(post_data), } r.update(extra) return self.request(**r) def head(self, path, data={}, **extra): "Construct a HEAD request." parsed = urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'HEAD', 'wsgi.input': FakePayload('') } r.update(extra) return self.request(**r) def options(self, path, data={}, **extra): "Constrict an OPTIONS request" parsed = urlparse(path) r = { 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'OPTIONS', 'wsgi.input': FakePayload('') } r.update(extra) return self.request(**r) def put(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Construct a PUT request." if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: post_data = data # Make `data` into a querystring only if it's not already a string. If # it is a string, we'll assume that the caller has already encoded it. query_string = None if not isinstance(data, basestring): query_string = urlencode(data, doseq=True) parsed = urlparse(path) r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': query_string or parsed[4], 'REQUEST_METHOD': 'PUT', 'wsgi.input': FakePayload(post_data), } r.update(extra) return self.request(**r) def delete(self, path, data={}, **extra): "Construct a DELETE request." parsed = urlparse(path) r = { 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'DELETE', 'wsgi.input': FakePayload('') } r.update(extra) return self.request(**r)
from __future__ import unicode_literals
def test_saves_with_cookie(self): """ Test the various cookie states :return: """ ####################################### # Generate the voter_device_id cookie response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content) # Make sure we got back a voter_device_id we can use self.assertEqual('voter_device_id' in json_data, True, "voter_device_id expected in the deviceIdGenerateView json response") # Now save the retrieved voter_device_id in a mock cookie cookies = SimpleCookie() cookies["voter_device_id"] = json_data['voter_device_id'] self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; ')) ####################################### # Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url) json_data2 = json.loads(response2.content) self.assertEqual('status' in json_data2, True, "status expected in the voterAddressSaveView json response but not found") self.assertEqual('voter_device_id' in json_data2, True, "voter_device_id expected in the voterAddressSaveView json response but not found") # With a brand new voter_device_id, a new voter record should be created self.assertEqual( json_data2['status'], 'VOTER_CREATED', "status: {status} (VOTER_CREATED expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Create a voter address so we can test retrieve response2 = self.client.post(self.voter_address_save_url, {'address': '123 Main Street, Oakland CA 94602'}) json_data2 = json.loads(response2.content) self.assertEqual('status' in json_data2, True, "status expected in the voterAddressSaveView json response but not found") self.assertEqual('voter_device_id' in json_data2, True, "voter_device_id expected in the voterAddressSaveView json response but not found") self.assertEqual('success' in json_data2, True, "success expected in the voterAddressSaveView json response but not found") self.assertEqual('address' in json_data2, True, "address expected in the voterAddressSaveView json response but not found") # First address save self.assertEqual( json_data2['status'], 'VOTER_ADDRESS_SAVED', "status: {status} (VOTER_ADDRESS_SAVED expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( status=json_data2['status'], voter_device_id=json_data2['voter_device_id'])) ####################################### # Try and save the voter address again response3 = self.client.post(self.voter_address_save_url, {'address': '321 Main Street, Oakland CA 94602'}) json_data3 = json.loads(response3.content) # First address update self.assertEqual( json_data3['status'], 'VOTER_ADDRESS_SAVED', "status: {status} (VOTER_ADDRESS_SAVED expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( status=json_data3['status'], voter_device_id=json_data3['voter_device_id'])) ####################################### # Try and save the voter address without a post variable response4 = self.client.get(self.voter_address_save_url) json_data4 = json.loads(response4.content) self.assertEqual('status' in json_data4, True, "status expected in the voterAddressSaveView json response but not found (no POST var)") self.assertEqual('voter_device_id' in json_data4, True, "voter_device_id expected in the voterAddressSaveView json response but not found" " (no POST var)") # Test error condition, missing address POST variable self.assertEqual( json_data4['status'], 'MISSING_POST_VARIABLE-ADDRESS', "status: {status} (MISSING_POST_VARIABLE-ADDRESS expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( status=json_data4['status'], voter_device_id=json_data4['voter_device_id'])) ####################################### # Test to make sure the address has been saved in the database response4 = self.client.get(self.voter_address_retrieve_url) json_data4 = json.loads(response4.content) # Are any expected fields missing? self.assertEqual('success' in json_data4, True, "success expected in the voterAddressSaveView json response but not found") self.assertEqual('address' in json_data4, True, "address expected in the voterAddressSaveView json response but not found") # A more thorough testing of expected variables is done in test_views_voter_address_retrieve.py # Does address match the value inserted last? self.assertEqual( json_data4['address'], '321 Main Street, Oakland CA 94602', "address: {address} ('321 Main Street, Oakland CA 94602' expected in voterAddressSaveView), " "voter_device_id: {voter_device_id}".format( address=json_data4['address'], voter_device_id=json_data4['voter_device_id']))