How to pass variable to test class

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Podi

    #1

    How to pass variable to test class

    Hi,

    Newbie question about unittest. I am having trouble passing a variable
    to a test class object.

    MyCase class will potentially have many test functions.

    Any help would be much appreciated.

    Thanks,
    P

    # File MyCase.py
    import unittest

    class MyCase(unittest .TestCase):
    def __init__(self, value):
    super(MyCase, self).__init__( )
    self.value = value
    def test1(self):
    print self.value
    def test2(self):
    print 'world'

    if __name__ == '__main__':
    msg = 'Hello'
    myCase = MyCase(msg)
    suite = unittest.TestSu ite()
    suite.addTest(m yCase)
    unittest.TextTe stRunner(verbos ity=2).run(suit e)


    D:\MyWorks>MyCa se.py
    Traceback (most recent call last):
    File "D:\MyWorks\MyC ase.py", line 14, in ?
    myCase = MyCase(msg)
    File "D:\MyWorks\MyC ase.py", line 5, in __init__
    super(MyCase, self).__init__( )
    File "C:\Python24\li b\unittest.py", line 208, in __init__
    raise ValueError, "no such test method in %s: %s" % \
    ValueError: no such test method in <class '__main__.MyCas e'>: runTest

  • Peter Otten

    #2
    Re: How to pass variable to test class

    Podi wrote:
    [color=blue]
    > Newbie question about unittest. I am having trouble passing a variable
    > to a test class object.
    >
    > MyCase class will potentially have many test functions.[/color]

    By default a unittest.TestCa se has only one test function called "runTest".
    Therefore you have to add multiple instances of your TestCase subclass to
    the suite and to pass the test function's name to the initializer
    explicitly:

    import unittest

    class MyTestCase(unit test.TestCase):
    def __init__(self, testname, value):
    super(MyTestCas e, self).__init__( testname)
    self.value = value
    def test1(self):
    pass
    def test2(self):
    pass

    if __name__ == "__main__":
    value = 42

    suite = unittest.TestSu ite()
    suite.addTest(M yTestCase("test 1", value))
    suite.addTest(M yTestCase("test 2", value))

    unittest.TextTe stRunner(verbos ity=2).run(suit e)

    However, the standard place for common setup is in the setUp() method.

    Peter

    Comment

    • Podi

      #3
      Re: How to pass variable to test class

      Thanks for replying.

      I need to pass some external values to the test cases because I want to
      run the same tests in different environments such as lab/instrument
      setup.

      Regards,
      Podi

      Comment

      Working...