471,854 Members | 1,980 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,854 software developers and data experts.

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.TestSuite()
suite.addTest(myCase)
unittest.TextTestRunner(verbosity=2).run(suite)
D:\MyWorks>MyCase.py
Traceback (most recent call last):
File "D:\MyWorks\MyCase.py", line 14, in ?
myCase = MyCase(msg)
File "D:\MyWorks\MyCase.py", line 5, in __init__
super(MyCase, self).__init__()
File "C:\Python24\lib\unittest.py", line 208, in __init__
raise ValueError, "no such test method in %s: %s" % \
ValueError: no such test method in <class '__main__.MyCase'>: runTest

Apr 16 '06 #1
2 3746
Podi wrote:
Newbie question about unittest. I am having trouble passing a variable
to a test class object.

MyCase class will potentially have many test functions.


By default a unittest.TestCase 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(unittest.TestCase):
def __init__(self, testname, value):
super(MyTestCase, self).__init__(testname)
self.value = value
def test1(self):
pass
def test2(self):
pass

if __name__ == "__main__":
value = 42

suite = unittest.TestSuite()
suite.addTest(MyTestCase("test1", value))
suite.addTest(MyTestCase("test2", value))

unittest.TextTestRunner(verbosity=2).run(suite)

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

Peter

Apr 17 '06 #2
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

Apr 20 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Doug Jordan | last post: by
12 posts views Thread by Bryan Parkoff | last post: by
5 posts views Thread by James | last post: by
NeoPa
reply views Thread by NeoPa | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.