test_win32api.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # General test module for win32api - please add some :)
  2. import unittest
  3. from pywin32_testutil import str2bytes
  4. import win32api, win32con, win32event, winerror
  5. import sys, os
  6. import tempfile
  7. import datetime
  8. class CurrentUserTestCase(unittest.TestCase):
  9. def testGetCurrentUser(self):
  10. name = "%s\\%s" % (win32api.GetDomainName(), win32api.GetUserName())
  11. self.failUnless(name == win32api.GetUserNameEx(win32api.NameSamCompatible))
  12. class TestTime(unittest.TestCase):
  13. def testTimezone(self):
  14. # GetTimeZoneInformation
  15. rc, tzinfo = win32api.GetTimeZoneInformation()
  16. if rc == win32con.TIME_ZONE_ID_DAYLIGHT:
  17. tz_str = tzinfo[4]
  18. tz_time = tzinfo[5]
  19. else:
  20. tz_str = tzinfo[1]
  21. tz_time = tzinfo[2]
  22. # for the sake of code exercise but don't output
  23. tz_str.encode()
  24. if not isinstance(tz_time, datetime.datetime) and not isinstance(tz_time, tuple):
  25. tz_time.Format()
  26. def TestDateFormat(self):
  27. DATE_LONGDATE = 2
  28. date_flags = DATE_LONGDATE
  29. win32api.GetDateFormat(0, date_flags, None)
  30. win32api.GetDateFormat(0, date_flags, 0)
  31. win32api.GetDateFormat(0, date_flags, datetime.datetime.now())
  32. win32api.GetDateFormat(0, date_flags, time.time())
  33. def TestTimeFormat(self):
  34. win32api.GetTimeFormat(0, 0, None)
  35. win32api.GetTimeFormat(0, 0, 0)
  36. win32api.GetTimeFormat(0, 0, datetime.datetime.now())
  37. win32api.GetTimeFormat(0, 0, time.time())
  38. class Registry(unittest.TestCase):
  39. key_name = r'PythonTestHarness\Whatever'
  40. def test1(self):
  41. # This used to leave a stale exception behind.
  42. def reg_operation():
  43. hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name)
  44. x = 3/0 # or a statement like: raise 'error'
  45. # do the test
  46. try:
  47. try:
  48. try:
  49. reg_operation()
  50. except:
  51. 1/0 # Force exception
  52. finally:
  53. win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name)
  54. except ZeroDivisionError:
  55. pass
  56. def testValues(self):
  57. key_name = r'PythonTestHarness\win32api'
  58. ## tuples containing value name, value type, data
  59. values=(
  60. (None, win32con.REG_SZ, 'This is default unnamed value'),
  61. ('REG_SZ', win32con.REG_SZ,'REG_SZ text data'),
  62. ('REG_EXPAND_SZ', win32con.REG_EXPAND_SZ, '%systemdir%'),
  63. ## REG_MULTI_SZ value needs to be a list since strings are returned as a list
  64. ('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1','string 2','string 3','string 4']),
  65. ('REG_MULTI_SZ_empty', win32con.REG_MULTI_SZ, []),
  66. ('REG_DWORD', win32con.REG_DWORD, 666),
  67. ('REG_QWORD_INT', win32con.REG_QWORD, 99),
  68. ('REG_QWORD', win32con.REG_QWORD, 2**33),
  69. ('REG_BINARY', win32con.REG_BINARY, str2bytes('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00')),
  70. )
  71. hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, key_name)
  72. for value_name, reg_type, data in values:
  73. win32api.RegSetValueEx(hkey, value_name, None, reg_type, data)
  74. for value_name, orig_type, orig_data in values:
  75. data, typ=win32api.RegQueryValueEx(hkey, value_name)
  76. self.assertEqual(typ, orig_type)
  77. self.assertEqual(data, orig_data)
  78. def testNotifyChange(self):
  79. def change():
  80. hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name)
  81. try:
  82. win32api.RegSetValue(hkey, None, win32con.REG_SZ, "foo")
  83. finally:
  84. win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name)
  85. evt = win32event.CreateEvent(None,0,0,None)
  86. ## REG_NOTIFY_CHANGE_LAST_SET - values
  87. ## REG_CHANGE_NOTIFY_NAME - keys
  88. ## REG_NOTIFY_CHANGE_SECURITY - security descriptor
  89. ## REG_NOTIFY_CHANGE_ATTRIBUTES
  90. win32api.RegNotifyChangeKeyValue(win32con.HKEY_CURRENT_USER,1,win32api.REG_NOTIFY_CHANGE_LAST_SET,evt,True)
  91. ret_code=win32event.WaitForSingleObject(evt,0)
  92. # Should be no change.
  93. self.failUnless(ret_code==win32con.WAIT_TIMEOUT)
  94. change()
  95. # Our event should now be in a signalled state.
  96. ret_code=win32event.WaitForSingleObject(evt,0)
  97. self.failUnless(ret_code==win32con.WAIT_OBJECT_0)
  98. class FileNames(unittest.TestCase):
  99. def testShortLongPathNames(self):
  100. try:
  101. me = __file__
  102. except NameError:
  103. me = sys.argv[0]
  104. fname = os.path.abspath(me).lower()
  105. short_name = win32api.GetShortPathName(fname).lower()
  106. long_name = win32api.GetLongPathName(short_name).lower()
  107. self.failUnless(long_name==fname, \
  108. "Expected long name ('%s') to be original name ('%s')" % (long_name, fname))
  109. self.failUnlessEqual(long_name, win32api.GetLongPathNameW(short_name).lower())
  110. long_name = win32api.GetLongPathNameW(short_name).lower()
  111. self.failUnless(type(long_name)==str, "GetLongPathNameW returned type '%s'" % (type(long_name),))
  112. self.failUnless(long_name==fname, \
  113. "Expected long name ('%s') to be original name ('%s')" % (long_name, fname))
  114. def testShortUnicodeNames(self):
  115. try:
  116. me = __file__
  117. except NameError:
  118. me = sys.argv[0]
  119. fname = os.path.abspath(me).lower()
  120. # passing unicode should cause GetShortPathNameW to be called.
  121. short_name = win32api.GetShortPathName(str(fname)).lower()
  122. self.failUnless(isinstance(short_name, str))
  123. long_name = win32api.GetLongPathName(short_name).lower()
  124. self.failUnless(long_name==fname, \
  125. "Expected long name ('%s') to be original name ('%s')" % (long_name, fname))
  126. self.failUnlessEqual(long_name, win32api.GetLongPathNameW(short_name).lower())
  127. long_name = win32api.GetLongPathNameW(short_name).lower()
  128. self.failUnless(type(long_name)==str, "GetLongPathNameW returned type '%s'" % (type(long_name),))
  129. self.failUnless(long_name==fname, \
  130. "Expected long name ('%s') to be original name ('%s')" % (long_name, fname))
  131. def testLongLongPathNames(self):
  132. # We need filename where the FQN is > 256 - simplest way is to create a
  133. # 250 character directory in the cwd (except - cwd may be on a drive
  134. # not supporting \\\\?\\ (eg, network share) - so use temp.
  135. import win32file
  136. basename = "a" * 250
  137. # but we need to ensure we use the 'long' version of the
  138. # temp dir for later comparison.
  139. long_temp_dir = win32api.GetLongPathNameW(tempfile.gettempdir())
  140. fname = "\\\\?\\" + os.path.join(long_temp_dir, basename)
  141. try:
  142. win32file.CreateDirectoryW(fname, None)
  143. except win32api.error as details:
  144. if details.winerror!=winerror.ERROR_ALREADY_EXISTS:
  145. raise
  146. try:
  147. # GetFileAttributes automatically calls GetFileAttributesW when
  148. # passed unicode
  149. try:
  150. attr = win32api.GetFileAttributes(fname)
  151. except win32api.error as details:
  152. if details.winerror != winerror.ERROR_FILENAME_EXCED_RANGE:
  153. raise
  154. attr = win32api.GetFileAttributes(str(fname))
  155. self.failUnless(attr & win32con.FILE_ATTRIBUTE_DIRECTORY, attr)
  156. long_name = win32api.GetLongPathNameW(fname)
  157. self.failUnlessEqual(long_name.lower(), fname.lower())
  158. finally:
  159. win32file.RemoveDirectory(fname)
  160. class FormatMessage(unittest.TestCase):
  161. def test_FromString(self):
  162. msg = "Hello %1, how are you %2?"
  163. inserts = ["Mark", "today"]
  164. result = win32api.FormatMessage(win32con.FORMAT_MESSAGE_FROM_STRING,
  165. msg, # source
  166. 0, # ID
  167. 0, # LangID
  168. inserts)
  169. self.assertEqual(result, "Hello Mark, how are you today?")
  170. class Misc(unittest.TestCase):
  171. def test_last_error(self):
  172. for x in (0, 1, -1, winerror.TRUST_E_PROVIDER_UNKNOWN):
  173. win32api.SetLastError(x)
  174. self.failUnlessEqual(x, win32api.GetLastError())
  175. def testVkKeyScan(self):
  176. # hopefully ' ' doesn't depend on the locale!
  177. self.failUnlessEqual(win32api.VkKeyScan(' '), 32)
  178. def testVkKeyScanEx(self):
  179. # hopefully ' ' doesn't depend on the locale!
  180. self.failUnlessEqual(win32api.VkKeyScanEx(' ', 0), 32)
  181. if __name__ == '__main__':
  182. unittest.main()