From a98049c5de9a4ac9e93eac9798e00df9c93caf81 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 15:25:32 +0000 Subject: Drop unneeded test --- rest_framework/tests/decorators.py | 8 -------- 1 file changed, 8 deletions(-) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/decorators.py b/rest_framework/tests/decorators.py index 5e6bce4e..4012188d 100644 --- a/rest_framework/tests/decorators.py +++ b/rest_framework/tests/decorators.py @@ -28,14 +28,6 @@ class DecoratorTestCase(TestCase): response.request = request return APIView.finalize_response(self, request, response, *args, **kwargs) - def test_wrap_view(self): - - @api_view(['GET']) - def view(request): - return Response({}) - - self.assertTrue(isinstance(view.cls_instance, APIView)) - def test_calling_method(self): @api_view(['GET']) -- cgit v1.2.3 From 37d49429ca34eed86ea142e5dceea4cd9536df2d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 15:51:14 +0000 Subject: Raise assertion errors if @api_view decorator is applied incorrectly. Fixes #596. --- rest_framework/tests/decorators.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/decorators.py b/rest_framework/tests/decorators.py index 4012188d..82f912e9 100644 --- a/rest_framework/tests/decorators.py +++ b/rest_framework/tests/decorators.py @@ -28,6 +28,28 @@ class DecoratorTestCase(TestCase): response.request = request return APIView.finalize_response(self, request, response, *args, **kwargs) + def test_api_view_incorrect(self): + """ + If @api_view is not applied correct, we should raise an assertion. + """ + + @api_view + def view(request): + return Response() + + request = self.factory.get('/') + self.assertRaises(AssertionError, view, request) + + def test_api_view_incorrect_arguments(self): + """ + If @api_view is missing arguments, we should raise an assertion. + """ + + with self.assertRaises(AssertionError): + @api_view('GET') + def view(request): + return Response() + def test_calling_method(self): @api_view(['GET']) -- cgit v1.2.3 From 71bd2faa792569c9f4c83a06904b927616bfdbf1 Mon Sep 17 00:00:00 2001 From: Kevin Stone Date: Sun, 20 Jan 2013 12:59:27 -0800 Subject: Added test case for format_suffix_patterns to validate changes introduced with issue #593. Signed-off-by: Kevin Stone --- rest_framework/tests/urlpatterns.py | 75 +++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 rest_framework/tests/urlpatterns.py (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/urlpatterns.py b/rest_framework/tests/urlpatterns.py new file mode 100644 index 00000000..e96e7cf3 --- /dev/null +++ b/rest_framework/tests/urlpatterns.py @@ -0,0 +1,75 @@ +from collections import namedtuple + +from django.core import urlresolvers + +from django.test import TestCase +from django.test.client import RequestFactory + +from rest_framework.compat import patterns, url, include +from rest_framework.urlpatterns import format_suffix_patterns + + +# A container class for test paths for the test case +URLTestPath = namedtuple('URLTestPath', ['path', 'args', 'kwargs']) + + +def test_view(request, *args, **kwargs): + pass + + +class FormatSuffixTests(TestCase): + def _test_urlpatterns(self, urlpatterns, test_paths): + factory = RequestFactory() + try: + urlpatterns = format_suffix_patterns(urlpatterns) + except: + self.fail("Failed to apply `format_suffix_patterns` on the supplied urlpatterns") + resolver = urlresolvers.RegexURLResolver(r'^/', urlpatterns) + for test_path in test_paths: + request = factory.get(test_path.path) + try: + callback, callback_args, callback_kwargs = resolver.resolve(request.path_info) + except: + self.fail("Failed to resolve URL: %s" % request.path_info) + self.assertEquals(callback_args, test_path.args) + self.assertEquals(callback_kwargs, test_path.kwargs) + + def test_format_suffix(self): + urlpatterns = patterns( + '', + url(r'^test$', test_view), + ) + test_paths = [ + URLTestPath('/test', (), {}), + URLTestPath('/test.api', (), {'format': 'api'}), + URLTestPath('/test.asdf', (), {'format': 'asdf'}), + ] + self._test_urlpatterns(urlpatterns, test_paths) + + def test_default_args(self): + urlpatterns = patterns( + '', + url(r'^test$', test_view, {'foo': 'bar'}), + ) + test_paths = [ + URLTestPath('/test', (), {'foo': 'bar', }), + URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}), + URLTestPath('/test.asdf', (), {'foo': 'bar', 'format': 'asdf'}), + ] + self._test_urlpatterns(urlpatterns, test_paths) + + def test_included_urls(self): + nested_patterns = patterns( + '', + url(r'^path$', test_view) + ) + urlpatterns = patterns( + '', + url(r'^test/', include(nested_patterns), {'foo': 'bar'}), + ) + test_paths = [ + URLTestPath('/test/path', (), {'foo': 'bar', }), + URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}), + URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}), + ] + self._test_urlpatterns(urlpatterns, test_paths) -- cgit v1.2.3 From dc1c57d595c3917e3fed9076894d5fa88ec083c9 Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Mon, 21 Jan 2013 12:45:30 +0100 Subject: Add failed testcase for fieldvalidation --- rest_framework/tests/serializer.py | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/serializer.py b/rest_framework/tests/serializer.py index bd96ba23..0ba4e765 100644 --- a/rest_framework/tests/serializer.py +++ b/rest_framework/tests/serializer.py @@ -241,6 +241,14 @@ class ValidationTests(TestCase): self.assertFalse(serializer.is_valid()) self.assertEquals(serializer.errors, {'content': [u'Test not in value']}) + incomplete_data = { + 'email': 'tom@example.com', + 'created': datetime.datetime(2012, 1, 1) + } + serializer = CommentSerializerWithFieldValidator(data=incomplete_data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'content': [u'This field is required.']}) + def test_bad_type_data_is_false(self): """ Data of the wrong type is not valid. -- cgit v1.2.3 From e7916ae0b1c4af35c55dc21e0d882f3f8ff3121e Mon Sep 17 00:00:00 2001 From: Kevin Stone Date: Mon, 21 Jan 2013 09:37:50 -0800 Subject: Tweaked some method names to be more clear and added a docstring to the test case class. Signed-off-by: Kevin Stone --- rest_framework/tests/urlpatterns.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/urlpatterns.py b/rest_framework/tests/urlpatterns.py index e96e7cf3..43e8ef69 100644 --- a/rest_framework/tests/urlpatterns.py +++ b/rest_framework/tests/urlpatterns.py @@ -13,12 +13,15 @@ from rest_framework.urlpatterns import format_suffix_patterns URLTestPath = namedtuple('URLTestPath', ['path', 'args', 'kwargs']) -def test_view(request, *args, **kwargs): +def dummy_view(request, *args, **kwargs): pass class FormatSuffixTests(TestCase): - def _test_urlpatterns(self, urlpatterns, test_paths): + """ + Tests `format_suffix_patterns` against different URLPatterns to ensure the URLs still resolve properly, including any captured parameters. + """ + def _resolve_urlpatterns(self, urlpatterns, test_paths): factory = RequestFactory() try: urlpatterns = format_suffix_patterns(urlpatterns) @@ -37,31 +40,31 @@ class FormatSuffixTests(TestCase): def test_format_suffix(self): urlpatterns = patterns( '', - url(r'^test$', test_view), + url(r'^test$', dummy_view), ) test_paths = [ URLTestPath('/test', (), {}), URLTestPath('/test.api', (), {'format': 'api'}), URLTestPath('/test.asdf', (), {'format': 'asdf'}), ] - self._test_urlpatterns(urlpatterns, test_paths) + self._resolve_urlpatterns(urlpatterns, test_paths) def test_default_args(self): urlpatterns = patterns( '', - url(r'^test$', test_view, {'foo': 'bar'}), + url(r'^test$', dummy_view, {'foo': 'bar'}), ) test_paths = [ URLTestPath('/test', (), {'foo': 'bar', }), URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}), URLTestPath('/test.asdf', (), {'foo': 'bar', 'format': 'asdf'}), ] - self._test_urlpatterns(urlpatterns, test_paths) + self._resolve_urlpatterns(urlpatterns, test_paths) def test_included_urls(self): nested_patterns = patterns( '', - url(r'^path$', test_view) + url(r'^path$', dummy_view) ) urlpatterns = patterns( '', @@ -72,4 +75,4 @@ class FormatSuffixTests(TestCase): URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}), URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}), ] - self._test_urlpatterns(urlpatterns, test_paths) + self._resolve_urlpatterns(urlpatterns, test_paths) -- cgit v1.2.3 From 65b62d64ec54b528b62a1500b8f6ffe216d45c09 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 21 Jan 2013 21:29:49 +0000 Subject: WWW-Authenticate responses --- rest_framework/tests/authentication.py | 41 +++++++++++++++++----------------- 1 file changed, 21 insertions(+), 20 deletions(-) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/authentication.py b/rest_framework/tests/authentication.py index e86041bc..1f17e8d2 100644 --- a/rest_framework/tests/authentication.py +++ b/rest_framework/tests/authentication.py @@ -4,7 +4,7 @@ from django.test import Client, TestCase from rest_framework import permissions from rest_framework.authtoken.models import Token -from rest_framework.authentication import TokenAuthentication +from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication from rest_framework.compat import patterns from rest_framework.views import APIView @@ -21,10 +21,10 @@ class MockView(APIView): def put(self, request): return HttpResponse({'a': 1, 'b': 2, 'c': 3}) -MockView.authentication_classes += (TokenAuthentication,) - urlpatterns = patterns('', - (r'^$', MockView.as_view()), + (r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])), + (r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])), + (r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])), (r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'), ) @@ -43,24 +43,25 @@ class BasicAuthTests(TestCase): def test_post_form_passing_basic_auth(self): """Ensure POSTing json over basic auth with correct credentials passes and does not require CSRF""" auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip() - response = self.csrf_client.post('/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) + response = self.csrf_client.post('/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 200) def test_post_json_passing_basic_auth(self): """Ensure POSTing form over basic auth with correct credentials passes and does not require CSRF""" auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip() - response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth) + response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 200) def test_post_form_failing_basic_auth(self): """Ensure POSTing form over basic auth without correct credentials fails""" - response = self.csrf_client.post('/', {'example': 'example'}) - self.assertEqual(response.status_code, 403) + response = self.csrf_client.post('/basic/', {'example': 'example'}) + self.assertEqual(response.status_code, 401) def test_post_json_failing_basic_auth(self): """Ensure POSTing json over basic auth without correct credentials fails""" - response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json') - self.assertEqual(response.status_code, 403) + response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json') + self.assertEqual(response.status_code, 401) + self.assertEqual(response['WWW-Authenticate'], 'Basic realm="api"') class SessionAuthTests(TestCase): @@ -83,7 +84,7 @@ class SessionAuthTests(TestCase): 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'}) + response = self.csrf_client.post('/session/', {'example': 'example'}) self.assertEqual(response.status_code, 403) def test_post_form_session_auth_passing(self): @@ -91,7 +92,7 @@ class SessionAuthTests(TestCase): 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'}) + response = self.non_csrf_client.post('/session/', {'example': 'example'}) self.assertEqual(response.status_code, 200) def test_put_form_session_auth_passing(self): @@ -99,14 +100,14 @@ class SessionAuthTests(TestCase): 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'}) + response = self.non_csrf_client.put('/session/', {'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. """ - response = self.csrf_client.post('/', {'example': 'example'}) + response = self.csrf_client.post('/session/', {'example': 'example'}) self.assertEqual(response.status_code, 403) @@ -127,24 +128,24 @@ class TokenAuthTests(TestCase): def test_post_form_passing_token_auth(self): """Ensure POSTing json over token auth with correct credentials passes and does not require CSRF""" auth = "Token " + self.key - response = self.csrf_client.post('/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) + response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 200) def test_post_json_passing_token_auth(self): """Ensure POSTing form over token auth with correct credentials passes and does not require CSRF""" auth = "Token " + self.key - response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth) + response = self.csrf_client.post('/token/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, 200) def test_post_form_failing_token_auth(self): """Ensure POSTing form over token auth without correct credentials fails""" - response = self.csrf_client.post('/', {'example': 'example'}) - self.assertEqual(response.status_code, 403) + response = self.csrf_client.post('/token/', {'example': 'example'}) + self.assertEqual(response.status_code, 401) def test_post_json_failing_token_auth(self): """Ensure POSTing json over token auth without correct credentials fails""" - response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json') - self.assertEqual(response.status_code, 403) + response = self.csrf_client.post('/token/', json.dumps({'example': 'example'}), 'application/json') + self.assertEqual(response.status_code, 401) def test_token_has_auto_assigned_key_if_none_provided(self): """Ensure creating a token with no key will auto-assign a key""" -- cgit v1.2.3 From f0071dbccd592ba3157738ced66809869f68b1cb Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Wed, 23 Jan 2013 07:52:56 +0100 Subject: Add separate test for failed custom validation --- rest_framework/tests/serializer.py | 96 +++++++++++++++++++++++--------------- 1 file changed, 59 insertions(+), 37 deletions(-) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/serializer.py b/rest_framework/tests/serializer.py index 0ba4e765..b4428ca3 100644 --- a/rest_framework/tests/serializer.py +++ b/rest_framework/tests/serializer.py @@ -162,7 +162,6 @@ class BasicTests(TestCase): """ Attempting to update fields set as read_only should have no effect. """ - serializer = PersonSerializer(self.person, data={'name': 'dwight', 'age': 99}) self.assertEquals(serializer.is_valid(), True) instance = serializer.save() @@ -183,8 +182,7 @@ class ValidationTests(TestCase): 'content': 'x' * 1001, 'created': datetime.datetime(2012, 1, 1) } - self.actionitem = ActionItem(title='Some to do item', - ) + self.actionitem = ActionItem(title='Some to do item',) def test_create(self): serializer = CommentSerializer(data=self.data) @@ -216,39 +214,6 @@ class ValidationTests(TestCase): self.assertEquals(serializer.is_valid(), True) self.assertEquals(serializer.errors, {}) - def test_field_validation(self): - - class CommentSerializerWithFieldValidator(CommentSerializer): - - def validate_content(self, attrs, source): - value = attrs[source] - if "test" not in value: - raise serializers.ValidationError("Test not in value") - return attrs - - data = { - 'email': 'tom@example.com', - 'content': 'A test comment', - 'created': datetime.datetime(2012, 1, 1) - } - - serializer = CommentSerializerWithFieldValidator(data=data) - self.assertTrue(serializer.is_valid()) - - data['content'] = 'This should not validate' - - serializer = CommentSerializerWithFieldValidator(data=data) - self.assertFalse(serializer.is_valid()) - self.assertEquals(serializer.errors, {'content': [u'Test not in value']}) - - incomplete_data = { - 'email': 'tom@example.com', - 'created': datetime.datetime(2012, 1, 1) - } - serializer = CommentSerializerWithFieldValidator(data=incomplete_data) - self.assertFalse(serializer.is_valid()) - self.assertEquals(serializer.errors, {'content': [u'This field is required.']}) - def test_bad_type_data_is_false(self): """ Data of the wrong type is not valid. @@ -318,12 +283,69 @@ class ValidationTests(TestCase): self.assertEquals(serializer.errors, {'info': [u'Ensure this value has at most 12 characters (it has 13).']}) +class CustomValidationTests(TestCase): + class CommentSerializerWithFieldValidator(CommentSerializer): + + def validate_email(self, attrs, source): + value = attrs[source] + + return attrs + + def validate_content(self, attrs, source): + value = attrs[source] + if "test" not in value: + raise serializers.ValidationError("Test not in value") + return attrs + + def test_field_validation(self): + data = { + 'email': 'tom@example.com', + 'content': 'A test comment', + 'created': datetime.datetime(2012, 1, 1) + } + + serializer = self.CommentSerializerWithFieldValidator(data=data) + self.assertTrue(serializer.is_valid()) + + data['content'] = 'This should not validate' + + serializer = self.CommentSerializerWithFieldValidator(data=data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'content': [u'Test not in value']}) + + def test_missing_data(self): + """ + Make sure that validate_content isn't called if the field is missing + """ + incomplete_data = { + 'email': 'tom@example.com', + 'created': datetime.datetime(2012, 1, 1) + } + serializer = self.CommentSerializerWithFieldValidator(data=incomplete_data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'content': [u'This field is required.']}) + + def test_wrong_data(self): + """ + Make sure that validate_content isn't called if the field input is wrong + """ + wrong_data = { + 'email': 'not an email', + 'content': 'A test comment', + 'created': datetime.datetime(2012, 1, 1) + } + serializer = self.CommentSerializerWithFieldValidator(data=wrong_data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'email': [u'Enter a valid e-mail address.']}) + + class PositiveIntegerAsChoiceTests(TestCase): def test_positive_integer_in_json_is_correctly_parsed(self): - data = {'some_integer':1} + data = {'some_integer': 1} serializer = PositiveIntegerAsChoiceSerializer(data=data) self.assertEquals(serializer.is_valid(), True) + class ModelValidationTests(TestCase): def test_validate_unique(self): """ -- cgit v1.2.3 From d6628d4e788693fe764a388b29b3c27f37d8fc87 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 24 Jan 2013 08:58:19 +0000 Subject: Test for #552. --- rest_framework/tests/pagination.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/pagination.py b/rest_framework/tests/pagination.py index 3b550877..e2492958 100644 --- a/rest_framework/tests/pagination.py +++ b/rest_framework/tests/pagination.py @@ -262,6 +262,11 @@ class CustomField(serializers.Field): class BasicModelSerializer(serializers.Serializer): text = CustomField() + def __init__(self, *args, **kwargs): + super(BasicModelSerializer, self).__init__(*args, **kwargs) + if not 'view' in self.context: + raise RuntimeError("context isn't getting passed into serializer init") + class TestContextPassedToCustomField(TestCase): def setUp(self): @@ -278,4 +283,3 @@ class TestContextPassedToCustomField(TestCase): response = self.view(request).render() self.assertEquals(response.status_code, status.HTTP_200_OK) - -- cgit v1.2.3 From b73d7e9bb4158d5cbbd9121cda3131b6e0cafd79 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 25 Jan 2013 13:58:19 +0000 Subject: Cleaning up GFK test module. Refs #607. --- rest_framework/tests/genericrelations.py | 43 +++++++++++++++++++++++--------- rest_framework/tests/models.py | 21 ---------------- 2 files changed, 31 insertions(+), 33 deletions(-) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/genericrelations.py b/rest_framework/tests/genericrelations.py index bc7378e1..dcdd8329 100644 --- a/rest_framework/tests/genericrelations.py +++ b/rest_framework/tests/genericrelations.py @@ -1,23 +1,42 @@ +from django.contrib.contenttypes.models import ContentType +from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey +from django.db import models from django.test import TestCase from rest_framework import serializers -from rest_framework.tests.models import * + + +class Tag(models.Model): + """ + Tags have a descriptive slug, and are attached to an arbitrary object. + """ + tag = models.SlugField() + content_type = models.ForeignKey(ContentType) + object_id = models.PositiveIntegerField() + content_object = GenericForeignKey('content_type', 'object_id') + + def __unicode__(self): + return self.tag + + +class Bookmark(models.Model): + """ + A URL bookmark that may have multiple tags attached. + """ + url = models.URLField() + tags = GenericRelation(Tag) class TestGenericRelations(TestCase): def setUp(self): - bookmark = Bookmark(url='https://www.djangoproject.com/') - bookmark.save() - django = Tag(tag_name='django') - django.save() - python = Tag(tag_name='python') - python.save() - t1 = TaggedItem(content_object=bookmark, tag=django) - t1.save() - t2 = TaggedItem(content_object=bookmark, tag=python) - t2.save() - self.bookmark = bookmark + self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/') + Tag.objects.create(content_object=self.bookmark, tag='django') + Tag.objects.create(content_object=self.bookmark, tag='python') def test_reverse_generic_relation(self): + """ + Test a relationship that spans a GenericRelation field. + """ + class BookmarkSerializer(serializers.ModelSerializer): tags = serializers.ManyRelatedField(source='tags') diff --git a/rest_framework/tests/models.py b/rest_framework/tests/models.py index 93f09761..9ab15328 100644 --- a/rest_framework/tests/models.py +++ b/rest_framework/tests/models.py @@ -86,27 +86,6 @@ class ReadOnlyManyToManyModel(RESTFrameworkModel): text = models.CharField(max_length=100, default='anchor') rel = models.ManyToManyField(Anchor) -# Models to test generic relations - - -class Tag(RESTFrameworkModel): - tag_name = models.SlugField() - - -class TaggedItem(RESTFrameworkModel): - tag = models.ForeignKey(Tag, related_name='items') - content_type = models.ForeignKey(ContentType) - object_id = models.PositiveIntegerField() - content_object = GenericForeignKey('content_type', 'object_id') - - def __unicode__(self): - return self.tag.tag_name - - -class Bookmark(RESTFrameworkModel): - url = models.URLField() - tags = GenericRelation(TaggedItem) - # Model to test filtering. class FilterableItem(RESTFrameworkModel): -- cgit v1.2.3 From b783887c33fa149112469af788d9c1f000bc4a2e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 25 Jan 2013 14:36:27 +0000 Subject: Test for GFK, using RelatedField. Refs #607. --- rest_framework/tests/genericrelations.py | 57 +++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 5 deletions(-) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/genericrelations.py b/rest_framework/tests/genericrelations.py index dcdd8329..146ad1e4 100644 --- a/rest_framework/tests/genericrelations.py +++ b/rest_framework/tests/genericrelations.py @@ -12,7 +12,7 @@ class Tag(models.Model): tag = models.SlugField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() - content_object = GenericForeignKey('content_type', 'object_id') + tagged_item = GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.tag @@ -25,20 +25,37 @@ class Bookmark(models.Model): url = models.URLField() tags = GenericRelation(Tag) + def __unicode__(self): + return 'Bookmark: %s' % self.url + + +class Note(models.Model): + """ + A textual note that may have multiple tags attached. + """ + text = models.TextField() + tags = GenericRelation(Tag) + + def __unicode__(self): + return 'Note: %s' % self.text + class TestGenericRelations(TestCase): def setUp(self): self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/') - Tag.objects.create(content_object=self.bookmark, tag='django') - Tag.objects.create(content_object=self.bookmark, tag='python') + Tag.objects.create(tagged_item=self.bookmark, tag='django') + Tag.objects.create(tagged_item=self.bookmark, tag='python') + self.note = Note.objects.create(text='Remember the milk') + Tag.objects.create(tagged_item=self.note, tag='reminder') - def test_reverse_generic_relation(self): + def test_generic_relation(self): """ Test a relationship that spans a GenericRelation field. + IE. A reverse generic relationship. """ class BookmarkSerializer(serializers.ModelSerializer): - tags = serializers.ManyRelatedField(source='tags') + tags = serializers.ManyRelatedField() class Meta: model = Bookmark @@ -50,3 +67,33 @@ class TestGenericRelations(TestCase): 'url': u'https://www.djangoproject.com/' } self.assertEquals(serializer.data, expected) + + def test_generic_fk(self): + """ + Test a relationship that spans a GenericForeignKey field. + IE. A forward generic relationship. + """ + + class TagSerializer(serializers.ModelSerializer): + tagged_item = serializers.RelatedField() + + class Meta: + model = Tag + exclude = ('id', 'content_type', 'object_id') + + serializer = TagSerializer(Tag.objects.all()) + expected = [ + { + 'tag': u'django', + 'tagged_item': u'Bookmark: https://www.djangoproject.com/' + }, + { + 'tag': u'python', + 'tagged_item': u'Bookmark: https://www.djangoproject.com/' + }, + { + 'tag': u'reminder', + 'tagged_item': u'Note: Remember the milk' + } + ] + self.assertEquals(serializer.data, expected) -- cgit v1.2.3 From 4d43e9f7def1ee3a3b37635dbd8487ee7ca61132 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 26 Jan 2013 20:55:09 +0000 Subject: Test for custom pagination serializers. Also refs #604. --- rest_framework/tests/pagination.py | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'rest_framework/tests') diff --git a/rest_framework/tests/pagination.py b/rest_framework/tests/pagination.py index e2492958..697dfb5b 100644 --- a/rest_framework/tests/pagination.py +++ b/rest_framework/tests/pagination.py @@ -252,6 +252,8 @@ class TestCustomPaginateByParam(TestCase): self.assertEquals(response.data['results'], self.data[:5]) +### Tests for context in pagination serializers + class CustomField(serializers.Field): def to_native(self, value): if not 'view' in self.context: @@ -283,3 +285,40 @@ class TestContextPassedToCustomField(TestCase): response = self.view(request).render() self.assertEquals(response.status_code, status.HTTP_200_OK) + + +### Tests for custom pagination serializers + +class LinksSerializer(serializers.Serializer): + next = pagination.NextPageField(source='*') + prev = pagination.PreviousPageField(source='*') + + +class CustomPaginationSerializer(pagination.BasePaginationSerializer): + links = LinksSerializer(source='*') # Takes the page object as the source + total_results = serializers.Field(source='paginator.count') + + results_field = 'objects' + + +class TestCustomPaginationSerializer(TestCase): + def setUp(self): + objects = ['john', 'paul', 'george', 'ringo'] + paginator = Paginator(objects, 2) + self.page = paginator.page(1) + + def test_custom_pagination_serializer(self): + request = RequestFactory().get('/foobar') + serializer = CustomPaginationSerializer( + instance=self.page, + context={'request': request} + ) + expected = { + 'links': { + 'next': 'http://testserver/foobar?page=2', + 'prev': None + }, + 'total_results': 4, + 'objects': ['john', 'paul'] + } + self.assertEquals(serializer.data, expected) -- cgit v1.2.3