1

I wrote a python module. Running python filename.py, only checks for syntax errors. Is there a tool, which checks for runtime errors also, like concatenating int with string etc..

Thank you
Bala

Update: Scripts are mainly about setting up a hadoop cluster in the cloud. I am not sure how I can write a unit test, because everything runs in the cloud. You can think of code as legacy code, and I just added more logging and some extra conditions a few places

3 Answers 3

2

Traditionally, if not writing full-fledged unit-tests and/or doc-tests (writing lots of tests is of course best practice!), one at least puts in every module a def main(): function to exercise it and ends the module with

if __name__ == '__main__':
  main()

so main() won't get in the way if the module's just imported, but it will execute if you run the module as your main script. Of course, you need to actually exercise the code in the module from within main(), for this to catch all kinds of semantic problems such as the type error you mention -- doing a really thorough job this way is often as hard as writing real unit tests and doc tests would be, but you can at least get started!

Sign up to request clarification or add additional context in comments.

4 Comments

I think main should call test() because I have seen people do this: import xyz; xyz.test()
Or rather: if __name__ == '__main__': test()
I prefer to uniformly use the name main for the main function that gets executed when a module's invoked as the main script, whatever its purpose (old-fashioned testing or otherwise), but I've never seen this specific issue addressed in a style guide.
GAE app caching also depends on it being called main. Another reason to stick to convention
2

You could write a unit test for your module. That way it will execute your code and any runtime errors (or even better, test failures) will be reported.

If you choose to go down this route, http://docs.python.org/library/unittest.html would probably be a good place to start. Alternatively, as Alex wrote, you can just put code at the bottom of your module that will execute when the module is run directly. This is more expedient and probably a better first approach, although if you have a lot of modules you may want a more structured approach.

1 Comment

Scripts are mainly about setting up a hadoop cluster in the cloud. I am not sure how I can write a unit test, because everything runs in the cloud. You can think of code as legacy code, and I just added more logging and some extra conditions a few places.
0

You can give a try to pyanalyze. It is able to detect possible run-time errors without running the program.

pip3 install pyanalyze
python3 -m pyanalyze file.py

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.