pyunit 在其他文件中模拟 sys.argv

Ale*_*lex 1 python unit-testing parameter-passing mockito

我有一个这样写的python文件:

import sys
cfgfile = sys.argv[1]
cfg = ConfigObj(cfgfile)
db_dbname=cfg.get("DB_NAME")
class UserMappingsLoader:
    def __init__(self):
        self.debug = 0
        self.cuStartTime = 0
        self.fiId = 0
Run Code Online (Sandbox Code Playgroud)

我想编写一个 pyunit 来测试此代码中的一种方法。但是当我运行我的测试代码时,它显示:

cfgfile = sys.argv[1]
list index out of range
Run Code Online (Sandbox Code Playgroud)

任何人都知道如何将 sys.argv 从测试文件模拟到这个文件?

jor*_*anm 5

您可以使用patch来自模拟模块的方法执行此操作。下面是一个例子:

from mock import patch

def test_your_function():
    fake_args = [None, "myfakearg"]
    with patch('sys.argv', fake_args):
        import yourmodule
        # rest of your test
Run Code Online (Sandbox Code Playgroud)