Skip to content

Commit

Permalink
[py3k] Silence many warnings while running the tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Gaynor committed Sep 7, 2012
1 parent 4321ee2 commit 292322f
Show file tree
Hide file tree
Showing 29 changed files with 213 additions and 196 deletions.
11 changes: 6 additions & 5 deletions django/contrib/auth/tests/models.py
@@ -1,8 +1,9 @@
from django.conf import settings
from django.contrib.auth.models import (Group, User, SiteProfileNotAvailable,
UserManager)
from django.test import TestCase
from django.test.utils import override_settings
from django.contrib.auth.models import (Group, User,
SiteProfileNotAvailable, UserManager)
from django.utils import six


@override_settings(USE_TZ=False, AUTH_PROFILE_MODULE='')
Expand All @@ -13,19 +14,19 @@ def test_site_profile_not_available(self):

# calling get_profile without AUTH_PROFILE_MODULE set
del settings.AUTH_PROFILE_MODULE
with self.assertRaisesRegexp(SiteProfileNotAvailable,
with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"You need to set AUTH_PROFILE_MODULE in your project"):
user.get_profile()

# Bad syntax in AUTH_PROFILE_MODULE:
settings.AUTH_PROFILE_MODULE = 'foobar'
with self.assertRaisesRegexp(SiteProfileNotAvailable,
with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"app_label and model_name should be separated by a dot"):
user.get_profile()

# module that doesn't exist
settings.AUTH_PROFILE_MODULE = 'foo.bar'
with self.assertRaisesRegexp(SiteProfileNotAvailable,
with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"Unable to load the profile model"):
user.get_profile()

