Say you want to have a test suite that tests logic which runs command-line processes that should *not* be run on the test machine (e.g. they would cause the test machine's configuration to be totally messed up). You want to test right down to the point where the call is made (i.e. you don't way to say "if testing, don't actually call"), and you would like to test the subprocess.* or os.* calls you're using to call the process. What do you use?
I haven't found a good mechanism yet (I'm still hopeful about that), so I hacked up something as a starting point for discussion. The module provides a simple API for creating stub scripts for given executables and a way to inject them into the PATH on test-suite entry and remove them on test-suite exit. You can provide return-code, stdout and stderr for the called executable to get a generic call-once-and-retrieve value executable, (or you can provide a script to run).import mockproc def setUp( self ): self.processes = mockproc.MockProc() self.processes.append( 'ls', stdout = '''total 20 drwxr-xr-x 2 mcfletch mcfletch 4096 2010-06-05 09:58 . drwxr-xr-x 12 mcfletch mcfletch 4096 2010-06-05 09:58 .. -rw-r--r-- 1 mcfletch mcfletch 3 2010-06-05 09:58 supercali.txt''', stderr='success' ) self.processes.enter() def tearDown( self ): self.processes.exit()
Calls to subprocess.Popen( 'ls' ) within the test-suite will now return the stubbed/mocked value rather than the real command ls. The overriding allows for "pushing" new overrides onto the stack (replacing the on-disk script) so that a single test which needs different values can append a new override and then remove() it to restore the original stub.
You can get the source-code via:
bzr branch lp:mockproc
Mostly I'm wondering if someone else has already published something more robust/featureful so I can kill this little project :) .
Pingbacks are closed.