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