def test_middleware(self): """ Testing that middleware saves requests""" cl = Client() cl.get(reverse("index")) cl.post(reverse("index")) cl.head(reverse("index")) qs = Request.objects.all() self.assertEqual(len(qs), 3)
def test_anonymous(self): anon_client = Client() r = anon_client.get("/work/{}/".format(self.work.id)) r = anon_client.head("/work/{}/".format(self.work.id)) self.assertEqual(r.status_code, 200) csrfmatch = re.search("name='csrfmiddlewaretoken' value='([^']*)'", str(r.content, 'utf-8')) self.assertFalse(csrfmatch) r = anon_client.post("/work/{}/kw/".format(self.work.id)) self.assertEqual(r.status_code, 302)
def test_view_for_meta(self): l = Location.objects.get(slug='las-vegas') c = Client() response = c.head(l.get_absolute_url()) print "@-->response %r" % dir(response) print "@-->location %r" % l.get_absolute_url() print "@-->context %r" % response.request.get('PATH_INFO') #print "@-->request %r" % response.context.get('request') request = response.context.get('request') print "@-->path %r" % request.get_full_path() self.assertEqual(1, 0)
class ResolverTestCase(TestCase): fixtures = [ 'test_uriregister.json', 'test_rewriterule.json', 'test_mediatype.json', 'test_acceptmapping.json' ] def setUp(self): self.c = Client() self.basePath = '/def' # this needs to be configured depending on how you've set up URL structure in your Django project def test_resolve_uri_invalid_HTTP_method(self): result = self.c.post(self.basePath + "something/sent/to/resolver") self.assertEqual(result.status_code, 405, 'Resolver.resolve_uri did not return a 405 error when receiving a POST') result = self.c.head(self.basePath + "something/sent/to/resolver") self.assertEqual(result.status_code, 405, 'Resolver.resolve_uri did not return a 405 error when receiving a HEAD') result = self.c.put(self.basePath + "something/sent/to/resolver") self.assertEqual(result.status_code, 405, 'Resolver.resolve_uri did not return a 405 error when receiving a PUT') result = self.c.delete(self.basePath + "something/sent/to/resolver") self.assertEqual(result.status_code, 405, 'Resolver.resolve_uri did not return a 405 error when receiving a DELETE') result = self.c.options(self.basePath + "something/sent/to/resolver") self.assertEqual(result.status_code, 405, 'Resolver.resolve_uri did not return a 405 error when receiving a OPTIONS') def test_resolve_uri_register_does_not_exist(self): result = self.c.get(self.basePath + "something/sent/to/resolver") self.assertEqual(result.status_code, 404, 'Resolver.resolve_uri did not return a 404 error when receiving a request for an unknown URI register') def test_resolve_uri_register_is_remote(self): result = self.c.get(self.basePath + "another-registry/to/resolver") self.assertEqual(result.status_code, 301, 'Resolver.resolve_uri did not return a 301 redirection when receiving a request for a remote URI register') def test_resolve_uri_no_matching_rules(self): result = self.c.get(self.basePath + "uri-gin/something/sent/to/resolver") self.assertEqual(result.status_code, 404, 'Resolver.resolve_uri did not return a 404 error when receiving a request for an unknown URI register') def test_resolve_uri_multiple_matching_rules(self): result = self.c.get(self.basePath + "uri-gin/this/is/a/duplicate/rule") self.assertEqual(result.status_code, 500, 'Resolver.resolve_uri did not return a 500 error when receiving a request matching multiple rules') def test_resolve_uri_no_acceptable_content(self): result = self.c.get(self.basePath + "uri-gin/something/twomappings", **{ "HTTP_ACCEPT": 'text/javascript' }) self.assertEqual(result.status_code, 406, 'Resolver.resolve_uri did not return a 406 error when receiving a request with no acceptable response') def test_resolve_uri_multiple_acceptable_content(self): result = self.c.get(self.basePath + "uri-gin/duplicate/accept/mappings/here", **{ "HTTP_ACCEPT": 'text/html' }) self.assertEqual(result.status_code, 500, 'Resolver.resolve_uri did not return a 500 error when receiving a request with multiple acceptable responses') def test_resolve_uri_success_one_group_one_mapping(self): result = self.c.get(self.basePath + "uri-gin/something/onegroup/onemapping/success", **{ "HTTP_ACCEPT": 'text/html' }) self.assertEqual(result['Location'], 'http://elsewhere.com/something', 'Resolver.resolve_uri did not return a 303 redirection to the appropriate location') def test_resolve_uri_success_one_group_two_mappings(self): result = self.c.get(self.basePath + "uri-gin/something/onegroup/twomappings/success", **{ "HTTP_ACCEPT": 'text/html' }) self.assertEqual(result['Location'], 'http://elsewhere.com/something', 'Resolver.resolve_uri did not return a 303 redirection to the appropriate location') def test_resolve_uri_success_two_groups_one_mapping(self): result = self.c.get(self.basePath + "uri-gin/first/twogroups/second/onemapping/success", **{ "HTTP_ACCEPT": 'text/html' }) self.assertEqual(result['Location'], 'http://elsewhere.com/first--second', 'Resolver.resolve_uri did not return a 303 redirection to the appropriate location') def test_resolve_uri_success_two_groups_two_mappings(self): result = self.c.get(self.basePath + "uri-gin/first/twogroups/second/twomappings/success", **{ "HTTP_ACCEPT": 'text/html' }) self.assertEqual(result['Location'], 'http://elsewhere.com/first--second', 'Resolver.resolve_uri did not return a 303 redirection to the appropriate location') def test_resolve_uri_success_extensions(self): result = self.c.get(self.basePath + "uri-gin/first/twogroups/second/twomappings/success.txt") self.assertEqual(result['Location'], 'http://fileextension.com/text.txt', 'Resolver.resolve_uri did not return a 303 redirection to the appropriate location when given a file extension')
class ClientTestCaseMixin(AuthTestCaseMixin): logger = logging.getLogger('tests') def setUp(self): self.c = Client() self.r_factory = RequestFactory() self.default_headers = {} super(ClientTestCaseMixin, self).setUp() def get_request_with_user(self, request): request.user = self.logged_user.user return request def logout(self): self.get(config.LOGOUT_URL) self.logged_user = None def authorize(self, username, password): assert_http_redirect( self.post(config.LOGIN_URL, { config.USERNAME: username, config.PASSWORD: password })) def get(self, url, headers=None): headers = headers or {} headers.update(self.default_headers) resp = self.c.get(url, **headers) return resp def put(self, url, data={}, headers=None): headers = headers or {} headers.update(self.default_headers) return self.c.put(url, data, **self.headers) def post(self, url, data, headers=None): headers = headers or {} headers.update(self.default_headers) return self.c.post(url, data, **headers) def head(self, url, headers=None): headers = headers or {} headers.update(self.default_headers) return self.c.head(url, **headers) def options(self, url, headers=None): headers = headers or {} headers.update(self.default_headers) return self.c.options(url, **headers) def delete(self, url, headers=None): headers = headers or {} headers.update(self.default_headers) resp = self.c.delete(url, **headers) return resp
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 delicious_cake.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 head(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 delicious_cake.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.head(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 delicious_cake.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 delicious_cake.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 delicious_cake.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 delicious_cake.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 EntityDefaultEditViewTest(AnnalistTestCase): """ Tests for record type edit views """ def setUp(self): init_annalist_test_site() init_annalist_test_coll() self.testsite = Site(TestBaseUri, TestBaseDir) self.testcoll = Collection.create(self.testsite, "testcoll", collection_create_values("testcoll")) self.testtype = RecordType.create(self.testcoll, "testtype", recordtype_create_values("testcoll", "testtype")) self.testdata = RecordTypeData.create(self.testcoll, "testtype", {}) self.type_ids = get_site_types_linked("testcoll") self.type_ids.append(FieldChoice("_type/testtype", label="RecordType testcoll/_type/testtype", link=recordtype_url("testcoll", "testtype") )) self.no_options = [ FieldChoice('', label="(no options)") ] # Login and permissions create_test_user(self.testcoll, "testuser", "testpassword") self.client = Client(HTTP_HOST=TestHost) loggedin = self.client.login(username="******", password="******") self.assertTrue(loggedin) return def tearDown(self): resetSitedata(scope="collections") return @classmethod def setUpClass(cls): super(EntityDefaultEditViewTest, cls).setUpClass() return @classmethod def tearDownClass(cls): super(EntityDefaultEditViewTest, cls).tearDownClass() #@@checkme@@ resetSitedata() return # ----------------------------------------------------------------------------- # Helpers # ----------------------------------------------------------------------------- def _create_entity_data(self, entity_id, update="Entity"): "Helper function creates entity data with supplied entity_id" e = EntityData.create(self.testdata, entity_id, entitydata_create_values(entity_id, update=update) ) return e def _check_entity_data_values(self, entity_id, type_id="testtype", type_uri=None, update="Entity", parent=None, update_dict=None): "Helper function checks content of form-updated record type entry with supplied entity_id" recorddata = RecordTypeData.load(self.testcoll, type_id) self.assertTrue(EntityData.exists(recorddata, entity_id)) e = EntityData.load(recorddata, entity_id) self.assertEqual(e.get_id(), entity_id) self.assertEqual(e.get_url(""), TestHostUri + entity_url("testcoll", type_id, entity_id)) v = entitydata_values(entity_id, type_id=type_id, type_uri=type_uri, update=update) if update_dict: v.update(update_dict) for k in update_dict: if update_dict[k] is None: v.pop(k, None) self.assertDictionaryMatch(e.get_values(), v) return e # ----------------------------------------------------------------------------- # Form rendering tests # ----------------------------------------------------------------------------- def test_get_form_rendering(self): u = entitydata_edit_url("new", "testcoll", "testtype", view_id="Default_view") r = self.client.get(u+"?continuation_url=/xyzzy/") self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertContains(r, "Collection testcoll") field_vals = default_fields( coll_id="testcoll", type_id="testtype", entity_id="00000001", tooltip1=context_view_field(r.context, 0, 0)['field_tooltip'], tooltip2=context_view_field(r.context, 0, 1)['field_tooltip'], tooltip3=context_view_field(r.context, 1, 0)['field_tooltip'], tooltip4=context_view_field(r.context, 2, 0)['field_tooltip'], ) formrow1 = """ <div class="small-12 medium-6 columns" title="%(tooltip1)s"> <div class="row view-value-row"> <div class="%(label_classes)s"> <span>Id</span> </div> <div class="%(input_classes)s"> <!-- cf http://stackoverflow.com/questions/1480588/input-size-vs-width --> <input type="text" size="64" name="entity_id" placeholder="(entity id)" value="00000001"> </div> </div> </div> """%field_vals(width=6) formrow2 = (""" <div class="small-12 medium-6 columns" title="%(tooltip2)s"> <div class="row view-value-row"> <div class="%(label_classes)s"> <span>Type</span> </div> <div class="%(input_classes)s"> """+ render_choice_options( "entity_type", self.type_ids, "_type/testtype")+ """ </div> </div> </div> """)%field_vals(width=6) formrow3 = """ <!-- editable text field --> <div class="small-12 columns" title="%(tooltip3)s"> <div class="row view-value-row"> <div class="%(label_classes)s"> <span>Label</span> </div> <div class="%(input_classes)s"> <input type="text" size="64" name="Entity_label" placeholder="(label)" value="%(default_label_esc)s"> </div> </div> </div> """%field_vals(width=12) formrow4 = """ <div class="small-12 columns" title="%(tooltip4)s"> <div class="row view-value-row"> <div class="%(label_classes)s"> <span>Comment</span> </div> <div class="%(input_classes)s"> <textarea cols="64" rows="6" name="Entity_comment" class="small-rows-4 medium-rows-8" placeholder="(description)"> %(default_comment_esc)s </textarea> </div> </div> </div> """%field_vals(width=12) # log.info("******\n"+r.content) self.assertContains(r, formrow1, html=True) self.assertContains(r, formrow2, html=True) self.assertContains(r, formrow3, html=True) self.assertContains(r, formrow4, html=True) return def test_get_new(self): u = entitydata_edit_url("new", "testcoll", "testtype", view_id="Default_view") r = self.client.get(u+"?continuation_url=/xyzzy/") self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") # Test context expect_context = default_view_context_data( coll_id="testcoll", type_id="testtype", entity_id="00000001", orig_id=None, type_ref="testtype", type_choices=self.type_ids, entity_label="", entity_descr="", action="new", update="Entity", continuation_url="/xyzzy/" ) self.assertEqual(len(r.context['fields']), 3) # 4 fields over 3 rows self.assertDictionaryMatch(context_bind_fields(r.context), expect_context) return def test_get_edit(self): u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="entity1") r = self.client.get(u+"?continuation_url=/xyzzy/") self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") # log.info(r.content) self.assertContains(r, "<title>Entity testcoll/testtype/entity1 - Default record view - Collection testcoll</title>") # Test context expect_context = default_view_context_data( coll_id="testcoll", type_id="testtype", entity_id="entity1", type_ref="testtype", type_choices=self.type_ids, entity_label="Entity testcoll/testtype/entity1", entity_descr="Entity coll testcoll, type testtype, entity entity1", action="edit", update="Entity", continuation_url="/xyzzy/" ) self.assertEqual(len(r.context['fields']), 3) # 4 fields over 3 rows self.assertDictionaryMatch(context_bind_fields(r.context), expect_context) return def test_get_edit_not_exists(self): u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="entitynone" ) r = self.client.get(u+"?continuation_url=/xyzzy/") self.check_entity_not_found_response(r, err_msg=make_message( message.ENTITY_DOES_NOT_EXIST, id="entitynone", label=error_label("testcoll", "testtype", "entitynone") ), redirect_url="/xyzzy/" ) return def test_head_new(self): u = entitydata_edit_url("new", "testcoll", "testtype", view_id="Default_view") r = self.client.head(u) self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertEqual(r.content, b"") return def test_head_edit(self): u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="entity1" ) r = self.client.head(u) self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertEqual(r.content, b"") return def test_head_edit_not_exists(self): u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="entitynone" ) r = self.client.head(u) self.check_entity_not_found_response(r, redirect_url="/testsite/c/testcoll/d/testtype/" ) return # ----------------------------------------------------------------------------- # Form response tests # ----------------------------------------------------------------------------- # -------- new entity -------- def test_post_new_entity(self): self.assertFalse(EntityData.exists(self.testdata, "newentity")) f = default_view_form_data(entity_id="newentity", action="new") u = entitydata_edit_url("new", "testcoll", "testtype", view_id="Default_view") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "testtype")) # Check new entity data created self._check_entity_data_values("newentity") return def test_post_new_entity_cancel(self): self.assertFalse(EntityData.exists(self.testdata, "newentity")) f = default_view_form_data(entity_id="newentity", action="new", cancel="Cancel") u = entitydata_edit_url("new", "testcoll", "testtype", view_id="Default_view") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "testtype")) # Check that new record type still does not exist self.assertFalse(EntityData.exists(self.testdata, "newentity")) return def test_post_new_entity_missing_id(self): f = default_view_form_data(action="new", entity_id="") u = entitydata_edit_url("new", "testcoll", "testtype", view_id="Default_view") r = self.client.post(u, f) self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertContains(r, "<h3>Problem with entity identifier</h3>") # Test context expect_context = default_view_context_data( coll_id="testcoll", type_id="testtype", entity_id="", orig_id="orig_entity_id", type_ref="", type_choices=self.type_ids, action="new" ) self.assertEqual(len(r.context['fields']), 3) # 4 fields over 3 rows self.assertDictionaryMatch(context_bind_fields(r.context), expect_context) return def test_post_new_entity_invalid_id(self): f = default_view_form_data( entity_id="!badentity", orig_id="orig_entity_id", action="new" ) u = entitydata_edit_url("new", "testcoll", "testtype", view_id="Default_view") r = self.client.post(u, f) self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertContains(r, "<h3>Problem with entity identifier</h3>") # Test context expect_context = default_view_context_data( coll_id="testcoll", type_id="testtype", entity_id="!badentity", orig_id="orig_entity_id", type_ref="_type/testtype", type_choices=self.type_ids, action="new" ) self.assertDictionaryMatch(context_bind_fields(r.context), expect_context) return def test_new_entity_default_type(self): # Checks logic related to creating a new recorddata entity in collection # for type defined in site data self.assertFalse(EntityData.exists(self.testdata, "newentity")) f = default_view_form_data(entity_id="newentity", type_id="Default_type", action="new") u = entitydata_edit_url("new", "testcoll", "Default_type", view_id="Default_view") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "Default_type")) # Check new entity data created self._check_entity_data_values( "newentity", type_id="Default_type", type_uri="annal:Default_type", update_dict= { '@type': ['annal:Default_type', 'annal:EntityData'] } ) return def test_new_entity_new_type(self): # Checks logic for creating an entity which may require creation of new recorddata # Create new type self.assertFalse(RecordType.exists(self.testcoll, "newtype")) f = type_view_form_data(action="new", coll_id="testcoll", type_entity_id="newtype", ) u = entitydata_edit_url("new", "testcoll", type_id="_type", view_id="Type_view") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "_type")) self.assertTrue(RecordType.exists(self.testcoll, "newtype")) # Create new entity self.assertFalse(EntityData.exists(self.testdata, "newentity")) f = default_view_form_data(entity_id="newentity", type_id="newtype", action="new") u = entitydata_edit_url("new", "testcoll", "newtype", view_id="Default_view") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "newtype")) # Check new entity data created self._check_entity_data_values("newentity", type_id="newtype") return # -------- copy type -------- def test_post_copy_entity(self): self.assertFalse(EntityData.exists(self.testdata, "copytype")) f = default_view_form_data(entity_id="copytype", action="copy") u = entitydata_edit_url("copy", "testcoll", "testtype", entity_id="entity1") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "testtype")) # Check that new record type exists self._check_entity_data_values("copytype") return def test_post_copy_entity_cancel(self): self.assertFalse(EntityData.exists(self.testdata, "copytype")) f = default_view_form_data(entity_id="copytype", action="copy", cancel="Cancel") u = entitydata_edit_url("copy", "testcoll", "testtype", entity_id="entity1") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "testtype")) # Check that target record type still does not exist self.assertFalse(EntityData.exists(self.testdata, "copytype")) return def test_post_copy_entity_missing_id(self): f = default_view_form_data(action="copy", entity_id="", orig_id="entity1") u = entitydata_edit_url("copy", "testcoll", "testtype", entity_id="entity1") r = self.client.post(u, f) self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertContains(r, "<h3>Problem with entity identifier</h3>") expect_context = default_view_context_data( action="copy", orig_id="entity1", type_ref="", type_choices=self.type_ids ) self.assertDictionaryMatch(context_bind_fields(r.context), expect_context) return def test_post_copy_entity_invalid_id(self): f = default_view_form_data( entity_id="!badentity", orig_id="entity1", action="copy" ) u = entitydata_edit_url("copy", "testcoll", "testtype", entity_id="entity1") r = self.client.post(u, f) self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertContains(r, "<h3>Problem with entity identifier</h3>") expect_context = default_view_context_data( action="copy", entity_id="!badentity", orig_id="entity1", type_ref="_type/testtype", type_choices=self.type_ids, ) self.assertDictionaryMatch(context_bind_fields(r.context), expect_context) return # -------- edit type -------- def test_post_edit_entity(self): self._create_entity_data("entityedit") self._check_entity_data_values("entityedit") f = default_view_form_data(entity_id="entityedit", action="edit", update="Updated entity") u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="entityedit") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "testtype")) self._check_entity_data_values("entityedit", update="Updated entity") return def test_post_edit_entity_new_id(self): self._create_entity_data("entityeditid1") e1 = self._check_entity_data_values("entityeditid1") # Now post edit form submission with different values and new id f = default_view_form_data(entity_id="entityeditid2", orig_id="entityeditid1", action="edit") u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="entityeditid1") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "testtype")) # Check that new record type exists and old does not self.assertFalse(EntityData.exists(self.testdata, "entityeditid1")) self._check_entity_data_values("entityeditid2") return def test_post_edit_entity_new_type(self): self._create_entity_data("entityedittype") e1 = self._check_entity_data_values("entityedittype") self.assertFalse(RecordType.exists(self.testcoll, "newtype")) newtype = RecordType.create(self.testcoll, "newtype", recordtype_create_values("newtype")) newtypedata = RecordTypeData(self.testcoll, "newtype") self.assertTrue(RecordType.exists(self.testcoll, "newtype")) self.assertFalse(RecordTypeData.exists(self.testcoll, "newtype")) # Now post edit form submission with new type id f = default_view_form_data( entity_id="entityedittype", orig_id="entityedittype", type_id="newtype", orig_type="testtype", action="edit") u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="entityedittype") r = self.client.post(u, f) # log.info("***********\n"+r.content) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "testtype")) # Check that new record type data now exists, and that new record exists and old does not self.assertTrue(RecordTypeData.exists(self.testcoll, "newtype")) self.assertFalse(EntityData.exists(self.testdata, "entityedittype")) self.assertTrue(EntityData.exists(newtypedata, "entityedittype")) self._check_entity_data_values("entityedittype", type_id="newtype") return def test_post_edit_entity_cancel(self): self._create_entity_data("edittype") self._check_entity_data_values("edittype") # Post from cancelled edit form f = default_view_form_data(entity_id="edittype", action="edit", cancel="Cancel", update="Updated entity") u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="edittype") r = self.client.post(u, f) self.assertEqual(r.status_code, 302) self.assertEqual(r.reason_phrase, "Found") self.assertEqual(r.content, b"") self.assertEqual(r['location'], entitydata_list_type_url("testcoll", "testtype")) # Check that target record type still does not exist and unchanged self._check_entity_data_values("edittype") return def test_post_edit_entity_missing_id(self): self._create_entity_data("edittype") self._check_entity_data_values("edittype") # Form post with ID missing f = default_view_form_data( action="edit", entity_id="", orig_id="edittype", update="Updated entity" ) u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="edittype") r = self.client.post(u, f) self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertContains(r, "<h3>Problem with entity identifier</h3>") # Test context for re-rendered form expect_context = default_view_context_data( action="edit", update="Updated entity", orig_id="edittype", type_ref="", type_choices=self.type_ids, record_type="/testsite/c/testcoll/d/_type/testtype/" ) self.assertEqual(len(r.context['fields']), 3) # 4 fields over 3 rows self.assertDictionaryMatch(context_bind_fields(r.context), expect_context) # Check stored entity is unchanged self._check_entity_data_values("edittype") return def test_post_edit_entity_invalid_id(self): self._create_entity_data("edittype") self._check_entity_data_values("edittype") # Form post with ID malformed f = default_view_form_data( entity_id="!badentity", orig_id="edittype", action="edit" ) u = entitydata_edit_url("edit", "testcoll", "testtype", entity_id="edittype") r = self.client.post(u, f) self.assertEqual(r.status_code, 200) self.assertEqual(r.reason_phrase, "OK") self.assertContains(r, "<h3>Problem with entity identifier</h3>") # Test context for re-rendered form expect_context = default_view_context_data( entity_id="!badentity", orig_id="edittype", action="edit", type_ref="_type/testtype", type_choices=self.type_ids, record_type="/testsite/c/testcoll/d/_type/testtype/" ) self.assertDictionaryMatch(context_bind_fields(r.context), expect_context) # Check stored entity is unchanged self._check_entity_data_values("edittype") return
def test_no_HEAD(self): c = Client() response = c.head("/api/v1/null") self.assertEquals(response.status_code, 405)
def head(self, url, *args, **kwargs): response = Client.head(self, url, *args, **kwargs)
class ClientTestCase(AuthTestCaseMixin, LiveServerTestCase, AssertMixin): logger = logging.getLogger('tests') def setUp(self): self.c = Client() self.r_factory = RequestFactory() self.default_headers = {} super(ClientTestCase, self).setUp() def get_request_with_user(self, request): request.user = self.logged_user.user return request def logout(self): self.get(config.LOGOUT_URL) self.logged_user = None def authorize(self, username, password): resp = self.post(config.LOGIN_URL, { config.USERNAME: username, config.PASSWORD: password }) self.assert_http_redirect(resp) def get(self, url, headers=None): headers = headers or {} headers.update(self.default_headers) resp = self.c.get(url, **headers) return resp def put(self, url, data={}, headers=None): headers = headers or {} headers.update(self.default_headers) return self.c.put(url, data, **self.headers) def post(self, url, data, headers=None): headers = headers or {} headers.update(self.default_headers) return self.c.post(url, data, **headers) def head(self, url, headers=None): headers = headers or {} headers.update(self.default_headers) return self.c.head(url, **headers) def options(self, url, headers=None): headers = headers or {} headers.update(self.default_headers) return self.c.options(url, **headers) def delete(self, url, headers=None): headers = headers or {} headers.update(self.default_headers) resp = self.c.delete(url, **headers) return resp def assert_http_ok(self, resp, msg=None): return self.assert_equal(resp.status_code, 200, msg) def assert_http_created(self, resp, msg=None): return self.assert_equal(resp.status_code, 201, msg) def assert_http_accepted(self, resp, msg=None): return self.assert_in(resp.status_code, [202, 204], msg) def assert_http_multiple_choices(self, resp, msg=None): return self.assertEqual(resp.status_code, 300, msg) def assert_http_redirect(self, resp, msg=None): """ Ensures the response is returning a HTTP 302. """ return self.assertEqual(resp.status_code, 302, msg) def assert_http_see_other(self, resp, msg=None): """ Ensures the response is returning a HTTP 303. """ return self.assertEqual(resp.status_code, 303, msg) def assert_http_not_modified(self, resp, msg=None): """ Ensures the response is returning a HTTP 304. """ return self.assertEqual(resp.status_code, 304, msg) def assert_http_bad_request(self, resp, msg=None): """ Ensures the response is returning a HTTP 400. """ return self.assertEqual(resp.status_code, 400, msg) def assert_http_unauthorized(self, resp, msg=None): """ Ensures the response is returning a HTTP 401. """ return self.assertEqual(resp.status_code, 401, msg) def assert_http_forbidden(self, resp, msg=None): """ Ensures the response is returning a HTTP 403. """ return self.assertEqual(resp.status_code, 403, msg) def assert_http_not_found(self, resp, msg=None): """ Ensures the response is returning a HTTP 404. """ return self.assertEqual(resp.status_code, 404, msg) def assert_http_method_not_allowed(self, resp, msg=None): """ Ensures the response is returning a HTTP 405. """ return self.assertEqual(resp.status_code, 405, msg) def assert_http_conflict(self, resp, msg=None): """ Ensures the response is returning a HTTP 409. """ return self.assertEqual(resp.status_code, 409, msg) def assert_http_gone(self, resp, msg=None): """ Ensures the response is returning a HTTP 410. """ return self.assertEqual(resp.status_code, 410, msg) def assert_http_unprocessable_entity(self, resp, msg=None): """ Ensures the response is returning a HTTP 422. """ return self.assertEqual(resp.status_code, 422, msg) def assert_http_too_many_requests(self, resp, msg=None): """ Ensures the response is returning a HTTP 429. """ return self.assertEqual(resp.status_code, 429, msg) def assert_http_application_error(self, resp, msg=None): """ Ensures the response is returning a HTTP 500. """ return self.assertEqual(resp.status_code, 500, msg) def assert_http_not_implemented(self, resp, msg=None): """ Ensures the response is returning a HTTP 501. """ return self.assertEqual(resp.status_code, 501, msg)