Fixed #27579 -- Added aliases for Python 3's assertion names in SimpleTestCase.

This commit is contained in:
Tim Graham 2016-12-07 17:42:31 -05:00 committed by GitHub
parent f909fa84be
commit b5f0b3478d
27 changed files with 84 additions and 104 deletions

View File

@ -802,6 +802,12 @@ class SimpleTestCase(unittest.TestCase):
standardMsg = '%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True)) standardMsg = '%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
self.fail(self._formatMessage(msg, standardMsg)) 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): class TransactionTestCase(SimpleTestCase):

View File

@ -49,9 +49,8 @@ Python style
* In tests, use :meth:`~django.test.SimpleTestCase.assertRaisesMessage` instead * In tests, use :meth:`~django.test.SimpleTestCase.assertRaisesMessage` instead
of :meth:`~unittest.TestCase.assertRaises` so you can check the exception of :meth:`~unittest.TestCase.assertRaises` so you can check the exception
message. Use :meth:`~unittest.TestCase.assertRaisesRegex` message. Use :meth:`~unittest.TestCase.assertRaisesRegex` only if you need
(``six.assertRaisesRegex()`` as long as we support Python 2) only if you need regular expression matching.
to use regular expression matching.
* In test docstrings, state the expected behavior that each test demonstrates. * In test docstrings, state the expected behavior that each test demonstrates.
Don't include preambles such as "Tests that" or "Ensures that". Don't include preambles such as "Tests that" or "Ensures that".

View File

@ -1952,7 +1952,7 @@ class AdminViewPermissionsTest(TestCase):
# Can't use self.assertRedirects() because User.get_absolute_url() is silly. # Can't use self.assertRedirects() because User.get_absolute_url() is silly.
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
# Domain may depend on contrib.sites tests also run # 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): 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,))) 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): def test_cyclic(self):
""" """

View File

@ -12,7 +12,6 @@ from django.contrib.auth.hashers import (
) )
from django.test import SimpleTestCase, mock from django.test import SimpleTestCase, mock
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import six
from django.utils.encoding import force_bytes from django.utils.encoding import force_bytes
try: try:
@ -436,7 +435,7 @@ class TestUtilsHashPass(SimpleTestCase):
PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'}) PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'})
# Python 3 adds quotes around module name # Python 3 adds quotes around module name
msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?" 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() PlainHasher()._load_library()

View File

@ -798,7 +798,7 @@ class BackendTestCase(TransactionTestCase):
self.assertIsInstance(connection.queries, list) self.assertIsInstance(connection.queries, list)
self.assertIsInstance(connection.queries[0], dict) 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() reset_queries()
self.assertEqual(0, len(connection.queries)) self.assertEqual(0, len(connection.queries))

View File

@ -4,7 +4,6 @@ from django.core.checks.urls import (
) )
from django.test import SimpleTestCase from django.test import SimpleTestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import six
class CheckUrlsTest(SimpleTestCase): class CheckUrlsTest(SimpleTestCase):
@ -35,7 +34,7 @@ class CheckUrlsTest(SimpleTestCase):
result = check_url_config(None) result = check_url_config(None)
warning = result[0] warning = result[0]
self.assertEqual(warning.id, 'urls.E004') 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"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) is "
r"invalid. Ensure that urlpatterns is a list of url\(\) instances.$" r"invalid. Ensure that urlpatterns is a list of url\(\) instances.$"
)) ))

View File

