views:

55

answers:

2

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....

+3  A: 

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

Matthew Manela
Dave Kirby
+2  A: 

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.iditit = True

class Test(..):
    def test_spawning(self):
        t = TestableVimSpawner()
        t.other_logic()
        self.failUnless(t.iditit)
Ivo van der Wijk