Navigation

Some functionality one might want to test makes use of external programs such
as a pager or a text editor. The tl.testing.script module provides
utilities that install simple mock scripts in places where the code to be
tested will find them. They take a string of Python code and create a wrapper
script that sets the Python path to match that of the test and runs the code.

If the script’s base name is known, it makes sense to put its directory to the
front of the system’s binary path, for instance in order for the script to be
found instead of a program with a well-known name. We remember the current
value of the PATH variable for use in the clean-up demonstrations:

Finally, install can be told to store the file path of the installed
script in the environment of the process since it is a common pattern for
applications to determine which external programs to run by examining a
environment variable such as PAGER or EDITOR. This works both if the
variable already existed, and if it is not yet used:

In addition to the Python source code passed to install, the generated
script will contain a few lines in the beginning that make it use the same
Python interpreter and module search path as the tests themselves. We
demonstrate this by preparing a script that compares its executable and Python
path with our own and imports and accesses a module that is not part of the
standard library. (We let it access tl.testing.script as we’re sure we
have can import it ourselves.)

The tl.testing.script module defines a function teardown_scripts that
cleans up after previous install calls. When a script is installed, files
and directories to be cleaned up later are stored in a module-global list:

teardown_scripts may take one argument that will be ignored so the
function can be used as a test suite’s tearDown callback. As we
demonstrate this, we’ll see that teardown_scripts may also be called if no
scripts were installed previously: