PageRenderTime 73ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/testing/web-platform/tests/tools/third_party/pytest/testing/test_unittest.py

https://bitbucket.org/vionika/spin.android
Python | 992 lines | 964 code | 4 blank | 24 comment | 0 complexity | ff4a80b7b26f282d8d92f805f3ad39f4 MD5 | raw file
Possible License(s): JSON, 0BSD, AGPL-1.0, BSD-2-Clause, GPL-3.0, LGPL-2.1, LGPL-3.0, CC0-1.0, AGPL-3.0, MPL-2.0, Apache-2.0, MIT, BSD-3-Clause, MPL-2.0-no-copyleft-exception, GPL-2.0, Unlicense
  1. from __future__ import absolute_import, division, print_function
  2. from _pytest.main import EXIT_NOTESTSCOLLECTED
  3. import pytest
  4. import gc
  5. def test_simple_unittest(testdir):
  6. testpath = testdir.makepyfile(
  7. """
  8. import unittest
  9. class MyTestCase(unittest.TestCase):
  10. def testpassing(self):
  11. self.assertEqual('foo', 'foo')
  12. def test_failing(self):
  13. self.assertEqual('foo', 'bar')
  14. """
  15. )
  16. reprec = testdir.inline_run(testpath)
  17. assert reprec.matchreport("testpassing").passed
  18. assert reprec.matchreport("test_failing").failed
  19. def test_runTest_method(testdir):
  20. testdir.makepyfile(
  21. """
  22. import unittest
  23. class MyTestCaseWithRunTest(unittest.TestCase):
  24. def runTest(self):
  25. self.assertEqual('foo', 'foo')
  26. class MyTestCaseWithoutRunTest(unittest.TestCase):
  27. def runTest(self):
  28. self.assertEqual('foo', 'foo')
  29. def test_something(self):
  30. pass
  31. """
  32. )
  33. result = testdir.runpytest("-v")
  34. result.stdout.fnmatch_lines(
  35. """
  36. *MyTestCaseWithRunTest::runTest*
  37. *MyTestCaseWithoutRunTest::test_something*
  38. *2 passed*
  39. """
  40. )
  41. def test_isclasscheck_issue53(testdir):
  42. testpath = testdir.makepyfile(
  43. """
  44. import unittest
  45. class _E(object):
  46. def __getattr__(self, tag):
  47. pass
  48. E = _E()
  49. """
  50. )
  51. result = testdir.runpytest(testpath)
  52. assert result.ret == EXIT_NOTESTSCOLLECTED
  53. def test_setup(testdir):
  54. testpath = testdir.makepyfile(
  55. """
  56. import unittest
  57. class MyTestCase(unittest.TestCase):
  58. def setUp(self):
  59. self.foo = 1
  60. def setup_method(self, method):
  61. self.foo2 = 1
  62. def test_both(self):
  63. self.assertEqual(1, self.foo)
  64. assert self.foo2 == 1
  65. def teardown_method(self, method):
  66. assert 0, "42"
  67. """
  68. )
  69. reprec = testdir.inline_run("-s", testpath)
  70. assert reprec.matchreport("test_both", when="call").passed
  71. rep = reprec.matchreport("test_both", when="teardown")
  72. assert rep.failed and "42" in str(rep.longrepr)
  73. def test_setUpModule(testdir):
  74. testpath = testdir.makepyfile(
  75. """
  76. values = []
  77. def setUpModule():
  78. values.append(1)
  79. def tearDownModule():
  80. del values[0]
  81. def test_hello():
  82. assert values == [1]
  83. def test_world():
  84. assert values == [1]
  85. """
  86. )
  87. result = testdir.runpytest(testpath)
  88. result.stdout.fnmatch_lines(["*2 passed*"])
  89. def test_setUpModule_failing_no_teardown(testdir):
  90. testpath = testdir.makepyfile(
  91. """
  92. values = []
  93. def setUpModule():
  94. 0/0
  95. def tearDownModule():
  96. values.append(1)
  97. def test_hello():
  98. pass
  99. """
  100. )
  101. reprec = testdir.inline_run(testpath)
  102. reprec.assertoutcome(passed=0, failed=1)
  103. call = reprec.getcalls("pytest_runtest_setup")[0]
  104. assert not call.item.module.values
  105. def test_new_instances(testdir):
  106. testpath = testdir.makepyfile(
  107. """
  108. import unittest
  109. class MyTestCase(unittest.TestCase):
  110. def test_func1(self):
  111. self.x = 2
  112. def test_func2(self):
  113. assert not hasattr(self, 'x')
  114. """
  115. )
  116. reprec = testdir.inline_run(testpath)
  117. reprec.assertoutcome(passed=2)
  118. def test_teardown(testdir):
  119. testpath = testdir.makepyfile(
  120. """
  121. import unittest
  122. class MyTestCase(unittest.TestCase):
  123. values = []
  124. def test_one(self):
  125. pass
  126. def tearDown(self):
  127. self.values.append(None)
  128. class Second(unittest.TestCase):
  129. def test_check(self):
  130. self.assertEqual(MyTestCase.values, [None])
  131. """
  132. )
  133. reprec = testdir.inline_run(testpath)
  134. passed, skipped, failed = reprec.countoutcomes()
  135. assert failed == 0, failed
  136. assert passed == 2
  137. assert passed + skipped + failed == 2
  138. def test_teardown_issue1649(testdir):
  139. """
  140. Are TestCase objects cleaned up? Often unittest TestCase objects set
  141. attributes that are large and expensive during setUp.
  142. The TestCase will not be cleaned up if the test fails, because it
  143. would then exist in the stackframe.
  144. """
  145. testpath = testdir.makepyfile(
  146. """
  147. import unittest
  148. class TestCaseObjectsShouldBeCleanedUp(unittest.TestCase):
  149. def setUp(self):
  150. self.an_expensive_object = 1
  151. def test_demo(self):
  152. pass
  153. """
  154. )
  155. testdir.inline_run("-s", testpath)
  156. gc.collect()
  157. for obj in gc.get_objects():
  158. assert type(obj).__name__ != "TestCaseObjectsShouldBeCleanedUp"
  159. def test_unittest_skip_issue148(testdir):
  160. testpath = testdir.makepyfile(
  161. """
  162. import unittest
  163. @unittest.skip("hello")
  164. class MyTestCase(unittest.TestCase):
  165. @classmethod
  166. def setUpClass(self):
  167. xxx
  168. def test_one(self):
  169. pass
  170. @classmethod
  171. def tearDownClass(self):
  172. xxx
  173. """
  174. )
  175. reprec = testdir.inline_run(testpath)
  176. reprec.assertoutcome(skipped=1)
  177. def test_method_and_teardown_failing_reporting(testdir):
  178. testdir.makepyfile(
  179. """
  180. import unittest, pytest
  181. class TC(unittest.TestCase):
  182. def tearDown(self):
  183. assert 0, "down1"
  184. def test_method(self):
  185. assert False, "down2"
  186. """
  187. )
  188. result = testdir.runpytest("-s")
  189. assert result.ret == 1
  190. result.stdout.fnmatch_lines(
  191. [
  192. "*tearDown*",
  193. "*assert 0*",
  194. "*test_method*",
  195. "*assert False*",
  196. "*1 failed*1 error*",
  197. ]
  198. )
  199. def test_setup_failure_is_shown(testdir):
  200. testdir.makepyfile(
  201. """
  202. import unittest
  203. import pytest
  204. class TC(unittest.TestCase):
  205. def setUp(self):
  206. assert 0, "down1"
  207. def test_method(self):
  208. print ("never42")
  209. xyz
  210. """
  211. )
  212. result = testdir.runpytest("-s")
  213. assert result.ret == 1
  214. result.stdout.fnmatch_lines(["*setUp*", "*assert 0*down1*", "*1 failed*"])
  215. assert "never42" not in result.stdout.str()
  216. def test_setup_setUpClass(testdir):
  217. testpath = testdir.makepyfile(
  218. """
  219. import unittest
  220. import pytest
  221. class MyTestCase(unittest.TestCase):
  222. x = 0
  223. @classmethod
  224. def setUpClass(cls):
  225. cls.x += 1
  226. def test_func1(self):
  227. assert self.x == 1
  228. def test_func2(self):
  229. assert self.x == 1
  230. @classmethod
  231. def tearDownClass(cls):
  232. cls.x -= 1
  233. def test_teareddown():
  234. assert MyTestCase.x == 0
  235. """
  236. )
  237. reprec = testdir.inline_run(testpath)
  238. reprec.assertoutcome(passed=3)
  239. def test_setup_class(testdir):
  240. testpath = testdir.makepyfile(
  241. """
  242. import unittest
  243. import pytest
  244. class MyTestCase(unittest.TestCase):
  245. x = 0
  246. def setup_class(cls):
  247. cls.x += 1
  248. def test_func1(self):
  249. assert self.x == 1
  250. def test_func2(self):
  251. assert self.x == 1
  252. def teardown_class(cls):
  253. cls.x -= 1
  254. def test_teareddown():
  255. assert MyTestCase.x == 0
  256. """
  257. )
  258. reprec = testdir.inline_run(testpath)
  259. reprec.assertoutcome(passed=3)
  260. @pytest.mark.parametrize("type", ["Error", "Failure"])
  261. def test_testcase_adderrorandfailure_defers(testdir, type):
  262. testdir.makepyfile(
  263. """
  264. from unittest import TestCase
  265. import pytest
  266. class MyTestCase(TestCase):
  267. def run(self, result):
  268. excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)
  269. try:
  270. result.add%s(self, excinfo._excinfo)
  271. except KeyboardInterrupt:
  272. raise
  273. except:
  274. pytest.fail("add%s should not raise")
  275. def test_hello(self):
  276. pass
  277. """
  278. % (type, type)
  279. )
  280. result = testdir.runpytest()
  281. assert "should not raise" not in result.stdout.str()
  282. @pytest.mark.parametrize("type", ["Error", "Failure"])
  283. def test_testcase_custom_exception_info(testdir, type):
  284. testdir.makepyfile(
  285. """
  286. from unittest import TestCase
  287. import py, pytest
  288. import _pytest._code
  289. class MyTestCase(TestCase):
  290. def run(self, result):
  291. excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)
  292. # we fake an incompatible exception info
  293. from _pytest.monkeypatch import MonkeyPatch
  294. mp = MonkeyPatch()
  295. def t(*args):
  296. mp.undo()
  297. raise TypeError()
  298. mp.setattr(_pytest._code, 'ExceptionInfo', t)
  299. try:
  300. excinfo = excinfo._excinfo
  301. result.add%(type)s(self, excinfo)
  302. finally:
  303. mp.undo()
  304. def test_hello(self):
  305. pass
  306. """
  307. % locals()
  308. )
  309. result = testdir.runpytest()
  310. result.stdout.fnmatch_lines(
  311. [
  312. "NOTE: Incompatible Exception Representation*",
  313. "*ZeroDivisionError*",
  314. "*1 failed*",
  315. ]
  316. )
  317. def test_testcase_totally_incompatible_exception_info(testdir):
  318. item, = testdir.getitems(
  319. """
  320. from unittest import TestCase
  321. class MyTestCase(TestCase):
  322. def test_hello(self):
  323. pass
  324. """
  325. )
  326. item.addError(None, 42)
  327. excinfo = item._excinfo.pop(0)
  328. assert "ERROR: Unknown Incompatible" in str(excinfo.getrepr())
  329. def test_module_level_pytestmark(testdir):
  330. testpath = testdir.makepyfile(
  331. """
  332. import unittest
  333. import pytest
  334. pytestmark = pytest.mark.xfail
  335. class MyTestCase(unittest.TestCase):
  336. def test_func1(self):
  337. assert 0
  338. """
  339. )
  340. reprec = testdir.inline_run(testpath, "-s")
  341. reprec.assertoutcome(skipped=1)
  342. class TestTrialUnittest(object):
  343. def setup_class(cls):
  344. cls.ut = pytest.importorskip("twisted.trial.unittest")
  345. # on windows trial uses a socket for a reactor and apparently doesn't close it properly
  346. # https://twistedmatrix.com/trac/ticket/9227
  347. cls.ignore_unclosed_socket_warning = ("-W", "always")
  348. def test_trial_testcase_runtest_not_collected(self, testdir):
  349. testdir.makepyfile(
  350. """
  351. from twisted.trial.unittest import TestCase
  352. class TC(TestCase):
  353. def test_hello(self):
  354. pass
  355. """
  356. )
  357. reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)
  358. reprec.assertoutcome(passed=1)
  359. testdir.makepyfile(
  360. """
  361. from twisted.trial.unittest import TestCase
  362. class TC(TestCase):
  363. def runTest(self):
  364. pass
  365. """
  366. )
  367. reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)
  368. reprec.assertoutcome(passed=1)
  369. def test_trial_exceptions_with_skips(self, testdir):
  370. testdir.makepyfile(
  371. """
  372. from twisted.trial import unittest
  373. import pytest
  374. class TC(unittest.TestCase):
  375. def test_hello(self):
  376. pytest.skip("skip_in_method")
  377. @pytest.mark.skipif("sys.version_info != 1")
  378. def test_hello2(self):
  379. pass
  380. @pytest.mark.xfail(reason="iwanto")
  381. def test_hello3(self):
  382. assert 0
  383. def test_hello4(self):
  384. pytest.xfail("i2wanto")
  385. def test_trial_skip(self):
  386. pass
  387. test_trial_skip.skip = "trialselfskip"
  388. def test_trial_todo(self):
  389. assert 0
  390. test_trial_todo.todo = "mytodo"
  391. def test_trial_todo_success(self):
  392. pass
  393. test_trial_todo_success.todo = "mytodo"
  394. class TC2(unittest.TestCase):
  395. def setup_class(cls):
  396. pytest.skip("skip_in_setup_class")
  397. def test_method(self):
  398. pass
  399. """
  400. )
  401. from _pytest.compat import _is_unittest_unexpected_success_a_failure
  402. should_fail = _is_unittest_unexpected_success_a_failure()
  403. result = testdir.runpytest("-rxs", *self.ignore_unclosed_socket_warning)
  404. result.stdout.fnmatch_lines_random(
  405. [
  406. "*XFAIL*test_trial_todo*",
  407. "*trialselfskip*",
  408. "*skip_in_setup_class*",
  409. "*iwanto*",
  410. "*i2wanto*",
  411. "*sys.version_info*",
  412. "*skip_in_method*",
  413. "*1 failed*4 skipped*3 xfailed*"
  414. if should_fail
  415. else "*4 skipped*3 xfail*1 xpass*",
  416. ]
  417. )
  418. assert result.ret == (1 if should_fail else 0)
  419. def test_trial_error(self, testdir):
  420. testdir.makepyfile(
  421. """
  422. from twisted.trial.unittest import TestCase
  423. from twisted.internet.defer import Deferred
  424. from twisted.internet import reactor
  425. class TC(TestCase):
  426. def test_one(self):
  427. crash
  428. def test_two(self):
  429. def f(_):
  430. crash
  431. d = Deferred()
  432. d.addCallback(f)
  433. reactor.callLater(0.3, d.callback, None)
  434. return d
  435. def test_three(self):
  436. def f():
  437. pass # will never get called
  438. reactor.callLater(0.3, f)
  439. # will crash at teardown
  440. def test_four(self):
  441. def f(_):
  442. reactor.callLater(0.3, f)
  443. crash
  444. d = Deferred()
  445. d.addCallback(f)
  446. reactor.callLater(0.3, d.callback, None)
  447. return d
  448. # will crash both at test time and at teardown
  449. """
  450. )
  451. result = testdir.runpytest()
  452. result.stdout.fnmatch_lines(
  453. [
  454. "*ERRORS*",
  455. "*DelayedCalls*",
  456. "*test_four*",
  457. "*NameError*crash*",
  458. "*test_one*",
  459. "*NameError*crash*",
  460. "*test_three*",
  461. "*DelayedCalls*",
  462. "*test_two*",
  463. "*crash*",
  464. ]
  465. )
  466. def test_trial_pdb(self, testdir):
  467. p = testdir.makepyfile(
  468. """
  469. from twisted.trial import unittest
  470. import pytest
  471. class TC(unittest.TestCase):
  472. def test_hello(self):
  473. assert 0, "hellopdb"
  474. """
  475. )
  476. child = testdir.spawn_pytest(p)
  477. child.expect("hellopdb")
  478. child.sendeof()
  479. def test_trial_testcase_skip_property(self, testdir):
  480. testpath = testdir.makepyfile(
  481. """
  482. from twisted.trial import unittest
  483. class MyTestCase(unittest.TestCase):
  484. skip = 'dont run'
  485. def test_func(self):
  486. pass
  487. """
  488. )
  489. reprec = testdir.inline_run(testpath, "-s")
  490. reprec.assertoutcome(skipped=1)
  491. def test_trial_testfunction_skip_property(self, testdir):
  492. testpath = testdir.makepyfile(
  493. """
  494. from twisted.trial import unittest
  495. class MyTestCase(unittest.TestCase):
  496. def test_func(self):
  497. pass
  498. test_func.skip = 'dont run'
  499. """
  500. )
  501. reprec = testdir.inline_run(testpath, "-s")
  502. reprec.assertoutcome(skipped=1)
  503. def test_trial_testcase_todo_property(self, testdir):
  504. testpath = testdir.makepyfile(
  505. """
  506. from twisted.trial import unittest
  507. class MyTestCase(unittest.TestCase):
  508. todo = 'dont run'
  509. def test_func(self):
  510. assert 0
  511. """
  512. )
  513. reprec = testdir.inline_run(testpath, "-s")
  514. reprec.assertoutcome(skipped=1)
  515. def test_trial_testfunction_todo_property(self, testdir):
  516. testpath = testdir.makepyfile(
  517. """
  518. from twisted.trial import unittest
  519. class MyTestCase(unittest.TestCase):
  520. def test_func(self):
  521. assert 0
  522. test_func.todo = 'dont run'
  523. """
  524. )
  525. reprec = testdir.inline_run(
  526. testpath, "-s", *self.ignore_unclosed_socket_warning
  527. )
  528. reprec.assertoutcome(skipped=1)
  529. def test_djangolike_testcase(testdir):
  530. # contributed from Morten Breekevold
  531. testdir.makepyfile(
  532. """
  533. from unittest import TestCase, main
  534. class DjangoLikeTestCase(TestCase):
  535. def setUp(self):
  536. print ("setUp()")
  537. def test_presetup_has_been_run(self):
  538. print ("test_thing()")
  539. self.assertTrue(hasattr(self, 'was_presetup'))
  540. def tearDown(self):
  541. print ("tearDown()")
  542. def __call__(self, result=None):
  543. try:
  544. self._pre_setup()
  545. except (KeyboardInterrupt, SystemExit):
  546. raise
  547. except Exception:
  548. import sys
  549. result.addError(self, sys.exc_info())
  550. return
  551. super(DjangoLikeTestCase, self).__call__(result)
  552. try:
  553. self._post_teardown()
  554. except (KeyboardInterrupt, SystemExit):
  555. raise
  556. except Exception:
  557. import sys
  558. result.addError(self, sys.exc_info())
  559. return
  560. def _pre_setup(self):
  561. print ("_pre_setup()")
  562. self.was_presetup = True
  563. def _post_teardown(self):
  564. print ("_post_teardown()")
  565. """
  566. )
  567. result = testdir.runpytest("-s")
  568. assert result.ret == 0
  569. result.stdout.fnmatch_lines(
  570. [
  571. "*_pre_setup()*",
  572. "*setUp()*",
  573. "*test_thing()*",
  574. "*tearDown()*",
  575. "*_post_teardown()*",
  576. ]
  577. )
  578. def test_unittest_not_shown_in_traceback(testdir):
  579. testdir.makepyfile(
  580. """
  581. import unittest
  582. class t(unittest.TestCase):
  583. def test_hello(self):
  584. x = 3
  585. self.assertEqual(x, 4)
  586. """
  587. )
  588. res = testdir.runpytest()
  589. assert "failUnlessEqual" not in res.stdout.str()
  590. def test_unorderable_types(testdir):
  591. testdir.makepyfile(
  592. """
  593. import unittest
  594. class TestJoinEmpty(unittest.TestCase):
  595. pass
  596. def make_test():
  597. class Test(unittest.TestCase):
  598. pass
  599. Test.__name__ = "TestFoo"
  600. return Test
  601. TestFoo = make_test()
  602. """
  603. )
  604. result = testdir.runpytest()
  605. assert "TypeError" not in result.stdout.str()
  606. assert result.ret == EXIT_NOTESTSCOLLECTED
  607. def test_unittest_typerror_traceback(testdir):
  608. testdir.makepyfile(
  609. """
  610. import unittest
  611. class TestJoinEmpty(unittest.TestCase):
  612. def test_hello(self, arg1):
  613. pass
  614. """
  615. )
  616. result = testdir.runpytest()
  617. assert "TypeError" in result.stdout.str()
  618. assert result.ret == 1
  619. @pytest.mark.parametrize("runner", ["pytest", "unittest"])
  620. def test_unittest_expected_failure_for_failing_test_is_xfail(testdir, runner):
  621. script = testdir.makepyfile(
  622. """
  623. import unittest
  624. class MyTestCase(unittest.TestCase):
  625. @unittest.expectedFailure
  626. def test_failing_test_is_xfail(self):
  627. assert False
  628. if __name__ == '__main__':
  629. unittest.main()
  630. """
  631. )
  632. if runner == "pytest":
  633. result = testdir.runpytest("-rxX")
  634. result.stdout.fnmatch_lines(
  635. ["*XFAIL*MyTestCase*test_failing_test_is_xfail*", "*1 xfailed*"]
  636. )
  637. else:
  638. result = testdir.runpython(script)
  639. result.stderr.fnmatch_lines(["*1 test in*", "*OK*(expected failures=1)*"])
  640. assert result.ret == 0
  641. @pytest.mark.parametrize("runner", ["pytest", "unittest"])
  642. def test_unittest_expected_failure_for_passing_test_is_fail(testdir, runner):
  643. script = testdir.makepyfile(
  644. """
  645. import unittest
  646. class MyTestCase(unittest.TestCase):
  647. @unittest.expectedFailure
  648. def test_passing_test_is_fail(self):
  649. assert True
  650. if __name__ == '__main__':
  651. unittest.main()
  652. """
  653. )
  654. from _pytest.compat import _is_unittest_unexpected_success_a_failure
  655. should_fail = _is_unittest_unexpected_success_a_failure()
  656. if runner == "pytest":
  657. result = testdir.runpytest("-rxX")
  658. result.stdout.fnmatch_lines(
  659. [
  660. "*MyTestCase*test_passing_test_is_fail*",
  661. "*1 failed*" if should_fail else "*1 xpassed*",
  662. ]
  663. )
  664. else:
  665. result = testdir.runpython(script)
  666. result.stderr.fnmatch_lines(["*1 test in*", "*(unexpected successes=1)*"])
  667. assert result.ret == (1 if should_fail else 0)
  668. @pytest.mark.parametrize(
  669. "fix_type, stmt", [("fixture", "return"), ("yield_fixture", "yield")]
  670. )
  671. def test_unittest_setup_interaction(testdir, fix_type, stmt):
  672. testdir.makepyfile(
  673. """
  674. import unittest
  675. import pytest
  676. class MyTestCase(unittest.TestCase):
  677. @pytest.{fix_type}(scope="class", autouse=True)
  678. def perclass(self, request):
  679. request.cls.hello = "world"
  680. {stmt}
  681. @pytest.{fix_type}(scope="function", autouse=True)
  682. def perfunction(self, request):
  683. request.instance.funcname = request.function.__name__
  684. {stmt}
  685. def test_method1(self):
  686. assert self.funcname == "test_method1"
  687. assert self.hello == "world"
  688. def test_method2(self):
  689. assert self.funcname == "test_method2"
  690. def test_classattr(self):
  691. assert self.__class__.hello == "world"
  692. """.format(
  693. fix_type=fix_type, stmt=stmt
  694. )
  695. )
  696. result = testdir.runpytest()
  697. result.stdout.fnmatch_lines("*3 passed*")
  698. def test_non_unittest_no_setupclass_support(testdir):
  699. testpath = testdir.makepyfile(
  700. """
  701. class TestFoo(object):
  702. x = 0
  703. @classmethod
  704. def setUpClass(cls):
  705. cls.x = 1
  706. def test_method1(self):
  707. assert self.x == 0
  708. @classmethod
  709. def tearDownClass(cls):
  710. cls.x = 1
  711. def test_not_teareddown():
  712. assert TestFoo.x == 0
  713. """
  714. )
  715. reprec = testdir.inline_run(testpath)
  716. reprec.assertoutcome(passed=2)
  717. def test_no_teardown_if_setupclass_failed(testdir):
  718. testpath = testdir.makepyfile(
  719. """
  720. import unittest
  721. class MyTestCase(unittest.TestCase):
  722. x = 0
  723. @classmethod
  724. def setUpClass(cls):
  725. cls.x = 1
  726. assert False
  727. def test_func1(self):
  728. cls.x = 10
  729. @classmethod
  730. def tearDownClass(cls):
  731. cls.x = 100
  732. def test_notTornDown():
  733. assert MyTestCase.x == 1
  734. """
  735. )
  736. reprec = testdir.inline_run(testpath)
  737. reprec.assertoutcome(passed=1, failed=1)
  738. def test_issue333_result_clearing(testdir):
  739. testdir.makeconftest(
  740. """
  741. import pytest
  742. @pytest.hookimpl(hookwrapper=True)
  743. def pytest_runtest_call(item):
  744. yield
  745. assert 0
  746. """
  747. )
  748. testdir.makepyfile(
  749. """
  750. import unittest
  751. class TestIt(unittest.TestCase):
  752. def test_func(self):
  753. 0/0
  754. """
  755. )
  756. reprec = testdir.inline_run()
  757. reprec.assertoutcome(failed=1)
  758. def test_unittest_raise_skip_issue748(testdir):
  759. testdir.makepyfile(
  760. test_foo="""
  761. import unittest
  762. class MyTestCase(unittest.TestCase):
  763. def test_one(self):
  764. raise unittest.SkipTest('skipping due to reasons')
  765. """
  766. )
  767. result = testdir.runpytest("-v", "-rs")
  768. result.stdout.fnmatch_lines(
  769. """
  770. *SKIP*[1]*test_foo.py*skipping due to reasons*
  771. *1 skipped*
  772. """
  773. )
  774. def test_unittest_skip_issue1169(testdir):
  775. testdir.makepyfile(
  776. test_foo="""
  777. import unittest
  778. class MyTestCase(unittest.TestCase):
  779. @unittest.skip("skipping due to reasons")
  780. def test_skip(self):
  781. self.fail()
  782. """
  783. )
  784. result = testdir.runpytest("-v", "-rs")
  785. result.stdout.fnmatch_lines(
  786. """
  787. *SKIP*[1]*skipping due to reasons*
  788. *1 skipped*
  789. """
  790. )
  791. def test_class_method_containing_test_issue1558(testdir):
  792. testdir.makepyfile(
  793. test_foo="""
  794. import unittest
  795. class MyTestCase(unittest.TestCase):
  796. def test_should_run(self):
  797. pass
  798. def test_should_not_run(self):
  799. pass
  800. test_should_not_run.__test__ = False
  801. """
  802. )
  803. reprec = testdir.inline_run()
  804. reprec.assertoutcome(passed=1)
  805. @pytest.mark.issue(3498)
  806. @pytest.mark.parametrize(
  807. "base", ["six.moves.builtins.object", "unittest.TestCase", "unittest2.TestCase"]
  808. )
  809. def test_usefixtures_marker_on_unittest(base, testdir):
  810. module = base.rsplit(".", 1)[0]
  811. pytest.importorskip(module)
  812. testdir.makepyfile(
  813. conftest="""
  814. import pytest
  815. @pytest.fixture(scope='function')
  816. def fixture1(request, monkeypatch):
  817. monkeypatch.setattr(request.instance, 'fixture1', True )
  818. @pytest.fixture(scope='function')
  819. def fixture2(request, monkeypatch):
  820. monkeypatch.setattr(request.instance, 'fixture2', True )
  821. def node_and_marks(item):
  822. print(item.nodeid)
  823. for mark in item.iter_markers():
  824. print(" ", mark)
  825. @pytest.fixture(autouse=True)
  826. def my_marks(request):
  827. node_and_marks(request.node)
  828. def pytest_collection_modifyitems(items):
  829. for item in items:
  830. node_and_marks(item)
  831. """
  832. )
  833. testdir.makepyfile(
  834. """
  835. import pytest
  836. import {module}
  837. class Tests({base}):
  838. fixture1 = False
  839. fixture2 = False
  840. @pytest.mark.usefixtures("fixture1")
  841. def test_one(self):
  842. assert self.fixture1
  843. assert not self.fixture2
  844. @pytest.mark.usefixtures("fixture1", "fixture2")
  845. def test_two(self):
  846. assert self.fixture1
  847. assert self.fixture2
  848. """.format(
  849. module=module, base=base
  850. )
  851. )
  852. result = testdir.runpytest("-s")
  853. result.assert_outcomes(passed=2)