test_loader.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. import sys
  2. import types
  3. import warnings
  4. import unittest
  5. # Decorator used in the deprecation tests to reset the warning registry for
  6. # test isolation and reproducibility.
  7. def warningregistry(func):
  8. def wrapper(*args, **kws):
  9. missing = []
  10. saved = getattr(warnings, '__warningregistry__', missing).copy()
  11. try:
  12. return func(*args, **kws)
  13. finally:
  14. if saved is missing:
  15. try:
  16. del warnings.__warningregistry__
  17. except AttributeError:
  18. pass
  19. else:
  20. warnings.__warningregistry__ = saved
  21. return wrapper
  22. class Test_TestLoader(unittest.TestCase):
  23. ### Basic object tests
  24. ################################################################
  25. def test___init__(self):
  26. loader = unittest.TestLoader()
  27. self.assertEqual([], loader.errors)
  28. ### Tests for TestLoader.loadTestsFromTestCase
  29. ################################################################
  30. # "Return a suite of all tests cases contained in the TestCase-derived
  31. # class testCaseClass"
  32. def test_loadTestsFromTestCase(self):
  33. class Foo(unittest.TestCase):
  34. def test_1(self): pass
  35. def test_2(self): pass
  36. def foo_bar(self): pass
  37. tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
  38. loader = unittest.TestLoader()
  39. self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
  40. # "Return a suite of all tests cases contained in the TestCase-derived
  41. # class testCaseClass"
  42. #
  43. # Make sure it does the right thing even if no tests were found
  44. def test_loadTestsFromTestCase__no_matches(self):
  45. class Foo(unittest.TestCase):
  46. def foo_bar(self): pass
  47. empty_suite = unittest.TestSuite()
  48. loader = unittest.TestLoader()
  49. self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
  50. # "Return a suite of all tests cases contained in the TestCase-derived
  51. # class testCaseClass"
  52. #
  53. # What happens if loadTestsFromTestCase() is given an object
  54. # that isn't a subclass of TestCase? Specifically, what happens
  55. # if testCaseClass is a subclass of TestSuite?
  56. #
  57. # This is checked for specifically in the code, so we better add a
  58. # test for it.
  59. def test_loadTestsFromTestCase__TestSuite_subclass(self):
  60. class NotATestCase(unittest.TestSuite):
  61. pass
  62. loader = unittest.TestLoader()
  63. try:
  64. loader.loadTestsFromTestCase(NotATestCase)
  65. except TypeError:
  66. pass
  67. else:
  68. self.fail('Should raise TypeError')
  69. # "Return a suite of all tests cases contained in the TestCase-derived
  70. # class testCaseClass"
  71. #
  72. # Make sure loadTestsFromTestCase() picks up the default test method
  73. # name (as specified by TestCase), even though the method name does
  74. # not match the default TestLoader.testMethodPrefix string
  75. def test_loadTestsFromTestCase__default_method_name(self):
  76. class Foo(unittest.TestCase):
  77. def runTest(self):
  78. pass
  79. loader = unittest.TestLoader()
  80. # This has to be false for the test to succeed
  81. self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
  82. suite = loader.loadTestsFromTestCase(Foo)
  83. self.assertIsInstance(suite, loader.suiteClass)
  84. self.assertEqual(list(suite), [Foo('runTest')])
  85. ################################################################
  86. ### /Tests for TestLoader.loadTestsFromTestCase
  87. ### Tests for TestLoader.loadTestsFromModule
  88. ################################################################
  89. # "This method searches `module` for classes derived from TestCase"
  90. def test_loadTestsFromModule__TestCase_subclass(self):
  91. m = types.ModuleType('m')
  92. class MyTestCase(unittest.TestCase):
  93. def test(self):
  94. pass
  95. m.testcase_1 = MyTestCase
  96. loader = unittest.TestLoader()
  97. suite = loader.loadTestsFromModule(m)
  98. self.assertIsInstance(suite, loader.suiteClass)
  99. expected = [loader.suiteClass([MyTestCase('test')])]
  100. self.assertEqual(list(suite), expected)
  101. # "This method searches `module` for classes derived from TestCase"
  102. #
  103. # What happens if no tests are found (no TestCase instances)?
  104. def test_loadTestsFromModule__no_TestCase_instances(self):
  105. m = types.ModuleType('m')
  106. loader = unittest.TestLoader()
  107. suite = loader.loadTestsFromModule(m)
  108. self.assertIsInstance(suite, loader.suiteClass)
  109. self.assertEqual(list(suite), [])
  110. # "This method searches `module` for classes derived from TestCase"
  111. #
  112. # What happens if no tests are found (TestCases instances, but no tests)?
  113. def test_loadTestsFromModule__no_TestCase_tests(self):
  114. m = types.ModuleType('m')
  115. class MyTestCase(unittest.TestCase):
  116. pass
  117. m.testcase_1 = MyTestCase
  118. loader = unittest.TestLoader()
  119. suite = loader.loadTestsFromModule(m)
  120. self.assertIsInstance(suite, loader.suiteClass)
  121. self.assertEqual(list(suite), [loader.suiteClass()])
  122. # "This method searches `module` for classes derived from TestCase"s
  123. #
  124. # What happens if loadTestsFromModule() is given something other
  125. # than a module?
  126. #
  127. # XXX Currently, it succeeds anyway. This flexibility
  128. # should either be documented or loadTestsFromModule() should
  129. # raise a TypeError
  130. #
  131. # XXX Certain people are using this behaviour. We'll add a test for it
  132. def test_loadTestsFromModule__not_a_module(self):
  133. class MyTestCase(unittest.TestCase):
  134. def test(self):
  135. pass
  136. class NotAModule(object):
  137. test_2 = MyTestCase
  138. loader = unittest.TestLoader()
  139. suite = loader.loadTestsFromModule(NotAModule)
  140. reference = [unittest.TestSuite([MyTestCase('test')])]
  141. self.assertEqual(list(suite), reference)
  142. # Check that loadTestsFromModule honors (or not) a module
  143. # with a load_tests function.
  144. @warningregistry
  145. def test_loadTestsFromModule__load_tests(self):
  146. m = types.ModuleType('m')
  147. class MyTestCase(unittest.TestCase):
  148. def test(self):
  149. pass
  150. m.testcase_1 = MyTestCase
  151. load_tests_args = []
  152. def load_tests(loader, tests, pattern):
  153. self.assertIsInstance(tests, unittest.TestSuite)
  154. load_tests_args.extend((loader, tests, pattern))
  155. return tests
  156. m.load_tests = load_tests
  157. loader = unittest.TestLoader()
  158. suite = loader.loadTestsFromModule(m)
  159. self.assertIsInstance(suite, unittest.TestSuite)
  160. self.assertEqual(load_tests_args, [loader, suite, None])
  161. # With Python 3.5, the undocumented and unofficial use_load_tests is
  162. # ignored (and deprecated).
  163. load_tests_args = []
  164. with warnings.catch_warnings(record=False):
  165. warnings.simplefilter('ignore')
  166. suite = loader.loadTestsFromModule(m, use_load_tests=False)
  167. self.assertEqual(load_tests_args, [loader, suite, None])
  168. @warningregistry
  169. def test_loadTestsFromModule__use_load_tests_deprecated_positional(self):
  170. m = types.ModuleType('m')
  171. class MyTestCase(unittest.TestCase):
  172. def test(self):
  173. pass
  174. m.testcase_1 = MyTestCase
  175. load_tests_args = []
  176. def load_tests(loader, tests, pattern):
  177. self.assertIsInstance(tests, unittest.TestSuite)
  178. load_tests_args.extend((loader, tests, pattern))
  179. return tests
  180. m.load_tests = load_tests
  181. # The method still works.
  182. loader = unittest.TestLoader()
  183. # use_load_tests=True as a positional argument.
  184. with warnings.catch_warnings(record=True) as w:
  185. warnings.simplefilter('always')
  186. suite = loader.loadTestsFromModule(m, False)
  187. self.assertIsInstance(suite, unittest.TestSuite)
  188. # load_tests was still called because use_load_tests is deprecated
  189. # and ignored.
  190. self.assertEqual(load_tests_args, [loader, suite, None])
  191. # We got a warning.
  192. self.assertIs(w[-1].category, DeprecationWarning)
  193. self.assertEqual(str(w[-1].message),
  194. 'use_load_tests is deprecated and ignored')
  195. @warningregistry
  196. def test_loadTestsFromModule__use_load_tests_deprecated_keyword(self):
  197. m = types.ModuleType('m')
  198. class MyTestCase(unittest.TestCase):
  199. def test(self):
  200. pass
  201. m.testcase_1 = MyTestCase
  202. load_tests_args = []
  203. def load_tests(loader, tests, pattern):
  204. self.assertIsInstance(tests, unittest.TestSuite)
  205. load_tests_args.extend((loader, tests, pattern))
  206. return tests
  207. m.load_tests = load_tests
  208. # The method still works.
  209. loader = unittest.TestLoader()
  210. with warnings.catch_warnings(record=True) as w:
  211. warnings.simplefilter('always')
  212. suite = loader.loadTestsFromModule(m, use_load_tests=False)
  213. self.assertIsInstance(suite, unittest.TestSuite)
  214. # load_tests was still called because use_load_tests is deprecated
  215. # and ignored.
  216. self.assertEqual(load_tests_args, [loader, suite, None])
  217. # We got a warning.
  218. self.assertIs(w[-1].category, DeprecationWarning)
  219. self.assertEqual(str(w[-1].message),
  220. 'use_load_tests is deprecated and ignored')
  221. @warningregistry
  222. def test_loadTestsFromModule__too_many_positional_args(self):
  223. m = types.ModuleType('m')
  224. class MyTestCase(unittest.TestCase):
  225. def test(self):
  226. pass
  227. m.testcase_1 = MyTestCase
  228. load_tests_args = []
  229. def load_tests(loader, tests, pattern):
  230. self.assertIsInstance(tests, unittest.TestSuite)
  231. load_tests_args.extend((loader, tests, pattern))
  232. return tests
  233. m.load_tests = load_tests
  234. loader = unittest.TestLoader()
  235. with self.assertRaises(TypeError) as cm, \
  236. warnings.catch_warnings(record=True) as w:
  237. warnings.simplefilter('always')
  238. loader.loadTestsFromModule(m, False, 'testme.*')
  239. # We still got the deprecation warning.
  240. self.assertIs(w[-1].category, DeprecationWarning)
  241. self.assertEqual(str(w[-1].message),
  242. 'use_load_tests is deprecated and ignored')
  243. # We also got a TypeError for too many positional arguments.
  244. self.assertEqual(type(cm.exception), TypeError)
  245. self.assertEqual(
  246. str(cm.exception),
  247. 'loadTestsFromModule() takes 1 positional argument but 3 were given')
  248. @warningregistry
  249. def test_loadTestsFromModule__use_load_tests_other_bad_keyword(self):
  250. m = types.ModuleType('m')
  251. class MyTestCase(unittest.TestCase):
  252. def test(self):
  253. pass
  254. m.testcase_1 = MyTestCase
  255. load_tests_args = []
  256. def load_tests(loader, tests, pattern):
  257. self.assertIsInstance(tests, unittest.TestSuite)
  258. load_tests_args.extend((loader, tests, pattern))
  259. return tests
  260. m.load_tests = load_tests
  261. loader = unittest.TestLoader()
  262. with warnings.catch_warnings():
  263. warnings.simplefilter('ignore')
  264. with self.assertRaises(TypeError) as cm:
  265. loader.loadTestsFromModule(
  266. m, use_load_tests=False, very_bad=True, worse=False)
  267. self.assertEqual(type(cm.exception), TypeError)
  268. # The error message names the first bad argument alphabetically,
  269. # however use_load_tests (which sorts first) is ignored.
  270. self.assertEqual(
  271. str(cm.exception),
  272. "loadTestsFromModule() got an unexpected keyword argument 'very_bad'")
  273. def test_loadTestsFromModule__pattern(self):
  274. m = types.ModuleType('m')
  275. class MyTestCase(unittest.TestCase):
  276. def test(self):
  277. pass
  278. m.testcase_1 = MyTestCase
  279. load_tests_args = []
  280. def load_tests(loader, tests, pattern):
  281. self.assertIsInstance(tests, unittest.TestSuite)
  282. load_tests_args.extend((loader, tests, pattern))
  283. return tests
  284. m.load_tests = load_tests
  285. loader = unittest.TestLoader()
  286. suite = loader.loadTestsFromModule(m, pattern='testme.*')
  287. self.assertIsInstance(suite, unittest.TestSuite)
  288. self.assertEqual(load_tests_args, [loader, suite, 'testme.*'])
  289. def test_loadTestsFromModule__faulty_load_tests(self):
  290. m = types.ModuleType('m')
  291. def load_tests(loader, tests, pattern):
  292. raise TypeError('some failure')
  293. m.load_tests = load_tests
  294. loader = unittest.TestLoader()
  295. suite = loader.loadTestsFromModule(m)
  296. self.assertIsInstance(suite, unittest.TestSuite)
  297. self.assertEqual(suite.countTestCases(), 1)
  298. # Errors loading the suite are also captured for introspection.
  299. self.assertNotEqual([], loader.errors)
  300. self.assertEqual(1, len(loader.errors))
  301. error = loader.errors[0]
  302. self.assertTrue(
  303. 'Failed to call load_tests:' in error,
  304. 'missing error string in %r' % error)
  305. test = list(suite)[0]
  306. self.assertRaisesRegex(TypeError, "some failure", test.m)
  307. ################################################################
  308. ### /Tests for TestLoader.loadTestsFromModule()
  309. ### Tests for TestLoader.loadTestsFromName()
  310. ################################################################
  311. # "The specifier name is a ``dotted name'' that may resolve either to
  312. # a module, a test case class, a TestSuite instance, a test method
  313. # within a test case class, or a callable object which returns a
  314. # TestCase or TestSuite instance."
  315. #
  316. # Is ValueError raised in response to an empty name?
  317. def test_loadTestsFromName__empty_name(self):
  318. loader = unittest.TestLoader()
  319. try:
  320. loader.loadTestsFromName('')
  321. except ValueError as e:
  322. self.assertEqual(str(e), "Empty module name")
  323. else:
  324. self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
  325. # "The specifier name is a ``dotted name'' that may resolve either to
  326. # a module, a test case class, a TestSuite instance, a test method
  327. # within a test case class, or a callable object which returns a
  328. # TestCase or TestSuite instance."
  329. #
  330. # What happens when the name contains invalid characters?
  331. def test_loadTestsFromName__malformed_name(self):
  332. loader = unittest.TestLoader()
  333. suite = loader.loadTestsFromName('abc () //')
  334. error, test = self.check_deferred_error(loader, suite)
  335. expected = "Failed to import test module: abc () //"
  336. expected_regex = "Failed to import test module: abc \(\) //"
  337. self.assertIn(
  338. expected, error,
  339. 'missing error string in %r' % error)
  340. self.assertRaisesRegex(
  341. ImportError, expected_regex, getattr(test, 'abc () //'))
  342. # "The specifier name is a ``dotted name'' that may resolve ... to a
  343. # module"
  344. #
  345. # What happens when a module by that name can't be found?
  346. def test_loadTestsFromName__unknown_module_name(self):
  347. loader = unittest.TestLoader()
  348. suite = loader.loadTestsFromName('sdasfasfasdf')
  349. expected = "No module named 'sdasfasfasdf'"
  350. error, test = self.check_deferred_error(loader, suite)
  351. self.assertIn(
  352. expected, error,
  353. 'missing error string in %r' % error)
  354. self.assertRaisesRegex(ImportError, expected, test.sdasfasfasdf)
  355. # "The specifier name is a ``dotted name'' that may resolve either to
  356. # a module, a test case class, a TestSuite instance, a test method
  357. # within a test case class, or a callable object which returns a
  358. # TestCase or TestSuite instance."
  359. #
  360. # What happens when the module is found, but the attribute isn't?
  361. def test_loadTestsFromName__unknown_attr_name_on_module(self):
  362. loader = unittest.TestLoader()
  363. suite = loader.loadTestsFromName('unittest.loader.sdasfasfasdf')
  364. expected = "module 'unittest.loader' has no attribute 'sdasfasfasdf'"
  365. error, test = self.check_deferred_error(loader, suite)
  366. self.assertIn(
  367. expected, error,
  368. 'missing error string in %r' % error)
  369. self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf)
  370. # "The specifier name is a ``dotted name'' that may resolve either to
  371. # a module, a test case class, a TestSuite instance, a test method
  372. # within a test case class, or a callable object which returns a
  373. # TestCase or TestSuite instance."
  374. #
  375. # What happens when the module is found, but the attribute isn't?
  376. def test_loadTestsFromName__unknown_attr_name_on_package(self):
  377. loader = unittest.TestLoader()
  378. suite = loader.loadTestsFromName('unittest.sdasfasfasdf')
  379. expected = "No module named 'unittest.sdasfasfasdf'"
  380. error, test = self.check_deferred_error(loader, suite)
  381. self.assertIn(
  382. expected, error,
  383. 'missing error string in %r' % error)
  384. self.assertRaisesRegex(ImportError, expected, test.sdasfasfasdf)
  385. # "The specifier name is a ``dotted name'' that may resolve either to
  386. # a module, a test case class, a TestSuite instance, a test method
  387. # within a test case class, or a callable object which returns a
  388. # TestCase or TestSuite instance."
  389. #
  390. # What happens when we provide the module, but the attribute can't be
  391. # found?
  392. def test_loadTestsFromName__relative_unknown_name(self):
  393. loader = unittest.TestLoader()
  394. suite = loader.loadTestsFromName('sdasfasfasdf', unittest)
  395. expected = "module 'unittest' has no attribute 'sdasfasfasdf'"
  396. error, test = self.check_deferred_error(loader, suite)
  397. self.assertIn(
  398. expected, error,
  399. 'missing error string in %r' % error)
  400. self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf)
  401. # "The specifier name is a ``dotted name'' that may resolve either to
  402. # a module, a test case class, a TestSuite instance, a test method
  403. # within a test case class, or a callable object which returns a
  404. # TestCase or TestSuite instance."
  405. # ...
  406. # "The method optionally resolves name relative to the given module"
  407. #
  408. # Does loadTestsFromName raise ValueError when passed an empty
  409. # name relative to a provided module?
  410. #
  411. # XXX Should probably raise a ValueError instead of an AttributeError
  412. def test_loadTestsFromName__relative_empty_name(self):
  413. loader = unittest.TestLoader()
  414. suite = loader.loadTestsFromName('', unittest)
  415. error, test = self.check_deferred_error(loader, suite)
  416. expected = "has no attribute ''"
  417. self.assertIn(
  418. expected, error,
  419. 'missing error string in %r' % error)
  420. self.assertRaisesRegex(AttributeError, expected, getattr(test, ''))
  421. # "The specifier name is a ``dotted name'' that may resolve either to
  422. # a module, a test case class, a TestSuite instance, a test method
  423. # within a test case class, or a callable object which returns a
  424. # TestCase or TestSuite instance."
  425. # ...
  426. # "The method optionally resolves name relative to the given module"
  427. #
  428. # What happens when an impossible name is given, relative to the provided
  429. # `module`?
  430. def test_loadTestsFromName__relative_malformed_name(self):
  431. loader = unittest.TestLoader()
  432. # XXX Should this raise AttributeError or ValueError?
  433. suite = loader.loadTestsFromName('abc () //', unittest)
  434. error, test = self.check_deferred_error(loader, suite)
  435. expected = "module 'unittest' has no attribute 'abc () //'"
  436. expected_regex = "module 'unittest' has no attribute 'abc \(\) //'"
  437. self.assertIn(
  438. expected, error,
  439. 'missing error string in %r' % error)
  440. self.assertRaisesRegex(
  441. AttributeError, expected_regex, getattr(test, 'abc () //'))
  442. # "The method optionally resolves name relative to the given module"
  443. #
  444. # Does loadTestsFromName raise TypeError when the `module` argument
  445. # isn't a module object?
  446. #
  447. # XXX Accepts the not-a-module object, ignoring the object's type
  448. # This should raise an exception or the method name should be changed
  449. #
  450. # XXX Some people are relying on this, so keep it for now
  451. def test_loadTestsFromName__relative_not_a_module(self):
  452. class MyTestCase(unittest.TestCase):
  453. def test(self):
  454. pass
  455. class NotAModule(object):
  456. test_2 = MyTestCase
  457. loader = unittest.TestLoader()
  458. suite = loader.loadTestsFromName('test_2', NotAModule)
  459. reference = [MyTestCase('test')]
  460. self.assertEqual(list(suite), reference)
  461. # "The specifier name is a ``dotted name'' that may resolve either to
  462. # a module, a test case class, a TestSuite instance, a test method
  463. # within a test case class, or a callable object which returns a
  464. # TestCase or TestSuite instance."
  465. #
  466. # Does it raise an exception if the name resolves to an invalid
  467. # object?
  468. def test_loadTestsFromName__relative_bad_object(self):
  469. m = types.ModuleType('m')
  470. m.testcase_1 = object()
  471. loader = unittest.TestLoader()
  472. try:
  473. loader.loadTestsFromName('testcase_1', m)
  474. except TypeError:
  475. pass
  476. else:
  477. self.fail("Should have raised TypeError")
  478. # "The specifier name is a ``dotted name'' that may
  479. # resolve either to ... a test case class"
  480. def test_loadTestsFromName__relative_TestCase_subclass(self):
  481. m = types.ModuleType('m')
  482. class MyTestCase(unittest.TestCase):
  483. def test(self):
  484. pass
  485. m.testcase_1 = MyTestCase
  486. loader = unittest.TestLoader()
  487. suite = loader.loadTestsFromName('testcase_1', m)
  488. self.assertIsInstance(suite, loader.suiteClass)
  489. self.assertEqual(list(suite), [MyTestCase('test')])
  490. # "The specifier name is a ``dotted name'' that may resolve either to
  491. # a module, a test case class, a TestSuite instance, a test method
  492. # within a test case class, or a callable object which returns a
  493. # TestCase or TestSuite instance."
  494. def test_loadTestsFromName__relative_TestSuite(self):
  495. m = types.ModuleType('m')
  496. class MyTestCase(unittest.TestCase):
  497. def test(self):
  498. pass
  499. m.testsuite = unittest.TestSuite([MyTestCase('test')])
  500. loader = unittest.TestLoader()
  501. suite = loader.loadTestsFromName('testsuite', m)
  502. self.assertIsInstance(suite, loader.suiteClass)
  503. self.assertEqual(list(suite), [MyTestCase('test')])
  504. # "The specifier name is a ``dotted name'' that may resolve ... to
  505. # ... a test method within a test case class"
  506. def test_loadTestsFromName__relative_testmethod(self):
  507. m = types.ModuleType('m')
  508. class MyTestCase(unittest.TestCase):
  509. def test(self):
  510. pass
  511. m.testcase_1 = MyTestCase
  512. loader = unittest.TestLoader()
  513. suite = loader.loadTestsFromName('testcase_1.test', m)
  514. self.assertIsInstance(suite, loader.suiteClass)
  515. self.assertEqual(list(suite), [MyTestCase('test')])
  516. # "The specifier name is a ``dotted name'' that may resolve either to
  517. # a module, a test case class, a TestSuite instance, a test method
  518. # within a test case class, or a callable object which returns a
  519. # TestCase or TestSuite instance."
  520. #
  521. # Does loadTestsFromName() raise the proper exception when trying to
  522. # resolve "a test method within a test case class" that doesn't exist
  523. # for the given name (relative to a provided module)?
  524. def test_loadTestsFromName__relative_invalid_testmethod(self):
  525. m = types.ModuleType('m')
  526. class MyTestCase(unittest.TestCase):
  527. def test(self):
  528. pass
  529. m.testcase_1 = MyTestCase
  530. loader = unittest.TestLoader()
  531. suite = loader.loadTestsFromName('testcase_1.testfoo', m)
  532. expected = "type object 'MyTestCase' has no attribute 'testfoo'"
  533. error, test = self.check_deferred_error(loader, suite)
  534. self.assertIn(
  535. expected, error,
  536. 'missing error string in %r' % error)
  537. self.assertRaisesRegex(AttributeError, expected, test.testfoo)
  538. # "The specifier name is a ``dotted name'' that may resolve ... to
  539. # ... a callable object which returns a ... TestSuite instance"
  540. def test_loadTestsFromName__callable__TestSuite(self):
  541. m = types.ModuleType('m')
  542. testcase_1 = unittest.FunctionTestCase(lambda: None)
  543. testcase_2 = unittest.FunctionTestCase(lambda: None)
  544. def return_TestSuite():
  545. return unittest.TestSuite([testcase_1, testcase_2])
  546. m.return_TestSuite = return_TestSuite
  547. loader = unittest.TestLoader()
  548. suite = loader.loadTestsFromName('return_TestSuite', m)
  549. self.assertIsInstance(suite, loader.suiteClass)
  550. self.assertEqual(list(suite), [testcase_1, testcase_2])
  551. # "The specifier name is a ``dotted name'' that may resolve ... to
  552. # ... a callable object which returns a TestCase ... instance"
  553. def test_loadTestsFromName__callable__TestCase_instance(self):
  554. m = types.ModuleType('m')
  555. testcase_1 = unittest.FunctionTestCase(lambda: None)
  556. def return_TestCase():
  557. return testcase_1
  558. m.return_TestCase = return_TestCase
  559. loader = unittest.TestLoader()
  560. suite = loader.loadTestsFromName('return_TestCase', m)
  561. self.assertIsInstance(suite, loader.suiteClass)
  562. self.assertEqual(list(suite), [testcase_1])
  563. # "The specifier name is a ``dotted name'' that may resolve ... to
  564. # ... a callable object which returns a TestCase ... instance"
  565. #*****************************************************************
  566. #Override the suiteClass attribute to ensure that the suiteClass
  567. #attribute is used
  568. def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
  569. class SubTestSuite(unittest.TestSuite):
  570. pass
  571. m = types.ModuleType('m')
  572. testcase_1 = unittest.FunctionTestCase(lambda: None)
  573. def return_TestCase():
  574. return testcase_1
  575. m.return_TestCase = return_TestCase
  576. loader = unittest.TestLoader()
  577. loader.suiteClass = SubTestSuite
  578. suite = loader.loadTestsFromName('return_TestCase', m)
  579. self.assertIsInstance(suite, loader.suiteClass)
  580. self.assertEqual(list(suite), [testcase_1])
  581. # "The specifier name is a ``dotted name'' that may resolve ... to
  582. # ... a test method within a test case class"
  583. #*****************************************************************
  584. #Override the suiteClass attribute to ensure that the suiteClass
  585. #attribute is used
  586. def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
  587. class SubTestSuite(unittest.TestSuite):
  588. pass
  589. m = types.ModuleType('m')
  590. class MyTestCase(unittest.TestCase):
  591. def test(self):
  592. pass
  593. m.testcase_1 = MyTestCase
  594. loader = unittest.TestLoader()
  595. loader.suiteClass=SubTestSuite
  596. suite = loader.loadTestsFromName('testcase_1.test', m)
  597. self.assertIsInstance(suite, loader.suiteClass)
  598. self.assertEqual(list(suite), [MyTestCase('test')])
  599. # "The specifier name is a ``dotted name'' that may resolve ... to
  600. # ... a callable object which returns a TestCase or TestSuite instance"
  601. #
  602. # What happens if the callable returns something else?
  603. def test_loadTestsFromName__callable__wrong_type(self):
  604. m = types.ModuleType('m')
  605. def return_wrong():
  606. return 6
  607. m.return_wrong = return_wrong
  608. loader = unittest.TestLoader()
  609. try:
  610. suite = loader.loadTestsFromName('return_wrong', m)
  611. except TypeError:
  612. pass
  613. else:
  614. self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
  615. # "The specifier can refer to modules and packages which have not been
  616. # imported; they will be imported as a side-effect"
  617. def test_loadTestsFromName__module_not_loaded(self):
  618. # We're going to try to load this module as a side-effect, so it
  619. # better not be loaded before we try.
  620. #
  621. module_name = 'unittest.test.dummy'
  622. sys.modules.pop(module_name, None)
  623. loader = unittest.TestLoader()
  624. try:
  625. suite = loader.loadTestsFromName(module_name)
  626. self.assertIsInstance(suite, loader.suiteClass)
  627. self.assertEqual(list(suite), [])
  628. # module should now be loaded, thanks to loadTestsFromName()
  629. self.assertIn(module_name, sys.modules)
  630. finally:
  631. if module_name in sys.modules:
  632. del sys.modules[module_name]
  633. ################################################################
  634. ### Tests for TestLoader.loadTestsFromName()
  635. ### Tests for TestLoader.loadTestsFromNames()
  636. ################################################################
  637. def check_deferred_error(self, loader, suite):
  638. """Helper function for checking that errors in loading are reported.
  639. :param loader: A loader with some errors.
  640. :param suite: A suite that should have a late bound error.
  641. :return: The first error message from the loader and the test object
  642. from the suite.
  643. """
  644. self.assertIsInstance(suite, unittest.TestSuite)
  645. self.assertEqual(suite.countTestCases(), 1)
  646. # Errors loading the suite are also captured for introspection.
  647. self.assertNotEqual([], loader.errors)
  648. self.assertEqual(1, len(loader.errors))
  649. error = loader.errors[0]
  650. test = list(suite)[0]
  651. return error, test
  652. # "Similar to loadTestsFromName(), but takes a sequence of names rather
  653. # than a single name."
  654. #
  655. # What happens if that sequence of names is empty?
  656. def test_loadTestsFromNames__empty_name_list(self):
  657. loader = unittest.TestLoader()
  658. suite = loader.loadTestsFromNames([])
  659. self.assertIsInstance(suite, loader.suiteClass)
  660. self.assertEqual(list(suite), [])
  661. # "Similar to loadTestsFromName(), but takes a sequence of names rather
  662. # than a single name."
  663. # ...
  664. # "The method optionally resolves name relative to the given module"
  665. #
  666. # What happens if that sequence of names is empty?
  667. #
  668. # XXX Should this raise a ValueError or just return an empty TestSuite?
  669. def test_loadTestsFromNames__relative_empty_name_list(self):
  670. loader = unittest.TestLoader()
  671. suite = loader.loadTestsFromNames([], unittest)
  672. self.assertIsInstance(suite, loader.suiteClass)
  673. self.assertEqual(list(suite), [])
  674. # "The specifier name is a ``dotted name'' that may resolve either to
  675. # a module, a test case class, a TestSuite instance, a test method
  676. # within a test case class, or a callable object which returns a
  677. # TestCase or TestSuite instance."
  678. #
  679. # Is ValueError raised in response to an empty name?
  680. def test_loadTestsFromNames__empty_name(self):
  681. loader = unittest.TestLoader()
  682. try:
  683. loader.loadTestsFromNames([''])
  684. except ValueError as e:
  685. self.assertEqual(str(e), "Empty module name")
  686. else:
  687. self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
  688. # "The specifier name is a ``dotted name'' that may resolve either to
  689. # a module, a test case class, a TestSuite instance, a test method
  690. # within a test case class, or a callable object which returns a
  691. # TestCase or TestSuite instance."
  692. #
  693. # What happens when presented with an impossible module name?
  694. def test_loadTestsFromNames__malformed_name(self):
  695. loader = unittest.TestLoader()
  696. # XXX Should this raise ValueError or ImportError?
  697. suite = loader.loadTestsFromNames(['abc () //'])
  698. error, test = self.check_deferred_error(loader, list(suite)[0])
  699. expected = "Failed to import test module: abc () //"
  700. expected_regex = "Failed to import test module: abc \(\) //"
  701. self.assertIn(
  702. expected, error,
  703. 'missing error string in %r' % error)
  704. self.assertRaisesRegex(
  705. ImportError, expected_regex, getattr(test, 'abc () //'))
  706. # "The specifier name is a ``dotted name'' that may resolve either to
  707. # a module, a test case class, a TestSuite instance, a test method
  708. # within a test case class, or a callable object which returns a
  709. # TestCase or TestSuite instance."
  710. #
  711. # What happens when no module can be found for the given name?
  712. def test_loadTestsFromNames__unknown_module_name(self):
  713. loader = unittest.TestLoader()
  714. suite = loader.loadTestsFromNames(['sdasfasfasdf'])
  715. error, test = self.check_deferred_error(loader, list(suite)[0])
  716. expected = "Failed to import test module: sdasfasfasdf"
  717. self.assertIn(
  718. expected, error,
  719. 'missing error string in %r' % error)
  720. self.assertRaisesRegex(ImportError, expected, test.sdasfasfasdf)
  721. # "The specifier name is a ``dotted name'' that may resolve either to
  722. # a module, a test case class, a TestSuite instance, a test method
  723. # within a test case class, or a callable object which returns a
  724. # TestCase or TestSuite instance."
  725. #
  726. # What happens when the module can be found, but not the attribute?
  727. def test_loadTestsFromNames__unknown_attr_name(self):
  728. loader = unittest.TestLoader()
  729. suite = loader.loadTestsFromNames(
  730. ['unittest.loader.sdasfasfasdf', 'unittest.test.dummy'])
  731. error, test = self.check_deferred_error(loader, list(suite)[0])
  732. expected = "module 'unittest.loader' has no attribute 'sdasfasfasdf'"
  733. self.assertIn(
  734. expected, error,
  735. 'missing error string in %r' % error)
  736. self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf)
  737. # "The specifier name is a ``dotted name'' that may resolve either to
  738. # a module, a test case class, a TestSuite instance, a test method
  739. # within a test case class, or a callable object which returns a
  740. # TestCase or TestSuite instance."
  741. # ...
  742. # "The method optionally resolves name relative to the given module"
  743. #
  744. # What happens when given an unknown attribute on a specified `module`
  745. # argument?
  746. def test_loadTestsFromNames__unknown_name_relative_1(self):
  747. loader = unittest.TestLoader()
  748. suite = loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
  749. error, test = self.check_deferred_error(loader, list(suite)[0])
  750. expected = "module 'unittest' has no attribute 'sdasfasfasdf'"
  751. self.assertIn(
  752. expected, error,
  753. 'missing error string in %r' % error)
  754. self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf)
  755. # "The specifier name is a ``dotted name'' that may resolve either to
  756. # a module, a test case class, a TestSuite instance, a test method
  757. # within a test case class, or a callable object which returns a
  758. # TestCase or TestSuite instance."
  759. # ...
  760. # "The method optionally resolves name relative to the given module"
  761. #
  762. # Do unknown attributes (relative to a provided module) still raise an
  763. # exception even in the presence of valid attribute names?
  764. def test_loadTestsFromNames__unknown_name_relative_2(self):
  765. loader = unittest.TestLoader()
  766. suite = loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
  767. error, test = self.check_deferred_error(loader, list(suite)[1])
  768. expected = "module 'unittest' has no attribute 'sdasfasfasdf'"
  769. self.assertIn(
  770. expected, error,
  771. 'missing error string in %r' % error)
  772. self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf)
  773. # "The specifier name is a ``dotted name'' that may resolve either to
  774. # a module, a test case class, a TestSuite instance, a test method
  775. # within a test case class, or a callable object which returns a
  776. # TestCase or TestSuite instance."
  777. # ...
  778. # "The method optionally resolves name relative to the given module"
  779. #
  780. # What happens when faced with the empty string?
  781. #
  782. # XXX This currently raises AttributeError, though ValueError is probably
  783. # more appropriate
  784. def test_loadTestsFromNames__relative_empty_name(self):
  785. loader = unittest.TestLoader()
  786. suite = loader.loadTestsFromNames([''], unittest)
  787. error, test = self.check_deferred_error(loader, list(suite)[0])
  788. expected = "has no attribute ''"
  789. self.assertIn(
  790. expected, error,
  791. 'missing error string in %r' % error)
  792. self.assertRaisesRegex(AttributeError, expected, getattr(test, ''))
  793. # "The specifier name is a ``dotted name'' that may resolve either to
  794. # a module, a test case class, a TestSuite instance, a test method
  795. # within a test case class, or a callable object which returns a
  796. # TestCase or TestSuite instance."
  797. # ...
  798. # "The method optionally resolves name relative to the given module"
  799. #
  800. # What happens when presented with an impossible attribute name?
  801. def test_loadTestsFromNames__relative_malformed_name(self):
  802. loader = unittest.TestLoader()
  803. # XXX Should this raise AttributeError or ValueError?
  804. suite = loader.loadTestsFromNames(['abc () //'], unittest)
  805. error, test = self.check_deferred_error(loader, list(suite)[0])
  806. expected = "module 'unittest' has no attribute 'abc () //'"
  807. expected_regex = "module 'unittest' has no attribute 'abc \(\) //'"
  808. self.assertIn(
  809. expected, error,
  810. 'missing error string in %r' % error)
  811. self.assertRaisesRegex(
  812. AttributeError, expected_regex, getattr(test, 'abc () //'))
  813. # "The method optionally resolves name relative to the given module"
  814. #
  815. # Does loadTestsFromNames() make sure the provided `module` is in fact
  816. # a module?
  817. #
  818. # XXX This validation is currently not done. This flexibility should
  819. # either be documented or a TypeError should be raised.
  820. def test_loadTestsFromNames__relative_not_a_module(self):
  821. class MyTestCase(unittest.TestCase):
  822. def test(self):
  823. pass
  824. class NotAModule(object):
  825. test_2 = MyTestCase
  826. loader = unittest.TestLoader()
  827. suite = loader.loadTestsFromNames(['test_2'], NotAModule)
  828. reference = [unittest.TestSuite([MyTestCase('test')])]
  829. self.assertEqual(list(suite), reference)
  830. # "The specifier name is a ``dotted name'' that may resolve either to
  831. # a module, a test case class, a TestSuite instance, a test method
  832. # within a test case class, or a callable object which returns a
  833. # TestCase or TestSuite instance."
  834. #
  835. # Does it raise an exception if the name resolves to an invalid
  836. # object?
  837. def test_loadTestsFromNames__relative_bad_object(self):
  838. m = types.ModuleType('m')
  839. m.testcase_1 = object()
  840. loader = unittest.TestLoader()
  841. try:
  842. loader.loadTestsFromNames(['testcase_1'], m)
  843. except TypeError:
  844. pass
  845. else:
  846. self.fail("Should have raised TypeError")
  847. # "The specifier name is a ``dotted name'' that may resolve ... to
  848. # ... a test case class"
  849. def test_loadTestsFromNames__relative_TestCase_subclass(self):
  850. m = types.ModuleType('m')
  851. class MyTestCase(unittest.TestCase):
  852. def test(self):
  853. pass
  854. m.testcase_1 = MyTestCase
  855. loader = unittest.TestLoader()
  856. suite = loader.loadTestsFromNames(['testcase_1'], m)
  857. self.assertIsInstance(suite, loader.suiteClass)
  858. expected = loader.suiteClass([MyTestCase('test')])
  859. self.assertEqual(list(suite), [expected])
  860. # "The specifier name is a ``dotted name'' that may resolve ... to
  861. # ... a TestSuite instance"
  862. def test_loadTestsFromNames__relative_TestSuite(self):
  863. m = types.ModuleType('m')
  864. class MyTestCase(unittest.TestCase):
  865. def test(self):
  866. pass
  867. m.testsuite = unittest.TestSuite([MyTestCase('test')])
  868. loader = unittest.TestLoader()
  869. suite = loader.loadTestsFromNames(['testsuite'], m)
  870. self.assertIsInstance(suite, loader.suiteClass)
  871. self.assertEqual(list(suite), [m.testsuite])
  872. # "The specifier name is a ``dotted name'' that may resolve ... to ... a
  873. # test method within a test case class"
  874. def test_loadTestsFromNames__relative_testmethod(self):
  875. m = types.ModuleType('m')
  876. class MyTestCase(unittest.TestCase):
  877. def test(self):
  878. pass
  879. m.testcase_1 = MyTestCase
  880. loader = unittest.TestLoader()
  881. suite = loader.loadTestsFromNames(['testcase_1.test'], m)
  882. self.assertIsInstance(suite, loader.suiteClass)
  883. ref_suite = unittest.TestSuite([MyTestCase('test')])
  884. self.assertEqual(list(suite), [ref_suite])
  885. # #14971: Make sure the dotted name resolution works even if the actual
  886. # function doesn't have the same name as is used to find it.
  887. def test_loadTestsFromName__function_with_different_name_than_method(self):
  888. # lambdas have the name '<lambda>'.
  889. m = types.ModuleType('m')
  890. class MyTestCase(unittest.TestCase):
  891. test = lambda: 1
  892. m.testcase_1 = MyTestCase
  893. loader = unittest.TestLoader()
  894. suite = loader.loadTestsFromNames(['testcase_1.test'], m)
  895. self.assertIsInstance(suite, loader.suiteClass)
  896. ref_suite = unittest.TestSuite([MyTestCase('test')])
  897. self.assertEqual(list(suite), [ref_suite])
  898. # "The specifier name is a ``dotted name'' that may resolve ... to ... a
  899. # test method within a test case class"
  900. #
  901. # Does the method gracefully handle names that initially look like they
  902. # resolve to "a test method within a test case class" but don't?
  903. def test_loadTestsFromNames__relative_invalid_testmethod(self):
  904. m = types.ModuleType('m')
  905. class MyTestCase(unittest.TestCase):
  906. def test(self):
  907. pass
  908. m.testcase_1 = MyTestCase
  909. loader = unittest.TestLoader()
  910. suite = loader.loadTestsFromNames(['testcase_1.testfoo'], m)
  911. error, test = self.check_deferred_error(loader, list(suite)[0])
  912. expected = "type object 'MyTestCase' has no attribute 'testfoo'"
  913. self.assertIn(
  914. expected, error,
  915. 'missing error string in %r' % error)
  916. self.assertRaisesRegex(AttributeError, expected, test.testfoo)
  917. # "The specifier name is a ``dotted name'' that may resolve ... to
  918. # ... a callable object which returns a ... TestSuite instance"
  919. def test_loadTestsFromNames__callable__TestSuite(self):
  920. m = types.ModuleType('m')
  921. testcase_1 = unittest.FunctionTestCase(lambda: None)
  922. testcase_2 = unittest.FunctionTestCase(lambda: None)
  923. def return_TestSuite():
  924. return unittest.TestSuite([testcase_1, testcase_2])
  925. m.return_TestSuite = return_TestSuite
  926. loader = unittest.TestLoader()
  927. suite = loader.loadTestsFromNames(['return_TestSuite'], m)
  928. self.assertIsInstance(suite, loader.suiteClass)
  929. expected = unittest.TestSuite([testcase_1, testcase_2])
  930. self.assertEqual(list(suite), [expected])
  931. # "The specifier name is a ``dotted name'' that may resolve ... to
  932. # ... a callable object which returns a TestCase ... instance"
  933. def test_loadTestsFromNames__callable__TestCase_instance(self):
  934. m = types.ModuleType('m')
  935. testcase_1 = unittest.FunctionTestCase(lambda: None)
  936. def return_TestCase():
  937. return testcase_1
  938. m.return_TestCase = return_TestCase
  939. loader = unittest.TestLoader()
  940. suite = loader.loadTestsFromNames(['return_TestCase'], m)
  941. self.assertIsInstance(suite, loader.suiteClass)
  942. ref_suite = unittest.TestSuite([testcase_1])
  943. self.assertEqual(list(suite), [ref_suite])
  944. # "The specifier name is a ``dotted name'' that may resolve ... to
  945. # ... a callable object which returns a TestCase or TestSuite instance"
  946. #
  947. # Are staticmethods handled correctly?
  948. def test_loadTestsFromNames__callable__call_staticmethod(self):
  949. m = types.ModuleType('m')
  950. class Test1(unittest.TestCase):
  951. def test(self):
  952. pass
  953. testcase_1 = Test1('test')
  954. class Foo(unittest.TestCase):
  955. @staticmethod
  956. def foo():
  957. return testcase_1
  958. m.Foo = Foo
  959. loader = unittest.TestLoader()
  960. suite = loader.loadTestsFromNames(['Foo.foo'], m)
  961. self.assertIsInstance(suite, loader.suiteClass)
  962. ref_suite = unittest.TestSuite([testcase_1])
  963. self.assertEqual(list(suite), [ref_suite])
  964. # "The specifier name is a ``dotted name'' that may resolve ... to
  965. # ... a callable object which returns a TestCase or TestSuite instance"
  966. #
  967. # What happens when the callable returns something else?
  968. def test_loadTestsFromNames__callable__wrong_type(self):
  969. m = types.ModuleType('m')
  970. def return_wrong():
  971. return 6
  972. m.return_wrong = return_wrong
  973. loader = unittest.TestLoader()
  974. try:
  975. suite = loader.loadTestsFromNames(['return_wrong'], m)
  976. except TypeError:
  977. pass
  978. else:
  979. self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
  980. # "The specifier can refer to modules and packages which have not been
  981. # imported; they will be imported as a side-effect"
  982. def test_loadTestsFromNames__module_not_loaded(self):
  983. # We're going to try to load this module as a side-effect, so it
  984. # better not be loaded before we try.
  985. #
  986. module_name = 'unittest.test.dummy'
  987. sys.modules.pop(module_name, None)
  988. loader = unittest.TestLoader()
  989. try:
  990. suite = loader.loadTestsFromNames([module_name])
  991. self.assertIsInstance(suite, loader.suiteClass)
  992. self.assertEqual(list(suite), [unittest.TestSuite()])
  993. # module should now be loaded, thanks to loadTestsFromName()
  994. self.assertIn(module_name, sys.modules)
  995. finally:
  996. if module_name in sys.modules:
  997. del sys.modules[module_name]
  998. ################################################################
  999. ### /Tests for TestLoader.loadTestsFromNames()
  1000. ### Tests for TestLoader.getTestCaseNames()
  1001. ################################################################
  1002. # "Return a sorted sequence of method names found within testCaseClass"
  1003. #
  1004. # Test.foobar is defined to make sure getTestCaseNames() respects
  1005. # loader.testMethodPrefix
  1006. def test_getTestCaseNames(self):
  1007. class Test(unittest.TestCase):
  1008. def test_1(self): pass
  1009. def test_2(self): pass
  1010. def foobar(self): pass
  1011. loader = unittest.TestLoader()
  1012. self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
  1013. # "Return a sorted sequence of method names found within testCaseClass"
  1014. #
  1015. # Does getTestCaseNames() behave appropriately if no tests are found?
  1016. def test_getTestCaseNames__no_tests(self):
  1017. class Test(unittest.TestCase):
  1018. def foobar(self): pass
  1019. loader = unittest.TestLoader()
  1020. self.assertEqual(loader.getTestCaseNames(Test), [])
  1021. # "Return a sorted sequence of method names found within testCaseClass"
  1022. #
  1023. # Are not-TestCases handled gracefully?
  1024. #
  1025. # XXX This should raise a TypeError, not return a list
  1026. #
  1027. # XXX It's too late in the 2.5 release cycle to fix this, but it should
  1028. # probably be revisited for 2.6
  1029. def test_getTestCaseNames__not_a_TestCase(self):
  1030. class BadCase(int):
  1031. def test_foo(self):
  1032. pass
  1033. loader = unittest.TestLoader()
  1034. names = loader.getTestCaseNames(BadCase)
  1035. self.assertEqual(names, ['test_foo'])
  1036. # "Return a sorted sequence of method names found within testCaseClass"
  1037. #
  1038. # Make sure inherited names are handled.
  1039. #
  1040. # TestP.foobar is defined to make sure getTestCaseNames() respects
  1041. # loader.testMethodPrefix
  1042. def test_getTestCaseNames__inheritance(self):
  1043. class TestP(unittest.TestCase):
  1044. def test_1(self): pass
  1045. def test_2(self): pass
  1046. def foobar(self): pass
  1047. class TestC(TestP):
  1048. def test_1(self): pass
  1049. def test_3(self): pass
  1050. loader = unittest.TestLoader()
  1051. names = ['test_1', 'test_2', 'test_3']
  1052. self.assertEqual(loader.getTestCaseNames(TestC), names)
  1053. ################################################################
  1054. ### /Tests for TestLoader.getTestCaseNames()
  1055. ### Tests for TestLoader.testMethodPrefix
  1056. ################################################################
  1057. # "String giving the prefix of method names which will be interpreted as
  1058. # test methods"
  1059. #
  1060. # Implicit in the documentation is that testMethodPrefix is respected by
  1061. # all loadTestsFrom* methods.
  1062. def test_testMethodPrefix__loadTestsFromTestCase(self):
  1063. class Foo(unittest.TestCase):
  1064. def test_1(self): pass
  1065. def test_2(self): pass
  1066. def foo_bar(self): pass
  1067. tests_1 = unittest.TestSuite([Foo('foo_bar')])
  1068. tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
  1069. loader = unittest.TestLoader()
  1070. loader.testMethodPrefix = 'foo'
  1071. self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
  1072. loader.testMethodPrefix = 'test'
  1073. self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
  1074. # "String giving the prefix of method names which will be interpreted as
  1075. # test methods"
  1076. #
  1077. # Implicit in the documentation is that testMethodPrefix is respected by
  1078. # all loadTestsFrom* methods.
  1079. def test_testMethodPrefix__loadTestsFromModule(self):
  1080. m = types.ModuleType('m')
  1081. class Foo(unittest.TestCase):
  1082. def test_1(self): pass
  1083. def test_2(self): pass
  1084. def foo_bar(self): pass
  1085. m.Foo = Foo
  1086. tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
  1087. tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
  1088. loader = unittest.TestLoader()
  1089. loader.testMethodPrefix = 'foo'
  1090. self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
  1091. loader.testMethodPrefix = 'test'
  1092. self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
  1093. # "String giving the prefix of method names which will be interpreted as
  1094. # test methods"
  1095. #
  1096. # Implicit in the documentation is that testMethodPrefix is respected by
  1097. # all loadTestsFrom* methods.
  1098. def test_testMethodPrefix__loadTestsFromName(self):
  1099. m = types.ModuleType('m')
  1100. class Foo(unittest.TestCase):
  1101. def test_1(self): pass
  1102. def test_2(self): pass
  1103. def foo_bar(self): pass
  1104. m.Foo = Foo
  1105. tests_1 = unittest.TestSuite([Foo('foo_bar')])
  1106. tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
  1107. loader = unittest.TestLoader()
  1108. loader.testMethodPrefix = 'foo'
  1109. self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
  1110. loader.testMethodPrefix = 'test'
  1111. self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
  1112. # "String giving the prefix of method names which will be interpreted as
  1113. # test methods"
  1114. #
  1115. # Implicit in the documentation is that testMethodPrefix is respected by
  1116. # all loadTestsFrom* methods.
  1117. def test_testMethodPrefix__loadTestsFromNames(self):
  1118. m = types.ModuleType('m')
  1119. class Foo(unittest.TestCase):
  1120. def test_1(self): pass
  1121. def test_2(self): pass
  1122. def foo_bar(self): pass
  1123. m.Foo = Foo
  1124. tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
  1125. tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
  1126. tests_2 = unittest.TestSuite([tests_2])
  1127. loader = unittest.TestLoader()
  1128. loader.testMethodPrefix = 'foo'
  1129. self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
  1130. loader.testMethodPrefix = 'test'
  1131. self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
  1132. # "The default value is 'test'"
  1133. def test_testMethodPrefix__default_value(self):
  1134. loader = unittest.TestLoader()
  1135. self.assertEqual(loader.testMethodPrefix, 'test')
  1136. ################################################################
  1137. ### /Tests for TestLoader.testMethodPrefix
  1138. ### Tests for TestLoader.sortTestMethodsUsing
  1139. ################################################################
  1140. # "Function to be used to compare method names when sorting them in
  1141. # getTestCaseNames() and all the loadTestsFromX() methods"
  1142. def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
  1143. def reversed_cmp(x, y):
  1144. return -((x > y) - (x < y))
  1145. class Foo(unittest.TestCase):
  1146. def test_1(self): pass
  1147. def test_2(self): pass
  1148. loader = unittest.TestLoader()
  1149. loader.sortTestMethodsUsing = reversed_cmp
  1150. tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
  1151. self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
  1152. # "Function to be used to compare method names when sorting them in
  1153. # getTestCaseNames() and all the loadTestsFromX() methods"
  1154. def test_sortTestMethodsUsing__loadTestsFromModule(self):
  1155. def reversed_cmp(x, y):
  1156. return -((x > y) - (x < y))
  1157. m = types.ModuleType('m')
  1158. class Foo(unittest.TestCase):
  1159. def test_1(self): pass
  1160. def test_2(self): pass
  1161. m.Foo = Foo
  1162. loader = unittest.TestLoader()
  1163. loader.sortTestMethodsUsing = reversed_cmp
  1164. tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
  1165. self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
  1166. # "Function to be used to compare method names when sorting them in
  1167. # getTestCaseNames() and all the loadTestsFromX() methods"
  1168. def test_sortTestMethodsUsing__loadTestsFromName(self):
  1169. def reversed_cmp(x, y):
  1170. return -((x > y) - (x < y))
  1171. m = types.ModuleType('m')
  1172. class Foo(unittest.TestCase):
  1173. def test_1(self): pass
  1174. def test_2(self): pass
  1175. m.Foo = Foo
  1176. loader = unittest.TestLoader()
  1177. loader.sortTestMethodsUsing = reversed_cmp
  1178. tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
  1179. self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
  1180. # "Function to be used to compare method names when sorting them in
  1181. # getTestCaseNames() and all the loadTestsFromX() methods"
  1182. def test_sortTestMethodsUsing__loadTestsFromNames(self):
  1183. def reversed_cmp(x, y):
  1184. return -((x > y) - (x < y))
  1185. m = types.ModuleType('m')
  1186. class Foo(unittest.TestCase):
  1187. def test_1(self): pass
  1188. def test_2(self): pass
  1189. m.Foo = Foo
  1190. loader = unittest.TestLoader()
  1191. loader.sortTestMethodsUsing = reversed_cmp
  1192. tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
  1193. self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
  1194. # "Function to be used to compare method names when sorting them in
  1195. # getTestCaseNames()"
  1196. #
  1197. # Does it actually affect getTestCaseNames()?
  1198. def test_sortTestMethodsUsing__getTestCaseNames(self):
  1199. def reversed_cmp(x, y):
  1200. return -((x > y) - (x < y))
  1201. class Foo(unittest.TestCase):
  1202. def test_1(self): pass
  1203. def test_2(self): pass
  1204. loader = unittest.TestLoader()
  1205. loader.sortTestMethodsUsing = reversed_cmp
  1206. test_names = ['test_2', 'test_1']
  1207. self.assertEqual(loader.getTestCaseNames(Foo), test_names)
  1208. # "The default value is the built-in cmp() function"
  1209. # Since cmp is now defunct, we simply verify that the results
  1210. # occur in the same order as they would with the default sort.
  1211. def test_sortTestMethodsUsing__default_value(self):
  1212. loader = unittest.TestLoader()
  1213. class Foo(unittest.TestCase):
  1214. def test_2(self): pass
  1215. def test_3(self): pass
  1216. def test_1(self): pass
  1217. test_names = ['test_2', 'test_3', 'test_1']
  1218. self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
  1219. # "it can be set to None to disable the sort."
  1220. #
  1221. # XXX How is this different from reassigning cmp? Are the tests returned
  1222. # in a random order or something? This behaviour should die
  1223. def test_sortTestMethodsUsing__None(self):
  1224. class Foo(unittest.TestCase):
  1225. def test_1(self): pass
  1226. def test_2(self): pass
  1227. loader = unittest.TestLoader()
  1228. loader.sortTestMethodsUsing = None
  1229. test_names = ['test_2', 'test_1']
  1230. self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
  1231. ################################################################
  1232. ### /Tests for TestLoader.sortTestMethodsUsing
  1233. ### Tests for TestLoader.suiteClass
  1234. ################################################################
  1235. # "Callable object that constructs a test suite from a list of tests."
  1236. def test_suiteClass__loadTestsFromTestCase(self):
  1237. class Foo(unittest.TestCase):
  1238. def test_1(self): pass
  1239. def test_2(self): pass
  1240. def foo_bar(self): pass
  1241. tests = [Foo('test_1'), Foo('test_2')]
  1242. loader = unittest.TestLoader()
  1243. loader.suiteClass = list
  1244. self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
  1245. # It is implicit in the documentation for TestLoader.suiteClass that
  1246. # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
  1247. def test_suiteClass__loadTestsFromModule(self):
  1248. m = types.ModuleType('m')
  1249. class Foo(unittest.TestCase):
  1250. def test_1(self): pass
  1251. def test_2(self): pass
  1252. def foo_bar(self): pass
  1253. m.Foo = Foo
  1254. tests = [[Foo('test_1'), Foo('test_2')]]
  1255. loader = unittest.TestLoader()
  1256. loader.suiteClass = list
  1257. self.assertEqual(loader.loadTestsFromModule(m), tests)
  1258. # It is implicit in the documentation for TestLoader.suiteClass that
  1259. # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
  1260. def test_suiteClass__loadTestsFromName(self):
  1261. m = types.ModuleType('m')
  1262. class Foo(unittest.TestCase):
  1263. def test_1(self): pass
  1264. def test_2(self): pass
  1265. def foo_bar(self): pass
  1266. m.Foo = Foo
  1267. tests = [Foo('test_1'), Foo('test_2')]
  1268. loader = unittest.TestLoader()
  1269. loader.suiteClass = list
  1270. self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
  1271. # It is implicit in the documentation for TestLoader.suiteClass that
  1272. # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
  1273. def test_suiteClass__loadTestsFromNames(self):
  1274. m = types.ModuleType('m')
  1275. class Foo(unittest.TestCase):
  1276. def test_1(self): pass
  1277. def test_2(self): pass
  1278. def foo_bar(self): pass
  1279. m.Foo = Foo
  1280. tests = [[Foo('test_1'), Foo('test_2')]]
  1281. loader = unittest.TestLoader()
  1282. loader.suiteClass = list
  1283. self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
  1284. # "The default value is the TestSuite class"
  1285. def test_suiteClass__default_value(self):
  1286. loader = unittest.TestLoader()
  1287. self.assertIs(loader.suiteClass, unittest.TestSuite)
  1288. if __name__ == "__main__":
  1289. unittest.main()