diff options
Diffstat (limited to 'tests')
26 files changed, 1121 insertions, 29 deletions
diff --git a/tests/modeltests/basic/models.py b/tests/modeltests/basic/models.py index c3ad38d661..835c5c90cf 100644 --- a/tests/modeltests/basic/models.py +++ b/tests/modeltests/basic/models.py @@ -4,12 +4,18 @@ This is a basic model with only two non-primary-key fields. """ - +# Python 2.3 doesn't have set as a builtin try: set except NameError: from sets import Set as set +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted + from django.db import models class Article(models.Model): diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index c856720a74..e8598bd68f 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -803,7 +803,7 @@ False >>> f.is_valid() True >>> type(f.cleaned_data['file']) -<class 'django.newforms.fields.UploadedFile'> +<class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> instance = f.save() >>> instance.file u'...test1.txt' @@ -814,7 +814,7 @@ u'...test1.txt' >>> f.is_valid() True >>> type(f.cleaned_data['file']) -<class 'django.newforms.fields.UploadedFile'> +<class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> instance = f.save() >>> instance.file u'...test1.txt' @@ -900,13 +900,13 @@ u'...test3.txt' ... class Meta: ... model = ImageFile ->>> image_data = open(os.path.join(os.path.dirname(__file__), "test.png")).read() +>>> image_data = open(os.path.join(os.path.dirname(__file__), "test.png"), 'rb').read() >>> f = ImageFileForm(data={'description': u'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}) >>> f.is_valid() True >>> type(f.cleaned_data['image']) -<class 'django.newforms.fields.UploadedFile'> +<class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> instance = f.save() >>> instance.image u'...test.png' @@ -918,7 +918,7 @@ u'...test.png' >>> f.is_valid() True >>> type(f.cleaned_data['image']) -<class 'django.newforms.fields.UploadedFile'> +<class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> instance = f.save() >>> instance.image u'...test.png' diff --git a/tests/modeltests/or_lookups/models.py b/tests/modeltests/or_lookups/models.py index 22bada07b1..6e56095d7c 100644 --- a/tests/modeltests/or_lookups/models.py +++ b/tests/modeltests/or_lookups/models.py @@ -8,6 +8,11 @@ Alternatively, use positional arguments, and pass one or more expressions of clauses using the variable ``django.db.models.Q`` (or any object with an add_to_query method). """ +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted from django.db import models diff --git a/tests/modeltests/pagination/models.py b/tests/modeltests/pagination/models.py index 1f08a32903..4b564f2f90 100644 --- a/tests/modeltests/pagination/models.py +++ b/tests/modeltests/pagination/models.py @@ -31,7 +31,7 @@ __test__ = {'API_TESTS':""" # New/current API (Paginator/Page) # #################################### ->>> from django.core.paginator import Paginator, InvalidPage +>>> from django.core.paginator import Paginator >>> paginator = Paginator(Article.objects.all(), 5) >>> paginator.count 9 @@ -82,15 +82,15 @@ True >>> p.end_index() 9 -# Invalid pages raise InvalidPage. +# Empty pages raise EmptyPage. >>> paginator.page(0) Traceback (most recent call last): ... -InvalidPage: ... +EmptyPage: ... >>> paginator.page(3) Traceback (most recent call last): ... -InvalidPage: ... +EmptyPage: ... # Empty paginators with allow_empty_first_page=True. >>> paginator = Paginator(Article.objects.filter(id=0), 5, allow_empty_first_page=True) @@ -148,7 +148,7 @@ True >>> from warnings import filterwarnings >>> filterwarnings("ignore") ->>> from django.core.paginator import ObjectPaginator, InvalidPage +>>> from django.core.paginator import ObjectPaginator, EmptyPage >>> paginator = ObjectPaginator(Article.objects.all(), 5) >>> paginator.hits 9 @@ -181,15 +181,15 @@ True >>> paginator.last_on_page(1) 9 -# Invalid pages raise InvalidPage. +# Invalid pages raise EmptyPage. >>> paginator.get_page(-1) Traceback (most recent call last): ... -InvalidPage: ... +EmptyPage: ... >>> paginator.get_page(2) Traceback (most recent call last): ... -InvalidPage: ... +EmptyPage: ... # Empty paginators with allow_empty_first_page=True. >>> paginator = ObjectPaginator(Article.objects.filter(id=0), 5) diff --git a/tests/modeltests/test_client/models.py b/tests/modeltests/test_client/models.py index 1a6e1bdc18..3797bf2d52 100644 --- a/tests/modeltests/test_client/models.py +++ b/tests/modeltests/test_client/models.py @@ -70,7 +70,13 @@ class ClientTest(TestCase): self.assertEqual(response.context['data'], '37') self.assertEqual(response.template.name, 'POST Template') self.failUnless('Data received' in response.content) - + + def test_response_headers(self): + "Check the value of HTTP headers returned in a response" + response = self.client.get("/test_client/header_view/") + + self.assertEquals(response['X-DJANGO-TEST'], 'Slartibartfast') + def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>""" diff --git a/tests/modeltests/test_client/urls.py b/tests/modeltests/test_client/urls.py index 09ee7eaf34..0e511d7360 100644 --- a/tests/modeltests/test_client/urls.py +++ b/tests/modeltests/test_client/urls.py @@ -5,6 +5,7 @@ import views urlpatterns = patterns('', (r'^get_view/$', views.get_view), (r'^post_view/$', views.post_view), + (r'^header_view/$', views.view_with_header), (r'^raw_post_view/$', views.raw_post_view), (r'^redirect_view/$', views.redirect_view), (r'^permanent_redirect_view/$', redirect_to, { 'url': '/test_client/get_view/' }), diff --git a/tests/modeltests/test_client/views.py b/tests/modeltests/test_client/views.py index 3f4a54c5bd..f4eab6462d 100644 --- a/tests/modeltests/test_client/views.py +++ b/tests/modeltests/test_client/views.py @@ -32,6 +32,12 @@ def post_view(request): return HttpResponse(t.render(c)) +def view_with_header(request): + "A view that has a custom header" + response = HttpResponse() + response['X-DJANGO-TEST'] = 'Slartibartfast' + return response + def raw_post_view(request): """A view which expects raw XML to be posted and returns content extracted from the XML""" diff --git a/tests/regressiontests/admin_scripts/__init__.py b/tests/regressiontests/admin_scripts/__init__.py new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/regressiontests/admin_scripts/__init__.py diff --git a/tests/regressiontests/admin_scripts/management/__init__.py b/tests/regressiontests/admin_scripts/management/__init__.py new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/regressiontests/admin_scripts/management/__init__.py diff --git a/tests/regressiontests/admin_scripts/management/commands/__init__.py b/tests/regressiontests/admin_scripts/management/commands/__init__.py new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/regressiontests/admin_scripts/management/commands/__init__.py diff --git a/tests/regressiontests/admin_scripts/management/commands/app_command.py b/tests/regressiontests/admin_scripts/management/commands/app_command.py new file mode 100644 index 0000000000..3d8c43755c --- /dev/null +++ b/tests/regressiontests/admin_scripts/management/commands/app_command.py @@ -0,0 +1,15 @@ +from django.core.management.base import AppCommand +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted + +class Command(AppCommand): + help = 'Test Application-based commands' + requires_model_validation = False + args = '[appname ...]' + + def handle_app(self, app, **options): + print 'EXECUTE:AppCommand app=%s, options=%s' % (app, sorted(options.items())) + diff --git a/tests/regressiontests/admin_scripts/management/commands/base_command.py b/tests/regressiontests/admin_scripts/management/commands/base_command.py new file mode 100644 index 0000000000..536f40409a --- /dev/null +++ b/tests/regressiontests/admin_scripts/management/commands/base_command.py @@ -0,0 +1,20 @@ +from django.core.management.base import BaseCommand +from optparse import make_option +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted + +class Command(BaseCommand): + option_list = BaseCommand.option_list + ( + make_option('--option_a','-a', action='store', dest='option_a', default='1'), + make_option('--option_b','-b', action='store', dest='option_b', default='2'), + make_option('--option_c','-c', action='store', dest='option_c', default='3'), + ) + help = 'Test basic commands' + requires_model_validation = False + args = '[labels ...]' + + def handle(self, *labels, **options): + print 'EXECUTE:BaseCommand labels=%s, options=%s' % (labels, sorted(options.items())) diff --git a/tests/regressiontests/admin_scripts/management/commands/label_command.py b/tests/regressiontests/admin_scripts/management/commands/label_command.py new file mode 100644 index 0000000000..e749209d9c --- /dev/null +++ b/tests/regressiontests/admin_scripts/management/commands/label_command.py @@ -0,0 +1,14 @@ +from django.core.management.base import LabelCommand +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted + +class Command(LabelCommand): + help = "Test Label-based commands" + requires_model_validation = False + args = '<label>' + + def handle_label(self, label, **options): + print 'EXECUTE:LabelCommand label=%s, options=%s' % (label, sorted(options.items())) diff --git a/tests/regressiontests/admin_scripts/management/commands/noargs_command.py b/tests/regressiontests/admin_scripts/management/commands/noargs_command.py new file mode 100644 index 0000000000..f0f418752a --- /dev/null +++ b/tests/regressiontests/admin_scripts/management/commands/noargs_command.py @@ -0,0 +1,14 @@ +from django.core.management.base import NoArgsCommand +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted + +class Command(NoArgsCommand): + help = "Test No-args commands" + requires_model_validation = False + + + def handle_noargs(self, **options): + print 'EXECUTE:NoArgsCommand options=%s' % sorted(options.items()) diff --git a/tests/regressiontests/admin_scripts/models.py b/tests/regressiontests/admin_scripts/models.py new file mode 100644 index 0000000000..96a40d22b7 --- /dev/null +++ b/tests/regressiontests/admin_scripts/models.py @@ -0,0 +1,12 @@ +from django.db import models + +class Article(models.Model): + headline = models.CharField(max_length=100, default='Default headline') + pub_date = models.DateTimeField() + + def __unicode__(self): + return self.headline + + class Meta: + ordering = ('-pub_date', 'headline') +
\ No newline at end of file diff --git a/tests/regressiontests/admin_scripts/tests.py b/tests/regressiontests/admin_scripts/tests.py new file mode 100644 index 0000000000..1bb0f7bed6 --- /dev/null +++ b/tests/regressiontests/admin_scripts/tests.py @@ -0,0 +1,908 @@ +""" +A series of tests to establish that the command-line managment tools work as +advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE +and default settings.py files. +""" +import os +import unittest +import shutil + +from django import conf, bin, get_version +from django.conf import settings + +class AdminScriptTestCase(unittest.TestCase): + def write_settings(self, filename, apps=None): + test_dir = os.path.dirname(os.path.dirname(__file__)) + settings_file = open(os.path.join(test_dir,filename), 'w') + settings_file.write('# Settings file automatically generated by regressiontests.admin_scripts test case\n') + exports = [ + 'DATABASE_ENGINE', + 'DATABASE_NAME', + 'DATABASE_USER', + 'DATABASE_PASSWORD', + 'DATABASE_HOST', + 'DATABASE_PORT', + 'ROOT_URLCONF' + ] + for s in exports: + if hasattr(settings,s): + settings_file.write("%s = '%s'\n" % (s, str(getattr(settings,s)))) + + if apps is None: + apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts'] + + if apps: + settings_file.write("INSTALLED_APPS = %s\n" % apps) + + settings_file.close() + + def remove_settings(self, filename): + test_dir = os.path.dirname(os.path.dirname(__file__)) + os.remove(os.path.join(test_dir, filename)) + # Also try to remove the pyc file; if it exists, it could + # mess up later tests that depend upon the .py file not existing + try: + os.remove(os.path.join(test_dir, filename + 'c')) + except OSError: + pass + + def run_test(self, script, args, settings_file=None, apps=None): + test_dir = os.path.dirname(os.path.dirname(__file__)) + project_dir = os.path.dirname(test_dir) + base_dir = os.path.dirname(project_dir) + + # Build the command line + cmd = 'python "%s"' % script + cmd += ''.join(' %s' % arg for arg in args) + + # Remember the old environment + old_django_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE', None) + old_python_path = os.environ.get('PYTHONPATH', None) + old_cwd = os.getcwd() + + # Set the test environment + if settings_file: + os.environ['DJANGO_SETTINGS_MODULE'] = settings_file + elif 'DJANGO_SETTINGS_MODULE' in os.environ: + del os.environ['DJANGO_SETTINGS_MODULE'] + + os.environ['PYTHONPATH'] = os.pathsep.join([test_dir,base_dir]) + + # Move to the test directory and run + os.chdir(test_dir) + stdin, stdout, stderr = os.popen3(cmd) + out, err = stdout.read(), stderr.read() + + # Restore the old environment + if old_django_settings_module: + os.environ['DJANGO_SETTINGS_MODULE'] = old_django_settings_module + if old_python_path: + os.environ['PYTHONPATH'] = old_python_path + + # Move back to the old working directory + os.chdir(old_cwd) + + return out, err + + def run_django_admin(self, args, settings_file=None): + bin_dir = os.path.dirname(bin.__file__) + return self.run_test(os.path.join(bin_dir,'django-admin.py'), args, settings_file) + + def run_manage(self, args, settings_file=None): + conf_dir = os.path.dirname(conf.__file__) + template_manage_py = os.path.join(conf_dir, 'project_template', 'manage.py') + + test_dir = os.path.dirname(os.path.dirname(__file__)) + test_manage_py = os.path.join(test_dir, 'manage.py') + shutil.copyfile(template_manage_py, test_manage_py) + + stdout, stderr = self.run_test('./manage.py', args, settings_file) + + # Cleanup - remove the generated manage.py script + os.remove(test_manage_py) + + return stdout, stderr + + def assertNoOutput(self, stream): + "Utility assertion: assert that the given stream is empty" + self.assertEquals(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream) + def assertOutput(self, stream, msg): + "Utility assertion: assert that the given message exists in the output" + self.assertTrue(msg in stream, "'%s' does not match actual output text '%s'" % (msg, stream)) + +########################################################################## +# DJANGO ADMIN TESTS +# This first series of test classes checks the environment processing +# of the django-admin.py script +########################################################################## + + +class DjangoAdminNoSettings(AdminScriptTestCase): + "A series of tests for django-admin.py when there is no settings.py file." + + def test_builtin_command(self): + "no settings: django-admin builtin commands fail with an import error when no settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') + + def test_builtin_with_bad_settings(self): + "no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_builtin_with_bad_environment(self): + "no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + +class DjangoAdminDefaultSettings(AdminScriptTestCase): + """A series of tests for django-admin.py when using a settings.py file that + contains the test application. + """ + def setUp(self): + self.write_settings('settings.py') + + def tearDown(self): + self.remove_settings('settings.py') + + def test_builtin_command(self): + "default: django-admin builtin commands fail with an import error when no settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') + + def test_builtin_with_settings(self): + "default: django-admin builtin commands succeed if settings are provided as argument" + args = ['sqlall','--settings=settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_environment(self): + "default: django-admin builtin commands succeed if settings are provided in the environment" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'settings') + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_bad_settings(self): + "default: django-admin builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_builtin_with_bad_environment(self): + "default: django-admin builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_custom_command(self): + "default: django-admin can't execute user commands" + args = ['noargs_command'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_settings(self): + "default: django-admin can't execute user commands, even if settings are provided as argument" + args = ['noargs_command', '--settings=settings'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_environment(self): + "default: django-admin can't execute user commands, even if settings are provided in environment" + args = ['noargs_command'] + out, err = self.run_django_admin(args,'settings') + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + +class DjangoAdminMinimalSettings(AdminScriptTestCase): + """A series of tests for django-admin.py when using a settings.py file that + doesn't contain the test application. + """ + def setUp(self): + self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) + + def tearDown(self): + self.remove_settings('settings.py') + + def test_builtin_command(self): + "minimal: django-admin builtin commands fail with an import error when no settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') + + def test_builtin_with_settings(self): + "minimal: django-admin builtin commands fail if settings are provided as argument" + args = ['sqlall','--settings=settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, 'App with label admin_scripts could not be found') + + def test_builtin_with_environment(self): + "minimal: django-admin builtin commands fail if settings are provided in the environment" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'settings') + self.assertNoOutput(out) + self.assertOutput(err, 'App with label admin_scripts could not be found') + + def test_builtin_with_bad_settings(self): + "minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_builtin_with_bad_environment(self): + "minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_custom_command(self): + "minimal: django-admin can't execute user commands" + args = ['noargs_command'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_settings(self): + "minimal: django-admin can't execute user commands, even if settings are provided as argument" + args = ['noargs_command', '--settings=settings'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_environment(self): + "minimal: django-admin can't execute user commands, even if settings are provided in environment" + args = ['noargs_command'] + out, err = self.run_django_admin(args,'settings') + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + +class DjangoAdminAlternateSettings(AdminScriptTestCase): + """A series of tests for django-admin.py when using a settings file + with a name other than 'settings.py'. + """ + def setUp(self): + self.write_settings('alternate_settings.py') + + def tearDown(self): + self.remove_settings('alternate_settings.py') + + def test_builtin_command(self): + "alternate: django-admin builtin commands fail with an import error when no settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') + + def test_builtin_with_settings(self): + "alternate: django-admin builtin commands succeed if settings are provided as argument" + args = ['sqlall','--settings=alternate_settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_environment(self): + "alternate: django-admin builtin commands succeed if settings are provided in the environment" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'alternate_settings') + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_bad_settings(self): + "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_builtin_with_bad_environment(self): + "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_custom_command(self): + "alternate: django-admin can't execute user commands" + args = ['noargs_command'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_settings(self): + "alternate: django-admin can't execute user commands, even if settings are provided as argument" + args = ['noargs_command', '--settings=alternate_settings'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_environment(self): + "alternate: django-admin can't execute user commands, even if settings are provided in environment" + args = ['noargs_command'] + out, err = self.run_django_admin(args,'alternate_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + +class DjangoAdminMultipleSettings(AdminScriptTestCase): + """A series of tests for django-admin.py when multiple settings files + (including the default 'settings.py') are available. The default settings + file is insufficient for performing the operations described, so the + alternate settings must be used by the running script. + """ + def setUp(self): + self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) + self.write_settings('alternate_settings.py') + + def tearDown(self): + self.remove_settings('settings.py') + self.remove_settings('alternate_settings.py') + + def test_builtin_command(self): + "alternate: django-admin builtin commands fail with an import error when no settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') + + def test_builtin_with_settings(self): + "alternate: django-admin builtin commands succeed if settings are provided as argument" + args = ['sqlall','--settings=alternate_settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_environment(self): + "alternate: django-admin builtin commands succeed if settings are provided in the environment" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'alternate_settings') + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_bad_settings(self): + "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_django_admin(args) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_builtin_with_bad_environment(self): + "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_django_admin(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_custom_command(self): + "alternate: django-admin can't execute user commands" + args = ['noargs_command'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_settings(self): + "alternate: django-admin can't execute user commands, even if settings are provided as argument" + args = ['noargs_command', '--settings=alternate_settings'] + out, err = self.run_django_admin(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_environment(self): + "alternate: django-admin can't execute user commands, even if settings are provided in environment" + args = ['noargs_command'] + out, err = self.run_django_admin(args,'alternate_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + +########################################################################## +# MANAGE.PY TESTS +# This next series of test classes checks the environment processing +# of the generated manage.py script +########################################################################## + +class ManageNoSettings(AdminScriptTestCase): + "A series of tests for manage.py when there is no settings.py file." + + def test_builtin_command(self): + "no settings: manage.py builtin commands fail with an import error when no settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_builtin_with_bad_settings(self): + "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_builtin_with_bad_environment(self): + "no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + +class ManageDefaultSettings(AdminScriptTestCase): + """A series of tests for manage.py when using a settings.py file that + contains the test application. + """ + def setUp(self): + self.write_settings('settings.py') + + def tearDown(self): + self.remove_settings('settings.py') + + def test_builtin_command(self): + "default: manage.py builtin commands succeed when default settings are appropriate" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_settings(self): + "default: manage.py builtin commands succeed if settings are provided as argument" + args = ['sqlall','--settings=settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_environment(self): + "default: manage.py builtin commands succeed if settings are provided in the environment" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'settings') + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_bad_settings(self): + "default: manage.py builtin commands succeed if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_builtin_with_bad_environment(self): + "default: manage.py builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'bad_settings') + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_custom_command(self): + "default: manage.py can execute user commands when default settings are appropriate" + args = ['noargs_command'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:NoArgsCommand") + + def test_custom_command_with_settings(self): + "default: manage.py can execute user commands when settings are provided as argument" + args = ['noargs_command', '--settings=settings'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:NoArgsCommand") + + def test_custom_command_with_environment(self): + "default: manage.py can execute user commands when settings are provided in environment" + args = ['noargs_command'] + out, err = self.run_manage(args,'settings') + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:NoArgsCommand") + +class ManageMinimalSettings(AdminScriptTestCase): + """A series of tests for manage.py when using a settings.py file that + doesn't contain the test application. + """ + def setUp(self): + self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) + + def tearDown(self): + self.remove_settings('settings.py') + + def test_builtin_command(self): + "minimal: manage.py builtin commands fail with an import error when no settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, 'App with label admin_scripts could not be found') + + def test_builtin_with_settings(self): + "minimal: manage.py builtin commands fail if settings are provided as argument" + args = ['sqlall','--settings=settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, 'App with label admin_scripts could not be found') + + def test_builtin_with_environment(self): + "minimal: manage.py builtin commands fail if settings are provided in the environment" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'settings') + self.assertNoOutput(out) + self.assertOutput(err, 'App with label admin_scripts could not be found') + + def test_builtin_with_bad_settings(self): + "minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_builtin_with_bad_environment(self): + "minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, 'App with label admin_scripts could not be found') + + def test_custom_command(self): + "minimal: manage.py can't execute user commands without appropriate settings" + args = ['noargs_command'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_settings(self): + "minimal: manage.py can't execute user commands, even if settings are provided as argument" + args = ['noargs_command', '--settings=settings'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_environment(self): + "minimal: manage.py can't execute user commands, even if settings are provided in environment" + args = ['noargs_command'] + out, err = self.run_manage(args,'settings') + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + +class ManageAlternateSettings(AdminScriptTestCase): + """A series of tests for manage.py when using a settings file + with a name other than 'settings.py'. + """ + def setUp(self): + self.write_settings('alternate_settings.py') + + def tearDown(self): + self.remove_settings('alternate_settings.py') + + def test_builtin_command(self): + "alternate: manage.py builtin commands fail with an import error when no default settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_builtin_with_settings(self): + "alternate: manage.py builtin commands fail if settings are provided as argument but no defaults" + args = ['sqlall','--settings=alternate_settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_builtin_with_environment(self): + "alternate: manage.py builtin commands fail if settings are provided in the environment but no defaults" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'alternate_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_builtin_with_bad_settings(self): + "alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_builtin_with_bad_environment(self): + "alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_custom_command(self): + "alternate: manage.py can't execute user commands" + args = ['noargs_command'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_custom_command_with_settings(self): + "alternate: manage.py can't execute user commands, even if settings are provided as argument" + args = ['noargs_command', '--settings=alternate_settings'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + def test_custom_command_with_environment(self): + "alternate: manage.py can't execute user commands, even if settings are provided in environment" + args = ['noargs_command'] + out, err = self.run_manage(args,'alternate_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") + + +class ManageMultipleSettings(AdminScriptTestCase): + """A series of tests for manage.py when multiple settings files + (including the default 'settings.py') are available. The default settings + file is insufficient for performing the operations described, so the + alternate settings must be used by the running script. + """ + def setUp(self): + self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) + self.write_settings('alternate_settings.py') + + def tearDown(self): + self.remove_settings('settings.py') + self.remove_settings('alternate_settings.py') + + def test_builtin_command(self): + "multiple: manage.py builtin commands fail with an import error when no settings provided" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, 'App with label admin_scripts could not be found.') + + def test_builtin_with_settings(self): + "multiple: manage.py builtin commands succeed if settings are provided as argument" + args = ['sqlall','--settings=alternate_settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, 'CREATE TABLE') + + def test_builtin_with_environment(self): + "multiple: manage.py builtin commands fail if settings are provided in the environment" + # FIXME: This doesn't seem to be the correct output. + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'alternate_settings') + self.assertNoOutput(out) + self.assertOutput(err, 'App with label admin_scripts could not be found.') + + def test_builtin_with_bad_settings(self): + "multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist" + args = ['sqlall','--settings=bad_settings', 'admin_scripts'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Could not import settings 'bad_settings'") + + def test_builtin_with_bad_environment(self): + "multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist" + args = ['sqlall','admin_scripts'] + out, err = self.run_manage(args,'bad_settings') + self.assertNoOutput(out) + self.assertOutput(err, "App with label admin_scripts could not be found") + + def test_custom_command(self): + "multiple: manage.py can't execute user commands using default settings" + args = ['noargs_command'] + out, err = self.run_manage(args) + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + + def test_custom_command_with_settings(self): + "multiple: manage.py can execute user commands if settings are provided as argument" + args = ['noargs_command', '--settings=alternate_settings'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:NoArgsCommand") + + def test_custom_command_with_environment(self): + "multiple: manage.py can execute user commands if settings are provided in environment" + args = ['noargs_command'] + out, err = self.run_manage(args,'alternate_settings') + self.assertNoOutput(out) + self.assertOutput(err, "Unknown command: 'noargs_command'") + +########################################################################## +# COMMAND PROCESSING TESTS +# Check that user-space commands are correctly handled - in particular, +# that arguments to the commands are correctly parsed and processed. +########################################################################## + +class CommandTypes(AdminScriptTestCase): + "Tests for the various types of base command types that can be defined." + def setUp(self): + self.write_settings('settings.py') + + def tearDown(self): + self.remove_settings('settings.py') + + def test_version(self): + "--version is handled as a special case" + args = ['--version'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + # Only check the first part of the version number + self.assertOutput(out, get_version().split('-')[0]) + + def test_help(self): + "--help is handled as a special case" + args = ['--help'] + out, err = self.run_manage(args) + self.assertOutput(out, "Usage: manage.py [options]") + self.assertOutput(err, "Type 'manage.py help <subcommand>' for help on a specific subcommand.") + + def test_specific_help(self): + "--help can be used on a specific command" + args = ['sqlall','--help'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "Prints the CREATE TABLE, custom SQL and CREATE INDEX SQL statements for the given model module name(s).") + + def test_base_command(self): + "User BaseCommands can execute when a label is provided" + args = ['base_command','testlabel'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', '1'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_base_command_no_label(self): + "User BaseCommands can execute when no labels are provided" + args = ['base_command'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=(), options=[('option_a', '1'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_base_command_multiple_label(self): + "User BaseCommands can execute when no labels are provided" + args = ['base_command','testlabel','anotherlabel'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel', 'anotherlabel'), options=[('option_a', '1'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_base_command_with_option(self): + "User BaseCommands can execute with options when a label is provided" + args = ['base_command','testlabel','--option_a=x'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_base_command_with_options(self): + "User BaseCommands can execute with multiple options when a label is provided" + args = ['base_command','testlabel','-a','x','--option_b=y'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', 'y'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_noargs(self): + "NoArg Commands can be executed" + args = ['noargs_command'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:NoArgsCommand options=[('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_noargs_with_args(self): + "NoArg Commands raise an error if an argument is provided" + args = ['noargs_command','argument'] + out, err = self.run_manage(args) + self.assertOutput(err, "Error: Command doesn't accept any arguments") + + def test_app_command(self): + "User AppCommands can execute when a single app name is provided" + args = ['app_command', 'auth'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.auth.models'") + self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py'])) + self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_app_command_no_apps(self): + "User AppCommands raise an error when no app name is provided" + args = ['app_command'] + out, err = self.run_manage(args) + self.assertOutput(err, 'Error: Enter at least one appname.') + + def test_app_command_multiple_apps(self): + "User AppCommands raise an error when multiple app names are provided" + args = ['app_command','auth','contenttypes'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.auth.models'") + self.assertOutput(out, os.sep.join(['django','contrib','auth','models.pyc']) + "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None)]") + self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.contenttypes.models'") + self.assertOutput(out, os.sep.join(['django','contrib','contenttypes','models.py'])) + self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_app_command_invalid_appname(self): + "User AppCommands can execute when a single app name is provided" + args = ['app_command', 'NOT_AN_APP'] + out, err = self.run_manage(args) + self.assertOutput(err, "App with label NOT_AN_APP could not be found") + + def test_app_command_some_invalid_appnames(self): + "User AppCommands can execute when some of the provided app names are invalid" + args = ['app_command', 'auth', 'NOT_AN_APP'] + out, err = self.run_manage(args) + self.assertOutput(err, "App with label NOT_AN_APP could not be found") + + def test_label_command(self): + "User LabelCommands can execute when a label is provided" + args = ['label_command','testlabel'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:LabelCommand label=testlabel, options=[('pythonpath', None), ('settings', None), ('traceback', None)]") + + def test_label_command_no_label(self): + "User LabelCommands raise an error if no label is provided" + args = ['label_command'] + out, err = self.run_manage(args) + self.assertOutput(err, 'Enter at least one label') + + def test_label_command_multiple_label(self): + "User LabelCommands are executed multiple times if multiple labels are provided" + args = ['label_command','testlabel','anotherlabel'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:LabelCommand label=testlabel, options=[('pythonpath', None), ('settings', None), ('traceback', None)]") + self.assertOutput(out, "EXECUTE:LabelCommand label=anotherlabel, options=[('pythonpath', None), ('settings', None), ('traceback', None)]") + +class ArgumentOrder(AdminScriptTestCase): + """Tests for 2-stage argument parsing scheme. + + django-admin command arguments are parsed in 2 parts; the core arguments + (--settings, --traceback and --pythonpath) are parsed using a Lax parser. + This Lax parser ignores any unknown options. Then the full settings are + passed to the command parser, which extracts commands of interest to the + individual command. + """ + def setUp(self): + self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) + self.write_settings('alternate_settings.py') + + def tearDown(self): + self.remove_settings('settings.py') + self.remove_settings('alternate_settings.py') + + def test_setting_then_option(self): + "Options passed after settings are correctly handled" + args = ['base_command','testlabel','--settings=alternate_settings','--option_a=x'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None)]") + + def test_setting_then_short_option(self): + "Short options passed after settings are correctly handled" + args = ['base_command','testlabel','--settings=alternate_settings','--option_a=x'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None)]") + + def test_option_then_setting(self): + "Options passed before settings are correctly handled" + args = ['base_command','testlabel','--option_a=x','--settings=alternate_settings'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None)]") + + def test_short_option_then_setting(self): + "Short options passed before settings are correctly handled" + args = ['base_command','testlabel','-a','x','--settings=alternate_settings'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None)]") + + def test_option_then_setting_then_option(self): + "Options are correctly handled when they are passed before and after a setting" + args = ['base_command','testlabel','--option_a=x','--settings=alternate_settings','--option_b=y'] + out, err = self.run_manage(args) + self.assertNoOutput(err) + self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', 'y'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None)]") + diff --git a/tests/regressiontests/defaultfilters/tests.py b/tests/regressiontests/defaultfilters/tests.py index b56c33a652..1b659a91f4 100644 --- a/tests/regressiontests/defaultfilters/tests.py +++ b/tests/regressiontests/defaultfilters/tests.py @@ -537,6 +537,12 @@ u'123' from django.template.defaultfilters import * import datetime +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted + if __name__ == '__main__': import doctest doctest.testmod() diff --git a/tests/regressiontests/file_uploads/tests.py b/tests/regressiontests/file_uploads/tests.py index 8992298470..d2b581686f 100644 --- a/tests/regressiontests/file_uploads/tests.py +++ b/tests/regressiontests/file_uploads/tests.py @@ -25,7 +25,7 @@ class FileUploadTests(TestCase): file2.seek(0) # This file contains chinese symbols for a name. - file3 = open(os.path.join(tdir, u'test_中文_Orl\u00e9ans.jpg'), 'w+b') + file3 = open(os.path.join(tdir, u'test_中文_Orl\u00e9ans.jpg'.encode('utf-8')), 'w+b') file3.write('b' * (2 ** 10)) file3.seek(0) @@ -147,12 +147,35 @@ class FileUploadTests(TestCase): def test_broken_custom_upload_handler(self): f = tempfile.NamedTemporaryFile() f.write('a' * (2 ** 21)) - + # AttributeError: You cannot alter upload handlers after the upload has been processed. self.assertRaises( AttributeError, self.client.post, - '/file_uploads/quota/broken/', + '/file_uploads/quota/broken/', {'f': open(f.name)} - ) -
\ No newline at end of file + ) + + def test_fileupload_getlist(self): + file1 = tempfile.NamedTemporaryFile() + file1.write('a' * (2 ** 23)) + + file2 = tempfile.NamedTemporaryFile() + file2.write('a' * (2 * 2 ** 18)) + + file2a = tempfile.NamedTemporaryFile() + file2a.write('a' * (5 * 2 ** 20)) + + response = self.client.post('/file_uploads/getlist_count/', { + 'file1': open(file1.name), + 'field1': u'test', + 'field2': u'test3', + 'field3': u'test5', + 'field4': u'test6', + 'field5': u'test7', + 'file2': (open(file2.name), open(file2a.name)) + }) + got = simplejson.loads(response.content) + + self.assertEqual(got.get('file1'), 1) + self.assertEqual(got.get('file2'), 2) diff --git a/tests/regressiontests/file_uploads/urls.py b/tests/regressiontests/file_uploads/urls.py index 529bee312d..cc4cc80fdd 100644 --- a/tests/regressiontests/file_uploads/urls.py +++ b/tests/regressiontests/file_uploads/urls.py @@ -7,4 +7,5 @@ urlpatterns = patterns('', (r'^echo/$', views.file_upload_echo), (r'^quota/$', views.file_upload_quota), (r'^quota/broken/$', views.file_upload_quota_broken), + (r'^getlist_count/$', views.file_upload_getlist_count), ) diff --git a/tests/regressiontests/file_uploads/views.py b/tests/regressiontests/file_uploads/views.py index 833cf90531..c45f6a609f 100644 --- a/tests/regressiontests/file_uploads/views.py +++ b/tests/regressiontests/file_uploads/views.py @@ -15,7 +15,7 @@ def file_upload_view(request): if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], unicode): # If a file is posted, the dummy client should only post the file name, # not the full path. - if os.path.dirname(form_data['file_field'].file_name) != '': + if os.path.dirname(form_data['file_field'].name) != '': return HttpResponseServerError() return HttpResponse('') else: @@ -29,7 +29,7 @@ def file_upload_view_verify(request): form_data.update(request.FILES) # Check to see if unicode names worked out. - if not request.FILES['file_unicode'].file_name.endswith(u'test_\u4e2d\u6587_Orl\xe9ans.jpg'): + if not request.FILES['file_unicode'].name.endswith(u'test_\u4e2d\u6587_Orl\xe9ans.jpg'): return HttpResponseServerError() for key, value in form_data.items(): @@ -51,7 +51,7 @@ def file_upload_echo(request): """ Simple view to echo back info about uploaded files for tests. """ - r = dict([(k, f.file_name) for k, f in request.FILES.items()]) + r = dict([(k, f.name) for k, f in request.FILES.items()]) return HttpResponse(simplejson.dumps(r)) def file_upload_quota(request): @@ -67,4 +67,14 @@ def file_upload_quota_broken(request): """ response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) - return response
\ No newline at end of file + return response + +def file_upload_getlist_count(request): + """ + Check the .getlist() function to ensure we receive the correct number of files. + """ + file_counts = {} + + for key in request.FILES.keys(): + file_counts[key] = len(request.FILES.getlist(key)) + return HttpResponse(simplejson.dumps(file_counts)) diff --git a/tests/regressiontests/forms/fields.py b/tests/regressiontests/forms/fields.py index 4725c3ecf3..f266e7bc50 100644 --- a/tests/regressiontests/forms/fields.py +++ b/tests/regressiontests/forms/fields.py @@ -800,10 +800,10 @@ Traceback (most recent call last): ValidationError: [u'The submitted file is empty.'] >>> type(f.clean(SimpleUploadedFile('name', 'Some File Content'))) -<class 'django.newforms.fields.UploadedFile'> +<class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf')) -<class 'django.newforms.fields.UploadedFile'> +<class 'django.core.files.uploadedfile.SimpleUploadedFile'> # URLField ################################################################## diff --git a/tests/regressiontests/model_inheritance_regress/models.py b/tests/regressiontests/model_inheritance_regress/models.py index 24d6186150..b78b493e15 100644 --- a/tests/regressiontests/model_inheritance_regress/models.py +++ b/tests/regressiontests/model_inheritance_regress/models.py @@ -6,6 +6,12 @@ import datetime from django.db import models +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted + class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) diff --git a/tests/regressiontests/queries/models.py b/tests/regressiontests/queries/models.py index 566411e513..65d0d6ec65 100644 --- a/tests/regressiontests/queries/models.py +++ b/tests/regressiontests/queries/models.py @@ -8,6 +8,12 @@ import pickle from django.db import models from django.db.models.query import Q +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted + class Tag(models.Model): name = models.CharField(max_length=10) parent = models.ForeignKey('self', blank=True, null=True, @@ -805,5 +811,14 @@ Bug #7371 >>> Related.objects.order_by('custom') [] +Bug #7448, #7707 -- Complex objects should be converted to strings before being +used in lookups. +>>> Item.objects.filter(created__in=[time1, time2]) +[<Item: one>, <Item: two>] + +Bug #7698 -- People like to slice with '0' as the high-water mark. +>>> Item.objects.all()[0:0] +[] + """} diff --git a/tests/regressiontests/utils/datastructures.py b/tests/regressiontests/utils/datastructures.py index 52bf81a9e0..5d31d21318 100644 --- a/tests/regressiontests/utils/datastructures.py +++ b/tests/regressiontests/utils/datastructures.py @@ -44,8 +44,15 @@ >>> d.keys() [2, 1] >>> real_dict = dict(tuples) ->>> real_dict.values() +>>> sorted(real_dict.values()) ['one', 'second-two'] ->>> d.values() +>>> d.values() # Here the order of SortedDict values *is* what we are testing ['second-two', 'one'] -"""
\ No newline at end of file +""" + +# Python 2.3 doesn't have sorted() +try: + sorted +except NameError: + from django.utils.itercompat import sorted +
\ No newline at end of file diff --git a/tests/regressiontests/utils/itercompat.py b/tests/regressiontests/utils/itercompat.py new file mode 100644 index 0000000000..ad79cffcd1 --- /dev/null +++ b/tests/regressiontests/utils/itercompat.py @@ -0,0 +1,15 @@ +""" +# Tests of the utils itercompat library. + +>>> from django.utils.itercompat import sorted as compat_sorted + +# Check the replacement version of sorted +>>> x = [5,1,4,2,3] +>>> y = compat_sorted(x) +>>> print y +[1, 2, 3, 4, 5] + +>>> print x +[5, 1, 4, 2, 3] + +"""
\ No newline at end of file diff --git a/tests/regressiontests/utils/tests.py b/tests/regressiontests/utils/tests.py index 6fc645505b..cd4762e02f 100644 --- a/tests/regressiontests/utils/tests.py +++ b/tests/regressiontests/utils/tests.py @@ -8,12 +8,14 @@ from django.utils import html, checksums import timesince import datastructures +import itercompat from decorators import DecoratorFromMiddlewareTests # Extra tests __test__ = { 'timesince': timesince, 'datastructures': datastructures, + 'itercompat': itercompat, } class TestUtilsHtml(TestCase): |
