如何在pytest中处理sys.argv?

sre*_*har 5 python pytest python-3.x

平台linux——Python 3.6.7、pytest-4.4.0、py-1.8.0、pluggy-0.9.0

#example.py
try:
    import configparser
except ImportError:
    import ConfigParser as configparser

CONFIG = configparser.ConfigParser()
CONFIG.read(sys.argv[1])
ININFO = {i:dict(CONFIG.items(i)) for i in CONFIG.sections()}
DATANAME = ININFO['data']['name']

def somefunction(DATANAME):
    """
        This function will take lot of variables from ini file
    """
    print(DATANAME)
    s1 = "Pass"
    s2 = "Fail"
    s3 = "Pass"
    print(s1, s2, s3)
    return [s1, s2, s3]

def test_somefunction():
    """
        Test function
           - Will check whether all steps are passed or not.
    """
    status = somefunction()
    for sts in status:
        assert sts == 'Pass', "Test has Failed!"

if __name__ == "__main__":

    somefunction()

Run Code Online (Sandbox Code Playgroud)

与上面的代码相同,我有很多文件,并且都有内置测试

我的执行方式是

#sudo python3 example.py inifile.ini
Run Code Online (Sandbox Code Playgroud)

请让我知道如何使用 pytest 执行此操作而不更改代码。

如果我替换sys.argv[1]为文件名,则可以正常工作,如下所示

sudo python3 -m pytest -s 
Run Code Online (Sandbox Code Playgroud)

指导我如何处理这个问题。

我添加并检查下面的屏幕截图 错误图像

示例 ini 文件 test.ini

[data]
name = some.name
age = 22

[data1]
name = someother.name
age = 32
Run Code Online (Sandbox Code Playgroud)

小智 1

正如我之前评论的,你只需要创建一个 python 文件来调用 pytest 和参数,从那里 pytest 将被触发。

$ python run.py example.py test.ini
Run Code Online (Sandbox Code Playgroud)

这里,run.py如下

$ cat run.py
# run.py
import pytest
import sys

def main():
    # extract your arg here
    print('Extracted arg is ==> %s' % sys.argv[2])
    pytest.main([sys.argv[1]])

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

example.py是你的 python 脚本。

test.ini是您的ini 文件。

希望这能澄清您的疑问。

所有学分都归于这个答案