Skip to content

Commit

Permalink
Fixed #27579 -- Added aliases for Python 3's assertion names in Simpl…
Browse files Browse the repository at this point in the history
…eTestCase.
  • Loading branch information
timgraham committed Dec 7, 2016
1 parent f909fa8 commit b5f0b34
Show file tree
Hide file tree
Showing 27 changed files with 84 additions and 104 deletions.
6 changes: 6 additions & 0 deletions django/test/testcases.py
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,12 @@ def assertXMLNotEqual(self, xml1, xml2, msg=None):
standardMsg = '%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
self.fail(self._formatMessage(msg, standardMsg))

if six.PY2:
assertCountEqual = unittest.TestCase.assertItemsEqual
assertNotRegex = unittest.TestCase.assertNotRegexpMatches
assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
assertRegex = unittest.TestCase.assertRegexpMatches


class TransactionTestCase(SimpleTestCase):

Expand Down
5 changes: 2 additions & 3 deletions docs/internals/contributing/writing-code/coding-style.txt
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,8 @@ Python style

* In tests, use :meth:`~django.test.SimpleTestCase.assertRaisesMessage` instead
of :meth:`~unittest.TestCase.assertRaises` so you can check the exception
message. Use :meth:`~unittest.TestCase.assertRaisesRegex`
(``six.assertRaisesRegex()`` as long as we support Python 2) only if you need
to use regular expression matching.
message. Use :meth:`~unittest.TestCase.assertRaisesRegex` only if you need
regular expression matching.

* In test docstrings, state the expected behavior that each test demonstrates.
Don't include preambles such as "Tests that" or "Ensures that".
Expand Down
4 changes: 2 additions & 2 deletions tests/admin_views/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1952,7 +1952,7 @@ def test_shortcut_view_only_available_to_staff(self):
# Can't use self.assertRedirects() because User.get_absolute_url() is silly.
self.assertEqual(response.status_code, 302)
# Domain may depend on contrib.sites tests also run
six.assertRegex(self, response.url, 'http://(testserver|example.com)/dummy/foo/')
self.assertRegex(response.url, 'http://(testserver|example.com)/dummy/foo/')

def test_has_module_permission(self):
"""
Expand Down Expand Up @@ -2113,7 +2113,7 @@ def test_nesting(self):
)
)
response = self.client.get(reverse('admin:admin_views_villain_delete', args=(self.v1.pk,)))
six.assertRegex(self, response.content, pattern)
self.assertRegex(response.content, pattern)

def test_cyclic(self):
"""
Expand Down
3 changes: 1 addition & 2 deletions tests/auth_tests/test_hashers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
)
from django.test import SimpleTestCase, mock
from django.test.utils import override_settings
from django.utils import six
from django.utils.encoding import force_bytes

try:
Expand Down Expand Up @@ -436,7 +435,7 @@ def test_load_library_importerror(self):
PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'})
# Python 3 adds quotes around module name
msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?"
with six.assertRaisesRegex(self, ValueError, msg):
with self.assertRaisesRegex(ValueError, msg):
PlainHasher()._load_library()


Expand Down
2 changes: 1 addition & 1 deletion tests/backends/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -798,7 +798,7 @@ def test_queries(self):

self.assertIsInstance(connection.queries, list)
self.assertIsInstance(connection.queries[0], dict)
six.assertCountEqual(self, connection.queries[0].keys(), ['sql', 'time'])
self.assertCountEqual(connection.queries[0].keys(), ['sql', 'time'])

reset_queries()
self.assertEqual(0, len(connection.queries))
Expand Down
3 changes: 1 addition & 2 deletions tests/check_framework/test_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils import six