@ -49,7 +49,7 @@ class GetStorageClassTests(SimpleTestCase):
""" """
get_storage_class raises an error if the requested import don't exist. 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') get_storage_class('storage.NonExistingStorage')
def test_get_nonexisting_storage_class(self): 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. get_storage_class raises an error if the requested module don't exist.
""" """
# Error message may or may not be the fully qualified path. # 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') get_storage_class('django.core.files.non_existing_storage.NonExistingStorage')
@ -703,7 +703,7 @@ class FileFieldStorageTests(TestCase):
obj2 = Storage() obj2 = Storage()
obj2.normal.save("django_test.txt", ContentFile("more content")) obj2.normal.save("django_test.txt", ContentFile("more content"))
obj2_name = obj2.normal.name 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) self.assertEqual(obj2.normal.size, 12)
obj2.normal.close() obj2.normal.close()
@ -711,7 +711,7 @@ class FileFieldStorageTests(TestCase):
obj2.delete() obj2.delete()
obj2.normal.save("django_test.txt", ContentFile("more content")) obj2.normal.save("django_test.txt", ContentFile("more content"))
self.assertNotEqual(obj2_name, obj2.normal.name) 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() obj2.normal.close()
def test_filefield_read(self): def test_filefield_read(self):
@ -750,7 +750,7 @@ class FileFieldStorageTests(TestCase):
try: try:
names = [o.normal.name for o in objs] names = [o.normal.name for o in objs]
self.assertEqual(names[0], "tests/multiple_files.txt") 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: finally:
for o in objs: for o in objs:
o.delete() o.delete()
@ -770,7 +770,7 @@ class FileFieldStorageTests(TestCase):
# Testing truncation. # Testing truncation.
names = [o.limited_length.name for o in objs] names = [o.limited_length.name for o in objs]
self.assertEqual(names[0], 'tests/%s' % filename) 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. # Testing exception is raised when filename is too short to truncate.
filename = 'short.longext' filename = 'short.longext'
@ -879,7 +879,7 @@ class SlowFile(ContentFile):
return super(ContentFile, self).chunks() return super(ContentFile, self).chunks()
class FileSaveRaceConditionTest(unittest.TestCase): class FileSaveRaceConditionTest(SimpleTestCase):
def setUp(self): def setUp(self):
self.storage_dir = tempfile.mkdtemp() self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir) self.storage = FileSystemStorage(self.storage_dir)
@ -897,7 +897,7 @@ class FileSaveRaceConditionTest(unittest.TestCase):
self.thread.join() self.thread.join()
files = sorted(os.listdir(self.storage_dir)) files = sorted(os.listdir(self.storage_dir))
self.assertEqual(files[0], 'conflict') 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.") @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) self.assertEqual(dir_mode, 0o777 & ~self.umask)
class FileStoragePathParsing(unittest.TestCase): class FileStoragePathParsing(SimpleTestCase):
def setUp(self): def setUp(self):
self.storage_dir = tempfile.mkdtemp() self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir) 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'))) 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.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
self.assertEqual(files[0], 'test') 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): 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'))) 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.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
self.assertEqual(files[0], '.test') 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): class ContentFileStorageTestCase(unittest.TestCase):

View File

