开发者

unit testing a python function which invokes a vim subprocess

开发者 https://www.devze.com 2023-01-18 03:05 出处:网络
I\'ve writte开发者_如何转开发n a function which opens a vim editor with the given filename when called.. How can I do the unittest of these types of operations....To unit test something like this you

I've writte开发者_如何转开发n a function which opens a vim editor with the given filename when called.. How can I do the unittest of these types of operations....


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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消