Python unittest passing arguments

后端 未结 6 1045
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  感情败类
    2020-11-28 23:52

    Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:

    • which of the dozen identical USB cards should I use for this test now?
    • which server should I use for this test now?
    • which XXX should I use?

    For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.

    Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)

    import os
    import unittest
    
    
    class MyTest(unittest.TestCase):
        def setUp(self):
            self.var1 = os.environ["VAR1"]
            self.var2 = os.environ["VAR2"]
    
        def test_01(self):
            print("var1: {}, var2: {}".format(self.var1, self.var2))
    

    Then from the command line (tested on Linux)

    $ export VAR1=1
    $ export VAR2=2
    $ python -m unittest MyTest
    var1: 1, var2: 2
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    OK
    

提交回复
热议问题