@ -214,7 +214,7 @@ class TestFixtures(TestCase):
""" """
Failing serializer import raises the proper error 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( management.call_command(
'loaddata', 'loaddata',
'bad_fixture1.unkn', 'bad_fixture1.unkn',

View File

@ -5,7 +5,6 @@ import re
from django.forms import RegexField, ValidationError from django.forms import RegexField, ValidationError
from django.test import SimpleTestCase from django.test import SimpleTestCase
from django.utils import six
class RegexFieldTest(SimpleTestCase): class RegexFieldTest(SimpleTestCase):
@ -46,12 +45,12 @@ class RegexFieldTest(SimpleTestCase):
f = RegexField('^[0-9]+$', min_length=5, max_length=10) 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).'"): with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'"):
f.clean('123') f.clean('123')
six.assertRaisesRegex( with self.assertRaisesRegex(
self, ValidationError, ValidationError,
r"'Ensure this value has at least 5 characters \(it has 3\)\.'," r"'Ensure this value has at least 5 characters \(it has 3\)\.',"
r" u?'Enter a valid value\.'", r" u?'Enter a valid value\.'",
f.clean, 'abc' ):
) f.clean('abc')
self.assertEqual('12345', f.clean('12345')) self.assertEqual('12345', f.clean('12345'))
self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890', f.clean('1234567890'))
with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'"): with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'"):

View File

@ -5,7 +5,6 @@ import datetime
from django.forms import SplitDateTimeField, ValidationError from django.forms import SplitDateTimeField, ValidationError
from django.forms.widgets import SplitDateTimeWidget from django.forms.widgets import SplitDateTimeWidget
from django.test import SimpleTestCase from django.test import SimpleTestCase
from django.utils import six
class SplitDateTimeFieldTest(SimpleTestCase): class SplitDateTimeFieldTest(SimpleTestCase):
@ -23,7 +22,7 @@ class SplitDateTimeFieldTest(SimpleTestCase):
f.clean('') f.clean('')
with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
f.clean('hello') 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']) f.clean(['hello', 'there'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(['2006-01-10', 'there']) f.clean(['2006-01-10', 'there'])
@ -43,7 +42,7 @@ class SplitDateTimeFieldTest(SimpleTestCase):
self.assertIsNone(f.clean(['', ''])) self.assertIsNone(f.clean(['', '']))
with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
f.clean('hello') 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']) f.clean(['hello', 'there'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(['2006-01-10', 'there']) f.clean(['2006-01-10', 'there'])

View File

@ -22,7 +22,6 @@ from django.http import QueryDict
from django.template import Context, Template from django.template import Context, Template
from django.test import SimpleTestCase from django.test import SimpleTestCase
from django.test.utils import str_prefix from django.test.utils import str_prefix
from django.utils import six
from django.utils.datastructures import MultiValueDict from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.html import format_html from django.utils.html import format_html
@ -1101,7 +1100,7 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/
self.assertEqual(f.errors['password1'], ['Forbidden value 2.']) self.assertEqual(f.errors['password1'], ['Forbidden value 2.'])
self.assertEqual(f.errors['password2'], ['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.') f.add_error('missing_field', 'Some error.')
def test_update_error_dict(self): def test_update_error_dict(self):
@ -2442,7 +2441,7 @@ Password: <input type="password" name="password" required />
form = UserRegistration(auto_id=False) form = UserRegistration(auto_id=False)
if form.is_valid(): if form.is_valid():
return 'VALID: %r' % sorted(six.iteritems(form.cleaned_data)) return 'VALID: %r' % sorted(form.cleaned_data.items())
t = Template( t = Template(
'<form action="" method="post">\n' '<form action="" method="post">\n'
@ -2912,8 +2911,8 @@ Good luck picking a username that doesn&#39;t already exist.</p>
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61']) f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex( self.assertRaisesRegex(
self, ValidationError, ValidationError,
r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'] r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
) )
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
@ -2928,10 +2927,8 @@ Good luck picking a username that doesn&#39;t already exist.</p>
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61']) f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex( with self.assertRaisesRegex(ValidationError, r"'Enter a complete value\.', u?'Enter an extension\.'"):
self, ValidationError, f.clean(['', '', '', 'Home'])
r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
)
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])

View File

@ -60,7 +60,7 @@ if HAS_GDAL:
@unittest.skipUnless(HAS_GDAL, "GDAL is required") @unittest.skipUnless(HAS_GDAL, "GDAL is required")
class GDALRasterTests(unittest.TestCase): class GDALRasterTests(SimpleTestCase):
""" """
Test a GDALRaster instance created from a file (GeoTiff). Test a GDALRaster instance created from a file (GeoTiff).
""" """
@ -71,7 +71,7 @@ class GDALRasterTests(unittest.TestCase):
def test_rs_name_repr(self): def test_rs_name_repr(self):
self.assertEqual(self.rs_path, self.rs.name) 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): def test_rs_driver(self):
self.assertEqual(self.rs.driver.name, 'GTiff') self.assertEqual(self.rs.driver.name, 'GTiff')

View File

