Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing a python function which invokes a vim subprocess

I've written a function which opens a vim editor with the given filename when called.. How can I do the unittest of these types of operations....

like image 822
pkumar Avatar asked Oct 01 '10 03:10

pkumar


2 Answers

To unit test something like this you must mock/stub out your dependencies. In this case lets say you are launching vim by calling os.system("vim").

In your unit test you can stub out that function call doing something like:

def launchVim():
    os.system("vim")

def testThatVimIsLaunched():
    try:
        realSystem = os.system
        called = []
        def stubSystem(command):
            if command == "vim":
                called.append(True)
        os.system = stubSystem

        launchVim() # function under test

        assert(called == [True])
    finally:
        os.system = realSystem

For more details on mocking and stubbing take a look at this article

Update: I added the try/finally to restore the original system function as suggested by Dave Kirby

like image 142
Matthew Manela Avatar answered Oct 22 '22 06:10

Matthew Manela


This is no longer unittesting but integration testing. Why do you need to launch vim? Usually, you would 'mock' this, simulate the process spawning and depend on the fact that python's subprocess module is well tested.

To accomplish this in your code, you can, for example, subclass the class that implements your functionality and override the method that's responsible for spawning. Then test this subclass. I.e.

class VimSpawner(object): # your actual code, to be tested
    ...
    def spawn(self):
        ... do subprocess magic

    def other_logic(self):
        ...
        self.spawn()

class TestableVimSpawner(VimSpawner):
    def spawn(self):
        ... mock the spawning
        self.ididit = True

class Test(..):
    def test_spawning(self):
        t = TestableVimSpawner()
        t.other_logic()
        self.failUnless(t.ididit)
like image 41
Ivo van der Wijk Avatar answered Oct 22 '22 04:10

Ivo van der Wijk