Debian Codegraph @

hypothesis-python/tests/cover/test_unittest.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import io
12 import sys
13 import unittest
14
15 import pytest
16
17 from hypothesis import given, strategies as st
18 from hypothesis.errors import FailedHealthCheck, HypothesisWarning
19
20 from tests.common.utils import fails_with, skipif_emscripten
21
22
23 class Thing_with_a_subThing(unittest.TestCase):
24 """Example test case using subTest for the actual test below."""
25
26 @given(st.tuples(st.booleans(), st.booleans()))
27 def thing(self, lst):
28 for i, b in enumerate(lst):
29 with pytest.warns(HypothesisWarning), self.subTest((i, b)):
30 self.assertTrue(b)
31
32
33 def test_subTest():
34 suite = unittest.TestSuite()
35 suite.addTest(Thing_with_a_subThing("thing"))
36 stream = io.StringIO()
37 out = unittest.TextTestRunner(stream=stream).run(suite)
38 assert len(out.failures) <= out.testsRun, out
39
40
41 class test_given_on_setUp_fails_health_check(unittest.TestCase):
42 @fails_with(FailedHealthCheck)
43 @given(st.integers())
44 def setUp(self, i):
45 pass
46
47 def test(self):
48 """Provide something to set up for, so the setUp method is called."""
49
50
51 SUBTEST_SUITE = """
52 import unittest
53 from hypothesis import given, settings, strategies as st
54
55 class MyTest(unittest.TestCase):
56 @given(s=st.text())
57 @settings(deadline=None)
58 def test_subtest(self, s):
59 with self.subTest(text=s):
60 self.assertIsInstance(s, str)
61
62 if __name__ == "__main__":
63 unittest.main()
64 """
65
66
67 @skipif_emscripten
68 @pytest.mark.parametrize("err", [[], ["-Werror"]])
69 def test_subTest_no_self(testdir, err):
70 # https://github.com/HypothesisWorks/hypothesis/issues/2462
71 # for some reason this issue happens only when running unittest from commandline
72 fname = testdir.makepyfile(tests=SUBTEST_SUITE)
73 result = testdir.run(sys.executable, *err, str(fname))
74 expected = pytest.ExitCode.TESTS_FAILED if err else pytest.ExitCode.OK
75 assert result.ret == expected, result.stderr.str()