本文介绍了Python unittest 传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,如何将参数从命令行传递给 unittest 函数?

In Python, how would I pass an argument from the command line to a unittest function?

这是目前的代码……我知道这是错误的.

Here is the code so far… I know it's wrong.

class TestingClass(unittest.TestCase):

    def testEmails(self):
        assertEqual(email_from_argument, "[email protected]")


if __name__ == "__main__":
    unittest.main(argv=[sys.argv[1]])
    email_from_argument = sys.argv[1]

推荐答案

所以这里的医生说你说那疼吗?那你别这样!"可能是对的.但是,如果您真的想要,这里有一种将参数传递给单元测试测试的方法:

So the doctors here that are saying "You say that hurts? Then don't do that!" are probably right. But if you really want to, here's one way of passing arguments to a unittest test:

import sys
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username:', self.USERNAME)
        print('password:', self.PASSWORD)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        MyTest.USERNAME = sys.argv.pop()
        MyTest.PASSWORD = sys.argv.pop()
    unittest.main()

这会让你运行:

python mytests.py myusername mypassword

您需要 argv.pops,所以您的命令行参数不会与 unittest 自己的参数混淆...

You need the argv.pops, so your command line parameters don't mess with unittest's own...

您可能想要研究的另一件事是使用环境变量:

The other thing you might want to look into is using environment variables:

import os
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username:', self.USERNAME)
        print('password:', self.PASSWORD)

if __name__ == "__main__":
    MyTest.USERNAME = os.environ.get('TEST_USERNAME', MyTest.USERNAME)
    MyTest.PASSWORD = os.environ.get('TEST_PASSWORD', MyTest.PASSWORD)
    unittest.main()

这会让你运行:

TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py

它的优点是您不会弄乱 unittest 自己的参数解析.缺点是它不会像在 Windows 上那样工作......

And it has the advantage that you're not messing with unittest's own argument parsing. The downside is it won't work quite like that on Windows...

这篇关于Python unittest 传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 23:10