assertLogs(logger, level=.
Understanding the Concept
assertLogs(logger, level=...) captures Python logging records during a test and fails when no matching record appears. It is appropriate for testing emitted diagnostics without printing to the console.
How this fits into a real test suite
A reliable test starts with a specific expected behavior. Keep the fixture small, arrange the input, call the real code, and assert a result the reader can verify. Add one boundary or failure case so the test does not pass only for a convenient example. In a larger project, run the same test automatically after each change.
Tests are repeatable experiments. Use temporary resources and injected dependencies where possible; when the environment is part of the requirement, add a separate integration test rather than weakening the unit test.
Worked Example
Read the code from the first line to the last. Identify which values are inputs, which operation is being demonstrated and what should happen before running it.
import logging
import unittest
class LoggingTests(unittest.TestCase):
def test_warning(self):
with self.assertLogs('sample.app', level='WARNING') as captured_logs:
logging.getLogger('sample.app').warning('retry requested')
self.assertIn('retry requested', captured_logs.output[0])
test_result = unittest.TestResult()
LoggingTests('test_warning').run(test_result)
print(test_result.wasSuccessful())
Walkthrough: What Each Part Does
- The central operation is self.assertLogs('sample.app', level='WARNING'). Read its actual arguments: those values determine what is tested, logged, measured or scheduled. Then locate the line that inspects its result or handles a failure.
- The imports make logging, unittest available. These are standard-library building blocks unless the example explicitly names an external tool.
- The definition LoggingTests creates reusable behavior. Its body runs when called, awaited or instantiated; defining it alone does not run the body of an ordinary function.
- The with or async with scope controls lifetime. Setup takes place on entry, and cleanup runs on exit even when an exception interrupts the body.
- The coordination call waits for a result or a completion condition. Predict what would happen if the worker failed or never became ready.
This demonstration focuses on one practical behavior. Before changing several lines, vary one input or one configuration choice and check whether the result changes for the reason you expected.
Example Output
True
The output above was captured by running the example in the available Python environment. The order of concurrent events, durations and platform-dependent values can legitimately differ on your computer.
Important Behavior and Edge Cases
Assuming assertLogs captures print() output or that messages from unrelated loggers always match.
Pay particular attention to the documented return values, errors and resource-lifetime rules. A convenient result under normal inputs does not guarantee correct behavior under cancellation, missing data or environmental failure.
Practice Exercise
Emit one warning through a named logger and assert that it was captured.
Write down the result you expect before running your changed code. Check at least one normal case and one boundary or failure case. If your example starts workers or opens resources, verify how they are cleaned up.
Further reading: official documentation and API reference.
Common Beginner Mistakes
- Assuming assertLogs captures print() output or that messages from unrelated loggers always match.
- Writing assertions that check implementation details but fail to validate the behavior that matters to the caller.
Key Takeaways
- assertLogs(logger, level=.
- assertLogs(logger, level=...) captures Python logging records during a test and fails when no matching record appears. It is appropriate for testing emitted diagnostics without printing to the console.
- Practice: Emit one warning through a named logger and assert that it was captured.