开发者

unittest in python: ignore an import from the code I want to test

I have a python program that imports pythoncom (and uses pythoncom.CoCreateInstance from it). I want to create a unittest for the program logic without it importing pythoncom (so I can run the test on Linux as well).

What options are there? Can I do it without modifying the system under test?

What I found so far:

sys.modules["pythoncom"] = "test"
import module_that_imports_pythoncom

My problem with it is if I have:

f开发者_JAVA技巧rom pythoncom.something import something

I'll get:

ImportError: No module named something.something

And sys.modules["something.something"] or sys.modules["pythoncom.something.something"] doesn't work.

Any ideas?


If you need to run tests and they actually are OS-dependent, you might want to use these decorators for example:

def run_only(func, predicate):
    if predicate():
        return func
    else:
        def f(*args, **kwargs): pass
        return f


def run_only_for_linux(func):
    pred = lambda: sys.platform == 'linux2'
    return run_only(func, pred)


@run_only_for_linux
def hello_linux():
    """docstring"""
    print("hello linux")

In this way you declare that the test only runs on linux without adding ugly complexity in the test itself.


You could put import pythoncom into a try except block.


Ok, what if you modify PYTHONPATH in the tests, and make a new package on the filesystem in a testing directory called pythoncom with the necessary subdirectories?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