assertWarns & assertLogs
assertWarns verifies that a warning is issued during test execution,
while assertLogs verifies that specific log messages are produced.
Both are context managers for clean usage.
assertWarns
import unittest
import warnings
class TestWarnings(unittest.TestCase):
def test_deprecated_function(self):
with self.assertWarns(DeprecationWarning):
deprecated_function()
def test_user_warning(self):
with self.assertWarns(UserWarning):
warnings.warn("This feature is experimental")
def test_warning_message(self):
with self.assertWarns(UserWarning) as warned:
risky_operation()
self.assertEqual(len(warned.warnings), 1)
self.assertIn("risky", str(warned.warnings[0].message))
assertLogs
class TestLogging(unittest.TestCase):
def test_error_logged(self):
with self.assertLogs(level='ERROR') as log:
process_request(invalid_data)
self.assertEqual(len(log.output), 1)
self.assertIn("Failed to process", log.output[0])
def test_specific_logger(self):
with self.assertLogs('myapp.auth', level='INFO') as log:
login_user("admin", "password123")
self.assertIn("Login successful", log.output[0])
def test_multiple_log_levels(self):
with self.assertLogs(level='WARNING') as log:
run_migration()
self.assertTrue(len(log.output) > 0)
assertNoLogs
def test_no_error_messages(self):
with self.assertNoLogs(level='ERROR'):
process_valid_request()
Key Takeaway
Use assertWarns to verify deprecation or user warnings, and
assertLogs to verify that your code logs the right messages at the right levels.