@ -1,8 +1,6 @@
import re import re
import unittest
from django.test import skipUnlessDBFeature from django.test import TestCase, skipUnlessDBFeature
from django.utils import six
from .utils import SpatialRefSys, oracle, postgis, spatialite from .utils import SpatialRefSys, oracle, postgis, spatialite
@ -51,7 +49,7 @@ test_srs = ({
@skipUnlessDBFeature("has_spatialrefsys_table") @skipUnlessDBFeature("has_spatialrefsys_table")
class SpatialRefSysTest(unittest.TestCase): class SpatialRefSysTest(TestCase):
def test_get_units(self): def test_get_units(self):
epsg_4326 = next(f for f in test_srs if f['srid'] == 4326) 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 :( # No proj.4 and different srtext on oracle backends :(
if postgis: if postgis:
self.assertTrue(srs.wkt.startswith(sd['srtext'])) 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): def test_osr(self):
""" """
@ -99,7 +97,7 @@ class SpatialRefSysTest(unittest.TestCase):
# Testing the SpatialReference object directly. # Testing the SpatialReference object directly.
if postgis or spatialite: if postgis or spatialite:
srs = sr.srs 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'])) self.assertTrue(srs.wkt.startswith(sd['srtext']))
def test_ellipsoid(self): def test_ellipsoid(self):

View File

@ -80,16 +80,9 @@ class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
needle = ''.join(parts) needle = ''.join(parts)
pattern = re.compile(r'^\#\:.*' + re.escape(needle), re.MULTILINE) pattern = re.compile(r'^\#\:.*' + re.escape(needle), re.MULTILINE)
if assert_presence: 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: else:
if six.PY3: return self.assertNotRegex(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
)
else:
return self.assertNotRegexpMatches(
po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle
)
def _get_token_line_number(self, path, token): def _get_token_line_number(self, path, token):
with open(path) as f: with open(path) as f:
@ -292,20 +285,20 @@ class BasicExtractorTests(ExtractorTests):
self.assertEqual(len(ws), 3) self.assertEqual(len(ws), 3)
for w in ws: for w in ws:
self.assertTrue(issubclass(w.category, TranslatorCommentWarning)) self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
six.assertRegex( self.assertRegex(
self, str(ws[0].message), str(ws[0].message),
r"The translator-targeted comment 'Translators: ignored i18n " r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #1' \(file templates[/\\]comments.thtml, line 4\) " r"comment #1' \(file templates[/\\]comments.thtml, line 4\) "
r"was ignored, because it wasn't the last item on the line\." r"was ignored, because it wasn't the last item on the line\."
) )
six.assertRegex( self.assertRegex(
self, str(ws[1].message), str(ws[1].message),
r"The translator-targeted comment 'Translators: ignored i18n " r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #3' \(file templates[/\\]comments.thtml, line 6\) " r"comment #3' \(file templates[/\\]comments.thtml, line 6\) "
r"was ignored, because it wasn't the last item on the line\." r"was ignored, because it wasn't the last item on the line\."
) )
six.assertRegex( self.assertRegex(
self, str(ws[2].message), str(ws[2].message),
r"The translator-targeted comment 'Translators: ignored i18n " r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #4' \(file templates[/\\]comments.thtml, line 8\) " r"comment #4' \(file templates[/\\]comments.thtml, line 8\) "
r"was ignored, because it wasn't the last item on the line\." 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.assertIn('#. Translators: valid i18n comment #7', po_contents)
self.assertMsgId('Translatable literal #9i', po_contents) self.assertMsgId('Translatable literal #9i', po_contents)
six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #8') self.assertRegex(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 #9')
self.assertMsgId("Translatable literal #9j", po_contents) self.assertMsgId("Translatable literal #9j", po_contents)
def test_makemessages_find_files(self): def test_makemessages_find_files(self):
@ -392,7 +385,7 @@ class BasicExtractorTests(ExtractorTests):
mocked_popen_wrapper.return_value = ( mocked_popen_wrapper.return_value = (
"any other return value\n", '', 0) "any other return value\n", '', 0)
cmd = MakeMessagesCommand() 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 cmd.gettext_version
def test_po_file_encoding_when_updating(self): def test_po_file_encoding_when_updating(self):

View File

@ -215,17 +215,17 @@ class TranslationTests(SimpleTestCase):
self.assertEqual(complex_nonlazy % {'num': 4, 'name': 'Jim'}, 'Hallo Jim, 4 guten Resultate') 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': 1}, 'Hallo Jim, 1 gutes Resultat')
self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 5}, 'Hallo Jim, 5 guten Resultate') 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'} complex_deferred % {'name': 'Jim'}
self.assertEqual(complex_str_nonlazy % {'num': 4, 'name': 'Jim'}, str('Hallo Jim, 4 guten Resultate')) 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': 1}, str('Hallo Jim, 1 gutes Resultat'))
self.assertEqual(complex_str_deferred % {'name': 'Jim', 'num': 5}, str('Hallo Jim, 5 guten Resultate')) 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'} complex_str_deferred % {'name': 'Jim'}
self.assertEqual(complex_context_nonlazy % {'num': 4, 'name': 'Jim'}, 'Willkommen Jim, 4 guten Resultate') 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': 1}, 'Willkommen Jim, 1 gutes Resultat')
self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 5}, 'Willkommen Jim, 5 guten Resultate') 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'} complex_context_deferred % {'name': 'Jim'}
@skipUnless(six.PY2, "PY3 doesn't have distinct int and long types") @skipUnless(six.PY2, "PY3 doesn't have distinct int and long types")
@ -1630,7 +1630,8 @@ class TestLanguageInfo(SimpleTestCase):
self.assertIs(li['bidi'], False) self.assertIs(li['bidi'], False)
def test_unknown_language_code(self): 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'): with translation.override('xx'):
# A language with no translation catalogs should fallback to the # A language with no translation catalogs should fallback to the
# untranslated string. # untranslated string.
@ -1644,7 +1645,8 @@ class TestLanguageInfo(SimpleTestCase):
self.assertIs(li['bidi'], False) self.assertIs(li['bidi'], False)
def test_unknown_language_code_and_country_code(self): 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): def test_fallback_language_code(self):
""" """