Expand Down
2 changes: 1 addition & 1 deletion django/test/testcases.py
Expand Up @@ -358,7 +358,7 @@ def assertRaisesMessage(self, expected_exception, expected_message,
args: Extra args.
kwargs: Extra kwargs.
"""
return self.assertRaisesRegexp(expected_exception,
return six.assertRaisesRegex(self, expected_exception,
re.escape(expected_message), callable_obj, *args, **kwargs)

def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
Expand Down
7 changes: 7 additions & 0 deletions django/utils/six.py
Expand Up @@ -370,13 +370,20 @@ def with_metaclass(meta, base=object):

if PY3:
_iterlists = "lists"
_assertRaisesRegex = "assertRaisesRegex"
else:
_iterlists = "iterlists"
_assertRaisesRegex = "assertRaisesRegexp"


def iterlists(d):
"""Return an iterator over the values of a MultiValueDict."""
return getattr(d, _iterlists)()


def assertRaisesRegex(self, *args, **kwargs):
return getattr(self, _assertRaisesRegex)(*args, **kwargs)


add_move(MovedModule("_dummy_thread", "dummy_thread"))
add_move(MovedModule("_thread", "thread"))
28 changes: 14 additions & 14 deletions tests/modeltests/basic/tests.py
Expand Up @@ -5,7 +5,7 @@
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields import Field, FieldDoesNotExist
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.utils.six import PY3
from django.utils import six
from django.utils.translation import ugettext_lazy

from .models import Article
Expand Down Expand Up @@ -82,7 +82,7 @@ def test_lookup(self):

# Django raises an Article.DoesNotExist exception for get() if the
# parameters don't match any object.
self.assertRaisesRegexp(
six.assertRaisesRegex(self,
ObjectDoesNotExist,
"Article matching query does not exist. Lookup parameters were "
"{'id__exact': 2000}",
Expand All @@ -91,22 +91,22 @@ def test_lookup(self):
)
# To avoid dict-ordering related errors check only one lookup
# in single assert.
self.assertRaisesRegexp(
six.assertRaisesRegex(self,
ObjectDoesNotExist,
".*'pub_date__year': 2005.*",
Article.objects.get,
pub_date__year=2005,
pub_date__month=8,
)
self.assertRaisesRegexp(
six.assertRaisesRegex(self,
ObjectDoesNotExist,
".*'pub_date__month': 8.*",
Article.objects.get,
pub_date__year=2005,
pub_date__month=8,
)

self.assertRaisesRegexp(
six.assertRaisesRegex(self,
ObjectDoesNotExist,
"Article matching query does not exist. Lookup parameters were "
"{'pub_date__week_day': 6}",
Expand Down Expand Up @@ -168,7 +168,7 @@ def test_object_creation(self):
self.assertEqual(a4.headline, 'Fourth article')

# Don't use invalid keyword arguments.
self.assertRaisesRegexp(
six.assertRaisesRegex(self,
TypeError,
"'foo' is an invalid keyword argument for this function",
Article,
Expand Down Expand Up @@ -259,29 +259,29 @@ def test_object_creation(self):
"datetime.datetime(2005, 7, 28, 0, 0)"])

# dates() requires valid arguments.
self.assertRaisesRegexp(
six.assertRaisesRegex(self,
TypeError,
"dates\(\) takes at least 3 arguments \(1 given\)",
Article.objects.dates,
)

self.assertRaisesRegexp(
six.assertRaisesRegex(self,
FieldDoesNotExist,
"Article has no field named 'invalid_field'",
Article.objects.dates,
"invalid_field",
"year",
)

self.assertRaisesRegexp(
six.assertRaisesRegex(self,
AssertionError,
"'kind' must be one of 'year', 'month' or 'day'.",
Article.objects.dates,
"pub_date",
"bad_kind",
)

self.assertRaisesRegexp(
six.assertRaisesRegex(self,
AssertionError,
"'order' must be either 'ASC' or 'DESC'.",
Article.objects.dates,
Expand Down Expand Up @@ -323,7 +323,7 @@ def test_object_creation(self):
"<Article: Third article>"])

# Slicing works with longs (Python 2 only -- Python 3 doesn't have longs).
if not PY3:
if not six.PY3:
self.assertEqual(Article.objects.all()[long(0)], a)
self.assertQuerysetEqual(Article.objects.all()[long(1):long(3)],
["<Article: Second article>", "<Article: Third article>"])
Expand Down Expand Up @@ -369,14 +369,14 @@ def test_object_creation(self):
"<Article: Updated article 8>"])

# Also, once you have sliced you can't filter, re-order or combine
self.assertRaisesRegexp(
six.assertRaisesRegex(self,
AssertionError,
"Cannot filter a query once a slice has been taken.",
Article.objects.all()[0:5].filter,
id=a.id,
)

self.assertRaisesRegexp(
six.assertRaisesRegex(self,
AssertionError,
"Cannot reorder a query once a slice has been taken.",
Article.objects.all()[0:5].order_by,
Expand Down Expand Up @@ -411,7 +411,7 @@ def test_object_creation(self):

# An Article instance doesn't have access to the "objects" attribute.
# That's only available on the class.
self.assertRaisesRegexp(
six.assertRaisesRegex(self,
AttributeError,
"Manager isn't accessible via Article instances",
getattr,
Expand Down
7 changes: 4 additions & 3 deletions tests/modeltests/empty/tests.py
@@ -1,10 +1,10 @@
from __future__ import absolute_import

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.models.loading import get_app
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import six

from .models import Empty

Expand All @@ -14,12 +14,13 @@ def test_empty(self):
m = Empty()
self.assertEqual(m.id, None)
m.save()
m2 = Empty.objects.create()
Empty.objects.create()
self.assertEqual(len(Empty.objects.all()), 2)
self.assertTrue(m.id is not None)
existing = Empty(m.id)
existing.save()


class NoModelTests(TestCase):
"""
Test for #7198 to ensure that the proper error message is raised
Expand All @@ -32,6 +33,6 @@ class NoModelTests(TestCase):
"""
@override_settings(INSTALLED_APPS=("modeltests.empty.no_models",))
def test_no_models(self):
with self.assertRaisesRegexp(ImproperlyConfigured,
with six.assertRaisesRegex(self, ImproperlyConfigured,
'App with label no_models is missing a models.py module.'):
get_app('no_models')
34 changes: 17 additions & 17 deletions tests/modeltests/fixtures/tests.py
Expand Up @@ -4,7 +4,7 @@
from django.core import management
from django.db import connection, IntegrityError
from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
from django.utils.six import StringIO
from django.utils import six

from .models import Article, Book, Spy, Tag, Visa

Expand All @@ -21,16 +21,17 @@ def testClassFixtures(self):
'<Article: Poker has no place on ESPN>',
])


class FixtureLoadingTests(TestCase):

def _dumpdata_assert(self, args, output, format='json', natural_keys=False,
use_base_manager=False, exclude_list=[]):
new_io = StringIO()
management.call_command('dumpdata', *args, **{'format':format,
'stdout':new_io,
'stderr':new_io,
'use_natural_keys':natural_keys,
'use_base_manager':use_base_manager,
new_io = six.StringIO()
management.call_command('dumpdata', *args, **{'format': format,
'stdout': new_io,
'stderr': new_io,
'use_natural_keys': natural_keys,
'use_base_manager': use_base_manager,
'exclude': exclude_list})
command_output = new_io.getvalue().strip()
self.assertEqual(command_output, output)
Expand All @@ -42,8 +43,6 @@ def test_initial_data(self):
])

def test_loading_and_dumping(self):
new_io = StringIO()

Site.objects.all().delete()
# Load fixture 1. Single JSON file, with two objects.
management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False)
Expand Down Expand Up @@ -184,12 +183,12 @@ def test_dumpdata_with_excludes(self):
exclude_list=['fixtures.Article', 'fixtures.Book', 'sites'])

# Excluding a bogus app should throw an error
with self.assertRaisesRegexp(management.CommandError,
with six.assertRaisesRegex(self, management.CommandError,
"Unknown app in excludes: foo_app"):
self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['foo_app'])

# Excluding a bogus model should throw an error
with self.assertRaisesRegexp(management.CommandError,
with six.assertRaisesRegex(self, management.CommandError,
"Unknown model in excludes: fixtures.FooModel"):
self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['fixtures.FooModel'])

Expand All @@ -199,7 +198,7 @@ def test_dumpdata_with_filtering_manager(self):
self.assertQuerysetEqual(Spy.objects.all(),
['<Spy: Paul>'])
# Use the default manager
self._dumpdata_assert(['fixtures.Spy'],'[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk)
self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk)
# Dump using Django's base manager. Should return all objects,
# even those normally filtered by the manager
self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk), use_base_manager=True)
Expand Down Expand Up @@ -227,7 +226,7 @@ def test_compressed_loading(self):

def test_ambiguous_compressed_fixture(self):
# The name "fixture5" is ambigous, so loading it will raise an error
with self.assertRaisesRegexp(management.CommandError,
with six.assertRaisesRegex(self, management.CommandError,
"Multiple fixtures named 'fixture5'"):
management.call_command('loaddata', 'fixture5', verbosity=0, commit=False)

Expand All @@ -251,7 +250,7 @@ def test_loaddata_error_message(self):
# is closed at the end of each test.
if connection.vendor == 'mysql':
connection.cursor().execute("SET sql_mode = 'TRADITIONAL'")
with self.assertRaisesRegexp(IntegrityError,
with six.assertRaisesRegex(self, IntegrityError,
"Could not load fixtures.Article\(pk=1\): .*$"):
management.call_command('loaddata', 'invalid.json', verbosity=0, commit=False)

Expand Down Expand Up @@ -290,10 +289,11 @@ def test_output_formats(self):
self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field><field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field><field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Prince</field></object><object pk="10" model="fixtures.book"><field type="CharField" name="name">Achieving self-awareness of Python programs</field><field to="fixtures.person" name="authors" rel="ManyToManyRel"></field></object></django-objects>""", format='xml', natural_keys=True)


