Tests now run with django-discover-runner instead of a custom suite.

This commit is contained in:
Omer Katz 2013-01-24 20:05:25 +03:00
parent a57c0c5aae
commit bbd0ef84b4
37 changed files with 346 additions and 476 deletions

1
development.txt Normal file
View File

@ -0,0 +1 @@
django-discover-runner>=0.2.2

View File

@ -11,10 +11,12 @@ import sys
# fix sys path so we don't need to setup PYTHONPATH
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'rest_framework.runtests.settings'
os.environ['DJANGO_SETTINGS_MODULE'] = 'rest_framework.tests.settings'
try:
from coverage import coverage
except ImportError:
print("Coverage is not installed. Aborting...")
def main():
"""Run the tests for rest_framework and generate a coverage report."""
@ -25,12 +27,14 @@ def main():
from django.conf import settings
from django.test.utils import get_runner
TestRunner = get_runner(settings)
if hasattr(TestRunner, 'func_name'):
# Pre 1.2 test runners were just functions,
# and did not support the 'failfast' option.
import warnings
warnings.warn(
'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.',
DeprecationWarning

View File

@ -1,43 +1,11 @@
#!/usr/bin/env python
# http://ericholscher.com/blog/2009/jun/29/enable-setuppy-test-your-django-apps/
# http://www.travisswicegood.com/2010/01/17/django-virtualenv-pip-and-fabric/
# http://code.djangoproject.com/svn/django/trunk/tests/runtests.py
import os
import sys
# fix sys path so we don't need to setup PYTHONPATH
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'rest_framework.runtests.settings'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rest_framework.tests.settings")
from django.conf import settings
from django.test.utils import get_runner
from django.core.management import execute_from_command_line
def usage():
return """
Usage: python runtests.py [UnitTestClass].[method]
You can pass the Class name of the `UnitTestClass` you want to test.
Append a method name if you only want to test a specific method of that class.
"""
def main():
TestRunner = get_runner(settings)
test_runner = TestRunner()
if len(sys.argv) == 2:
test_case = '.' + sys.argv[1]
elif len(sys.argv) == 1:
test_case = ''
else:
print usage()
sys.exit(1)
failures = test_runner.run_tests(['tests' + test_case])
sys.exit(failures)
if __name__ == '__main__':
main()
sys.argv.append('test')
execute_from_command_line(sys.argv)

View File

@ -1,117 +0,0 @@
# Django settings for testproject project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DEBUG_PROPAGATE_EXCEPTIONS = True
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'sqlite.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-uk'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'u@x-aj9(hoh#rb-^ymf#g2jx_hp0vj7u5#b@ag1n^seu9e!%cy'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'rest_framework',
'rest_framework.authtoken',
'rest_framework.tests'
)
STATIC_URL = '/static/'
import django
if django.VERSION < (1, 3):
INSTALLED_APPS += ('staticfiles',)
# If we're running on the Jenkins server we want to archive the coverage reports as XML.
import os
if os.environ.get('HUDSON_URL', None):
TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner'
TEST_OUTPUT_VERBOSE = True
TEST_OUTPUT_DESCRIPTIONS = True
TEST_OUTPUT_DIR = 'xmlrunner'

View File

