The class unittest.TestCase provides two special methods, setUp and tearDown, which run before and after every call to a test method. This is needed when testing generators, which are exhausted after every test. We demonstrate this by testing a program that checks the line in a file in which a given string occurs for the first time:
class StringNotFoundException(Exception): pass def find_string(file, string): for i,lines in enumerate(file.readlines()): if string in lines: return i raise StringNotFoundException(
f'String {string} not found in File {file.name}.')
We assume that this code is saved in a file named find_in_file.py.
A test has to prepare a file and open it and remove it after the test as given in the following example:
import unittest import os # used for, for example, deleting files from find_in_file import find_string, StringNotFoundException...