class FixtureTransactionTests(TransactionTestCase):
def _dumpdata_assert(self, args, output, format='json'):
new_io = StringIO()
management.call_command('dumpdata', *args, **{'format':format, 'stdout':new_io})
new_io = six.StringIO()
management.call_command('dumpdata', *args, **{'format': format, 'stdout': new_io})
command_output = new_io.getvalue().strip()
self.assertEqual(command_output, output)

Expand All @@ -308,7 +308,7 @@ def test_format_discovery(self):

# Try to load fixture 2 using format discovery; this will fail
# because there are two fixture2's in the fixtures directory
with self.assertRaisesRegexp(management.CommandError,
with six.assertRaisesRegex(self, management.CommandError,
"Multiple fixtures named 'fixture2'"):
management.call_command('loaddata', 'fixture2', verbosity=0)

Expand Down
3 changes: 2 additions & 1 deletion tests/modeltests/many_to_many/tests.py
@@ -1,6 +1,7 @@
from __future__ import absolute_import

from django.test import TestCase
from django.utils import six

from .models import Article, Publication

Expand Down Expand Up @@ -52,7 +53,7 @@ def test_add(self):
])

# Adding an object of the wrong type raises TypeError
with self.assertRaisesRegexp(TypeError, "'Publication' instance expected, got <Article.*"):
with six.assertRaisesRegex(self, TypeError, "'Publication' instance expected, got <Article.*"):
a6.publications.add(a5)
# Add a Publication directly via publications.add by using keyword arguments.
p4 = a6.publications.create(title='Highlights for Adults')
Expand Down
2 changes: 1 addition & 1 deletion tests/modeltests/many_to_one/tests.py
Expand Up @@ -70,7 +70,7 @@ def test_add(self):
self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"])

# Adding an object of the wrong type raises TypeError.
with self.assertRaisesRegexp(TypeError, "'Article' instance expected, got <Reporter.*"):
with six.assertRaisesRegex(self, TypeError, "'Article' instance expected, got <Reporter.*"):
self.r.article_set.add(self.r2)
self.assertQuerysetEqual(self.r.article_set.all(),
[
Expand Down
3 changes: 2 additions & 1 deletion tests/modeltests/update_only_fields/tests.py
@@ -1,7 +1,8 @@
from __future__ import absolute_import

from django.test import TestCase
from django.db.models.signals import pre_save, post_save
from django.test import TestCase

from .models import Person, Employee, ProxyEmployee, Profile, Account


Expand Down
3 changes: 2 additions & 1 deletion tests/modeltests/validation/test_error_messages.py
Expand Up @@ -3,6 +3,7 @@

from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.unittest import TestCase


Expand All @@ -18,7 +19,7 @@ def test_autofield_field_raises_error_message(self):
self._test_validation_messages(f, 'fõo',
["'fõo' value must be an integer."])
# primary_key must be True. Refs #12467.
with self.assertRaisesRegexp(AssertionError,
with six.assertRaisesRegex(self, AssertionError,
"AutoFields must have primary_key=True."):
models.AutoField(primary_key=False)

Expand Down

0 comments on commit 292322f

Please sign in to comment.