class BaseFuncTestCase(TestCase): """ Utitlity methods to pull stuff out of session etc. """ def setUp(self): """ Turn of HOSTS check and setup reusable attributes """ self.settings = getattr(settings, "COOKIELESS", DEFAULT_SETTINGS) self.settings["HOSTS"] = [] self.browser = Client() self.browser.request() self.engine = import_module(settings.SESSION_ENGINE) self.crypt_sesh = CryptSession() self.factory = RequestFactory() self.skey = settings.SESSION_COOKIE_NAME # This is a bit crap - because matching is fragile and also its # reused to split up and grab the session id - TODO: replace with regex self.hidden = '<input type="hidden" name="%s" value="' % self.skey def get_session(self, response, url="/", agent="unknown browser"): """ Extract id from response and retrieve session """ # post or get parts = "" if not response.content: print("RESPONSE FAILED: {}".format(response.__class__)) else: content = response.content.decode() if self.hidden in content: splitter = self.hidden else: splitter = "%s=" % self.skey parts = content.split(splitter, 1) session_key = "" if len(parts) > 1: parts = parts[1].split('"', 1) session_id = parts[0] request = self.factory.get(url, REMOTE_ADDR="127.0.0.1", HTTP_USER_AGENT=agent) try: session_key = self.crypt_sesh.decrypt(request, session_id) except: # Silently start new session in case fake session_id format causes error pass else: session_id = "" try: session = self.engine.SessionStore(session_key) except: session = self.engine.SessionStore() return session, session_id
class CryptTestCase(unittest.TestCase): """ Check the session id encryption is working OK """ # urls = 'django-cookieless.test_urls' def setUp(self): """ Get a session and a crypt_session """ self.settings = getattr(settings, "COOKIELESS", DEFAULT_SETTINGS) self.engine = import_module(settings.SESSION_ENGINE) self.crypt_sesh = CryptSession() self.factory = RequestFactory() def crypt_ok(self, request=None): """ Check encryption works with various settings """ if not request: request = self.factory.get("/") session = self.engine.SessionStore() session.create() self.assertNotEqual(session.session_key, None) sessionid = self.crypt_sesh.encrypt(request, session.session_key) session_key = self.crypt_sesh.decrypt(request, sessionid) return session.session_key, session_key def test_default(self): self.settings["CLIENT_ID"] = False self.settings["HOSTS"] = [] keys = self.crypt_ok() self.assertEqual(*keys) def test_client_id(self): self.settings["CLIENT_ID"] = False self.settings["HOSTS"] = [] keys = self.crypt_ok() self.assertEqual(*keys) def test_hosts_check(self): self.settings["CLIENT_ID"] = False request = self.factory.get("/") request.META["HTTP_REFERER"] = "http://localhost:12345/foobar" settings.COOKIELESS_HOSTS = ["localhost"] keys = self.crypt_ok(request) self.assertEqual(*keys) def test_test_client(self): """Cookieless can cause fail of test browser so check it""" self.browser = Client() self.browser.request() self.assertTrue(self.browser)
class BaseFuncTestCase(TestCase): """ Utitlity methods to pull stuff out of session etc. """ def setUp(self): """ Turn of HOSTS check and setup reusable attributes """ self.settings = getattr(settings, 'COOKIELESS', DEFAULT_SETTINGS) self.settings['HOSTS'] = [] self.browser = Client() self.browser.request() self.engine = import_module(settings.SESSION_ENGINE) self.crypt_sesh = CryptSession() self.factory = RequestFactory() self.skey = settings.SESSION_COOKIE_NAME # This is a bit crap - because matching is fragile and also its # reused to split up and grab the session id - TODO: replace with regex self.hidden = '<input type="hidden" name="%s" value="' % self.skey def get_session(self, response, url='/', agent='unknown browser'): """ Extract id from response and retrieve session """ # post or get parts = '' if not response.content: print 'RESPONSE FAILED: %s' % response.__class__ if response.content.find(self.hidden) > -1: splitter = self.hidden else: splitter = '%s=' % self.skey parts = response.content.split(splitter, 1) session_key = '' if len(parts) > 1: parts = parts[1].split('"', 1) session_id = parts[0] request = self.factory.get(url, REMOTE_ADDR='127.0.0.1', HTTP_USER_AGENT=agent) try: session_key = self.crypt_sesh.decrypt(request, session_id) except: # Silently start new session in case fake session_id format causes error pass else: session_id = '' try: session = self.engine.SessionStore(session_key) except: session = self.engine.SessionStore() return session, session_id
def request(self, **request): if 'PATH_INFO' in request: path=self.prefix+request['PATH_INFO'] else: path=self.prefix request['PATH_INFO']=path print "\nclient PATH_INFO:", path return DClient.request(self, **request)
def request(self, **request): if 'PATH_INFO' in request: path = self.prefix + request['PATH_INFO'] else: path = self.prefix request['PATH_INFO'] = path print "\nclient PATH_INFO:", path return DClient.request(self, **request)
def test_authentication_on_form(self): client = Client() response = client.post('/upload_email/', data) assert not 'ok' in response.content, response.content request = client.request() client.login(username='******', password='******') response = client.post('/upload_email/', data) assert 'ok' in response.content, response.content
class BaseTest(TestCase): def setUp(self): create_paths() self.client = Client() connection._set_isolation_level(0) def tearDown(self): execute_sql('SELECT ak.drop_all_schemas()') for dev_name in os.listdir(ROOT.devs): if dev_name != ANONYM_NAME: execute_sql('DROP TABLESPACE IF EXISTS "%s"' % dev_name) Popen('sudo rm -r %s %s' % (ROOT.devs, ROOT.trash), shell=True) shutil.rmtree(ROOT.locks) shutil.rmtree(ROOT.domains) def request(self, method, path, data='', content_type=None, status=OK): if not path.startswith('/'): path = '/' + path if not isinstance(data, str): data = json.dumps(data) content_type = content_type or 'application/json' parsed = urlparse(path) request = { 'REQUEST_METHOD': method, 'PATH_INFO': urllib.unquote(parsed[2]), 'QUERY_STRING': parsed[4], 'wsgi.input': FakePayload(data), 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest', } if data: request['CONTENT_LENGTH'] = len(data) if content_type: request['CONTENT_TYPE'] = content_type response = self.client.request(**request) self.assertEqual(response.status_code, status, response.content) return (json.loads(response.content) if response['Content-Type'].startswith('application/json') else response.content) def get(self, path, status=OK): return self.request('GET', path, status=status) def post(self, path, data='', content_type=None, status=OK): return self.request('POST', path, data, content_type, status) def put(self, path, data='', content_type=None, status=OK): if not content_type and isinstance(data, str): content_type = 'text/plain' return self.request('PUT', path, data, content_type, status) def delete(self, path, status=OK): return self.request('DELETE', path, status=status)
def execute(self, request=None, url=None): if not url: url = self.url extra = {} if self.ip_address: extra['REMOTE_ADDR'] = self.ip_address request = request or self.get_request() client = Client() if self.method != "get": # Django 1.4 is not able to handle DELETE requests with payload. # workaround here: extra.update({ 'wsgi.input': FakePayload(request), 'CONTENT_LENGTH': len(request), 'CONTENT_TYPE': "text/json", 'PATH_INFO': client._get_path(urlparse(url)), 'REQUEST_METHOD': self.method.upper() }) return client.request(**extra) else: return client.get(url, **extra);
class TestApiClient(object): def __init__(self, serializer=None): """ Sets up a fresh ``TestApiClient`` instance. If you are employing a custom serializer, you can pass the class to the ``serializer=`` kwarg. """ self.client = Client() self.serializer = serializer if not self.serializer: self.serializer = Serializer() def get_content_type(self, short_format): """ Given a short name (such as ``json`` or ``xml``), returns the full content-type for it (``application/json`` or ``application/xml`` in this case). """ return self.serializer.content_types.get(short_format, 'json') def get(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``GET`` request to the provided URI. Optionally accepts a ``data`` kwarg, which in the case of ``GET``, lets you send along ``GET`` parameters. This is useful when testing filtering or other things that read off the ``GET`` params. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.get('/api/v1/entry/1/', data={'format': 'json', 'title__startswith': 'a', 'limit': 20, 'offset': 60}) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['HTTP_ACCEPT'] = content_type # GET & DELETE are the only times we don't serialize the data. if data is not None: kwargs['data'] = data if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication return self.client.get(uri, **kwargs) def post(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``POST`` request to the provided URI. Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``POST`` the ``data`` gets serialized & sent as the body instead of becoming part of the URI. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.post('/api/v1/entry/', data={ 'created': '2012-05-01T20:02:36', 'slug': 'another-post', 'title': 'Another Post', 'user': '******', }) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['content_type'] = content_type if data is not None: kwargs['data'] = self.serializer.serialize(data, format=content_type) if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication return self.client.post(uri, **kwargs) def put(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``PUT`` request to the provided URI. Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``PUT`` the ``data`` gets serialized & sent as the body instead of becoming part of the URI. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.put('/api/v1/entry/1/', data={ 'created': '2012-05-01T20:02:36', 'slug': 'another-post', 'title': 'Another Post', 'user': '******', }) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['content_type'] = content_type if data is not None: kwargs['data'] = self.serializer.serialize(data, format=content_type) if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication return self.client.put(uri, **kwargs) def patch(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``PATCH`` request to the provided URI. Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``PATCH`` the ``data`` gets serialized & sent as the body instead of becoming part of the URI. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.patch('/api/v1/entry/1/', data={ 'created': '2012-05-01T20:02:36', 'slug': 'another-post', 'title': 'Another Post', 'user': '******', }) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['content_type'] = content_type if data is not None: kwargs['data'] = self.serializer.serialize(data, format=content_type) if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication # This hurts because Django doesn't support PATCH natively. parsed = urlparse(uri) r = { 'CONTENT_LENGTH': len(kwargs['data']), 'CONTENT_TYPE': content_type, 'PATH_INFO': self.client._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'PATCH', 'wsgi.input': FakePayload(kwargs['data']), } r.update(kwargs) return self.client.request(**r) def delete(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``DELETE`` request to the provided URI. Optionally accepts a ``data`` kwarg, which in the case of ``DELETE``, lets you send along ``DELETE`` parameters. This is useful when testing filtering or other things that read off the ``DELETE`` params. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.delete('/api/v1/entry/1/', data={'format': 'json'}) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['content_type'] = content_type # GET & DELETE are the only times we don't serialize the data. if data is not None: kwargs['data'] = data if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication return self.client.delete(uri, **kwargs)
class TestApiClient(object): def __init__(self, serializer=None): """ Sets up a fresh ``TestApiClient`` instance. If you are employing a custom serializer, you can pass the class to the ``serializer=`` kwarg. """ self.client = Client() self.serializer = serializer if not self.serializer: self.serializer = Serializer() def get_content_type(self, short_format): """ Given a short name (such as ``json`` or ``xml``), returns the full content-type for it (``application/json`` or ``application/xml`` in this case). """ return self.serializer.content_types.get(short_format or 'json') def get(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``GET`` request to the provided URI. Optionally accepts a ``data`` kwarg, which in the case of ``GET``, lets you send along ``GET`` parameters. This is useful when testing filtering or other things that read off the ``GET`` params. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.get('/api/v1/entry/1/', data={'format': 'json', 'title__startswith': 'a', 'limit': 20, 'offset': 60}) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['HTTP_ACCEPT'] = content_type # GET & DELETE are the only times we don't serialize the data. if data is not None: kwargs['data'] = data if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication return self.client.get(uri, **kwargs) def post(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``POST`` request to the provided URI. Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``POST`` the ``data`` gets serialized & sent as the body instead of becoming part of the URI. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.post('/api/v1/entry/', data={ 'created': '2012-05-01T20:02:36', 'slug': 'another-post', 'title': 'Another Post', 'user': '******', }) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['content_type'] = content_type if data is not None: kwargs['data'] = self.serializer.serialize(data, format=content_type) if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication return self.client.post(uri, **kwargs) def put(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``PUT`` request to the provided URI. Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``PUT`` the ``data`` gets serialized & sent as the body instead of becoming part of the URI. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.put('/api/v1/entry/1/', data={ 'created': '2012-05-01T20:02:36', 'slug': 'another-post', 'title': 'Another Post', 'user': '******', }) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['content_type'] = content_type if data is not None: kwargs['data'] = self.serializer.serialize(data, format=content_type) if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication return self.client.put(uri, **kwargs) def patch(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``PATCH`` request to the provided URI. Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``PATCH`` the ``data`` gets serialized & sent as the body instead of becoming part of the URI. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.patch('/api/v1/entry/1/', data={ 'created': '2012-05-01T20:02:36', 'slug': 'another-post', 'title': 'Another Post', 'user': '******', }) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['content_type'] = content_type if data is not None: kwargs['data'] = self.serializer.serialize(data, format=content_type) if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication # This hurts because Django doesn't support PATCH natively. parsed = urlparse(uri) r = { 'CONTENT_LENGTH': len(kwargs['data']), 'CONTENT_TYPE': content_type, 'PATH_INFO': self.client._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'PATCH', 'wsgi.input': FakePayload(kwargs['data']), } r.update(kwargs) return self.client.request(**r) def delete(self, uri, format='json', data=None, authentication=None, **kwargs): """ Performs a simulated ``DELETE`` request to the provided URI. Optionally accepts a ``data`` kwarg, which in the case of ``DELETE``, lets you send along ``DELETE`` parameters. This is useful when testing filtering or other things that read off the ``DELETE`` params. Example:: from tastypie.test import TestApiClient client = TestApiClient() response = client.delete('/api/v1/entry/1/', data={'format': 'json'}) Optionally accepts an ``authentication`` kwarg, which should be an HTTP header with the correct authentication data already setup. All other ``**kwargs`` passed in get passed through to the Django ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client for details. """ content_type = self.get_content_type(format) kwargs['content_type'] = content_type # GET & DELETE are the only times we don't serialize the data. if data is not None: kwargs['data'] = data if authentication is not None: kwargs['HTTP_AUTHORIZATION'] = authentication return self.client.delete(uri, **kwargs)
class TestModelRequest(TestCase): WEIGHT = 10 HEIGHT = 123 CEPHALIC_PERIMETER = 30 AGE = 1 def setUp(self): """ This method will run before any test case. """ self.client = Client() self.user = self.make_user() self.patient = Patient.objects.create( ses="1234567", user=self.user, mother_name="Mãe", father_name="Pai", ethnicity=3, sus_number="12345678911", civil_registry_of_birth="12345678911", ) self.user2 = self.make_user(username='******') self.health_team = HealthTeam.objects.create( cpf="057.641.271-65", user=self.user2, speciality=HealthTeam.NEUROLOGY, council_acronym=HealthTeam.CRM, register_number="1234567", registration_state=HealthTeam.DF, ) self.curve = Curves.objects.create( patient=self.patient, weight=self.WEIGHT, height=self.HEIGHT, cephalic_perimeter=self.CEPHALIC_PERIMETER, age=self.AGE, ) Curves.objects.create( patient=self.patient, weight=self.WEIGHT, height=self.HEIGHT, cephalic_perimeter=self.CEPHALIC_PERIMETER, age=45, ) def test_curves_form_valid_create_view(self): """ Test if create form is valid with all required fields """ self.client.force_login(user=self.health_team.user) data = { 'height': self.HEIGHT, 'weight': self.WEIGHT, 'age': 12, 'cephalic_perimeter': self.CEPHALIC_PERIMETER, } response = self.client.post(path=reverse( 'medicalrecords:create_curve', kwargs={'username': self.patient.user.username}), data=data, follow=True) self.assertEquals(response.status_code, 200) def test_data_parse_curves_height(self): self.client.force_login(user=self.user2) self.client.request() response = self.client.get(path=reverse( viewname='medicalrecords:curve_ajax', ), follow=True, data={ 'username': self.patient.user.username, 'data_type': 'height', 'time_frame': 'months' }) self.assertEquals(response.status_code, 200) response = self.client.get(path=reverse( viewname='medicalrecords:curve_ajax', ), follow=True, data={ 'username': self.patient.user.username, 'data_type': 'height', 'time_frame': 'years' }) self.assertEquals(response.status_code, 200) def test_data_parse_curves_weight(self): self.client.force_login(user=self.user2) self.client.request() response = self.client.get(path=reverse( viewname='medicalrecords:curve_ajax', ), follow=True, data={ 'username': self.patient.user.username, 'data_type': 'weight', 'time_frame': 'months' }) self.assertEquals(response.status_code, 200) response = self.client.get(path=reverse( viewname='medicalrecords:curve_ajax', ), follow=True, data={ 'username': self.patient.user.username, 'data_type': 'weight', 'time_frame': 'years' }) self.assertEquals(response.status_code, 200) def test_data_parse_curves_bmi(self): self.client.force_login(user=self.user2) self.client.request() self.patient.user.gender = 'Female' self.patient.user.save() response = self.client.get(path=reverse( viewname='medicalrecords:curve_ajax', ), follow=True, data={ 'username': self.patient.user.username, 'data_type': 'bmi', 'time_frame': 'years' }) self.assertEquals(response.status_code, 200) def test_api_gender(self): curve_api = CurveDataParser() curve_api.patient = self.patient self.patient.user.gender = 'Male' self.patient.user.save() self.assertEquals(curve_api.api_gender(), 'male') self.patient.user.gender = 'Female' self.patient.user.save() self.assertEquals(self.patient.user.gender, 'Female') self.assertEquals(curve_api.api_gender(), 'female') def test_data_parse_curves_cephalic_perimeter(self): self.client.force_login(user=self.user2) self.client.request() response = self.client.get(path=reverse( viewname='medicalrecords:curve_ajax', ), follow=True, data={ 'username': self.patient.user.username, 'data_type': 'cephalic_perimeter', }) self.assertEquals(response.status_code, 200) def test_curves_form_invalid_create_view(self): """ Test if create form is invalid with unique together """ self.client.force_login(user=self.health_team.user) data = { 'height': self.HEIGHT, 'weight': self.WEIGHT, 'age': self.AGE, 'cephalic_perimeter': self.CEPHALIC_PERIMETER, } response = self.client.post(path=reverse( 'medicalrecords:create_curve', kwargs={'username': self.user.username}), data=data, follow=True) self.assertEquals(response.status_code, 200) response2 = self.client.post(path=reverse( 'medicalrecords:create_curve', kwargs={'username': self.user.username}), data=data, follow=True) self.assertEquals(response2.status_code, 200) def test_curves_validation(self): """ Test if curves age validation is ok """ self.curve_test = Curves.objects.create( patient=self.patient, weight=self.WEIGHT, height=self.HEIGHT, cephalic_perimeter=self.CEPHALIC_PERIMETER, age=233, ) self.curve_test.save() self.curve_test.refresh_from_db() self.assertEquals(self.curve_test.cephalic_perimeter, 0)