pywin32-checkins Mailing List for Python for Windows Extensions (Page 29)
OLD project page for the Python extensions for Windows
Brought to you by:
mhammond
You can subscribe to this list here.
2003 |
Jan
|
Feb
|
Mar
|
Apr
(2) |
May
(1) |
Jun
(6) |
Jul
(50) |
Aug
(11) |
Sep
(24) |
Oct
(184) |
Nov
(118) |
Dec
(22) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2004 |
Jan
(31) |
Feb
(25) |
Mar
(34) |
Apr
(105) |
May
(49) |
Jun
(38) |
Jul
(39) |
Aug
(7) |
Sep
(98) |
Oct
(79) |
Nov
(20) |
Dec
(17) |
2005 |
Jan
(66) |
Feb
(32) |
Mar
(43) |
Apr
(30) |
May
(58) |
Jun
(30) |
Jul
(16) |
Aug
(4) |
Sep
(21) |
Oct
(42) |
Nov
(11) |
Dec
(14) |
2006 |
Jan
(42) |
Feb
(30) |
Mar
(22) |
Apr
(1) |
May
(9) |
Jun
(15) |
Jul
(20) |
Aug
(9) |
Sep
(8) |
Oct
(1) |
Nov
(9) |
Dec
(43) |
2007 |
Jan
(52) |
Feb
(45) |
Mar
(20) |
Apr
(12) |
May
(59) |
Jun
(39) |
Jul
(35) |
Aug
(31) |
Sep
(17) |
Oct
(20) |
Nov
(4) |
Dec
(4) |
2008 |
Jan
(28) |
Feb
(111) |
Mar
(4) |
Apr
(27) |
May
(40) |
Jun
(27) |
Jul
(32) |
Aug
(94) |
Sep
(87) |
Oct
(153) |
Nov
(336) |
Dec
(331) |
2009 |
Jan
(298) |
Feb
(127) |
Mar
(20) |
Apr
(8) |
May
|
Jun
(10) |
Jul
(6) |
Aug
|
Sep
(2) |
Oct
(2) |
Nov
|
Dec
(1) |
2010 |
Jan
(7) |
Feb
(1) |
Mar
|
Apr
|
May
(15) |
Jun
(4) |
Jul
(3) |
Aug
(28) |
Sep
(1) |
Oct
(19) |
Nov
(16) |
Dec
(6) |
2011 |
Jan
(2) |
Feb
(18) |
Mar
(17) |
Apr
(12) |
May
(5) |
Jun
(11) |
Jul
(7) |
Aug
(2) |
Sep
(2) |
Oct
(4) |
Nov
(4) |
Dec
|
2012 |
Jan
(6) |
Feb
(2) |
Mar
|
Apr
(8) |
May
(4) |
Jun
(3) |
Jul
(13) |
Aug
(27) |
Sep
(8) |
Oct
(9) |
Nov
(3) |
Dec
(2) |
2013 |
Jan
|
Feb
(1) |
Mar
(5) |
Apr
(10) |
May
|
Jun
(2) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(1) |
Dec
(9) |
2014 |
Jan
(2) |
Feb
(4) |
Mar
(4) |
Apr
(1) |
May
(4) |
Jun
(2) |
Jul
|
Aug
|
Sep
|
Oct
(2) |
Nov
|
Dec
(1) |
2015 |
Jan
(1) |
Feb
|
Mar
|
Apr
(6) |
May
(2) |
Jun
|
Jul
|
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
2016 |
Jan
(3) |
Feb
(2) |
Mar
|
Apr
(3) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2017 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(1) |
Oct
|
Nov
|
Dec
|
From: Mark H. <mha...@us...> - 2009-01-07 06:27:53
|
Update of /cvsroot/pywin32/pywin32/Pythonwin In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv7401/Pythonwin Modified Files: Tag: py3k dllmain.cpp win32uimodule.cpp Log Message: merge win32ui shutdown fixes and traceback printing from py3k-integration branch Index: win32uimodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/win32uimodule.cpp,v retrieving revision 1.39.2.11 retrieving revision 1.39.2.12 diff -C2 -d -r1.39.2.11 -r1.39.2.12 *** win32uimodule.cpp 3 Jan 2009 04:45:17 -0000 1.39.2.11 --- win32uimodule.cpp 7 Jan 2009 06:27:42 -0000 1.39.2.12 *************** *** 666,670 **** // not good (and not what we want!? PyErr_NormalizeException(&type, &value, &traceback); ! if (type && PyErr_GivenExceptionMatches(type, PyExc_SystemExit)) { // Replace it with a RuntimeError. --- 666,677 ---- // not good (and not what we want!? PyErr_NormalizeException(&type, &value, &traceback); ! #ifdef DEBUG ! // dump it to the debugger in debug builds. ! char *msg = GetPythonTraceback(type, value, traceback); ! if (msg) { ! OutputDebugString(msg); ! free(msg); ! } ! #endif if (type && PyErr_GivenExceptionMatches(type, PyExc_SystemExit)) { // Replace it with a RuntimeError. *************** *** 2389,2392 **** --- 2396,2401 ---- // These are primarily here as a debugging aid. Destroy what I created // to help MFC detect useful memory leak reports + if (bInFatalShutdown) + return; ui_assoc_object::handleMgr.cleanup(); Index: dllmain.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/dllmain.cpp,v retrieving revision 1.5.4.1 retrieving revision 1.5.4.2 diff -C2 -d -r1.5.4.1 -r1.5.4.2 *** dllmain.cpp 29 Aug 2008 05:53:29 -0000 1.5.4.1 --- dllmain.cpp 7 Jan 2009 06:27:42 -0000 1.5.4.2 *************** *** 212,216 **** // could not have been created. Let the Python code manage if it wants! Win32uiFinalize(); - Python_delete_assoc(pCreatedApp); // so Python wont try and use it. AfxWinTerm(); afxCurrentWinApp = NULL; // So AfxGetApp fails from here. --- 212,215 ---- |
From: Mark H. <mha...@us...> - 2009-01-07 06:25:24
|
Update of /cvsroot/pywin32/pywin32/win32/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv7136/win32/test Modified Files: Tag: py3k test_clipboard.py test_odbc.py test_pywintypes.py test_security.py test_sspi.py test_win32api.py test_win32crypt.py test_win32file.py test_win32inet.py test_win32pipe.py test_win32wnet.py testall.py Log Message: merge recent test changes from the trunk Index: test_security.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_security.py,v retrieving revision 1.4.4.2 retrieving revision 1.4.4.3 diff -C2 -d -r1.4.4.2 -r1.4.4.3 *** test_security.py 11 Dec 2008 04:13:36 -0000 1.4.4.2 --- test_security.py 7 Jan 2009 06:25:16 -0000 1.4.4.3 *************** *** 2,5 **** --- 2,7 ---- import sys, os import unittest + import winerror + from pywin32_testutil import testmain, TestSkipped, ob2memory import win32api, win32con, win32security, ntsecuritycon *************** *** 18,25 **** def testBuffer(self): ! # hrm - what about py3k - intent is to check the buffer slots return ! # something sane. ! self.failUnlessEqual(buffer(win32security.LookupAccountName('','Administrator')[0]), ! buffer(win32security.LookupAccountName('','Administrator')[0])) def testMemory(self): --- 20,25 ---- def testBuffer(self): ! self.failUnlessEqual(ob2memory(win32security.LookupAccountName('','Administrator')[0]), ! ob2memory(win32security.LookupAccountName('','Administrator')[0])) def testMemory(self): *************** *** 42,46 **** sd4.SetSecurityDescriptorSacl(1,sacl,0) ! class TestDS(unittest.TestCase): def testDsGetDcName(self): # Not sure what we can actually test here! At least calling it --- 42,61 ---- sd4.SetSecurityDescriptorSacl(1,sacl,0) ! class DomainTests(unittest.TestCase): ! def setUp(self): ! self.ds_handle = None ! try: ! # saving the handle means the other test itself should bind faster. ! self.ds_handle = win32security.DsBind() ! except win32security.error as exc: ! if exc.winerror != winerror.ERROR_NO_SUCH_DOMAIN: ! raise ! raise TestSkipped(exc) ! ! def tearDown(self): ! if self.ds_handle is not None: ! self.ds_handle.close() ! ! class TestDS(DomainTests): def testDsGetDcName(self): # Not sure what we can actually test here! At least calling it *************** *** 75,79 **** self.failUnlessEqual(expected, result[0][2]) ! class TestTranslate(unittest.TestCase): def _testTranslate(self, fmt_from, fmt_to): name = win32api.GetUserNameEx(fmt_from) --- 90,94 ---- self.failUnlessEqual(expected, result[0][2]) ! class TestTranslate(DomainTests): def _testTranslate(self, fmt_from, fmt_to): name = win32api.GetUserNameEx(fmt_from) *************** *** 95,97 **** if __name__=='__main__': ! unittest.main() --- 110,112 ---- if __name__=='__main__': ! testmain() Index: test_win32pipe.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32pipe.py,v retrieving revision 1.4 retrieving revision 1.4.2.1 diff -C2 -d -r1.4 -r1.4.2.1 *** test_win32pipe.py 7 Jun 2008 07:23:54 -0000 1.4 --- test_win32pipe.py 7 Jan 2009 06:25:16 -0000 1.4.2.1 *************** *** 2,5 **** --- 2,6 ---- import time import threading + from pywin32_testutil import str2bytes # py3k-friendly helper *************** *** 19,25 **** self.failUnless(hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,)) hr, got = win32file.ReadFile(pipe_handle, 100) ! self.failUnless(got == "foo\0bar") time.sleep(wait_time) ! win32file.WriteFile(pipe_handle, "bar\0foo") pipe_handle.Close() event.set() --- 20,26 ---- self.failUnless(hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,)) hr, got = win32file.ReadFile(pipe_handle, 100) ! self.failUnlessEqual(got, str2bytes("foo\0bar")) time.sleep(wait_time) ! win32file.WriteFile(pipe_handle, str2bytes("bar\0foo")) pipe_handle.Close() event.set() *************** *** 48,53 **** self.startPipeServer(event) ! got = win32pipe.CallNamedPipe(self.pipename,"foo\0bar", 1024, win32pipe.NMPWAIT_WAIT_FOREVER) ! self.failUnlessEqual(got, "bar\0foo") event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") --- 49,54 ---- self.startPipeServer(event) ! got = win32pipe.CallNamedPipe(self.pipename,str2bytes("foo\0bar"), 1024, win32pipe.NMPWAIT_WAIT_FOREVER) ! self.failUnlessEqual(got, str2bytes("bar\0foo")) event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") *************** *** 70,75 **** hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None) ! hr, got = win32pipe.TransactNamedPipe(hpipe, "foo\0bar", 1024, None) ! self.failUnlessEqual(got, "bar\0foo") event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") --- 71,76 ---- hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None) ! hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None) ! self.failUnlessEqual(got, str2bytes("bar\0foo")) event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") *************** *** 95,100 **** buffer = win32file.AllocateReadBuffer(1024) ! hr, got = win32pipe.TransactNamedPipe(hpipe, "foo\0bar", buffer, None) ! self.failUnlessEqual(got, "bar\0foo") event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") --- 96,101 ---- buffer = win32file.AllocateReadBuffer(1024) ! hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, None) ! self.failUnlessEqual(got, str2bytes("bar\0foo")) event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") *************** *** 120,128 **** buffer = win32file.AllocateReadBuffer(1024) ! hr, got = win32pipe.TransactNamedPipe(hpipe, "foo\0bar", buffer, overlapped) self.failUnlessEqual(hr, winerror.ERROR_IO_PENDING) nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True) got = buffer[:nbytes] ! self.failUnlessEqual(got, "bar\0foo") event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") --- 121,129 ---- buffer = win32file.AllocateReadBuffer(1024) ! hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, overlapped) self.failUnlessEqual(hr, winerror.ERROR_IO_PENDING) nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True) got = buffer[:nbytes] ! self.failUnlessEqual(got, str2bytes("bar\0foo")) event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") Index: test_sspi.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_sspi.py,v retrieving revision 1.3.4.2 retrieving revision 1.3.4.3 diff -C2 -d -r1.3.4.2 -r1.3.4.3 *** test_sspi.py 3 Oct 2008 22:44:37 -0000 1.3.4.2 --- test_sspi.py 7 Jan 2009 06:25:16 -0000 1.3.4.3 *************** *** 3,8 **** --- 3,21 ---- # See also the other SSPI demos. import win32security, sspi, sspicon, win32api + from pywin32_testutil import TestSkipped, testmain, str2bytes import unittest + # It is quite likely that the Kerberos tests will fail due to not being + # installed. The NTLM tests do *not* get the same behaviour as they should + # always be there. + def applyHandlingSkips(func, *args): + try: + return func(*args) + except win32api.error as exc: + if exc.winerror == sspicon.SEC_E_NO_CREDENTIALS: + raise TestSkipped(exc) + raise + + class TestSSPI(unittest.TestCase): *************** *** 32,36 **** def testImpersonateKerberos(self): ! self._doTestImpersonate("Kerberos") def testImpersonateNTLM(self): --- 45,49 ---- def testImpersonateKerberos(self): ! applyHandlingSkips(self._doTestImpersonate, "Kerberos") def testImpersonateNTLM(self): *************** *** 42,46 **** pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) ! msg=b'some data to be encrypted ......' trailersize=pkg_size_info['SecurityTrailer'] --- 55,59 ---- pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) ! msg=str2bytes('some data to be encrypted ......') trailersize=pkg_size_info['SecurityTrailer'] *************** *** 53,61 **** self.failUnlessEqual(msg, encbuf[0].Buffer) # and test the higher-level functions ! data, sig = sspiclient.encrypt(b"hello") ! self.assertEqual(sspiserver.decrypt(data, sig), b"hello") ! data, sig = sspiserver.encrypt(b"hello") ! self.assertEqual(sspiclient.decrypt(data, sig), b"hello") def testEncryptNTLM(self): --- 66,75 ---- self.failUnlessEqual(msg, encbuf[0].Buffer) # and test the higher-level functions ! data_in = str2bytes("hello") ! data, sig = sspiclient.encrypt(data_in) ! self.assertEqual(sspiserver.decrypt(data, sig), data_in) ! data, sig = sspiserver.encrypt(data_in) ! self.assertEqual(sspiclient.decrypt(data, sig), data_in) def testEncryptNTLM(self): *************** *** 63,67 **** def testEncryptKerberos(self): ! self._doTestEncrypt("Kerberos") def _doTestSign(self, pkg_name): --- 77,81 ---- def testEncryptKerberos(self): ! applyHandlingSkips(self._doTestEncrypt, "Kerberos") def _doTestSign(self, pkg_name): *************** *** 70,74 **** pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) ! msg=b'some data to be encrypted ......' sigsize=pkg_size_info['MaxSignature'] --- 84,88 ---- pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) ! msg=str2bytes('some data to be encrypted ......') sigsize=pkg_size_info['MaxSignature'] *************** *** 82,97 **** sspiclient.next_seq_num = 1 sspiserver.next_seq_num = 1 ! key = sspiclient.sign(b"hello") ! sspiserver.verify(b"hello", key) ! key = sspiclient.sign(b"hello") self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED, ! sspiserver.verify, b"hellox", key) # and the other way ! key = sspiserver.sign(b"hello") ! sspiclient.verify(b"hello", key) ! key = sspiserver.sign(b"hello") self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED, ! sspiclient.verify, b"hellox", key) def testSignNTLM(self): --- 96,112 ---- sspiclient.next_seq_num = 1 sspiserver.next_seq_num = 1 ! data = str2bytes("hello") ! key = sspiclient.sign(data) ! sspiserver.verify(data, key) ! key = sspiclient.sign(data) self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED, ! sspiserver.verify, data + data, key) # and the other way ! key = sspiserver.sign(data) ! sspiclient.verify(data, key) ! key = sspiserver.sign(data) self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED, ! sspiclient.verify, data + data, key) def testSignNTLM(self): *************** *** 99,120 **** def testSignKerberos(self): ! self._doTestSign("Kerberos") ! def testSequenceSign(self): # Only Kerberos supports sequence detection. sspiclient, sspiserver = self._doAuth("Kerberos") ! key = sspiclient.sign(b"hello") ! sspiclient.sign(b"hello") self.assertRaisesHRESULT(sspicon.SEC_E_OUT_OF_SEQUENCE, ! sspiserver.verify, b'hello', key) ! def testSequenceEncrypt(self): # Only Kerberos supports sequence detection. sspiclient, sspiserver = self._doAuth("Kerberos") ! blob, key = sspiclient.encrypt(b"hello",) ! blob, key = sspiclient.encrypt(b"hello") self.assertRaisesHRESULT(sspicon.SEC_E_OUT_OF_SEQUENCE, sspiserver.decrypt, blob, key) if __name__=='__main__': ! unittest.main() --- 114,141 ---- def testSignKerberos(self): ! applyHandlingSkips(self._doTestSign, "Kerberos") ! def _testSequenceSign(self): # Only Kerberos supports sequence detection. sspiclient, sspiserver = self._doAuth("Kerberos") ! key = sspiclient.sign("hello") ! sspiclient.sign("hello") self.assertRaisesHRESULT(sspicon.SEC_E_OUT_OF_SEQUENCE, ! sspiserver.verify, 'hello', key) ! def testSequenceSign(self): ! applyHandlingSkips(self._testSequenceSign) ! ! def _testSequenceEncrypt(self): # Only Kerberos supports sequence detection. sspiclient, sspiserver = self._doAuth("Kerberos") ! blob, key = sspiclient.encrypt("hello",) ! blob, key = sspiclient.encrypt("hello") self.assertRaisesHRESULT(sspicon.SEC_E_OUT_OF_SEQUENCE, sspiserver.decrypt, blob, key) + def testSequenceEncrypt(self): + applyHandlingSkips(self._testSequenceEncrypt) + if __name__=='__main__': ! testmain() Index: test_win32api.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32api.py,v retrieving revision 1.13.2.3 retrieving revision 1.13.2.4 diff -C2 -d -r1.13.2.3 -r1.13.2.4 *** test_win32api.py 11 Dec 2008 04:13:36 -0000 1.13.2.3 --- test_win32api.py 7 Jan 2009 06:25:16 -0000 1.13.2.4 *************** *** 2,5 **** --- 2,6 ---- import unittest + from pywin32_testutil import str2bytes import win32api, win32con, win32event, winerror *************** *** 68,72 **** ('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1','string 2','string 3','string 4']), ('REG_DWORD', win32con.REG_DWORD, 666), ! ('REG_BINARY', win32con.REG_BINARY, b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00'), ) --- 69,73 ---- ('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1','string 2','string 3','string 4']), ('REG_DWORD', win32con.REG_DWORD, 666), ! ('REG_BINARY', win32con.REG_BINARY, str2bytes('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00')), ) Index: test_win32inet.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32inet.py,v retrieving revision 1.1.4.2 retrieving revision 1.1.4.3 diff -C2 -d -r1.1.4.2 -r1.1.4.3 *** test_win32inet.py 11 Dec 2008 07:17:46 -0000 1.1.4.2 --- test_win32inet.py 7 Jan 2009 06:25:16 -0000 1.1.4.3 *************** *** 1,4 **** --- 1,5 ---- from win32inet import * from win32inetcon import * + from pywin32_testutil import str2bytes # py3k-friendly helper import unittest *************** *** 36,41 **** break chunks.append(chunk) ! data = ''.join(chunks) ! assert data.find("Python")>0, repr(data) # This must appear somewhere on the main page! def testFtpCommand(self): --- 37,42 ---- break chunks.append(chunk) ! data = str2bytes('').join(chunks) ! assert data.find(str2bytes("Python"))>0, repr(data) # This must appear somewhere on the main page! def testFtpCommand(self): Index: test_odbc.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_odbc.py,v retrieving revision 1.7.2.3 retrieving revision 1.7.2.4 diff -C2 -d -r1.7.2.3 -r1.7.2.4 *** test_odbc.py 11 Dec 2008 07:02:51 -0000 1.7.2.3 --- test_odbc.py 7 Jan 2009 06:25:16 -0000 1.7.2.4 *************** *** 6,9 **** --- 6,11 ---- import tempfile + from pywin32_testutil import str2bytes, str2memory, TestSkipped + # We use the DAO ODBC driver from win32com.client.gencache import EnsureDispatch *************** *** 31,35 **** pass else: ! raise RuntimeError("Can't find a DB engine") workspace = dbe.Workspaces(0) --- 33,37 ---- pass else: ! raise TestSkipped("Can't find a DB engine") workspace = dbe.Workspaces(0) *************** *** 104,109 **** def test_insert_select_unicode_ext(self): ! userid = str(b"t-\xe0\xf2", "mbcs") ! username = str(b"test-\xe0\xf2 name", "mbcs") self.test_insert_select_unicode(userid, username) --- 106,111 ---- def test_insert_select_unicode_ext(self): ! userid = "t-\xe0\xf2" ! username = "test-\xe0\xf2 name" self.test_insert_select_unicode(userid, username) *************** *** 143,151 **** def testLongBinary(self): """ Test a long raw field in excess of internal cursor data size (65536)""" ! self._test_val('longbinaryfield', memoryview(b'\0\1\2' * 70000)) def testRaw(self): ## Test binary data ! self._test_val('rawfield', memoryview(b'\1\2\3\4\0\5\6\7\8')) def test_widechar(self): --- 145,153 ---- def testLongBinary(self): """ Test a long raw field in excess of internal cursor data size (65536)""" ! self._test_val('longbinaryfield', str2memory('\0\1\2' * 70000)) def testRaw(self): ## Test binary data ! self._test_val('rawfield', str2memory('\1\2\3\4\0\5\6\7\8')) def test_widechar(self): *************** *** 173,177 **** def test_set_zero_length(self): self.assertEqual(self.cur.execute("insert into %s (userid,username) " ! "values (?,?)" %self.tablename, [b'Frank', '']),1) self.assertEqual(self.cur.execute("select * from %s" %self.tablename), 0) self.assertEqual(len(self.cur.fetchone()[1]),0) --- 175,179 ---- def test_set_zero_length(self): self.assertEqual(self.cur.execute("insert into %s (userid,username) " ! "values (?,?)" %self.tablename, [str2bytes('Frank'), '']),1) self.assertEqual(self.cur.execute("select * from %s" %self.tablename), 0) self.assertEqual(len(self.cur.fetchone()[1]),0) Index: test_clipboard.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_clipboard.py,v retrieving revision 1.6.2.3 retrieving revision 1.6.2.4 diff -C2 -d -r1.6.2.3 -r1.6.2.4 *** test_clipboard.py 27 Nov 2008 11:31:11 -0000 1.6.2.3 --- test_clipboard.py 7 Jan 2009 06:25:16 -0000 1.6.2.4 *************** *** 8,11 **** --- 8,13 ---- import array + from pywin32_testutil import str2bytes + custom_format_name = "PythonClipboardTestFormat" *************** *** 68,77 **** # GetClipboardData doesn't to auto string conversions - so on py3k, # CF_TEXT returns bytes. ! expected = val.encode("ascii") self.failUnlessEqual(GetClipboardData(win32con.CF_TEXT), expected) SetClipboardText(val, win32con.CF_UNICODETEXT) self.failUnlessEqual(GetClipboardData(win32con.CF_UNICODETEXT), val) def test_string(self): ! val = "test".encode("ascii") SetClipboardData(win32con.CF_TEXT, val) self.failUnlessEqual(GetClipboardData(win32con.CF_TEXT), val) --- 70,79 ---- # GetClipboardData doesn't to auto string conversions - so on py3k, # CF_TEXT returns bytes. ! expected = str2bytes(val) self.failUnlessEqual(GetClipboardData(win32con.CF_TEXT), expected) SetClipboardText(val, win32con.CF_UNICODETEXT) self.failUnlessEqual(GetClipboardData(win32con.CF_UNICODETEXT), val) def test_string(self): ! val = str2bytes("test") SetClipboardData(win32con.CF_TEXT, val) self.failUnlessEqual(GetClipboardData(win32con.CF_TEXT), val) *************** *** 83,88 **** CloseClipboard() def test_mem(self): ! val = "test".encode("ascii") ! expected = "test\0".encode("ascii") SetClipboardData(win32con.CF_TEXT, val) # Get the raw data - this will include the '\0' --- 85,90 ---- CloseClipboard() def test_mem(self): ! val = str2bytes("test") ! expected = str2bytes("test\0") SetClipboardData(win32con.CF_TEXT, val) # Get the raw data - this will include the '\0' *************** *** 98,102 **** self.failUnlessRaises(pywintypes.error, GetGlobalMemory, 1) def test_custom_mem(self): ! test_data = b"hello\x00\xff" test_buffer = array.array("b", test_data) cf = RegisterClipboardFormat(custom_format_name) --- 100,104 ---- self.failUnlessRaises(pywintypes.error, GetGlobalMemory, 1) def test_custom_mem(self): ! test_data = str2bytes("hello\x00\xff") test_buffer = array.array("b", test_data) cf = RegisterClipboardFormat(custom_format_name) Index: test_pywintypes.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_pywintypes.py,v retrieving revision 1.3.4.2 retrieving revision 1.3.4.3 diff -C2 -d -r1.3.4.2 -r1.3.4.3 *** test_pywintypes.py 11 Dec 2008 04:13:36 -0000 1.3.4.2 --- test_pywintypes.py 7 Jan 2009 06:25:16 -0000 1.3.4.3 *************** *** 2,5 **** --- 2,6 ---- import pywintypes import time + from pywin32_testutil import str2bytes, ob2memory class TestCase(unittest.TestCase): *************** *** 38,44 **** s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) ! iid2 = pywintypes.IID(bytes(iid), True) self.assertEquals(iid, iid2) ! self.assertRaises(ValueError, pywintypes.IID, b'00', True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer --- 39,45 ---- s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) ! iid2 = pywintypes.IID(ob2memory(iid), True) self.assertEquals(iid, iid2) ! self.assertRaises(ValueError, pywintypes.IID, str2bytes('00'), True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer Index: test_win32wnet.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32wnet.py,v retrieving revision 1.1.4.2 retrieving revision 1.1.4.3 diff -C2 -d -r1.1.4.2 -r1.1.4.3 *** test_win32wnet.py 11 Dec 2008 04:13:36 -0000 1.1.4.2 --- test_win32wnet.py 7 Jan 2009 06:25:16 -0000 1.1.4.3 *************** *** 4,7 **** --- 4,9 ---- import netbios + from pywin32_testutil import str2bytes + RESOURCE_CONNECTED = 0x00000001 RESOURCE_GLOBALNET = 0x00000002 *************** *** 111,115 **** ncb.Command = netbios.NCBASTAT ncb.Lana_num = byte_to_int(la_enum.lana[i]) ! ncb.Callname = "* ".encode("ascii") # ensure bytes on py2x and 3k adapter = netbios.ADAPTER_STATUS() ncb.Buffer = adapter --- 113,117 ---- ncb.Command = netbios.NCBASTAT ncb.Lana_num = byte_to_int(la_enum.lana[i]) ! ncb.Callname = str2bytes("* ") # ensure bytes on py2x and 3k adapter = netbios.ADAPTER_STATUS() ncb.Buffer = adapter Index: test_win32file.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32file.py,v retrieving revision 1.13.2.4 retrieving revision 1.13.2.5 diff -C2 -d -r1.13.2.4 -r1.13.2.5 *** test_win32file.py 11 Dec 2008 07:06:51 -0000 1.13.2.4 --- test_win32file.py 7 Jan 2009 06:25:16 -0000 1.13.2.5 *************** *** 1,3 **** --- 1,4 ---- import unittest + from pywin32_testutil import str2bytes import win32api, win32file, win32pipe, pywintypes, winerror, win32event import win32con, ntsecuritycon *************** *** 19,23 **** os.unlink(filename) handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None) ! test_data = b"Hello\0there" try: win32file.WriteFile(handle, test_data) --- 20,24 ---- os.unlink(filename) handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None) ! test_data = str2bytes("Hello\0there") try: win32file.WriteFile(handle, test_data) *************** *** 44,48 **** # Write a known number of bytes to the file. ! data = b"z" * 1025 win32file.WriteFile(h, data) --- 45,49 ---- # Write a known number of bytes to the file. ! data = str2bytes("z") * 1025 win32file.WriteFile(h, data) *************** *** 66,70 **** # GetFileAttributesEx/GetFileAttributesExW tests. self.failUnlessEqual(win32file.GetFileAttributesEx(testName), win32file.GetFileAttributesExW(testName)) ! attr, ct, at, wt, size = win32file.GetFileAttributesEx(testName) self.failUnless(size==newSize, --- 67,71 ---- # GetFileAttributesEx/GetFileAttributesExW tests. self.failUnlessEqual(win32file.GetFileAttributesEx(testName), win32file.GetFileAttributesExW(testName)) ! attr, ct, at, wt, size = win32file.GetFileAttributesEx(testName) self.failUnless(size==newSize, *************** *** 92,96 **** try: #Write some data ! data = b'Some data' (res, written) = win32file.WriteFile(f, data) --- 93,97 ---- try: #Write some data ! data = str2bytes('Some data') (res, written) = win32file.WriteFile(f, data) *************** *** 126,130 **** # Create the file and write shit-loads of data to it. h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0) ! chunk_data = b"z" * 0x8000 num_loops = 512 expected_size = num_loops * len(chunk_data) --- 127,131 ---- # Create the file and write shit-loads of data to it. h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0) ! chunk_data = str2bytes("z") * 0x8000 num_loops = 512 expected_size = num_loops * len(chunk_data) *************** *** 236,240 **** time.sleep(0.1) # let thread do its thing. try: ! win32pipe.CallNamedPipe(r"\\.\pipe\pywin32_test_pipe", b"Hello there", BUFSIZE, 0) except win32pipe.error: # Testing for overlapped death causes this --- 237,241 ---- time.sleep(0.1) # let thread do its thing. try: ! win32pipe.CallNamedPipe(r"\\.\pipe\pywin32_test_pipe", str2bytes("Hello there"), BUFSIZE, 0) except win32pipe.error: # Testing for overlapped death causes this *************** *** 298,302 **** s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', port)) ! win32file.WSASend(s, b"hello", None) overlapped = pywintypes.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) --- 299,303 ---- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', port)) ! win32file.WSASend(s, str2bytes("hello"), None) overlapped = pywintypes.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) *************** *** 309,313 **** nbytes = win32file.GetOverlappedResult(s.fileno(), overlapped, True) got = buffer[:nbytes] ! self.failUnlessEqual(got, b"hello") # thread should have stopped stopped.wait(2) --- 310,314 ---- nbytes = win32file.GetOverlappedResult(s.fileno(), overlapped, True) got = buffer[:nbytes] ! self.failUnlessEqual(got, str2bytes("hello")) # thread should have stopped stopped.wait(2) *************** *** 485,489 **** fname = tempfile.mktemp("win32file_test") f = open(fname, "wb") ! f.write(b"hello") f.close() f = None --- 486,490 ---- fname = tempfile.mktemp("win32file_test") f = open(fname, "wb") ! f.write(str2bytes("hello")) f.close() f = None Index: test_win32crypt.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32crypt.py,v retrieving revision 1.1 retrieving revision 1.1.4.1 diff -C2 -d -r1.1 -r1.1.4.1 *** test_win32crypt.py 4 Jul 2005 05:40:29 -0000 1.1 --- test_win32crypt.py 7 Jan 2009 06:25:16 -0000 1.1.4.1 *************** *** 1,10 **** ! # Test module for win32timezone import unittest import win32crypt class Crypt(unittest.TestCase): def testSimple(self): ! data = "My test data" entropy = None desc = "My description" --- 1,12 ---- ! # Test module for win32crypt import unittest import win32crypt + from pywin32_testutil import str2bytes # py3k-friendly helper + class Crypt(unittest.TestCase): def testSimple(self): ! data = str2bytes("My test data") entropy = None desc = "My description" *************** *** 17,22 **** def testEntropy(self): ! data = "My test data" ! entropy = "My test entropy" desc = "My description" flags = 0 --- 19,24 ---- def testEntropy(self): ! data = str2bytes("My test data") ! entropy = str2bytes("My test entropy") desc = "My description" flags = 0 Index: testall.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/testall.py,v retrieving revision 1.6.2.5 retrieving revision 1.6.2.6 diff -C2 -d -r1.6.2.5 -r1.6.2.6 *** testall.py 11 Dec 2008 07:06:51 -0000 1.6.2.5 --- testall.py 7 Jan 2009 06:25:16 -0000 1.6.2.6 *************** *** 1,4 **** --- 1,7 ---- import sys, os + import re import unittest + import traceback + import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed *************** *** 18,24 **** } ! ok_exceptions = { ! "RegCreateKeyTransacted": ("NotImplementedError"), ! } class TestRunner: --- 21,72 ---- } ! # re to pull apart an exception line into the exception type and the args. ! re_exception = re.compile("([a-zA-Z0-9_.]*): (.*)$") ! def find_exception_in_output(data): ! have_traceback = False ! for line in data.splitlines(): ! line = line.decode('ascii') # not sure what the correct encoding is... ! if line.startswith("Traceback ("): ! have_traceback = True ! continue ! if line.startswith(" "): ! continue ! if have_traceback: ! # first line not starting with a space since the traceback. ! # must be the exception! ! m = re_exception.match(line) ! if m: ! exc_type, args = m.groups() ! # get hacky - get the *real* exception object from the name. ! bits = exc_type.split(".", 1) ! if len(bits) > 1: ! mod = __import__(bits[0]) ! exc = getattr(mod, bits[1]) ! else: ! # probably builtin ! exc = eval(bits[0]) ! else: ! # hrm - probably just an exception with no args ! try: ! exc = eval(line.strip()) ! args = "()" ! except: ! return None ! # try and turn the args into real args. ! try: ! args = eval(args) ! except: ! pass ! if not isinstance(args, tuple): ! args = (args,) ! # try and instantiate the exception. ! try: ! ret = exc(*args) ! except: ! ret = None ! return ret ! # apparently not - keep looking... ! have_traceback = False ! class TestRunner: *************** *** 42,45 **** --- 90,97 ---- if rc: base = os.path.basename(self.argv[1]) + # See if we can detect and reconstruct an exception in the output. + reconstituted = find_exception_in_output(output) + if reconstituted is not None: + raise reconstituted raise AssertionError("%s failed with exit code %s. Output is:\n%s" % (base, rc, output)) *************** *** 53,59 **** if ext != ".py" or base in ui_demos or base in bad_demos: continue - if base in ok_exceptions: - print("Ack - can't handle test %s - can't catch specific exceptions" % (base,)) - continue argv = (sys.executable, os.path.join(demo_dir, base+".py")) + \ argvs.get(base, ()) --- 105,108 ---- *************** *** 100,106 **** try: mod = __import__(base) ! except ImportError as why: ! print("FAILED to import test module") ! print(why) continue if hasattr(mod, "suite"): --- 149,155 ---- try: mod = __import__(base) ! except: ! print("FAILED to import test module %r" % base) ! traceback.print_exc() continue if hasattr(mod, "suite"): *************** *** 113,120 **** return suite ! class CustomLoader(unittest.TestLoader): def loadTestsFromModule(self, module): ! return suite() if __name__=='__main__': ! unittest.TestProgram(testLoader=CustomLoader())(argv=sys.argv) --- 162,169 ---- return suite ! class CustomLoader(pywin32_testutil.TestLoader): def loadTestsFromModule(self, module): ! return self.fixupTestsForLeakTests(suite()) if __name__=='__main__': ! pywin32_testutil.testmain(testLoader=CustomLoader()) |
From: Mark H. <mha...@us...> - 2009-01-07 06:25:24
|
Update of /cvsroot/pywin32/pywin32/com/win32com/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv7136/com/win32com/test Modified Files: Tag: py3k testClipboard.py testShell.py testStreams.py testvb.py util.py Log Message: merge recent test changes from the trunk Index: testStreams.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testStreams.py,v retrieving revision 1.6.2.2 retrieving revision 1.6.2.3 diff -C2 -d -r1.6.2.2 -r1.6.2.3 *** testStreams.py 5 Jan 2009 12:51:27 -0000 1.6.2.2 --- testStreams.py 7 Jan 2009 06:25:15 -0000 1.6.2.3 *************** *** 4,7 **** --- 4,8 ---- import unittest + from pywin32_testutil import str2bytes class Persists: *************** *** 10,14 **** _com_interfaces_ = [ pythoncom.IID_IPersistStreamInit ] def __init__(self): ! self.data = "abcdefg".encode("ascii") self.dirty = 1 def GetClassID(self): --- 11,15 ---- _com_interfaces_ = [ pythoncom.IID_IPersistStreamInit ] def __init__(self): ! self.data = str2bytes("abcdefg") self.dirty = 1 def GetClassID(self): *************** *** 67,71 **** """ def Read(self, amount): ! return 'x'.encode('ascii')*(amount+1) class StreamTest(win32com.test.util.TestCase): --- 68,72 ---- """ def Read(self, amount): ! return str2bytes('x')*(amount+1) class StreamTest(win32com.test.util.TestCase): *************** *** 81,85 **** def testit(self): ! mydata = 'abcdefghijklmnopqrstuvwxyz'.encode('ascii') # First test the objects just as Python objects... --- 82,86 ---- def testit(self): ! mydata = str2bytes('abcdefghijklmnopqrstuvwxyz') # First test the objects just as Python objects... *************** *** 101,105 **** self._readWrite(mydata, s2, s2) ! self._readWrite("string with\0a NULL".encode('ascii'), s2, s2) # reset the stream s.Write(mydata) --- 102,106 ---- self._readWrite(mydata, s2, s2) ! self._readWrite(str2bytes("string with\0a NULL"), s2, s2) # reset the stream s.Write(mydata) Index: testvb.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testvb.py,v retrieving revision 1.20.4.6 retrieving revision 1.20.4.7 diff -C2 -d -r1.20.4.6 -r1.20.4.7 *** testvb.py 5 Jan 2009 12:51:27 -0000 1.20.4.6 --- testvb.py 7 Jan 2009 06:25:15 -0000 1.20.4.7 *************** *** 9,21 **** from win32com.server.util import NewCollection, wrap from win32com.test import util import traceback - def string_to_buffer(s): - if sys.version_info < (3,0): - return buffer(s) - else: - return memoryview(s.encode("ascii")) - # for debugging useDispatcher = None --- 9,16 ---- from win32com.server.util import NewCollection, wrap from win32com.test import util + from pywin32_testutil import str2memory import traceback # for debugging useDispatcher = None *************** *** 74,79 **** if vbtest.VariantProperty != 10: raise error("Could not set the variant integer property correctly.") ! vbtest.VariantProperty = string_to_buffer('raw\0data') ! if vbtest.VariantProperty != string_to_buffer('raw\0data'): raise error("Could not set the variant buffer property correctly.") vbtest.StringProperty = "Hello from Python" --- 69,74 ---- if vbtest.VariantProperty != 10: raise error("Could not set the variant integer property correctly.") ! vbtest.VariantProperty = str2memory('raw\0data') ! if vbtest.VariantProperty != str2memory('raw\0data'): raise error("Could not set the variant buffer property correctly.") vbtest.StringProperty = "Hello from Python" Index: util.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/util.py,v retrieving revision 1.9.2.7 retrieving revision 1.9.2.8 diff -C2 -d -r1.9.2.7 -r1.9.2.8 *** util.py 5 Jan 2009 12:51:27 -0000 1.9.2.7 --- util.py 7 Jan 2009 06:25:15 -0000 1.9.2.8 *************** *** 12,15 **** --- 12,18 ---- import io as StringIO + import pywin32_testutil + from pywin32_testutil import TestLoader, TestResult, TestRunner, LeakTestCase + def CheckClean(): # Ensure no lingering exceptions - Python should have zero outstanding *************** *** 143,259 **** return len("".join(self.captured).split("\n")) - class LeakTestCase(unittest.TestCase): - def __init__(self, real_test): - unittest.TestCase.__init__(self) - self.real_test = real_test - self.num_test_cases = 1 - self.num_leak_iters = 2 # seems to be enough! - if hasattr(sys, "gettotalrefcount"): - self.num_test_cases = self.num_test_cases + self.num_leak_iters - def countTestCases(self): - return self.num_test_cases - def runTest(self): - assert 0, "not used" - def __call__(self, result = None): - # Always ensure we don't leak gateways/interfaces - gc.collect() - ni = _GetInterfaceCount() - ng = _GetGatewayCount() - self.real_test(result) - # Failed - no point checking anything else - if result.shouldStop or not result.wasSuccessful(): - return - self._do_leak_tests(result) - gc.collect() - lost_i = _GetInterfaceCount() - ni - lost_g = _GetGatewayCount() - ng - if lost_i or lost_g: - msg = "%d interface objects and %d gateway objects leaked" \ - % (lost_i, lost_g) - result.addFailure(self.real_test, (AssertionError, msg, None)) - def _do_leak_tests(self, result = None): - try: - gtrc = sys.gettotalrefcount - except AttributeError: - return # can't do leak tests in this build - def gtrc(): - return 0 - # Assume already called once, to prime any caches etc - trc = gtrc() - for i in range(self.num_leak_iters): - self.real_test(result) - if result.shouldStop: - break - del i # created after we remembered the refcount! - # int division here means one or 2 stray references won't force - # failure, but one per loop - gc.collect() - lost = (gtrc() - trc) // self.num_leak_iters - if lost < 0: - msg = "LeakTest: %s appeared to gain %d references!!" % (self.real_test, -lost) - result.addFailure(self.real_test, (AssertionError, msg, None)) - if lost > 0: - msg = "LeakTest: %s lost %d references" % (self.real_test, lost) - result.addFailure(self.real_test, (AssertionError, msg, None)) - - class TestLoader(unittest.TestLoader): - def loadTestsFromTestCase(self, testCaseClass): - """Return a suite of all tests cases contained in testCaseClass""" - leak_tests = [] - for name in self.getTestCaseNames(testCaseClass): - real_test = testCaseClass(name) - leak_test = self._getTestWrapper(real_test) - leak_tests.append(leak_test) - return self.suiteClass(leak_tests) - def _getTestWrapper(self, test): - no_leak_tests = getattr(test, "no_leak_tests", False) - if no_leak_tests: - print("Test says it doesn't want leak tests!") - return test - return LeakTestCase(test) - def loadTestsFromModule(self, mod): - if hasattr(mod, "suite"): - return mod.suite() - else: - return unittest.TestLoader.loadTestsFromModule(self, mod) - def loadTestsFromName(self, name, module=None): - test = unittest.TestLoader.loadTestsFromName(self, name, module) - if isinstance(test, unittest.TestSuite): - pass # hmmm? print "Don't wrap suites yet!", test._tests - elif isinstance(test, unittest.TestCase): - test = self._getTestWrapper(test) - else: - print("XXX - what is", test) - return test - - class TestResult(unittest._TextTestResult): - def __init__(self, *args, **kw): - super(TestResult, self).__init__(*args, **kw) - self.num_invalid_clsid = 0 - - def addError(self, test, err): - """Called when an error has occurred. 'err' is a tuple of values as - returned by sys.exc_info(). - """ - if isinstance(err[1], pythoncom.com_error) and \ - err[1].hresult==winerror.CO_E_CLASSSTRING: - self.num_invalid_clsid += 1 - if self.showAll: - self.stream.writeln("SKIP") - elif self.dots: - self.stream.write('S') - self.stream.flush() - return - super(TestResult, self).addError(test, err) - - def printErrors(self): - super(TestResult, self).printErrors() - if self.num_invalid_clsid: - self.stream.writeln("SKIPPED: %d tests due to missing COM objects used for testing" % - self.num_invalid_clsid) - - class TestRunner(unittest.TextTestRunner): - def _makeResult(self): - return TestResult(self.stream, self.descriptions, self.verbosity) # Utilities to set the win32com logger to something what just captures --- 146,149 ---- *************** *** 331,344 **** return "exec: " + cmd_repr ! class TestProgram(unittest.TestProgram): ! def runTests(self): ! if self.testRunner is None: ! self.testRunner = TestRunner(verbosity=self.verbosity) ! unittest.TestProgram(self) ! def testmain(*args, **kw): ! new_kw = kw.copy() ! if 'testLoader' not in new_kw: ! new_kw['testLoader'] = TestLoader() ! unittest.main(*args, **new_kw) CheckClean() --- 221,226 ---- return "exec: " + cmd_repr ! def testmain(*args, **kw): ! pywin32_testutil.testmain(*args, **new_kw) CheckClean() Index: testShell.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testShell.py,v retrieving revision 1.10.4.4 retrieving revision 1.10.4.5 diff -C2 -d -r1.10.4.4 -r1.10.4.5 *** testShell.py 27 Nov 2008 11:31:05 -0000 1.10.4.4 --- testShell.py 7 Jan 2009 06:25:15 -0000 1.10.4.5 *************** *** 16,19 **** --- 16,20 ---- import win32com.test.util + from pywin32_testutil import str2bytes class ShellTester(win32com.test.util.TestCase): *************** *** 75,94 **** def testPIDL(self): # A PIDL of "\1" is: cb pidl cb ! expect = b"\03\00" b"\1" b"\0\0" ! self.assertEqual(shell.PIDLAsString([b"\1"]), expect) ! self._rtPIDL([b"\0"]) ! self._rtPIDL([b"\1", b"\2", b"\3"]) ! self._rtPIDL([b"\0" * 2048] * 2048) # PIDL must be a list self.assertRaises(TypeError, shell.PIDLAsString, "foo") def testCIDA(self): ! self._rtCIDA([b"\0"], [ [b"\0"] ]) ! self._rtCIDA([b"\1"], [ [b"\2"] ]) ! self._rtCIDA([b"\0"], [ [b"\0"], [b"\1"], [b"\2"] ]) def testBadShortPIDL(self): # A too-short child element: cb pidl cb ! pidl = b"\01\00" b"\1" self.assertRaises(ValueError, shell.StringAsPIDL, pidl) --- 76,95 ---- def testPIDL(self): # A PIDL of "\1" is: cb pidl cb ! expect = str2bytes("\03\00" "\1" "\0\0") ! self.assertEqual(shell.PIDLAsString([str2bytes("\1")]), expect) ! self._rtPIDL([str2bytes("\0")]) ! self._rtPIDL([str2bytes("\1"), str2bytes("\2"), str2bytes("\3")]) ! self._rtPIDL([str2bytes("\0") * 2048] * 2048) # PIDL must be a list self.assertRaises(TypeError, shell.PIDLAsString, "foo") def testCIDA(self): ! self._rtCIDA([str2bytes("\0")], [ [str2bytes("\0")] ]) ! self._rtCIDA([str2bytes("\1")], [ [str2bytes("\2")] ]) ! self._rtCIDA([str2bytes("\0")], [ [str2bytes("\0")], [str2bytes("\1")], [str2bytes("\2")] ]) def testBadShortPIDL(self): # A too-short child element: cb pidl cb ! pidl = str2bytes("\01\00" "\1") self.assertRaises(ValueError, shell.StringAsPIDL, pidl) *************** *** 182,186 **** self.src_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell") self.dest_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell_dest") ! self.test_data = b"Hello from\0Python" f=open(self.src_name, "wb") f.write(self.test_data) --- 183,187 ---- self.src_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell") self.dest_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell_dest") ! self.test_data = str2bytes("Hello from\0Python") f=open(self.src_name, "wb") f.write(self.test_data) Index: testClipboard.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testClipboard.py,v retrieving revision 1.2.4.2 retrieving revision 1.2.4.3 diff -C2 -d -r1.2.4.2 -r1.2.4.3 *** testClipboard.py 27 Nov 2008 04:58:41 -0000 1.2.4.2 --- testClipboard.py 7 Jan 2009 06:25:15 -0000 1.2.4.3 *************** *** 6,9 **** --- 6,11 ---- import win32clipboard + from pywin32_testutil import str2bytes + from win32com.server.util import NewEnum, wrap from win32com.server.exception import COMException *************** *** 47,51 **** ret_stg = pythoncom.STGMEDIUM() # ensure always 'bytes' by encoding string. ! ret_stg.set(pythoncom.TYMED_HGLOBAL, self.strval.encode("ascii")) elif cf == win32con.CF_UNICODETEXT: ret_stg = pythoncom.STGMEDIUM() --- 49,53 ---- ret_stg = pythoncom.STGMEDIUM() # ensure always 'bytes' by encoding string. ! ret_stg.set(pythoncom.TYMED_HGLOBAL, str2bytes(self.strval)) elif cf == win32con.CF_UNICODETEXT: ret_stg = pythoncom.STGMEDIUM() *************** *** 111,116 **** win32clipboard.OpenClipboard() got = win32clipboard.GetClipboardData(win32con.CF_TEXT) ! # CF_TEXT gives bytes on py3k - use encode() to ensure that's true. ! expected = "Hello from Python".encode("ascii") self.assertEqual(got, expected) # Now check unicode --- 113,118 ---- win32clipboard.OpenClipboard() got = win32clipboard.GetClipboardData(win32con.CF_TEXT) ! # CF_TEXT gives bytes on py3k - use str2bytes() to ensure that's true. ! expected = str2bytes("Hello from Python") self.assertEqual(got, expected) # Now check unicode *************** *** 121,125 **** def testWin32ToCom(self): # Set the data via the std win32 clipboard functions. ! val = "Hello again!".encode("ascii") # ensure always bytes, even in py3k win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32con.CF_TEXT, val) --- 123,127 ---- def testWin32ToCom(self): # Set the data via the std win32 clipboard functions. ! val = str2bytes("Hello again!") # ensure always bytes, even in py3k win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32con.CF_TEXT, val) *************** *** 133,137 **** # knowing if it meant to be a string, or a binary buffer, so # it must return it too. ! self.failUnlessEqual(got, "Hello again!\0".encode("ascii")) def testDataObjectFlush(self): --- 135,139 ---- # knowing if it meant to be a string, or a binary buffer, so # it must return it too. ! self.failUnlessEqual(got, str2bytes("Hello again!\0")) def testDataObjectFlush(self): |
From: Mark H. <mha...@us...> - 2009-01-07 06:25:23
|
Update of /cvsroot/pywin32/pywin32/win32/Demos In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv7136/win32/Demos Modified Files: Tag: py3k BackupRead_BackupWrite.py CreateFileTransacted_MiniVersion.py eventLogDemo.py mmapfile_demo.py win32clipboardDemo.py win32fileDemo.py Log Message: merge recent test changes from the trunk Index: CreateFileTransacted_MiniVersion.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/CreateFileTransacted_MiniVersion.py,v retrieving revision 1.2.2.1 retrieving revision 1.2.2.2 diff -C2 -d -r1.2.2.1 -r1.2.2.2 *** CreateFileTransacted_MiniVersion.py 29 Aug 2008 04:59:23 -0000 1.2.2.1 --- CreateFileTransacted_MiniVersion.py 7 Jan 2009 06:25:15 -0000 1.2.2.2 *************** *** 8,11 **** --- 8,13 ---- import win32con, winioctlcon import struct + import os + from pywin32_testutil import str2bytes # py3k-friendly helper """ *************** *** 22,26 **** tempdir=win32api.GetTempPath() tempfile=win32api.GetTempFileName(tempdir,'cft')[0] ! print(tempfile) f=open(tempfile,'w') f.write('This is original file.\n') --- 24,28 ---- tempdir=win32api.GetTempPath() tempfile=win32api.GetTempFileName(tempdir,'cft')[0] ! print("Demonstrating transactions on tempfile", tempfile) f=open(tempfile,'w') f.write('This is original file.\n') *************** *** 32,42 **** None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans) ! win32file.WriteFile(hfile, 'This is first miniversion.\n') ! buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,'',buf_size,None) struct_ver, struct_len, base_ver, ver_1=struct.unpack(buf_fmt, buf) win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN) ! win32file.WriteFile(hfile, 'This is second miniversion!\n') ! buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,'',buf_size,None) struct_ver, struct_len, base_ver, ver_2=struct.unpack(buf_fmt, buf) hfile.Close() --- 34,44 ---- None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans) ! win32file.WriteFile(hfile, str2bytes('This is first miniversion.\n')) ! buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,None,buf_size,None) struct_ver, struct_len, base_ver, ver_1=struct.unpack(buf_fmt, buf) win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN) ! win32file.WriteFile(hfile, str2bytes('This is second miniversion!\n')) ! buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,None,buf_size,None) struct_ver, struct_len, base_ver, ver_2=struct.unpack(buf_fmt, buf) hfile.Close() *************** *** 63,64 **** --- 65,68 ---- ## MiniVersions are destroyed when transaction is committed or rolled back win32transaction.CommitTransaction(trans) + + os.unlink(tempfile) Index: win32fileDemo.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/win32fileDemo.py,v retrieving revision 1.6.4.4 retrieving revision 1.6.4.5 diff -C2 -d -r1.6.4.4 -r1.6.4.5 *** win32fileDemo.py 11 Dec 2008 07:06:51 -0000 1.6.4.4 --- win32fileDemo.py 7 Jan 2009 06:25:15 -0000 1.6.4.5 *************** *** 21,26 **** 0, None) ! test_data = "Hello\0there" ! win32file.WriteFile(handle, test_data.encode('ascii')) handle.Close() # Open it for reading. --- 21,26 ---- 0, None) ! test_data = "Hello\0there".encode("ascii") ! win32file.WriteFile(handle, test_data) handle.Close() # Open it for reading. *************** *** 28,33 **** rc, data = win32file.ReadFile(handle, 1024) handle.Close() ! if data.decode('ascii') == test_data: print("Successfully wrote and read a file") os.unlink(testName) --- 28,35 ---- rc, data = win32file.ReadFile(handle, 1024) handle.Close() ! if data == test_data: print("Successfully wrote and read a file") + else: + raise Exception("Got different data back???") os.unlink(testName) Index: mmapfile_demo.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/mmapfile_demo.py,v retrieving revision 1.1.2.1 retrieving revision 1.1.2.2 diff -C2 -d -r1.1.2.1 -r1.1.2.2 *** mmapfile_demo.py 29 Aug 2008 04:59:23 -0000 1.1.2.1 --- mmapfile_demo.py 7 Jan 2009 06:25:15 -0000 1.1.2.2 *************** *** 1,4 **** --- 1,7 ---- import win32api, mmapfile + import winerror import tempfile, os + from pywin32_testutil import str2bytes + system_info=win32api.GetSystemInfo() page_size=system_info[1] *************** *** 12,18 **** m1=mmapfile.mmapfile(File=fname, Name=mapping_name, MaximumSize=fsize) m1.seek(100) ! m1.write_byte(b'?') m1.seek(-1,1) ! assert m1.read_byte()==b'?' ## A reopened named mapping should have exact same size as original mapping --- 15,21 ---- m1=mmapfile.mmapfile(File=fname, Name=mapping_name, MaximumSize=fsize) m1.seek(100) ! m1.write_byte(str2bytes('?')) m1.seek(-1,1) ! assert m1.read_byte()==str2bytes('?') ## A reopened named mapping should have exact same size as original mapping *************** *** 20,25 **** assert m2.size()==m1.size() m1.seek(0,0) ! m1.write(fsize*b's') ! assert m2.read(fsize)==fsize*b's' move_src=100 --- 23,28 ---- assert m2.size()==m1.size() m1.seek(0,0) ! m1.write(fsize*str2bytes('s')) ! assert m2.read(fsize)==fsize*str2bytes('s') move_src=100 *************** *** 29,36 **** m2.seek(move_src,0) assert m2.tell()==move_src ! m2.write(b'm'*move_size) m2.move(move_dest, move_src, move_size) m2.seek(move_dest, 0) ! assert m2.read(move_size) == b'm' * move_size ## m2.write('x'* (fsize+1)) --- 32,39 ---- m2.seek(move_src,0) assert m2.tell()==move_src ! m2.write(str2bytes('m')*move_size) m2.move(move_dest, move_src, move_size) m2.seek(move_dest, 0) ! assert m2.read(move_size) == str2bytes('m') * move_size ## m2.write('x'* (fsize+1)) *************** *** 39,43 **** assert m1.size()==fsize * 2 m1.seek(fsize) ! m1.write(b'w' * fsize) m1.flush() m1.close() --- 42,46 ---- assert m1.size()==fsize * 2 m1.seek(fsize) ! m1.write(str2bytes('w') * fsize) m1.flush() m1.close() *************** *** 50,54 **** fname_large=tempfile.mktemp() mapping_name='Pywin32_large_mmap' ! offsetdata=b'This is start of offset' ## Deliberately use odd numbers to test rounding logic --- 53,57 ---- fname_large=tempfile.mktemp() mapping_name='Pywin32_large_mmap' ! offsetdata=str2bytes('This is start of offset') ## Deliberately use odd numbers to test rounding logic *************** *** 68,80 **** m2=None try: ! m1=mmapfile.mmapfile(fname_large, mapping_name, fsize, 0, offset*2) ! m1.seek(offset) ! m1.write(offsetdata) ! ! ## When reopening an existing mapping without passing a file handle, you have ! ## to specify a positive size even though it's ignored ! m2=mmapfile.mmapfile(File=None, Name=mapping_name, MaximumSize=1, ! FileOffset=offset, NumberOfBytesToMap=view_size) ! assert m2.read(len(offsetdata))==offsetdata finally: if m1 is not None: --- 71,90 ---- m2=None try: ! try: ! m1=mmapfile.mmapfile(fname_large, mapping_name, fsize, 0, offset*2) ! except mmapfile.error as exc: ! # if we don't have enough disk-space, that's OK. ! if exc.winerror!=winerror.ERROR_DISK_FULL: ! raise ! print("skipping large file test - need", fsize, "available bytes.") ! else: ! m1.seek(offset) ! m1.write(offsetdata) ! ! ## When reopening an existing mapping without passing a file handle, you have ! ## to specify a positive size even though it's ignored ! m2=mmapfile.mmapfile(File=None, Name=mapping_name, MaximumSize=1, ! FileOffset=offset, NumberOfBytesToMap=view_size) ! assert m2.read(len(offsetdata))==offsetdata finally: if m1 is not None: Index: BackupRead_BackupWrite.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/BackupRead_BackupWrite.py,v retrieving revision 1.1.4.1 retrieving revision 1.1.4.2 diff -C2 -d -r1.1.4.1 -r1.1.4.2 *** BackupRead_BackupWrite.py 29 Aug 2008 04:59:23 -0000 1.1.4.1 --- BackupRead_BackupWrite.py 7 Jan 2009 06:25:15 -0000 1.1.4.2 *************** *** 5,8 **** --- 5,9 ---- import pythoncom, pywintypes import struct, traceback + from pywin32_testutil import str2bytes, ob2memory all_sd_info=win32security.DACL_SECURITY_INFORMATION|win32security.DACL_SECURITY_INFORMATION| \ *************** *** 69,73 **** print('Written:',bytes_written,'Context:',outctxt) win32file.BackupRead(h, 0, buf, True, True, ctxt) ! win32file.BackupWrite(outh, 0, b'', True, True, outctxt) win32file.CloseHandle(h) win32file.CloseHandle(outh) --- 70,74 ---- print('Written:',bytes_written,'Context:',outctxt) win32file.BackupRead(h, 0, buf, True, True, ctxt) ! win32file.BackupWrite(outh, 0, str2bytes(''), True, True, outctxt) win32file.CloseHandle(h) win32file.CloseHandle(outh) *************** *** 76,80 **** assert open(tempfile+':streamdata').read()==open(outfile+':streamdata').read(),"streamdata contents differ !" assert open(tempfile+':anotherstream').read()==open(outfile+':anotherstream').read(),"anotherstream contents differ !" ! assert bytes(win32security.GetFileSecurity(tempfile,all_sd_info))[:]== \ ! bytes(win32security.GetFileSecurity(outfile, all_sd_info))[:], "Security descriptors are different !" ## also should check Summary Info programatically --- 77,81 ---- assert open(tempfile+':streamdata').read()==open(outfile+':streamdata').read(),"streamdata contents differ !" assert open(tempfile+':anotherstream').read()==open(outfile+':anotherstream').read(),"anotherstream contents differ !" ! assert ob2memory(win32security.GetFileSecurity(tempfile,all_sd_info))[:]== \ ! ob2memory(win32security.GetFileSecurity(outfile, all_sd_info))[:], "Security descriptors are different !" ## also should check Summary Info programatically Index: eventLogDemo.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/eventLogDemo.py,v retrieving revision 1.5.4.4 retrieving revision 1.5.4.5 diff -C2 -d -r1.5.4.4 -r1.5.4.5 *** eventLogDemo.py 11 Dec 2008 07:17:46 -0000 1.5.4.4 --- eventLogDemo.py 7 Jan 2009 06:25:15 -0000 1.5.4.5 *************** *** 90,100 **** win32evtlogutil.ReportEvent(logType, 2, strings=["The message text for event 2","Another insert"], ! data = b"Raw\0Data", sid = my_sid) win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE, strings=["A warning","An even more dire warning"], ! data = b"Raw\0Data", sid = my_sid) win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["An info","Too much info"], ! data = b"Raw\0Data", sid = my_sid) print("Successfully wrote 3 records to the log") --- 90,100 ---- win32evtlogutil.ReportEvent(logType, 2, strings=["The message text for event 2","Another insert"], ! data = "Raw\0Data".encode("ascii"), sid = my_sid) win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE, strings=["A warning","An even more dire warning"], ! data = "Raw\0Data".encode("ascii"), sid = my_sid) win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["An info","Too much info"], ! data = "Raw\0Data".encode("ascii"), sid = my_sid) print("Successfully wrote 3 records to the log") Index: win32clipboardDemo.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/win32clipboardDemo.py,v retrieving revision 1.2.4.1 retrieving revision 1.2.4.2 diff -C2 -d -r1.2.4.1 -r1.2.4.2 *** win32clipboardDemo.py 29 Aug 2008 04:59:23 -0000 1.2.4.1 --- win32clipboardDemo.py 7 Jan 2009 06:25:15 -0000 1.2.4.2 *************** *** 3,6 **** --- 3,7 ---- # Demo/test of the win32clipboard module. from win32clipboard import * + from pywin32_testutil import str2bytes # py3k-friendly helper import win32con import types *************** *** 28,37 **** try: text = "Hello from Python" SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) ! assert got == text, "Didnt get the correct result back - '%r'." % (got,) ! # Win32 documentation says I can get the result back as CF_UNICODE or CF_OEMTEXT. ! # But it appears I need to close the clipboard for this to kick-in. ! # but if I attempt to, it fails! finally: CloseClipboard() --- 29,37 ---- try: text = "Hello from Python" + text_bytes = str2bytes(text) SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) ! # CF_TEXT always gives us 'bytes' back . ! assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) finally: CloseClipboard() *************** *** 39,52 **** OpenClipboard() try: got = GetClipboardData(win32con.CF_UNICODETEXT) assert got == text, "Didnt get the correct result back - '%r'." % (got,) assert type(got)==str, "Didnt get the correct result back - '%r'." % (got,) got = GetClipboardData(win32con.CF_OEMTEXT) ! assert got == text, "Didnt get the correct result back - '%r'." % (got,) # Unicode tests EmptyClipboard() text = "Hello from Python unicode" # Now set the Unicode value SetClipboardData(win32con.CF_UNICODETEXT, text) --- 39,55 ---- OpenClipboard() try: + # CF_UNICODE text always gives unicode objects back. got = GetClipboardData(win32con.CF_UNICODETEXT) assert got == text, "Didnt get the correct result back - '%r'." % (got,) assert type(got)==str, "Didnt get the correct result back - '%r'." % (got,) + # CF_OEMTEXT is a bytes-based format. got = GetClipboardData(win32con.CF_OEMTEXT) ! assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) # Unicode tests EmptyClipboard() text = "Hello from Python unicode" + text_bytes = str2bytes(text) # Now set the Unicode value SetClipboardData(win32con.CF_UNICODETEXT, text) *************** *** 63,74 **** try: ! # Make sure I can still get the text. got = GetClipboardData(win32con.CF_TEXT) ! assert got == text, "Didnt get the correct result back - '%r'." % (got,) # Make sure we get back the correct types. got = GetClipboardData(win32con.CF_UNICODETEXT) assert type(got)==str, "Didnt get the correct result back - '%r'." % (got,) got = GetClipboardData(win32con.CF_OEMTEXT) ! assert got == text, "Didnt get the correct result back - '%r'." % (got,) print("Clipboard text tests worked correctly") finally: --- 66,77 ---- try: ! # Make sure I can still get the text as bytes got = GetClipboardData(win32con.CF_TEXT) ! assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) # Make sure we get back the correct types. got = GetClipboardData(win32con.CF_UNICODETEXT) assert type(got)==str, "Didnt get the correct result back - '%r'." % (got,) got = GetClipboardData(win32con.CF_OEMTEXT) ! assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) print("Clipboard text tests worked correctly") finally: *************** *** 102,105 **** --- 105,110 ---- def __cmp__(self, other): return cmp(self.__dict__, other.__dict__) + def __eq__(self, other): + return self.__dict__==other.__dict__ def TestCustomFormat(): |
From: Mark H. <mha...@us...> - 2009-01-07 06:25:19
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv7136/win32/Lib Modified Files: Tag: py3k sspi.py Added Files: Tag: py3k pywin32_testutil.py Log Message: merge recent test changes from the trunk Index: sspi.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/sspi.py,v retrieving revision 1.3.4.2 retrieving revision 1.3.4.3 diff -C2 -d -r1.3.4.2 -r1.3.4.3 *** sspi.py 26 Sep 2008 00:37:23 -0000 1.3.4.2 --- sspi.py 7 Jan 2009 06:25:16 -0000 1.3.4.3 *************** *** 218,225 **** if err==0: break ! sig = sspiclient.sign(b"hello") ! sspiserver.verify(b"hello", sig) ! data, key = sspiclient.encrypt(b"hello") ! assert sspiserver.decrypt(data, key) == b"hello" print("cool!") --- 218,226 ---- if err==0: break ! data = "hello".encode("ascii") # py3k-friendly ! sig = sspiclient.sign(data) ! sspiserver.verify(data, sig) ! data, key = sspiclient.encrypt(data) ! assert sspiserver.decrypt(data, key) == data print("cool!") --- NEW FILE: pywin32_testutil.py --- # Utilities for the pywin32 tests import sys import unittest import gc import winerror ## ## General purpose utilities for the test suite. ## # The test suite has lots of string constants containing binary data, but # the strings are used in various "bytes" contexts. def str2bytes(sval): if sys.version_info < (3,0) and isinstance(sval, str): sval = sval.decode("latin1") return sval.encode("latin1") # Sometimes we want to pass a string that should explicitly be treated as # a memory blob. def str2memory(sval): if sys.version_info < (3,0): return buffer(sval) # py3k. return memoryview(sval.encode("latin1")) # Sometimes we want to pass an object that exposes its memory def ob2memory(ob): if sys.version_info < (3,0): return buffer(ob) # py3k. return memoryview(ob) # Note: no str2unicode: we use u'' literals or unicode() function, and 2to3 # ## ## unittest related stuff ## # This is a specialized TestCase adaptor which wraps a real test. class LeakTestCase(unittest.TestCase): """An 'adaptor' which takes another test. In debug builds we execute the test once to remove one-off side-effects, then capture the total reference count, then execute the test a few times. If the total refcount at the end is greater than we first captured, we have a leak! In release builds the test is executed just once, as normal. Generally used automatically by the test runner - you can safely ignore this. """ def __init__(self, real_test): unittest.TestCase.__init__(self) self.real_test = real_test self.num_test_cases = 1 self.num_leak_iters = 2 # seems to be enough! if hasattr(sys, "gettotalrefcount"): self.num_test_cases = self.num_test_cases + self.num_leak_iters def countTestCases(self): return self.num_test_cases def __call__(self, result = None): # For the COM suite's sake, always ensure we don't leak # gateways/interfaces from pythoncom import _GetInterfaceCount, _GetGatewayCount gc.collect() ni = _GetInterfaceCount() ng = _GetGatewayCount() self.real_test(result) # Failed - no point checking anything else if result.shouldStop or not result.wasSuccessful(): return self._do_leak_tests(result) gc.collect() lost_i = _GetInterfaceCount() - ni lost_g = _GetGatewayCount() - ng if lost_i or lost_g: msg = "%d interface objects and %d gateway objects leaked" \ % (lost_i, lost_g) result.addFailure(self.real_test, (AssertionError, msg, None)) def runTest(self): assert 0, "not used" def _do_leak_tests(self, result = None): try: gtrc = sys.gettotalrefcount except AttributeError: return # can't do leak tests in this build # Assume already called once, to prime any caches etc gc.collect() trc = gtrc() for i in range(self.num_leak_iters): self.real_test(result) if result.shouldStop: break del i # created after we remembered the refcount! # int division here means one or 2 stray references won't force # failure, but one per loop gc.collect() lost = (gtrc() - trc) // self.num_leak_iters if lost < 0: msg = "LeakTest: %s appeared to gain %d references!!" % (self.real_test, -lost) result.addFailure(self.real_test, (AssertionError, msg, None)) if lost > 0: msg = "LeakTest: %s lost %d references" % (self.real_test, lost) result.addFailure(self.real_test, (AssertionError, msg, None)) class TestLoader(unittest.TestLoader): def loadTestsFromTestCase(self, testCaseClass): """Return a suite of all tests cases contained in testCaseClass""" leak_tests = [] for name in self.getTestCaseNames(testCaseClass): real_test = testCaseClass(name) leak_test = self._getTestWrapper(real_test) leak_tests.append(leak_test) return self.suiteClass(leak_tests) def fixupTestsForLeakTests(self, test): if isinstance(test, unittest.TestSuite): test._tests = [self.fixupTestsForLeakTests(t) for t in test._tests] return test else: # just a normal test case. return self._getTestWrapper(test) def _getTestWrapper(self, test): # one or 2 tests in the COM test suite set this... no_leak_tests = getattr(test, "no_leak_tests", False) if no_leak_tests: print("Test says it doesn't want leak tests!") return test return LeakTestCase(test) def loadTestsFromModule(self, mod): if hasattr(mod, "suite"): tests = mod.suite() else: tests = unittest.TestLoader.loadTestsFromModule(self, mod) return self.fixupTestsForLeakTests(tests) def loadTestsFromName(self, name, module=None): test = unittest.TestLoader.loadTestsFromName(self, name, module) if isinstance(test, unittest.TestSuite): pass # hmmm? print "Don't wrap suites yet!", test._tests elif isinstance(test, unittest.TestCase): test = self._getTestWrapper(test) else: print("XXX - what is", test) return test # Lots of classes necessary to support one simple feature: we want a 3rd # test result state - "SKIPPED" - to indicate that the test wasn't able # to be executed for various reasons. Inspired by bzr's tests, but it # has other concepts, such as "Expected Failure", which we don't bother # with. # win32 error codes that probably mean we need to be elevated (ie, if we # aren't elevated, we treat these error codes as 'skipped') non_admin_error_codes = [winerror.ERROR_ACCESS_DENIED, winerror.ERROR_PRIVILEGE_NOT_HELD] _is_admin = None def check_is_admin(): global _is_admin if _is_admin is None: from win32com.shell.shell import IsUserAnAdmin try: _is_admin = IsUserAnAdmin() except NotImplementedError: # not impl on this platform - must be old - assume is admin _is_admin = True return _is_admin # If this exception is raised by a test, the test is reported as a 'skip' class TestSkipped(Exception): pass # The 'TestResult' subclass that records the failures and has the special # handling for the TestSkipped exception. class TestResult(unittest._TextTestResult): def __init__(self, *args, **kw): super(TestResult, self).__init__(*args, **kw) self.num_skipped = 0 def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ # translate a couple of 'well-known' exceptions into 'skipped' import pywintypes exc_val = err[1] # translate ERROR_ACCESS_DENIED for non-admin users to be skipped. # (access denied errors for an admin user aren't expected.) if isinstance(exc_val, pywintypes.error) \ and exc_val.winerror in non_admin_error_codes \ and not check_is_admin(): exc_val = TestSkipped(exc_val) # and COM errors due to objects not being registered (the com test # suite will attempt to catch this and handle it itself if the user # is admin) elif isinstance(exc_val, pywintypes.com_error) and \ exc_val.hresult==winerror.CO_E_CLASSSTRING: exc_val = TestSkipped(exc_val) # NotImplemented generally means the platform doesn't support the # functionality. elif isinstance(exc_val, NotImplementedError): exc_val = TestSkipped(NotImplementedError) if isinstance(exc_val, TestSkipped): self.num_skipped += 1 if self.showAll: self.stream.writeln("SKIP") elif self.dots: self.stream.write('S') self.stream.flush() return super(TestResult, self).addError(test, err) def printErrors(self): super(TestResult, self).printErrors() if self.num_skipped: self.stream.writeln("SKIPPED: %d tests" % self.num_skipped) # TestRunner subclass necessary just to get our TestResult hooked up. class TestRunner(unittest.TextTestRunner): def _makeResult(self): return TestResult(self.stream, self.descriptions, self.verbosity) # TestProgream subclass necessary just to get our TestRunner hooked up, # which is necessary to get our TestResult hooked up *sob* class TestProgram(unittest.TestProgram): def runTests(self): # clobber existing runner - *sob* - it shouldn't be this hard self.testRunner = TestRunner(verbosity=self.verbosity) unittest.TestProgram.runTests(self) # A convenient entry-point - if used, 'SKIPPED' exceptions will be supressed. def testmain(*args, **kw): new_kw = kw.copy() if 'testLoader' not in new_kw: new_kw['testLoader'] = TestLoader() program_class = new_kw.get('testProgram', TestProgram) program_class(*args, **new_kw) |
Update of /cvsroot/pywin32/pywin32/win32/Demos In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4367/win32/Demos Modified Files: BackupRead_BackupWrite.py CreateFileTransacted_MiniVersion.py eventLogDemo.py mmapfile_demo.py win32clipboardDemo.py win32fileDemo.py Log Message: Move most tests and demos to using pywin32_testutil helpers, particularly for tests involving bytes and buffers. Some tests raise TestSkipped when appropriate and other minor test fixes. Index: CreateFileTransacted_MiniVersion.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/CreateFileTransacted_MiniVersion.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** CreateFileTransacted_MiniVersion.py 8 Nov 2007 20:02:30 -0000 1.2 --- CreateFileTransacted_MiniVersion.py 7 Jan 2009 06:03:29 -0000 1.3 *************** *** 8,11 **** --- 8,13 ---- import win32con, winioctlcon import struct + import os + from pywin32_testutil import str2bytes # py3k-friendly helper """ *************** *** 22,26 **** tempdir=win32api.GetTempPath() tempfile=win32api.GetTempFileName(tempdir,'cft')[0] ! print tempfile f=open(tempfile,'w') f.write('This is original file.\n') --- 24,28 ---- tempdir=win32api.GetTempPath() tempfile=win32api.GetTempFileName(tempdir,'cft')[0] ! print "Demonstrating transactions on tempfile", tempfile f=open(tempfile,'w') f.write('This is original file.\n') *************** *** 32,42 **** None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans) ! win32file.WriteFile(hfile, 'This is first miniversion.\n') ! buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,'',buf_size,None) struct_ver, struct_len, base_ver, ver_1=struct.unpack(buf_fmt, buf) win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN) ! win32file.WriteFile(hfile, 'This is second miniversion!\n') ! buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,'',buf_size,None) struct_ver, struct_len, base_ver, ver_2=struct.unpack(buf_fmt, buf) hfile.Close() --- 34,44 ---- None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans) ! win32file.WriteFile(hfile, str2bytes('This is first miniversion.\n')) ! buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,None,buf_size,None) struct_ver, struct_len, base_ver, ver_1=struct.unpack(buf_fmt, buf) win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN) ! win32file.WriteFile(hfile, str2bytes('This is second miniversion!\n')) ! buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,None,buf_size,None) struct_ver, struct_len, base_ver, ver_2=struct.unpack(buf_fmt, buf) hfile.Close() *************** *** 63,64 **** --- 65,68 ---- ## MiniVersions are destroyed when transaction is committed or rolled back win32transaction.CommitTransaction(trans) + + os.unlink(tempfile) Index: win32fileDemo.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/win32fileDemo.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** win32fileDemo.py 11 Dec 2008 06:58:21 -0000 1.7 --- win32fileDemo.py 7 Jan 2009 06:03:29 -0000 1.8 *************** *** 21,26 **** 0, None) ! test_data = "Hello\0there" ! win32file.WriteFile(handle, test_data.encode('ascii')) handle.Close() # Open it for reading. --- 21,26 ---- 0, None) ! test_data = "Hello\0there".encode("ascii") ! win32file.WriteFile(handle, test_data) handle.Close() # Open it for reading. *************** *** 28,33 **** rc, data = win32file.ReadFile(handle, 1024) handle.Close() ! if data.decode('ascii') == test_data: print "Successfully wrote and read a file" os.unlink(testName) --- 28,35 ---- rc, data = win32file.ReadFile(handle, 1024) handle.Close() ! if data == test_data: print "Successfully wrote and read a file" + else: + raise Exception("Got different data back???") os.unlink(testName) Index: mmapfile_demo.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/mmapfile_demo.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** mmapfile_demo.py 28 Jun 2007 08:28:21 -0000 1.1 --- mmapfile_demo.py 7 Jan 2009 06:03:29 -0000 1.2 *************** *** 1,4 **** --- 1,7 ---- import win32api, mmapfile + import winerror import tempfile, os + from pywin32_testutil import str2bytes + system_info=win32api.GetSystemInfo() page_size=system_info[1] *************** *** 12,18 **** m1=mmapfile.mmapfile(File=fname, Name=mapping_name, MaximumSize=fsize) m1.seek(100) ! m1.write_byte('?') m1.seek(-1,1) ! assert m1.read_byte()=='?' ## A reopened named mapping should have exact same size as original mapping --- 15,21 ---- m1=mmapfile.mmapfile(File=fname, Name=mapping_name, MaximumSize=fsize) m1.seek(100) ! m1.write_byte(str2bytes('?')) m1.seek(-1,1) ! assert m1.read_byte()==str2bytes('?') ## A reopened named mapping should have exact same size as original mapping *************** *** 20,25 **** assert m2.size()==m1.size() m1.seek(0,0) ! m1.write(fsize*'s') ! assert m2.read(fsize)==fsize*'s' move_src=100 --- 23,28 ---- assert m2.size()==m1.size() m1.seek(0,0) ! m1.write(fsize*str2bytes('s')) ! assert m2.read(fsize)==fsize*str2bytes('s') move_src=100 *************** *** 29,36 **** m2.seek(move_src,0) assert m2.tell()==move_src ! m2.write('m'*move_size) m2.move(move_dest, move_src, move_size) m2.seek(move_dest, 0) ! assert m2.read(move_size) == 'm' * move_size ## m2.write('x'* (fsize+1)) --- 32,39 ---- m2.seek(move_src,0) assert m2.tell()==move_src ! m2.write(str2bytes('m')*move_size) m2.move(move_dest, move_src, move_size) m2.seek(move_dest, 0) ! assert m2.read(move_size) == str2bytes('m') * move_size ## m2.write('x'* (fsize+1)) *************** *** 39,43 **** assert m1.size()==fsize * 2 m1.seek(fsize) ! m1.write('w' * fsize) m1.flush() m1.close() --- 42,46 ---- assert m1.size()==fsize * 2 m1.seek(fsize) ! m1.write(str2bytes('w') * fsize) m1.flush() m1.close() *************** *** 50,54 **** fname_large=tempfile.mktemp() mapping_name='Pywin32_large_mmap' ! offsetdata='This is start of offset' ## Deliberately use odd numbers to test rounding logic --- 53,57 ---- fname_large=tempfile.mktemp() mapping_name='Pywin32_large_mmap' ! offsetdata=str2bytes('This is start of offset') ## Deliberately use odd numbers to test rounding logic *************** *** 68,80 **** m2=None try: ! m1=mmapfile.mmapfile(fname_large, mapping_name, fsize, 0, offset*2) ! m1.seek(offset) ! m1.write(offsetdata) ! ! ## When reopening an existing mapping without passing a file handle, you have ! ## to specify a positive size even though it's ignored ! m2=mmapfile.mmapfile(File=None, Name=mapping_name, MaximumSize=1, ! FileOffset=offset, NumberOfBytesToMap=view_size) ! assert m2.read(len(offsetdata))==offsetdata finally: if m1 is not None: --- 71,90 ---- m2=None try: ! try: ! m1=mmapfile.mmapfile(fname_large, mapping_name, fsize, 0, offset*2) ! except mmapfile.error, exc: ! # if we don't have enough disk-space, that's OK. ! if exc.winerror!=winerror.ERROR_DISK_FULL: ! raise ! print "skipping large file test - need", fsize, "available bytes." ! else: ! m1.seek(offset) ! m1.write(offsetdata) ! ! ## When reopening an existing mapping without passing a file handle, you have ! ## to specify a positive size even though it's ignored ! m2=mmapfile.mmapfile(File=None, Name=mapping_name, MaximumSize=1, ! FileOffset=offset, NumberOfBytesToMap=view_size) ! assert m2.read(len(offsetdata))==offsetdata finally: if m1 is not None: Index: BackupRead_BackupWrite.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/BackupRead_BackupWrite.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** BackupRead_BackupWrite.py 7 Jan 2005 00:20:24 -0000 1.1 --- BackupRead_BackupWrite.py 7 Jan 2009 06:03:29 -0000 1.2 *************** *** 5,8 **** --- 5,9 ---- import pythoncom, pywintypes import struct, traceback + from pywin32_testutil import str2bytes, ob2memory all_sd_info=win32security.DACL_SECURITY_INFORMATION|win32security.DACL_SECURITY_INFORMATION| \ *************** *** 69,73 **** print 'Written:',bytes_written,'Context:',outctxt win32file.BackupRead(h, 0, buf, True, True, ctxt) ! win32file.BackupWrite(outh, 0, '', True, True, outctxt) win32file.CloseHandle(h) win32file.CloseHandle(outh) --- 70,74 ---- print 'Written:',bytes_written,'Context:',outctxt win32file.BackupRead(h, 0, buf, True, True, ctxt) ! win32file.BackupWrite(outh, 0, str2bytes(''), True, True, outctxt) win32file.CloseHandle(h) win32file.CloseHandle(outh) *************** *** 76,80 **** assert open(tempfile+':streamdata').read()==open(outfile+':streamdata').read(),"streamdata contents differ !" assert open(tempfile+':anotherstream').read()==open(outfile+':anotherstream').read(),"anotherstream contents differ !" ! assert buffer(win32security.GetFileSecurity(tempfile,all_sd_info))[:]== \ ! buffer(win32security.GetFileSecurity(outfile, all_sd_info))[:], "Security descriptors are different !" ## also should check Summary Info programatically --- 77,81 ---- assert open(tempfile+':streamdata').read()==open(outfile+':streamdata').read(),"streamdata contents differ !" assert open(tempfile+':anotherstream').read()==open(outfile+':anotherstream').read(),"anotherstream contents differ !" ! assert ob2memory(win32security.GetFileSecurity(tempfile,all_sd_info))[:]== \ ! ob2memory(win32security.GetFileSecurity(outfile, all_sd_info))[:], "Security descriptors are different !" ## also should check Summary Info programatically Index: eventLogDemo.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/eventLogDemo.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** eventLogDemo.py 11 Dec 2008 06:57:50 -0000 1.7 --- eventLogDemo.py 7 Jan 2009 06:03:29 -0000 1.8 *************** *** 90,100 **** win32evtlogutil.ReportEvent(logType, 2, strings=["The message text for event 2","Another insert"], ! data = "Raw\0Data", sid = my_sid) win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE, strings=["A warning","An even more dire warning"], ! data = "Raw\0Data", sid = my_sid) win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["An info","Too much info"], ! data = "Raw\0Data", sid = my_sid) print("Successfully wrote 3 records to the log") --- 90,100 ---- win32evtlogutil.ReportEvent(logType, 2, strings=["The message text for event 2","Another insert"], ! data = "Raw\0Data".encode("ascii"), sid = my_sid) win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE, strings=["A warning","An even more dire warning"], ! data = "Raw\0Data".encode("ascii"), sid = my_sid) win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["An info","Too much info"], ! data = "Raw\0Data".encode("ascii"), sid = my_sid) print("Successfully wrote 3 records to the log") Index: win32clipboardDemo.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Demos/win32clipboardDemo.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** win32clipboardDemo.py 3 Feb 2003 00:30:29 -0000 1.2 --- win32clipboardDemo.py 7 Jan 2009 06:03:29 -0000 1.3 *************** *** 3,6 **** --- 3,7 ---- # Demo/test of the win32clipboard module. from win32clipboard import * + from pywin32_testutil import str2bytes # py3k-friendly helper import win32con import types *************** *** 28,37 **** try: text = "Hello from Python" SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) ! assert got == text, "Didnt get the correct result back - '%r'." % (got,) ! # Win32 documentation says I can get the result back as CF_UNICODE or CF_OEMTEXT. ! # But it appears I need to close the clipboard for this to kick-in. ! # but if I attempt to, it fails! finally: CloseClipboard() --- 29,37 ---- try: text = "Hello from Python" + text_bytes = str2bytes(text) SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) ! # CF_TEXT always gives us 'bytes' back . ! assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) finally: CloseClipboard() *************** *** 39,52 **** OpenClipboard() try: got = GetClipboardData(win32con.CF_UNICODETEXT) assert got == text, "Didnt get the correct result back - '%r'." % (got,) assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,) got = GetClipboardData(win32con.CF_OEMTEXT) ! assert got == text, "Didnt get the correct result back - '%r'." % (got,) # Unicode tests EmptyClipboard() text = u"Hello from Python unicode" # Now set the Unicode value SetClipboardData(win32con.CF_UNICODETEXT, text) --- 39,55 ---- OpenClipboard() try: + # CF_UNICODE text always gives unicode objects back. got = GetClipboardData(win32con.CF_UNICODETEXT) assert got == text, "Didnt get the correct result back - '%r'." % (got,) assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,) + # CF_OEMTEXT is a bytes-based format. got = GetClipboardData(win32con.CF_OEMTEXT) ! assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) # Unicode tests EmptyClipboard() text = u"Hello from Python unicode" + text_bytes = str2bytes(text) # Now set the Unicode value SetClipboardData(win32con.CF_UNICODETEXT, text) *************** *** 63,74 **** try: ! # Make sure I can still get the text. got = GetClipboardData(win32con.CF_TEXT) ! assert got == text, "Didnt get the correct result back - '%r'." % (got,) # Make sure we get back the correct types. got = GetClipboardData(win32con.CF_UNICODETEXT) assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,) got = GetClipboardData(win32con.CF_OEMTEXT) ! assert got == text, "Didnt get the correct result back - '%r'." % (got,) print "Clipboard text tests worked correctly" finally: --- 66,77 ---- try: ! # Make sure I can still get the text as bytes got = GetClipboardData(win32con.CF_TEXT) ! assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) # Make sure we get back the correct types. got = GetClipboardData(win32con.CF_UNICODETEXT) assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,) got = GetClipboardData(win32con.CF_OEMTEXT) ! assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) print "Clipboard text tests worked correctly" finally: *************** *** 102,105 **** --- 105,110 ---- def __cmp__(self, other): return cmp(self.__dict__, other.__dict__) + def __eq__(self, other): + return self.__dict__==other.__dict__ def TestCustomFormat(): |
From: Mark H. <mha...@us...> - 2009-01-07 06:03:37
|
Update of /cvsroot/pywin32/pywin32/win32/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4367/win32/test Modified Files: test_clipboard.py test_odbc.py test_pywintypes.py test_security.py test_sspi.py test_win32api.py test_win32crypt.py test_win32file.py test_win32inet.py test_win32pipe.py test_win32wnet.py Log Message: Move most tests and demos to using pywin32_testutil helpers, particularly for tests involving bytes and buffers. Some tests raise TestSkipped when appropriate and other minor test fixes. Index: test_security.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_security.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_security.py 11 Dec 2008 00:24:53 -0000 1.5 --- test_security.py 7 Jan 2009 06:03:29 -0000 1.6 *************** *** 2,5 **** --- 2,7 ---- import sys, os import unittest + import winerror + from pywin32_testutil import testmain, TestSkipped, ob2memory import win32api, win32con, win32security, ntsecuritycon *************** *** 18,25 **** def testBuffer(self): ! # hrm - what about py3k - intent is to check the buffer slots return ! # something sane. ! self.failUnlessEqual(buffer(win32security.LookupAccountName('','Administrator')[0]), ! buffer(win32security.LookupAccountName('','Administrator')[0])) def testMemory(self): --- 20,25 ---- def testBuffer(self): ! self.failUnlessEqual(ob2memory(win32security.LookupAccountName('','Administrator')[0]), ! ob2memory(win32security.LookupAccountName('','Administrator')[0])) def testMemory(self): *************** *** 42,46 **** sd4.SetSecurityDescriptorSacl(1,sacl,0) ! class TestDS(unittest.TestCase): def testDsGetDcName(self): # Not sure what we can actually test here! At least calling it --- 42,61 ---- sd4.SetSecurityDescriptorSacl(1,sacl,0) ! class DomainTests(unittest.TestCase): ! def setUp(self): ! self.ds_handle = None ! try: ! # saving the handle means the other test itself should bind faster. ! self.ds_handle = win32security.DsBind() ! except win32security.error, exc: ! if exc.winerror != winerror.ERROR_NO_SUCH_DOMAIN: ! raise ! raise TestSkipped(exc) ! ! def tearDown(self): ! if self.ds_handle is not None: ! self.ds_handle.close() ! ! class TestDS(DomainTests): def testDsGetDcName(self): # Not sure what we can actually test here! At least calling it *************** *** 75,79 **** self.failUnlessEqual(expected, result[0][2]) ! class TestTranslate(unittest.TestCase): def _testTranslate(self, fmt_from, fmt_to): name = win32api.GetUserNameEx(fmt_from) --- 90,94 ---- self.failUnlessEqual(expected, result[0][2]) ! class TestTranslate(DomainTests): def _testTranslate(self, fmt_from, fmt_to): name = win32api.GetUserNameEx(fmt_from) *************** *** 95,97 **** if __name__=='__main__': ! unittest.main() --- 110,112 ---- if __name__=='__main__': ! testmain() Index: test_win32pipe.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32pipe.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_win32pipe.py 7 Jun 2008 07:23:54 -0000 1.4 --- test_win32pipe.py 7 Jan 2009 06:03:29 -0000 1.5 *************** *** 2,5 **** --- 2,6 ---- import time import threading + from pywin32_testutil import str2bytes # py3k-friendly helper *************** *** 19,25 **** self.failUnless(hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,)) hr, got = win32file.ReadFile(pipe_handle, 100) ! self.failUnless(got == "foo\0bar") time.sleep(wait_time) ! win32file.WriteFile(pipe_handle, "bar\0foo") pipe_handle.Close() event.set() --- 20,26 ---- self.failUnless(hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,)) hr, got = win32file.ReadFile(pipe_handle, 100) ! self.failUnlessEqual(got, str2bytes("foo\0bar")) time.sleep(wait_time) ! win32file.WriteFile(pipe_handle, str2bytes("bar\0foo")) pipe_handle.Close() event.set() *************** *** 48,53 **** self.startPipeServer(event) ! got = win32pipe.CallNamedPipe(self.pipename,"foo\0bar", 1024, win32pipe.NMPWAIT_WAIT_FOREVER) ! self.failUnlessEqual(got, "bar\0foo") event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") --- 49,54 ---- self.startPipeServer(event) ! got = win32pipe.CallNamedPipe(self.pipename,str2bytes("foo\0bar"), 1024, win32pipe.NMPWAIT_WAIT_FOREVER) ! self.failUnlessEqual(got, str2bytes("bar\0foo")) event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") *************** *** 70,75 **** hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None) ! hr, got = win32pipe.TransactNamedPipe(hpipe, "foo\0bar", 1024, None) ! self.failUnlessEqual(got, "bar\0foo") event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") --- 71,76 ---- hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None) ! hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None) ! self.failUnlessEqual(got, str2bytes("bar\0foo")) event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") *************** *** 95,100 **** buffer = win32file.AllocateReadBuffer(1024) ! hr, got = win32pipe.TransactNamedPipe(hpipe, "foo\0bar", buffer, None) ! self.failUnlessEqual(got, "bar\0foo") event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") --- 96,101 ---- buffer = win32file.AllocateReadBuffer(1024) ! hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, None) ! self.failUnlessEqual(got, str2bytes("bar\0foo")) event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") *************** *** 120,128 **** buffer = win32file.AllocateReadBuffer(1024) ! hr, got = win32pipe.TransactNamedPipe(hpipe, "foo\0bar", buffer, overlapped) self.failUnlessEqual(hr, winerror.ERROR_IO_PENDING) nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True) got = buffer[:nbytes] ! self.failUnlessEqual(got, "bar\0foo") event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") --- 121,129 ---- buffer = win32file.AllocateReadBuffer(1024) ! hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, overlapped) self.failUnlessEqual(hr, winerror.ERROR_IO_PENDING) nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True) got = buffer[:nbytes] ! self.failUnlessEqual(got, str2bytes("bar\0foo")) event.wait(5) self.failUnless(event.isSet(), "Pipe server thread didn't terminate") Index: test_sspi.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_sspi.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_sspi.py 4 Oct 2008 03:16:24 -0000 1.4 --- test_sspi.py 7 Jan 2009 06:03:29 -0000 1.5 *************** *** 3,8 **** --- 3,21 ---- # See also the other SSPI demos. import win32security, sspi, sspicon, win32api + from pywin32_testutil import TestSkipped, testmain, str2bytes import unittest + # It is quite likely that the Kerberos tests will fail due to not being + # installed. The NTLM tests do *not* get the same behaviour as they should + # always be there. + def applyHandlingSkips(func, *args): + try: + return func(*args) + except win32api.error, exc: + if exc.winerror == sspicon.SEC_E_NO_CREDENTIALS: + raise TestSkipped(exc) + raise + + class TestSSPI(unittest.TestCase): *************** *** 32,36 **** def testImpersonateKerberos(self): ! self._doTestImpersonate("Kerberos") def testImpersonateNTLM(self): --- 45,49 ---- def testImpersonateKerberos(self): ! applyHandlingSkips(self._doTestImpersonate, "Kerberos") def testImpersonateNTLM(self): *************** *** 42,46 **** pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) ! msg='some data to be encrypted ......' trailersize=pkg_size_info['SecurityTrailer'] --- 55,59 ---- pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) ! msg=str2bytes('some data to be encrypted ......') trailersize=pkg_size_info['SecurityTrailer'] *************** *** 53,61 **** self.failUnlessEqual(msg, encbuf[0].Buffer) # and test the higher-level functions ! data, sig = sspiclient.encrypt("hello") ! self.assertEqual(sspiserver.decrypt(data, sig), "hello") ! data, sig = sspiserver.encrypt("hello") ! self.assertEqual(sspiclient.decrypt(data, sig), "hello") def testEncryptNTLM(self): --- 66,75 ---- self.failUnlessEqual(msg, encbuf[0].Buffer) # and test the higher-level functions ! data_in = str2bytes("hello") ! data, sig = sspiclient.encrypt(data_in) ! self.assertEqual(sspiserver.decrypt(data, sig), data_in) ! data, sig = sspiserver.encrypt(data_in) ! self.assertEqual(sspiclient.decrypt(data, sig), data_in) def testEncryptNTLM(self): *************** *** 63,67 **** def testEncryptKerberos(self): ! self._doTestEncrypt("Kerberos") def _doTestSign(self, pkg_name): --- 77,81 ---- def testEncryptKerberos(self): ! applyHandlingSkips(self._doTestEncrypt, "Kerberos") def _doTestSign(self, pkg_name): *************** *** 70,74 **** pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) ! msg='some data to be encrypted ......' sigsize=pkg_size_info['MaxSignature'] --- 84,88 ---- pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES) ! msg=str2bytes('some data to be encrypted ......') sigsize=pkg_size_info['MaxSignature'] *************** *** 82,97 **** sspiclient.next_seq_num = 1 sspiserver.next_seq_num = 1 ! key = sspiclient.sign("hello") ! sspiserver.verify("hello", key) ! key = sspiclient.sign("hello") self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED, ! sspiserver.verify, "hellox", key) # and the other way ! key = sspiserver.sign("hello") ! sspiclient.verify("hello", key) ! key = sspiserver.sign("hello") self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED, ! sspiclient.verify, "hellox", key) def testSignNTLM(self): --- 96,112 ---- sspiclient.next_seq_num = 1 sspiserver.next_seq_num = 1 ! data = str2bytes("hello") ! key = sspiclient.sign(data) ! sspiserver.verify(data, key) ! key = sspiclient.sign(data) self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED, ! sspiserver.verify, data + data, key) # and the other way ! key = sspiserver.sign(data) ! sspiclient.verify(data, key) ! key = sspiserver.sign(data) self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED, ! sspiclient.verify, data + data, key) def testSignNTLM(self): *************** *** 99,105 **** def testSignKerberos(self): ! self._doTestSign("Kerberos") ! def testSequenceSign(self): # Only Kerberos supports sequence detection. sspiclient, sspiserver = self._doAuth("Kerberos") --- 114,120 ---- def testSignKerberos(self): ! applyHandlingSkips(self._doTestSign, "Kerberos") ! def _testSequenceSign(self): # Only Kerberos supports sequence detection. sspiclient, sspiserver = self._doAuth("Kerberos") *************** *** 109,113 **** sspiserver.verify, 'hello', key) ! def testSequenceEncrypt(self): # Only Kerberos supports sequence detection. sspiclient, sspiserver = self._doAuth("Kerberos") --- 124,131 ---- sspiserver.verify, 'hello', key) ! def testSequenceSign(self): ! applyHandlingSkips(self._testSequenceSign) ! ! def _testSequenceEncrypt(self): # Only Kerberos supports sequence detection. sspiclient, sspiserver = self._doAuth("Kerberos") *************** *** 117,120 **** sspiserver.decrypt, blob, key) if __name__=='__main__': ! unittest.main() --- 135,141 ---- sspiserver.decrypt, blob, key) + def testSequenceEncrypt(self): + applyHandlingSkips(self._testSequenceEncrypt) + if __name__=='__main__': ! testmain() Index: test_win32api.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32api.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_win32api.py 11 Dec 2008 00:21:42 -0000 1.15 --- test_win32api.py 7 Jan 2009 06:03:29 -0000 1.16 *************** *** 2,5 **** --- 2,6 ---- import unittest + from pywin32_testutil import str2bytes import win32api, win32con, win32event, winerror *************** *** 68,72 **** ('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1','string 2','string 3','string 4']), ('REG_DWORD', win32con.REG_DWORD, 666), ! ('REG_BINARY', win32con.REG_BINARY, '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00'), ) --- 69,73 ---- ('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1','string 2','string 3','string 4']), ('REG_DWORD', win32con.REG_DWORD, 666), ! ('REG_BINARY', win32con.REG_BINARY, str2bytes('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00')), ) *************** *** 165,169 **** long_name = win32api.GetLongPathNameW(fname) ! self.failUnlessEqual(long_name, fname) finally: win32file.RemoveDirectory(fname) --- 166,170 ---- long_name = win32api.GetLongPathNameW(fname) ! self.failUnlessEqual(long_name.lower(), fname.lower()) finally: win32file.RemoveDirectory(fname) Index: test_win32inet.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32inet.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_win32inet.py 11 Dec 2008 07:00:54 -0000 1.2 --- test_win32inet.py 7 Jan 2009 06:03:29 -0000 1.3 *************** *** 1,4 **** --- 1,5 ---- from win32inet import * from win32inetcon import * + from pywin32_testutil import str2bytes # py3k-friendly helper import unittest *************** *** 36,41 **** break chunks.append(chunk) ! data = ''.join(chunks) ! assert data.find("Python")>0, repr(data) # This must appear somewhere on the main page! def testFtpCommand(self): --- 37,42 ---- break chunks.append(chunk) ! data = str2bytes('').join(chunks) ! assert data.find(str2bytes("Python"))>0, repr(data) # This must appear somewhere on the main page! def testFtpCommand(self): Index: test_odbc.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_odbc.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** test_odbc.py 27 Nov 2008 09:32:34 -0000 1.12 --- test_odbc.py 7 Jan 2009 06:03:29 -0000 1.13 *************** *** 6,9 **** --- 6,11 ---- import tempfile + from pywin32_testutil import str2bytes, str2memory, TestSkipped + # We use the DAO ODBC driver from win32com.client.gencache import EnsureDispatch *************** *** 31,35 **** pass else: ! raise RuntimeError("Can't find a DB engine") workspace = dbe.Workspaces(0) --- 33,37 ---- pass else: ! raise TestSkipped("Can't find a DB engine") workspace = dbe.Workspaces(0) *************** *** 104,109 **** def test_insert_select_unicode_ext(self): ! userid = unicode("t-\xe0\xf2", "mbcs") ! username = unicode("test-\xe0\xf2 name", "mbcs") self.test_insert_select_unicode(userid, username) --- 106,111 ---- def test_insert_select_unicode_ext(self): ! userid = u"t-\xe0\xf2" ! username = u"test-\xe0\xf2 name" self.test_insert_select_unicode(userid, username) *************** *** 143,151 **** def testLongBinary(self): """ Test a long raw field in excess of internal cursor data size (65536)""" ! self._test_val('longbinaryfield', buffer('\0\1\2' * 70000)) def testRaw(self): ## Test binary data ! self._test_val('rawfield', buffer('\1\2\3\4\0\5\6\7\8')) def test_widechar(self): --- 145,153 ---- def testLongBinary(self): """ Test a long raw field in excess of internal cursor data size (65536)""" ! self._test_val('longbinaryfield', str2memory('\0\1\2' * 70000)) def testRaw(self): ## Test binary data ! self._test_val('rawfield', str2memory('\1\2\3\4\0\5\6\7\8')) def test_widechar(self): *************** *** 173,177 **** def test_set_zero_length(self): self.assertEqual(self.cur.execute("insert into %s (userid,username) " ! "values (?,?)" %self.tablename, ['Frank', '']),1) self.assertEqual(self.cur.execute("select * from %s" %self.tablename), 0) self.assertEqual(len(self.cur.fetchone()[1]),0) --- 175,179 ---- def test_set_zero_length(self): self.assertEqual(self.cur.execute("insert into %s (userid,username) " ! "values (?,?)" %self.tablename, [str2bytes('Frank'), '']),1) self.assertEqual(self.cur.execute("select * from %s" %self.tablename), 0) self.assertEqual(len(self.cur.fetchone()[1]),0) Index: test_clipboard.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_clipboard.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** test_clipboard.py 26 Nov 2008 01:11:54 -0000 1.7 --- test_clipboard.py 7 Jan 2009 06:03:29 -0000 1.8 *************** *** 8,11 **** --- 8,13 ---- import array + from pywin32_testutil import str2bytes + custom_format_name = "PythonClipboardTestFormat" *************** *** 68,77 **** # GetClipboardData doesn't to auto string conversions - so on py3k, # CF_TEXT returns bytes. ! expected = val.encode("ascii") self.failUnlessEqual(GetClipboardData(win32con.CF_TEXT), expected) SetClipboardText(val, win32con.CF_UNICODETEXT) self.failUnlessEqual(GetClipboardData(win32con.CF_UNICODETEXT), val) def test_string(self): ! val = "test".encode("ascii") SetClipboardData(win32con.CF_TEXT, val) self.failUnlessEqual(GetClipboardData(win32con.CF_TEXT), val) --- 70,79 ---- # GetClipboardData doesn't to auto string conversions - so on py3k, # CF_TEXT returns bytes. ! expected = str2bytes(val) self.failUnlessEqual(GetClipboardData(win32con.CF_TEXT), expected) SetClipboardText(val, win32con.CF_UNICODETEXT) self.failUnlessEqual(GetClipboardData(win32con.CF_UNICODETEXT), val) def test_string(self): ! val = str2bytes("test") SetClipboardData(win32con.CF_TEXT, val) self.failUnlessEqual(GetClipboardData(win32con.CF_TEXT), val) *************** *** 83,88 **** CloseClipboard() def test_mem(self): ! val = "test".encode("ascii") ! expected = "test\0".encode("ascii") SetClipboardData(win32con.CF_TEXT, val) # Get the raw data - this will include the '\0' --- 85,90 ---- CloseClipboard() def test_mem(self): ! val = str2bytes("test") ! expected = str2bytes("test\0") SetClipboardData(win32con.CF_TEXT, val) # Get the raw data - this will include the '\0' *************** *** 98,103 **** self.failUnlessRaises(pywintypes.error, GetGlobalMemory, 1) def test_custom_mem(self): ! test_data = "hello\x00\xff" ! test_buffer = array.array("c", test_data) cf = RegisterClipboardFormat(custom_format_name) self.failUnlessEqual(custom_format_name, GetClipboardFormatName(cf)) --- 100,105 ---- self.failUnlessRaises(pywintypes.error, GetGlobalMemory, 1) def test_custom_mem(self): ! test_data = str2bytes("hello\x00\xff") ! test_buffer = array.array("b", test_data) cf = RegisterClipboardFormat(custom_format_name) self.failUnlessEqual(custom_format_name, GetClipboardFormatName(cf)) Index: test_pywintypes.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_pywintypes.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_pywintypes.py 11 Dec 2008 00:24:53 -0000 1.4 --- test_pywintypes.py 7 Jan 2009 06:03:29 -0000 1.5 *************** *** 2,5 **** --- 2,6 ---- import pywintypes import time + from pywin32_testutil import str2bytes, ob2memory class TestCase(unittest.TestCase): *************** *** 38,44 **** s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) ! iid2 = pywintypes.IID(buffer(iid), True) self.assertEquals(iid, iid2) ! self.assertRaises(ValueError, pywintypes.IID, '00', True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer --- 39,45 ---- s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) ! iid2 = pywintypes.IID(ob2memory(iid), True) self.assertEquals(iid, iid2) ! self.assertRaises(ValueError, pywintypes.IID, str2bytes('00'), True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer Index: test_win32wnet.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32wnet.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_win32wnet.py 11 Dec 2008 05:12:39 -0000 1.3 --- test_win32wnet.py 7 Jan 2009 06:03:29 -0000 1.4 *************** *** 4,7 **** --- 4,9 ---- import netbios + from pywin32_testutil import str2bytes + RESOURCE_CONNECTED = 0x00000001 RESOURCE_GLOBALNET = 0x00000002 *************** *** 111,115 **** ncb.Command = netbios.NCBASTAT ncb.Lana_num = byte_to_int(la_enum.lana[i]) ! ncb.Callname = "* ".encode("ascii") # ensure bytes on py2x and 3k adapter = netbios.ADAPTER_STATUS() ncb.Buffer = adapter --- 113,117 ---- ncb.Command = netbios.NCBASTAT ncb.Lana_num = byte_to_int(la_enum.lana[i]) ! ncb.Callname = str2bytes("* ") # ensure bytes on py2x and 3k adapter = netbios.ADAPTER_STATUS() ncb.Buffer = adapter Index: test_win32file.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32file.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** test_win32file.py 17 Dec 2008 13:06:19 -0000 1.21 --- test_win32file.py 7 Jan 2009 06:03:29 -0000 1.22 *************** *** 1,3 **** --- 1,4 ---- import unittest + from pywin32_testutil import str2bytes import win32api, win32file, win32pipe, pywintypes, winerror, win32event import win32con, ntsecuritycon *************** *** 20,24 **** os.unlink(filename) handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None) ! test_data = "Hello\0there" try: win32file.WriteFile(handle, test_data) --- 21,25 ---- os.unlink(filename) handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None) ! test_data = str2bytes("Hello\0there") try: win32file.WriteFile(handle, test_data) *************** *** 45,49 **** # Write a known number of bytes to the file. ! data = "z" * 1025 win32file.WriteFile(h, data) --- 46,50 ---- # Write a known number of bytes to the file. ! data = str2bytes("z") * 1025 win32file.WriteFile(h, data) *************** *** 93,97 **** try: #Write some data ! data = 'Some data' (res, written) = win32file.WriteFile(f, data) --- 94,98 ---- try: #Write some data ! data = str2bytes('Some data') (res, written) = win32file.WriteFile(f, data) *************** *** 127,131 **** # Create the file and write shit-loads of data to it. h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0) ! chunk_data = "z" * 0x8000 num_loops = 512 expected_size = num_loops * len(chunk_data) --- 128,132 ---- # Create the file and write shit-loads of data to it. h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0) ! chunk_data = str2bytes("z") * 0x8000 num_loops = 512 expected_size = num_loops * len(chunk_data) *************** *** 237,241 **** time.sleep(0.1) # let thread do its thing. try: ! win32pipe.CallNamedPipe(r"\\.\pipe\pywin32_test_pipe", "Hello there", BUFSIZE, 0) except win32pipe.error: # Testing for overlapped death causes this --- 238,242 ---- time.sleep(0.1) # let thread do its thing. try: ! win32pipe.CallNamedPipe(r"\\.\pipe\pywin32_test_pipe", str2bytes("Hello there"), BUFSIZE, 0) except win32pipe.error: # Testing for overlapped death causes this *************** *** 299,303 **** s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', port)) ! win32file.WSASend(s, "hello", None) overlapped = pywintypes.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) --- 300,304 ---- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', port)) ! win32file.WSASend(s, str2bytes("hello"), None) overlapped = pywintypes.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) *************** *** 310,314 **** nbytes = win32file.GetOverlappedResult(s.fileno(), overlapped, True) got = buffer[:nbytes] ! self.failUnlessEqual(got, "hello") # thread should have stopped stopped.wait(2) --- 311,315 ---- nbytes = win32file.GetOverlappedResult(s.fileno(), overlapped, True) got = buffer[:nbytes] ! self.failUnlessEqual(got, str2bytes("hello")) # thread should have stopped stopped.wait(2) *************** *** 486,490 **** fname = tempfile.mktemp("win32file_test") f = open(fname, "wb") ! f.write("hello") f.close() f = None --- 487,491 ---- fname = tempfile.mktemp("win32file_test") f = open(fname, "wb") ! f.write(str2bytes("hello")) f.close() f = None Index: test_win32crypt.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/test_win32crypt.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_win32crypt.py 4 Jul 2005 05:40:29 -0000 1.1 --- test_win32crypt.py 7 Jan 2009 06:03:29 -0000 1.2 *************** *** 1,10 **** ! # Test module for win32timezone import unittest import win32crypt class Crypt(unittest.TestCase): def testSimple(self): ! data = "My test data" entropy = None desc = "My description" --- 1,12 ---- ! # Test module for win32crypt import unittest import win32crypt + from pywin32_testutil import str2bytes # py3k-friendly helper + class Crypt(unittest.TestCase): def testSimple(self): ! data = str2bytes("My test data") entropy = None desc = "My description" *************** *** 17,22 **** def testEntropy(self): ! data = "My test data" ! entropy = "My test entropy" desc = "My description" flags = 0 --- 19,24 ---- def testEntropy(self): ! data = str2bytes("My test data") ! entropy = str2bytes("My test entropy") desc = "My description" flags = 0 |
From: Mark H. <mha...@us...> - 2009-01-07 06:03:35
|
Update of /cvsroot/pywin32/pywin32/com/win32com/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4367/com/win32com/test Modified Files: testClipboard.py testShell.py testStreams.py testvb.py Log Message: Move most tests and demos to using pywin32_testutil helpers, particularly for tests involving bytes and buffers. Some tests raise TestSkipped when appropriate and other minor test fixes. Index: testvb.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testvb.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** testvb.py 19 Dec 2008 01:53:28 -0000 1.25 --- testvb.py 7 Jan 2009 06:03:29 -0000 1.26 *************** *** 9,21 **** from win32com.server.util import NewCollection, wrap from win32com.test import util import traceback - def string_to_buffer(s): - if sys.version_info < (3,0): - return buffer(s) - else: - return memoryview(s.encode("ascii")) - # for debugging useDispatcher = None --- 9,16 ---- from win32com.server.util import NewCollection, wrap from win32com.test import util + from pywin32_testutil import str2memory import traceback # for debugging useDispatcher = None *************** *** 74,79 **** if vbtest.VariantProperty != 10: raise error("Could not set the variant integer property correctly.") ! vbtest.VariantProperty = string_to_buffer('raw\0data') ! if vbtest.VariantProperty != string_to_buffer('raw\0data'): raise error("Could not set the variant buffer property correctly.") vbtest.StringProperty = "Hello from Python" --- 69,74 ---- if vbtest.VariantProperty != 10: raise error("Could not set the variant integer property correctly.") ! vbtest.VariantProperty = str2memory('raw\0data') ! if vbtest.VariantProperty != str2memory('raw\0data'): raise error("Could not set the variant buffer property correctly.") vbtest.StringProperty = "Hello from Python" Index: testStreams.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testStreams.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** testStreams.py 19 Dec 2008 01:52:15 -0000 1.8 --- testStreams.py 7 Jan 2009 06:03:29 -0000 1.9 *************** *** 4,7 **** --- 4,8 ---- import unittest + from pywin32_testutil import str2bytes class Persists: *************** *** 10,14 **** _com_interfaces_ = [ pythoncom.IID_IPersistStreamInit ] def __init__(self): ! self.data = "abcdefg".encode("ascii") self.dirty = 1 def GetClassID(self): --- 11,15 ---- _com_interfaces_ = [ pythoncom.IID_IPersistStreamInit ] def __init__(self): ! self.data = str2bytes("abcdefg") self.dirty = 1 def GetClassID(self): *************** *** 67,71 **** """ def Read(self, amount): ! return 'x'.encode('ascii')*(amount+1) class StreamTest(win32com.test.util.TestCase): --- 68,72 ---- """ def Read(self, amount): ! return str2bytes('x')*(amount+1) class StreamTest(win32com.test.util.TestCase): *************** *** 81,85 **** def testit(self): ! mydata = 'abcdefghijklmnopqrstuvwxyz'.encode('ascii') # First test the objects just as Python objects... --- 82,86 ---- def testit(self): ! mydata = str2bytes('abcdefghijklmnopqrstuvwxyz') # First test the objects just as Python objects... *************** *** 101,105 **** self._readWrite(mydata, s2, s2) ! self._readWrite("string with\0a NULL".encode('ascii'), s2, s2) # reset the stream s.Write(mydata) --- 102,106 ---- self._readWrite(mydata, s2, s2) ! self._readWrite(str2bytes("string with\0a NULL"), s2, s2) # reset the stream s.Write(mydata) Index: testShell.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testShell.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** testShell.py 26 Nov 2008 01:27:40 -0000 1.12 --- testShell.py 7 Jan 2009 06:03:29 -0000 1.13 *************** *** 16,19 **** --- 16,20 ---- import win32com.test.util + from pywin32_testutil import str2bytes class ShellTester(win32com.test.util.TestCase): *************** *** 75,94 **** def testPIDL(self): # A PIDL of "\1" is: cb pidl cb ! expect = "\03\00" "\1" "\0\0" ! self.assertEqual(shell.PIDLAsString(["\1"]), expect) ! self._rtPIDL(["\0"]) ! self._rtPIDL(["\1", "\2", "\3"]) ! self._rtPIDL(["\0" * 2048] * 2048) # PIDL must be a list self.assertRaises(TypeError, shell.PIDLAsString, "foo") def testCIDA(self): ! self._rtCIDA(["\0"], [ ["\0"] ]) ! self._rtCIDA(["\1"], [ ["\2"] ]) ! self._rtCIDA(["\0"], [ ["\0"], ["\1"], ["\2"] ]) def testBadShortPIDL(self): # A too-short child element: cb pidl cb ! pidl = "\01\00" "\1" self.assertRaises(ValueError, shell.StringAsPIDL, pidl) --- 76,95 ---- def testPIDL(self): # A PIDL of "\1" is: cb pidl cb ! expect = str2bytes("\03\00" "\1" "\0\0") ! self.assertEqual(shell.PIDLAsString([str2bytes("\1")]), expect) ! self._rtPIDL([str2bytes("\0")]) ! self._rtPIDL([str2bytes("\1"), str2bytes("\2"), str2bytes("\3")]) ! self._rtPIDL([str2bytes("\0") * 2048] * 2048) # PIDL must be a list self.assertRaises(TypeError, shell.PIDLAsString, "foo") def testCIDA(self): ! self._rtCIDA([str2bytes("\0")], [ [str2bytes("\0")] ]) ! self._rtCIDA([str2bytes("\1")], [ [str2bytes("\2")] ]) ! self._rtCIDA([str2bytes("\0")], [ [str2bytes("\0")], [str2bytes("\1")], [str2bytes("\2")] ]) def testBadShortPIDL(self): # A too-short child element: cb pidl cb ! pidl = str2bytes("\01\00" "\1") self.assertRaises(ValueError, shell.StringAsPIDL, pidl) *************** *** 182,187 **** self.src_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell") self.dest_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell_dest") ! self.test_data = "Hello from\0Python" ! f=file(self.src_name, "wb") f.write(self.test_data) f.close() --- 183,188 ---- self.src_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell") self.dest_name = os.path.join(tempfile.gettempdir(), "pywin32_testshell_dest") ! self.test_data = str2bytes("Hello from\0Python") ! f=open(self.src_name, "wb") f.write(self.test_data) f.close() Index: testClipboard.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testClipboard.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** testClipboard.py 26 Nov 2008 01:20:23 -0000 1.3 --- testClipboard.py 7 Jan 2009 06:03:29 -0000 1.4 *************** *** 6,9 **** --- 6,11 ---- import win32clipboard + from pywin32_testutil import str2bytes + from win32com.server.util import NewEnum, wrap from win32com.server.exception import COMException *************** *** 47,51 **** ret_stg = pythoncom.STGMEDIUM() # ensure always 'bytes' by encoding string. ! ret_stg.set(pythoncom.TYMED_HGLOBAL, self.strval.encode("ascii")) elif cf == win32con.CF_UNICODETEXT: ret_stg = pythoncom.STGMEDIUM() --- 49,53 ---- ret_stg = pythoncom.STGMEDIUM() # ensure always 'bytes' by encoding string. ! ret_stg.set(pythoncom.TYMED_HGLOBAL, str2bytes(self.strval)) elif cf == win32con.CF_UNICODETEXT: ret_stg = pythoncom.STGMEDIUM() *************** *** 111,116 **** win32clipboard.OpenClipboard() got = win32clipboard.GetClipboardData(win32con.CF_TEXT) ! # CF_TEXT gives bytes on py3k - use encode() to ensure that's true. ! expected = "Hello from Python".encode("ascii") self.assertEqual(got, expected) # Now check unicode --- 113,118 ---- win32clipboard.OpenClipboard() got = win32clipboard.GetClipboardData(win32con.CF_TEXT) ! # CF_TEXT gives bytes on py3k - use str2bytes() to ensure that's true. ! expected = str2bytes("Hello from Python") self.assertEqual(got, expected) # Now check unicode *************** *** 121,125 **** def testWin32ToCom(self): # Set the data via the std win32 clipboard functions. ! val = "Hello again!".encode("ascii") # ensure always bytes, even in py3k win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32con.CF_TEXT, val) --- 123,127 ---- def testWin32ToCom(self): # Set the data via the std win32 clipboard functions. ! val = str2bytes("Hello again!") # ensure always bytes, even in py3k win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32con.CF_TEXT, val) *************** *** 133,137 **** # knowing if it meant to be a string, or a binary buffer, so # it must return it too. ! self.failUnlessEqual(got, "Hello again!\0".encode("ascii")) def testDataObjectFlush(self): --- 135,139 ---- # knowing if it meant to be a string, or a binary buffer, so # it must return it too. ! self.failUnlessEqual(got, str2bytes("Hello again!\0")) def testDataObjectFlush(self): |
From: Mark H. <mha...@us...> - 2009-01-07 06:03:35
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4367/win32/Lib Modified Files: sspi.py Log Message: Move most tests and demos to using pywin32_testutil helpers, particularly for tests involving bytes and buffers. Some tests raise TestSkipped when appropriate and other minor test fixes. Index: sspi.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/sspi.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** sspi.py 14 Nov 2008 00:22:25 -0000 1.4 --- sspi.py 7 Jan 2009 06:03:29 -0000 1.5 *************** *** 218,225 **** if err==0: break ! sig = sspiclient.sign("hello") ! sspiserver.verify("hello", sig) ! data, key = sspiclient.encrypt("hello") ! assert sspiserver.decrypt(data, key) == "hello" print "cool!" --- 218,226 ---- if err==0: break ! data = "hello".encode("ascii") # py3k-friendly ! sig = sspiclient.sign(data) ! sspiserver.verify(data, sig) ! data, key = sspiclient.encrypt(data) ! assert sspiserver.decrypt(data, key) == data print "cool!" |
From: Mark H. <mha...@us...> - 2009-01-07 06:00:09
|
Update of /cvsroot/pywin32/pywin32/com/win32com/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv3949/com/win32com/test Modified Files: util.py Log Message: Rationalize win32com test utilities into new pywin32_testutil module. Includes support for tests being "skipped" rather than failing due to something out of our control, and some helpers for dealing with bytes and buffers on py3k. Index: util.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/util.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** util.py 19 Dec 2008 01:54:10 -0000 1.17 --- util.py 7 Jan 2009 05:59:56 -0000 1.18 *************** *** 12,15 **** --- 12,18 ---- import cStringIO as StringIO + import pywin32_testutil + from pywin32_testutil import TestLoader, TestResult, TestRunner, LeakTestCase + def CheckClean(): # Ensure no lingering exceptions - Python should have zero outstanding *************** *** 143,259 **** return len("".join(self.captured).split("\n")) - class LeakTestCase(unittest.TestCase): - def __init__(self, real_test): - unittest.TestCase.__init__(self) - self.real_test = real_test - self.num_test_cases = 1 - self.num_leak_iters = 2 # seems to be enough! - if hasattr(sys, "gettotalrefcount"): - self.num_test_cases = self.num_test_cases + self.num_leak_iters - def countTestCases(self): - return self.num_test_cases - def runTest(self): - assert 0, "not used" - def __call__(self, result = None): - # Always ensure we don't leak gateways/interfaces - gc.collect() - ni = _GetInterfaceCount() - ng = _GetGatewayCount() - self.real_test(result) - # Failed - no point checking anything else - if result.shouldStop or not result.wasSuccessful(): - return - self._do_leak_tests(result) - gc.collect() - lost_i = _GetInterfaceCount() - ni - lost_g = _GetGatewayCount() - ng - if lost_i or lost_g: - msg = "%d interface objects and %d gateway objects leaked" \ - % (lost_i, lost_g) - result.addFailure(self.real_test, (AssertionError, msg, None)) - def _do_leak_tests(self, result = None): - try: - gtrc = sys.gettotalrefcount - except AttributeError: - return # can't do leak tests in this build - def gtrc(): - return 0 - # Assume already called once, to prime any caches etc - trc = gtrc() - for i in range(self.num_leak_iters): - self.real_test(result) - if result.shouldStop: - break - del i # created after we remembered the refcount! - # int division here means one or 2 stray references won't force - # failure, but one per loop - gc.collect() - lost = (gtrc() - trc) // self.num_leak_iters - if lost < 0: - msg = "LeakTest: %s appeared to gain %d references!!" % (self.real_test, -lost) - result.addFailure(self.real_test, (AssertionError, msg, None)) - if lost > 0: - msg = "LeakTest: %s lost %d references" % (self.real_test, lost) - result.addFailure(self.real_test, (AssertionError, msg, None)) - - class TestLoader(unittest.TestLoader): - def loadTestsFromTestCase(self, testCaseClass): - """Return a suite of all tests cases contained in testCaseClass""" - leak_tests = [] - for name in self.getTestCaseNames(testCaseClass): - real_test = testCaseClass(name) - leak_test = self._getTestWrapper(real_test) - leak_tests.append(leak_test) - return self.suiteClass(leak_tests) - def _getTestWrapper(self, test): - no_leak_tests = getattr(test, "no_leak_tests", False) - if no_leak_tests: - print "Test says it doesn't want leak tests!" - return test - return LeakTestCase(test) - def loadTestsFromModule(self, mod): - if hasattr(mod, "suite"): - return mod.suite() - else: - return unittest.TestLoader.loadTestsFromModule(self, mod) - def loadTestsFromName(self, name, module=None): - test = unittest.TestLoader.loadTestsFromName(self, name, module) - if isinstance(test, unittest.TestSuite): - pass # hmmm? print "Don't wrap suites yet!", test._tests - elif isinstance(test, unittest.TestCase): - test = self._getTestWrapper(test) - else: - print "XXX - what is", test - return test - - class TestResult(unittest._TextTestResult): - def __init__(self, *args, **kw): - super(TestResult, self).__init__(*args, **kw) - self.num_invalid_clsid = 0 - - def addError(self, test, err): - """Called when an error has occurred. 'err' is a tuple of values as - returned by sys.exc_info(). - """ - if isinstance(err[1], pythoncom.com_error) and \ - err[1].hresult==winerror.CO_E_CLASSSTRING: - self.num_invalid_clsid += 1 - if self.showAll: - self.stream.writeln("SKIP") - elif self.dots: - self.stream.write('S') - self.stream.flush() - return - super(TestResult, self).addError(test, err) - - def printErrors(self): - super(TestResult, self).printErrors() - if self.num_invalid_clsid: - self.stream.writeln("SKIPPED: %d tests due to missing COM objects used for testing" % - self.num_invalid_clsid) - - class TestRunner(unittest.TextTestRunner): - def _makeResult(self): - return TestResult(self.stream, self.descriptions, self.verbosity) # Utilities to set the win32com logger to something what just captures --- 146,149 ---- *************** *** 331,344 **** return "exec: " + cmd_repr ! class TestProgram(unittest.TestProgram): ! def runTests(self): ! if self.testRunner is None: ! self.testRunner = TestRunner(verbosity=self.verbosity) ! unittest.TestProgram(self) ! def testmain(*args, **kw): ! new_kw = kw.copy() ! if 'testLoader' not in new_kw: ! new_kw['testLoader'] = TestLoader() ! unittest.main(*args, **new_kw) CheckClean() --- 221,226 ---- return "exec: " + cmd_repr ! def testmain(*args, **kw): ! pywin32_testutil.testmain(*args, **new_kw) CheckClean() |
From: Mark H. <mha...@us...> - 2009-01-07 06:00:02
|
Update of /cvsroot/pywin32/pywin32/win32/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv3949/win32/test Modified Files: testall.py Log Message: Rationalize win32com test utilities into new pywin32_testutil module. Includes support for tests being "skipped" rather than failing due to something out of our control, and some helpers for dealing with bytes and buffers on py3k. Index: testall.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/test/testall.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** testall.py 19 Dec 2008 05:09:27 -0000 1.11 --- testall.py 7 Jan 2009 05:59:56 -0000 1.12 *************** *** 1,5 **** --- 1,7 ---- import sys, os + import re import unittest import traceback + import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed *************** *** 19,25 **** } ! ok_exceptions = { ! "RegCreateKeyTransacted": ("NotImplementedError"), ! } class TestRunner: --- 21,72 ---- } ! # re to pull apart an exception line into the exception type and the args. ! re_exception = re.compile("([a-zA-Z0-9_.]*): (.*)$") ! def find_exception_in_output(data): ! have_traceback = False ! for line in data.splitlines(): ! line = line.decode('ascii') # not sure what the correct encoding is... ! if line.startswith("Traceback ("): ! have_traceback = True ! continue ! if line.startswith(" "): ! continue ! if have_traceback: ! # first line not starting with a space since the traceback. ! # must be the exception! ! m = re_exception.match(line) ! if m: ! exc_type, args = m.groups() ! # get hacky - get the *real* exception object from the name. ! bits = exc_type.split(".", 1) ! if len(bits) > 1: ! mod = __import__(bits[0]) ! exc = getattr(mod, bits[1]) ! else: ! # probably builtin ! exc = eval(bits[0]) ! else: ! # hrm - probably just an exception with no args ! try: ! exc = eval(line.strip()) ! args = "()" ! except: ! return None ! # try and turn the args into real args. ! try: ! args = eval(args) ! except: ! pass ! if not isinstance(args, tuple): ! args = (args,) ! # try and instantiate the exception. ! try: ! ret = exc(*args) ! except: ! ret = None ! return ret ! # apparently not - keep looking... ! have_traceback = False ! class TestRunner: *************** *** 43,46 **** --- 90,97 ---- if rc: base = os.path.basename(self.argv[1]) + # See if we can detect and reconstruct an exception in the output. + reconstituted = find_exception_in_output(output) + if reconstituted is not None: + raise reconstituted raise AssertionError("%s failed with exit code %s. Output is:\n%s" % (base, rc, output)) *************** *** 54,60 **** if ext != ".py" or base in ui_demos or base in bad_demos: continue - if base in ok_exceptions: - print "Ack - can't handle test %s - can't catch specific exceptions" % (base,) - continue argv = (sys.executable, os.path.join(demo_dir, base+".py")) + \ argvs.get(base, ()) --- 105,108 ---- *************** *** 114,121 **** return suite ! class CustomLoader(unittest.TestLoader): def loadTestsFromModule(self, module): ! return suite() if __name__=='__main__': ! unittest.TestProgram(testLoader=CustomLoader())(argv=sys.argv) --- 162,169 ---- return suite ! class CustomLoader(pywin32_testutil.TestLoader): def loadTestsFromModule(self, module): ! return self.fixupTestsForLeakTests(suite()) if __name__=='__main__': ! pywin32_testutil.testmain(testLoader=CustomLoader()) |
From: Mark H. <mha...@us...> - 2009-01-07 06:00:02
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv3949/win32/Lib Added Files: pywin32_testutil.py Log Message: Rationalize win32com test utilities into new pywin32_testutil module. Includes support for tests being "skipped" rather than failing due to something out of our control, and some helpers for dealing with bytes and buffers on py3k. --- NEW FILE: pywin32_testutil.py --- # Utilities for the pywin32 tests import sys import unittest import gc import winerror ## ## General purpose utilities for the test suite. ## # The test suite has lots of string constants containing binary data, but # the strings are used in various "bytes" contexts. def str2bytes(sval): if sys.version_info < (3,0) and isinstance(sval, str): sval = sval.decode("latin1") return sval.encode("latin1") # Sometimes we want to pass a string that should explicitly be treated as # a memory blob. def str2memory(sval): if sys.version_info < (3,0): return buffer(sval) # py3k. return memoryview(sval.encode("latin1")) # Sometimes we want to pass an object that exposes its memory def ob2memory(ob): if sys.version_info < (3,0): return buffer(ob) # py3k. return memoryview(ob) # Note: no str2unicode: we use u'' literals or unicode() function, and 2to3 # ## ## unittest related stuff ## # This is a specialized TestCase adaptor which wraps a real test. class LeakTestCase(unittest.TestCase): """An 'adaptor' which takes another test. In debug builds we execute the test once to remove one-off side-effects, then capture the total reference count, then execute the test a few times. If the total refcount at the end is greater than we first captured, we have a leak! In release builds the test is executed just once, as normal. Generally used automatically by the test runner - you can safely ignore this. """ def __init__(self, real_test): unittest.TestCase.__init__(self) self.real_test = real_test self.num_test_cases = 1 self.num_leak_iters = 2 # seems to be enough! if hasattr(sys, "gettotalrefcount"): self.num_test_cases = self.num_test_cases + self.num_leak_iters def countTestCases(self): return self.num_test_cases def __call__(self, result = None): # For the COM suite's sake, always ensure we don't leak # gateways/interfaces from pythoncom import _GetInterfaceCount, _GetGatewayCount gc.collect() ni = _GetInterfaceCount() ng = _GetGatewayCount() self.real_test(result) # Failed - no point checking anything else if result.shouldStop or not result.wasSuccessful(): return self._do_leak_tests(result) gc.collect() lost_i = _GetInterfaceCount() - ni lost_g = _GetGatewayCount() - ng if lost_i or lost_g: msg = "%d interface objects and %d gateway objects leaked" \ % (lost_i, lost_g) result.addFailure(self.real_test, (AssertionError, msg, None)) def runTest(self): assert 0, "not used" def _do_leak_tests(self, result = None): try: gtrc = sys.gettotalrefcount except AttributeError: return # can't do leak tests in this build # Assume already called once, to prime any caches etc gc.collect() trc = gtrc() for i in range(self.num_leak_iters): self.real_test(result) if result.shouldStop: break del i # created after we remembered the refcount! # int division here means one or 2 stray references won't force # failure, but one per loop gc.collect() lost = (gtrc() - trc) // self.num_leak_iters if lost < 0: msg = "LeakTest: %s appeared to gain %d references!!" % (self.real_test, -lost) result.addFailure(self.real_test, (AssertionError, msg, None)) if lost > 0: msg = "LeakTest: %s lost %d references" % (self.real_test, lost) result.addFailure(self.real_test, (AssertionError, msg, None)) class TestLoader(unittest.TestLoader): def loadTestsFromTestCase(self, testCaseClass): """Return a suite of all tests cases contained in testCaseClass""" leak_tests = [] for name in self.getTestCaseNames(testCaseClass): real_test = testCaseClass(name) leak_test = self._getTestWrapper(real_test) leak_tests.append(leak_test) return self.suiteClass(leak_tests) def fixupTestsForLeakTests(self, test): if isinstance(test, unittest.TestSuite): test._tests = [self.fixupTestsForLeakTests(t) for t in test._tests] return test else: # just a normal test case. return self._getTestWrapper(test) def _getTestWrapper(self, test): # one or 2 tests in the COM test suite set this... no_leak_tests = getattr(test, "no_leak_tests", False) if no_leak_tests: print "Test says it doesn't want leak tests!" return test return LeakTestCase(test) def loadTestsFromModule(self, mod): if hasattr(mod, "suite"): tests = mod.suite() else: tests = unittest.TestLoader.loadTestsFromModule(self, mod) return self.fixupTestsForLeakTests(tests) def loadTestsFromName(self, name, module=None): test = unittest.TestLoader.loadTestsFromName(self, name, module) if isinstance(test, unittest.TestSuite): pass # hmmm? print "Don't wrap suites yet!", test._tests elif isinstance(test, unittest.TestCase): test = self._getTestWrapper(test) else: print "XXX - what is", test return test # Lots of classes necessary to support one simple feature: we want a 3rd # test result state - "SKIPPED" - to indicate that the test wasn't able # to be executed for various reasons. Inspired by bzr's tests, but it # has other concepts, such as "Expected Failure", which we don't bother # with. # win32 error codes that probably mean we need to be elevated (ie, if we # aren't elevated, we treat these error codes as 'skipped') non_admin_error_codes = [winerror.ERROR_ACCESS_DENIED, winerror.ERROR_PRIVILEGE_NOT_HELD] _is_admin = None def check_is_admin(): global _is_admin if _is_admin is None: from win32com.shell.shell import IsUserAnAdmin try: _is_admin = IsUserAnAdmin() except NotImplementedError: # not impl on this platform - must be old - assume is admin _is_admin = True return _is_admin # If this exception is raised by a test, the test is reported as a 'skip' class TestSkipped(Exception): pass # The 'TestResult' subclass that records the failures and has the special # handling for the TestSkipped exception. class TestResult(unittest._TextTestResult): def __init__(self, *args, **kw): super(TestResult, self).__init__(*args, **kw) self.num_skipped = 0 def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ # translate a couple of 'well-known' exceptions into 'skipped' import pywintypes exc_val = err[1] # translate ERROR_ACCESS_DENIED for non-admin users to be skipped. # (access denied errors for an admin user aren't expected.) if isinstance(exc_val, pywintypes.error) \ and exc_val.winerror in non_admin_error_codes \ and not check_is_admin(): exc_val = TestSkipped(exc_val) # and COM errors due to objects not being registered (the com test # suite will attempt to catch this and handle it itself if the user # is admin) elif isinstance(exc_val, pywintypes.com_error) and \ exc_val.hresult==winerror.CO_E_CLASSSTRING: exc_val = TestSkipped(exc_val) # NotImplemented generally means the platform doesn't support the # functionality. elif isinstance(exc_val, NotImplementedError): exc_val = TestSkipped(NotImplementedError) if isinstance(exc_val, TestSkipped): self.num_skipped += 1 if self.showAll: self.stream.writeln("SKIP") elif self.dots: self.stream.write('S') self.stream.flush() return super(TestResult, self).addError(test, err) def printErrors(self): super(TestResult, self).printErrors() if self.num_skipped: self.stream.writeln("SKIPPED: %d tests" % self.num_skipped) # TestRunner subclass necessary just to get our TestResult hooked up. class TestRunner(unittest.TextTestRunner): def _makeResult(self): return TestResult(self.stream, self.descriptions, self.verbosity) # TestProgream subclass necessary just to get our TestRunner hooked up, # which is necessary to get our TestResult hooked up *sob* class TestProgram(unittest.TestProgram): def runTests(self): # clobber existing runner - *sob* - it shouldn't be this hard self.testRunner = TestRunner(verbosity=self.verbosity) unittest.TestProgram.runTests(self) # A convenient entry-point - if used, 'SKIPPED' exceptions will be supressed. def testmain(*args, **kw): new_kw = kw.copy() if 'testLoader' not in new_kw: new_kw['testLoader'] = TestLoader() program_class = new_kw.get('testProgram', TestProgram) program_class(*args, **new_kw) |
From: Mark H. <mha...@us...> - 2009-01-07 05:56:54
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv3910/win32/Lib Modified Files: winioctlcon.py Log Message: remove L suffixes on various constants Index: winioctlcon.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/winioctlcon.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** winioctlcon.py 17 Feb 2007 05:32:55 -0000 1.3 --- winioctlcon.py 7 Jan 2009 05:56:49 -0000 1.4 *************** *** 7,11 **** def DEVICE_TYPE_FROM_CTL_CODE(ctrlCode): ! return (ctrlCode & 0xffff0000L) >> 16 FILE_DEVICE_BEEP = 0x00000001 --- 7,11 ---- def DEVICE_TYPE_FROM_CTL_CODE(ctrlCode): ! return (ctrlCode & 0xffff0000) >> 16 FILE_DEVICE_BEEP = 0x00000001 *************** *** 86,92 **** WRITE_COMPRESSION_INFO_VALID = 0x00000010 READ_COMPRESSION_INFO_VALID = 0x00000020 ! TAPE_RETURN_STATISTICS = 0L ! TAPE_RETURN_ENV_INFO = 1L ! TAPE_RESET_STATISTICS = 2L MEDIA_ERASEABLE = 0x00000001 MEDIA_WRITE_ONCE = 0x00000002 --- 86,92 ---- WRITE_COMPRESSION_INFO_VALID = 0x00000010 READ_COMPRESSION_INFO_VALID = 0x00000020 ! TAPE_RETURN_STATISTICS = 0 ! TAPE_RETURN_ENV_INFO = 1 ! TAPE_RESET_STATISTICS = 2 MEDIA_ERASEABLE = 0x00000001 MEDIA_WRITE_ONCE = 0x00000002 *************** *** 94,98 **** MEDIA_READ_WRITE = 0x00000008 MEDIA_WRITE_PROTECTED = 0x00000100 ! MEDIA_CURRENTLY_MOUNTED = 0x80000000L IOCTL_DISK_BASE = FILE_DEVICE_DISK PARTITION_ENTRY_UNUSED = 0x00 --- 94,98 ---- MEDIA_READ_WRITE = 0x00000008 MEDIA_WRITE_PROTECTED = 0x00000100 ! MEDIA_CURRENTLY_MOUNTED = 0x80000000 IOCTL_DISK_BASE = FILE_DEVICE_DISK PARTITION_ENTRY_UNUSED = 0x00 *************** *** 203,218 **** CHANGER_DRIVE_EMPTY_ON_DOOR_ACCESS = 0x20000000 ! CHANGER_RESERVED_BIT = 0x80000000L ! CHANGER_PREDISMOUNT_ALIGN_TO_SLOT = 0x80000001L ! CHANGER_PREDISMOUNT_ALIGN_TO_DRIVE = 0x80000002L ! CHANGER_CLEANER_AUTODISMOUNT = 0x80000004L ! CHANGER_TRUE_EXCHANGE_CAPABLE = 0x80000008L ! CHANGER_SLOTS_USE_TRAYS = 0x80000010L ! CHANGER_RTN_MEDIA_TO_ORIGINAL_ADDR = 0x80000020L ! CHANGER_CLEANER_OPS_NOT_SUPPORTED = 0x80000040L ! CHANGER_IEPORT_USER_CONTROL_OPEN = 0x80000080L ! CHANGER_IEPORT_USER_CONTROL_CLOSE = 0x80000100L ! CHANGER_MOVE_EXTENDS_IEPORT = 0x80000200L ! CHANGER_MOVE_RETRACTS_IEPORT = 0x80000400L --- 203,218 ---- CHANGER_DRIVE_EMPTY_ON_DOOR_ACCESS = 0x20000000 ! CHANGER_RESERVED_BIT = 0x80000000 ! CHANGER_PREDISMOUNT_ALIGN_TO_SLOT = 0x80000001 ! CHANGER_PREDISMOUNT_ALIGN_TO_DRIVE = 0x80000002 ! CHANGER_CLEANER_AUTODISMOUNT = 0x80000004 ! CHANGER_TRUE_EXCHANGE_CAPABLE = 0x80000008 ! CHANGER_SLOTS_USE_TRAYS = 0x80000010 ! CHANGER_RTN_MEDIA_TO_ORIGINAL_ADDR = 0x80000020 ! CHANGER_CLEANER_OPS_NOT_SUPPORTED = 0x80000040 ! CHANGER_IEPORT_USER_CONTROL_OPEN = 0x80000080 ! CHANGER_IEPORT_USER_CONTROL_CLOSE = 0x80000100 ! CHANGER_MOVE_EXTENDS_IEPORT = 0x80000200 ! CHANGER_MOVE_RETRACTS_IEPORT = 0x80000400 *************** *** 248,252 **** ERROR_TRAY_MALFUNCTION = 0x00000010 ERROR_INIT_STATUS_NEEDED = 0x00000011 ! ERROR_UNHANDLED_ERROR = 0xFFFFFFFFL SEARCH_ALL = 0x0 SEARCH_PRIMARY = 0x1 --- 248,252 ---- ERROR_TRAY_MALFUNCTION = 0x00000010 ERROR_INIT_STATUS_NEEDED = 0x00000011 ! ERROR_UNHANDLED_ERROR = 0xFFFFFFFF SEARCH_ALL = 0x0 SEARCH_PRIMARY = 0x1 *************** *** 283,287 **** USN_REASON_STREAM_CHANGE = 0x00200000 USN_REASON_TRANSACTED_CHANGE = 0x00400000 ! USN_REASON_CLOSE = 0x80000000L USN_DELETE_FLAG_DELETE = 0x00000001 USN_DELETE_FLAG_NOTIFY = 0x00000002 --- 283,287 ---- USN_REASON_STREAM_CHANGE = 0x00200000 USN_REASON_TRANSACTED_CHANGE = 0x00400000 ! USN_REASON_CLOSE = 0x80000000 USN_DELETE_FLAG_DELETE = 0x00000001 USN_DELETE_FLAG_NOTIFY = 0x00000002 |
From: Mark H. <mha...@us...> - 2009-01-07 04:11:12
|
Update of /cvsroot/pywin32/pywin32 In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv30987 Modified Files: setup.py Log Message: fix syntax so 2to3 does the right-thing Index: setup.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/setup.py,v retrieving revision 1.88 retrieving revision 1.89 diff -C2 -d -r1.88 -r1.89 *** setup.py 5 Jan 2009 11:01:45 -0000 1.88 --- setup.py 7 Jan 2009 04:11:06 -0000 1.89 *************** *** 76,80 **** # using the 'imports' fixer and therefore start much faster... if is_py3k: ! import winreg as _winreg else: import _winreg --- 76,80 ---- # using the 'imports' fixer and therefore start much faster... if is_py3k: ! import winreg as winreg else: import _winreg |
From: Mark H. <mha...@us...> - 2009-01-07 04:10:33
|
Update of /cvsroot/pywin32/pywin32/com/win32com/client In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv30942/com/win32com/client Modified Files: build.py Log Message: remove unused import of types module Index: build.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/build.py,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** build.py 4 Jan 2009 13:43:16 -0000 1.36 --- build.py 7 Jan 2009 04:10:24 -0000 1.37 *************** *** 19,23 **** import sys import string - import types from keyword import iskeyword --- 19,22 ---- |
From: Mark H. <mha...@us...> - 2009-01-07 04:10:09
|
Update of /cvsroot/pywin32/pywin32/com/win32com/servers In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv30864/com/win32com/servers Modified Files: PythonTools.py Log Message: py3k-friendly use of reload Index: PythonTools.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/servers/PythonTools.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** PythonTools.py 6 Dec 2008 01:46:49 -0000 1.6 --- PythonTools.py 7 Jan 2009 04:09:57 -0000 1.7 *************** *** 7,10 **** --- 7,14 ---- def reload(self, module): if module in sys.modules: + try: + from imp import reload + except ImportError: + pass # builtin in py2k reload(sys.modules[module]) return "reload succeeded." |
From: Mark H. <mha...@us...> - 2009-01-07 04:09:39
|
Update of /cvsroot/pywin32/pywin32/com/win32com/client In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv30833/com/win32com/client Modified Files: selecttlb.py Log Message: allow the list of typelibs to sort on py3k Index: selecttlb.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/selecttlb.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** selecttlb.py 14 Nov 2008 00:22:25 -0000 1.11 --- selecttlb.py 7 Jan 2009 04:09:32 -0000 1.12 *************** *** 32,35 **** --- 32,37 ---- rc = cmp(self.major, other.minor) return rc + def __lt__(self, other): # rich-cmp/py3k-friendly version + return self.__cmp__(other) < 0 def Resolve(self): |
From: Mark H. <mha...@us...> - 2009-01-07 04:08:33
|
Update of /cvsroot/pywin32/pywin32/com/win32comext/adsi In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv30739/com/win32comext/adsi Modified Files: adsicon.py Log Message: remove L suffix on error constants Index: adsicon.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32comext/adsi/adsicon.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** adsicon.py 26 May 2005 11:39:17 -0000 1.3 --- adsicon.py 7 Jan 2009 04:08:28 -0000 1.4 *************** *** 242,248 **** E_ADS_SCHEMA_VIOLATION = _HRESULT_TYPEDEF_((-2147463153)) E_ADS_COLUMN_NOT_SET = _HRESULT_TYPEDEF_((-2147463152)) ! S_ADS_ERRORSOCCURRED = _HRESULT_TYPEDEF_(0x00005011L) ! S_ADS_NOMORE_ROWS = _HRESULT_TYPEDEF_(0x00005012L) ! S_ADS_NOMORE_COLUMNS = _HRESULT_TYPEDEF_(0x00005013L) E_ADS_INVALID_FILTER = _HRESULT_TYPEDEF_((-2147463148)) --- 242,248 ---- E_ADS_SCHEMA_VIOLATION = _HRESULT_TYPEDEF_((-2147463153)) E_ADS_COLUMN_NOT_SET = _HRESULT_TYPEDEF_((-2147463152)) ! S_ADS_ERRORSOCCURRED = _HRESULT_TYPEDEF_(0x00005011) ! S_ADS_NOMORE_ROWS = _HRESULT_TYPEDEF_(0x00005012) ! S_ADS_NOMORE_COLUMNS = _HRESULT_TYPEDEF_(0x00005013) E_ADS_INVALID_FILTER = _HRESULT_TYPEDEF_((-2147463148)) |
From: Mark H. <mha...@us...> - 2009-01-05 12:51:37
|
Update of /cvsroot/pywin32/pywin32/Pythonwin In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4261/Pythonwin Modified Files: Tag: py3k win32win.cpp Log Message: merge lots of changes (most via 2to3) from the trunk Index: win32win.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/win32win.cpp,v retrieving revision 1.21.2.3 retrieving revision 1.21.2.4 diff -C2 -d -r1.21.2.3 -r1.21.2.4 *** win32win.cpp 28 Dec 2008 12:53:32 -0000 1.21.2.3 --- win32win.cpp 5 Jan 2009 12:51:26 -0000 1.21.2.4 *************** *** 2711,2716 **** RETURN_ERR("BeginPaint failed"); PyObject *obDC = ui_assoc_object::make (ui_dc_object::type, pTemp)->GetGoodRet(); ! PyObject *obRet = Py_BuildValue("O(Ni(iiii)iiN)", obDC, ! PyWinLong_FromHANDLE(ps.hdc), ps.fErase, ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom, --- 2711,2716 ---- RETURN_ERR("BeginPaint failed"); PyObject *obDC = ui_assoc_object::make (ui_dc_object::type, pTemp)->GetGoodRet(); ! PyObject *obRet = Py_BuildValue("O(ii(iiii)iiN)", obDC, ! ps.hdc, ps.fErase, ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom, *************** *** 3703,3710 **** return NULL; GUI_BGN_SAVE; ! try { pFrame->LoadBarState(profileName); // @pyseemfc CFrameWnd|LoadBarState } ! catch (...) { GUI_BLOCK_THREADS; PyWinObject_FreeTCHAR(profileName); --- 3703,3710 ---- return NULL; GUI_BGN_SAVE; ! PYWINTYPES_TRY { pFrame->LoadBarState(profileName); // @pyseemfc CFrameWnd|LoadBarState } ! PYWINTYPES_EXCEPT { GUI_BLOCK_THREADS; PyWinObject_FreeTCHAR(profileName); |
Update of /cvsroot/pywin32/pywin32/com/win32com/test In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4261/com/win32com/test Modified Files: Tag: py3k testAXScript.py testPyComTest.py testStreams.py testmakepy.py testvb.py util.py Log Message: merge lots of changes (most via 2to3) from the trunk Index: testPyComTest.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testPyComTest.py,v retrieving revision 1.32.2.7 retrieving revision 1.32.2.8 diff -C2 -d -r1.32.2.7 -r1.32.2.8 *** testPyComTest.py 4 Dec 2008 07:32:05 -0000 1.32.2.7 --- testPyComTest.py 5 Jan 2009 12:51:27 -0000 1.32.2.8 *************** *** 3,12 **** import sys; sys.coinit_flags=0 # Must be free-threaded! ! import win32api, types, pythoncom, time import sys, os, win32com, win32com.client.connect from win32com.test.util import CheckClean ! from win32com.client import constants import win32com ! from .util import RegisterPythonServer importMsg = "**** PyCOMTest is not installed ***\n PyCOMTest is a Python test specific COM client and server.\n It is likely this server is not installed on this machine\n To install the server, you must get the win32com sources\n and build it using MS Visual C++" --- 3,12 ---- import sys; sys.coinit_flags=0 # Must be free-threaded! ! import win32api, pythoncom, time import sys, os, win32com, win32com.client.connect from win32com.test.util import CheckClean ! from win32com.client import constants, DispatchBaseClass import win32com ! from win32com.test.util import RegisterPythonServer importMsg = "**** PyCOMTest is not installed ***\n PyCOMTest is a Python test specific COM client and server.\n It is likely this server is not installed on this machine\n To install the server, you must get the win32com sources\n and build it using MS Visual C++" *************** *** 33,36 **** --- 33,45 ---- verbose = 0 + # convert a normal int to a long int - used to avoid, eg, '1L' for py3k + # friendliness + def ensure_long(int_val): + if sys.version_info > (3,): + # py3k - no such thing as a 'long' + return int_val + # on py2x, we just use an expression that results in a long + return 0x100000000-0x100000000+int_val + def progress(*args): if verbose: *************** *** 180,184 **** i1, i2 = o.GetMultipleInterfaces() ! if type(i1) != types.InstanceType or type(i2) != types.InstanceType: # Yay - is now an instance returned! raise error("GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2)) --- 189,193 ---- i1, i2 = o.GetMultipleInterfaces() ! if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass): # Yay - is now an instance returned! raise error("GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2)) *************** *** 212,216 **** raise error("GetSetUnknown failed") progress("Checking getting/passing IDispatch") ! if type(o.GetSetDispatch(o)) !=types.InstanceType: raise error("GetSetDispatch failed") progress("Checking getting/passing IDispatch of known type") --- 221,225 ---- raise error("GetSetUnknown failed") progress("Checking getting/passing IDispatch") ! if not isinstance(o.GetSetDispatch(o), DispatchBaseClass): raise error("GetSetDispatch failed") progress("Checking getting/passing IDispatch of known type") *************** *** 223,227 **** if o.GetSetVariant(o) != o: raise error("GetSetVariant (dispatch) failed") ! for l in sys.maxint, sys.maxint+1, 1 << 65: if o.GetSetVariant(l) != l: raise error("GetSetVariant (long) failed") --- 232,239 ---- if o.GetSetVariant(o) != o: raise error("GetSetVariant (dispatch) failed") ! # We want to explicitly test > 32 bits. py3k has no 'maxint' and ! # 'maxsize+1' is no good on 64bit platforms as its 65 bits! ! big = 2147483647 # sys.maxint on py2k ! for l in big, big+1, 1 << 65: if o.GetSetVariant(l) != l: raise error("GetSetVariant (long) failed") *************** *** 271,278 **** TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5) ! TestConstant("ULongTest1", 0xFFFFFFFF) ! TestConstant("ULongTest2", 0x7FFFFFFF) ! TestConstant("LongTest1", -0x7FFFFFFF) ! TestConstant("LongTest2", 0x7FFFFFFF) TestConstant("UCharTest", 255) TestConstant("CharTest", -1) --- 283,290 ---- TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5) ! TestConstant("ULongTest1", ensure_long(0xFFFFFFFF)) ! TestConstant("ULongTest2", ensure_long(0x7FFFFFFF)) ! TestConstant("LongTest1", ensure_long(-0x7FFFFFFF)) ! TestConstant("LongTest2", ensure_long(0x7FFFFFFF)) TestConstant("UCharTest", 255) TestConstant("CharTest", -1) Index: util.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/util.py,v retrieving revision 1.9.2.6 retrieving revision 1.9.2.7 diff -C2 -d -r1.9.2.6 -r1.9.2.7 *** util.py 11 Dec 2008 05:45:21 -0000 1.9.2.6 --- util.py 5 Jan 2009 12:51:27 -0000 1.9.2.7 *************** *** 187,191 **** del i # created after we remembered the refcount! # int division here means one or 2 stray references won't force ! # failure, but one per loop lost = (gtrc() - trc) // self.num_leak_iters if lost < 0: --- 187,192 ---- del i # created after we remembered the refcount! # int division here means one or 2 stray references won't force ! # failure, but one per loop ! gc.collect() lost = (gtrc() - trc) // self.num_leak_iters if lost < 0: *************** *** 265,276 **** self.emitted.append(record) def setup_test_logger(): old_log = getattr(win32com, "logger", None) ! win32com.logger = logging.Logger('test') ! handler = LogHandler() ! win32com.logger.addHandler(handler) return handler.emitted, old_log def restore_test_logger(prev_logger): if prev_logger is None: del win32com.logger --- 266,285 ---- self.emitted.append(record) + _win32com_logger = None def setup_test_logger(): old_log = getattr(win32com, "logger", None) ! global _win32com_logger ! if _win32com_logger is None: ! _win32com_logger = logging.Logger('test') ! handler = LogHandler() ! _win32com_logger.addHandler(handler) ! ! win32com.logger = _win32com_logger ! handler = _win32com_logger.handlers[0] ! handler.emitted = [] return handler.emitted, old_log def restore_test_logger(prev_logger): + assert prev_logger is None, "who needs this?" if prev_logger is None: del win32com.logger *************** *** 322,331 **** return "exec: " + cmd_repr def testmain(*args, **kw): new_kw = kw.copy() if 'testLoader' not in new_kw: new_kw['testLoader'] = TestLoader() - if 'testRunner' not in new_kw: - new_kw['testRunner'] = TestRunner() unittest.main(*args, **new_kw) CheckClean() --- 331,344 ---- return "exec: " + cmd_repr + class TestProgram(unittest.TestProgram): + def runTests(self): + if self.testRunner is None: + self.testRunner = TestRunner(verbosity=self.verbosity) + unittest.TestProgram(self) + def testmain(*args, **kw): new_kw = kw.copy() if 'testLoader' not in new_kw: new_kw['testLoader'] = TestLoader() unittest.main(*args, **new_kw) CheckClean() Index: testStreams.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testStreams.py,v retrieving revision 1.6.2.1 retrieving revision 1.6.2.2 diff -C2 -d -r1.6.2.1 -r1.6.2.2 *** testStreams.py 13 Sep 2008 12:27:42 -0000 1.6.2.1 --- testStreams.py 5 Jan 2009 12:51:27 -0000 1.6.2.2 *************** *** 10,14 **** _com_interfaces_ = [ pythoncom.IID_IPersistStreamInit ] def __init__(self): ! self.data = b"abcdefg" self.dirty = 1 def GetClassID(self): --- 10,14 ---- _com_interfaces_ = [ pythoncom.IID_IPersistStreamInit ] def __init__(self): ! self.data = "abcdefg".encode("ascii") self.dirty = 1 def GetClassID(self): *************** *** 67,71 **** """ def Read(self, amount): ! return b'x'*(amount+1) class StreamTest(win32com.test.util.TestCase): --- 67,71 ---- """ def Read(self, amount): ! return 'x'.encode('ascii')*(amount+1) class StreamTest(win32com.test.util.TestCase): *************** *** 81,85 **** def testit(self): ! mydata = b'abcdefghijklmnopqrstuvwxyz' # First test the objects just as Python objects... --- 81,85 ---- def testit(self): ! mydata = 'abcdefghijklmnopqrstuvwxyz'.encode('ascii') # First test the objects just as Python objects... *************** *** 90,94 **** p.Save(s, 0) self.assertEqual(s.data, mydata) ! # Wrap the Python objects as COM objects, and make the calls as if # they were non-Python COM objects. --- 90,94 ---- p.Save(s, 0) self.assertEqual(s.data, mydata) ! # Wrap the Python objects as COM objects, and make the calls as if # they were non-Python COM objects. *************** *** 101,105 **** self._readWrite(mydata, s2, s2) ! self._readWrite(b"string with\0a NULL", s2, s2) # reset the stream s.Write(mydata) --- 101,105 ---- self._readWrite(mydata, s2, s2) ! self._readWrite("string with\0a NULL".encode('ascii'), s2, s2) # reset the stream s.Write(mydata) *************** *** 108,111 **** --- 108,112 ---- self.assertEqual(s.data, mydata) + def testerrors(self): # setup a test logger to capture tracebacks etc. records, old_log = win32com.test.util.setup_test_logger() Index: testAXScript.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testAXScript.py,v retrieving revision 1.7.4.3 retrieving revision 1.7.4.4 diff -C2 -d -r1.7.4.3 -r1.7.4.4 *** testAXScript.py 27 Nov 2008 11:31:05 -0000 1.7.4.3 --- testAXScript.py 5 Jan 2009 12:51:27 -0000 1.7.4.4 *************** *** 13,17 **** def setUp(self): file = win32api.GetFullPathName(os.path.join(win32com.axscript.client.__path__[0], "pyscript.py")) ! from .util import RegisterPythonServer self.verbose = verbose RegisterPythonServer(file, 'python', verbose=self.verbose) --- 13,17 ---- def setUp(self): file = win32api.GetFullPathName(os.path.join(win32com.axscript.client.__path__[0], "pyscript.py")) ! from win32com.test.util import RegisterPythonServer self.verbose = verbose RegisterPythonServer(file, 'python', verbose=self.verbose) Index: testvb.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testvb.py,v retrieving revision 1.20.4.5 retrieving revision 1.20.4.6 diff -C2 -d -r1.20.4.5 -r1.20.4.6 *** testvb.py 19 Dec 2008 02:33:56 -0000 1.20.4.5 --- testvb.py 5 Jan 2009 12:51:27 -0000 1.20.4.6 *************** *** 4,7 **** --- 4,8 ---- # + import sys import winerror import pythoncom, win32com.client, win32com.client.dynamic, win32com.client.gencache *************** *** 11,14 **** --- 12,21 ---- import traceback + def string_to_buffer(s): + if sys.version_info < (3,0): + return buffer(s) + else: + return memoryview(s.encode("ascii")) + # for debugging useDispatcher = None *************** *** 67,75 **** if vbtest.VariantProperty != 10: raise error("Could not set the variant integer property correctly.") ! vbtest.VariantProperty = b'raw\0data' ! # FIX ME!!! ! print("Skipping bytes/variant tests 'cos they don't work :(") ! #if vbtest.VariantProperty != b'raw\0data': ! # raise error("Could not set the variant buffer property correctly: %r" % vbtest.VariantProperty) vbtest.StringProperty = "Hello from Python" if vbtest.StringProperty != "Hello from Python": --- 74,80 ---- if vbtest.VariantProperty != 10: raise error("Could not set the variant integer property correctly.") ! vbtest.VariantProperty = string_to_buffer('raw\0data') ! if vbtest.VariantProperty != string_to_buffer('raw\0data'): ! raise error("Could not set the variant buffer property correctly.") vbtest.StringProperty = "Hello from Python" if vbtest.StringProperty != "Hello from Python": *************** *** 82,87 **** raise error("Could not set the variant property to an array of floats correctly - '%s'." % (vbtest.VariantProperty,)) - TestStructs(vbtest) TestArrays(vbtest, bUseGenerated) TestCollections(vbtest) --- 87,92 ---- raise error("Could not set the variant property to an array of floats correctly - '%s'." % (vbtest.VariantProperty,)) TestArrays(vbtest, bUseGenerated) + TestStructs(vbtest) TestCollections(vbtest) *************** *** 397,401 **** pass m = s.__members__ ! assert m[0]=="int_val" and m[1]=="str_val" and m[2]=="ob_val" and m[3]=="sub_val" # Test attribute errors. --- 402,406 ---- pass m = s.__members__ ! assert m[0]=="int_val" and m[1]=="str_val" and m[2]=="ob_val" and m[3]=="sub_val", m # Test attribute errors. *************** *** 408,412 **** # test repr - it uses repr() of the sub-objects, so check it matches. expected = "com_struct(int_val=%r, str_val=%r, ob_val=%r, sub_val=%r)" % (s.int_val, s.str_val, s.ob_val, s.sub_val) - print("REPR is", repr(s)) if repr(s) != expected: print("Expected repr:", expected) --- 413,416 ---- *************** *** 424,432 **** --- 428,461 ---- raise error("New value wrong") + def TestObjectSemantics(ob): + # a convenient place to test some of our equality semantics + assert ob==ob._oleobj_ + assert not ob!=ob._oleobj_ + # same test again, but lhs and rhs reversed. + assert ob._oleobj_==ob + assert not ob._oleobj_!=ob + # same tests but against different pointers. COM identity rules should + # still ensure all works + assert ob._oleobj_==ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown) + assert not ob._oleobj_!=ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown) + + assert ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown)==ob._oleobj_ + assert not ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown)!=ob._oleobj_ + + assert ob._oleobj_==ob._oleobj_.QueryInterface(pythoncom.IID_IDispatch) + assert not ob._oleobj_!=ob._oleobj_.QueryInterface(pythoncom.IID_IDispatch) + + assert ob._oleobj_.QueryInterface(pythoncom.IID_IDispatch)==ob._oleobj_ + assert not ob._oleobj_.QueryInterface(pythoncom.IID_IDispatch)!=ob._oleobj_ + + print("Object semantic tests passed") + def DoTestAll(): o = win32com.client.Dispatch("PyCOMVBTest.Tester") + TestObjectSemantics(o) TestVB(o,1) o = win32com.client.dynamic.DumbDispatch("PyCOMVBTest.Tester") + TestObjectSemantics(o) TestVB(o,0) Index: testmakepy.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/test/testmakepy.py,v retrieving revision 1.5.4.2 retrieving revision 1.5.4.3 diff -C2 -d -r1.5.4.2 -r1.5.4.3 *** testmakepy.py 4 Dec 2008 05:08:41 -0000 1.5.4.2 --- testmakepy.py 5 Jan 2009 12:51:27 -0000 1.5.4.3 *************** *** 26,30 **** # Ignore these 2 errors, as the are very common and can obscure # useful warnings. ! if details[0] not in [winerror.TYPE_E_CANTLOADLIBRARY, winerror.TYPE_E_LIBNOTREGISTERED]: print("** COM error on", info.desc) --- 26,30 ---- # Ignore these 2 errors, as the are very common and can obscure # useful warnings. ! if details.hresult not in [winerror.TYPE_E_CANTLOADLIBRARY, winerror.TYPE_E_LIBNOTREGISTERED]: print("** COM error on", info.desc) |
From: Mark H. <mha...@us...> - 2009-01-05 12:51:33
|
Update of /cvsroot/pywin32/pywin32/com/win32comext/mapi/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4261/com/win32comext/mapi/src Modified Files: Tag: py3k PyIMAPIAdviseSink.cpp Log Message: merge lots of changes (most via 2to3) from the trunk Index: PyIMAPIAdviseSink.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32comext/mapi/src/PyIMAPIAdviseSink.cpp,v retrieving revision 1.1 retrieving revision 1.1.2.1 diff -C2 -d -r1.1 -r1.1.2.1 *** PyIMAPIAdviseSink.cpp 9 Aug 2008 01:51:39 -0000 1.1 --- PyIMAPIAdviseSink.cpp 5 Jan 2009 12:51:27 -0000 1.1.2.1 *************** *** 17,21 **** switch (n->ulEventType) { case fnevCriticalError: { ! ERROR_NOTIFICATION &err(n->info.err); ret = Py_BuildValue("k(s#iiN)", n->ulEventType, --- 17,21 ---- switch (n->ulEventType) { case fnevCriticalError: { ! ERROR_NOTIFICATION &err = n->info.err; ret = Py_BuildValue("k(s#iiN)", n->ulEventType, *************** *** 27,31 **** } case fnevExtended: { ! EXTENDED_NOTIFICATION &ext(n->info.ext); ret = Py_BuildValue("k(ks#)", n->ulEventType, ext.ulEvent, ext.pbEventParameters, ext.cb); --- 27,31 ---- } case fnevExtended: { ! EXTENDED_NOTIFICATION &ext = n->info.ext; ret = Py_BuildValue("k(ks#)", n->ulEventType, ext.ulEvent, ext.pbEventParameters, ext.cb); *************** *** 33,37 **** } case fnevNewMail: { ! NEWMAIL_NOTIFICATION &newmail(n->info.newmail); PyObject *msg_class = newmail.ulFlags&MAPI_UNICODE? PyWinObject_FromWCHAR((const WCHAR *)newmail.lpszMessageClass) : --- 33,37 ---- } case fnevNewMail: { ! NEWMAIL_NOTIFICATION &newmail = n->info.newmail; PyObject *msg_class = newmail.ulFlags&MAPI_UNICODE? PyWinObject_FromWCHAR((const WCHAR *)newmail.lpszMessageClass) : *************** *** 54,58 **** case fnevObjectMoved: case fnevSearchComplete: { ! OBJECT_NOTIFICATION &obj(n->info.obj); PyObject *obArray = PyMAPIObject_FromSPropTagArray(obj.lpPropTagArray); if (!obArray) --- 54,58 ---- case fnevObjectMoved: case fnevSearchComplete: { ! OBJECT_NOTIFICATION &obj = n->info.obj; PyObject *obArray = PyMAPIObject_FromSPropTagArray(obj.lpPropTagArray); if (!obArray) *************** *** 69,73 **** } case fnevTableModified: { ! TABLE_NOTIFICATION &tab(n->info.tab); ret = Py_BuildValue("k(kiNNN)", n->ulEventType, --- 69,73 ---- } case fnevTableModified: { ! TABLE_NOTIFICATION &tab = n->info.tab; ret = Py_BuildValue("k(kiNNN)", n->ulEventType, *************** *** 80,84 **** } case fnevStatusObjectModified: { ! STATUS_OBJECT_NOTIFICATION &statobj(n->info.statobj); ret = Py_BuildValue("k(s#N)", n->ulEventType, --- 80,84 ---- } case fnevStatusObjectModified: { ! STATUS_OBJECT_NOTIFICATION &statobj = n->info.statobj; ret = Py_BuildValue("k(s#N)", n->ulEventType, |
From: Mark H. <mha...@us...> - 2009-01-05 12:51:33
|
Update of /cvsroot/pywin32/pywin32/com/win32com/server In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4261/com/win32com/server Modified Files: Tag: py3k register.py Log Message: merge lots of changes (most via 2to3) from the trunk Index: register.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/server/register.py,v retrieving revision 1.21.2.2 retrieving revision 1.21.2.3 diff -C2 -d -r1.21.2.2 -r1.21.2.3 *** register.py 27 Nov 2008 04:58:41 -0000 1.21.2.2 --- register.py 5 Jan 2009 12:51:26 -0000 1.21.2.3 *************** *** 476,479 **** --- 476,552 ---- return ret + # Attempt to 're-execute' our current process with elevation. + def ReExecuteElevated(flags): + from win32com.shell.shell import ShellExecuteEx + from win32com.shell import shellcon + import win32process, win32event + import winxpgui # we've already checked we are running XP above + import tempfile + + if not flags['quiet']: + print("Requesting elevation and retrying...") + new_params = " ".join(['"' + a + '"' for a in sys.argv]) + # If we aren't already in unattended mode, we want our sub-process to + # be. + if not flags['unattended']: + new_params += " --unattended" + # specifying the parent means the dialog is centered over our window, + # which is a good usability clue. + # hwnd is unlikely on the command-line, but flags may come from elsewhere + hwnd = flags.get('hwnd', None) + if hwnd is None: + try: + hwnd = winxpgui.GetConsoleWindow() + except winxpgui.error: + hwnd = 0 + # Redirect output so we give the user some clue what went wrong. This + # also means we need to use COMSPEC. However, the "current directory" + # appears to end up ignored - so we execute things via a temp batch file. + tempbase = tempfile.mktemp("pycomserverreg") + outfile = tempbase + ".out" + batfile = tempbase + ".bat" + try: + batf = open(batfile, "w") + try: + cwd = os.getcwd() + print("@echo off", file=batf) + # nothing is 'inherited' by the elevated process, including the + # environment. I wonder if we need to set more? + print("set PYTHONPATH=%s" % os.environ.get('PYTHONPATH', ''), file=batf) + # may be on a different drive - select that before attempting to CD. + print(os.path.splitdrive(cwd)[0], file=batf) + print('cd "%s"' % os.getcwd(), file=batf) + print('%s %s > "%s" 2>&1' % (win32api.GetShortPathName(sys.executable), new_params, outfile), file=batf) + finally: + batf.close() + executable = os.environ.get('COMSPEC', 'cmd.exe') + rc = ShellExecuteEx(hwnd=hwnd, + fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, + lpVerb="runas", + lpFile=executable, + lpParameters='/C "%s"' % batfile, + nShow=win32con.SW_SHOW) + hproc = rc['hProcess'] + win32event.WaitForSingleObject(hproc, win32event.INFINITE) + exit_code = win32process.GetExitCodeProcess(hproc) + outf = open(outfile) + try: + output = outf.read() + finally: + outf.close() + + if exit_code: + # Even if quiet you get to see this message. + print("Error: registration failed (exit code %s)." % exit_code) + # if we are quiet then the output if likely to already be nearly + # empty, so always print it. + print(output, end=' ') + finally: + for f in (outfile, batfile): + try: + os.unlink(f) + except os.error as exc: + print("Failed to remove tempfile '%s': %s" % (f, exc)) + def UseCommandLine(*classes, **flags): unregisterInfo = '--unregister_info' in sys.argv *************** *** 496,536 **** or sys.getwindowsversion()[0] < 5: raise ! from win32com.shell.shell import ShellExecuteEx ! from win32com.shell import shellcon ! import win32process, win32event ! import winxpgui # we've already checked we are running XP above ! ! if not flags['quiet']: ! print("Requesting elevation and retrying...") ! new_params = " ".join(['"' + a + '"' for a in sys.argv]) ! # specifying the parent means the dialog is centered over our window, ! # which is a good usability clue. ! # hwnd is unlikely on the command-line, but flags may come from elsewhere ! hwnd = flags.get('hwnd', None) ! if hwnd is None: ! try: ! hwnd = winxpgui.GetConsoleWindow() ! except winxpgui.error: ! hwnd = 0 ! rc = ShellExecuteEx(hwnd=hwnd, ! fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, ! lpVerb="runas", ! lpFile=win32api.GetShortPathName(sys.executable), ! lpParameters=new_params, ! lpDirectory=os.getcwd(), ! nShow=win32con.SW_SHOW) ! # Output is lost to the new console which opens, so the ! # best we can do is get the exit code of the process. ! hproc = rc['hProcess'] ! win32event.WaitForSingleObject(hproc, win32event.INFINITE) ! exit_code = win32process.GetExitCodeProcess(hproc) ! if exit_code: ! # Even if quiet you get to see this error. ! print("Error: registration failed (exit code %s)." % exit_code) ! print("Please re-execute this command from an elevated command-prompt") ! print("to see details about the error.") ! else: ! if not flags['quiet']: ! print("Elevated process succeeded.") def RegisterPyComCategory(): --- 569,573 ---- or sys.getwindowsversion()[0] < 5: raise ! ReExecuteElevated(flags) def RegisterPyComCategory(): |
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4261/Pythonwin/pywin/scintilla Modified Files: Tag: py3k IDLEenvironment.py bindings.py control.py document.py view.py Log Message: merge lots of changes (most via 2to3) from the trunk Index: control.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla/control.py,v retrieving revision 1.17.2.4 retrieving revision 1.17.2.5 diff -C2 -d -r1.17.2.4 -r1.17.2.5 *** control.py 3 Jan 2009 04:45:17 -0000 1.17.2.4 --- control.py 5 Jan 2009 12:51:26 -0000 1.17.2.5 *************** *** 201,213 **** def SCICallTipShow(self, text, pos=-1): if pos==-1: pos = self.GetSel()[0] - """ - if isinstance(text, str): - # I'm really not sure what the correct encoding - # to use is - but it has gotta be better than total - # failure due to the array module - text = text.encode("mbcs") - """ buff = (text + "\0").encode(default_scintilla_encoding) - ## addressBuffer = buff.buffer_info()[0] self.SendScintilla(scintillacon.SCI_CALLTIPSHOW, pos, buff) def SCICallTipCancel(self): --- 201,205 ---- Index: view.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla/view.py,v retrieving revision 1.28.2.5 retrieving revision 1.28.2.6 diff -C2 -d -r1.28.2.5 -r1.28.2.6 *** view.py 27 Nov 2008 11:31:03 -0000 1.28.2.5 --- view.py 5 Jan 2009 12:51:26 -0000 1.28.2.6 *************** *** 387,396 **** def SaveTextFile(self, filename): doc = self.GetDocument() ! s = self.GetTextRange() ! # Save in binary mode so line endings are not translated. ! # Edit control uses '\r\n', and universal newlines mode replaces ALL '\r' with '\r\n'. ! f = open(filename, 'wb') ! f.write(s.encode('mbcs')) ! f.close() doc.SetModifiedFlag(0) return 1 --- 387,398 ---- def SaveTextFile(self, filename): doc = self.GetDocument() ! # Open in binary mode as scintilla itself ensures the ! # line endings are already appropriate, and our doc save ! # method handles encoding, BOMs, etc. ! f = open(filename, 'wb') ! try: ! doc._SaveTextToFile(self, f) ! finally: ! f.close() doc.SetModifiedFlag(0) return 1 *************** *** 652,657 **** hdcFormat = dc.GetHandleAttrib() fr = struct.pack(fmt, hdcRender, hdcFormat, rc[0], rc[1], rc[2], rc[3], rc[0], rc[1], rc[2], rc[3], pageStart, lengthDoc) - ## frBuff = array......array('b', fr) - ## addressFrBuff = frBuff.buffer_info()[0] nextPageStart = self.SendScintilla(EM_FORMATRANGE, draw, fr) return nextPageStart --- 654,657 ---- Index: bindings.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla/bindings.py,v retrieving revision 1.5.2.4 retrieving revision 1.5.2.5 diff -C2 -d -r1.5.2.4 -r1.5.2.5 *** bindings.py 11 Dec 2008 05:45:21 -0000 1.5.2.4 --- bindings.py 5 Jan 2009 12:51:26 -0000 1.5.2.5 *************** *** 148,155 **** rc = 1 except: - traceback.print_exc(chain=False) message = "Firing event '%s' failed." % event print(message) ! self.report_error(message) rc = 1 # Let any default handlers have a go! --- 148,154 ---- rc = 1 except: message = "Firing event '%s' failed." % event print(message) ! traceback.print_exc() self.report_error(message) rc = 1 # Let any default handlers have a go! Index: IDLEenvironment.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla/IDLEenvironment.py,v retrieving revision 1.11.2.3 retrieving revision 1.11.2.4 diff -C2 -d -r1.11.2.3 -r1.11.2.4 *** IDLEenvironment.py 27 Nov 2008 11:31:03 -0000 1.11.2.3 --- IDLEenvironment.py 5 Jan 2009 12:51:26 -0000 1.11.2.4 *************** *** 356,363 **** raise TextError("Empty range") self.edit.SetSel((pos, pos)) - self.edit.SCIAddText(text) - - """ - # IDLE only deals with "\n" - we will be nicer --- 356,359 ---- *************** *** 367,372 **** self.edit.SCINewline() self.edit.SCIAddText(bit) - """ - def delete(self, start, end=None): --- 363,366 ---- Index: document.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla/document.py,v retrieving revision 1.6.4.4 retrieving revision 1.6.4.5 diff -C2 -d -r1.6.4.4 -r1.6.4.5 *** document.py 8 Sep 2008 04:08:27 -0000 1.6.4.4 --- document.py 5 Jan 2009 12:51:26 -0000 1.6.4.5 *************** *** 1,13 **** import win32ui from pywin.mfc import docview ! from pywin import is_platform_unicode, default_platform_encoding, default_scintilla_encoding from . import scintillacon import win32con import string import os ParentScintillaDocument=docview.Document class CScintillaDocument(ParentScintillaDocument): "A SyntEdit document. " def DeleteContents(self): pass --- 1,24 ---- import win32ui from pywin.mfc import docview ! from pywin import default_scintilla_encoding from . import scintillacon import win32con import string import os + import codecs + + crlf_bytes = "\r\n".encode("ascii") + lf_bytes = "\n".encode("ascii") ParentScintillaDocument=docview.Document class CScintillaDocument(ParentScintillaDocument): "A SyntEdit document. " + def __init__(self, *args): + self.bom = None # the BOM, if any, read from the file. + # the encoding we detected from the source. Might have + # detected via the BOM or an encoding decl. + self.source_encoding = None + ParentScintillaDocument.__init__(self, *args) + def DeleteContents(self): pass *************** *** 15,24 **** def OnOpenDocument(self, filename): # init data members ! # print ("CScintillaDocument.OnOpenDocument", filename) self.SetPathName(filename) # Must set this early! try: ! f = open(filename, 'r') try: ! text = f.read() finally: f.close() --- 26,37 ---- def OnOpenDocument(self, filename): # init data members ! #print "Opening", filename self.SetPathName(filename) # Must set this early! try: ! # load the text as binary we can get smart ! # about detecting any existing EOL conventions. ! f = open(filename, 'rb') try: ! self._LoadTextFromFile(f) finally: f.close() *************** *** 27,31 **** return 0 - self._SetLoadedText(text) return 1 --- 40,43 ---- *************** *** 43,57 **** # File related functions # Helper to transfer text from the MFC document to the control. ! def _SetLoadedText(self, text): ! # In universal newlines mode, line endings read from file are translated to '\n', ! # but edit control expects CR/LF ('\r\n'). ! # Might be simpler to just tell scintilla to use '\n' ! # SendScintilla(scintillacon.SCI_SETEOLMODE, scintillacon.SC_EOL_LF) ! # and have eols automatically translated back when written to file ! if os.linesep != '\n': ! text=text.replace('\n', os.linesep) ! # Translate from unicode to UTF-8 bytes for Scintilla ! char_text = text.encode(default_scintilla_encoding) view = self.GetFirstView() --- 55,110 ---- # File related functions # Helper to transfer text from the MFC document to the control. ! def _LoadTextFromFile(self, f): ! # detect EOL mode - we don't support \r only - so find the ! # first '\n' and guess based on the char before. ! l = f.readline() ! # If line ends with \r\n or has no line ending, use CRLF. ! if l.endswith(crlf_bytes) or not l.endswith(lf_bytes): ! eol_mode = scintillacon.SC_EOL_CRLF ! else: ! eol_mode = scintillacon.SC_EOL_LF ! # Detect the encoding. ! # XXX - todo - support pep263 encoding declarations as well as ! # the BOM detection here (but note that unlike our BOM, the ! # encoding declaration could change between loading and saving ! # - particularly with a new file - so it also needs to be ! # implemented at save time.) ! for bom, encoding in ( ! (codecs.BOM_UTF8, "utf8"), ! (codecs.BOM_UTF16_LE, "utf_16_le"), ! (codecs.BOM_UTF16_BE, "utf_16_be"), ! ): ! if l.startswith(bom): ! self.bom = bom ! self.source_encoding = encoding ! l = l[len(bom):] # remove it. ! break ! ! # reading by lines would be too slow? Maybe we can use the ! # incremental encoders? For now just stick with loading the ! # entire file in memory. ! text = l + f.read() ! ! # Translate from source encoding to UTF-8 bytes for Scintilla ! source_encoding = self.source_encoding ! # This latin1 sucks until we get pep263 support; if we don't ! # know an encoding we just write as binary (maybe we should ! # try ascii to let the 'decoding failed' handling below to ! # provide a nice warning that the file is non-ascii) ! if source_encoding is None: ! source_encoding = 'latin1' ! # we could optimize this by avoiding utf8 to-ing and from-ing, ! # but then we would lose the ability to handle invalid utf8 ! # (and even then, the use of encoding aliases makes this tricky) ! # To create an invalid utf8 file: ! # >>> open(filename, "wb").write(codecs.BOM_UTF8+"bad \xa9har\r\n") ! try: ! dec = text.decode(source_encoding) ! except UnicodeError: ! print("WARNING: Failed to decode bytes from %r encoding - treating as latin1" % source_encoding) ! dec = text.decode('latin1') ! # and put it back as utf8 - this shouldn't fail. ! text = dec.encode(default_scintilla_encoding) view = self.GetFirstView() *************** *** 62,68 **** view.SetReadOnly(0) view.SendScintilla(scintillacon.SCI_CLEARALL) ! view.SendMessage(scintillacon.SCI_ADDTEXT, char_text) view.SendScintilla(scintillacon.SCI_SETUNDOCOLLECTION, 1, 0) view.SendScintilla(win32con.EM_EMPTYUNDOBUFFER, 0, 0) def FinalizeViewCreation(self, view): --- 115,135 ---- view.SetReadOnly(0) view.SendScintilla(scintillacon.SCI_CLEARALL) ! view.SendMessage(scintillacon.SCI_ADDTEXT, text) view.SendScintilla(scintillacon.SCI_SETUNDOCOLLECTION, 1, 0) view.SendScintilla(win32con.EM_EMPTYUNDOBUFFER, 0, 0) + # set EOL mode + view.SendScintilla(scintillacon.SCI_SETEOLMODE, eol_mode) + + def _SaveTextToFile(self, view, f): + s = view.GetTextRange() # already decoded from scintilla's encoding + if self.bom: + f.write(self.bom) + source_encoding = self.source_encoding + if source_encoding is None: + source_encoding = 'latin1' + + f.write(s.encode(source_encoding)) + self.SetModifiedFlag(0) + def FinalizeViewCreation(self, view): |
From: Mark H. <mha...@us...> - 2009-01-05 12:51:33
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4261/win32/src Modified Files: Tag: py3k .cvsignore Added Files: Tag: py3k win32popen.cpp Log Message: merge lots of changes (most via 2to3) from the trunk --- NEW FILE: win32popen.cpp --- #include "windows.h" // @doc #include "Python.h" // Not used in py3k #if (PY_VERSION_HEX < 0x03000000) #include "malloc.h" #include "io.h" #include "fcntl.h" #include "PyWinTypes.h" #define DllExport _declspec(dllexport) // These tell _PyPopen() wether to return 1, 2, or 3 file objects. #define POPEN_1 1 #define POPEN_2 2 #define POPEN_3 3 #define POPEN_4 4 static PyObject *_PyPopen(char *, int, int); static int _PyPclose(FILE *file); /* * Internal dictionary mapping popen* file pointers to process handles, * for use when retrieving the process exit code. See _PyPclose() below * for more information on this dictionary's use. */ static PyObject *_PyPopenProcs = NULL; // @pymethod pipe|win32pipe|popen|Popen that works from a GUI. // @rdesc The result of this function is a pipe (file) connected to the // processes stdin or stdout, depending on the requested mode. PyObject *PyPopen(PyObject *self, PyObject *args) { char *cmdstring; char *mode="r"; int bufsize=-1; PyObject *f,*s; int tm=0; if (!PyArg_ParseTuple(args, "s|s:popen", &cmdstring, // @pyparm string|cmdstring||The cmdstring to pass to the shell &mode)) // @pyparm string|mode||Either 'r' or 'w' return NULL; s = PyTuple_New(0); if (*mode == 'r') tm = _O_RDONLY; else if (*mode != 'w') { PyErr_SetString(PyExc_ValueError, "mode must be 'r' or 'w'"); return NULL; } else tm = _O_WRONLY; if (*(mode+1) == 't') f = _PyPopen(cmdstring, tm | _O_TEXT , POPEN_1); else if (*(mode+1) == 'b') f = _PyPopen(cmdstring, tm | _O_BINARY , POPEN_1); else f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); return f; } // @pymethod (pipe, pipe)|win32pipe|popen2|Variation on <om win32pipe.popen> // @rdesc The result of this function is a pipe (file) connected to the // processes stdin, and a pipe connected to the processes stdout. PyObject *PyPopen2(PyObject *self, PyObject *args) { char *cmdstring; char *mode="t"; PyObject *f; int tm=0; if (!PyArg_ParseTuple(args, "s|s:popen2", &cmdstring, // @pyparm string|cmdstring||The cmdstring to pass to the shell &mode)) // @pyparm string|mode||Either 't' or 'b' return NULL; if (*mode == 't') tm = _O_TEXT; else if (*mode != 'b') { PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); return NULL; } else tm = _O_BINARY; f = _PyPopen(cmdstring, tm , POPEN_2); return f; } // @pymethod (pipe, pipe, pipe)|win32pipe|popen3|Variation on <om win32pipe.popen> // @rdesc The result of this function is 3 pipes - the processes stdin, stdout and stderr PyObject *PyPopen3(PyObject *self, PyObject *args) { char *cmdstring; char *mode="t"; PyObject *f; int tm=0; if (!PyArg_ParseTuple(args, "s|s:Popen3", &cmdstring, // @pyparm string|cmdstring||The cmdstring to pass to the shell &mode)) // @pyparm string|mode||Either 't' or 'b' return NULL; if (*mode == 't') tm = _O_TEXT; else if (*mode != 'b') { PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); return NULL; } else tm = _O_BINARY; f = _PyPopen(cmdstring, tm , POPEN_3); return f; } // @pymethod (pipe, pipe)|win32pipe|popen4|Variation on <om win32pipe.popen> // @rdesc The result of this function is 2 pipes - the processes stdin, // and stdout+stderr combined as a single pipe. PyObject *PyPopen4(PyObject *self, PyObject *args) { char *cmdstring; char *mode="t"; PyObject *f; int tm=0; if (!PyArg_ParseTuple(args, "s|s:popen4", &cmdstring, // @pyparm string|cmdstring||The cmdstring to pass to the shell &mode)) // @pyparm string|mode||Either 't' or 'b' return NULL; if (*mode == 't') tm = _O_TEXT; else if (*mode != 'b') { PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); return NULL; } else tm = _O_BINARY; f = _PyPopen(cmdstring, tm , POPEN_4); return f; } static int _PyPopenCreateProcess(char *cmdstring, HANDLE hStdin, HANDLE hStdout, HANDLE hStderr, HANDLE *hProcess) { PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; char *s1,*s2, *s3=" /c "; const char *szConsoleSpawn = "win32popenWin9x.exe \""; DWORD i; size_t x; if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) { s1 = (char *)_alloca(i); if (!(x = GetEnvironmentVariable("COMSPEC", s1, i))) return FALSE; x = i + strlen(s3) + strlen(cmdstring) + 1; s2 = (char *)_alloca(x); ZeroMemory(s2, x); sprintf(s2, "%s%s%s", s1, s3, cmdstring); } // Could be an else here to try cmd.exe / command.com in the path // Now we'll just error out.. else return FALSE; ZeroMemory( &siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; siStartInfo.hStdInput = hStdin; siStartInfo.hStdOutput = hStdout; siStartInfo.hStdError = hStderr; siStartInfo.wShowWindow = SW_HIDE; if ( CreateProcess(NULL, s2, NULL, NULL, TRUE, 0, /* no new console so Ctrl+C kills child too */ NULL, NULL, &siStartInfo, &piProcInfo) ) { // Close the handles now so anyone waiting is woken. CloseHandle(piProcInfo.hThread); /* Return process handle */ *hProcess = piProcInfo.hProcess; return TRUE; } return FALSE; } // The following code is based off of KB: Q190351 static PyObject *_PyPopen(char *cmdstring, int mode, int n) { HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr, hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup, hChildStderrRdDup, hProcess; // hChildStdoutWrDup; SECURITY_ATTRIBUTES saAttr; BOOL fSuccess; int fd1, fd2, fd3; FILE *f1, *f2, *f3; long file_count; PyObject *f; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) return PyWin_SetAPIError("CreatePipe"); // Create new output read handle and the input write handle. Set // the inheritance properties to FALSE. Otherwise, the child inherits // the these handles; resulting in non-closeable handles to the pipes // being created. fSuccess = DuplicateHandle( GetCurrentProcess(), hChildStdinWr, GetCurrentProcess(), &hChildStdinWrDup, 0, FALSE, DUPLICATE_SAME_ACCESS); if (!fSuccess) return PyWin_SetAPIError("DuplicateHandle"); // Close the inheritable version of ChildStdin // that we're using. CloseHandle(hChildStdinWr); if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) return PyWin_SetAPIError("CreatePipe"); fSuccess = DuplicateHandle( GetCurrentProcess(), hChildStdoutRd, GetCurrentProcess(), &hChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS); if (!fSuccess) return PyWin_SetAPIError("DuplicateHandle"); // Close the inheritable version of ChildStdout // that we're using. CloseHandle(hChildStdoutRd); if (n != POPEN_4) { if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0)) return PyWin_SetAPIError("CreatePipe"); fSuccess = DuplicateHandle( GetCurrentProcess(), hChildStderrRd, GetCurrentProcess(), &hChildStderrRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS); if (!fSuccess) return PyWin_SetAPIError("DuplicateHandle"); // Close the inheritable version of ChildStdErr that we're using. CloseHandle(hChildStderrRd); } switch (n) { case POPEN_1: switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) { case _O_WRONLY | _O_TEXT: // Case for writing to child Stdin in text mode. fd1 = _open_osfhandle((INT_PTR)hChildStdinWrDup, mode); f1 = _fdopen(fd1, "w"); f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose); PyFile_SetBufSize(f, 0); // We don't care about these pipes anymore, so close them. CloseHandle(hChildStdoutRdDup); CloseHandle(hChildStderrRdDup); break; case _O_RDONLY | _O_TEXT: // Case for reading from child Stdout in text mode. fd1 = _open_osfhandle((INT_PTR)hChildStdoutRdDup, mode); f1 = _fdopen(fd1, "r"); f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose); PyFile_SetBufSize(f, 0); // We don't care about these pipes anymore, so close them. CloseHandle(hChildStdinWrDup); CloseHandle(hChildStderrRdDup); break; case _O_RDONLY | _O_BINARY: // Case for readinig from child Stdout in binary mode. fd1 = _open_osfhandle((INT_PTR)hChildStdoutRdDup, mode); f1 = _fdopen(fd1, "rb"); f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose); PyFile_SetBufSize(f, 0); // We don't care about these pipes anymore, so close them. CloseHandle(hChildStdinWrDup); CloseHandle(hChildStderrRdDup); break; case _O_WRONLY | _O_BINARY: // Case for writing to child Stdin in binary mode. fd1 = _open_osfhandle((INT_PTR)hChildStdinWrDup, mode); f1 = _fdopen(fd1, "wb"); f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose); PyFile_SetBufSize(f, 0); // We don't care about these pipes anymore, so close them. CloseHandle(hChildStdoutRdDup); CloseHandle(hChildStderrRdDup); break; } file_count = 1; break; case POPEN_2: case POPEN_4: { char *m1, *m2; PyObject *p1, *p2; if (mode & _O_TEXT) { m1="r"; m2="w"; } else { m1="rb"; m2="wb"; } fd1 = _open_osfhandle((INT_PTR)hChildStdinWrDup, mode); f1 = _fdopen(fd1, m2); fd2 = _open_osfhandle((INT_PTR)hChildStdoutRdDup, mode); f2 = _fdopen(fd2, m1); p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); PyFile_SetBufSize(p1, 0); p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); PyFile_SetBufSize(p2, 0); if (n != 4) CloseHandle(hChildStderrRdDup); f = Py_BuildValue("OO",p1,p2); Py_XDECREF(p1); Py_XDECREF(p2); file_count = 2; break; } case POPEN_3: { char *m1, *m2; PyObject *p1, *p2, *p3; if (mode & _O_TEXT) { m1="r"; m2="w"; } else { m1="rb"; m2="wb"; } fd1 = _open_osfhandle((INT_PTR)hChildStdinWrDup, mode); f1 = _fdopen(fd1, m2); fd2 = _open_osfhandle((INT_PTR)hChildStdoutRdDup, mode); f2 = _fdopen(fd2, m1); fd3 = _open_osfhandle((INT_PTR)hChildStderrRdDup, mode); f3 = _fdopen(fd3, m1); p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose); PyFile_SetBufSize(p1, 0); PyFile_SetBufSize(p2, 0); PyFile_SetBufSize(p3, 0); f = Py_BuildValue("OOO",p1,p2,p3); Py_XDECREF(p1); Py_XDECREF(p2); Py_XDECREF(p3); file_count = 3; break; } } if (n == POPEN_4) { if (!_PyPopenCreateProcess(cmdstring, hChildStdinRd, hChildStdoutWr, hChildStdoutWr, &hProcess)) return PyWin_SetAPIError("CreateProcess"); } else { if (!_PyPopenCreateProcess(cmdstring, hChildStdinRd, hChildStdoutWr, hChildStderrWr, &hProcess)) return PyWin_SetAPIError("CreateProcess"); } /* * Insert the files we've created into the process dictionary * all referencing the list with the process handle and the * initial number of files (see description below in _PyPclose). * Since if _PyPclose later tried to wait on a process when all * handles weren't closed, it could create a deadlock with the * child, we spend some energy here to try to ensure that we * either insert all file handles into the dictionary or none * at all. It's a little clumsy with the various popen modes * and variable number of files involved. */ if (!_PyPopenProcs) { _PyPopenProcs = PyDict_New(); } if (_PyPopenProcs) { PyObject *procObj, *hProcessObj, *intObj, *fileObj[3]; int ins_rc[3]; fileObj[0] = fileObj[1] = fileObj[2] = NULL; ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; procObj = PyList_New(2); hProcessObj = PyLong_FromVoidPtr(hProcess); intObj = PyInt_FromLong(file_count); if (procObj && hProcessObj && intObj) { PyList_SetItem(procObj,0,hProcessObj); PyList_SetItem(procObj,1,intObj); fileObj[0] = PyLong_FromVoidPtr(f1); if (fileObj[0]) { ins_rc[0] = PyDict_SetItem(_PyPopenProcs, fileObj[0], procObj); } if (file_count >= 2) { fileObj[1] = PyLong_FromVoidPtr(f2); if (fileObj[1]) { ins_rc[1] = PyDict_SetItem(_PyPopenProcs, fileObj[1], procObj); } } if (file_count >= 3) { fileObj[2] = PyLong_FromVoidPtr(f3); if (fileObj[2]) { ins_rc[2] = PyDict_SetItem(_PyPopenProcs, fileObj[2], procObj); } } if (ins_rc[0] < 0 || !fileObj[0] || ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) { /* Something failed - remove any dictionary * entries that did make it. */ if (!ins_rc[0] && fileObj[0]) { PyDict_DelItem(_PyPopenProcs, fileObj[0]); } if (!ins_rc[1] && fileObj[1]) { PyDict_DelItem(_PyPopenProcs, fileObj[1]); } if (!ins_rc[2] && fileObj[2]) { PyDict_DelItem(_PyPopenProcs, fileObj[2]); } } } /* * Clean up our localized references for the dictionary keys * and value since PyDict_SetItem will Py_INCREF any copies * that got placed in the dictionary. */ Py_XDECREF(procObj); Py_XDECREF(fileObj[0]); Py_XDECREF(fileObj[1]); Py_XDECREF(fileObj[2]); } // Child is launched. Close the parents copy of those pipe handles // that only the child should have open. // You need to make sure that no handles to the write end of the // output pipe are maintained in this process or else the pipe will // not close when the child process exits and the ReadFile will hang. if (!CloseHandle(hChildStdinRd)) return PyWin_SetAPIError("CloseHandle"); if (!CloseHandle(hChildStdoutWr)) return PyWin_SetAPIError("CloseHandle"); if ((n != 4) && (!CloseHandle(hChildStderrWr))) return PyWin_SetAPIError("CloseHandle"); return f; } /* * Wrapper for fclose() to use for popen* files, so we can retrieve the * exit code for the child process and return as a result of the close. * * This function uses the _PyPopenProcs dictionary in order to map the * input file pointer to information about the process that was * originally created by the popen* call that created the file pointer. * The dictionary uses the file pointer as a key (with one entry * inserted for each file returned by the original popen* call) and a * single list object as the value for all files from a single call. * The list object contains the Win32 process handle at [0], and a file * count at [1], which is initialized to the total number of file * handles using that list. * * This function closes whichever handle it is passed, and decrements * the file count in the dictionary for the process handle pointed to * by this file. On the last close (when the file count reaches zero), * this function will wait for the child process and then return its * exit code as the result of the close() operation. This permits the * files to be closed in any order - it is always the close() of the * final handle that will return the exit code. */ static int _PyPclose(FILE *file) { int result; DWORD exit_code; HANDLE hProcess; PyObject *procObj, *hProcessObj, *intObj, *fileObj; long file_count; /* Close the file handle first, to ensure it can't block the * child from exiting if it's the last handle. */ result = fclose(file); if (_PyPopenProcs) { CEnterLeavePython _celp; if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && (procObj = PyDict_GetItem(_PyPopenProcs, fileObj)) != NULL && (hProcessObj = PyList_GetItem(procObj,0)) != NULL && (intObj = PyList_GetItem(procObj,1)) != NULL) { hProcess = PyLong_AsVoidPtr(hProcessObj); file_count = PyInt_AsLong(intObj); if (file_count > 1) { /* Still other files referencing process */ file_count--; PyList_SetItem(procObj,1, PyInt_FromLong(file_count)); } else { Py_BEGIN_ALLOW_THREADS /* Last file for this process */ if (result != EOF && WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED && GetExitCodeProcess(hProcess, &exit_code)) { /* Possible truncation here in 16-bit environments, but * real exit codes are just the lower byte in any event. */ result = exit_code; } else { /* Indicate failure - this will cause the file object * to raise an I/O error and translate the last Win32 * error code from errno. We do have a problem with * last errors that overlap the normal errno table, * but that's a consistent problem with the file object. */ if (result != EOF) { /* If the error wasn't from the fclose(), then * set errno for the file object error handling. */ errno = GetLastError(); } result = -1; } /* Free up the native handle at this point */ CloseHandle(hProcess); Py_END_ALLOW_THREADS } /* Remove this file pointer from dictionary */ PyDict_DelItem(_PyPopenProcs, fileObj); if (PyDict_Size(_PyPopenProcs) == 0) { Py_DECREF(_PyPopenProcs); _PyPopenProcs = NULL; } } /* if object retrieval ok */ Py_XDECREF(fileObj); } /* if _PyPopenProcs */ return result; } #endif // PY_VERSION_HEX < 0x03000000 Index: .cvsignore =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/.cvsignore,v retrieving revision 1.6 retrieving revision 1.6.4.1 diff -C2 -d -r1.6 -r1.6.4.1 *** .cvsignore 22 Feb 2006 08:06:09 -0000 1.6 --- .cvsignore 5 Jan 2009 12:51:27 -0000 1.6.4.1 *************** *** 1,18 **** PythonServiceMessages.h *_wrap.doc - win32cryptmodule.cpp - win32eventmodule_win*.cpp win32evtlog_messages.h - win32evtlogmodule.cpp - win32filemodule_win*.cpp - win32guimodule_win*.cpp - win32jobmodule.cpp - win32pipemodule.cpp - win32processmodule_win*.cpp - win32securitymodule.cpp win32service_messages.h ! win32servicemodule.cpp ! wincerapimodule.cpp ! win32inetmodule.cpp ! winxpguimodule.cpp ! _winxpthememodule.cpp --- 1,6 ---- PythonServiceMessages.h *_wrap.doc win32evtlog_messages.h win32service_messages.h ! *_py2_swig.cpp ! *_py3_swig.cpp |
From: Mark H. <mha...@us...> - 2009-01-05 12:51:33
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv4261/win32/Lib Modified Files: Tag: py3k regutil.py Log Message: merge lots of changes (most via 2to3) from the trunk Index: regutil.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/regutil.py,v retrieving revision 1.3.4.3 retrieving revision 1.3.4.4 diff -C2 -d -r1.3.4.3 -r1.3.4.4 *** regutil.py 27 Nov 2008 11:31:05 -0000 1.3.4.3 --- regutil.py 5 Jan 2009 12:51:27 -0000 1.3.4.4 *************** *** 31,44 **** """A helper to set the default value for a key in the registry """ - import types if rootkey is None: rootkey = GetRootKey() ! if isinstance(value, str): typeId = win32con.REG_SZ ! elif isinstance(value, bytes): ! typeId = win32con.REG_BINARY ! elif isinstance(value, int): typeId = win32con.REG_DWORD else: ! raise TypeError("Value must be string or integer - was passed " + str(value)) win32api.RegSetValue(rootkey, subKey, typeId ,value) --- 31,41 ---- """A helper to set the default value for a key in the registry """ if rootkey is None: rootkey = GetRootKey() ! if type(value)==str: typeId = win32con.REG_SZ ! elif type(value)==int: typeId = win32con.REG_DWORD else: ! raise TypeError("Value must be string or integer - was passed " + repr(value)) win32api.RegSetValue(rootkey, subKey, typeId ,value) |