如何在python测试中传递命令行参数

时间:2019-02-22 09:25:14

标签: python oop testing decorator python-decorators

我有一个微服务类MsActionDetector。因为ms是在.sh脚本内(无论是在本地还是在容器内)启动的,所以需要从命令行中获取参数。

class MsActionDetector(BaseMicroservice):

    def __init__(self):
        self.config = safe_load(open(sys.argv[1]))
        ....

我想执行集成测试,从而在测试中实例化微服务,但这不起作用,因为该类除命令行参数外。我该如何实现? python Decorator是解决方案吗?我应该修改构造函数吗?

1 个答案:

答案 0 :(得分:0)

sys.argv是一个没有魔法的列表。它是从命令行初始化的,但是您可以随意更改它。因此,在实例化MsActionDetector之前,很容易将其设置为测试类中所需的值:

sys.argv = ['cmd', 'path/to/file']
msad = MsActionDetector()     # will open path/to/file
...