class CheckUrlsTest(SimpleTestCase):
Expand Down Expand Up @@ -35,7 +34,7 @@ def test_contains_tuple_not_url_instance(self):
result = check_url_config(None)
warning = result[0]
self.assertEqual(warning.id, 'urls.E004')
six.assertRegex(self, warning.msg, (
self.assertRegex(warning.msg, (
r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) is "
r"invalid. Ensure that urlpatterns is a list of url\(\) instances.$"
))
Expand Down
22 changes: 11 additions & 11 deletions tests/file_storage/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def test_get_invalid_storage_module(self):
"""
get_storage_class raises an error if the requested import don't exist.
"""
with six.assertRaisesRegex(self, ImportError, "No module named '?storage'?"):
with self.assertRaisesRegex(ImportError, "No module named '?storage'?"):
get_storage_class('storage.NonExistingStorage')

def test_get_nonexisting_storage_class(self):
Expand All @@ -64,7 +64,7 @@ def test_get_nonexisting_storage_module(self):
get_storage_class raises an error if the requested module don't exist.
"""
# Error message may or may not be the fully qualified path.
with six.assertRaisesRegex(self, ImportError, "No module named '?(django.core.files.)?non_existing_storage'?"):
with self.assertRaisesRegex(ImportError, "No module named '?(django.core.files.)?non_existing_storage'?"):
get_storage_class('django.core.files.non_existing_storage.NonExistingStorage')


Expand Down Expand Up @@ -703,15 +703,15 @@ def test_files(self):
obj2 = Storage()
obj2.normal.save("django_test.txt", ContentFile("more content"))
obj2_name = obj2.normal.name
six.assertRegex(self, obj2_name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX)
self.assertRegex(obj2_name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX)
self.assertEqual(obj2.normal.size, 12)
obj2.normal.close()

# Deleting an object does not delete the file it uses.
obj2.delete()
obj2.normal.save("django_test.txt", ContentFile("more content"))
self.assertNotEqual(obj2_name, obj2.normal.name)
six.assertRegex(self, obj2.normal.name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX)
self.assertRegex(obj2.normal.name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX)
obj2.normal.close()

def test_filefield_read(self):
Expand Down Expand Up @@ -750,7 +750,7 @@ def test_duplicate_filename(self):
try:
names = [o.normal.name for o in objs]
self.assertEqual(names[0], "tests/multiple_files.txt")
six.assertRegex(self, names[1], "tests/multiple_files_%s.txt" % FILE_SUFFIX_REGEX)
self.assertRegex(names[1], "tests/multiple_files_%s.txt" % FILE_SUFFIX_REGEX)
finally:
for o in objs:
o.delete()
Expand All @@ -770,7 +770,7 @@ def test_file_truncation(self):
# Testing truncation.
names = [o.limited_length.name for o in objs]
self.assertEqual(names[0], 'tests/%s' % filename)
six.assertRegex(self, names[1], 'tests/fi_%s.ext' % FILE_SUFFIX_REGEX)
self.assertRegex(names[1], 'tests/fi_%s.ext' % FILE_SUFFIX_REGEX)

# Testing exception is raised when filename is too short to truncate.
filename = 'short.longext'
Expand Down Expand Up @@ -879,7 +879,7 @@ def chunks(self):
return super(ContentFile, self).chunks()


class FileSaveRaceConditionTest(unittest.TestCase):
class FileSaveRaceConditionTest(SimpleTestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir)
Expand All @@ -897,7 +897,7 @@ def test_race_condition(self):
self.thread.join()
files = sorted(os.listdir(self.storage_dir))
self.assertEqual(files[0], 'conflict')
six.assertRegex(self, files[1], 'conflict_%s' % FILE_SUFFIX_REGEX)
self.assertRegex(files[1], 'conflict_%s' % FILE_SUFFIX_REGEX)


@unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports umasks and chmod.")
Expand Down Expand Up @@ -940,7 +940,7 @@ def test_file_upload_directory_default_permissions(self):
self.assertEqual(dir_mode, 0o777 & ~self.umask)


class FileStoragePathParsing(unittest.TestCase):
class FileStoragePathParsing(SimpleTestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir)
Expand All @@ -961,7 +961,7 @@ def test_directory_with_dot(self):
files = sorted(os.listdir(os.path.join(self.storage_dir, 'dotted.path')))
self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
self.assertEqual(files[0], 'test')
six.assertRegex(self, files[1], 'test_%s' % FILE_SUFFIX_REGEX)
self.assertRegex(files[1], 'test_%s' % FILE_SUFFIX_REGEX)

def test_first_character_dot(self):
"""
Expand All @@ -974,7 +974,7 @@ def test_first_character_dot(self):
files = sorted(os.listdir(os.path.join(self.storage_dir, 'dotted.path')))
self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
self.assertEqual(files[0], '.test')
six.assertRegex(self, files[1], '.test_%s' % FILE_SUFFIX_REGEX)
self.assertRegex(files[1], '.test_%s' % FILE_SUFFIX_REGEX)


class ContentFileStorageTestCase(unittest.TestCase):
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures_regress/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def test_unimportable_serializer(self):
"""
Failing serializer import raises the proper error
"""
with six.assertRaisesRegex(self, ImportError, r"No module named.*unexistent"):
with self.assertRaisesRegex(ImportError, r"No module named.*unexistent"):
management.call_command(
'loaddata',
'bad_fixture1.unkn',
Expand Down
9 changes: 4 additions & 5 deletions tests/forms_tests/field_tests/test_regexfield.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from django.forms import RegexField, ValidationError
from django.test import SimpleTestCase
from django.utils import six


class RegexFieldTest(SimpleTestCase):
Expand Down Expand Up @@ -46,12 +45,12 @@ def test_regexfield_4(self):
f = RegexField('^[0-9]+$', min_length=5, max_length=10)
with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'"):
f.clean('123')
six.assertRaisesRegex(
self, ValidationError,
with self.assertRaisesRegex(
ValidationError,
r"'Ensure this value has at least 5 characters \(it has 3\)\.',"
r" u?'Enter a valid value\.'",
f.clean, 'abc'
)
):
f.clean('abc')
self.assertEqual('12345', f.clean('12345'))
self.assertEqual('1234567890', f.clean('1234567890'))
with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'"):
Expand Down
5 changes: 2 additions & 3 deletions tests/forms_tests/field_tests/test_splitdatetimefield.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from django.forms import SplitDateTimeField, ValidationError
from django.forms.widgets import SplitDateTimeWidget
from django.test import SimpleTestCase
from django.utils import six


class SplitDateTimeFieldTest(SimpleTestCase):
Expand All @@ -23,7 +22,7 @@ def test_splitdatetimefield_1(self):
f.clean('')
with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
f.clean('hello')
with six.assertRaisesRegex(self, ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"):
with self.assertRaisesRegex(ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"):
f.clean(['hello', 'there'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(['2006-01-10', 'there'])
Expand All @@ -43,7 +42,7 @@ def test_splitdatetimefield_2(self):
self.assertIsNone(f.clean(['', '']))
with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
f.clean('hello')
with six.assertRaisesRegex(self, ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"):
with self.assertRaisesRegex(ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"):
f.clean(['hello', 'there'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(['2006-01-10', 'there'])
Expand Down
15 changes: 6 additions & 9 deletions tests/forms_tests/tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
from django.template import Context, Template
from django.test import SimpleTestCase
from django.test.utils import str_prefix
from django.utils import six
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.html import format_html
Expand Down Expand Up @@ -1101,7 +1100,7 @@ def clean(self):
self.assertEqual(f.errors['password1'], ['Forbidden value 2.'])
self.assertEqual(f.errors['password2'], ['Forbidden value 2.'])

with six.assertRaisesRegex(self, ValueError, "has no field named"):
with self.assertRaisesMessage(ValueError, "has no field named"):
f.add_error('missing_field', 'Some error.')

def test_update_error_dict(self):
Expand Down Expand Up @@ -2442,7 +2441,7 @@ def my_function(method, post_data):
form = UserRegistration(auto_id=False)

if form.is_valid():
return 'VALID: %r' % sorted(six.iteritems(form.cleaned_data))
return 'VALID: %r' % sorted(form.cleaned_data.items())

t = Template(
'<form action="" method="post">\n'
Expand Down Expand Up @@ -2912,8 +2911,8 @@ def compress(self, data_list):
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex(
self, ValidationError,
self.assertRaisesRegex(
ValidationError,
r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
)
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
Expand All @@ -2928,10 +2927,8 @@ def compress(self, data_list):
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex(
self, ValidationError,
r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
)
with self.assertRaisesRegex(ValidationError, r"'Enter a complete value\.', u?'Enter an extension\.'"):
f.clean(['', '', '', 'Home'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home'])

Expand Down
4 changes: 2 additions & 2 deletions tests/gis_tests/gdal_tests/test_raster.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@


@unittest.skipUnless(HAS_GDAL, "GDAL is required")
class GDALRasterTests(unittest.TestCase):
class GDALRasterTests(SimpleTestCase):
"""
Test a GDALRaster instance created from a file (GeoTiff).
"""
Expand All @@ -71,7 +71,7 @@ def setUp(self):

def test_rs_name_repr(self):
self.assertEqual(self.rs_path, self.rs.name)
six.assertRegex(self, repr(self.rs), r"<Raster object at 0x\w+>")
self.assertRegex(repr(self.rs), r"<Raster object at 0x\w+>")

def test_rs_driver(self):
self.assertEqual(self.rs.driver.name, 'GTiff')
Expand Down
10 changes: 4 additions & 6 deletions tests/gis_tests/test_spatialrefsys.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import re
import unittest

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

from .utils import SpatialRefSys, oracle, postgis, spatialite

Expand Down Expand Up @@ -51,7 +49,7 @@


@skipUnlessDBFeature("has_spatialrefsys_table")
class SpatialRefSysTest(unittest.TestCase):
class SpatialRefSysTest(TestCase):

def test_get_units(self):
epsg_4326 = next(f for f in test_srs if f['srid'] == 4326)
Expand Down Expand Up @@ -79,7 +77,7 @@ def test_retrieve(self):
# No proj.4 and different srtext on oracle backends :(
if postgis:
self.assertTrue(srs.wkt.startswith(sd['srtext']))
six.assertRegex(self, srs.proj4text, sd['proj4_re'])
self.assertRegex(srs.proj4text, sd['proj4_re'])

def test_osr(self):
"""
Expand All @@ -99,7 +97,7 @@ def test_osr(self):
# Testing the SpatialReference object directly.
if postgis or spatialite:
srs = sr.srs
six.assertRegex(self, srs.proj4, sd['proj4_re'])
self.assertRegex(srs.proj4, sd['proj4_re'])
self.assertTrue(srs.wkt.startswith(sd['srtext']))

def test_ellipsoid(self):
Expand Down
Loading

0 comments on commit b5f0b34

Please sign in to comment.