View File

@ -527,4 +527,4 @@ class LogFormattersTests(SimpleTestCase):
with patch_django_server_logger() as logger_output: with patch_django_server_logger() as logger_output:
logger.info(log_msg) 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)

View File

@ -2,7 +2,6 @@ from __future__ import unicode_literals
from django.core.exceptions import FieldError from django.core.exceptions import FieldError
from django.test import TestCase from django.test import TestCase
from django.utils import six
from .models import ( from .models import (
Entry, Line, Post, RegressionModelSplit, SelfRefer, SelfReferChild, Entry, Line, Post, RegressionModelSplit, SelfRefer, SelfReferChild,
@ -37,10 +36,9 @@ class M2MRegressionTests(TestCase):
def test_internal_related_name_not_in_error_msg(self): def test_internal_related_name_not_in_error_msg(self):
# The secret internal related names for self-referential many-to-many # The secret internal related names for self-referential many-to-many
# fields shouldn't appear in the list when an error is made. # fields shouldn't appear in the list when an error is made.
self.assertRaisesMessage(
six.assertRaisesRegex( FieldError,
self, FieldError, "Choices are: id, name, references, related, selfreferchild, selfreferchildsibling",
"Choices are: id, name, references, related, selfreferchild, selfreferchildsibling$",
lambda: SelfRefer.objects.filter(porcupine='fred') lambda: SelfRefer.objects.filter(porcupine='fred')
) )

View File

@ -5,7 +5,6 @@ from django.core.exceptions import FieldError, MultipleObjectsReturned
from django.db import models, transaction from django.db import models, transaction
from django.db.utils import IntegrityError from django.db.utils import IntegrityError
from django.test import TestCase, ignore_warnings from django.test import TestCase, ignore_warnings
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.translation import ugettext_lazy from django.utils.translation import ugettext_lazy
@ -73,8 +72,7 @@ class ManyToOneTests(TestCase):
# Adding an object of the wrong type raises TypeError. # Adding an object of the wrong type raises TypeError.
with transaction.atomic(): with transaction.atomic():
with six.assertRaisesRegex(self, TypeError, with self.assertRaisesMessage(TypeError, "'Article' instance expected, got <Reporter:"):
"'Article' instance expected, got <Reporter.*"):
self.r.article_set.add(self.r2) self.r.article_set.add(self.r2)
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.r.article_set.all(), self.r.article_set.all(),
@ -440,7 +438,7 @@ class ManyToOneTests(TestCase):
reporter = Reporter.objects.create(first_name='John', last_name='Smith', email='john.smith@example.com') reporter = Reporter.objects.create(first_name='John', last_name='Smith', email='john.smith@example.com')
lazy = ugettext_lazy('test') lazy = ugettext_lazy('test')
reporter.article_set.create(headline=lazy, pub_date=datetime.date(2011, 6, 10)) reporter.article_set.create(headline=lazy, pub_date=datetime.date(2011, 6, 10))
notlazy = six.text_type(lazy) notlazy = str(lazy)
article = reporter.article_set.get() article = reporter.article_set.get()
self.assertEqual(article.headline, notlazy) self.assertEqual(article.headline, notlazy)

View File

@ -465,7 +465,7 @@ class WriterTests(SimpleTestCase):
self.assertEqual(string, "migrations.test_writer.EmailValidator(message='hello')") self.assertEqual(string, "migrations.test_writer.EmailValidator(message='hello')")
validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello") validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello")
with six.assertRaisesRegex(self, ImportError, "No module named '?custom'?"): with self.assertRaisesRegex(ImportError, "No module named '?custom'?"):
MigrationWriter.serialize(validator) MigrationWriter.serialize(validator)
validator = deconstructible(path="django.core.validators.EmailValidator2")(EmailValidator)(message="hello") validator = deconstructible(path="django.core.validators.EmailValidator2")(EmailValidator)(message="hello")

View File

@ -15,7 +15,6 @@ from django.core.checks import Error
from django.forms.models import BaseModelFormSet from django.forms.models import BaseModelFormSet
from django.forms.widgets import Select from django.forms.widgets import Select
from django.test import SimpleTestCase, TestCase from django.test import SimpleTestCase, TestCase
from django.utils import six
from .models import ( from .models import (
Band, Concert, ValidationTestInlineModel, ValidationTestModel, Band, Concert, ValidationTestInlineModel, ValidationTestModel,
@ -645,7 +644,7 @@ class CheckTestCase(SimpleTestCase):
self.assertEqual(error.hint, hint) self.assertEqual(error.hint, hint)
self.assertEqual(error.obj, invalid_obj) self.assertEqual(error.obj, invalid_obj)
self.assertEqual(error.id, id) self.assertEqual(error.id, id)
six.assertRegex(self, error.msg, msg) self.assertRegex(error.msg, msg)
def assertIsValid(self, model_admin, model): def assertIsValid(self, model_admin, model):
admin_obj = model_admin(model, AdminSite()) admin_obj = model_admin(model, AdminSite())

View File

@ -342,7 +342,7 @@ class TemplateTagLoadingTests(SimpleTestCase):
"trying to load 'template_tests.broken_tag': cannot import name " "trying to load 'template_tests.broken_tag': cannot import name "
"'?Xtemplate'?" "'?Xtemplate'?"
) )
with six.assertRaisesRegex(self, InvalidTemplateLibrary, msg): with self.assertRaisesRegex(InvalidTemplateLibrary, msg):
Engine(libraries={ Engine(libraries={
'broken_tag': 'template_tests.broken_tag', 'broken_tag': 'template_tests.broken_tag',
}) })
@ -355,7 +355,7 @@ class TemplateTagLoadingTests(SimpleTestCase):
"import name '?Xtemplate'?" "import name '?Xtemplate'?"
) )
with extend_sys_path(egg_name): with extend_sys_path(egg_name):
with six.assertRaisesRegex(self, InvalidTemplateLibrary, msg): with self.assertRaisesRegex(InvalidTemplateLibrary, msg):
Engine(libraries={ Engine(libraries={
'broken_egg': 'tagsegg.templatetags.broken_egg', 'broken_egg': 'tagsegg.templatetags.broken_egg',
}) })