@ -11,6 +11,7 @@ from rest_framework.views import APIView
import json
import base64
import sure
class MockView(APIView):
permission_classes = (permissions.IsAuthenticated,)
@ -31,7 +32,7 @@ urlpatterns = patterns('',
class BasicAuthTests(TestCase):
"""Basic authentication"""
urls = 'rest_framework.tests.authentication'
urls = 'rest_framework.tests.test_authentication'
def setUp(self):
self.csrf_client = Client(enforce_csrf_checks=True)
@ -44,29 +45,30 @@ class BasicAuthTests(TestCase):
"""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('/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
response.status_code.should.equal(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('/basic/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json',
HTTP_AUTHORIZATION=auth)
response.status_code.should.equal(200)
def test_post_form_failing_basic_auth(self):
"""Ensure POSTing form over basic auth without correct credentials fails"""
response = self.csrf_client.post('/basic/', {'example': 'example'})
self.assertEqual(response.status_code, 401)
response.status_code.should.equal(401)
def test_post_json_failing_basic_auth(self):
"""Ensure POSTing json over basic auth without correct credentials fails"""
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"')
response.status_code.should.equal(401)
response['WWW-Authenticate'].should.equal('Basic realm="api"')
class SessionAuthTests(TestCase):
"""User session authentication"""
urls = 'rest_framework.tests.authentication'
urls = 'rest_framework.tests.test_authentication'
def setUp(self):
self.csrf_client = Client(enforce_csrf_checks=True)
@ -85,7 +87,7 @@ class SessionAuthTests(TestCase):
"""
self.csrf_client.login(username=self.username, password=self.password)
response = self.csrf_client.post('/session/', {'example': 'example'})
self.assertEqual(response.status_code, 403)
response.status_code.should.equal(403)
def test_post_form_session_auth_passing(self):
"""
@ -93,7 +95,7 @@ class SessionAuthTests(TestCase):
"""
self.non_csrf_client.login(username=self.username, password=self.password)
response = self.non_csrf_client.post('/session/', {'example': 'example'})
self.assertEqual(response.status_code, 200)
response.status_code.should.equal(200)
def test_put_form_session_auth_passing(self):
"""
@ -101,19 +103,19 @@ class SessionAuthTests(TestCase):
"""
self.non_csrf_client.login(username=self.username, password=self.password)
response = self.non_csrf_client.put('/session/', {'example': 'example'})
self.assertEqual(response.status_code, 200)
response.status_code.should.equal(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('/session/', {'example': 'example'})
self.assertEqual(response.status_code, 403)
response.status_code.should.equal(403)
class TokenAuthTests(TestCase):
"""Token authentication"""
urls = 'rest_framework.tests.authentication'
urls = 'rest_framework.tests.test_authentication'
def setUp(self):
self.csrf_client = Client(enforce_csrf_checks=True)
@ -129,29 +131,30 @@ class TokenAuthTests(TestCase):
"""Ensure POSTing json over token auth with correct credentials passes and does not require CSRF"""
auth = "Token " + self.key
response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
response.status_code.should.equal(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('/token/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
response = self.csrf_client.post('/token/', json.dumps({'example': 'example'}), 'application/json',
HTTP_AUTHORIZATION=auth)
response.status_code.should.equal(200)
def test_post_form_failing_token_auth(self):
"""Ensure POSTing form over token auth without correct credentials fails"""
response = self.csrf_client.post('/token/', {'example': 'example'})
self.assertEqual(response.status_code, 401)
response.status_code.should.equal(401)
def test_post_json_failing_token_auth(self):
"""Ensure POSTing json over token auth without correct credentials fails"""
response = self.csrf_client.post('/token/', json.dumps({'example': 'example'}), 'application/json')
self.assertEqual(response.status_code, 401)
response.status_code.should.equal(401)
def test_token_has_auto_assigned_key_if_none_provided(self):
"""Ensure creating a token with no key will auto-assign a key"""
self.token.delete()
token = Token.objects.create(user=self.user)
self.assertTrue(bool(token.key))
token.key.should.be.ok
def test_token_login_json(self):
"""Ensure token login view using JSON POST works."""

View File

@ -35,7 +35,7 @@ urlpatterns = patterns('',
class BreadcrumbTests(TestCase):
"""Tests the breadcrumb functionality used by the HTML renderer."""
urls = 'rest_framework.tests.breadcrumbs'
urls = 'rest_framework.tests.test_breadcrumbs'
def test_root_breadcrumbs(self):
url = '/'

View File

@ -20,7 +20,6 @@ from rest_framework.tests.utils import RequestFactory
class DecoratorTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
@ -51,7 +50,6 @@ class DecoratorTestCase(TestCase):
return Response()
def test_calling_method(self):
@api_view(['GET'])
def view(request):
return Response({})
@ -65,7 +63,6 @@ class DecoratorTestCase(TestCase):
self.assertEqual(response.status_code, 405)
def test_calling_put_method(self):
@api_view(['GET', 'PUT'])
def view(request):
return Response({})
@ -79,7 +76,6 @@ class DecoratorTestCase(TestCase):
self.assertEqual(response.status_code, 405)
def test_calling_patch_method(self):
@api_view(['GET', 'PATCH'])
def view(request):
return Response({})
@ -93,7 +89,6 @@ class DecoratorTestCase(TestCase):
self.assertEqual(response.status_code, 405)
def test_renderer_classes(self):
@api_view(['GET'])
@renderer_classes([JSONRenderer])
def view(request):
@ -104,7 +99,6 @@ class DecoratorTestCase(TestCase):
self.assertTrue(isinstance(response.accepted_renderer, JSONRenderer))
def test_parser_classes(self):
@api_view(['GET'])
@parser_classes([JSONParser])
def view(request):
@ -117,7 +111,6 @@ class DecoratorTestCase(TestCase):
view(request)
def test_authentication_classes(self):
@api_view(['GET'])
@authentication_classes([BasicAuthentication])
def view(request):
@ -130,7 +123,6 @@ class DecoratorTestCase(TestCase):
view(request)
def test_permission_classes(self):
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def view(request):

View File

@ -48,20 +48,25 @@ MARKED_DOWN_gte_21 = """<h2 id="an-example-docstring">an example docstring</h2>
class TestViewNamesAndDescriptions(TestCase):
def test_resource_name_uses_classname_by_default(self):
"""Ensure Resource names are based on the classname by default."""
class MockView(APIView):
pass
self.assertEquals(MockView().get_name(), 'Mock')
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(APIView):
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."""
class MockView(APIView):
"""an example docstring
====================
@ -86,8 +91,10 @@ class TestViewNamesAndDescriptions(TestCase):
class MockView(APIView):
"""docstring"""
def get_description(self):
return example
self.assertEquals(MockView().get_description(), example)
def test_resource_description_does_not_require_docstring(self):
@ -97,12 +104,15 @@ class TestViewNamesAndDescriptions(TestCase):
class MockView(APIView):
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."""
class MockView(APIView):
pass
self.assertEquals(MockView().get_description(), '')
def test_markdown(self):

View File

@ -9,7 +9,6 @@ from rest_framework.tests.models import FilterableItem, BasicModel
factory = RequestFactory()
if django_filters:
# Basic filter on a list view.
class FilterFieldsRootView(generics.ListCreateAPIView):

View File

@ -39,7 +39,7 @@ urlpatterns = patterns('',
class TemplateHTMLRendererTests(TestCase):
urls = 'rest_framework.tests.htmlrenderer'
urls = 'rest_framework.tests.test_htmlrenderer'
def setUp(self):
"""
@ -79,7 +79,7 @@ class TemplateHTMLRendererTests(TestCase):
class TemplateHTMLRendererExceptionTests(TestCase):
urls = 'rest_framework.tests.htmlrenderer'
urls = 'rest_framework.tests.test_htmlrenderer'
def setUp(self):
"""

View File

@ -20,7 +20,8 @@ class BlogPostCommentSerializer(serializers.ModelSerializer):
class PhotoSerializer(serializers.Serializer):
description = serializers.CharField()
album_url = serializers.HyperlinkedRelatedField(source='album', view_name='album-detail', queryset=Album.objects.all(), slug_field='title', slug_url_kwarg='title')
album_url = serializers.HyperlinkedRelatedField(source='album', view_name='album-detail',
queryset=Album.objects.all(), slug_field='title', slug_url_kwarg='title')
def restore_object(self, attrs, instance=None):
return Photo(**attrs)
@ -95,7 +96,7 @@ urlpatterns = patterns('',
class TestBasicHyperlinkedView(TestCase):
urls = 'rest_framework.tests.hyperlinkedserializers'
urls = 'rest_framework.tests.test_hyperlinkedserializers'
def setUp(self):
"""
@ -132,7 +133,7 @@ class TestBasicHyperlinkedView(TestCase):
class TestManyToManyHyperlinkedView(TestCase):
urls = 'rest_framework.tests.hyperlinkedserializers'
urls = 'rest_framework.tests.test_hyperlinkedserializers'
def setUp(self):
"""
@ -180,7 +181,7 @@ class TestManyToManyHyperlinkedView(TestCase):
class TestCreateWithForeignKeys(TestCase):
urls = 'rest_framework.tests.hyperlinkedserializers'
urls = 'rest_framework.tests.test_hyperlinkedserializers'
def setUp(self):
"""
@ -190,7 +191,6 @@ class TestCreateWithForeignKeys(TestCase):
self.create_view = BlogPostCommentListCreate.as_view()
def test_create_comment(self):
data = {
'text': 'A test comment',
'blog_post_url': 'http://testserver/posts/1/'
@ -205,7 +205,7 @@ class TestCreateWithForeignKeys(TestCase):
class TestCreateWithForeignKeysAndCustomSlug(TestCase):
urls = 'rest_framework.tests.hyperlinkedserializers'
urls = 'rest_framework.tests.test_hyperlinkedserializers'
def setUp(self):
"""
@ -215,7 +215,6 @@ class TestCreateWithForeignKeysAndCustomSlug(TestCase):
self.list_create_view = PhotoListCreate.as_view()
def test_create_photo(self):
data = {
'description': 'A test photo',
'album_url': 'http://testserver/albums/test-album/'
@ -224,13 +223,14 @@ class TestCreateWithForeignKeysAndCustomSlug(TestCase):
request = factory.post('/photos/', data=data)
response = self.list_create_view(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertNotIn('Location', response, msg='Location should only be included if there is a "url" field on the serializer')
self.assertNotIn('Location', response,
msg='Location should only be included if there is a "url" field on the serializer')
self.assertEqual(self.post.photo_set.count(), 1)
self.assertEqual(self.post.photo_set.all()[0].description, 'A test photo')
class TestOptionalRelationHyperlinkedView(TestCase):
urls = 'rest_framework.tests.hyperlinkedserializers'
urls = 'rest_framework.tests.test_hyperlinkedserializers'
def setUp(self):
"""

View File

@ -97,7 +97,6 @@ class IntegrationTestPagination(TestCase):
class IntegrationTestPaginationAndFiltering(TestCase):
def setUp(self):
"""
Create 50 FilterableItem instances.

View File

@ -59,7 +59,7 @@ class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer):
# TODO: Add test that .data cannot be accessed prior to .is_valid
class HyperlinkedManyToManyTests(TestCase):
urls = 'rest_framework.tests.relations_hyperlink'
urls = 'rest_framework.tests.test_relations_hyperlink'
def setUp(self):
for idx in range(1, 4):
@ -75,8 +75,10 @@ class HyperlinkedManyToManyTests(TestCase):
serializer = ManyToManySourceSerializer(queryset)
expected = [
{'url': '/manytomanysource/1/', 'name': u'source-1', 'targets': ['/manytomanytarget/1/']},
{'url': '/manytomanysource/2/', 'name': u'source-2', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': u'source-3', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}
{'url': '/manytomanysource/2/', 'name': u'source-2',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': u'source-3',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}
]
self.assertEquals(serializer.data, expected)
@ -84,14 +86,17 @@ class HyperlinkedManyToManyTests(TestCase):
queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset)
expected = [
{'url': '/manytomanytarget/1/', 'name': u'target-1', 'sources': ['/manytomanysource/1/', '/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/2/', 'name': u'target-2', 'sources': ['/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/1/', 'name': u'target-1',
'sources': ['/manytomanysource/1/', '/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/2/', 'name': u'target-2',
'sources': ['/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/3/', 'name': u'target-3', 'sources': ['/manytomanysource/3/']}
]
self.assertEquals(serializer.data, expected)
def test_many_to_many_update(self):
data = {'url': '/manytomanysource/1/', 'name': u'source-1', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}
data = {'url': '/manytomanysource/1/', 'name': u'source-1',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}
instance = ManyToManySource.objects.get(pk=1)
serializer = ManyToManySourceSerializer(instance, data=data)
self.assertTrue(serializer.is_valid())
@ -102,9 +107,12 @@ class HyperlinkedManyToManyTests(TestCase):
queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset)
expected = [
{'url': '/manytomanysource/1/', 'name': u'source-1', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']},
{'url': '/manytomanysource/2/', 'name': u'source-2', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': u'source-3', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}
{'url': '/manytomanysource/1/', 'name': u'source-1',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']},
{'url': '/manytomanysource/2/', 'name': u'source-2',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': u'source-3',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}
]
self.assertEquals(serializer.data, expected)
@ -121,14 +129,16 @@ class HyperlinkedManyToManyTests(TestCase):
serializer = ManyToManyTargetSerializer(queryset)
expected = [
{'url': '/manytomanytarget/1/', 'name': u'target-1', 'sources': ['/manytomanysource/1/']},
{'url': '/manytomanytarget/2/', 'name': u'target-2', 'sources': ['/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/2/', 'name': u'target-2',
'sources': ['/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/3/', 'name': u'target-3', 'sources': ['/manytomanysource/3/']}
]
self.assertEquals(serializer.data, expected)
def test_many_to_many_create(self):
data = {'url': '/manytomanysource/4/', 'name': u'source-4', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/3/']}
data = {'url': '/manytomanysource/4/', 'name': u'source-4',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/3/']}
serializer = ManyToManySourceSerializer(data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
@ -140,14 +150,18 @@ class HyperlinkedManyToManyTests(TestCase):
serializer = ManyToManySourceSerializer(queryset)
expected = [
{'url': '/manytomanysource/1/', 'name': u'source-1', 'targets': ['/manytomanytarget/1/']},
{'url': '/manytomanysource/2/', 'name': u'source-2', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': u'source-3', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']},
{'url': '/manytomanysource/4/', 'name': u'source-4', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/3/']}
{'url': '/manytomanysource/2/', 'name': u'source-2',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': u'source-3',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']},
{'url': '/manytomanysource/4/', 'name': u'source-4',
'targets': ['/manytomanytarget/1/', '/manytomanytarget/3/']}
]
self.assertEquals(serializer.data, expected)
def test_reverse_many_to_many_create(self):
data = {'url': '/manytomanytarget/4/', 'name': u'target-4', 'sources': ['/manytomanysource/1/', '/manytomanysource/3/']}
data = {'url': '/manytomanytarget/4/', 'name': u'target-4',
'sources': ['/manytomanysource/1/', '/manytomanysource/3/']}
serializer = ManyToManyTargetSerializer(data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
@ -158,16 +172,19 @@ class HyperlinkedManyToManyTests(TestCase):
queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset)
expected = [
{'url': '/manytomanytarget/1/', 'name': u'target-1', 'sources': ['/manytomanysource/1/', '/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/2/', 'name': u'target-2', 'sources': ['/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/1/', 'name': u'target-1',
'sources': ['/manytomanysource/1/', '/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/2/', 'name': u'target-2',
'sources': ['/manytomanysource/2/', '/manytomanysource/3/']},
{'url': '/manytomanytarget/3/', 'name': u'target-3', 'sources': ['/manytomanysource/3/']},
{'url': '/manytomanytarget/4/', 'name': u'target-4', 'sources': ['/manytomanysource/1/', '/manytomanysource/3/']}
{'url': '/manytomanytarget/4/', 'name': u'target-4',
'sources': ['/manytomanysource/1/', '/manytomanysource/3/']}
]
self.assertEquals(serializer.data, expected)
class HyperlinkedForeignKeyTests(TestCase):
urls = 'rest_framework.tests.relations_hyperlink'
urls = 'rest_framework.tests.test_relations_hyperlink'
def setUp(self):
target = ForeignKeyTarget(name='target-1')
@ -192,7 +209,8 @@ class HyperlinkedForeignKeyTests(TestCase):
queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset)
expected = [
{'url': '/foreignkeytarget/1/', 'name': u'target-1', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']},
{'url': '/foreignkeytarget/1/', 'name': u'target-1',
'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']},
{'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': []},
]
self.assertEquals(serializer.data, expected)
@ -223,7 +241,8 @@ class HyperlinkedForeignKeyTests(TestCase):
self.assertEquals(serializer.errors, {'target': [u'Incorrect type. Expected url string, received int.']})
def test_reverse_foreign_key_update(self):
data = {'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']}
data = {'url': '/foreignkeytarget/2/', 'name': u'target-2',
'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']}
instance = ForeignKeyTarget.objects.get(pk=2)
serializer = ForeignKeyTargetSerializer(instance, data=data)
self.assertTrue(serializer.is_valid())
@ -232,7 +251,8 @@ class HyperlinkedForeignKeyTests(TestCase):
queryset = ForeignKeyTarget.objects.all()
new_serializer = ForeignKeyTargetSerializer(queryset)
expected = [
{'url': '/foreignkeytarget/1/', 'name': u'target-1', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']},
{'url': '/foreignkeytarget/1/', 'name': u'target-1',
'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']},
{'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': []},
]
self.assertEquals(new_serializer.data, expected)
@ -245,7 +265,8 @@ class HyperlinkedForeignKeyTests(TestCase):
serializer = ForeignKeyTargetSerializer(queryset)
expected = [
{'url': '/foreignkeytarget/1/', 'name': u'target-1', 'sources': ['/foreignkeysource/2/']},
{'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']},
{'url': '/foreignkeytarget/2/', 'name': u'target-2',
'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']},
]
self.assertEquals(serializer.data, expected)
@ -269,7 +290,8 @@ class HyperlinkedForeignKeyTests(TestCase):
self.assertEquals(serializer.data, expected)
def test_reverse_foreign_key_create(self):
data = {'url': '/foreignkeytarget/3/', 'name': u'target-3', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']}
data = {'url': '/foreignkeytarget/3/', 'name': u'target-3',
'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']}
serializer = ForeignKeyTargetSerializer(data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
@ -282,7 +304,8 @@ class HyperlinkedForeignKeyTests(TestCase):
expected = [
{'url': '/foreignkeytarget/1/', 'name': u'target-1', 'sources': ['/foreignkeysource/2/']},
{'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': []},
{'url': '/foreignkeytarget/3/', 'name': u'target-3', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']},
{'url': '/foreignkeytarget/3/', 'name': u'target-3',
'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']},
]
self.assertEquals(serializer.data, expected)
@ -295,7 +318,7 @@ class HyperlinkedForeignKeyTests(TestCase):
class HyperlinkedNullableForeignKeyTests(TestCase):
urls = 'rest_framework.tests.relations_hyperlink'
urls = 'rest_framework.tests.test_relations_hyperlink'
def setUp(self):
target = ForeignKeyTarget(name='target-1')
@ -423,7 +446,7 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
class HyperlinkedNullableOneToOneTests(TestCase):
urls = 'rest_framework.tests.relations_hyperlink'
urls = 'rest_framework.tests.test_relations_hyperlink'
def setUp(self):
target = OneToOneTarget(name='target-1')

View File

@ -25,7 +25,6 @@ DUMMYCONTENT = 'dummycontent'
RENDERER_A_SERIALIZER = lambda x: 'Renderer A: %s' % x
RENDERER_B_SERIALIZER = lambda x: 'Renderer B: %s' % x
expected_results = [
((elem for elem in [1, 2, 3]), JSONRenderer, '[1, 2, 3]') # Generator
]
@ -63,7 +62,6 @@ class MockView(APIView):
class MockGETView(APIView):
def get(self, request, **kwargs):
return Response({'foo': ['bar', 'baz']})
@ -126,7 +124,7 @@ class RendererEndToEndTests(TestCase):
End-to-end testing of renderers using an RendererMixin on a generic view.
"""
urls = 'rest_framework.tests.renderers'
urls = 'rest_framework.tests.test_renderers'
def test_default_renderer_serializes_content(self):
"""If the Accept header is not set the default renderer should serialize the response."""
@ -257,7 +255,7 @@ class JSONPRendererTests(TestCase):
Tests specific to the JSONP Renderer
"""
urls = 'rest_framework.tests.renderers'
urls = 'rest_framework.tests.test_renderers'
def test_without_callback_with_json_renderer(self):
"""
@ -426,7 +424,7 @@ class CacheRenderTest(TestCase):
Tests specific to caching responses
"""
urls = 'rest_framework.tests.renderers'
urls = 'rest_framework.tests.test_renderers'
cache_key = 'just_a_cache_key'

View File

@ -111,6 +111,7 @@ class TestContentParsing(TestCase):
if VERSION >= (1, 5):
from django.test.client import MULTIPART_CONTENT, BOUNDARY, encode_multipart
request = Request(factory.put('/', encode_multipart(BOUNDARY, data),
content_type=MULTIPART_CONTENT))
else:
@ -244,7 +245,7 @@ urlpatterns = patterns('',
class TestContentParsingWithAuthentication(TestCase):
urls = 'rest_framework.tests.request'
urls = 'rest_framework.tests.test_request'
def setUp(self):
self.csrf_client = Client(enforce_csrf_checks=True)
@ -280,7 +281,6 @@ class TestContentParsingWithAuthentication(TestCase):
class TestUserSetter(TestCase):
def setUp(self):
# Pass request object through session middleware so session is
# available to login and logout functions
@ -306,7 +306,6 @@ class TestUserSetter(TestCase):
class TestAuthSetter(TestCase):
def test_auth_can_be_set(self):
request = Request(factory.get('/'))
request.auth = 'DUMMY'

View File

@ -78,7 +78,7 @@ class RendererIntegrationTests(TestCase):
End-to-end testing of renderers using an ResponseMixin on a generic view.
"""
urls = 'rest_framework.tests.response'
urls = 'rest_framework.tests.test_response'
def test_default_renderer_serializes_content(self):
"""If the Accept header is not set the default renderer should serialize the response."""
@ -158,7 +158,7 @@ class Issue122Tests(TestCase):
"""
Tests that covers #122.
"""
urls = 'rest_framework.tests.response'
urls = 'rest_framework.tests.test_response'
def test_only_html_renderer(self):
"""

View File

@ -18,7 +18,7 @@ class ReverseTests(TestCase):
"""
Tests for fully qualifed URLs when using `reverse`.
"""
urls = 'rest_framework.tests.reverse'
urls = 'rest_framework.tests.test_reverse'
def test_reversed_urls_are_fully_qualified(self):
request = factory.get('/view')

View File

@ -49,7 +49,6 @@ class BookSerializer(serializers.ModelSerializer):
class ActionItemSerializer(serializers.ModelSerializer):
class Meta:
model = ActionItem
@ -64,7 +63,6 @@ class PersonSerializer(serializers.ModelSerializer):
class AlbumsSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = ['title'] # lists are also valid options
@ -187,12 +185,14 @@ class ValidationTests(TestCase):
def test_create(self):
serializer = CommentSerializer(data=self.data)
self.assertEquals(serializer.is_valid(), False)
self.assertEquals(serializer.errors, {'content': [u'Ensure this value has at most 1000 characters (it has 1001).']})
self.assertEquals(serializer.errors,
{'content': [u'Ensure this value has at most 1000 characters (it has 1001).']})
def test_update(self):
serializer = CommentSerializer(self.comment, data=self.data)
self.assertEquals(serializer.is_valid(), False)
self.assertEquals(serializer.errors, {'content': [u'Ensure this value has at most 1000 characters (it has 1001).']})
self.assertEquals(serializer.errors,
{'content': [u'Ensure this value has at most 1000 characters (it has 1001).']})
def test_update_missing_field(self):
data = {
@ -234,9 +234,7 @@ class ValidationTests(TestCase):
self.assertEquals(serializer.errors, {'non_field_errors': [u'Invalid data']})
def test_cross_field_validation(self):
class CommentSerializerWithCrossFieldValidator(CommentSerializer):
def validate(self, attrs):
if attrs["email"] not in attrs["content"]:
raise serializers.ValidationError("Email address not in content")
@ -285,7 +283,6 @@ class ValidationTests(TestCase):
class CustomValidationTests(TestCase):
class CommentSerializerWithFieldValidator(CommentSerializer):
def validate_email(self, attrs, source):
value = attrs[source]
@ -731,7 +728,6 @@ class RelatedTraversalTest(TestCase):
class SerializerMethodFieldTests(TestCase):
def setUp(self):
class BoopSerializer(serializers.Serializer):
beep = serializers.SerializerMethodField('get_beep')
boop = serializers.Field()
@ -746,7 +742,6 @@ class SerializerMethodFieldTests(TestCase):
self.serializer_class = BoopSerializer
def test_serializer_method_field(self):
class MyModel(object):
boop = ['a', 'b', 'c']
@ -766,7 +761,6 @@ class SerializerMethodFieldTests(TestCase):
# Test for issue #324
class BlankFieldTests(TestCase):
def setUp(self):
class BlankFieldModelSerializer(serializers.ModelSerializer):
class Meta:
model = BlankFieldModel
@ -825,6 +819,7 @@ class SerializerPickleTests(TestCase):
"""
Test pickleability of the output of Serializers
"""
def test_pickle_simple_model_serializer_data(self):
"""
Test simple serializer
@ -837,10 +832,12 @@ class SerializerPickleTests(TestCase):
have unpickleable meta data--in order to make sure metadata doesn't get pulled into the pickle.
See DictWithMetadata.__getstate__
"""
class InnerPersonSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('name', 'age')
pickle.dumps(InnerPersonSerializer(Person(name="Noah", age=950)).data)
@ -882,13 +879,13 @@ class DepthTest(TestCase):
class NestedSerializerContextTests(TestCase):
def test_nested_serializer_context(self):
"""
Regression for #497
https://github.com/tomchristie/django-rest-framework/issues/497
"""
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = Photo

View File

@ -9,13 +9,17 @@ class TestSettings(TestCase):
def test_non_import_errors(self):
"""Make sure other errors aren't suppressed."""
settings = APISettings({'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.tests.extras.bad_import.ModelSerializer'}, DEFAULTS, IMPORT_STRINGS)
settings = APISettings(
{'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.tests.extras.bad_import.ModelSerializer'}, DEFAULTS,
IMPORT_STRINGS)
with self.assertRaises(ValueError):
settings.DEFAULT_MODEL_SERIALIZER_CLASS
def test_import_error_message_maintained(self):
"""Make sure real import errors are captured and raised sensibly."""
settings = APISettings({'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.tests.extras.not_here.ModelSerializer'}, DEFAULTS, IMPORT_STRINGS)
settings = APISettings(
{'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.tests.extras.not_here.ModelSerializer'}, DEFAULTS,
IMPORT_STRINGS)
with self.assertRaises(ImportError) as cm:
settings.DEFAULT_MODEL_SERIALIZER_CLASS
self.assertTrue('ImportError' in str(cm.exception))

View File

@ -16,6 +16,7 @@ class TestSettingsManager(object):
modified.
"""
def __init__(self):
self._original_settings = {}
@ -51,6 +52,7 @@ class SettingsTestCase(TestCase):
self.settings_manager.revert().
"""
def __init__(self, *args, **kwargs):
super(SettingsTestCase, self).__init__(*args, **kwargs)
self.settings_manager = TestSettingsManager()

View File

@ -37,7 +37,7 @@ class MockView_MinuteThrottling(APIView):
class ThrottlingTests(TestCase):
urls = 'rest_framework.tests.throttling'
urls = 'rest_framework.tests.test_throttling'
def setUp(self):
"""

View File

@ -21,6 +21,7 @@ class FormatSuffixTests(TestCase):
"""
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:

View File

@ -1,13 +0,0 @@
"""
Force import of all modules in this package in order to get the standard test
runner to pick up the tests. Yowzers.
"""
import os
modules = [filename.rsplit('.', 1)[0]
for filename in os.listdir(os.path.dirname(__file__))
if filename.endswith('.py') and not filename.startswith('_')]
__test__ = dict()
for module in modules:
exec("from rest_framework.tests.%s import *" % module)