Home | History | Annotate | Download | only in test
      1 from cStringIO import StringIO
      2 
      3 import os
      4 import sys
      5 import unittest
      6 
      7 
      8 class Test_TestProgram(unittest.TestCase):
      9 
     10     def test_discovery_from_dotted_path(self):
     11         loader = unittest.TestLoader()
     12 
     13         tests = [self]
     14         expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__))
     15 
     16         self.wasRun = False
     17         def _find_tests(start_dir, pattern):
     18             self.wasRun = True
     19             self.assertEqual(start_dir, expectedPath)
     20             return tests
     21         loader._find_tests = _find_tests
     22         suite = loader.discover('unittest.test')
     23         self.assertTrue(self.wasRun)
     24         self.assertEqual(suite._tests, tests)
     25 
     26     # Horrible white box test
     27     def testNoExit(self):
     28         result = object()
     29         test = object()
     30 
     31         class FakeRunner(object):
     32             def run(self, test):
     33                 self.test = test
     34                 return result
     35 
     36         runner = FakeRunner()
     37 
     38         oldParseArgs = unittest.TestProgram.parseArgs
     39         def restoreParseArgs():
     40             unittest.TestProgram.parseArgs = oldParseArgs
     41         unittest.TestProgram.parseArgs = lambda *args: None
     42         self.addCleanup(restoreParseArgs)
     43 
     44         def removeTest():
     45             del unittest.TestProgram.test
     46         unittest.TestProgram.test = test
     47         self.addCleanup(removeTest)
     48 
     49         program = unittest.TestProgram(testRunner=runner, exit=False, verbosity=2)
     50 
     51         self.assertEqual(program.result, result)
     52         self.assertEqual(runner.test, test)
     53         self.assertEqual(program.verbosity, 2)
     54 
     55     class FooBar(unittest.TestCase):
     56         def testPass(self):
     57             assert True
     58         def testFail(self):
     59             assert False
     60 
     61     class FooBarLoader(unittest.TestLoader):
     62         """Test loader that returns a suite containing FooBar."""
     63         def loadTestsFromModule(self, module):
     64             return self.suiteClass(
     65                 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
     66 
     67 
     68     def test_NonExit(self):
     69         program = unittest.main(exit=False,
     70                                 argv=["foobar"],
     71                                 testRunner=unittest.TextTestRunner(stream=StringIO()),
     72                                 testLoader=self.FooBarLoader())
     73         self.assertTrue(hasattr(program, 'result'))
     74 
     75 
     76     def test_Exit(self):
     77         self.assertRaises(
     78             SystemExit,
     79             unittest.main,
     80             argv=["foobar"],
     81             testRunner=unittest.TextTestRunner(stream=StringIO()),
     82             exit=True,
     83             testLoader=self.FooBarLoader())
     84 
     85 
     86     def test_ExitAsDefault(self):
     87         self.assertRaises(
     88             SystemExit,
     89             unittest.main,
     90             argv=["foobar"],
     91             testRunner=unittest.TextTestRunner(stream=StringIO()),
     92             testLoader=self.FooBarLoader())
     93 
     94 
     95 class InitialisableProgram(unittest.TestProgram):
     96     exit = False
     97     result = None
     98     verbosity = 1
     99     defaultTest = None
    100     testRunner = None
    101     testLoader = unittest.defaultTestLoader
    102     progName = 'test'
    103     test = 'test'
    104     def __init__(self, *args):
    105         pass
    106 
    107 RESULT = object()
    108 
    109 class FakeRunner(object):
    110     initArgs = None
    111     test = None
    112     raiseError = False
    113 
    114     def __init__(self, **kwargs):
    115         FakeRunner.initArgs = kwargs
    116         if FakeRunner.raiseError:
    117             FakeRunner.raiseError = False
    118             raise TypeError
    119 
    120     def run(self, test):
    121         FakeRunner.test = test
    122         return RESULT
    123 
    124 class TestCommandLineArgs(unittest.TestCase):
    125 
    126     def setUp(self):
    127         self.program = InitialisableProgram()
    128         self.program.createTests = lambda: None
    129         FakeRunner.initArgs = None
    130         FakeRunner.test = None
    131         FakeRunner.raiseError = False
    132 
    133     def testHelpAndUnknown(self):
    134         program = self.program
    135         def usageExit(msg=None):
    136             program.msg = msg
    137             program.exit = True
    138         program.usageExit = usageExit
    139 
    140         for opt in '-h', '-H', '--help':
    141             program.exit = False
    142             program.parseArgs([None, opt])
    143             self.assertTrue(program.exit)
    144             self.assertIsNone(program.msg)
    145 
    146         program.parseArgs([None, '-$'])
    147         self.assertTrue(program.exit)
    148         self.assertIsNotNone(program.msg)
    149 
    150     def testVerbosity(self):
    151         program = self.program
    152 
    153         for opt in '-q', '--quiet':
    154             program.verbosity = 1
    155             program.parseArgs([None, opt])
    156             self.assertEqual(program.verbosity, 0)
    157 
    158         for opt in '-v', '--verbose':
    159             program.verbosity = 1
    160             program.parseArgs([None, opt])
    161             self.assertEqual(program.verbosity, 2)
    162 
    163     def testBufferCatchFailfast(self):
    164         program = self.program
    165         for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'),
    166                       ('catch', 'catchbreak')):
    167             if attr == 'catch' and not hasInstallHandler:
    168                 continue
    169 
    170             short_opt = '-%s' % arg[0]
    171             long_opt = '--%s' % arg
    172             for opt in short_opt, long_opt:
    173                 setattr(program, attr, None)
    174 
    175                 program.parseArgs([None, opt])
    176                 self.assertTrue(getattr(program, attr))
    177 
    178             for opt in short_opt, long_opt:
    179                 not_none = object()
    180                 setattr(program, attr, not_none)
    181 
    182                 program.parseArgs([None, opt])
    183                 self.assertEqual(getattr(program, attr), not_none)
    184 
    185     def testRunTestsRunnerClass(self):
    186         program = self.program
    187 
    188         program.testRunner = FakeRunner
    189         program.verbosity = 'verbosity'
    190         program.failfast = 'failfast'
    191         program.buffer = 'buffer'
    192 
    193         program.runTests()
    194 
    195         self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity',
    196                                                 'failfast': 'failfast',
    197                                                 'buffer': 'buffer'})
    198         self.assertEqual(FakeRunner.test, 'test')
    199         self.assertIs(program.result, RESULT)
    200 
    201     def testRunTestsRunnerInstance(self):
    202         program = self.program
    203 
    204         program.testRunner = FakeRunner()
    205         FakeRunner.initArgs = None
    206 
    207         program.runTests()
    208 
    209         # A new FakeRunner should not have been instantiated
    210         self.assertIsNone(FakeRunner.initArgs)
    211 
    212         self.assertEqual(FakeRunner.test, 'test')
    213         self.assertIs(program.result, RESULT)
    214 
    215     def testRunTestsOldRunnerClass(self):
    216         program = self.program
    217 
    218         FakeRunner.raiseError = True
    219         program.testRunner = FakeRunner
    220         program.verbosity = 'verbosity'
    221         program.failfast = 'failfast'
    222         program.buffer = 'buffer'
    223         program.test = 'test'
    224 
    225         program.runTests()
    226 
    227         # If initializing raises a type error it should be retried
    228         # without the new keyword arguments
    229         self.assertEqual(FakeRunner.initArgs, {})
    230         self.assertEqual(FakeRunner.test, 'test')
    231         self.assertIs(program.result, RESULT)
    232 
    233     def testCatchBreakInstallsHandler(self):
    234         module = sys.modules['unittest.main']
    235         original = module.installHandler
    236         def restore():
    237             module.installHandler = original
    238         self.addCleanup(restore)
    239 
    240         self.installed = False
    241         def fakeInstallHandler():
    242             self.installed = True
    243         module.installHandler = fakeInstallHandler
    244 
    245         program = self.program
    246         program.catchbreak = True
    247 
    248         program.testRunner = FakeRunner
    249 
    250         program.runTests()
    251         self.assertTrue(self.installed)
    252 
    253 
    254 if __name__ == '__main__':
    255     unittest.main()
    256