blob: 0c1bf294631746088dda643e4b826aa1aa71f323 [file] [log] [blame]
Guido van Rossumde598552000-03-28 20:36:51 +00001# Test the windows specific win32reg module.
2# Only win32reg functions not hit here: FlushKey, LoadKey and SaveKey
3
Guido van Rossumde598552000-03-28 20:36:51 +00004import os, sys
Thomas Woutersed03b412007-08-28 21:37:11 +00005import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Brian Curtin60853212010-05-26 17:43:50 +00007threading = support.import_module("threading")
Brian Curtin3035c392010-04-21 23:56:21 +00008from platform import machine
Fredrik Lundhf7850422001-01-17 21:51:36 +00009
R. David Murraya21e4ca2009-03-31 23:16:50 +000010# Do this first so test will be skipped if module doesn't exist
11support.import_module('winreg')
12# Now import everything
13from winreg import *
14
Brian Curtin3035c392010-04-21 23:56:21 +000015try:
16 REMOTE_NAME = sys.argv[sys.argv.index("--remote")+1]
17except (IndexError, ValueError):
18 REMOTE_NAME = None
19
20# tuple of (major, minor)
21WIN_VER = sys.getwindowsversion()[:2]
22# Some tests should only run on 64-bit architectures where WOW64 will be.
23WIN64_MACHINE = True if machine() == "AMD64" else False
24
25# Starting with Windows 7 and Windows Server 2008 R2, WOW64 no longer uses
26# registry reflection and formerly reflected keys are shared instead.
27# Windows 7 and Windows Server 2008 R2 are version 6.1. Due to this, some
28# tests are only valid up until 6.1
29HAS_REFLECTION = True if WIN_VER < (6, 1) else False
30
Guido van Rossumde598552000-03-28 20:36:51 +000031test_key_name = "SOFTWARE\\Python Registry Test Key - Delete Me"
Brian Curtin3035c392010-04-21 23:56:21 +000032# On OS'es that support reflection we should test with a reflected key
33test_reflect_key_name = "SOFTWARE\\Classes\\Python Test Key - Delete Me"
Guido van Rossumde598552000-03-28 20:36:51 +000034
35test_data = [
36 ("Int Value", 45, REG_DWORD),
Guido van Rossum0a185522003-11-30 22:46:18 +000037 ("String Val", "A string value", REG_SZ),
Guido van Rossumde598552000-03-28 20:36:51 +000038 ("StringExpand", "The path is %path%", REG_EXPAND_SZ),
Guido van Rossumde598552000-03-28 20:36:51 +000039 ("Multi-string", ["Lots", "of", "string", "values"], REG_MULTI_SZ),
Thomas Woutersed03b412007-08-28 21:37:11 +000040 ("Raw Data", b"binary\x00data", REG_BINARY),
Guido van Rossum291481b2003-12-03 15:24:02 +000041 ("Big String", "x"*(2**14-1), REG_SZ),
Guido van Rossuma8c360e2007-07-17 20:50:43 +000042 ("Big Binary", b"x"*(2**14), REG_BINARY),
Martin v. Löwisf82d9b52007-09-03 07:43:05 +000043 # Two and three kanjis, meaning: "Japan" and "Japanese")
44 ("Japanese 日本", "日本語", REG_SZ),
Guido van Rossumde598552000-03-28 20:36:51 +000045]
46
Brian Curtin3035c392010-04-21 23:56:21 +000047class BaseWinregTests(unittest.TestCase):
Guido van Rossumde598552000-03-28 20:36:51 +000048
Martin v. Löwisb7a51562009-06-07 17:55:17 +000049 def setUp(self):
50 # Make sure that the test key is absent when the test
51 # starts.
52 self.delete_tree(HKEY_CURRENT_USER, test_key_name)
53
54 def delete_tree(self, root, subkey):
55 try:
56 hkey = OpenKey(root, subkey, KEY_ALL_ACCESS)
57 except WindowsError:
58 # subkey does not exist
59 return
60 while True:
61 try:
62 subsubkey = EnumKey(hkey, 0)
63 except WindowsError:
64 # no more subkeys
65 break
66 self.delete_tree(hkey, subsubkey)
67 CloseKey(hkey)
68 DeleteKey(root, subkey)
69
Brian Curtin3035c392010-04-21 23:56:21 +000070 def _write_test_data(self, root_key, subkeystr="sub_key",
71 CreateKey=CreateKey):
Thomas Woutersed03b412007-08-28 21:37:11 +000072 # Set the default value for this key.
73 SetValue(root_key, test_key_name, REG_SZ, "Default value")
74 key = CreateKey(root_key, test_key_name)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000075 self.assertTrue(key.handle != 0)
Thomas Woutersed03b412007-08-28 21:37:11 +000076 # Create a sub-key
Martin v. Löwisf82d9b52007-09-03 07:43:05 +000077 sub_key = CreateKey(key, subkeystr)
Thomas Woutersed03b412007-08-28 21:37:11 +000078 # Give the sub-key some named values
79
80 for value_name, value_data, value_type in test_data:
81 SetValueEx(sub_key, value_name, 0, value_type, value_data)
82
83 # Check we wrote as many items as we thought.
84 nkeys, nvalues, since_mod = QueryInfoKey(key)
Ezio Melottib3aedd42010-11-20 19:04:17 +000085 self.assertEqual(nkeys, 1, "Not the correct number of sub keys")
86 self.assertEqual(nvalues, 1, "Not the correct number of values")
Thomas Woutersed03b412007-08-28 21:37:11 +000087 nkeys, nvalues, since_mod = QueryInfoKey(sub_key)
Ezio Melottib3aedd42010-11-20 19:04:17 +000088 self.assertEqual(nkeys, 0, "Not the correct number of sub keys")
89 self.assertEqual(nvalues, len(test_data),
90 "Not the correct number of values")
Thomas Woutersed03b412007-08-28 21:37:11 +000091 # Close this key this way...
92 # (but before we do, copy the key as an integer - this allows
93 # us to test that the key really gets closed).
94 int_sub_key = int(sub_key)
95 CloseKey(sub_key)
96 try:
97 QueryInfoKey(int_sub_key)
98 self.fail("It appears the CloseKey() function does "
99 "not close the actual key!")
100 except EnvironmentError:
101 pass
102 # ... and close that key that way :-)
103 int_key = int(key)
104 key.Close()
105 try:
106 QueryInfoKey(int_key)
107 self.fail("It appears the key.Close() function "
108 "does not close the actual key!")
109 except EnvironmentError:
110 pass
111
Brian Curtin3035c392010-04-21 23:56:21 +0000112 def _read_test_data(self, root_key, subkeystr="sub_key", OpenKey=OpenKey):
Thomas Woutersed03b412007-08-28 21:37:11 +0000113 # Check we can get default value for this key.
114 val = QueryValue(root_key, test_key_name)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000115 self.assertEqual(val, "Default value",
116 "Registry didn't give back the correct value")
Thomas Woutersed03b412007-08-28 21:37:11 +0000117
118 key = OpenKey(root_key, test_key_name)
119 # Read the sub-keys
Thomas Hellere83ebd92008-01-24 10:31:31 +0000120 with OpenKey(key, subkeystr) as sub_key:
Christian Heimes2380ac72008-01-09 00:17:24 +0000121 # Check I can enumerate over the values.
122 index = 0
123 while 1:
124 try:
125 data = EnumValue(sub_key, index)
126 except EnvironmentError:
127 break
Ezio Melottib3aedd42010-11-20 19:04:17 +0000128 self.assertEqual(data in test_data, True,
129 "Didn't read back the correct test data")
Christian Heimes2380ac72008-01-09 00:17:24 +0000130 index = index + 1
Ezio Melottib3aedd42010-11-20 19:04:17 +0000131 self.assertEqual(index, len(test_data),
132 "Didn't read the correct number of items")
Christian Heimes2380ac72008-01-09 00:17:24 +0000133 # Check I can directly access each item
134 for value_name, value_data, value_type in test_data:
135 read_val, read_typ = QueryValueEx(sub_key, value_name)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000136 self.assertEqual(read_val, value_data,
137 "Could not directly read the value")
138 self.assertEqual(read_typ, value_type,
139 "Could not directly read the value")
Thomas Woutersed03b412007-08-28 21:37:11 +0000140 sub_key.Close()
141 # Enumerate our main key.
142 read_val = EnumKey(key, 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000143 self.assertEqual(read_val, subkeystr, "Read subkey value wrong")
Thomas Woutersed03b412007-08-28 21:37:11 +0000144 try:
145 EnumKey(key, 1)
146 self.fail("Was able to get a second key when I only have one!")
147 except EnvironmentError:
148 pass
149
150 key.Close()
151
Brian Curtin3035c392010-04-21 23:56:21 +0000152 def _delete_test_data(self, root_key, subkeystr="sub_key"):
Thomas Woutersed03b412007-08-28 21:37:11 +0000153 key = OpenKey(root_key, test_key_name, 0, KEY_ALL_ACCESS)
Martin v. Löwisf82d9b52007-09-03 07:43:05 +0000154 sub_key = OpenKey(key, subkeystr, 0, KEY_ALL_ACCESS)
Thomas Woutersed03b412007-08-28 21:37:11 +0000155 # It is not necessary to delete the values before deleting
156 # the key (although subkeys must not exist). We delete them
157 # manually just to prove we can :-)
158 for value_name, value_data, value_type in test_data:
159 DeleteValue(sub_key, value_name)
160
161 nkeys, nvalues, since_mod = QueryInfoKey(sub_key)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000162 self.assertEqual(nkeys, 0, "subkey not empty before delete")
163 self.assertEqual(nvalues, 0, "subkey not empty before delete")
Thomas Woutersed03b412007-08-28 21:37:11 +0000164 sub_key.Close()
Martin v. Löwisf82d9b52007-09-03 07:43:05 +0000165 DeleteKey(key, subkeystr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000166
167 try:
168 # Shouldnt be able to delete it twice!
Martin v. Löwisf82d9b52007-09-03 07:43:05 +0000169 DeleteKey(key, subkeystr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000170 self.fail("Deleting the key twice succeeded")
171 except EnvironmentError:
172 pass
173 key.Close()
174 DeleteKey(root_key, test_key_name)
175 # Opening should now fail!
176 try:
177 key = OpenKey(root_key, test_key_name)
178 self.fail("Could open the non-existent key")
179 except WindowsError: # Use this error name this time
180 pass
181
Brian Curtin3035c392010-04-21 23:56:21 +0000182 def _test_all(self, root_key, subkeystr="sub_key"):
183 self._write_test_data(root_key, subkeystr)
184 self._read_test_data(root_key, subkeystr)
185 self._delete_test_data(root_key, subkeystr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000186
Brian Curtin1771b542010-09-27 17:56:36 +0000187 def _test_named_args(self, key, sub_key):
188 with CreateKeyEx(key=key, sub_key=sub_key, reserved=0,
189 access=KEY_ALL_ACCESS) as ckey:
190 self.assertTrue(ckey.handle != 0)
191
192 with OpenKeyEx(key=key, sub_key=sub_key, reserved=0,
193 access=KEY_ALL_ACCESS) as okey:
194 self.assertTrue(okey.handle != 0)
195
196
Brian Curtin3035c392010-04-21 23:56:21 +0000197class LocalWinregTests(BaseWinregTests):
Thomas Woutersed03b412007-08-28 21:37:11 +0000198
Brian Curtin3035c392010-04-21 23:56:21 +0000199 def test_registry_works(self):
200 self._test_all(HKEY_CURRENT_USER)
201 self._test_all(HKEY_CURRENT_USER, "日本-subkey")
202
203 def test_registry_works_extended_functions(self):
204 # Substitute the regular CreateKey and OpenKey calls with their
205 # extended counterparts.
206 # Note: DeleteKeyEx is not used here because it is platform dependent
207 cke = lambda key, sub_key: CreateKeyEx(key, sub_key, 0, KEY_ALL_ACCESS)
208 self._write_test_data(HKEY_CURRENT_USER, CreateKey=cke)
209
210 oke = lambda key, sub_key: OpenKeyEx(key, sub_key, 0, KEY_READ)
211 self._read_test_data(HKEY_CURRENT_USER, OpenKey=oke)
212
213 self._delete_test_data(HKEY_CURRENT_USER)
214
Brian Curtin1771b542010-09-27 17:56:36 +0000215 def test_named_arguments(self):
216 self._test_named_args(HKEY_CURRENT_USER, test_key_name)
217 # Use the regular DeleteKey to clean up
218 # DeleteKeyEx takes named args and is tested separately
219 DeleteKey(HKEY_CURRENT_USER, test_key_name)
220
Brian Curtin3035c392010-04-21 23:56:21 +0000221 def test_connect_registry_to_local_machine_works(self):
Thomas Woutersed03b412007-08-28 21:37:11 +0000222 # perform minimal ConnectRegistry test which just invokes it
223 h = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
Brian Curtin3035c392010-04-21 23:56:21 +0000224 self.assertNotEqual(h.handle, 0)
Thomas Woutersed03b412007-08-28 21:37:11 +0000225 h.Close()
Brian Curtin3035c392010-04-21 23:56:21 +0000226 self.assertEqual(h.handle, 0)
Thomas Woutersed03b412007-08-28 21:37:11 +0000227
Brian Curtin3035c392010-04-21 23:56:21 +0000228 def test_inexistant_remote_registry(self):
229 connect = lambda: ConnectRegistry("abcdefghijkl", HKEY_CURRENT_USER)
230 self.assertRaises(WindowsError, connect)
Thomas Woutersed03b412007-08-28 21:37:11 +0000231
Christian Heimes2380ac72008-01-09 00:17:24 +0000232 def testExpandEnvironmentStrings(self):
233 r = ExpandEnvironmentStrings("%windir%\\test")
234 self.assertEqual(type(r), str)
235 self.assertEqual(r, os.environ["windir"] + "\\test")
236
Brian Curtin3035c392010-04-21 23:56:21 +0000237 def test_context_manager(self):
238 # ensure that the handle is closed if an exception occurs
239 try:
240 with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as h:
241 self.assertNotEqual(h.handle, 0)
242 raise WindowsError
243 except WindowsError:
244 self.assertEqual(h.handle, 0)
245
Brian Curtin60853212010-05-26 17:43:50 +0000246 def test_changing_value(self):
247 # Issue2810: A race condition in 2.6 and 3.1 may cause
248 # EnumValue or QueryValue to throw "WindowsError: More data is
249 # available"
250 done = False
251
252 class VeryActiveThread(threading.Thread):
253 def run(self):
254 with CreateKey(HKEY_CURRENT_USER, test_key_name) as key:
255 use_short = True
256 long_string = 'x'*2000
257 while not done:
258 s = 'x' if use_short else long_string
259 use_short = not use_short
260 SetValue(key, 'changing_value', REG_SZ, s)
261
262 thread = VeryActiveThread()
263 thread.start()
264 try:
265 with CreateKey(HKEY_CURRENT_USER,
266 test_key_name+'\\changing_value') as key:
267 for _ in range(1000):
268 num_subkeys, num_values, t = QueryInfoKey(key)
269 for i in range(num_values):
270 name = EnumValue(key, i)
271 QueryValue(key, name[0])
272 finally:
273 done = True
274 thread.join()
275 DeleteKey(HKEY_CURRENT_USER, test_key_name+'\\changing_value')
276 DeleteKey(HKEY_CURRENT_USER, test_key_name)
277
278 def test_long_key(self):
279 # Issue2810, in 2.6 and 3.1 when the key name was exactly 256
280 # characters, EnumKey threw "WindowsError: More data is
281 # available"
282 name = 'x'*256
283 try:
284 with CreateKey(HKEY_CURRENT_USER, test_key_name) as key:
285 SetValue(key, name, REG_SZ, 'x')
286 num_subkeys, num_values, t = QueryInfoKey(key)
287 EnumKey(key, 0)
288 finally:
289 DeleteKey(HKEY_CURRENT_USER, '\\'.join((test_key_name, name)))
290 DeleteKey(HKEY_CURRENT_USER, test_key_name)
291
292 def test_dynamic_key(self):
293 # Issue2810, when the value is dynamically generated, these
294 # throw "WindowsError: More data is available" in 2.6 and 3.1
295 EnumValue(HKEY_PERFORMANCE_DATA, 0)
296 QueryValueEx(HKEY_PERFORMANCE_DATA, "")
297
Brian Curtin3035c392010-04-21 23:56:21 +0000298 # Reflection requires XP x64/Vista at a minimum. XP doesn't have this stuff
299 # or DeleteKeyEx so make sure their use raises NotImplementedError
300 @unittest.skipUnless(WIN_VER < (5, 2), "Requires Windows XP")
301 def test_reflection_unsupported(self):
302 try:
303 with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
304 self.assertNotEqual(ck.handle, 0)
305
306 key = OpenKey(HKEY_CURRENT_USER, test_key_name)
307 self.assertNotEqual(key.handle, 0)
308
309 with self.assertRaises(NotImplementedError):
310 DisableReflectionKey(key)
311 with self.assertRaises(NotImplementedError):
312 EnableReflectionKey(key)
313 with self.assertRaises(NotImplementedError):
314 QueryReflectionKey(key)
315 with self.assertRaises(NotImplementedError):
316 DeleteKeyEx(HKEY_CURRENT_USER, test_key_name)
317 finally:
318 DeleteKey(HKEY_CURRENT_USER, test_key_name)
319
320
321@unittest.skipUnless(REMOTE_NAME, "Skipping remote registry tests")
322class RemoteWinregTests(BaseWinregTests):
323
324 def test_remote_registry_works(self):
325 remote_key = ConnectRegistry(REMOTE_NAME, HKEY_CURRENT_USER)
326 self._test_all(remote_key)
327
328
329@unittest.skipUnless(WIN64_MACHINE, "x64 specific registry tests")
330class Win64WinregTests(BaseWinregTests):
331
Brian Curtin1771b542010-09-27 17:56:36 +0000332 def test_named_arguments(self):
333 self._test_named_args(HKEY_CURRENT_USER, test_key_name)
334 # Clean up and also exercise the named arguments
335 DeleteKeyEx(key=HKEY_CURRENT_USER, sub_key=test_key_name,
336 access=KEY_ALL_ACCESS, reserved=0)
337
Brian Curtin3035c392010-04-21 23:56:21 +0000338 def test_reflection_functions(self):
339 # Test that we can call the query, enable, and disable functions
340 # on a key which isn't on the reflection list with no consequences.
341 with OpenKey(HKEY_LOCAL_MACHINE, "Software") as key:
342 # HKLM\Software is redirected but not reflected in all OSes
343 self.assertTrue(QueryReflectionKey(key))
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000344 self.assertIsNone(EnableReflectionKey(key))
345 self.assertIsNone(DisableReflectionKey(key))
Brian Curtin3035c392010-04-21 23:56:21 +0000346 self.assertTrue(QueryReflectionKey(key))
347
348 @unittest.skipUnless(HAS_REFLECTION, "OS doesn't support reflection")
349 def test_reflection(self):
350 # Test that we can create, open, and delete keys in the 32-bit
351 # area. Because we are doing this in a key which gets reflected,
352 # test the differences of 32 and 64-bit keys before and after the
353 # reflection occurs (ie. when the created key is closed).
354 try:
355 with CreateKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
356 KEY_ALL_ACCESS | KEY_WOW64_32KEY) as created_key:
357 self.assertNotEqual(created_key.handle, 0)
358
359 # The key should now be available in the 32-bit area
360 with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
361 KEY_ALL_ACCESS | KEY_WOW64_32KEY) as key:
362 self.assertNotEqual(key.handle, 0)
363
364 # Write a value to what currently is only in the 32-bit area
365 SetValueEx(created_key, "", 0, REG_SZ, "32KEY")
366
367 # The key is not reflected until created_key is closed.
368 # The 64-bit version of the key should not be available yet.
369 open_fail = lambda: OpenKey(HKEY_CURRENT_USER,
370 test_reflect_key_name, 0,
371 KEY_READ | KEY_WOW64_64KEY)
372 self.assertRaises(WindowsError, open_fail)
373
374 # Now explicitly open the 64-bit version of the key
375 with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
376 KEY_ALL_ACCESS | KEY_WOW64_64KEY) as key:
377 self.assertNotEqual(key.handle, 0)
378 # Make sure the original value we set is there
379 self.assertEqual("32KEY", QueryValue(key, ""))
380 # Set a new value, which will get reflected to 32-bit
381 SetValueEx(key, "", 0, REG_SZ, "64KEY")
382
383 # Reflection uses a "last-writer wins policy, so the value we set
384 # on the 64-bit key should be the same on 32-bit
385 with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,
386 KEY_READ | KEY_WOW64_32KEY) as key:
387 self.assertEqual("64KEY", QueryValue(key, ""))
388 finally:
389 DeleteKeyEx(HKEY_CURRENT_USER, test_reflect_key_name,
390 KEY_WOW64_32KEY, 0)
391
392 @unittest.skipUnless(HAS_REFLECTION, "OS doesn't support reflection")
393 def test_disable_reflection(self):
394 # Make use of a key which gets redirected and reflected
395 try:
396 with CreateKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
397 KEY_ALL_ACCESS | KEY_WOW64_32KEY) as created_key:
398 # QueryReflectionKey returns whether or not the key is disabled
399 disabled = QueryReflectionKey(created_key)
400 self.assertEqual(type(disabled), bool)
401 # HKCU\Software\Classes is reflected by default
402 self.assertFalse(disabled)
403
404 DisableReflectionKey(created_key)
405 self.assertTrue(QueryReflectionKey(created_key))
406
407 # The key is now closed and would normally be reflected to the
408 # 64-bit area, but let's make sure that didn't happen.
409 open_fail = lambda: OpenKeyEx(HKEY_CURRENT_USER,
410 test_reflect_key_name, 0,
411 KEY_READ | KEY_WOW64_64KEY)
412 self.assertRaises(WindowsError, open_fail)
413
414 # Make sure the 32-bit key is actually there
415 with OpenKeyEx(HKEY_CURRENT_USER, test_reflect_key_name, 0,
416 KEY_READ | KEY_WOW64_32KEY) as key:
417 self.assertNotEqual(key.handle, 0)
418 finally:
419 DeleteKeyEx(HKEY_CURRENT_USER, test_reflect_key_name,
420 KEY_WOW64_32KEY, 0)
421
422
Thomas Woutersed03b412007-08-28 21:37:11 +0000423def test_main():
Brian Curtin3035c392010-04-21 23:56:21 +0000424 support.run_unittest(LocalWinregTests, RemoteWinregTests,
425 Win64WinregTests)
Thomas Woutersed03b412007-08-28 21:37:11 +0000426
427if __name__ == "__main__":
Brian Curtin3035c392010-04-21 23:56:21 +0000428 if not REMOTE_NAME:
Thomas Woutersed03b412007-08-28 21:37:11 +0000429 print("Remote registry calls can be tested using",
430 "'test_winreg.py --remote \\\\machine_name'")
Thomas Woutersed03b412007-08-28 21:37:11 +0000431 test_main()