MCS 260 Fall 2021
assert statement is simple: It is followed by an expression, usually a boolean expression. If that expression is truthy, nothing happens. If it is falsy, the AssertionError exception is raised.
One use for
assert is during debugging of a program under development: It stops execution if expected conditions are not met.
is mostly equivalent to
So a good use for
if not fact(0)==1: raise AssertionError()
In software development, testing refers to the process of checking that a program does what it is supposed to do, i.e. that it meets the desired specifications.
Most often this takes the form of code that performs testing in an automated way.
Some software development approaches rely very heavily on testing.
Make some scripts that test your modules and programs.
dynam.py might tested by a script
In this approach, finding, running, and interpreting results of tests is all manual.
Many options for orchestrating tests.
Pytest is not typically included with Python. You need to install it before you can use it. This command should do that:
python3 -m pip install pytest
Then test to make sure it's working with
python3 -m pytest
Put tests in files named
Put each test in a function named
Each test should return normally if it succeeds, or raise an exception if it fails.
In a terminal, the command
python3 -m pytest
will find all tests (in current dir), run them, and report.
Let's make tests for the module
Make tests that encode essential functions of the program, with most of them testing a single part (function, class, etc.) in isolation. These are unit tests.
Every time you make a change to the program, run the tests again.
Most pytest test functions accept no arguments. But if you write one with an argument called
tmpdir, pytest will create a temporary directory before the test runs, and delete it when the test ends.
tmpdir argument will be an object that contains data about the created directory. Calling
str(tmpdir) will give the full path as a string.
This feature is very helpful when a test involves writing and reading files.