From b5f0b3478dfcf0335f8ac2038d59f54b4a05f2a0 Mon Sep 17 00:00:00 2001
From: Tim Graham
Date: Wed, 7 Dec 2016 17:42:31 -0500
Subject: [PATCH] Fixed #27579 -- Added aliases for Python 3's assertion names
in SimpleTestCase.
---
django/test/testcases.py | 6 ++++
.../writing-code/coding-style.txt | 5 ++--
tests/admin_views/tests.py | 4 +--
tests/auth_tests/test_hashers.py | 3 +-
tests/backends/tests.py | 2 +-
tests/check_framework/test_urls.py | 3 +-
tests/file_storage/tests.py | 22 +++++++-------
tests/fixtures_regress/tests.py | 2 +-
.../field_tests/test_regexfield.py | 9 +++---
.../field_tests/test_splitdatetimefield.py | 5 ++--
tests/forms_tests/tests/test_forms.py | 15 ++++------
tests/gis_tests/gdal_tests/test_raster.py | 4 +--
tests/gis_tests/test_spatialrefsys.py | 10 +++----
tests/i18n/test_extraction.py | 29 +++++++------------
tests/i18n/tests.py | 12 ++++----
tests/logging_tests/tests.py | 2 +-
tests/m2m_regress/tests.py | 8 ++---
tests/many_to_one/tests.py | 6 ++--
tests/migrations/test_writer.py | 2 +-
tests/modeladmin/tests.py | 3 +-
tests/template_tests/test_custom.py | 4 +--
tests/template_tests/test_parser.py | 8 ++---
tests/test_utils/tests.py | 7 ++---
tests/timezones/tests.py | 2 +-
tests/urlpatterns_reverse/tests.py | 2 +-
tests/utils_tests/test_module_loading.py | 5 ++--
tests/version/tests.py | 8 ++---
27 files changed, 84 insertions(+), 104 deletions(-)
diff --git a/django/test/testcases.py b/django/test/testcases.py
index be5720a80b..4538716ce7 100644
--- a/django/test/testcases.py
+++ b/django/test/testcases.py
@@ -802,6 +802,12 @@ class SimpleTestCase(unittest.TestCase):
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):
diff --git a/docs/internals/contributing/writing-code/coding-style.txt b/docs/internals/contributing/writing-code/coding-style.txt
index 7b7712919b..fe0a21c5a5 100644
--- a/docs/internals/contributing/writing-code/coding-style.txt
+++ b/docs/internals/contributing/writing-code/coding-style.txt
@@ -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".
diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
index ae66e2e508..e8e8d1c2d4 100644
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -1952,7 +1952,7 @@ class AdminViewPermissionsTest(TestCase):
# 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):
"""
@@ -2113,7 +2113,7 @@ class AdminViewDeletedObjectsTest(TestCase):
)
)
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):
"""
diff --git a/tests/auth_tests/test_hashers.py b/tests/auth_tests/test_hashers.py
index 69ca1a141f..1d0832da32 100644
--- a/tests/auth_tests/test_hashers.py
+++ b/tests/auth_tests/test_hashers.py
@@ -12,7 +12,6 @@ from django.contrib.auth.hashers import (
)
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:
@@ -436,7 +435,7 @@ class TestUtilsHashPass(SimpleTestCase):
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()
diff --git a/tests/backends/tests.py b/tests/backends/tests.py
index f2bb1b8998..558878562c 100644
--- a/tests/backends/tests.py
+++ b/tests/backends/tests.py
@@ -798,7 +798,7 @@ class BackendTestCase(TransactionTestCase):
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))
diff --git a/tests/check_framework/test_urls.py b/tests/check_framework/test_urls.py
index 3418af8ac0..159c41e7a9 100644
--- a/tests/check_framework/test_urls.py
+++ b/tests/check_framework/test_urls.py
@@ -4,7 +4,6 @@ from django.core.checks.urls import (
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
-from django.utils import six
class CheckUrlsTest(SimpleTestCase):
@@ -35,7 +34,7 @@ class CheckUrlsTest(SimpleTestCase):
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/\$', at 0x(\w+)>\) is "
r"invalid. Ensure that urlpatterns is a list of url\(\) instances.$"
))
diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py
index 422435518e..3ac6483623 100644
--- a/tests/file_storage/tests.py
+++ b/tests/file_storage/tests.py
@@ -49,7 +49,7 @@ class GetStorageClassTests(SimpleTestCase):
"""
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):
@@ -64,7 +64,7 @@ class GetStorageClassTests(SimpleTestCase):
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')
@@ -703,7 +703,7 @@ class FileFieldStorageTests(TestCase):
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()
@@ -711,7 +711,7 @@ class FileFieldStorageTests(TestCase):
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):
@@ -750,7 +750,7 @@ class FileFieldStorageTests(TestCase):
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()
@@ -770,7 +770,7 @@ class FileFieldStorageTests(TestCase):
# 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'
@@ -879,7 +879,7 @@ class SlowFile(ContentFile):
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)
@@ -897,7 +897,7 @@ class FileSaveRaceConditionTest(unittest.TestCase):
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.")
@@ -940,7 +940,7 @@ class FileStoragePermissions(unittest.TestCase):
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)
@@ -961,7 +961,7 @@ class FileStoragePathParsing(unittest.TestCase):
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):
"""
@@ -974,7 +974,7 @@ class FileStoragePathParsing(unittest.TestCase):
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):
diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py
index cc787e432d..42f410d753 100644
--- a/tests/fixtures_regress/tests.py
+++ b/tests/fixtures_regress/tests.py
@@ -214,7 +214,7 @@ class TestFixtures(TestCase):
"""
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',
diff --git a/tests/forms_tests/field_tests/test_regexfield.py b/tests/forms_tests/field_tests/test_regexfield.py
index c0e75438f6..02a627b8d2 100644
--- a/tests/forms_tests/field_tests/test_regexfield.py
+++ b/tests/forms_tests/field_tests/test_regexfield.py
@@ -5,7 +5,6 @@ import re
from django.forms import RegexField, ValidationError
from django.test import SimpleTestCase
-from django.utils import six
class RegexFieldTest(SimpleTestCase):
@@ -46,12 +45,12 @@ class RegexFieldTest(SimpleTestCase):
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).'"):
diff --git a/tests/forms_tests/field_tests/test_splitdatetimefield.py b/tests/forms_tests/field_tests/test_splitdatetimefield.py
index e46eb163a8..db8df41441 100644
--- a/tests/forms_tests/field_tests/test_splitdatetimefield.py
+++ b/tests/forms_tests/field_tests/test_splitdatetimefield.py
@@ -5,7 +5,6 @@ import datetime
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):
@@ -23,7 +22,7 @@ class SplitDateTimeFieldTest(SimpleTestCase):
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'])
@@ -43,7 +42,7 @@ class SplitDateTimeFieldTest(SimpleTestCase):
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'])
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
index 8007ad85af..8e94d29463 100644
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -22,7 +22,6 @@ from django.http import QueryDict
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
@@ -1101,7 +1100,7 @@ value="Should escape < & > and <script>alert('xss')</
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):
@@ -2442,7 +2441,7 @@ Password:
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(
'
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.'"):
@@ -2928,10 +2927,8 @@ Good luck picking a username that doesn't already exist.
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'])
diff --git a/tests/gis_tests/gdal_tests/test_raster.py b/tests/gis_tests/gdal_tests/test_raster.py
index 8aff5bcec4..8649e9f231 100644
--- a/tests/gis_tests/gdal_tests/test_raster.py
+++ b/tests/gis_tests/gdal_tests/test_raster.py
@@ -60,7 +60,7 @@ if HAS_GDAL:
@unittest.skipUnless(HAS_GDAL, "GDAL is required")
-class GDALRasterTests(unittest.TestCase):
+class GDALRasterTests(SimpleTestCase):
"""
Test a GDALRaster instance created from a file (GeoTiff).
"""
@@ -71,7 +71,7 @@ class GDALRasterTests(unittest.TestCase):
def test_rs_name_repr(self):
self.assertEqual(self.rs_path, self.rs.name)
- six.assertRegex(self, repr(self.rs), r"")
+ self.assertRegex(repr(self.rs), r"")
def test_rs_driver(self):
self.assertEqual(self.rs.driver.name, 'GTiff')
diff --git a/tests/gis_tests/test_spatialrefsys.py b/tests/gis_tests/test_spatialrefsys.py
index 93ff3f6263..90e8084af1 100644
--- a/tests/gis_tests/test_spatialrefsys.py
+++ b/tests/gis_tests/test_spatialrefsys.py
@@ -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
@@ -51,7 +49,7 @@ test_srs = ({
@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)
@@ -79,7 +77,7 @@ class SpatialRefSysTest(unittest.TestCase):
# 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):
"""
@@ -99,7 +97,7 @@ class SpatialRefSysTest(unittest.TestCase):
# 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):
diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
index 708e8475a4..9311a1e7f0 100644
--- a/tests/i18n/test_extraction.py
+++ b/tests/i18n/test_extraction.py
@@ -80,16 +80,9 @@ class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
needle = ''.join(parts)
pattern = re.compile(r'^\#\:.*' + re.escape(needle), re.MULTILINE)
if assert_presence:
- return six.assertRegex(self, po_contents, pattern, '"%s" not found in final .po file.' % needle)
+ return self.assertRegex(po_contents, pattern, '"%s" not found in final .po file.' % needle)
else:
- if six.PY3:
- return self.assertNotRegex(
- po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle
- )
- else:
- return self.assertNotRegexpMatches(
- po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle
- )
+ return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle)
def _get_token_line_number(self, path, token):
with open(path) as f:
@@ -292,20 +285,20 @@ class BasicExtractorTests(ExtractorTests):
self.assertEqual(len(ws), 3)
for w in ws:
self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
- six.assertRegex(
- self, str(ws[0].message),
+ self.assertRegex(
+ str(ws[0].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #1' \(file templates[/\\]comments.thtml, line 4\) "
r"was ignored, because it wasn't the last item on the line\."
)
- six.assertRegex(
- self, str(ws[1].message),
+ self.assertRegex(
+ str(ws[1].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #3' \(file templates[/\\]comments.thtml, line 6\) "
r"was ignored, because it wasn't the last item on the line\."
)
- six.assertRegex(
- self, str(ws[2].message),
+ self.assertRegex(
+ str(ws[2].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #4' \(file templates[/\\]comments.thtml, line 8\) "
r"was ignored, because it wasn't the last item on the line\."
@@ -343,8 +336,8 @@ class BasicExtractorTests(ExtractorTests):
self.assertIn('#. Translators: valid i18n comment #7', po_contents)
self.assertMsgId('Translatable literal #9i', po_contents)
- six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #8')
- six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #9')
+ self.assertRegex(po_contents, r'#\..+Translators: valid i18n comment #8')
+ self.assertRegex(po_contents, r'#\..+Translators: valid i18n comment #9')
self.assertMsgId("Translatable literal #9j", po_contents)
def test_makemessages_find_files(self):
@@ -392,7 +385,7 @@ class BasicExtractorTests(ExtractorTests):
mocked_popen_wrapper.return_value = (
"any other return value\n", '', 0)
cmd = MakeMessagesCommand()
- with six.assertRaisesRegex(self, CommandError, "Unable to get gettext version. Is it installed?"):
+ with self.assertRaisesMessage(CommandError, "Unable to get gettext version. Is it installed?"):
cmd.gettext_version
def test_po_file_encoding_when_updating(self):
diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
index 8d8d4c752e..fdd8903e0f 100644
--- a/tests/i18n/tests.py
+++ b/tests/i18n/tests.py
@@ -215,17 +215,17 @@ class TranslationTests(SimpleTestCase):
self.assertEqual(complex_nonlazy % {'num': 4, 'name': 'Jim'}, 'Hallo Jim, 4 guten Resultate')
self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 1}, 'Hallo Jim, 1 gutes Resultat')
self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 5}, 'Hallo Jim, 5 guten Resultate')
- with six.assertRaisesRegex(self, KeyError, 'Your dictionary lacks key.*'):
+ with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'):
complex_deferred % {'name': 'Jim'}
self.assertEqual(complex_str_nonlazy % {'num': 4, 'name': 'Jim'}, str('Hallo Jim, 4 guten Resultate'))
self.assertEqual(complex_str_deferred % {'name': 'Jim', 'num': 1}, str('Hallo Jim, 1 gutes Resultat'))
self.assertEqual(complex_str_deferred % {'name': 'Jim', 'num': 5}, str('Hallo Jim, 5 guten Resultate'))
- with six.assertRaisesRegex(self, KeyError, 'Your dictionary lacks key.*'):
+ with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'):
complex_str_deferred % {'name': 'Jim'}
self.assertEqual(complex_context_nonlazy % {'num': 4, 'name': 'Jim'}, 'Willkommen Jim, 4 guten Resultate')
self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 1}, 'Willkommen Jim, 1 gutes Resultat')
self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 5}, 'Willkommen Jim, 5 guten Resultate')
- with six.assertRaisesRegex(self, KeyError, 'Your dictionary lacks key.*'):
+ with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'):
complex_context_deferred % {'name': 'Jim'}
@skipUnless(six.PY2, "PY3 doesn't have distinct int and long types")
@@ -1630,7 +1630,8 @@ class TestLanguageInfo(SimpleTestCase):
self.assertIs(li['bidi'], False)
def test_unknown_language_code(self):
- six.assertRaisesRegex(self, KeyError, r"Unknown language code xx\.", get_language_info, 'xx')
+ with self.assertRaisesMessage(KeyError, "Unknown language code xx"):
+ get_language_info('xx')
with translation.override('xx'):
# A language with no translation catalogs should fallback to the
# untranslated string.
@@ -1644,7 +1645,8 @@ class TestLanguageInfo(SimpleTestCase):
self.assertIs(li['bidi'], False)
def test_unknown_language_code_and_country_code(self):
- six.assertRaisesRegex(self, KeyError, r"Unknown language code xx-xx and xx\.", get_language_info, 'xx-xx')
+ with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"):
+ get_language_info('xx-xx')
def test_fallback_language_code(self):
"""
diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py
index c494a08ee4..0557ea182b 100644
--- a/tests/logging_tests/tests.py
+++ b/tests/logging_tests/tests.py
@@ -527,4 +527,4 @@ class LogFormattersTests(SimpleTestCase):
with patch_django_server_logger() as logger_output:
logger.info(log_msg)
- six.assertRegex(self, logger_output.getvalue(), r'^\[[-:,.\s\d]+\] %s' % log_msg)
+ self.assertRegex(logger_output.getvalue(), r'^\[[-:,.\s\d]+\] %s' % log_msg)
diff --git a/tests/m2m_regress/tests.py b/tests/m2m_regress/tests.py
index 88b7ebb952..3c882c595a 100644
--- a/tests/m2m_regress/tests.py
+++ b/tests/m2m_regress/tests.py
@@ -2,7 +2,6 @@ from __future__ import unicode_literals
from django.core.exceptions import FieldError
from django.test import TestCase
-from django.utils import six
from .models import (
Entry, Line, Post, RegressionModelSplit, SelfRefer, SelfReferChild,
@@ -37,10 +36,9 @@ class M2MRegressionTests(TestCase):
def test_internal_related_name_not_in_error_msg(self):
# The secret internal related names for self-referential many-to-many
# fields shouldn't appear in the list when an error is made.
-
- six.assertRaisesRegex(
- self, FieldError,
- "Choices are: id, name, references, related, selfreferchild, selfreferchildsibling$",
+ self.assertRaisesMessage(
+ FieldError,
+ "Choices are: id, name, references, related, selfreferchild, selfreferchildsibling",
lambda: SelfRefer.objects.filter(porcupine='fred')
)
diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py
index 4244bc4fb0..e29c485baa 100644
--- a/tests/many_to_one/tests.py
+++ b/tests/many_to_one/tests.py
@@ -5,7 +5,6 @@ from django.core.exceptions import FieldError, MultipleObjectsReturned
from django.db import models, transaction
from django.db.utils import IntegrityError
from django.test import TestCase, ignore_warnings
-from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.translation import ugettext_lazy
@@ -73,8 +72,7 @@ class ManyToOneTests(TestCase):
# Adding an object of the wrong type raises TypeError.
with transaction.atomic():
- with six.assertRaisesRegex(self, TypeError,
- "'Article' instance expected, got "):
+ with self.assertRaisesRegex(TypeError, "Variable must be a string or number, got <(class|type) 'dict'>"):
Variable({})
def test_filter_args_count(self):
diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py
index 969cbf7659..0013452cac 100644
--- a/tests/test_utils/tests.py
+++ b/tests/test_utils/tests.py
@@ -368,16 +368,15 @@ class AssertTemplateUsedContextManagerTests(SimpleTestCase):
pass
def test_error_message(self):
- with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html'):
+ with self.assertRaisesRegex(AssertionError, r'^template_used/base\.html'):
with self.assertTemplateUsed('template_used/base.html'):
pass
- with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html'):
+ with self.assertRaisesRegex(AssertionError, r'^template_used/base\.html'):
with self.assertTemplateUsed(template_name='template_used/base.html'):
pass
- with six.assertRaisesRegex(
- self, AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
+ with self.assertRaisesRegex(AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
with self.assertTemplateUsed('template_used/base.html'):
render_to_string('template_used/alternative.html')
diff --git a/tests/timezones/tests.py b/tests/timezones/tests.py
index c50d356074..8f9bd23241 100644
--- a/tests/timezones/tests.py
+++ b/tests/timezones/tests.py
@@ -679,7 +679,7 @@ class SerializationTests(SimpleTestCase):
def assert_yaml_contains_datetime(self, yaml, dt):
# Depending on the yaml dumper, '!timestamp' might be absent
- six.assertRegex(self, yaml, r"\n fields: {dt: !(!timestamp)? '%s'}" % re.escape(dt))
+ self.assertRegex(yaml, r"\n fields: {dt: !(!timestamp)? '%s'}" % re.escape(dt))
def test_naive_datetime(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30)
diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py
index ca894fcc8e..4b31e382e1 100644
--- a/tests/urlpatterns_reverse/tests.py
+++ b/tests/urlpatterns_reverse/tests.py
@@ -1005,7 +1005,7 @@ class ViewLoadingTests(SimpleTestCase):
def test_exceptions(self):
# A missing view (identified by an AttributeError) should raise
# ViewDoesNotExist, ...
- with six.assertRaisesRegex(self, ViewDoesNotExist, ".*View does not exist in.*"):
+ with self.assertRaisesMessage(ViewDoesNotExist, "View does not exist in"):
get_callable('urlpatterns_reverse.views.i_should_not_exist')
# ... but if the AttributeError is caused by something else don't
# swallow it.
diff --git a/tests/utils_tests/test_module_loading.py b/tests/utils_tests/test_module_loading.py
index 738d3c7d04..2a524a2cf2 100644
--- a/tests/utils_tests/test_module_loading.py
+++ b/tests/utils_tests/test_module_loading.py
@@ -7,7 +7,6 @@ from zipimport import zipimporter
from django.test import SimpleTestCase, TestCase, modify_settings
from django.test.utils import extend_sys_path
-from django.utils import six
from django.utils._os import upath
from django.utils.module_loading import (
autodiscover_modules, import_string, module_has_submodule,
@@ -147,11 +146,11 @@ class AutodiscoverModulesTestCase(SimpleTestCase):
autodiscover_modules('missing_module')
def test_autodiscover_modules_found_but_bad_module(self):
- with six.assertRaisesRegex(self, ImportError, "No module named '?a_package_name_that_does_not_exist'?"):
+ with self.assertRaisesRegex(ImportError, "No module named '?a_package_name_that_does_not_exist'?"):
autodiscover_modules('bad_module')
def test_autodiscover_modules_several_one_bad_module(self):
- with six.assertRaisesRegex(self, ImportError, "No module named '?a_package_name_that_does_not_exist'?"):
+ with self.assertRaisesRegex(ImportError, "No module named '?a_package_name_that_does_not_exist'?"):
autodiscover_modules('good_module', 'bad_module')
def test_autodiscover_modules_several_found(self):
diff --git a/tests/version/tests.py b/tests/version/tests.py
index b0566685b6..b9541cd31a 100644
--- a/tests/version/tests.py
+++ b/tests/version/tests.py
@@ -1,17 +1,15 @@
-from unittest import TestCase
-
from django import get_version
-from django.utils import six
+from django.test import SimpleTestCase
-class VersionTests(TestCase):
+class VersionTests(SimpleTestCase):
def test_development(self):
ver_tuple = (1, 4, 0, 'alpha', 0)
# This will return a different result when it's run within or outside
# of a git clone: 1.4.devYYYYMMDDHHMMSS or 1.4.
ver_string = get_version(ver_tuple)
- six.assertRegex(self, ver_string, r'1\.4(\.dev[0-9]+)?')
+ self.assertRegex(ver_string, r'1\.4(\.dev[0-9]+)?')
def test_releases(self):
tuples_to_strings = (