»Core Development>Code coverage>Lib/test/test_winreg.py

Python code coverage for Lib/test/test_winreg.py

#countcontent
1n/a# Test the windows specific win32reg module.
2n/a# Only win32reg functions not hit here: FlushKey, LoadKey and SaveKey
3n/a
4n/aimport os, sys, errno
5n/aimport unittest
6n/afrom test import support
7n/athreading = support.import_module("threading")
8n/afrom platform import machine
9n/a
10n/a# Do this first so test will be skipped if module doesn't exist
11n/asupport.import_module('winreg', required_on=['win'])
12n/a# Now import everything
13n/afrom winreg import *
14n/a
15n/atry:
16n/a REMOTE_NAME = sys.argv[sys.argv.index("--remote")+1]
17n/aexcept (IndexError, ValueError):
18n/a REMOTE_NAME = None
19n/a
20n/a# tuple of (major, minor)
21n/aWIN_VER = sys.getwindowsversion()[:2]
22n/a# Some tests should only run on 64-bit architectures where WOW64 will be.
23n/aWIN64_MACHINE = True if machine() == "AMD64" else False
24n/a
25n/a# Starting with Windows 7 and Windows Server 2008 R2, WOW64 no longer uses
26n/a# registry reflection and formerly reflected keys are shared instead.
27n/a# Windows 7 and Windows Server 2008 R2 are version 6.1. Due to this, some
28n/a# tests are only valid up until 6.1
29n/aHAS_REFLECTION = True if WIN_VER < (6, 1) else False
30n/a
31n/a# Use a per-process key to prevent concurrent test runs (buildbot!) from
32n/a# stomping on each other.
33n/atest_key_base = "Python Test Key [%d] - Delete Me" % (os.getpid(),)
34n/atest_key_name = "SOFTWARE\\" + test_key_base
35n/a# On OS'es that support reflection we should test with a reflected key
36n/atest_reflect_key_name = "SOFTWARE\\Classes\\" + test_key_base
37n/a
38n/atest_data = [
39n/a ("Int Value", 45, REG_DWORD),
40n/a ("Qword Value", 0x1122334455667788, REG_QWORD),
41n/a ("String Val", "A string value", REG_SZ),
42n/a ("StringExpand", "The path is %path%", REG_EXPAND_SZ),
43n/a ("Multi-string", ["Lots", "of", "string", "values"], REG_MULTI_SZ),
44n/a ("Raw Data", b"binary\x00data", REG_BINARY),
45n/a ("Big String", "x"*(2**14-1), REG_SZ),
46n/a ("Big Binary", b"x"*(2**14), REG_BINARY),
47n/a # Two and three kanjis, meaning: "Japan" and "Japanese")
48n/a ("Japanese 日本", "日本語", REG_SZ),
49n/a]
50n/a
51n/aclass BaseWinregTests(unittest.TestCase):
52n/a
53n/a def setUp(self):
54n/a # Make sure that the test key is absent when the test
55n/a # starts.
56n/a self.delete_tree(HKEY_CURRENT_USER, test_key_name)
57n/a
58n/a def delete_tree(self, root, subkey):
59n/a try:
60n/a hkey = OpenKey(root, subkey, 0, KEY_ALL_ACCESS)
61n/a except OSError:
62n/a # subkey does not exist
63n/a return
64n/a while True:
65n/a try:
66n/a subsubkey = EnumKey(hkey, 0)
67n/a except OSError:
68n/a # no more subkeys
69n/a break
70n/a self.delete_tree(hkey, subsubkey)
71n/a CloseKey(hkey)
72n/a DeleteKey(root, subkey)
73n/a
74n/a def _write_test_data(self, root_key, subkeystr="sub_key",
75n/a CreateKey=CreateKey):
76n/a # Set the default value for this key.
77n/a SetValue(root_key, test_key_name, REG_SZ, "Default value")
78n/a key = CreateKey(root_key, test_key_name)
79n/a self.assertTrue(key.handle != 0)
80n/a # Create a sub-key
81n/a sub_key = CreateKey(key, subkeystr)
82n/a # Give the sub-key some named values
83n/a
84n/a for value_name, value_data, value_type in test_data:
85n/a SetValueEx(sub_key, value_name, 0, value_type, value_data)
86n/a
87n/a # Check we wrote as many items as we thought.
88n/a nkeys, nvalues, since_mod = QueryInfoKey(key)
89n/a self.assertEqual(nkeys, 1, "Not the correct number of sub keys")
90n/a self.assertEqual(nvalues, 1, "Not the correct number of values")
91n/a nkeys, nvalues, since_mod = QueryInfoKey(sub_key)
92n/a self.assertEqual(nkeys, 0, "Not the correct number of sub keys")
93n/a self.assertEqual(nvalues, len(test_data),
94n/a "Not the correct number of values")
95n/a # Close this key this way...
96n/a # (but before we do, copy the key as an integer - this allows
97n/a # us to test that the key really gets closed).
98n/a int_sub_key = int(sub_key)
99n/a CloseKey(sub_key)
100n/a try:
101n/a QueryInfoKey(int_sub_key)
102n/a self.fail("It appears the CloseKey() function does "
103n/a "not close the actual key!")
104n/a except OSError:
105n/a pass
106n/a # ... and close that key that way :-)
107n/a int_key = int(key)
108n/a key.Close()
109n/a try:
110n/a QueryInfoKey(int_key)
111n/a self.fail("It appears the key.Close() function "
112n/a "does not close the actual key!")
113n/a except OSError:
114n/a pass
115n/a
116n/a def _read_test_data(self, root_key, subkeystr="sub_key", OpenKey=OpenKey):
117n/a # Check we can get default value for this key.
118n/a val = QueryValue(root_key, test_key_name)
119n/a self.assertEqual(val, "Default value",
120n/a "Registry didn't give back the correct value")
121n/a
122n/a key = OpenKey(root_key, test_key_name)
123n/a # Read the sub-keys
124n/a with OpenKey(key, subkeystr) as sub_key:
125n/a # Check I can enumerate over the values.
126n/a index = 0
127n/a while 1:
128n/a try:
129n/a data = EnumValue(sub_key, index)
130n/a except OSError:
131n/a break
132n/a self.assertEqual(data in test_data, True,
133n/a "Didn't read back the correct test data")
134n/a index = index + 1
135n/a self.assertEqual(index, len(test_data),
136n/a "Didn't read the correct number of items")
137n/a # Check I can directly access each item
138n/a for value_name, value_data, value_type in test_data:
139n/a read_val, read_typ = QueryValueEx(sub_key, value_name)
140n/a self.assertEqual(read_val, value_data,
141n/a "Could not directly read the value")
142n/a self.assertEqual(read_typ, value_type,
143n/a "Could not directly read the value")
144n/a sub_key.Close()
145n/a # Enumerate our main key.
146n/a read_val = EnumKey(key, 0)
147n/a self.assertEqual(read_val, subkeystr, "Read subkey value wrong")
148n/a try:
149n/a EnumKey(key, 1)
150n/a self.fail("Was able to get a second key when I only have one!")
151n/a except OSError:
152n/a pass
153n/a
154n/a key.Close()
155n/a
156n/a def _delete_test_data(self, root_key, subkeystr="sub_key"):
157n/a key = OpenKey(root_key, test_key_name, 0, KEY_ALL_ACCESS)
158n/a sub_key = OpenKey(key, subkeystr, 0, KEY_ALL_ACCESS)
159n/a # It is not necessary to delete the values before deleting
160n/a # the key (although subkeys must not exist). We delete them
161n/a # manually just to prove we can :-)
162n/a for value_name, value_data, value_type in test_data:
163n/a DeleteValue(sub_key, value_name)
164n/a
165n/a nkeys, nvalues, since_mod = QueryInfoKey(sub_key)
166n/a self.assertEqual(nkeys, 0, "subkey not empty before delete")
167n/a self.assertEqual(nvalues, 0, "subkey not empty before delete")
168n/a sub_key.Close()
169n/a DeleteKey(key, subkeystr)
170n/a
171n/a try:
172n/a # Shouldn't be able to delete it twice!
173n/a DeleteKey(key, subkeystr)
174n/a self.fail("Deleting the key twice succeeded")
175n/a except OSError:
176n/a pass
177n/a key.Close()
178n/a DeleteKey(root_key, test_key_name)
179n/a # Opening should now fail!
180n/a try:
181n/a key = OpenKey(root_key, test_key_name)
182n/a self.fail("Could open the non-existent key")
183n/a except OSError: # Use this error name this time
184n/a pass
185n/a
186n/a def _test_all(self, root_key, subkeystr="sub_key"):
187n/a self._write_test_data(root_key, subkeystr)
188n/a self._read_test_data(root_key, subkeystr)
189n/a self._delete_test_data(root_key, subkeystr)
190n/a
191n/a def _test_named_args(self, key, sub_key):
192n/a with CreateKeyEx(key=key, sub_key=sub_key, reserved=0,
193n/a access=KEY_ALL_ACCESS) as ckey:
194n/a self.assertTrue(ckey.handle != 0)
195n/a
196n/a with OpenKeyEx(key=key, sub_key=sub_key, reserved=0,
197n/a access=KEY_ALL_ACCESS) as okey:
198n/a self.assertTrue(okey.handle != 0)
199n/a
200n/a
201n/aclass LocalWinregTests(BaseWinregTests):
202n/a
203n/a def test_registry_works(self):
204n/a self._test_all(HKEY_CURRENT_USER)
205n/a self._test_all(HKEY_CURRENT_USER, "日本-subkey")
206n/a
207n/a def test_registry_works_extended_functions(self):
208n/a # Substitute the regular CreateKey and OpenKey calls with their
209n/a # extended counterparts.
210n/a # Note: DeleteKeyEx is not used here because it is platform dependent
211n/a cke = lambda key, sub_key: CreateKeyEx(key, sub_key, 0, KEY_ALL_ACCESS)
212n/a self._write_test_data(HKEY_CURRENT_USER, CreateKey=cke)
213n/a
214n/a oke = lambda key, sub_key: OpenKeyEx(key, sub_key, 0, KEY_READ)
215n/a self._read_test_data(HKEY_CURRENT_USER, OpenKey=oke)
216n/a
217n/a self._delete_test_data(HKEY_CURRENT_USER)
218n/a
219n/a def test_named_arguments(self):
220n/a self._test_named_args(HKEY_CURRENT_USER, test_key_name)
221n/a # Use the regular DeleteKey to clean up
222n/a # DeleteKeyEx takes named args and is tested separately
223n/a DeleteKey(HKEY_CURRENT_USER, test_key_name)
224n/a
225n/a def test_connect_registry_to_local_machine_works(self):
226n/a # perform minimal ConnectRegistry test which just invokes it
227n/a h = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
228n/a self.assertNotEqual(h.handle, 0)
229n/a h.Close()
230n/a self.assertEqual(h.handle, 0)
231n/a
232n/a def test_inexistant_remote_registry(self):
233n/a connect = lambda: ConnectRegistry("abcdefghijkl", HKEY_CURRENT_USER)
234n/a self.assertRaises(OSError, connect)
235n/a
236n/a def testExpandEnvironmentStrings(self):
237n/a r = ExpandEnvironmentStrings("%windir%\\test")
238n/a self.assertEqual(type(r), str)
239n/a self.assertEqual(r, os.environ["windir"] + "\\test")
240n/a
241n/a def test_context_manager(self):
242n/a # ensure that the handle is closed if an exception occurs
243n/a try:
244n/a with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as h:
245n/a self.assertNotEqual(h.handle, 0)
246n/a raise OSError
247n/a except OSError:
248n/a self.assertEqual(h.handle, 0)
249n/a
250n/a def test_changing_value(self):
251n/a # Issue2810: A race condition in 2.6 and 3.1 may cause
252n/a # EnumValue or QueryValue to raise "WindowsError: More data is
253n/a # available"
254n/a done = False
255n/a
256n/a class VeryActiveThread(threading.Thread):
257n/a def run(self):
258n/a with CreateKey(HKEY_CURRENT_USER, test_key_name) as key:
259n/a use_short = True
260n/a long_string = 'x'*2000
261n/a while not done:
262n/a s = 'x' if use_short else long_string
263n/a use_short = not use_short
264n/a SetValue(key, 'changing_value', REG_SZ, s)
265n/a
266n/a thread = VeryActiveThread()
267n/a thread.start()
268n/a try:
269n/a with CreateKey(HKEY_CURRENT_USER,
270n/a test_key_name+'\\changing_value') as key:
271n/a for _ in range(1000):
272n/a num_subkeys, num_values, t = QueryInfoKey(key)
273n/a for i in range(num_values):
274n/a name = EnumValue(key, i)
275n/a QueryValue(key, name[0])
276n/a finally:
277n/a done = True
278n/a thread.join()
279n/a DeleteKey(HKEY_CURRENT_USER, test_key_name+'\\changing_value')
280n/a DeleteKey(HKEY_CURRENT_USER, test_key_name)
281n/a
282n/a def test_long_key(self):
283n/a # Issue2810, in 2.6 and 3.1 when the key name was exactly 256
284n/a # characters, EnumKey raised "WindowsError: More data is
285n/a # available"
286n/a name = 'x'*256
287n/a try:
288n/a with CreateKey(HKEY_CURRENT_USER, test_key_name) as key:
289n/a SetValue(key, name, REG_SZ, 'x')
290n/a num_subkeys, num_values, t = QueryInfoKey(key)
291n/a EnumKey(key, 0)
292n/a finally:
293n/a DeleteKey(HKEY_CURRENT_USER, '\\'.join((test_key_name, name)))
294n/a DeleteKey(HKEY_CURRENT_USER, test_key_name)
295n/a
296n/a def test_dynamic_key(self):
297n/a # Issue2810, when the value is dynamically generated, these
298n/a # raise "WindowsError: More data is available" in 2.6 and 3.1
299n/a try:
300n/a EnumValue(HKEY_PERFORMANCE_DATA, 0)
301n/a except OSError as e:
302n/a if e.errno in (errno.EPERM, errno.EACCES):
303n/a self.skipTest("access denied to registry key "
304n/a "(are you running in a non-interactive session?)")
305n/a raise
306n/a QueryValueEx(HKEY_PERFORMANCE_DATA, "")
307n/a
308n/a # Reflection requires XP x64/Vista at a minimum. XP doesn't have this stuff
309n/a # or DeleteKeyEx so make sure their use raises NotImplementedError
310n/a @unittest.skipUnless(WIN_VER < (5, 2), "Requires Windows XP")
311n/a def test_reflection_unsupported(self):
312n/a try:
313n/a with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
314n/a self.assertNotEqual(ck.handle, 0)
315n/a
316n/a key = OpenKey(HKEY_CURRENT_USER, test_key_name)
317n/a self.assertNotEqual(key.handle, 0)
318n/a
319n/a with self.assertRaises(NotImplementedError):
320n/a DisableReflectionKey(key)
321n/a with self.assertRaises(NotImplementedError):
322n/a EnableReflectionKey(key)
323n/a with self.assertRaises(NotImplementedError):
324n/a QueryReflectionKey(key)
325n/a with self.assertRaises(NotImplementedError):
326n/a DeleteKeyEx(HKEY_CURRENT_USER, test_key_name)
327n/a finally:
328n/a DeleteKey(HKEY_CURRENT_USER, test_key_name)
329n/a
330n/a def test_setvalueex_value_range(self):
331n/a # Test for Issue #14420, accept proper ranges for SetValueEx.
332n/a # Py2Reg, which gets called by SetValueEx, was using PyLong_AsLong,
333n/a # thus raising OverflowError. The implementation now uses
334n/a # PyLong_AsUnsignedLong to match DWORD's size.
335n/a try:
336n/a with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
337n/a self.assertNotEqual(ck.handle, 0)
338n/a SetValueEx(ck, "test_name", None, REG_DWORD, 0x80000000)
339n/a finally:
340n/a DeleteKey(HKEY_CURRENT_USER, test_key_name)
341n/a
342n/a def test_queryvalueex_return_value(self):
343n/a # Test for Issue #16759, return unsigned int from QueryValueEx.
344n/a # Reg2Py, which gets called by QueryValueEx, was returning a value
345n/a # generated by PyLong_FromLong. The implementation now uses
346n/a # PyLong_FromUnsignedLong to match DWORD's size.
347n/a try:
348n/a with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
349n/a self.assertNotEqual(ck.handle, 0)
350n/a test_val = 0x80000000
351n/a SetValueEx(ck, "test_name", None, REG_DWORD, test_val)
352n/a ret_val, ret_type = QueryValueEx(ck, "test_name")
353n/a self.assertEqual(ret_type, REG_DWORD)
354n/a self.assertEqual(ret_val, test_val)
355n/a finally:
356n/a DeleteKey(HKEY_CURRENT_USER, test_key_name)
357n/a
358n/a def test_setvalueex_crash_with_none_arg(self):
359n/a # Test for Issue #21151, segfault when None is passed to SetValueEx
360n/a try:
361n/a with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
362n/a self.assertNotEqual(ck.handle, 0)
363n/a test_val = None
364n/a SetValueEx(ck, "test_name", 0, REG_BINARY, test_val)
365n/a ret_val, ret_type = QueryValueEx(ck, "test_name")
366n/a self.assertEqual(ret_type, REG_BINARY)
367n/a self.assertEqual(ret_val, test_val)
368n/a finally:
369n/a DeleteKey(HKEY_CURRENT_USER, test_key_name)
370n/a
371n/a def test_read_string_containing_null(self):
372n/a # Test for issue 25778: REG_SZ should not contain null characters
373n/a try:
374n/a with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
375n/a self.assertNotEqual(ck.handle, 0)
376n/a test_val = "A string\x00 with a null"
377n/a SetValueEx(ck, "test_name", 0, REG_SZ, test_val)
378n/a ret_val, ret_type = QueryValueEx(ck, "test_name")
379n/a self.assertEqual(ret_type, REG_SZ)
380n/a self.assertEqual(ret_val, "A string")
381n/a finally:
382n/a DeleteKey(HKEY_CURRENT_USER, test_key_name)
383n/a
384n/a
385n/a@unittest.skipUnless(REMOTE_NAME, "Skipping remote registry tests")
386n/aclass RemoteWinregTests(BaseWinregTests):
387n/a
388n/a def test_remote_registry_works(self):
389n/a remote_key = ConnectRegistry(REMOTE_NAME, HKEY_CURRENT_USER)
390n/a self._test_all(remote_key)
391n/a
392n/a
393n/a@unittest.skipUnless(WIN64_MACHINE, "x64 specific registry tests")
394n/aclass Win64WinregTests(BaseWinregTests):
395n/a
396n/a def test_named_arguments(self):
397n/a self._test_named_args(HKEY_CURRENT_USER, test_key_name)
398n/a # Clean up and also exercise the named arguments
399n/a DeleteKeyEx(key=HKEY_CURRENT_USER, sub_key=test_key_name,
400n/a access=KEY_ALL_ACCESS, reserved=0)
401n/a
402n/a def test_reflection_functions(self):
403n/a # Test that we can call the query, enable, and disable functions
404n/a # on a key which isn't on the reflection list with no consequences.
405n/a with OpenKey(HKEY_LOCAL_MACHINE, "Software") as key:
406n/a # HKLM\Software is redirected but not reflected in all OSes
407n/a self.assertTrue(QueryReflectionKey(key))
408n/a self.assertIsNone(EnableReflectionKey(key))
409n/a self.assertIsNone(DisableReflectionKey(key))
410n/a self.assertTrue(QueryReflectionKey(key))
411n/a
412n/a @unittest.skipUnless(HAS_REFLECTION, "OS doesn't support reflection")
413n/a def test_reflection(self):
414n/a # Test that we can create, open, and delete keys in the 32-bit
415n/a # area. Because we are doing this in a key which gets reflected,
416n/a # test the differences of 32 and 64-bit keys before and after the
417n/a # reflection occurs (ie. when the created key is closed).
418n/a try:
419n/a with CreateKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
420n/a KEY_ALL_ACCESS | KEY_WOW64_32KEY) as created_key:
421n/a self.assertNotEqual(created_key.handle, 0)
422n/a
423n/a # The key should now be available in the 32-bit area
424n/a with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
425n/a KEY_ALL_ACCESS | KEY_WOW64_32KEY) as key:
426n/a self.assertNotEqual(key.handle, 0)
427n/a
428n/a # Write a value to what currently is only in the 32-bit area
429n/a SetValueEx(created_key, "", 0, REG_SZ, "32KEY")
430n/a
431n/a # The key is not reflected until created_key is closed.
432n/a # The 64-bit version of the key should not be available yet.
433n/a open_fail = lambda: OpenKey(HKEY_CURRENT_USER,
434n/a test_reflect_key_name, 0,
435n/a KEY_READ | KEY_WOW64_64KEY)
436n/a self.assertRaises(OSError, open_fail)
437n/a
438n/a # Now explicitly open the 64-bit version of the key
439n/a with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
440n/a KEY_ALL_ACCESS | KEY_WOW64_64KEY) as key:
441n/a self.assertNotEqual(key.handle, 0)
442n/a # Make sure the original value we set is there
443n/a self.assertEqual("32KEY", QueryValue(key, ""))
444n/a # Set a new value, which will get reflected to 32-bit
445n/a SetValueEx(key, "", 0, REG_SZ, "64KEY")
446n/a
447n/a # Reflection uses a "last-writer wins policy, so the value we set
448n/a # on the 64-bit key should be the same on 32-bit
449n/a with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
450n/a KEY_READ | KEY_WOW64_32KEY) as key:
451n/a self.assertEqual("64KEY", QueryValue(key, ""))
452n/a finally:
453n/a DeleteKeyEx(HKEY_CURRENT_USER, test_reflect_key_name,
454n/a KEY_WOW64_32KEY, 0)
455n/a
456n/a @unittest.skipUnless(HAS_REFLECTION, "OS doesn't support reflection")
457n/a def test_disable_reflection(self):
458n/a # Make use of a key which gets redirected and reflected
459n/a try:
460n/a with CreateKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
461n/a KEY_ALL_ACCESS | KEY_WOW64_32KEY) as created_key:
462n/a # QueryReflectionKey returns whether or not the key is disabled
463n/a disabled = QueryReflectionKey(created_key)
464n/a self.assertEqual(type(disabled), bool)
465n/a # HKCU\Software\Classes is reflected by default
466n/a self.assertFalse(disabled)
467n/a
468n/a DisableReflectionKey(created_key)
469n/a self.assertTrue(QueryReflectionKey(created_key))
470n/a
471n/a # The key is now closed and would normally be reflected to the
472n/a # 64-bit area, but let's make sure that didn't happen.
473n/a open_fail = lambda: OpenKeyEx(HKEY_CURRENT_USER,
474n/a test_reflect_key_name, 0,
475n/a KEY_READ | KEY_WOW64_64KEY)
476n/a self.assertRaises(OSError, open_fail)
477n/a
478n/a # Make sure the 32-bit key is actually there
479n/a with OpenKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
480n/a KEY_READ | KEY_WOW64_32KEY) as key:
481n/a self.assertNotEqual(key.handle, 0)
482n/a finally:
483n/a DeleteKeyEx(HKEY_CURRENT_USER, test_reflect_key_name,
484n/a KEY_WOW64_32KEY, 0)
485n/a
486n/a def test_exception_numbers(self):
487n/a with self.assertRaises(FileNotFoundError) as ctx:
488n/a QueryValue(HKEY_CLASSES_ROOT, 'some_value_that_does_not_exist')
489n/a
490n/adef test_main():
491n/a support.run_unittest(LocalWinregTests, RemoteWinregTests,
492n/a Win64WinregTests)
493n/a
494n/aif __name__ == "__main__":
495n/a if not REMOTE_NAME:
496n/a print("Remote registry calls can be tested using",
497n/a "'test_winreg.py --remote \\\\machine_name'")
498n/a test_main()