ยปCore Development>Code coverage>Lib/test/test_support.py

Python code coverage for Lib/test/test_support.py

#countcontent
1n/aimport importlib
2n/aimport shutil
3n/aimport stat
4n/aimport sys
5n/aimport os
6n/aimport unittest
7n/aimport socket
8n/aimport tempfile
9n/aimport errno
10n/afrom test import support
11n/a
12n/aTESTFN = support.TESTFN
13n/a
14n/a
15n/aclass TestSupport(unittest.TestCase):
16n/a
17n/a def test_import_module(self):
18n/a support.import_module("ftplib")
19n/a self.assertRaises(unittest.SkipTest, support.import_module, "foo")
20n/a
21n/a def test_import_fresh_module(self):
22n/a support.import_fresh_module("ftplib")
23n/a
24n/a def test_get_attribute(self):
25n/a self.assertEqual(support.get_attribute(self, "test_get_attribute"),
26n/a self.test_get_attribute)
27n/a self.assertRaises(unittest.SkipTest, support.get_attribute, self, "foo")
28n/a
29n/a @unittest.skip("failing buildbots")
30n/a def test_get_original_stdout(self):
31n/a self.assertEqual(support.get_original_stdout(), sys.stdout)
32n/a
33n/a def test_unload(self):
34n/a import sched
35n/a self.assertIn("sched", sys.modules)
36n/a support.unload("sched")
37n/a self.assertNotIn("sched", sys.modules)
38n/a
39n/a def test_unlink(self):
40n/a with open(TESTFN, "w") as f:
41n/a pass
42n/a support.unlink(TESTFN)
43n/a self.assertFalse(os.path.exists(TESTFN))
44n/a support.unlink(TESTFN)
45n/a
46n/a def test_rmtree(self):
47n/a dirpath = support.TESTFN + 'd'
48n/a subdirpath = os.path.join(dirpath, 'subdir')
49n/a os.mkdir(dirpath)
50n/a os.mkdir(subdirpath)
51n/a support.rmtree(dirpath)
52n/a self.assertFalse(os.path.exists(dirpath))
53n/a with support.swap_attr(support, 'verbose', 0):
54n/a support.rmtree(dirpath)
55n/a
56n/a os.mkdir(dirpath)
57n/a os.mkdir(subdirpath)
58n/a os.chmod(dirpath, stat.S_IRUSR|stat.S_IXUSR)
59n/a with support.swap_attr(support, 'verbose', 0):
60n/a support.rmtree(dirpath)
61n/a self.assertFalse(os.path.exists(dirpath))
62n/a
63n/a os.mkdir(dirpath)
64n/a os.mkdir(subdirpath)
65n/a os.chmod(dirpath, 0)
66n/a with support.swap_attr(support, 'verbose', 0):
67n/a support.rmtree(dirpath)
68n/a self.assertFalse(os.path.exists(dirpath))
69n/a
70n/a def test_forget(self):
71n/a mod_filename = TESTFN + '.py'
72n/a with open(mod_filename, 'w') as f:
73n/a print('foo = 1', file=f)
74n/a sys.path.insert(0, os.curdir)
75n/a importlib.invalidate_caches()
76n/a try:
77n/a mod = __import__(TESTFN)
78n/a self.assertIn(TESTFN, sys.modules)
79n/a
80n/a support.forget(TESTFN)
81n/a self.assertNotIn(TESTFN, sys.modules)
82n/a finally:
83n/a del sys.path[0]
84n/a support.unlink(mod_filename)
85n/a support.rmtree('__pycache__')
86n/a
87n/a def test_HOST(self):
88n/a s = socket.socket()
89n/a s.bind((support.HOST, 0))
90n/a s.close()
91n/a
92n/a def test_find_unused_port(self):
93n/a port = support.find_unused_port()
94n/a s = socket.socket()
95n/a s.bind((support.HOST, port))
96n/a s.close()
97n/a
98n/a def test_bind_port(self):
99n/a s = socket.socket()
100n/a support.bind_port(s)
101n/a s.listen()
102n/a s.close()
103n/a
104n/a # Tests for temp_dir()
105n/a
106n/a def test_temp_dir(self):
107n/a """Test that temp_dir() creates and destroys its directory."""
108n/a parent_dir = tempfile.mkdtemp()
109n/a parent_dir = os.path.realpath(parent_dir)
110n/a
111n/a try:
112n/a path = os.path.join(parent_dir, 'temp')
113n/a self.assertFalse(os.path.isdir(path))
114n/a with support.temp_dir(path) as temp_path:
115n/a self.assertEqual(temp_path, path)
116n/a self.assertTrue(os.path.isdir(path))
117n/a self.assertFalse(os.path.isdir(path))
118n/a finally:
119n/a support.rmtree(parent_dir)
120n/a
121n/a def test_temp_dir__path_none(self):
122n/a """Test passing no path."""
123n/a with support.temp_dir() as temp_path:
124n/a self.assertTrue(os.path.isdir(temp_path))
125n/a self.assertFalse(os.path.isdir(temp_path))
126n/a
127n/a def test_temp_dir__existing_dir__quiet_default(self):
128n/a """Test passing a directory that already exists."""
129n/a def call_temp_dir(path):
130n/a with support.temp_dir(path) as temp_path:
131n/a raise Exception("should not get here")
132n/a
133n/a path = tempfile.mkdtemp()
134n/a path = os.path.realpath(path)
135n/a try:
136n/a self.assertTrue(os.path.isdir(path))
137n/a self.assertRaises(FileExistsError, call_temp_dir, path)
138n/a # Make sure temp_dir did not delete the original directory.
139n/a self.assertTrue(os.path.isdir(path))
140n/a finally:
141n/a shutil.rmtree(path)
142n/a
143n/a def test_temp_dir__existing_dir__quiet_true(self):
144n/a """Test passing a directory that already exists with quiet=True."""
145n/a path = tempfile.mkdtemp()
146n/a path = os.path.realpath(path)
147n/a
148n/a try:
149n/a with support.check_warnings() as recorder:
150n/a with support.temp_dir(path, quiet=True) as temp_path:
151n/a self.assertEqual(path, temp_path)
152n/a warnings = [str(w.message) for w in recorder.warnings]
153n/a # Make sure temp_dir did not delete the original directory.
154n/a self.assertTrue(os.path.isdir(path))
155n/a finally:
156n/a shutil.rmtree(path)
157n/a
158n/a self.assertEqual(len(warnings), 1, warnings)
159n/a warn = warnings[0]
160n/a self.assertTrue(warn.startswith(f'tests may fail, unable to create '
161n/a f'temporary directory {path!r}: '),
162n/a warn)
163n/a
164n/a # Tests for change_cwd()
165n/a
166n/a def test_change_cwd(self):
167n/a original_cwd = os.getcwd()
168n/a
169n/a with support.temp_dir() as temp_path:
170n/a with support.change_cwd(temp_path) as new_cwd:
171n/a self.assertEqual(new_cwd, temp_path)
172n/a self.assertEqual(os.getcwd(), new_cwd)
173n/a
174n/a self.assertEqual(os.getcwd(), original_cwd)
175n/a
176n/a def test_change_cwd__non_existent_dir(self):
177n/a """Test passing a non-existent directory."""
178n/a original_cwd = os.getcwd()
179n/a
180n/a def call_change_cwd(path):
181n/a with support.change_cwd(path) as new_cwd:
182n/a raise Exception("should not get here")
183n/a
184n/a with support.temp_dir() as parent_dir:
185n/a non_existent_dir = os.path.join(parent_dir, 'does_not_exist')
186n/a self.assertRaises(FileNotFoundError, call_change_cwd,
187n/a non_existent_dir)
188n/a
189n/a self.assertEqual(os.getcwd(), original_cwd)
190n/a
191n/a def test_change_cwd__non_existent_dir__quiet_true(self):
192n/a """Test passing a non-existent directory with quiet=True."""
193n/a original_cwd = os.getcwd()
194n/a
195n/a with support.temp_dir() as parent_dir:
196n/a bad_dir = os.path.join(parent_dir, 'does_not_exist')
197n/a with support.check_warnings() as recorder:
198n/a with support.change_cwd(bad_dir, quiet=True) as new_cwd:
199n/a self.assertEqual(new_cwd, original_cwd)
200n/a self.assertEqual(os.getcwd(), new_cwd)
201n/a warnings = [str(w.message) for w in recorder.warnings]
202n/a
203n/a self.assertEqual(len(warnings), 1, warnings)
204n/a warn = warnings[0]
205n/a self.assertTrue(warn.startswith(f'tests may fail, unable to change '
206n/a f'the current working directory '
207n/a f'to {bad_dir!r}: '),
208n/a warn)
209n/a
210n/a # Tests for change_cwd()
211n/a
212n/a def test_change_cwd__chdir_warning(self):
213n/a """Check the warning message when os.chdir() fails."""
214n/a path = TESTFN + '_does_not_exist'
215n/a with support.check_warnings() as recorder:
216n/a with support.change_cwd(path=path, quiet=True):
217n/a pass
218n/a messages = [str(w.message) for w in recorder.warnings]
219n/a
220n/a self.assertEqual(len(messages), 1, messages)
221n/a msg = messages[0]
222n/a self.assertTrue(msg.startswith(f'tests may fail, unable to change '
223n/a f'the current working directory '
224n/a f'to {path!r}: '),
225n/a msg)
226n/a
227n/a # Tests for temp_cwd()
228n/a
229n/a def test_temp_cwd(self):
230n/a here = os.getcwd()
231n/a with support.temp_cwd(name=TESTFN):
232n/a self.assertEqual(os.path.basename(os.getcwd()), TESTFN)
233n/a self.assertFalse(os.path.exists(TESTFN))
234n/a self.assertTrue(os.path.basename(os.getcwd()), here)
235n/a
236n/a
237n/a def test_temp_cwd__name_none(self):
238n/a """Test passing None to temp_cwd()."""
239n/a original_cwd = os.getcwd()
240n/a with support.temp_cwd(name=None) as new_cwd:
241n/a self.assertNotEqual(new_cwd, original_cwd)
242n/a self.assertTrue(os.path.isdir(new_cwd))
243n/a self.assertEqual(os.getcwd(), new_cwd)
244n/a self.assertEqual(os.getcwd(), original_cwd)
245n/a
246n/a def test_sortdict(self):
247n/a self.assertEqual(support.sortdict({3:3, 2:2, 1:1}), "{1: 1, 2: 2, 3: 3}")
248n/a
249n/a def test_make_bad_fd(self):
250n/a fd = support.make_bad_fd()
251n/a with self.assertRaises(OSError) as cm:
252n/a os.write(fd, b"foo")
253n/a self.assertEqual(cm.exception.errno, errno.EBADF)
254n/a
255n/a def test_check_syntax_error(self):
256n/a support.check_syntax_error(self, "def class", lineno=1, offset=9)
257n/a with self.assertRaises(AssertionError):
258n/a support.check_syntax_error(self, "x=1")
259n/a
260n/a def test_CleanImport(self):
261n/a import importlib
262n/a with support.CleanImport("asyncore"):
263n/a importlib.import_module("asyncore")
264n/a
265n/a def test_DirsOnSysPath(self):
266n/a with support.DirsOnSysPath('foo', 'bar'):
267n/a self.assertIn("foo", sys.path)
268n/a self.assertIn("bar", sys.path)
269n/a self.assertNotIn("foo", sys.path)
270n/a self.assertNotIn("bar", sys.path)
271n/a
272n/a def test_captured_stdout(self):
273n/a with support.captured_stdout() as stdout:
274n/a print("hello")
275n/a self.assertEqual(stdout.getvalue(), "hello\n")
276n/a
277n/a def test_captured_stderr(self):
278n/a with support.captured_stderr() as stderr:
279n/a print("hello", file=sys.stderr)
280n/a self.assertEqual(stderr.getvalue(), "hello\n")
281n/a
282n/a def test_captured_stdin(self):
283n/a with support.captured_stdin() as stdin:
284n/a stdin.write('hello\n')
285n/a stdin.seek(0)
286n/a # call test code that consumes from sys.stdin
287n/a captured = input()
288n/a self.assertEqual(captured, "hello")
289n/a
290n/a def test_gc_collect(self):
291n/a support.gc_collect()
292n/a
293n/a def test_python_is_optimized(self):
294n/a self.assertIsInstance(support.python_is_optimized(), bool)
295n/a
296n/a def test_swap_attr(self):
297n/a class Obj:
298n/a x = 1
299n/a obj = Obj()
300n/a with support.swap_attr(obj, "x", 5):
301n/a self.assertEqual(obj.x, 5)
302n/a self.assertEqual(obj.x, 1)
303n/a
304n/a def test_swap_item(self):
305n/a D = {"item":1}
306n/a with support.swap_item(D, "item", 5):
307n/a self.assertEqual(D["item"], 5)
308n/a self.assertEqual(D["item"], 1)
309n/a
310n/a class RefClass:
311n/a attribute1 = None
312n/a attribute2 = None
313n/a _hidden_attribute1 = None
314n/a __magic_1__ = None
315n/a
316n/a class OtherClass:
317n/a attribute2 = None
318n/a attribute3 = None
319n/a __magic_1__ = None
320n/a __magic_2__ = None
321n/a
322n/a def test_detect_api_mismatch(self):
323n/a missing_items = support.detect_api_mismatch(self.RefClass,
324n/a self.OtherClass)
325n/a self.assertEqual({'attribute1'}, missing_items)
326n/a
327n/a missing_items = support.detect_api_mismatch(self.OtherClass,
328n/a self.RefClass)
329n/a self.assertEqual({'attribute3', '__magic_2__'}, missing_items)
330n/a
331n/a def test_detect_api_mismatch__ignore(self):
332n/a ignore = ['attribute1', 'attribute3', '__magic_2__', 'not_in_either']
333n/a
334n/a missing_items = support.detect_api_mismatch(
335n/a self.RefClass, self.OtherClass, ignore=ignore)
336n/a self.assertEqual(set(), missing_items)
337n/a
338n/a missing_items = support.detect_api_mismatch(
339n/a self.OtherClass, self.RefClass, ignore=ignore)
340n/a self.assertEqual(set(), missing_items)
341n/a
342n/a def test_check__all__(self):
343n/a extra = {'tempdir'}
344n/a blacklist = {'template'}
345n/a support.check__all__(self,
346n/a tempfile,
347n/a extra=extra,
348n/a blacklist=blacklist)
349n/a
350n/a extra = {'TextTestResult', 'installHandler'}
351n/a blacklist = {'load_tests', "TestProgram", "BaseTestSuite"}
352n/a
353n/a support.check__all__(self,
354n/a unittest,
355n/a ("unittest.result", "unittest.case",
356n/a "unittest.suite", "unittest.loader",
357n/a "unittest.main", "unittest.runner",
358n/a "unittest.signals"),
359n/a extra=extra,
360n/a blacklist=blacklist)
361n/a
362n/a self.assertRaises(AssertionError, support.check__all__, self, unittest)
363n/a
364n/a # XXX -follows a list of untested API
365n/a # make_legacy_pyc
366n/a # is_resource_enabled
367n/a # requires
368n/a # fcmp
369n/a # umaks
370n/a # findfile
371n/a # check_warnings
372n/a # EnvironmentVarGuard
373n/a # TransientResource
374n/a # transient_internet
375n/a # run_with_locale
376n/a # set_memlimit
377n/a # bigmemtest
378n/a # precisionbigmemtest
379n/a # bigaddrspacetest
380n/a # requires_resource
381n/a # run_doctest
382n/a # threading_cleanup
383n/a # reap_threads
384n/a # reap_children
385n/a # strip_python_stderr
386n/a # args_from_interpreter_flags
387n/a # can_symlink
388n/a # skip_unless_symlink
389n/a # SuppressCrashReport
390n/a
391n/a
392n/adef test_main():
393n/a tests = [TestSupport]
394n/a support.run_unittest(*tests)
395n/a
396n/aif __name__ == '__main__':
397n/a test_main()