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