test_win32file.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. import unittest
  2. from pywin32_testutil import str2bytes, TestSkipped, testmain
  3. import win32api, win32file, win32pipe, pywintypes, winerror, win32event
  4. import win32con, ntsecuritycon
  5. import sys
  6. import os
  7. import tempfile
  8. import threading
  9. import time
  10. import shutil
  11. import socket
  12. import datetime
  13. import random
  14. import win32timezone
  15. try:
  16. set
  17. except NameError:
  18. from sets import Set as set
  19. class TestReadBuffer(unittest.TestCase):
  20. def testLen(self):
  21. buffer = win32file.AllocateReadBuffer(1)
  22. self.failUnlessEqual(len(buffer), 1)
  23. def testSimpleIndex(self):
  24. buffer = win32file.AllocateReadBuffer(1)
  25. buffer[0] = 0xFF
  26. self.assertEqual(buffer[0], 0xFF)
  27. def testSimpleSlice(self):
  28. buffer = win32file.AllocateReadBuffer(2)
  29. val = str2bytes('\0\0')
  30. buffer[:2] = val
  31. self.failUnlessEqual(buffer[0:2], val)
  32. class TestSimpleOps(unittest.TestCase):
  33. def testSimpleFiles(self):
  34. fd, filename = tempfile.mkstemp()
  35. os.close(fd)
  36. os.unlink(filename)
  37. handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None)
  38. test_data = str2bytes("Hello\0there")
  39. try:
  40. win32file.WriteFile(handle, test_data)
  41. handle.Close()
  42. # Try and open for read
  43. handle = win32file.CreateFile(filename, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
  44. rc, data = win32file.ReadFile(handle, 1024)
  45. self.assertEquals(data, test_data)
  46. finally:
  47. handle.Close()
  48. try:
  49. os.unlink(filename)
  50. except os.error:
  51. pass
  52. # A simple test using normal read/write operations.
  53. def testMoreFiles(self):
  54. # Create a file in the %TEMP% directory.
  55. testName = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )
  56. desiredAccess = win32file.GENERIC_READ | win32file.GENERIC_WRITE
  57. # Set a flag to delete the file automatically when it is closed.
  58. fileFlags = win32file.FILE_FLAG_DELETE_ON_CLOSE
  59. h = win32file.CreateFile( testName, desiredAccess, win32file.FILE_SHARE_READ, None, win32file.CREATE_ALWAYS, fileFlags, 0)
  60. # Write a known number of bytes to the file.
  61. data = str2bytes("z") * 1025
  62. win32file.WriteFile(h, data)
  63. self.failUnless(win32file.GetFileSize(h) == len(data), "WARNING: Written file does not have the same size as the length of the data in it!")
  64. # Ensure we can read the data back.
  65. win32file.SetFilePointer(h, 0, win32file.FILE_BEGIN)
  66. hr, read_data = win32file.ReadFile(h, len(data)+10) # + 10 to get anything extra
  67. self.failUnless(hr==0, "Readfile returned %d" % hr)
  68. self.failUnless(read_data == data, "Read data is not what we wrote!")
  69. # Now truncate the file at 1/2 its existing size.
  70. newSize = len(data)//2
  71. win32file.SetFilePointer(h, newSize, win32file.FILE_BEGIN)
  72. win32file.SetEndOfFile(h)
  73. self.failUnlessEqual(win32file.GetFileSize(h), newSize)
  74. # GetFileAttributesEx/GetFileAttributesExW tests.
  75. self.failUnlessEqual(win32file.GetFileAttributesEx(testName), win32file.GetFileAttributesExW(testName))
  76. attr, ct, at, wt, size = win32file.GetFileAttributesEx(testName)
  77. self.failUnless(size==newSize,
  78. "Expected GetFileAttributesEx to return the same size as GetFileSize()")
  79. self.failUnless(attr==win32file.GetFileAttributes(testName),
  80. "Expected GetFileAttributesEx to return the same attributes as GetFileAttributes")
  81. h = None # Close the file by removing the last reference to the handle!
  82. self.failUnless(not os.path.isfile(testName), "After closing the file, it still exists!")
  83. def testFilePointer(self):
  84. # via [ 979270 ] SetFilePointer fails with negative offset
  85. # Create a file in the %TEMP% directory.
  86. filename = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )
  87. f = win32file.CreateFile(filename,
  88. win32file.GENERIC_READ|win32file.GENERIC_WRITE,
  89. 0,
  90. None,
  91. win32file.CREATE_ALWAYS,
  92. win32file.FILE_ATTRIBUTE_NORMAL,
  93. 0)
  94. try:
  95. #Write some data
  96. data = str2bytes('Some data')
  97. (res, written) = win32file.WriteFile(f, data)
  98. self.failIf(res)
  99. self.assertEqual(written, len(data))
  100. #Move at the beginning and read the data
  101. win32file.SetFilePointer(f, 0, win32file.FILE_BEGIN)
  102. (res, s) = win32file.ReadFile(f, len(data))
  103. self.failIf(res)
  104. self.assertEqual(s, data)
  105. #Move at the end and read the data
  106. win32file.SetFilePointer(f, -len(data), win32file.FILE_END)
  107. (res, s) = win32file.ReadFile(f, len(data))
  108. self.failIf(res)
  109. self.failUnlessEqual(s, data)
  110. finally:
  111. f.Close()
  112. os.unlink(filename)
  113. def testFileTimesTimezones(self):
  114. filename = tempfile.mktemp("-testFileTimes")
  115. # now() is always returning a timestamp with microseconds but the
  116. # file APIs all have zero microseconds, so some comparisons fail.
  117. now_utc = win32timezone.utcnow().replace(microsecond=0)
  118. now_local = now_utc.astimezone(win32timezone.TimeZoneInfo.local())
  119. h = win32file.CreateFile(filename,
  120. win32file.GENERIC_READ|win32file.GENERIC_WRITE,
  121. 0, None, win32file.CREATE_ALWAYS, 0, 0)
  122. try:
  123. win32file.SetFileTime(h, now_utc, now_utc, now_utc)
  124. ct, at, wt = win32file.GetFileTime(h)
  125. self.failUnlessEqual(now_local, ct)
  126. self.failUnlessEqual(now_local, at)
  127. self.failUnlessEqual(now_local, wt)
  128. # and the reverse - set local, check against utc
  129. win32file.SetFileTime(h, now_local, now_local, now_local)
  130. ct, at, wt = win32file.GetFileTime(h)
  131. self.failUnlessEqual(now_utc, ct)
  132. self.failUnlessEqual(now_utc, at)
  133. self.failUnlessEqual(now_utc, wt)
  134. finally:
  135. h.close()
  136. os.unlink(filename)
  137. def testFileTimes(self):
  138. from win32timezone import TimeZoneInfo
  139. # now() is always returning a timestamp with microseconds but the
  140. # file APIs all have zero microseconds, so some comparisons fail.
  141. now = datetime.datetime.now(tz=TimeZoneInfo.utc()).replace(microsecond=0)
  142. nowish = now + datetime.timedelta(seconds=1)
  143. later = now + datetime.timedelta(seconds=120)
  144. filename = tempfile.mktemp("-testFileTimes")
  145. # Windows docs the 'last time' isn't valid until the last write
  146. # handle is closed - so create the file, then re-open it to check.
  147. open(filename,"w").close()
  148. f = win32file.CreateFile(filename, win32file.GENERIC_READ|win32file.GENERIC_WRITE,
  149. 0, None,
  150. win32con.OPEN_EXISTING, 0, None)
  151. try:
  152. ct, at, wt = win32file.GetFileTime(f)
  153. self.failUnless(ct >= now, "File was created in the past - now=%s, created=%s" % (now, ct))
  154. self.failUnless( now <= ct <= nowish, (now, ct))
  155. self.failUnless(wt >= now, "File was written-to in the past now=%s, written=%s" % (now,wt))
  156. self.failUnless( now <= wt <= nowish, (now, wt))
  157. # Now set the times.
  158. win32file.SetFileTime(f, later, later, later, UTCTimes=True)
  159. # Get them back.
  160. ct, at, wt = win32file.GetFileTime(f)
  161. # XXX - the builtin PyTime type appears to be out by a dst offset.
  162. # just ignore that type here...
  163. self.failUnlessEqual(ct, later)
  164. self.failUnlessEqual(at, later)
  165. self.failUnlessEqual(wt, later)
  166. finally:
  167. f.Close()
  168. os.unlink(filename)
  169. class TestGetFileInfoByHandleEx(unittest.TestCase):
  170. __handle = __filename = None
  171. def setUp(self):
  172. fd, self.__filename = tempfile.mkstemp()
  173. os.close(fd)
  174. def tearDown(self):
  175. if self.__handle is not None:
  176. self.__handle.Close()
  177. if self.__filename is not None:
  178. try:
  179. os.unlink(self.__filename)
  180. except OSError:
  181. pass
  182. self.__handle = self.__filename = None
  183. def testFileBasicInfo(self):
  184. attr = win32file.GetFileAttributes(self.__filename)
  185. f = win32file.CreateFile(self.__filename, win32file.GENERIC_READ, 0, None,
  186. win32con.OPEN_EXISTING, 0, None)
  187. self.__handle = f
  188. ct, at, wt = win32file.GetFileTime(f)
  189. # bug #752: this throws ERROR_BAD_LENGTH (24) in x86 binaries of build 221
  190. basic_info = win32file.GetFileInformationByHandleEx(f, win32file.FileBasicInfo)
  191. self.assertEqual(ct, basic_info['CreationTime'])
  192. self.assertEqual(at, basic_info['LastAccessTime'])
  193. self.assertEqual(wt, basic_info['LastWriteTime'])
  194. self.assertEqual(attr, basic_info['FileAttributes'])
  195. class TestOverlapped(unittest.TestCase):
  196. def testSimpleOverlapped(self):
  197. # Create a file in the %TEMP% directory.
  198. import win32event
  199. testName = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )
  200. desiredAccess = win32file.GENERIC_WRITE
  201. overlapped = pywintypes.OVERLAPPED()
  202. evt = win32event.CreateEvent(None, 0, 0, None)
  203. overlapped.hEvent = evt
  204. # Create the file and write shit-loads of data to it.
  205. h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0)
  206. chunk_data = str2bytes("z") * 0x8000
  207. num_loops = 512
  208. expected_size = num_loops * len(chunk_data)
  209. for i in range(num_loops):
  210. win32file.WriteFile(h, chunk_data, overlapped)
  211. win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE)
  212. overlapped.Offset = overlapped.Offset + len(chunk_data)
  213. h.Close()
  214. # Now read the data back overlapped
  215. overlapped = pywintypes.OVERLAPPED()
  216. evt = win32event.CreateEvent(None, 0, 0, None)
  217. overlapped.hEvent = evt
  218. desiredAccess = win32file.GENERIC_READ
  219. h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.OPEN_EXISTING, 0, 0)
  220. buffer = win32file.AllocateReadBuffer(0xFFFF)
  221. while 1:
  222. try:
  223. hr, data = win32file.ReadFile(h, buffer, overlapped)
  224. win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE)
  225. overlapped.Offset = overlapped.Offset + len(data)
  226. if not data is buffer:
  227. self.fail("Unexpected result from ReadFile - should be the same buffer we passed it")
  228. except win32api.error:
  229. break
  230. h.Close()
  231. def testCompletionPortsMultiple(self):
  232. # Mainly checking that we can "associate" an existing handle. This
  233. # failed in build 203.
  234. ioport = win32file.CreateIoCompletionPort(win32file.INVALID_HANDLE_VALUE,
  235. 0, 0, 0)
  236. socks = []
  237. for PORT in range(9123, 9125):
  238. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  239. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  240. sock.bind(('', PORT))
  241. sock.listen(1)
  242. socks.append(sock)
  243. new = win32file.CreateIoCompletionPort(sock.fileno(), ioport, PORT, 0)
  244. assert new is ioport
  245. for s in socks:
  246. s.close()
  247. hv = int(ioport)
  248. ioport = new = None
  249. # The handle itself should be closed now (unless we leak references!)
  250. # Check that.
  251. try:
  252. win32file.CloseHandle(hv)
  253. raise RuntimeError("Expected close to fail!")
  254. except win32file.error as details:
  255. self.failUnlessEqual(details.winerror, winerror.ERROR_INVALID_HANDLE)
  256. def testCompletionPortsQueued(self):
  257. class Foo: pass
  258. io_req_port = win32file.CreateIoCompletionPort(-1, None, 0, 0)
  259. overlapped = pywintypes.OVERLAPPED()
  260. overlapped.object = Foo()
  261. win32file.PostQueuedCompletionStatus(io_req_port, 0, 99, overlapped)
  262. errCode, bytes, key, overlapped = \
  263. win32file.GetQueuedCompletionStatus(io_req_port, win32event.INFINITE)
  264. self.failUnlessEqual(errCode, 0)
  265. self.failUnless(isinstance(overlapped.object, Foo))
  266. def _IOCPServerThread(self, handle, port, drop_overlapped_reference):
  267. overlapped = pywintypes.OVERLAPPED()
  268. win32pipe.ConnectNamedPipe(handle, overlapped)
  269. if drop_overlapped_reference:
  270. # Be naughty - the overlapped object is now dead, but
  271. # GetQueuedCompletionStatus will still find it. Our check of
  272. # reference counting should catch that error.
  273. overlapped = None
  274. # even if we fail, be sure to close the handle; prevents hangs
  275. # on Vista 64...
  276. try:
  277. self.failUnlessRaises(RuntimeError,
  278. win32file.GetQueuedCompletionStatus, port, -1)
  279. finally:
  280. handle.Close()
  281. return
  282. result = win32file.GetQueuedCompletionStatus(port, -1)
  283. ol2 = result[-1]
  284. self.failUnless(ol2 is overlapped)
  285. data = win32file.ReadFile(handle, 512)[1]
  286. win32file.WriteFile(handle, data)
  287. def testCompletionPortsNonQueued(self, test_overlapped_death = 0):
  288. # In 204 we had a reference count bug when OVERLAPPED objects were
  289. # associated with a completion port other than via
  290. # PostQueuedCompletionStatus. This test is based on the reproduction
  291. # reported with that bug.
  292. # Create the pipe.
  293. BUFSIZE = 512
  294. pipe_name = r"\\.\pipe\pywin32_test_pipe"
  295. handle = win32pipe.CreateNamedPipe(pipe_name,
  296. win32pipe.PIPE_ACCESS_DUPLEX|
  297. win32file.FILE_FLAG_OVERLAPPED,
  298. win32pipe.PIPE_TYPE_MESSAGE|
  299. win32pipe.PIPE_READMODE_MESSAGE|
  300. win32pipe.PIPE_WAIT,
  301. 1, BUFSIZE, BUFSIZE,
  302. win32pipe.NMPWAIT_WAIT_FOREVER,
  303. None)
  304. # Create an IOCP and associate it with the handle.
  305. port = win32file.CreateIoCompletionPort(-1, 0, 0, 0)
  306. win32file.CreateIoCompletionPort(handle, port, 1, 0)
  307. t = threading.Thread(target=self._IOCPServerThread, args=(handle,port, test_overlapped_death))
  308. t.setDaemon(True) # avoid hanging entire test suite on failure.
  309. t.start()
  310. try:
  311. time.sleep(0.1) # let thread do its thing.
  312. try:
  313. win32pipe.CallNamedPipe(r"\\.\pipe\pywin32_test_pipe", str2bytes("Hello there"), BUFSIZE, 0)
  314. except win32pipe.error:
  315. # Testing for overlapped death causes this
  316. if not test_overlapped_death:
  317. raise
  318. finally:
  319. if not test_overlapped_death:
  320. handle.Close()
  321. t.join(3)
  322. self.failIf(t.is_alive(), "thread didn't finish")
  323. def testCompletionPortsNonQueuedBadReference(self):
  324. self.testCompletionPortsNonQueued(True)
  325. def testHashable(self):
  326. overlapped = pywintypes.OVERLAPPED()
  327. d = {}
  328. d[overlapped] = "hello"
  329. self.failUnlessEqual(d[overlapped], "hello")
  330. def testComparable(self):
  331. overlapped = pywintypes.OVERLAPPED()
  332. self.failUnlessEqual(overlapped, overlapped)
  333. # ensure we explicitly test the operators.
  334. self.failUnless(overlapped == overlapped)
  335. self.failIf(overlapped != overlapped)
  336. def testComparable2(self):
  337. # 2 overlapped objects compare equal if their contents are the same.
  338. overlapped1 = pywintypes.OVERLAPPED()
  339. overlapped2 = pywintypes.OVERLAPPED()
  340. self.failUnlessEqual(overlapped1, overlapped2)
  341. # ensure we explicitly test the operators.
  342. self.failUnless(overlapped1 == overlapped2)
  343. self.failIf(overlapped1 != overlapped2)
  344. # now change something in one of them - should no longer be equal.
  345. overlapped1.hEvent = 1
  346. self.failIfEqual(overlapped1, overlapped2)
  347. # ensure we explicitly test the operators.
  348. self.failIf(overlapped1 == overlapped2)
  349. self.failUnless(overlapped1 != overlapped2)
  350. class TestSocketExtensions(unittest.TestCase):
  351. def acceptWorker(self, port, running_event, stopped_event):
  352. listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  353. listener.bind(('', port))
  354. listener.listen(200)
  355. # create accept socket
  356. accepter = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  357. # An overlapped
  358. overlapped = pywintypes.OVERLAPPED()
  359. overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
  360. # accept the connection.
  361. # We used to allow strings etc to be passed here, and they would be
  362. # modified! Obviously this is evil :)
  363. buffer = " " * 1024 # EVIL - SHOULD NOT BE ALLOWED.
  364. self.assertRaises(TypeError, win32file.AcceptEx, listener, accepter, buffer, overlapped)
  365. # This is the correct way to allocate the buffer...
  366. buffer = win32file.AllocateReadBuffer(1024)
  367. rc = win32file.AcceptEx(listener, accepter, buffer, overlapped)
  368. self.failUnlessEqual(rc, winerror.ERROR_IO_PENDING)
  369. # Set the event to say we are all ready
  370. running_event.set()
  371. # and wait for the connection.
  372. rc = win32event.WaitForSingleObject(overlapped.hEvent, 2000)
  373. if rc == win32event.WAIT_TIMEOUT:
  374. self.fail("timed out waiting for a connection")
  375. nbytes = win32file.GetOverlappedResult(listener.fileno(), overlapped, False)
  376. #fam, loc, rem = win32file.GetAcceptExSockaddrs(accepter, buffer)
  377. accepter.send(buffer[:nbytes])
  378. # NOT set in a finally - this means *successfully* stopped!
  379. stopped_event.set()
  380. def testAcceptEx(self):
  381. port = 4680
  382. running = threading.Event()
  383. stopped = threading.Event()
  384. t = threading.Thread(target=self.acceptWorker, args=(port, running,stopped))
  385. t.start()
  386. running.wait(2)
  387. if not running.isSet():
  388. self.fail("AcceptEx Worker thread failed to start")
  389. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  390. s.connect(('127.0.0.1', port))
  391. win32file.WSASend(s, str2bytes("hello"), None)
  392. overlapped = pywintypes.OVERLAPPED()
  393. overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
  394. # Like above - WSARecv used to allow strings as the receive buffer!!
  395. buffer = " " * 10
  396. self.assertRaises(TypeError, win32file.WSARecv, s, buffer, overlapped)
  397. # This one should work :)
  398. buffer = win32file.AllocateReadBuffer(10)
  399. win32file.WSARecv(s, buffer, overlapped)
  400. nbytes = win32file.GetOverlappedResult(s.fileno(), overlapped, True)
  401. got = buffer[:nbytes]
  402. self.failUnlessEqual(got, str2bytes("hello"))
  403. # thread should have stopped
  404. stopped.wait(2)
  405. if not stopped.isSet():
  406. self.fail("AcceptEx Worker thread failed to successfully stop")
  407. class TestFindFiles(unittest.TestCase):
  408. def testIter(self):
  409. dir = os.path.join(os.getcwd(), "*")
  410. files = win32file.FindFilesW(dir)
  411. set1 = set()
  412. set1.update(files)
  413. set2 = set()
  414. for file in win32file.FindFilesIterator(dir):
  415. set2.add(file)
  416. assert len(set2) > 5, "This directory has less than 5 files!?"
  417. self.failUnlessEqual(set1, set2)
  418. def testBadDir(self):
  419. dir = os.path.join(os.getcwd(), "a dir that doesnt exist", "*")
  420. self.assertRaises(win32file.error, win32file.FindFilesIterator, dir)
  421. def testEmptySpec(self):
  422. spec = os.path.join(os.getcwd(), "*.foo_bar")
  423. num = 0
  424. for i in win32file.FindFilesIterator(spec):
  425. num += 1
  426. self.failUnlessEqual(0, num)
  427. def testEmptyDir(self):
  428. test_path = os.path.join(win32api.GetTempPath(), "win32file_test_directory")
  429. try:
  430. # Note: previously used shutil.rmtree, but when looking for
  431. # reference count leaks, that function showed leaks! os.rmdir
  432. # doesn't have that problem.
  433. os.rmdir(test_path)
  434. except os.error:
  435. pass
  436. os.mkdir(test_path)
  437. try:
  438. num = 0
  439. for i in win32file.FindFilesIterator(os.path.join(test_path, "*")):
  440. num += 1
  441. # Expecting "." and ".." only
  442. self.failUnlessEqual(2, num)
  443. finally:
  444. os.rmdir(test_path)
  445. class TestDirectoryChanges(unittest.TestCase):
  446. num_test_dirs = 1
  447. def setUp(self):
  448. self.watcher_threads = []
  449. self.watcher_thread_changes = []
  450. self.dir_names = []
  451. self.dir_handles = []
  452. for i in range(self.num_test_dirs):
  453. td = tempfile.mktemp("-test-directory-changes-%d" % i)
  454. os.mkdir(td)
  455. self.dir_names.append(td)
  456. hdir = win32file.CreateFile(td,
  457. ntsecuritycon.FILE_LIST_DIRECTORY,
  458. win32con.FILE_SHARE_READ,
  459. None, # security desc
  460. win32con.OPEN_EXISTING,
  461. win32con.FILE_FLAG_BACKUP_SEMANTICS |
  462. win32con.FILE_FLAG_OVERLAPPED,
  463. None)
  464. self.dir_handles.append(hdir)
  465. changes = []
  466. t = threading.Thread(target=self._watcherThreadOverlapped,
  467. args=(td, hdir, changes))
  468. t.start()
  469. self.watcher_threads.append(t)
  470. self.watcher_thread_changes.append(changes)
  471. def _watcherThread(self, dn, dh, changes):
  472. # A synchronous version:
  473. # XXX - not used - I was having a whole lot of problems trying to
  474. # get this to work. Specifically:
  475. # * ReadDirectoryChangesW without an OVERLAPPED blocks infinitely.
  476. # * If another thread attempts to close the handle while
  477. # ReadDirectoryChangesW is waiting on it, the ::CloseHandle() method
  478. # blocks (which has nothing to do with the GIL - it is correctly
  479. # managed)
  480. # Which ends up with no way to kill the thread!
  481. flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME
  482. while 1:
  483. try:
  484. print("waiting", dh)
  485. changes = win32file.ReadDirectoryChangesW(dh,
  486. 8192,
  487. False, #sub-tree
  488. flags)
  489. print("got", changes)
  490. except:
  491. raise
  492. changes.extend(changes)
  493. def _watcherThreadOverlapped(self, dn, dh, changes):
  494. flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME
  495. buf = win32file.AllocateReadBuffer(8192)
  496. overlapped = pywintypes.OVERLAPPED()
  497. overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
  498. while 1:
  499. win32file.ReadDirectoryChangesW(dh,
  500. buf,
  501. False, #sub-tree
  502. flags,
  503. overlapped)
  504. # Wait for our event, or for 5 seconds.
  505. rc = win32event.WaitForSingleObject(overlapped.hEvent, 5000)
  506. if rc == win32event.WAIT_OBJECT_0:
  507. # got some data! Must use GetOverlappedResult to find out
  508. # how much is valid! 0 generally means the handle has
  509. # been closed. Blocking is OK here, as the event has
  510. # already been set.
  511. nbytes = win32file.GetOverlappedResult(dh, overlapped, True)
  512. if nbytes:
  513. bits = win32file.FILE_NOTIFY_INFORMATION(buf, nbytes)
  514. changes.extend(bits)
  515. else:
  516. # This is "normal" exit - our 'tearDown' closes the
  517. # handle.
  518. # print "looks like dir handle was closed!"
  519. return
  520. else:
  521. print("ERROR: Watcher thread timed-out!")
  522. return # kill the thread!
  523. def tearDown(self):
  524. # be careful about raising errors at teardown!
  525. for h in self.dir_handles:
  526. # See comments in _watcherThread above - this appears to
  527. # deadlock if a synchronous ReadDirectoryChangesW is waiting...
  528. # (No such problems with an asynch ReadDirectoryChangesW)
  529. h.Close()
  530. for dn in self.dir_names:
  531. try:
  532. shutil.rmtree(dn)
  533. except OSError:
  534. print("FAILED to remove directory", dn)
  535. for t in self.watcher_threads:
  536. # closing dir handle should have killed threads!
  537. t.join(5)
  538. if t.is_alive():
  539. print("FAILED to wait for thread termination")
  540. def stablize(self):
  541. time.sleep(0.5)
  542. def testSimple(self):
  543. self.stablize()
  544. for dn in self.dir_names:
  545. fn = os.path.join(dn, "test_file")
  546. open(fn, "w").close()
  547. self.stablize()
  548. changes = self.watcher_thread_changes[0]
  549. self.failUnlessEqual(changes, [(1, "test_file")])
  550. def testSmall(self):
  551. self.stablize()
  552. for dn in self.dir_names:
  553. fn = os.path.join(dn, "x")
  554. open(fn, "w").close()
  555. self.stablize()
  556. changes = self.watcher_thread_changes[0]
  557. self.failUnlessEqual(changes, [(1, "x")])
  558. class TestEncrypt(unittest.TestCase):
  559. def testEncrypt(self):
  560. fname = tempfile.mktemp("win32file_test")
  561. f = open(fname, "wb")
  562. f.write(str2bytes("hello"))
  563. f.close()
  564. f = None
  565. try:
  566. try:
  567. win32file.EncryptFile(fname)
  568. except win32file.error as details:
  569. if details.winerror != winerror.ERROR_ACCESS_DENIED:
  570. raise
  571. print("It appears this is not NTFS - cant encrypt/decrypt")
  572. win32file.DecryptFile(fname)
  573. finally:
  574. if f is not None:
  575. f.close()
  576. os.unlink(fname)
  577. class TestConnect(unittest.TestCase):
  578. def connect_thread_runner(self, expect_payload, giveup_event):
  579. # As Windows 2000 doesn't do ConnectEx, we need to use a non-blocking
  580. # accept, as our test connection may never come. May as well use
  581. # AcceptEx for this...
  582. listener = socket.socket()
  583. self.addr = ('localhost', random.randint(10000,64000))
  584. listener.bind(self.addr)
  585. listener.listen(1)
  586. # create accept socket
  587. accepter = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  588. # An overlapped
  589. overlapped = pywintypes.OVERLAPPED()
  590. overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
  591. # accept the connection.
  592. if expect_payload:
  593. buf_size = 1024
  594. else:
  595. # when we don't expect data we must be careful to only pass the
  596. # exact number of bytes for the endpoint data...
  597. buf_size = win32file.CalculateSocketEndPointSize(listener)
  598. buffer = win32file.AllocateReadBuffer(buf_size)
  599. win32file.AcceptEx(listener, accepter, buffer, overlapped)
  600. # wait for the connection or our test to fail.
  601. events = giveup_event, overlapped.hEvent
  602. rc = win32event.WaitForMultipleObjects(events, False, 2000)
  603. if rc == win32event.WAIT_TIMEOUT:
  604. self.fail("timed out waiting for a connection")
  605. if rc == win32event.WAIT_OBJECT_0:
  606. # Our main thread running the test failed and will never connect.
  607. return
  608. # must be a connection.
  609. nbytes = win32file.GetOverlappedResult(listener.fileno(), overlapped, False)
  610. if expect_payload:
  611. self.request = buffer[:nbytes]
  612. accepter.send(str2bytes('some expected response'))
  613. def test_connect_with_payload(self):
  614. giveup_event = win32event.CreateEvent(None, 0, 0, None)
  615. t = threading.Thread(target=self.connect_thread_runner,
  616. args=(True, giveup_event))
  617. t.start()
  618. time.sleep(0.1)
  619. s2 = socket.socket()
  620. ol = pywintypes.OVERLAPPED()
  621. s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand
  622. try:
  623. win32file.ConnectEx(s2, self.addr, ol, str2bytes("some expected request"))
  624. except win32file.error as exc:
  625. win32event.SetEvent(giveup_event)
  626. if exc.winerror == 10022: # WSAEINVAL
  627. raise TestSkipped("ConnectEx is not available on this platform")
  628. raise # some error error we don't expect.
  629. # We occasionally see ERROR_CONNECTION_REFUSED in automation
  630. try:
  631. win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  632. except win32file.error as exc:
  633. win32event.SetEvent(giveup_event)
  634. if exc.winerror == winerror.ERROR_CONNECTION_REFUSED:
  635. raise TestSkipped("Assuming ERROR_CONNECTION_REFUSED is transient")
  636. raise
  637. ol = pywintypes.OVERLAPPED()
  638. buff = win32file.AllocateReadBuffer(1024)
  639. win32file.WSARecv(s2, buff, ol, 0)
  640. length = win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  641. self.response = buff[:length]
  642. self.assertEqual(self.response, str2bytes('some expected response'))
  643. self.assertEqual(self.request, str2bytes('some expected request'))
  644. t.join(5)
  645. self.failIf(t.is_alive(), "worker thread didn't terminate")
  646. def test_connect_without_payload(self):
  647. giveup_event = win32event.CreateEvent(None, 0, 0, None)
  648. t = threading.Thread(target=self.connect_thread_runner,
  649. args=(False, giveup_event))
  650. t.start()
  651. time.sleep(0.1)
  652. s2 = socket.socket()
  653. ol = pywintypes.OVERLAPPED()
  654. s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand
  655. try:
  656. win32file.ConnectEx(s2, self.addr, ol)
  657. except win32file.error as exc:
  658. win32event.SetEvent(giveup_event)
  659. if exc.winerror == 10022: # WSAEINVAL
  660. raise TestSkipped("ConnectEx is not available on this platform")
  661. raise # some error error we don't expect.
  662. # We occasionally see ERROR_CONNECTION_REFUSED in automation
  663. try:
  664. win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  665. except win32file.error as exc:
  666. win32event.SetEvent(giveup_event)
  667. if exc.winerror == winerror.ERROR_CONNECTION_REFUSED:
  668. raise TestSkipped("Assuming ERROR_CONNECTION_REFUSED is transient")
  669. raise
  670. ol = pywintypes.OVERLAPPED()
  671. buff = win32file.AllocateReadBuffer(1024)
  672. win32file.WSARecv(s2, buff, ol, 0)
  673. length = win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  674. self.response = buff[:length]
  675. self.assertEqual(self.response, str2bytes('some expected response'))
  676. t.join(5)
  677. self.failIf(t.is_alive(), "worker thread didn't terminate")
  678. class TestTransmit(unittest.TestCase):
  679. def test_transmit(self):
  680. import binascii
  681. bytes = os.urandom(1024*1024)
  682. val = binascii.hexlify(bytes)
  683. val_length = len(val)
  684. f = tempfile.TemporaryFile()
  685. f.write(val)
  686. def runner():
  687. s1 = socket.socket()
  688. # binding fails occasionally on github CI with:
  689. # OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
  690. # which probably just means the random port is already in use, so
  691. # let that happen a few times.
  692. for i in range(5):
  693. self.addr = ('localhost', random.randint(10000,64000))
  694. try:
  695. s1.bind(self.addr)
  696. break
  697. except os.error as exc:
  698. if exc.winerror != 10013:
  699. raise
  700. print("Failed to use port", self.addr, "trying another random one")
  701. else:
  702. raise RuntimeError("Failed to find an available port to bind to.")
  703. s1.listen(1)
  704. cli, addr = s1.accept()
  705. buf = 1
  706. self.request = []
  707. while buf:
  708. buf = cli.recv(1024*100)
  709. self.request.append(buf)
  710. th = threading.Thread(target=runner)
  711. th.start()
  712. time.sleep(0.5)
  713. s2 = socket.socket()
  714. s2.connect(self.addr)
  715. length = 0
  716. aaa = str2bytes("[AAA]")
  717. bbb = str2bytes("[BBB]")
  718. ccc = str2bytes("[CCC]")
  719. ddd = str2bytes("[DDD]")
  720. empty = str2bytes("")
  721. ol = pywintypes.OVERLAPPED()
  722. f.seek(0)
  723. win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0)
  724. length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  725. ol = pywintypes.OVERLAPPED()
  726. f.seek(0)
  727. win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, aaa, bbb)
  728. length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  729. ol = pywintypes.OVERLAPPED()
  730. f.seek(0)
  731. win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, empty, empty)
  732. length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  733. ol = pywintypes.OVERLAPPED()
  734. f.seek(0)
  735. win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, None, ccc)
  736. length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  737. ol = pywintypes.OVERLAPPED()
  738. f.seek(0)
  739. win32file.TransmitFile(s2, win32file._get_osfhandle(f.fileno()), val_length, 0, ol, 0, ddd)
  740. length += win32file.GetOverlappedResult(s2.fileno(), ol, 1)
  741. s2.close()
  742. th.join()
  743. buf = str2bytes('').join(self.request)
  744. self.assertEqual(length, len(buf))
  745. expected = val + aaa + val + bbb + val + val + ccc + ddd + val
  746. self.assertEqual(type(expected), type(buf))
  747. self.assert_(expected == buf)
  748. class TestWSAEnumNetworkEvents(unittest.TestCase):
  749. def test_basics(self):
  750. s = socket.socket()
  751. e = win32event.CreateEvent(None, 1, 0, None)
  752. win32file.WSAEventSelect(s, e, 0)
  753. self.assertEquals(win32file.WSAEnumNetworkEvents(s), {})
  754. self.assertEquals(win32file.WSAEnumNetworkEvents(s, e), {})
  755. self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, e, 3)
  756. self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, "spam")
  757. self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, "spam", e)
  758. self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, "spam")
  759. f = open("NUL")
  760. h = win32file._get_osfhandle(f.fileno())
  761. self.assertRaises(win32file.error, win32file.WSAEnumNetworkEvents, h)
  762. self.assertRaises(win32file.error, win32file.WSAEnumNetworkEvents, s, h)
  763. try:
  764. win32file.WSAEnumNetworkEvents(h)
  765. except win32file.error as e:
  766. self.assertEquals(e.winerror, win32file.WSAENOTSOCK)
  767. try:
  768. win32file.WSAEnumNetworkEvents(s, h)
  769. except win32file.error as e:
  770. # According to the docs it would seem reasonable that
  771. # this would fail with WSAEINVAL, but it doesn't.
  772. self.assertEquals(e.winerror, win32file.WSAENOTSOCK)
  773. def test_functional(self):
  774. # This is not really a unit test, but it does exercise the code
  775. # quite well and can serve as an example of WSAEventSelect and
  776. # WSAEnumNetworkEvents usage.
  777. port = socket.socket()
  778. port.setblocking(0)
  779. port_event = win32event.CreateEvent(None, 0, 0, None)
  780. win32file.WSAEventSelect(port, port_event,
  781. win32file.FD_ACCEPT |
  782. win32file.FD_CLOSE)
  783. port.bind(("127.0.0.1", 0))
  784. port.listen(10)
  785. client = socket.socket()
  786. client.setblocking(0)
  787. client_event = win32event.CreateEvent(None, 0, 0, None)
  788. win32file.WSAEventSelect(client, client_event,
  789. win32file.FD_CONNECT |
  790. win32file.FD_READ |
  791. win32file.FD_WRITE |
  792. win32file.FD_CLOSE)
  793. err = client.connect_ex(port.getsockname())
  794. self.assertEquals(err, win32file.WSAEWOULDBLOCK)
  795. res = win32event.WaitForSingleObject(port_event, 1000)
  796. self.assertEquals(res, win32event.WAIT_OBJECT_0)
  797. events = win32file.WSAEnumNetworkEvents(port, port_event)
  798. self.assertEquals(events, {win32file.FD_ACCEPT: 0})
  799. server, addr = port.accept()
  800. server.setblocking(0)
  801. server_event = win32event.CreateEvent(None, 1, 0, None)
  802. win32file.WSAEventSelect(server, server_event,
  803. win32file.FD_READ |
  804. win32file.FD_WRITE |
  805. win32file.FD_CLOSE)
  806. res = win32event.WaitForSingleObject(server_event, 1000)
  807. self.assertEquals(res, win32event.WAIT_OBJECT_0)
  808. events = win32file.WSAEnumNetworkEvents(server, server_event)
  809. self.assertEquals(events, {win32file.FD_WRITE: 0})
  810. res = win32event.WaitForSingleObject(client_event, 1000)
  811. self.assertEquals(res, win32event.WAIT_OBJECT_0)
  812. events = win32file.WSAEnumNetworkEvents(client, client_event)
  813. self.assertEquals(events, {win32file.FD_CONNECT: 0,
  814. win32file.FD_WRITE: 0})
  815. sent = 0
  816. data = str2bytes("x") * 16 * 1024
  817. while sent < 16 * 1024 * 1024:
  818. try:
  819. sent += client.send(data)
  820. except socket.error as e:
  821. if e.args[0] == win32file.WSAEINTR:
  822. continue
  823. elif e.args[0] in (win32file.WSAEWOULDBLOCK, win32file.WSAENOBUFS):
  824. break
  825. else:
  826. raise
  827. else:
  828. self.fail("could not find socket buffer limit")
  829. events = win32file.WSAEnumNetworkEvents(client)
  830. self.assertEquals(events, {})
  831. res = win32event.WaitForSingleObject(server_event, 1000)
  832. self.assertEquals(res, win32event.WAIT_OBJECT_0)
  833. events = win32file.WSAEnumNetworkEvents(server, server_event)
  834. self.assertEquals(events, {win32file.FD_READ: 0})
  835. received = 0
  836. while received < sent:
  837. try:
  838. received += len(server.recv(16 * 1024))
  839. except socket.error as e:
  840. if e.args[0] in [win32file.WSAEINTR, win32file.WSAEWOULDBLOCK]:
  841. continue
  842. else:
  843. raise
  844. self.assertEquals(received, sent)
  845. events = win32file.WSAEnumNetworkEvents(server)
  846. self.assertEquals(events, {})
  847. res = win32event.WaitForSingleObject(client_event, 1000)
  848. self.assertEquals(res, win32event.WAIT_OBJECT_0)
  849. events = win32file.WSAEnumNetworkEvents(client, client_event)
  850. self.assertEquals(events, {win32file.FD_WRITE: 0})
  851. client.shutdown(socket.SHUT_WR)
  852. res = win32event.WaitForSingleObject(server_event, 1000)
  853. self.assertEquals(res, win32event.WAIT_OBJECT_0)
  854. # strange timing issues...
  855. for i in range(5):
  856. events = win32file.WSAEnumNetworkEvents(server, server_event)
  857. if events: break
  858. win32api.Sleep(100)
  859. else:
  860. raise AssertionError("failed to get events")
  861. self.assertEquals(events, {win32file.FD_CLOSE: 0})
  862. events = win32file.WSAEnumNetworkEvents(client)
  863. self.assertEquals(events, {})
  864. server.close()
  865. res = win32event.WaitForSingleObject(client_event, 1000)
  866. self.assertEquals(res, win32event.WAIT_OBJECT_0)
  867. events = win32file.WSAEnumNetworkEvents(client, client_event)
  868. self.assertEquals(events, {win32file.FD_CLOSE: 0})
  869. client.close()
  870. events = win32file.WSAEnumNetworkEvents(port)
  871. self.assertEquals(events, {})
  872. if __name__ == '__main__':
  873. testmain()