问题
Problem
Yes I know you shouldn't send arguments to a unittest but in this case I have to so that it can access a piece of hardware within the current framework. For reasons for which the detail is irrelevant, I can't use a simple board = myBoard.getBoard()
method within the tests, otherwise I wouldn't be here asking you all.
Horrible Attempt 1
class Test(object):
@staticmethod
def __call__(board):
_board = board
global _board
logging.info('Entering a Unit Test')
suite = unittest.TestLoader()
suite = suite.loadTestsFromTestCase(TestCase)
unittest.TextTestRunner().run(suite)
This method will be called upon to perform a unittest at somepoint. This is the way things are set out in the current framework, I'm just following the rules.
You can see here I assign a global variable (horrible). This can then be accessed by the test methods easily:
class TestCase(unittest.TestCase):
def runTest(self):
logging.critical('running')
def setUp(self):
logging.critical('setup')
def test_Me(self):
logging.critical('me')
The result is it won't enter runTest
but it will setUp
before each test_
method. Pretty much what I'd like, I can deal with it not entering runTest
Horrible Attempt 2
I'd like to do the above but without global variables so I tried this method:
class Test(object):
@staticmethod
def __call__(board):
logging.info('Entering a basic Unit Test')
suite = unittest.TestSuite() #creates a suite for testing
suite.addTest(BasicCase(board))
unittest.TextTestRunner().run(suite)
class BasicCase(unittest.TestCase):
def __init__(self, board):
self.board = board
logging.critical('init')
super(BasicCase, self).__init__()
def runTest(self):
logging.critical('runtest')
def setUp(self):
logging.critical('reset')
infra.Reset.__call__(self.board) #allows me to pass the board in a much nicer way
def test_Connect(self):
logging.critical('connection')
Problem with the above is that it will obviously only do init
, setUp
and runTest
but it'll miss any test_
methods.
If I add:
suite.addTest(BasicCase(board).test_Connect)
Then it unnecessarily calls init
twice and I have to add an extra member variable to test_Connect
to accept the test
object. I can deal with this too as I can return a list of the test_
methods but it just seems like a pain to do. Also I don't think it runs setUp
every time it enters a new test_
method. Not ideal.
So ...
So is there some other method I can use that allows me to quickly run everything like a unittest but allows me to pass the board
object?
If I should be using a different python module, then please say but I'm using unittest
due to the lovely outputs and assert
methods I get.
来源:https://stackoverflow.com/questions/30706863/how-to-send-arguments-to-a-unittest-without-global-variables