Wednesday, 15 August 2012

Python unit testing code which calls OS/Module level python functions -



Python unit testing code which calls OS/Module level python functions -

i have python module/script few of these

at various nested levels within script take command line inputs, validate them, apply sensible defaults i check if few directories exist

the above 2 examples. trying find out best "strategy" test this. have done have constructed wrapper functions around raw_input , os.path.exists in module , in test override these 2 functions take input array list or mocked behaviour. approach has next disadvantages

wrapper functions exist sake of testing , pollutes code i have remember utilize wrapper function in code everytime , not phone call os.path.exists or raw_input

any brilliant suggestions?

the short reply monkey patch these scheme calls.

there examples in reply how display redirected stdin in python?

here simple illustration raw_input() using lambda throws away prompt , returns want.

system under test $ cat ./name_getter.py #!/usr/bin/env python class namegetter(object): def get_name(self): self.name = raw_input('what name? ') def greet(self): print 'hello, ', self.name, '!' def run(self): self.get_name() self.greet() if __name__ == '__main__': ng = namegetter() ng.run() $ echo derek | ./name_getter.py name? hello, derek ! test case: $ cat ./t_name_getter.py #!/usr/bin/env python import unittest import name_getter class testnamegetter(unittest.testcase): def test_get_alice(self): name_getter.raw_input = lambda _: 'alice' ng = name_getter.namegetter() ng.get_name() self.assertequals(ng.name, 'alice') def test_get_bob(self): name_getter.raw_input = lambda _: 'bob' ng = name_getter.namegetter() ng.get_name() self.assertequals(ng.name, 'bob') if __name__ == '__main__': unittest.main() $ ./t_name_getter.py -v test_get_alice (__main__.testnamegetter) ... ok test_get_bob (__main__.testnamegetter) ... ok ---------------------------------------------------------------------- ran 2 tests in 0.000s ok

python unit-testing python-2.7 pyunit

No comments:

Post a Comment