I am trying to write a parser in Python for a special text file format. To get an idea how to structure the code I looked into the source code of the JSON parser which is part of the Python standard library (Python/Lib/json
).
In this json directory there is a tests
directory which holds a number of unit tests. I replaced the json tests with my tests but now I do not know how to call them.
Looking into the directory there is a __init__.py
file making it a module and inside of this file there is the following code snippet for running the tests:
here = os.path.dirname(__file__)
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith("test") and fn.endswith(".py"):
modname = "json.tests." + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (json, json.encoder, json.decoder):
suite.addTest(doctest.DocTestSuite(mod))
suite.addTest(TestPyTest('test_pyjson'))
suite.addTest(TestCTest('test_cjson'))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
main()
My problem is now how are these unit tests executed? I am confused because the if __name__ == '__main__':
if clause validates to true if this file is called directly and not being imported as a module. However as it is in the __init__.py
file of the module it should be executed right after import.
Should an import tests
in the python console start all the unit tests?