Python unittest passing arguments

后端 未结 6 1060
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 23:16

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(unittes         


        
6条回答
  •  萌比男神i
    2020-11-28 23:45

    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 : {}'.format(self.USERNAME))
            print('password : {}'.format(self.PASSWORD))
    
    
    if __name__ == "__main__":
        if len(sys.argv) > 1:
            MyTest.USERNAME = sys.argv.pop()
            MyTest.PASSWORD = sys.argv.pop()
        unittest.main()
    

    that will let you run with:

    python mytests.py ausername apassword
    

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

    [update] 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 : {}'.format(self.USERNAME))
            print('password : {}'.format(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()
    

    That will let you run with:

    TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py
    

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

提交回复
热议问题