Fixed #32227 -- Prevented crash when setUpTestData() errors with --debug-sql.

Thanks Mariusz Felisiak for the report.
This commit is contained in:
Adam Johnson 2020-11-26 10:07:18 +00:00 committed by Mariusz Felisiak
parent 7603036bd0
commit b9fd09d21b
2 changed files with 35 additions and 2 deletions

View File

@ -38,6 +38,7 @@ class DebugSQLTextTestResult(unittest.TextTestResult):
def __init__(self, stream, descriptions, verbosity): def __init__(self, stream, descriptions, verbosity):
self.logger = logging.getLogger('django.db.backends') self.logger = logging.getLogger('django.db.backends')
self.logger.setLevel(logging.DEBUG) self.logger.setLevel(logging.DEBUG)
self.debug_sql_stream = None
super().__init__(stream, descriptions, verbosity) super().__init__(stream, descriptions, verbosity)
def startTest(self, test): def startTest(self, test):
@ -56,8 +57,13 @@ class DebugSQLTextTestResult(unittest.TextTestResult):
def addError(self, test, err): def addError(self, test, err):
super().addError(test, err) super().addError(test, err)
self.debug_sql_stream.seek(0) if self.debug_sql_stream is None:
self.errors[-1] = self.errors[-1] + (self.debug_sql_stream.read(),) # Error before tests e.g. in setUpTestData().
sql = ''
else:
self.debug_sql_stream.seek(0)
sql = self.debug_sql_stream.read()
self.errors[-1] = self.errors[-1] + (sql,)
def addFailure(self, test, err): def addFailure(self, test, err):
super().addFailure(test, err) super().addFailure(test, err)

View File

@ -25,6 +25,14 @@ class TestDebugSQL(unittest.TestCase):
Person.objects.filter(first_name='error').count() Person.objects.filter(first_name='error').count()
raise Exception raise Exception
class ErrorSetUpTestDataTest(TestCase):
@classmethod
def setUpTestData(cls):
raise Exception
def runTest(self):
pass
class PassingSubTest(TestCase): class PassingSubTest(TestCase):
def runTest(self): def runTest(self):
with self.subTest(): with self.subTest():
@ -107,3 +115,22 @@ class TestDebugSQL(unittest.TestCase):
'''FROM "test_runner_person" WHERE ''' '''FROM "test_runner_person" WHERE '''
'''"test_runner_person"."first_name" = 'subtest-pass';'''), '''"test_runner_person"."first_name" = 'subtest-pass';'''),
] ]
def test_setupclass_exception(self):
runner = DiscoverRunner(debug_sql=True, verbosity=0)
suite = runner.test_suite()
suite.addTest(self.ErrorSetUpTestDataTest())
old_config = runner.setup_databases()
stream = StringIO()
runner.test_runner(
verbosity=0,
stream=stream,
resultclass=runner.get_resultclass(),
).run(suite)
runner.teardown_databases(old_config)
output = stream.getvalue()
self.assertIn(
'ERROR: setUpClass '
'(test_runner.test_debug_sql.TestDebugSQL.ErrorSetUpTestDataTest)',
output,
)