I’m a noob in python.
I’m kind of confused about how the python unit test are supposed to be built and run for the actual applications, i.e. if I have a program that starts from a main method I should be able to start unit tests for this program via the same entry point?
So I’m trying to create a program one of the parameters for which should tell the program to run unit tests instead of normal execution (see below) but also being able to accept all parameters that unittest.main() can accept. I would appreciate any advice about better approach of separating the actual program execution and unit tests in pythonic way or any help with the example below if the approach I’m taking is correct:
class MyClass
def write_to_file(self, file):
open(file, 'w').write("Hello world!")
class MyClassTest (unittest.TestCase)
self.mc = MyClass()
self.test_file = os.path.join(os.path.curdir, "a_file.txt")
def setUp(self):
pass
def test_write_to_file(self):
try:
write_to_file(self.test_file)
except IOError:
self.fail("Error!")
if __name__== "__main__":
parser = argparse.ArgumentParser(description="Some desc")
group = parser.add_mutually_exclusive_group()
group.add_argument("-w", "--write", help=': write hello world to given file')
group.add-argument("-t", "--test", help=': run unit tests, use "all" to run all tests')
args = parser.parse_args(sys.argv[1:])
mcl = MyClass()
if args.write:
mcl.write_to_file(args.write)
# below is the questionnable part
if args.test:
#removing -t or --test argument because otherwise unittest.main() will complain
del sys.argv[1:]
if args.test == "all":
unittest.main()
else:
# Adding the argument that was specified after the -t into the sys.argv to be picked up by the unittest.main() - doesn't work correctly (1)
sys.argv.append(args.test)
unittest.main()
(1) If I’m specifying executing MyClass with -t MyTestCase option i expect it to be able to run in accordance with the help message unittest.main() but it says there is an AttributeError: ‘module’ object has no attribute MyTestCase
Thanks!
I would put the class (the “unit” under test) in a file by itself, and the “main” program and unit tests in two more files. The latter would be executable scripts; the first would simply be imported by them.