Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_win32api.py 9.5KB

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