Python 2.6: proper usage of unittest.TestSuite

后端 未结 3 1912
刺人心
刺人心 2020-12-21 08:12

Using Python 2.6, I have a very simple test in a python file in a directory:

#mytest.py
import unittest

class BasicTests(unittest.TestCase):
    def test_ok         


        
相关标签:
3条回答
  • 2020-12-21 08:31

    Update: it looks like what I have above is in fact, correct. When I installed a copy of Python 2.7, everything worked fine. I dug through the unittest.py source code and found that this line of code was not working the way one would expect:

        elif isinstance(obj, TestSuite):
            return obj
        elif hasattr(obj, '__call__'):
            test = obj()
    

    The first elif condition is failing, and thus it falls down into the one after where the exception is raised. I'm still not sure how that could even remotely happen — maybe a bad compilation — but I've gone ahead and filed a bug with the provider.

    0 讨论(0)
  • 2020-12-21 08:49

    You might want to try:

    mytest.py:

    import unittest
    
    class BasicTests(unittest.TestCase):
        def test_ok(self):
            self.assertTrue(True)
    
    if __name__ == '__main__':
        unittest.sys.argv.insert(1,'--verbose')
        unittest.main(argv = unittest.sys.argv)    
    

    Then,

    % python mytest.py
    

    runs all tests in all subclasses of TestCase, and

    % python mytest.py BasicTests.test_ok
    

    runs just test_ok. This second form of the command is useful when you know there is a problem with one test and don't wish to run through every test.

    0 讨论(0)
  • 2020-12-21 08:56

    I don't usually work with unittest on the command line, but have my own test running scripts.

    You need to add a function suite to the module

    def suite():
        return unittest.TestLoader().loadTestsFromTestCase(BasicTests)
    

    and then call it like python -m unittest mytest.suite. But then I run into the following problem:

    TypeError: calling <function suite at 0x00C1FB70> returned <unittest.TestSuite tests=[<mysite.BasicTests testMethod=test_ok>]>, not a test
    

    which happens because unittest uses something like isinstance(mytest.suite(), TestSuite) but through executing with -m, you get two different versions of the TestSuite class (one is __main__.TestSuite, the other is unittest.TestSuite), so isinstance returns false.
    To me, this looks like a bug. Patching unittest.py by inserting from unittest import TestSuite, TestCase at the beginning of loadTestsFromName solves the isinstance problem. Sorry I can't give you the "correct" solution (if there is one).

    0 讨论(0)
提交回复
热议问题