1
# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
2
# See LICENSE for details.
5
import StringIO, sys, types
7
from twisted.trial import unittest, runner
8
from twisted.scripts import trial
9
from twisted.python import util
10
from twisted.python.compat import set
12
from twisted.trial.test.test_loader import testNames
14
pyunit = __import__('unittest')
17
def sibpath(filename):
18
"""For finding files in twisted/trial/test"""
19
return util.sibpath(__file__, filename)
23
class ForceGarbageCollection(unittest.TestCase):
25
Tests for the --force-gc option.
29
self.config = trial.Options()
31
self.patch(gc, 'collect', self.collect)
32
test = pyunit.FunctionTestCase(self.simpleTest)
33
self.test = runner.TestSuite([test, test])
38
A simple test method that records that it was run.
40
self.log.append('test')
45
A replacement for gc.collect that logs calls to itself.
47
self.log.append('collect')
52
Return a L{runner.TrialRunner} object that is safe to use in tests.
54
runner = trial._makeRunner(self.config)
55
runner.stream = StringIO.StringIO()
59
def test_forceGc(self):
61
Passing the --force-gc option to the trial script forces the garbage
62
collector to run before and after each test.
64
self.config['force-gc'] = True
65
self.config.postOptions()
66
runner = self.makeRunner()
68
self.assertEqual(self.log, ['collect', 'test', 'collect',
69
'collect', 'test', 'collect'])
72
def test_unforceGc(self):
74
By default, no garbage collection is forced.
76
self.config.postOptions()
77
runner = self.makeRunner()
79
self.assertEqual(self.log, ['test', 'test'])
83
class TestSuiteUsed(unittest.TestCase):
85
Check the category of tests suite used by the loader.
90
Create a trial configuration object.
92
self.config = trial.Options()
95
def test_defaultSuite(self):
97
By default, the loader should use L{runner.DestructiveTestSuite}
99
loader = trial._getLoader(self.config)
100
self.assertEquals(loader.suiteFactory, runner.DestructiveTestSuite)
103
def test_untilFailureSuite(self):
105
The C{until-failure} configuration uses the L{runner.TestSuite} to keep
106
instances alive across runs.
108
self.config['until-failure'] = True
109
loader = trial._getLoader(self.config)
110
self.assertEquals(loader.suiteFactory, runner.TestSuite)
114
class TestModuleTest(unittest.TestCase):
116
self.config = trial.Options()
121
def test_testNames(self):
123
Check that the testNames helper method accurately collects the
124
names of tests in suite.
126
self.assertEqual(testNames(self), [self.id()])
128
def assertSuitesEqual(self, test1, names):
129
loader = runner.TestLoader()
130
names1 = testNames(test1)
131
names2 = testNames(runner.TestSuite(map(loader.loadByName, names)))
134
self.assertEqual(names1, names2)
136
def test_baseState(self):
137
self.failUnlessEqual(0, len(self.config['tests']))
139
def test_testmoduleOnModule(self):
141
Check that --testmodule loads a suite which contains the tests
142
referred to in test-case-name inside its parameter.
144
self.config.opt_testmodule(sibpath('moduletest.py'))
145
self.assertSuitesEqual(trial._getSuite(self.config),
146
['twisted.trial.test.test_test_visitor'])
148
def test_testmoduleTwice(self):
150
When the same module is specified with two --testmodule flags, it
151
should only appear once in the suite.
153
self.config.opt_testmodule(sibpath('moduletest.py'))
154
self.config.opt_testmodule(sibpath('moduletest.py'))
155
self.assertSuitesEqual(trial._getSuite(self.config),
156
['twisted.trial.test.test_test_visitor'])
158
def test_testmoduleOnSourceAndTarget(self):
160
If --testmodule is specified twice, once for module A and once for
161
a module which refers to module A, then make sure module A is only
164
self.config.opt_testmodule(sibpath('moduletest.py'))
165
self.config.opt_testmodule(sibpath('test_test_visitor.py'))
166
self.assertSuitesEqual(trial._getSuite(self.config),
167
['twisted.trial.test.test_test_visitor'])
169
def test_testmoduleOnSelfModule(self):
171
When given a module that refers to *itself* in the test-case-name
172
variable, check that --testmodule only adds the tests once.
174
self.config.opt_testmodule(sibpath('moduleself.py'))
175
self.assertSuitesEqual(trial._getSuite(self.config),
176
['twisted.trial.test.moduleself'])
178
def test_testmoduleOnScript(self):
180
Check that --testmodule loads tests referred to in test-case-name
183
self.config.opt_testmodule(sibpath('scripttest.py'))
184
self.assertSuitesEqual(trial._getSuite(self.config),
185
['twisted.trial.test.test_test_visitor',
186
'twisted.trial.test.test_class'])
188
def test_testmoduleOnNonexistentFile(self):
190
Check that --testmodule displays a meaningful error message when
191
passed a non-existent filename.
193
buffy = StringIO.StringIO()
194
stderr, sys.stderr = sys.stderr, buffy
195
filename = 'test_thisbetternoteverexist.py'
197
self.config.opt_testmodule(filename)
198
self.failUnlessEqual(0, len(self.config['tests']))
199
self.failUnlessEqual("File %r doesn't exist\n" % (filename,),
204
def test_testmoduleOnEmptyVars(self):
206
Check that --testmodule adds no tests to the suite for modules
207
which lack test-case-name buffer variables.
209
self.config.opt_testmodule(sibpath('novars.py'))
210
self.failUnlessEqual(0, len(self.config['tests']))
212
def test_testmoduleOnModuleName(self):
214
Check that --testmodule does *not* support module names as arguments
215
and that it displays a meaningful error message.
217
buffy = StringIO.StringIO()
218
stderr, sys.stderr = sys.stderr, buffy
219
moduleName = 'twisted.trial.test.test_script'
221
self.config.opt_testmodule(moduleName)
222
self.failUnlessEqual(0, len(self.config['tests']))
223
self.failUnlessEqual("File %r doesn't exist\n" % (moduleName,),
228
def test_parseLocalVariable(self):
229
declaration = '-*- test-case-name: twisted.trial.test.test_tests -*-'
230
localVars = trial._parseLocalVariables(declaration)
231
self.failUnlessEqual({'test-case-name':
232
'twisted.trial.test.test_tests'},
235
def test_trailingSemicolon(self):
236
declaration = '-*- test-case-name: twisted.trial.test.test_tests; -*-'
237
localVars = trial._parseLocalVariables(declaration)
238
self.failUnlessEqual({'test-case-name':
239
'twisted.trial.test.test_tests'},
242
def test_parseLocalVariables(self):
243
declaration = ('-*- test-case-name: twisted.trial.test.test_tests; '
245
localVars = trial._parseLocalVariables(declaration)
246
self.failUnlessEqual({'test-case-name':
247
'twisted.trial.test.test_tests',
251
def test_surroundingGuff(self):
252
declaration = ('## -*- test-case-name: '
253
'twisted.trial.test.test_tests -*- #')
254
localVars = trial._parseLocalVariables(declaration)
255
self.failUnlessEqual({'test-case-name':
256
'twisted.trial.test.test_tests'},
259
def test_invalidLine(self):
260
self.failUnlessRaises(ValueError, trial._parseLocalVariables,
263
def test_invalidDeclaration(self):
264
self.failUnlessRaises(ValueError, trial._parseLocalVariables,
266
self.failUnlessRaises(ValueError, trial._parseLocalVariables,
267
'-*- foo: bar; qux -*-')
268
self.failUnlessRaises(ValueError, trial._parseLocalVariables,
269
'-*- foo: bar: baz; qux: qax -*-')
271
def test_variablesFromFile(self):
272
localVars = trial.loadLocalVariables(sibpath('moduletest.py'))
273
self.failUnlessEqual({'test-case-name':
274
'twisted.trial.test.test_test_visitor'},
277
def test_noVariablesInFile(self):
278
localVars = trial.loadLocalVariables(sibpath('novars.py'))
279
self.failUnlessEqual({}, localVars)
281
def test_variablesFromScript(self):
282
localVars = trial.loadLocalVariables(sibpath('scripttest.py'))
283
self.failUnlessEqual(
284
{'test-case-name': ('twisted.trial.test.test_test_visitor,'
285
'twisted.trial.test.test_class')},
288
def test_getTestModules(self):
289
modules = trial.getTestModules(sibpath('moduletest.py'))
290
self.failUnlessEqual(modules, ['twisted.trial.test.test_test_visitor'])
292
def test_getTestModules_noVars(self):
293
modules = trial.getTestModules(sibpath('novars.py'))
294
self.failUnlessEqual(len(modules), 0)
296
def test_getTestModules_multiple(self):
297
modules = trial.getTestModules(sibpath('scripttest.py'))
298
self.failUnlessEqual(set(modules),
299
set(['twisted.trial.test.test_test_visitor',
300
'twisted.trial.test.test_class']))
302
def test_looksLikeTestModule(self):
303
for filename in ['test_script.py', 'twisted/trial/test/test_script.py']:
304
self.failUnless(trial.isTestFile(filename),
305
"%r should be a test file" % (filename,))
306
for filename in ['twisted/trial/test/moduletest.py',
307
sibpath('scripttest.py'), sibpath('test_foo.bat')]:
308
self.failIf(trial.isTestFile(filename),
309
"%r should *not* be a test file" % (filename,))
312
class WithoutModuleTests(unittest.TestCase):
314
Test the C{without-module} flag.
319
Create a L{trial.Options} object to be used in the tests, and save
322
self.config = trial.Options()
323
self.savedModules = dict(sys.modules)
328
Restore C{sys.modules}.
330
for module in ('imaplib', 'smtplib'):
331
if module in self.savedModules:
332
sys.modules[module] = self.savedModules[module]
334
sys.modules.pop(module, None)
337
def _checkSMTP(self):
339
Try to import the C{smtplib} module, and return it.
345
def _checkIMAP(self):
347
Try to import the C{imaplib} module, and return it.
353
def test_disableOneModule(self):
355
Check that after disabling a module, it can't be imported anymore.
357
self.config.parseOptions(["--without-module", "smtplib"])
358
self.assertRaises(ImportError, self._checkSMTP)
359
# Restore sys.modules
360
del sys.modules["smtplib"]
361
# Then the function should succeed
362
self.assertIsInstance(self._checkSMTP(), types.ModuleType)
365
def test_disableMultipleModules(self):
367
Check that several modules can be disabled at once.
369
self.config.parseOptions(["--without-module", "smtplib,imaplib"])
370
self.assertRaises(ImportError, self._checkSMTP)
371
self.assertRaises(ImportError, self._checkIMAP)
372
# Restore sys.modules
373
del sys.modules["smtplib"]
374
del sys.modules["imaplib"]
375
# Then the functions should succeed
376
self.assertIsInstance(self._checkSMTP(), types.ModuleType)
377
self.assertIsInstance(self._checkIMAP(), types.ModuleType)
380
def test_disableAlreadyImportedModule(self):
382
Disabling an already imported module should produce a warning.
384
self.assertIsInstance(self._checkSMTP(), types.ModuleType)
385
self.assertWarns(RuntimeWarning,
386
"Module 'smtplib' already imported, disabling anyway.",
388
self.config.parseOptions, ["--without-module", "smtplib"])
389
self.assertRaises(ImportError, self._checkSMTP)