diff options
Diffstat (limited to 'djangorestframework/tests')
| -rw-r--r-- | djangorestframework/tests/authentication.py | 18 | ||||
| -rw-r--r-- | djangorestframework/tests/description.py | 54 | ||||
| -rw-r--r-- | djangorestframework/tests/mixins.py | 5 | ||||
| -rw-r--r-- | djangorestframework/tests/renderers.py | 11 | ||||
| -rw-r--r-- | djangorestframework/tests/validators.py | 49 |
5 files changed, 74 insertions, 63 deletions
diff --git a/djangorestframework/tests/authentication.py b/djangorestframework/tests/authentication.py index 1835c523..303bf96b 100644 --- a/djangorestframework/tests/authentication.py +++ b/djangorestframework/tests/authentication.py @@ -11,7 +11,7 @@ import base64 class MockView(View): - permissions = ( permissions.IsAuthenticated, ) + permissions = (permissions.IsAuthenticated,) def post(self, request): return {'a': 1, 'b': 2, 'c': 3} @@ -74,24 +74,32 @@ class SessionAuthTests(TestCase): self.csrf_client.logout() def test_post_form_session_auth_failing_csrf(self): - """Ensure POSTing form over session authentication without CSRF token fails.""" + """ + Ensure POSTing form over session authentication without CSRF token fails. + """ self.csrf_client.login(username=self.username, password=self.password) response = self.csrf_client.post('/', {'example': 'example'}) self.assertEqual(response.status_code, 403) def test_post_form_session_auth_passing(self): - """Ensure POSTing form over session authentication with logged in user and CSRF token passes.""" + """ + Ensure POSTing form over session authentication with logged in user and CSRF token passes. + """ self.non_csrf_client.login(username=self.username, password=self.password) response = self.non_csrf_client.post('/', {'example': 'example'}) self.assertEqual(response.status_code, 200) def test_put_form_session_auth_passing(self): - """Ensure PUTting form over session authentication with logged in user and CSRF token passes.""" + """ + Ensure PUTting form over session authentication with logged in user and CSRF token passes. + """ self.non_csrf_client.login(username=self.username, password=self.password) response = self.non_csrf_client.put('/', {'example': 'example'}) self.assertEqual(response.status_code, 200) def test_post_form_session_auth_failing(self): - """Ensure POSTing form over session authentication without logged in user fails.""" + """ + Ensure POSTing form over session authentication without logged in user fails. + """ response = self.csrf_client.post('/', {'example': 'example'}) self.assertEqual(response.status_code, 403) diff --git a/djangorestframework/tests/description.py b/djangorestframework/tests/description.py index 56dcdfab..212b4ca4 100644 --- a/djangorestframework/tests/description.py +++ b/djangorestframework/tests/description.py @@ -1,7 +1,6 @@ from django.test import TestCase from djangorestframework.views import View from djangorestframework.compat import apply_markdown -from djangorestframework.utils.description import get_name, get_description # We check that docstrings get nicely un-indented. DESCRIPTION = """an example docstring @@ -51,15 +50,15 @@ class TestViewNamesAndDescriptions(TestCase): """Ensure Resource names are based on the classname by default.""" class MockView(View): pass - self.assertEquals(get_name(MockView()), 'Mock') + self.assertEquals(MockView().get_name(), 'Mock') - # This has been turned off now. - #def test_resource_name_can_be_set_explicitly(self): - # """Ensure Resource names can be set using the 'name' class attribute.""" - # example = 'Some Other Name' - # class MockView(View): - # name = example - # self.assertEquals(get_name(MockView()), example) + def test_resource_name_can_be_set_explicitly(self): + """Ensure Resource names can be set using the 'get_name' method.""" + example = 'Some Other Name' + class MockView(View): + def get_name(self): + return example + self.assertEquals(MockView().get_name(), example) def test_resource_description_uses_docstring_by_default(self): """Ensure Resource names are based on the docstring by default.""" @@ -79,29 +78,30 @@ class TestViewNamesAndDescriptions(TestCase): # hash style header #""" - self.assertEquals(get_description(MockView()), DESCRIPTION) - - # This has been turned off now - #def test_resource_description_can_be_set_explicitly(self): - # """Ensure Resource descriptions can be set using the 'description' class attribute.""" - # example = 'Some other description' - # class MockView(View): - # """docstring""" - # description = example - # self.assertEquals(get_description(MockView()), example) + self.assertEquals(MockView().get_description(), DESCRIPTION) - #def test_resource_description_does_not_require_docstring(self): - # """Ensure that empty docstrings do not affect the Resource's description if it has been set using the 'description' class attribute.""" - # example = 'Some other description' - # class MockView(View): - # description = example - # self.assertEquals(get_description(MockView()), example) + def test_resource_description_can_be_set_explicitly(self): + """Ensure Resource descriptions can be set using the 'get_description' method.""" + example = 'Some other description' + class MockView(View): + """docstring""" + def get_description(self): + return example + self.assertEquals(MockView().get_description(), example) + + def test_resource_description_does_not_require_docstring(self): + """Ensure that empty docstrings do not affect the Resource's description if it has been set using the 'get_description' method.""" + example = 'Some other description' + class MockView(View): + def get_description(self): + return example + self.assertEquals(MockView().get_description(), example) def test_resource_description_can_be_empty(self): - """Ensure that if a resource has no doctring or 'description' class attribute, then it's description is the empty string""" + """Ensure that if a resource has no doctring or 'description' class attribute, then it's description is the empty string.""" class MockView(View): pass - self.assertEquals(get_description(MockView()), '') + self.assertEquals(MockView().get_description(), '') def test_markdown(self): """Ensure markdown to HTML works as expected""" diff --git a/djangorestframework/tests/mixins.py b/djangorestframework/tests/mixins.py index 72e0b8b0..a7512efc 100644 --- a/djangorestframework/tests/mixins.py +++ b/djangorestframework/tests/mixins.py @@ -30,7 +30,7 @@ class TestModelRead(TestModelsTestCase): mixin = ReadModelMixin() mixin.resource = GroupResource - response = mixin.get(request, group.id) + response = mixin.get(request, id=group.id) self.assertEquals(group.name, response.name) def test_read_404(self): @@ -41,8 +41,7 @@ class TestModelRead(TestModelsTestCase): mixin = ReadModelMixin() mixin.resource = GroupResource - with self.assertRaises(ErrorResponse): - response = mixin.get(request, 12345) + self.assertRaises(ErrorResponse, mixin.get, request, id=12345) class TestModelCreation(TestModelsTestCase): diff --git a/djangorestframework/tests/renderers.py b/djangorestframework/tests/renderers.py index adb46f7f..ef2ad0a7 100644 --- a/djangorestframework/tests/renderers.py +++ b/djangorestframework/tests/renderers.py @@ -1,3 +1,5 @@ +import re + from django.conf.urls.defaults import patterns, url from django.test import TestCase @@ -174,6 +176,12 @@ class RendererIntegrationTests(TestCase): _flat_repr = '{"foo": ["bar", "baz"]}' _indented_repr = '{\n "foo": [\n "bar",\n "baz"\n ]\n}' +def strip_trailing_whitespace(content): + """ + Seems to be some inconsistencies re. trailing whitespace with + different versions of the json lib. + """ + return re.sub(' +\n', '\n', content) class JSONRendererTests(TestCase): """ @@ -187,6 +195,7 @@ class JSONRendererTests(TestCase): obj = {'foo': ['bar', 'baz']} renderer = JSONRenderer(None) content = renderer.render(obj, 'application/json') + # Fix failing test case which depends on version of JSON library. self.assertEquals(content, _flat_repr) def test_with_content_type_args(self): @@ -196,7 +205,7 @@ class JSONRendererTests(TestCase): obj = {'foo': ['bar', 'baz']} renderer = JSONRenderer(None) content = renderer.render(obj, 'application/json; indent=2') - self.assertEquals(content, _indented_repr) + self.assertEquals(strip_trailing_whitespace(content), _indented_repr) def test_render_and_parse(self): """ diff --git a/djangorestframework/tests/validators.py b/djangorestframework/tests/validators.py index 7b643272..15d92231 100644 --- a/djangorestframework/tests/validators.py +++ b/djangorestframework/tests/validators.py @@ -1,12 +1,9 @@ from django import forms from django.db import models from django.test import TestCase -from djangorestframework.compat import RequestFactory -from djangorestframework.resources import Resource, FormResource, ModelResource +from djangorestframework.resources import FormResource, ModelResource from djangorestframework.response import ErrorResponse from djangorestframework.views import View -from djangorestframework.resources import Resource - class TestDisabledValidations(TestCase): @@ -22,7 +19,7 @@ class TestDisabledValidations(TestCase): resource = DisabledFormResource view = MockView() - content = {'qwerty':'uiop'} + content = {'qwerty': 'uiop'} self.assertEqual(FormResource(view).validate_request(content, None), content) def test_disabled_form_validator_get_bound_form_returns_none(self): @@ -35,10 +32,9 @@ class TestDisabledValidations(TestCase): resource = DisabledFormResource view = MockView() - content = {'qwerty':'uiop'} + content = {'qwerty': 'uiop'} self.assertEqual(FormResource(view).get_bound_form(content), None) - def test_disabled_model_form_validator_returns_content_unchanged(self): """If the view's form is None and does not have a Resource with a model set then ModelFormValidator(view).validate_request(content, None) should just return the content unmodified.""" @@ -47,8 +43,8 @@ class TestDisabledValidations(TestCase): resource = ModelResource view = DisabledModelFormView() - content = {'qwerty':'uiop'} - self.assertEqual(ModelResource(view).get_bound_form(content), None)# + content = {'qwerty': 'uiop'} + self.assertEqual(ModelResource(view).get_bound_form(content), None) def test_disabled_model_form_validator_get_bound_form_returns_none(self): """If the form attribute is None on FormValidatorMixin then get_bound_form(content) should just return None.""" @@ -56,9 +52,10 @@ class TestDisabledValidations(TestCase): resource = ModelResource view = DisabledModelFormView() - content = {'qwerty':'uiop'} + content = {'qwerty': 'uiop'} self.assertEqual(ModelResource(view).get_bound_form(content), None) + class TestNonFieldErrors(TestCase): """Tests against form validation errors caused by non-field errors. (eg as might be caused by some custom form validation)""" @@ -72,7 +69,7 @@ class TestNonFieldErrors(TestCase): def clean(self): if 'field1' in self.cleaned_data and 'field2' in self.cleaned_data: raise forms.ValidationError(self.ERROR_TEXT) - return self.cleaned_data #pragma: no cover + return self.cleaned_data class MockResource(FormResource): form = MockForm @@ -87,7 +84,7 @@ class TestNonFieldErrors(TestCase): except ErrorResponse, exc: self.assertEqual(exc.response.raw_content, {'errors': [MockForm.ERROR_TEXT]}) else: - self.fail('ErrorResponse was not raised') #pragma: no cover + self.fail('ErrorResponse was not raised') class TestFormValidation(TestCase): @@ -115,10 +112,9 @@ class TestFormValidation(TestCase): self.MockFormView = MockFormView self.MockModelFormView = MockModelFormView - def validation_returns_content_unchanged_if_already_valid_and_clean(self, validator): """If the content is already valid and clean then validate(content) should just return the content unmodified.""" - content = {'qwerty':'uiop'} + content = {'qwerty': 'uiop'} self.assertEqual(validator.validate_request(content, None), content) def validation_failure_raises_response_exception(self, validator): @@ -143,7 +139,9 @@ class TestFormValidation(TestCase): raise errors on unexpected request data""" content = {'qwerty': 'uiop', 'extra': 'extra'} validator.allow_unknown_form_fields = True - self.assertDictEqual({'qwerty': u'uiop'}, validator.validate_request(content, None), "Resource didn't accept unknown fields.") + self.assertEqual({'qwerty': u'uiop'}, + validator.validate_request(content, None), + "Resource didn't accept unknown fields.") validator.allow_unknown_form_fields = False def validation_does_not_require_extra_fields_if_explicitly_set(self, validator): @@ -159,7 +157,7 @@ class TestFormValidation(TestCase): except ErrorResponse, exc: self.assertEqual(exc.response.raw_content, {'field_errors': {'qwerty': ['This field is required.']}}) else: - self.fail('ResourceException was not raised') #pragma: no cover + self.fail('ResourceException was not raised') def validation_failed_due_to_field_error_returns_appropriate_message(self, validator): """If validation fails due to a field error, ensure the response contains a single field error""" @@ -169,7 +167,7 @@ class TestFormValidation(TestCase): except ErrorResponse, exc: self.assertEqual(exc.response.raw_content, {'field_errors': {'qwerty': ['This field is required.']}}) else: - self.fail('ResourceException was not raised') #pragma: no cover + self.fail('ResourceException was not raised') def validation_failed_due_to_invalid_field_returns_appropriate_message(self, validator): """If validation fails due to an invalid field, ensure the response contains a single field error""" @@ -179,7 +177,7 @@ class TestFormValidation(TestCase): except ErrorResponse, exc: self.assertEqual(exc.response.raw_content, {'field_errors': {'extra': ['This field does not exist.']}}) else: - self.fail('ResourceException was not raised') #pragma: no cover + self.fail('ResourceException was not raised') def validation_failed_due_to_multiple_errors_returns_appropriate_message(self, validator): """If validation for multiple reasons, ensure the response contains each error""" @@ -190,7 +188,7 @@ class TestFormValidation(TestCase): self.assertEqual(exc.response.raw_content, {'field_errors': {'qwerty': ['This field is required.'], 'extra': ['This field does not exist.']}}) else: - self.fail('ResourceException was not raised') #pragma: no cover + self.fail('ResourceException was not raised') # Tests on FormResource @@ -209,7 +207,7 @@ class TestFormValidation(TestCase): def test_validation_allows_extra_fields_if_explicitly_set(self): validator = self.MockFormResource(self.MockFormView()) self.validation_allows_extra_fields_if_explicitly_set(validator) - + def test_validation_allows_unknown_fields_if_explicitly_allowed(self): validator = self.MockFormResource(self.MockFormView()) self.validation_allows_unknown_fields_if_explicitly_allowed(validator) @@ -294,22 +292,21 @@ class TestModelFormValidator(TestCase): self.validator = MockResource(MockView) - def test_property_fields_are_allowed_on_model_forms(self): """Validation on ModelForms may include property fields that exist on the Model to be included in the input.""" - content = {'qwerty':'example', 'uiop': 'example', 'readonly': 'read only'} + content = {'qwerty': 'example', 'uiop': 'example', 'readonly': 'read only'} self.assertEqual(self.validator.validate_request(content, None), content) def test_property_fields_are_not_required_on_model_forms(self): """Validation on ModelForms does not require property fields that exist on the Model to be included in the input.""" - content = {'qwerty':'example', 'uiop': 'example'} + content = {'qwerty': 'example', 'uiop': 'example'} self.assertEqual(self.validator.validate_request(content, None), content) def test_extra_fields_not_allowed_on_model_forms(self): """If some (otherwise valid) content includes fields that are not in the form then validation should fail. It might be okay on normal form submission, but for Web APIs we oughta get strict, as it'll help show up broken clients more easily (eg submitting content with a misnamed field)""" - content = {'qwerty': 'example', 'uiop':'example', 'readonly': 'read only', 'extra': 'extra'} + content = {'qwerty': 'example', 'uiop': 'example', 'readonly': 'read only', 'extra': 'extra'} self.assertRaises(ErrorResponse, self.validator.validate_request, content, None) def test_validate_requires_fields_on_model_forms(self): @@ -321,10 +318,8 @@ class TestModelFormValidator(TestCase): def test_validate_does_not_require_blankable_fields_on_model_forms(self): """Test standard ModelForm validation behaviour - fields with blank=True are not required.""" - content = {'qwerty':'example', 'readonly': 'read only'} + content = {'qwerty': 'example', 'readonly': 'read only'} self.validator.validate_request(content, None) def test_model_form_validator_uses_model_forms(self): self.assertTrue(isinstance(self.validator.get_bound_form(), forms.ModelForm)) - - |
