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