Testing, Debugging, and Logging
Check a small function, investigate a failure, and report useful events.
python, unittest, testing, debugging, loggingMake a claim checkable
A test chooses an input, runs a piece of code, and checks an expected result. Good examples include ordinary inputs, boundaries, and expected failures. Tests help find problems; a passing test does not prove every possible case.
Python illustration
Save this as test_total.py and run python -m unittest test_total in a
local environment:
import unittest
def total(values):
return sum(values)
class TotalTests(unittest.TestCase):
def test_empty_and_values(self):
self.assertEqual(total([]), 0)
self.assertEqual(total([2, 4, 3]), 9)
if __name__ == "__main__":
unittest.main()
The prepared checks compare 0 with 0 and 9 with 9. A successful
test run reports one passing test; exact timing and formatting can vary.
This site displays the example and does not run it.
See the reasoning
Follow the example one step at a time
Follow the two assertions in the prepared unittest example. This is a prepared teaching demonstration, not live code execution.
Run the empty case
total([]) → 0 expected: 0
The function sums an empty list and returns zero.
Investigate and report
When a test fails, read the traceback and reproduce the smallest failing
case. breakpoint() can pause a local Python program in the configured
debugger; inspect local values and step through the relevant code. Remove
or disable temporary breakpoints before sharing a finished program.
For durable diagnostics, use logging.getLogger(__name__) and appropriate
levels such as info, warning, and error. Logging is configured by the
application, and messages may not appear unless its configuration permits
the level. Include useful context without secrets or sensitive personal data.
Logging an error is not a substitute for handling or propagating it correctly.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("Processed %d items", 3)
In a fresh program with this configuration, the informational message
includes Processed 3 items; the exact prefix depends on logging
configuration. Avoid logging sensitive inputs.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
