[TIP] argv with unitest
Matt Harrison
matthewharrison at gmail.com
Sun Sep 6 09:59:30 PDT 2009
On Sun, Sep 6, 2009 at 6:53 AM, Mag Gam<magawake at gmail.com> wrote:
> I have tried using the
> http://www.artima.com/weblogs/viewpost.jsp?thread=4829 for a reference
> but I am still having problems,
>
> I think I should take couple of steps back....and write some
> pseudocode for a good testing framework template.
>
> Foo.pl -- The purpose is to to count from 1 to 100
>
> Arguments
>
> --help -h
> --stdout -s
> --stderr -e
>
> Should raise an exception if a wrong argument was given and run a
> Usage() function
>
> I would invoke it like this:
>
> python Foo.pl --stdout outfile --stderr errorfile
>
> My tests would be like this:
> If stdout is set, will it create a file of stdout?
>
> If --help or -h is set the Usage() call should be called and return an
> error code 1
>
> If --help and --stdout is set --help should over ride and still return
> an error code 1
>
> How can I incorporate this to a good testing framework?
>
>
I would advocate non calling sys.exit from the main function. Only
call if from here
if __name__ == '__main__':
sys.exit(main(sys.argv))
Then have main return the exit code you want.
As far as testing a doctest would look something like this:
>>> main(['--stdout', 'outfile'])
>>> print open('outfile').read()
0
1
2
....
A unittest would look similar
import unittest
class TestCount(unittest.TestCase):
def test_count(self):
main(['--stdout', 'outfile'])
results = open('outfile').read()
self.assertEqual(results, '0\n1\n2\n....)
if __name__=='__main__':
unittest.main()
I gave a talk about best practices for writing scripts which includes
testing examples. Newer slides are here[0] video is here[1].
good luck,
-matt
0 - http://panela.blog-city.com/oscon_scripting_with_python_handout.htm
1 - http://us.pycon.org/2009/conference/schedule/event/61/
More information about the testing-in-python
mailing list