View File

@ -3,17 +3,15 @@ Testing some internals of the template processing. These are *not* examples to b
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from unittest import TestCase
from django.template import Library, TemplateSyntaxError from django.template import Library, TemplateSyntaxError
from django.template.base import ( from django.template.base import (
TOKEN_BLOCK, FilterExpression, Parser, Token, Variable, TOKEN_BLOCK, FilterExpression, Parser, Token, Variable,
) )
from django.template.defaultfilters import register as filter_library from django.template.defaultfilters import register as filter_library
from django.utils import six from django.test import SimpleTestCase
class ParserTests(TestCase): class ParserTests(SimpleTestCase):
def test_token_smart_split(self): def test_token_smart_split(self):
""" """
@ -72,7 +70,7 @@ class ParserTests(TestCase):
Variable("article._hidden") Variable("article._hidden")
# Variables should raise on non string type # Variables should raise on non string type
with six.assertRaisesRegex(self, TypeError, "Variable must be a string or number, got <(class|type) 'dict'>"): with self.assertRaisesRegex(TypeError, "Variable must be a string or number, got <(class|type) 'dict'>"):
Variable({}) Variable({})
def test_filter_args_count(self): def test_filter_args_count(self):

View File

@ -368,16 +368,15 @@ class AssertTemplateUsedContextManagerTests(SimpleTestCase):
pass pass
def test_error_message(self): 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'): with self.assertTemplateUsed('template_used/base.html'):
pass 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'): with self.assertTemplateUsed(template_name='template_used/base.html'):
pass pass
with six.assertRaisesRegex( with self.assertRaisesRegex(AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
self, AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
with self.assertTemplateUsed('template_used/base.html'): with self.assertTemplateUsed('template_used/base.html'):
render_to_string('template_used/alternative.html') render_to_string('template_used/alternative.html')

View File

@ -679,7 +679,7 @@ class SerializationTests(SimpleTestCase):
def assert_yaml_contains_datetime(self, yaml, dt): def assert_yaml_contains_datetime(self, yaml, dt):
# Depending on the yaml dumper, '!timestamp' might be absent # 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): def test_naive_datetime(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30) dt = datetime.datetime(2011, 9, 1, 13, 20, 30)

View File

@ -1005,7 +1005,7 @@ class ViewLoadingTests(SimpleTestCase):
def test_exceptions(self): def test_exceptions(self):
# A missing view (identified by an AttributeError) should raise # A missing view (identified by an AttributeError) should raise
# ViewDoesNotExist, ... # 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') get_callable('urlpatterns_reverse.views.i_should_not_exist')
# ... but if the AttributeError is caused by something else don't # ... but if the AttributeError is caused by something else don't
# swallow it. # swallow it.

View File

@ -7,7 +7,6 @@ from zipimport import zipimporter
from django.test import SimpleTestCase, TestCase, modify_settings from django.test import SimpleTestCase, TestCase, modify_settings
from django.test.utils import extend_sys_path from django.test.utils import extend_sys_path
from django.utils import six
from django.utils._os import upath from django.utils._os import upath
from django.utils.module_loading import ( from django.utils.module_loading import (
autodiscover_modules, import_string, module_has_submodule, autodiscover_modules, import_string, module_has_submodule,
@ -147,11 +146,11 @@ class AutodiscoverModulesTestCase(SimpleTestCase):
autodiscover_modules('missing_module') autodiscover_modules('missing_module')
def test_autodiscover_modules_found_but_bad_module(self): 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') autodiscover_modules('bad_module')
def test_autodiscover_modules_several_one_bad_module(self): 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') autodiscover_modules('good_module', 'bad_module')
def test_autodiscover_modules_several_found(self): def test_autodiscover_modules_several_found(self):

View File

@ -1,17 +1,15 @@
from unittest import TestCase
from django import get_version 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): def test_development(self):
ver_tuple = (1, 4, 0, 'alpha', 0) ver_tuple = (1, 4, 0, 'alpha', 0)
# This will return a different result when it's run within or outside # This will return a different result when it's run within or outside
# of a git clone: 1.4.devYYYYMMDDHHMMSS or 1.4. # of a git clone: 1.4.devYYYYMMDDHHMMSS or 1.4.
ver_string = get_version(ver_tuple) 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): def test_releases(self):
tuples_to_strings = ( tuples_to_strings = (