python中的unittest:忽略我想要测试的代码的导入

时间:2010-06-15 13:38:43

标签: python unit-testing

我有一个导入pythoncom的python程序(并使用pythoncom.CoCreateInstance)。我想为程序逻辑创建一个单元测试而不导入pythoncom(所以我也可以在Linux上运行测试)。

有哪些选择?我可以不修改被测系统吗?

到目前为止我发现了:

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

我的问题是,如果我有:

from pythoncom.something import something

我会得到:

ImportError: No module named something.something

sys.modules["something.something"]sys.modules["pythoncom.something.something"]不起作用。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

如果您需要运行测试并且它们实际上是依赖于操作系统的,您可能希望使用这些装饰器,例如:

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

通过这种方式,您可以声明测试仅在Linux上运行,而不会在测试本身中增加难看的复杂性。

答案 1 :(得分:0)

您可以将import pythoncom放入try except块。

答案 2 :(得分:0)

好的,如果在测试中修改PYTHONPATH,并在名为pythoncom的测试目录中的文件系统上创建一个包含必要子目录的新包,该怎么办?