From 800868a19f8001c4fdb496e65aeb99ce209479a3 Mon Sep 17 00:00:00 2001 From: Avasam Date: Tue, 28 May 2024 17:21:23 -0400 Subject: [PATCH] Use `assert`/`AssertionError` in tests (#2268) --- com/win32com/test/errorSemantics.py | 178 ++++++------- com/win32com/test/pippo_server.py | 3 +- com/win32com/test/policySemantics.py | 19 +- com/win32com/test/testAccess.py | 14 +- com/win32com/test/testCollections.py | 68 +++-- com/win32com/test/testDictionary.py | 24 +- com/win32com/test/testDynamic.py | 19 +- com/win32com/test/testExplorer.py | 6 +- com/win32com/test/testGIT.py | 12 +- com/win32com/test/testMSOffice.py | 35 ++- com/win32com/test/testNetscape.py | 5 +- com/win32com/test/testPyComTest.py | 167 ++++++------- com/win32com/test/testall.py | 2 +- com/win32com/test/testmakepy.py | 2 +- com/win32com/test/testvb.py | 262 ++++++++++---------- com/win32comext/directsound/test/ds_test.py | 12 +- isapi/test/extension_simple.py | 10 +- win32/test/test_sspi.py | 4 +- win32/test/test_win32api.py | 2 +- win32/test/test_win32crypt.py | 2 +- win32/test/test_win32file.py | 4 +- win32/test/test_win32trace.py | 2 +- win32/test/testall.py | 9 +- 23 files changed, 397 insertions(+), 464 deletions(-) diff --git a/com/win32com/test/errorSemantics.py b/com/win32com/test/errorSemantics.py index ddeddc93a..843395c41 100644 --- a/com/win32com/test/errorSemantics.py +++ b/com/win32com/test/errorSemantics.py @@ -19,11 +19,6 @@ from win32com.test.util import CaptureWriter -class error(Exception): - def __init__(self, msg, com_exception=None): - Exception.__init__(self, msg, str(com_exception)) - - # Our COM server. class TestServer: _public_methods_ = ["Clone", "Commit", "LockRegion", "Read"] @@ -56,23 +51,21 @@ def test(): com_server = wrap(TestServer(), pythoncom.IID_IStream) try: com_server.Clone() - raise error("Expecting this call to fail!") + raise AssertionError("Expecting this call to fail!") except pythoncom.com_error as com_exc: - if com_exc.hresult != winerror.E_UNEXPECTED: - raise error( - "Calling the object natively did not yield the correct scode", com_exc - ) + assert com_exc.hresult == winerror.E_UNEXPECTED, ( + "Calling the object natively did not yield the correct scode", + str(com_exc), + ) exc = com_exc.excepinfo - if not exc or exc[-1] != winerror.E_UNEXPECTED: - raise error( - "The scode element of the exception tuple did not yield the correct scode", - com_exc, - ) - if exc[2] != "Not today": - raise error( - "The description in the exception tuple did not yield the correct string", - com_exc, - ) + assert exc and exc[-1] == winerror.E_UNEXPECTED, ( + "The scode element of the exception tuple did not yield the correct scode", + str(com_exc), + ) + assert exc[2] == "Not today", ( + "The description in the exception tuple did not yield the correct string", + str(com_exc), + ) cap = CaptureWriter() try: cap.capture() @@ -80,41 +73,40 @@ def test(): com_server.Commit(0) finally: cap.release() - raise error("Expecting this call to fail!") + raise AssertionError("Expecting this call to fail!") except pythoncom.com_error as com_exc: - if com_exc.hresult != winerror.E_FAIL: - raise error("The hresult was not E_FAIL for an internal error", com_exc) - if com_exc.excepinfo[1] != "Python COM Server Internal Error": - raise error( - "The description in the exception tuple did not yield the correct string", - com_exc, - ) + assert com_exc.hresult == winerror.E_FAIL, ( + "The hresult was not E_FAIL for an internal error", + str(com_exc), + ) + assert com_exc.excepinfo[1] == "Python COM Server Internal Error", ( + "The description in the exception tuple did not yield the correct string", + str(com_exc), + ) # Check we saw a traceback in stderr - if cap.get_captured().find("Traceback") < 0: - raise error(f"Could not find a traceback in stderr: {cap.get_captured()!r}") + assert ( + cap.get_captured().find("Traceback") >= 0 + ), f"Could not find a traceback in stderr: {cap.get_captured()!r}" # Now do it all again, but using IDispatch com_server = Dispatch(wrap(TestServer())) try: com_server.Clone() - raise error("Expecting this call to fail!") + raise AssertionError("Expecting this call to fail!") except pythoncom.com_error as com_exc: - if com_exc.hresult != winerror.DISP_E_EXCEPTION: - raise error( - "Calling the object via IDispatch did not yield the correct scode", - com_exc, - ) + assert com_exc.hresult == winerror.DISP_E_EXCEPTION, ( + "Calling the object via IDispatch did not yield the correct scode", + str(com_exc), + ) exc = com_exc.excepinfo - if not exc or exc[-1] != winerror.E_UNEXPECTED: - raise error( - "The scode element of the exception tuple did not yield the correct scode", - com_exc, - ) - if exc[2] != "Not today": - raise error( - "The description in the exception tuple did not yield the correct string", - com_exc, - ) + assert exc and exc[-1] == winerror.E_UNEXPECTED, ( + "The scode element of the exception tuple did not yield the correct scode", + str(com_exc), + ) + assert exc[2] == "Not today", ( + "The description in the exception tuple did not yield the correct string", + str(com_exc), + ) cap.clear() try: @@ -123,27 +115,25 @@ def test(): com_server.Commit(0) finally: cap.release() - raise error("Expecting this call to fail!") + raise AssertionError("Expecting this call to fail!") except pythoncom.com_error as com_exc: - if com_exc.hresult != winerror.DISP_E_EXCEPTION: - raise error( - "Calling the object via IDispatch did not yield the correct scode", - com_exc, - ) + assert com_exc.hresult == winerror.DISP_E_EXCEPTION, ( + "Calling the object via IDispatch did not yield the correct scode", + str(com_exc), + ) exc = com_exc.excepinfo - if not exc or exc[-1] != winerror.E_FAIL: - raise error( - "The scode element of the exception tuple did not yield the correct scode", - com_exc, - ) - if exc[1] != "Python COM Server Internal Error": - raise error( - "The description in the exception tuple did not yield the correct string", - com_exc, - ) + assert exc and exc[-1] == winerror.E_FAIL, ( + "The scode element of the exception tuple did not yield the correct scode", + str(com_exc), + ) + assert exc[1] == "Python COM Server Internal Error", ( + "The description in the exception tuple did not yield the correct string", + str(com_exc), + ) # Check we saw a traceback in stderr - if cap.get_captured().find("Traceback") < 0: - raise error(f"Could not find a traceback in stderr: {cap.get_captured()!r}") + assert ( + cap.get_captured().find("Traceback") >= 0 + ), f"Could not find a traceback in stderr: {cap.get_captured()!r}" # And an explicit com_error cap.clear() @@ -153,39 +143,33 @@ def test(): com_server.Commit(1) finally: cap.release() - raise error("Expecting this call to fail!") + raise AssertionError("Expecting this call to fail!") except pythoncom.com_error as com_exc: - if com_exc.hresult != winerror.DISP_E_EXCEPTION: - raise error( - "Calling the object via IDispatch did not yield the correct scode", - com_exc, - ) + assert com_exc.hresult == winerror.DISP_E_EXCEPTION, ( + "Calling the object via IDispatch did not yield the correct scode", + str(com_exc), + ) exc = com_exc.excepinfo - if not exc or exc[-1] != winerror.E_FAIL: - raise error( - "The scode element of the exception tuple did not yield the correct scode", - com_exc, - ) - if exc[1] != "source": - raise error( - "The source in the exception tuple did not yield the correct string", - com_exc, - ) - if exc[2] != "\U0001F600": - raise error( - "The description in the exception tuple did not yield the correct string", - com_exc, - ) - if exc[3] != "helpfile": - raise error( - "The helpfile in the exception tuple did not yield the correct string", - com_exc, - ) - if exc[4] != 1: - raise error( - "The help context in the exception tuple did not yield the correct string", - com_exc, - ) + assert exc and exc[-1] == winerror.E_FAIL, ( + "The scode element of the exception tuple did not yield the correct scode", + str(com_exc), + ) + assert exc[1] == "source", ( + "The source in the exception tuple did not yield the correct string", + str(com_exc), + ) + assert exc[2] == "\U0001F600", ( + "The description in the exception tuple did not yield the correct string", + str(com_exc), + ) + assert exc[3] == "helpfile", ( + "The helpfile in the exception tuple did not yield the correct string", + str(com_exc), + ) + assert exc[4] == 1, ( + "The help context in the exception tuple did not yield the correct string", + str(com_exc), + ) try: @@ -225,7 +209,7 @@ def testLogger(): com_server = wrap(TestServer(), pythoncom.IID_IStream) try: com_server.Commit(0) - raise RuntimeError("should have failed") + raise AssertionError("should have failed") except pythoncom.error as exc: # `excepinfo` is a tuple with elt 2 being the traceback we captured. message = exc.excepinfo[2] @@ -240,7 +224,7 @@ def testLogger(): com_server = Dispatch(wrap(TestServer())) try: com_server.Commit(0) - raise RuntimeError("should have failed") + raise AssertionError("should have failed") except pythoncom.error as exc: # `excepinfo` is a tuple with elt 2 being the traceback we captured. message = exc.excepinfo[2] diff --git a/com/win32com/test/pippo_server.py b/com/win32com/test/pippo_server.py index ac3a00c78..c5ae2df40 100644 --- a/com/win32com/test/pippo_server.py +++ b/com/win32com/test/pippo_server.py @@ -52,8 +52,7 @@ def BuildTypelib(): if newer(idl, tlb): print(f"Compiling {idl}") rc = os.system(f'midl "{idl}"') - if rc: - raise RuntimeError("Compiling MIDL failed!") + assert not rc, "Compiling MIDL failed!" # Can't work out how to prevent MIDL from generating the stubs. # just nuke them for fname in "dlldata.c pippo_i.c pippo_p.c pippo.h".split(): diff --git a/com/win32com/test/policySemantics.py b/com/win32com/test/policySemantics.py index 746522f72..009c25e3f 100644 --- a/com/win32com/test/policySemantics.py +++ b/com/win32com/test/policySemantics.py @@ -7,10 +7,6 @@ import winerror -class Error(Exception): - pass - - # An object representing a list of numbers class PythonSemanticClass: _public_methods_ = ["In"] # DISPIDs are allocated. @@ -62,8 +58,13 @@ def DispExTest(ob): assert hr == winerror.S_FALSE, "Bad result at end of enum" break dispids.sort() - if dispids != [pythoncom.DISPID_EVALUATE, pythoncom.DISPID_NEWENUM, 10, 11, 1000]: - raise Error("Got back the wrong dispids: %s" % dispids) + assert dispids == [ + pythoncom.DISPID_EVALUATE, + pythoncom.DISPID_NEWENUM, + 10, + 11, + 1000, + ], f"Got back the wrong dispids: {dispids}" def SemanticTest(ob): @@ -72,8 +73,7 @@ def SemanticTest(ob): ob.Add(2) ob.Add(3) # invoke _value_ - if ob() != (1, 2, 3): - raise Error("Bad result - got %s" % (repr(ob()))) + assert ob() == (1, 2, 3), f"Bad result - got {ob()!r}" dispob = ob._oleobj_ @@ -83,8 +83,7 @@ def SemanticTest(ob): pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, 1, ) - if rc != 6: - raise Error("Evaluate returned %d" % rc) + assert rc == 6, f"Evaluate returned {rc}" class Tester(win32com.test.util.TestCase): diff --git a/com/win32com/test/testAccess.py b/com/win32com/test/testAccess.py index 50332db02..0428667ac 100644 --- a/com/win32com/test/testAccess.py +++ b/com/win32com/test/testAccess.py @@ -95,15 +95,15 @@ def CreateTestAccessDatabase(dbname=None): # Reset the bookmark to the one we saved. # But first check the test is actually doing something! tab1.MoveLast() - if tab1.Fields("First Name").Value != "Second": - raise RuntimeError("Unexpected record is last - makes bookmark test pointless!") + assert ( + tab1.Fields("First Name").Value == "Second" + ), "Unexpected record is last - makes bookmark test pointless!" tab1.Bookmark = bk - if tab1.Bookmark != bk: - raise RuntimeError("The bookmark data is not the same") - - if tab1.Fields("First Name").Value != "Mark": - raise RuntimeError("The bookmark did not reset the record pointer correctly") + assert tab1.Bookmark == bk, "The bookmark data is not the same" + assert ( + tab1.Fields("First Name").Value == "Mark" + ), "The bookmark did not reset the record pointer correctly" return dbname diff --git a/com/win32com/test/testCollections.py b/com/win32com/test/testCollections.py index 10bfce775..8c992d610 100644 --- a/com/win32com/test/testCollections.py +++ b/com/win32com/test/testCollections.py @@ -13,8 +13,6 @@ import win32com.test.util import winerror -error = "collection test error" - def MakeEmptyEnum(): # create the Python enumerator object as a real COM object @@ -34,36 +32,26 @@ def MakeTestEnum(): def TestEnumAgainst(o, check): for i in range(len(check)): - if o(i) != check[i]: - raise error( - "Using default method gave the incorrect value - {}/{}".format( - repr(o(i)), repr(check[i]) - ) - ) + assert ( + o(i) == check[i] + ), f"Using default method gave the incorrect value - {o(i)!r}/{check[i]!r}" for i in range(len(check)): - if o.Item(i) != check[i]: - raise error( - "Using Item method gave the incorrect value - {}/{}".format( - repr(o(i)), repr(check[i]) - ) - ) + assert ( + o.Item(i) == check[i] + ), f"Using Item method gave the incorrect value - {o(i)!r}/{check[i]!r}" # First try looping. cmp = [] for s in o: cmp.append(s) - if cmp[: len(check)] != check: - raise error( - "Result after looping isnt correct - {}/{}".format( - repr(cmp[: len(check)]), repr(check) - ) - ) + assert ( + cmp[: len(check)] == check + ), f"Result after looping isn't correct - {cmp[: len(check)]!r}/{check!r}" for i in range(len(check)): - if o[i] != check[i]: - raise error("Using indexing gave the incorrect value") + assert o[i] == check[i], "Using indexing gave the incorrect value" def TestEnum(quiet=None): @@ -109,51 +97,57 @@ def TestEnum(quiet=None): try: o() - raise error("default method with no args worked when it shouldnt have!") + raise AssertionError( + "default method with no args worked when it shouldn't have!" + ) except pythoncom.com_error as exc: - if exc.hresult != winerror.DISP_E_BADPARAMCOUNT: - raise error(f"Expected DISP_E_BADPARAMCOUNT - got {exc}") + assert ( + exc.hresult == winerror.DISP_E_BADPARAMCOUNT + ), f"Expected DISP_E_BADPARAMCOUNT - got {exc}" try: o.Insert("foo", 2) - raise error("Insert worked when it shouldnt have!") + raise AssertionError("Insert worked when it shouldn't have!") except pythoncom.com_error as exc: - if exc.hresult != winerror.DISP_E_TYPEMISMATCH: - raise error(f"Expected DISP_E_TYPEMISMATCH - got {exc}") + assert ( + exc.hresult == winerror.DISP_E_TYPEMISMATCH + ), f"Expected DISP_E_TYPEMISMATCH - got {exc}" # Remove the sublist for this test! try: o.Remove(o.Count()) - raise error("Remove worked when it shouldnt have!") + raise AssertionError("Remove worked when it shouldn't have!") except pythoncom.com_error as exc: - if exc.hresult != winerror.DISP_E_BADINDEX: - raise error(f"Expected DISP_E_BADINDEX - got {exc}") + assert ( + exc.hresult == winerror.DISP_E_BADINDEX + ), f"Expected DISP_E_BADINDEX - got {exc}" # Test an empty collection if not quiet: print("Empty collection test") o = MakeEmptyEnum() for item in o: - raise error("Empty list performed an iteration") + raise AssertionError("Empty list performed an iteration") try: ob = o[1] - raise error("Empty list could be indexed") + raise AssertionError("Empty list could be indexed") except IndexError: pass try: ob = o[0] - raise error("Empty list could be indexed") + raise AssertionError("Empty list could be indexed") except IndexError: pass try: ob = o(0) - raise error("Empty list could be indexed") + raise AssertionError("Empty list could be indexed") except pythoncom.com_error as exc: - if exc.hresult != winerror.DISP_E_BADINDEX: - raise error(f"Expected DISP_E_BADINDEX - got {exc}") + assert ( + exc.hresult == winerror.DISP_E_BADINDEX + ), f"Expected DISP_E_BADINDEX - got {exc}" class TestCase(win32com.test.util.TestCase): diff --git a/com/win32com/test/testDictionary.py b/com/win32com/test/testDictionary.py index c191dc4aa..dfcbb98d4 100644 --- a/com/win32com/test/testDictionary.py +++ b/com/win32com/test/testDictionary.py @@ -18,12 +18,9 @@ def MakeTestDictionary(): def TestDictAgainst(dict, check): for key, value in list(check.items()): - if dict(key) != value: - raise Exception( - "Indexing for '{}' gave the incorrect value - {}/{}".format( - repr(key), repr(dict[key]), repr(check[key]) - ) - ) + assert ( + dict(key) == value + ), f"Indexing for '{key!r}' gave the incorrect value - {dict[key]!r}/{check[key]!r}" # Ensure we have the correct version registered. @@ -68,24 +65,27 @@ def TestDict(quiet=None): raise Exception("default method with no args worked when it shouldnt have!") except pythoncom.com_error as xxx_todo_changeme: (hr, desc, exc, argErr) = xxx_todo_changeme.args - if hr != winerror.DISP_E_BADPARAMCOUNT: - raise Exception("Expected DISP_E_BADPARAMCOUNT - got %d (%s)" % (hr, desc)) + assert ( + hr == winerror.DISP_E_BADPARAMCOUNT + ), f"Expected DISP_E_BADPARAMCOUNT - got {hr} ({desc})" try: dict("hi", "there") raise Exception("multiple args worked when it shouldnt have!") except pythoncom.com_error as xxx_todo_changeme1: (hr, desc, exc, argErr) = xxx_todo_changeme1.args - if hr != winerror.DISP_E_BADPARAMCOUNT: - raise Exception("Expected DISP_E_BADPARAMCOUNT - got %d (%s)" % (hr, desc)) + assert ( + hr == winerror.DISP_E_BADPARAMCOUNT + ), f"Expected DISP_E_BADPARAMCOUNT - got {hr} ({desc})" try: dict(0) raise Exception("int key worked when it shouldnt have!") except pythoncom.com_error as xxx_todo_changeme2: (hr, desc, exc, argErr) = xxx_todo_changeme2.args - if hr != winerror.DISP_E_TYPEMISMATCH: - raise Exception("Expected DISP_E_TYPEMISMATCH - got %d (%s)" % (hr, desc)) + assert ( + hr == winerror.DISP_E_TYPEMISMATCH + ), f"Expected DISP_E_TYPEMISMATCH - got {hr} ({desc})" if not quiet: print("Python.Dictionary tests complete.") diff --git a/com/win32com/test/testDynamic.py b/com/win32com/test/testDynamic.py index 0d073c4a8..75765fb87 100644 --- a/com/win32com/test/testDynamic.py +++ b/com/win32com/test/testDynamic.py @@ -4,8 +4,6 @@ import winerror from win32com.server.exception import COMException -error = "testDynamic error" - iid = pythoncom.MakeIID("{b48969a0-784b-11d0-ae71-d23f56000000}") @@ -61,23 +59,20 @@ def Test(): client = win32com.client.dynamic.Dispatch(iid) client.ANewAttr = "Hello" - if client.ANewAttr != "Hello": - raise error("Could not set dynamic property") + assert client.ANewAttr == "Hello", "Could not set dynamic property" v = ["Hello", "From", "Python", 1.4] client.TestSequence = v - if v != list(client.TestSequence): - raise error( - "Dynamic sequences not working! {!r}/{!r}".format( - repr(v), repr(client.testSequence) - ) - ) + assert v == list( + client.TestSequence + ), "Dynamic sequences not working! {!r}/{!r}".format( + repr(v), repr(client.testSequence) + ) client.write("This", "output", "has", "come", "via", "testDynamic.py") # Check our new "_FlagAsMethod" works (kinda!) client._FlagAsMethod("NotReallyAMethod") - if not callable(client.NotReallyAMethod): - raise error("Method I flagged as callable isn't!") + assert callable(client.NotReallyAMethod), "Method I flagged as callable isn't!" client = None finally: diff --git a/com/win32com/test/testExplorer.py b/com/win32com/test/testExplorer.py index 369d4358f..8ac8e44d6 100644 --- a/com/win32com/test/testExplorer.py +++ b/com/win32com/test/testExplorer.py @@ -42,8 +42,7 @@ def TestExplorerEvents(): return iexplore.Visible = 1 - if not bVisibleEventFired: - raise RuntimeError("The IE event did not appear to fire!") + assert bVisibleEventFired, "The IE event did not appear to fire!" iexplore.Quit() iexplore = None @@ -51,8 +50,7 @@ def TestExplorerEvents(): ie = win32com.client.Dispatch("InternetExplorer.Application") ie_events = win32com.client.DispatchWithEvents(ie, ExplorerEvents) ie.Visible = 1 - if not bVisibleEventFired: - raise RuntimeError("The IE event did not appear to fire!") + assert bVisibleEventFired, "The IE event did not appear to fire!" ie.Quit() ie = None print("IE Event tests worked.") diff --git a/com/win32com/test/testGIT.py b/com/win32com/test/testGIT.py index 011a11a98..f5228a6b2 100644 --- a/com/win32com/test/testGIT.py +++ b/com/win32com/test/testGIT.py @@ -30,18 +30,16 @@ def TestInterp(interp): - if interp.Eval("1+1") != 2: - raise ValueError("The interpreter returned the wrong result.") + assert interp.Eval("1+1") == 2, "The interpreter returned the wrong result." try: interp.Eval(1 + 1) - raise ValueError("The interpreter did not raise an exception") + raise AssertionError("The interpreter did not raise an exception") except pythoncom.com_error as details: import winerror - if details[0] != winerror.DISP_E_TYPEMISMATCH: - raise ValueError( - "The interpreter exception was not winerror.DISP_E_TYPEMISMATCH." - ) + assert ( + details[0] == winerror.DISP_E_TYPEMISMATCH + ), "The interpreter exception was not winerror.DISP_E_TYPEMISMATCH." def TestInterpInThread(stopEvent, cookie): diff --git a/com/win32com/test/testMSOffice.py b/com/win32com/test/testMSOffice.py index 8b3e0df9e..b65a964b0 100644 --- a/com/win32com/test/testMSOffice.py +++ b/com/win32com/test/testMSOffice.py @@ -14,8 +14,6 @@ from win32com.client import gencache from win32com.test.util import CheckClean -error = "MSOffice test error" - # Test a few of the MSOffice components. def TestWord(): @@ -105,11 +103,9 @@ def TestWord8OldStyle(): def TextExcel(xl): xl.Visible = 0 - if xl.Visible: - raise error("Visible property is true.") + assert not xl.Visible, "Visible property is true." xl.Visible = 1 - if not xl.Visible: - raise error("Visible property not true.") + assert xl.Visible, "Visible property not true." if int(xl.Version.split(".")[0]) >= 8: xl.Workbooks.Add() @@ -123,30 +119,27 @@ def TextExcel(xl): for i in range(20): xl.Cells(i + 1, i + 1).Value = "Hi %d" % i - if xl.Range("A1").Value != "Hi 0": - raise error("Single cell range failed") - - if xl.Range("A1:B1").Value != (("Hi 0", 2),): - raise error("flat-horizontal cell range failed") - - if xl.Range("A1:A2").Value != (("Hi 0",), ("x",)): - raise error("flat-vertical cell range failed") - - if xl.Range("A1:C3").Value != ( + assert xl.Range("A1").Value == "Hi 0", "Single cell range failed" + assert xl.Range("A1:B1").Value == ( + ("Hi 0", 2), + ), "flat-horizontal cell range failed" + assert xl.Range("A1:A2").Value == ( + ("Hi 0",), + ("x",), + ), "flat-vertical cell range failed" + assert xl.Range("A1:C3").Value == ( ("Hi 0", 2, 3), ("x", "Hi 1", "z"), (3, 2, "Hi 2"), - ): - raise error("square cell range failed") + ), "square cell range failed" xl.Range("A1:C3").Value = ((3, 2, 1), ("x", "y", "z"), (1, 2, 3)) - if xl.Range("A1:C3").Value != ( + assert xl.Range("A1:C3").Value == ( (3, 2, 1), ("x", "y", "z"), (1, 2, 3), - ): - raise error("Range was not what I set it to!") + ), "Range was not what I set it to!" # test dates out with Excel xl.Cells(5, 1).Value = "Excel time" diff --git a/com/win32com/test/testNetscape.py b/com/win32com/test/testNetscape.py index 471de8028..ed3638031 100644 --- a/com/win32com/test/testNetscape.py +++ b/com/win32com/test/testNetscape.py @@ -6,13 +6,10 @@ import netscape -error = "Netscape Test Error" - if __name__ == "__main__": n = netscape.CNetworkCX() rc = n.Open("http://d|/temp/apyext.html", 0, None, 0, None) - if not rc: - raise error("Open method of Netscape failed") + assert rc, "Open method of Netscape failed" while 1: num, str = n.Read(None, 0) print("Got ", num, str) diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index 578376246..a906de5c9 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -21,8 +21,6 @@ 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++" -error = Exception - # This test uses a Python implemented COM server - ensure correctly registered. RegisterPythonServer( os.path.join(os.path.dirname(__file__), "..", "servers", "test_pycomtest.py"), @@ -49,8 +47,7 @@ def check_get_set(func, arg): got = func(arg) - if got != arg: - raise error(f"{func} failed - expected {arg!r}, got {got!r}") + assert got == arg, f"{func} failed - expected {arg!r}, got {got!r}" def check_get_set_raises(exc, func, arg): @@ -59,7 +56,9 @@ def check_get_set_raises(exc, func, arg): except exc as e: pass # what we expect! else: - raise error(f"{func} with arg {arg!r} didn't raise {exc} - returned {got!r}") + raise AssertionError( + f"{func} with arg {arg!r} didn't raise {exc} - returned {got!r}" + ) def progress(*args): @@ -77,19 +76,17 @@ def TestApplyResult(fn, args, result): progress("Testing ", fnName) pref = "function " + fnName rc = fn(*args) - if rc != result: - raise error(f"{pref} failed - result not {result!r} but {rc!r}") + assert rc == result, f"{pref} failed - result not {result!r} but {rc!r}" def TestConstant(constName, pyConst): try: comConst = getattr(constants, constName) except: - raise error(f"Constant {constName} missing") - if comConst != pyConst: - raise error( - f"Constant value wrong for {constName} - got {comConst}, wanted {pyConst}" - ) + raise AssertionError(f"Constant {constName} missing") + assert ( + comConst == pyConst + ), f"Constant value wrong for {constName} - got {comConst}, wanted {pyConst}" # Simple handler class. This demo only fires one event. @@ -132,21 +129,22 @@ def TestCommon(o, is_generated): progress("Checking default args") rc = o.TestOptionals() - if rc[:-1] != ("def", 0, 1) or abs(rc[-1] - 3.14) > 0.01: - print(rc) - raise error("Did not get the optional values correctly") + assert rc[:-1] == ("def", 0, 1) and abs(rc[-1] - 3.14) <= 0.01, ( + "Did not get the optional values correctly", + rc, + ) rc = o.TestOptionals("Hi", 2, 3, 1.1) - if rc[:-1] != ("Hi", 2, 3) or abs(rc[-1] - 1.1) > 0.01: - print(rc) - raise error("Did not get the specified optional values correctly") + assert rc[:-1] == ("Hi", 2, 3) and abs(rc[-1] - 1.1) <= 0.01, ( + "Did not get the specified optional values correctly", + rc, + ) rc = o.TestOptionals2(0) - if rc != (0, "", 1): - print(rc) - raise error("Did not get the optional2 values correctly") + assert rc == (0, "", 1), ("Did not get the optional2 values correctly", rc) rc = o.TestOptionals2(1.1, "Hi", 2) - if rc[1:] != ("Hi", 2) or abs(rc[0] - 1.1) > 0.01: - print(rc) - raise error("Did not get the specified optional2 values correctly") + assert rc[1:] == ("Hi", 2) and abs(rc[0] - 1.1) <= 0.01, ( + "Did not get the specified optional2 values correctly", + rc, + ) progress("Checking getting/passing IUnknown") check_get_set(o.GetSetUnknown, o) @@ -156,13 +154,13 @@ def TestCommon(o, is_generated): expected_class = o.__class__ # CoClass instances have `default_interface` expected_class = getattr(expected_class, "default_interface", expected_class) - if not isinstance(o.GetSetDispatch(o), expected_class): - raise error(f"GetSetDispatch failed: {o.GetSetDispatch(o)!r}") + assert isinstance( + o.GetSetDispatch(o), expected_class + ), f"GetSetDispatch failed: {o.GetSetDispatch(o)!r}" progress("Checking getting/passing IDispatch of known type") expected_class = o.__class__ expected_class = getattr(expected_class, "default_interface", expected_class) - if o.GetSetInterface(o).__class__ != expected_class: - raise error("GetSetDispatch failed") + assert o.GetSetInterface(o).__class__ == expected_class, "GetSetDispatch failed" progress("Checking misc args") check_get_set(o.GetSetVariant, 4) @@ -177,10 +175,9 @@ def TestCommon(o, is_generated): check_get_set(o.GetSetUnsignedInt, 0) check_get_set(o.GetSetUnsignedInt, 1) check_get_set(o.GetSetUnsignedInt, 0x80000000) - if o.GetSetUnsignedInt(-1) != 0xFFFFFFFF: - # -1 is a special case - we accept a negative int (silently converting to - # unsigned) but when getting it back we convert it to a long. - raise error("unsigned -1 failed") + # -1 is a special case - we accept a negative int (silently converting to unsigned) + # but when getting it back we convert it to a long. + assert o.GetSetUnsignedInt(-1) == 0xFFFFFFFF, "unsigned -1 failed" check_get_set(o.GetSetLong, 0) check_get_set(o.GetSetLong, -1) @@ -190,8 +187,7 @@ def TestCommon(o, is_generated): check_get_set(o.GetSetUnsignedLong, 1) check_get_set(o.GetSetUnsignedLong, 0x80000000) # -1 is a special case - see above. - if o.GetSetUnsignedLong(-1) != 0xFFFFFFFF: - raise error("unsigned -1 failed") + assert o.GetSetUnsignedLong(-1) == 0xFFFFFFFF, "unsigned -1 failed" # We want to explicitly test > 32 bits. # 'maxsize+1' is no good on 64bit platforms as its 65 bits! @@ -206,8 +202,13 @@ def TestCommon(o, is_generated): progress("Checking var args") o.SetVarArgs("Hi", "There", "From", "Python", 1) - if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1): - raise error("VarArgs failed -" + str(o.GetLastVarArgs())) + assert o.GetLastVarArgs() == ( + "Hi", + "There", + "From", + "Python", + 1, + ), f"VarArgs failed -{o.GetLastVarArgs()}" progress("Checking arrays") l = [] @@ -232,21 +233,21 @@ def TestCommon(o, is_generated): progress("Checking properties") o.LongProp = 3 - if o.LongProp != 3 or o.IntProp != 3: - raise error("Property value wrong - got %d/%d" % (o.LongProp, o.IntProp)) + assert ( + o.LongProp == o.IntProp == 3 + ), f"Property value wrong - got {o.LongProp}/{o.IntProp}" o.LongProp = o.IntProp = -3 - if o.LongProp != -3 or o.IntProp != -3: - raise error("Property value wrong - got %d/%d" % (o.LongProp, o.IntProp)) + assert ( + o.LongProp == o.IntProp == -3 + ), f"Property value wrong - got {o.LongProp}/{o.IntProp}" # This number fits in an unsigned long. Attempting to set it to a normal # long will involve overflow, which is to be expected. But we do # expect it to work in a property explicitly a VT_UI4. check = 3 * 10**9 o.ULongProp = check - if o.ULongProp != check: - raise error( - "Property value wrong - got %d (expected %d)" % (o.ULongProp, check) - ) - + assert ( + o.ULongProp == check + ), f"Property value wrong - got {o.ULongProp} (expected {check})" TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function TestApplyResult(o.Test, ("Unused", 1 == 1), 1) # A bool function @@ -281,12 +282,10 @@ def TestCommon(o, is_generated): progress("Checking currency") # currency. pythoncom.__future_currency__ = 1 - if o.CurrencyProp != 0: - raise error(f"Expecting 0, got {o.CurrencyProp!r}") + assert o.CurrencyProp == 0, f"Expecting 0, got {o.CurrencyProp!r}" for val in ("1234.5678", "1234.56", "1234"): o.CurrencyProp = decimal.Decimal(val) - if o.CurrencyProp != decimal.Decimal(val): - raise error(f"{val} got {o.CurrencyProp!r}") + assert o.CurrencyProp == decimal.Decimal(val), f"{val} got {o.CurrencyProp!r}" v1 = decimal.Decimal("1234.5678") TestApplyResult(o.DoubleCurrency, (v1,), v1 * 2) @@ -307,8 +306,7 @@ def TestTrickyTypesWithVariants(o, is_generated): v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_VARIANT, 2) o.TestByRefVariant(v) got = v.value - if got != 4: - raise error("TestByRefVariant failed") + assert got == 4, "TestByRefVariant failed" if is_generated: got = o.TestByRefString("Foo") @@ -316,8 +314,7 @@ def TestTrickyTypesWithVariants(o, is_generated): v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, "Foo") o.TestByRefString(v) got = v.value - if got != "FooFoo": - raise error("TestByRefString failed") + assert got == "FooFoo", "TestByRefString failed" # check we can pass ints as a VT_UI1 vals = [1, 2, 3, 4] @@ -348,8 +345,7 @@ def TestTrickyTypesWithVariants(o, is_generated): else: arg = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_ARRAY | pythoncom.VT_R8, vals) o.ChangeDoubleSafeArray(arg) - if arg.value != expected: - raise error("ChangeDoubleSafeArray got the wrong value") + assert arg.value == expected, "ChangeDoubleSafeArray got the wrong value" if is_generated: got = o.DoubleInOutString("foo") @@ -383,7 +379,7 @@ def TestDynamic(): # TypeMismatch error. try: check_get_set_raises(ValueError, o.GetSetInt, "foo") - raise error("no exception raised") + raise AssertionError("no exception raised") except pythoncom.com_error as exc: if exc.hresult != winerror.DISP_E_TYPEMISMATCH: raise @@ -398,8 +394,7 @@ def TestDynamic(): # damn - props with params don't work for dynamic objects :( # o.SetParamProp(0, 1) - # if o.ParamProp(0) != 1: - # raise RuntimeError, o.paramProp(0) + # assert o.ParamProp(0) == 1, o.paramProp(0) def TestGenerated(): @@ -428,11 +423,10 @@ def TestGenerated(): # XXX - this is failing in dynamic tests, but should work fine. i1, i2 = o.GetMultipleInterfaces() - if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass): - # Yay - is now an instance returned! - raise error( - f"GetMultipleInterfaces did not return instances - got '{i1}', '{i2}'" - ) + # Yay - is now an instance returned! + assert isinstance(i1, DispatchBaseClass) and isinstance( + i2, DispatchBaseClass + ), f"GetMultipleInterfaces did not return instances - got '{i1}', '{i2}'" del i1 del i2 @@ -447,12 +441,12 @@ def TestGenerated(): # Pass some non-sequence objects to our array decoder, and watch it fail. try: o.SetVariantSafeArray("foo") - raise error("Expected a type error") + raise AssertionError("Expected a type error") except TypeError: pass try: o.SetVariantSafeArray(666) - raise error("Expected a type error") + raise AssertionError("Expected a type error") except TypeError: pass @@ -484,13 +478,11 @@ def TestGenerated(): TestApplyResult(o.TestInOut, (2.0, True, 4), (4.0, False, 8)) o.SetParamProp(0, 1) - if o.ParamProp(0) != 1: - raise RuntimeError(o.paramProp(0)) + assert o.ParamProp(0) == 1, o.paramProp(0) # Make sure CastTo works - even though it is only casting it to itself! o2 = CastTo(o, "IPyCOMTest") - if o != o2: - raise error("CastTo should have returned the same object") + assert o == o2, "CastTo should have returned the same object" # Do the connection point thing... # Create a connection object. @@ -550,7 +542,7 @@ def _TestPyVariant(o, is_generated, val, checker=None): def _TestPyVariantFails(o, is_generated, val, exc): try: _TestPyVariant(o, is_generated, val) - raise error(f"Setting {val!r} didn't raise {exc}") + raise AssertionError(f"Setting {val!r} didn't raise {exc}") except exc: pass @@ -603,23 +595,19 @@ def TestCounter(counter, bIsGenerated): ret = counter.Item(num + 1) else: ret = counter[num] - if ret != num + 1: - raise error( - "Random access into element %d failed - return was %s" - % (num, repr(ret)) - ) + assert ( + ret == num + 1 + ), f"Random access into element {num} failed - return was {ret!r}" except IndexError: - raise error("** IndexError accessing collection element %d" % num) + raise AssertionError(f"** IndexError accessing collection element {num}") num = 0 if bIsGenerated: counter.SetTestProperty(1) counter.TestProperty = 1 # Note this has a second, default arg. counter.SetTestProperty(1, 2) - if counter.TestPropertyWithDef != 0: - raise error("Unexpected property set value!") - if counter.TestPropertyNoDef(1) != 1: - raise error("Unexpected property set value!") + assert counter.TestPropertyWithDef == 0, "Unexpected property set value!" + assert counter.TestPropertyNoDef(1) == 1, "Unexpected property set value!" else: pass # counter.TestProperty = 1 @@ -631,16 +619,17 @@ def TestCounter(counter, bIsGenerated): if bIsGenerated: bounds = counter.GetBounds() - if bounds[0] != 1 or bounds[1] != 10: - raise error("** Error - counter did not give the same properties back") + assert ( + bounds[0] == 1 and bounds[1] == 10 + ), "** Error - counter did not give the same properties back" counter.SetBounds(bounds[0], bounds[1]) for item in counter: num = num + 1 - if num != len(counter): - raise error("*** Length of counter and loop iterations dont match ***") - if num != 10: - raise error("*** Unexpected number of loop iterations ***") + assert num == len( + counter + ), "*** Length of counter and loop iterations dont match ***" + assert num == 10, "*** Unexpected number of loop iterations ***" try: counter = iter(counter)._iter_.Clone() # Test Clone() and enum directly @@ -652,15 +641,13 @@ def TestCounter(counter, bIsGenerated): num = 0 for item in counter: num = num + 1 - if num != 10: - raise error("*** Unexpected number of loop iterations - got %d ***" % num) + assert num == 10, f"*** Unexpected number of loop iterations - got {num} ***" progress("Finished testing counter") def TestLocalVTable(ob): # Python doesn't fully implement this interface. - if ob.DoubleString("foo") != "foofoo": - raise error("couldn't foofoo") + assert ob.DoubleString("foo") == "foofoo", "couldn't foofoo" ############################### diff --git a/com/win32com/test/testall.py b/com/win32com/test/testall.py index 1e4498905..e9abe1036 100644 --- a/com/win32com/test/testall.py +++ b/com/win32com/test/testall.py @@ -218,7 +218,7 @@ def make_test_suite(test_level=1): for mod_name in unittest_modules[i]: mod, func = get_test_mod_and_func(mod_name, import_failures) if mod is None: - raise Exception(f"no such module '{mod_name}'") + raise ModuleNotFoundError(f"no such module '{mod_name}'") if func is not None: test = CapturingFunctionTestCase(func, description=mod_name) else: diff --git a/com/win32com/test/testmakepy.py b/com/win32com/test/testmakepy.py index 2d414d3d8..633758649 100644 --- a/com/win32com/test/testmakepy.py +++ b/com/win32com/test/testmakepy.py @@ -31,7 +31,7 @@ def TestBuildAll(verbose=1): print(details) except KeyboardInterrupt: print("Interrupted!") - raise KeyboardInterrupt + raise except: print("Failed:", info.desc) traceback.print_exc() diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index 02e33b614..a99b3a0a2 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -16,10 +16,8 @@ # for debugging useDispatcher = None -## import win32com.server.dispatcher -## useDispatcher = win32com.server.dispatcher.DefaultDebugDispatcher - -error = RuntimeError +# import win32com.server.dispatcher +# useDispatcher = win32com.server.dispatcher.DefaultDebugDispatcher # Set up a COM object that VB will do some callbacks on. This is used @@ -77,30 +75,31 @@ def CallbackVoidOneByRefButReturnNone(self, intVal): def TestVB(vbtest, bUseGenerated): vbtest.LongProperty = -1 - if vbtest.LongProperty != -1: - raise error("Could not set the long property correctly.") + assert vbtest.LongProperty == -1, "Could not set the long property correctly." vbtest.IntProperty = 10 - if vbtest.IntProperty != 10: - raise error("Could not set the integer property correctly.") + assert vbtest.IntProperty == 10, "Could not set the integer property correctly." vbtest.VariantProperty = 10 - if vbtest.VariantProperty != 10: - raise error("Could not set the variant integer property correctly.") + assert ( + vbtest.VariantProperty == 10 + ), "Could not set the variant integer property correctly." vbtest.VariantProperty = memoryview(b"raw\0data") - if vbtest.VariantProperty != memoryview(b"raw\0data"): - raise error("Could not set the variant buffer property correctly.") + assert vbtest.VariantProperty == memoryview( + b"raw\0data" + ), "Could not set the variant buffer property correctly." vbtest.StringProperty = "Hello from Python" - if vbtest.StringProperty != "Hello from Python": - raise error("Could not set the string property correctly.") + assert ( + vbtest.StringProperty == "Hello from Python" + ), "Could not set the string property correctly." vbtest.VariantProperty = "Hello from Python" - if vbtest.VariantProperty != "Hello from Python": - raise error("Could not set the variant string property correctly.") + assert ( + vbtest.VariantProperty == "Hello from Python" + ), "Could not set the variant string property correctly." vbtest.VariantProperty = (1.0, 2.0, 3.0) - if vbtest.VariantProperty != (1.0, 2.0, 3.0): - raise error( - "Could not set the variant property to an array of floats correctly - '{}'.".format( - vbtest.VariantProperty - ) - ) + assert vbtest.VariantProperty == ( + 1.0, + 2.0, + 3.0, + ), f"Could not set the variant property to an array of floats correctly - '{vbtest.VariantProperty}'." TestArrays(vbtest, bUseGenerated) TestStructs(vbtest) @@ -116,37 +115,35 @@ def TestVB(vbtest, bUseGenerated): # A property that only has PUTREF defined. vbtest.VariantPutref = vbtest - if vbtest.VariantPutref._oleobj_ != vbtest._oleobj_: - raise error("Could not set the VariantPutref property correctly.") + assert ( + vbtest.VariantPutref._oleobj_ == vbtest._oleobj_ + ), "Could not set the VariantPutref property correctly." # Cant test further types for this VariantPutref, as only # COM objects can be stored ByRef. # A "set" type property - only works for generated. # VB recognizes a collection via a few "private" interfaces that we # could later build support in for. - # vbtest.CollectionProperty = NewCollection((1,2,"3", "Four")) - # if vbtest.CollectionProperty != (1,2,"3", "Four"): - # raise error("Could not set the Collection property correctly - got back " + str(vbtest.CollectionProperty)) + # vbtest.CollectionProperty = NewCollection((1, 2, "3", "Four")) + # assert vbtest.CollectionProperty == ( + # 1, 2, "3", "Four", + # ), f"Could not set the Collection property correctly - got back {vbtest.CollectionProperty}" # These are sub's that have a single byref param # Result should be just the byref. - if vbtest.IncrementIntegerParam(1) != 2: - raise error("Could not pass an integer byref") + assert vbtest.IncrementIntegerParam(1) == 2, "Could not pass an integer byref" # Sigh - we cant have *both* "ommited byref" and optional args # We really have to opt that args nominated as optional work as optional # rather than simply all byrefs working as optional. - # if vbtest.IncrementIntegerParam() != 1: - # raise error("Could not pass an omitted integer byref") - - if vbtest.IncrementVariantParam(1) != 2: - raise error( - "Could not pass an int VARIANT byref:" - + str(vbtest.IncrementVariantParam(1)) - ) + # assert vbtest.IncrementIntegerParam() == 1, "Could not pass an omitted integer byref" - if vbtest.IncrementVariantParam(1.5) != 2.5: - raise error("Could not pass a float VARIANT byref") + assert ( + vbtest.IncrementVariantParam(1) == 2 + ), f"Could not pass an int VARIANT byref: {vbtest.IncrementVariantParam(1)}" + assert ( + vbtest.IncrementVariantParam(1.5) == 2.5 + ), "Could not pass a float VARIANT byref" # Can't test IncrementVariantParam with the param omitted as it # it not declared in the VB code as "Optional" @@ -154,8 +151,7 @@ def TestVB(vbtest, bUseGenerated): vbtest.DoSomeCallbacks(callback_ob) ret = vbtest.PassIntByVal(1) - if ret != 2: - raise error("Could not increment the integer - " + str(ret)) + assert ret == 2, f"Could not increment the integer - {ret}" TestVBInterface(vbtest) # Python doesnt support byrefs without some sort of generated support. @@ -163,15 +159,12 @@ def TestVB(vbtest, bUseGenerated): # This is a VB function that takes a single byref # Hence 2 return values - function and byref. ret = vbtest.PassIntByRef(1) - if ret != (1, 2): - raise error("Could not increment the integer - " + str(ret)) + assert ret == (1, 2), f"Could not increment the integer - {ret}" # Check you can leave a byref arg blank. - -# see above -# ret = vbtest.PassIntByRef() -# if ret != (0,1): -# raise error("Could not increment the integer with default arg- "+str(ret)) + # see above + # ret = vbtest.PassIntByRef() + # assert ret == (0, 1), f"Could not increment the integer with default arg - {ret}" def _DoTestCollection(vbtest, col_name, expected): @@ -186,53 +179,45 @@ def _getcount(ob): check = [] for item in c: check.append(item) - if check != list(expected): - raise error(f"Collection {col_name} didn't have {expected!r} (had {check!r})") + assert check == list( + expected + ), f"Collection {col_name} didn't have {expected!r} (had {check!r})" # Just looping over the collection again works (ie, is restartable) check = [] for item in c: check.append(item) - if check != list(expected): - raise error( - "Collection 2nd time around {} didn't have {!r} (had {!r})".format( - col_name, expected, check - ) - ) + assert check == list( + expected + ), f"Collection 2nd time around {col_name} didn't have {expected!r} (had {check!r})" + # Check we can get it via iter() i = iter(getattr(vbtest, col_name)) check = [] for item in i: check.append(item) - if check != list(expected): - raise error( - "Collection iterator {} didn't have {!r} 2nd time around (had {!r})".format( - col_name, expected, check - ) - ) + assert check == list( + expected + ), f"Collection iterator {col_name} didn't have {expected!r} 2nd time around (had {check!r})" # but an iterator is not restartable check = [] for item in i: check.append(item) - if check != []: - raise error( - "2nd time around Collection iterator {} wasn't empty (had {!r})".format( - col_name, check - ) - ) - + assert ( + check == [] + ), "2nd time around Collection iterator {col_name} wasn't empty (had {check!r})" # Check len()==Count() c = getattr(vbtest, col_name) - if len(c) != _getcount(c): - raise error( - f"Collection {col_name} __len__({len(c)!r}) wasn't==Count({_getcount(c)!r})" - ) + assert len(c) == _getcount( + c + ), f"Collection {col_name} __len__({len(c)!r}) wasn't==Count({_getcount(c)!r})" # Check we can do it with zero based indexing. c = getattr(vbtest, col_name) check = [] for i in range(_getcount(c)): check.append(c[i]) - if check != list(expected): - raise error(f"Collection {col_name} didn't have {expected!r} (had {check!r})") + assert check == list( + expected + ), f"Collection {col_name} didn't have {expected!r} (had {check!r})" # Check we can do it with our old "Skip/Next" methods. c = getattr(vbtest, col_name)._NewEnum() @@ -242,15 +227,17 @@ def _getcount(ob): if not n: break check.append(n[0]) - if check != list(expected): - raise error(f"Collection {col_name} didn't have {expected!r} (had {check!r})") + assert check == list( + expected + ), f"Collection {col_name} didn't have {expected!r} (had {check!r})" def TestCollections(vbtest): _DoTestCollection(vbtest, "CollectionProperty", [1, "Two", "3"]) # zero based indexing works for simple VB collections. - if vbtest.CollectionProperty[0] != 1: - raise error("The CollectionProperty[0] element was not the default value") + assert ( + vbtest.CollectionProperty[0] == 1 + ), "The CollectionProperty[0] element was not the default value" _DoTestCollection(vbtest, "EnumerableCollectionProperty", []) vbtest.EnumerableCollectionProperty.Add(1) @@ -262,15 +249,13 @@ def TestCollections(vbtest): def _DoTestArray(vbtest, data, expected_exception=None): try: vbtest.ArrayProperty = data - if expected_exception is not None: - raise error("Expected '%s'" % expected_exception) + assert expected_exception is None, f"Expected '{expected_exception}'" except expected_exception: return got = vbtest.ArrayProperty - if got != data: - raise error( - f"Could not set the array data correctly - got {got!r}, expected {data!r}" - ) + assert ( + got == data + ), f"Could not set the array data correctly - got {got!r}, expected {data!r}" def TestArrays(vbtest, bUseGenerated): @@ -339,14 +324,12 @@ def TestArrays(vbtest, bUseGenerated): # and one for the byref. testData = "Mark was here".split() resultData, byRefParam = vbtest.PassSAFEARRAY(testData) - if testData != list(resultData): - raise error( - "The safe array data was not what we expected - got " + str(resultData) - ) - if testData != list(byRefParam): - raise error( - "The safe array data was not what we expected - got " + str(byRefParam) - ) + assert testData == list( + resultData + ), f"The safe array data was not what we expected - got {resultData}" + assert testData == list( + byRefParam + ), f"The safe array data was not what we expected - got {byRefParam}" testData = [1.0, 2.0, 3.0] resultData, byRefParam = vbtest.PassSAFEARRAYVariant(testData) assert testData == list(byRefParam) @@ -372,62 +355,69 @@ def TestArrays(vbtest, bUseGenerated): def TestStructs(vbtest): try: vbtest.IntProperty = "One" - raise error("Should have failed by now") + raise AssertionError("Should have failed by now") except pythoncom.com_error as exc: - if exc.hresult != winerror.DISP_E_TYPEMISMATCH: - raise error("Expected DISP_E_TYPEMISMATCH") + assert ( + exc.hresult == winerror.DISP_E_TYPEMISMATCH + ), "Expected DISP_E_TYPEMISMATCH" s = vbtest.StructProperty - if s.int_val != 99 or str(s.str_val) != "hello": - raise error("The struct value was not correct") + assert ( + s.int_val == 99 and str(s.str_val) == "hello" + ), "The struct value was not correct" s.str_val = "Hi from Python" s.int_val = 11 - if s.int_val != 11 or str(s.str_val) != "Hi from Python": - raise error("The struct value didnt persist!") - - if s.sub_val.int_val != 66 or str(s.sub_val.str_val) != "sub hello": - raise error("The sub-struct value was not correct") + assert ( + s.int_val == 11 and str(s.str_val) == "Hi from Python" + ), "The struct value didn't persist!" + assert ( + s.sub_val.int_val == 66 and str(s.sub_val.str_val) == "sub hello" + ), "The sub-struct value was not correct" sub = s.sub_val sub.int_val = 22 - if sub.int_val != 22: - print(sub.int_val) - raise error("The sub-struct value didnt persist!") - - if s.sub_val.int_val != 22: - print(s.sub_val.int_val) - raise error("The sub-struct value (re-fetched) didnt persist!") - - if ( - s.sub_val.array_val[0].int_val != 0 - or str(s.sub_val.array_val[0].str_val) != "zero" - ): - print(s.sub_val.array_val[0].int_val) - raise error("The array element wasnt correct") + assert sub.int_val == 22, ( + f"The sub-struct value didn't persist!", + str(sub.int_val), + ) + assert s.sub_val.int_val == 22, ( + "The sub-struct value (re-fetched) didn't persist!", + str(s.sub_val.int_val), + ) + assert ( + s.sub_val.array_val[0].int_val == 0 + and str(s.sub_val.array_val[0].str_val) == "zero" + ), ("The array element wasn't correct", str(s.sub_val.array_val[0].int_val)) s.sub_val.array_val[0].int_val = 99 s.sub_val.array_val[1].int_val = 66 - if s.sub_val.array_val[0].int_val != 99 or s.sub_val.array_val[1].int_val != 66: - print(s.sub_val.array_val[0].int_val) - raise error("The array element didnt persist.") + assert ( + s.sub_val.array_val[0].int_val == 99 and s.sub_val.array_val[1].int_val == 66 + ), ( + "The array elements didn't persist.", + str(s.sub_val.array_val[0].int_val), + str(s.sub_val.array_val[1].int_val), + ) # Now pass the struct back to VB vbtest.StructProperty = s # And get it back again s = vbtest.StructProperty - if s.int_val != 11 or str(s.str_val) != "Hi from Python": - raise error("After sending to VB, the struct value didnt persist!") - if s.sub_val.array_val[0].int_val != 99: - raise error("After sending to VB, the struct array value didnt persist!") + assert ( + s.int_val == 11 and str(s.str_val) == "Hi from Python" + ), "After sending to VB, the struct value didn't persist!" + assert ( + s.sub_val.array_val[0].int_val == 99 + ), "After sending to VB, the struct array value didn't persist!" # Now do some object equality tests. assert s == s assert s is not None try: s < None - raise error("Expected type error") + raise AssertionError("Expected type error") except TypeError: pass try: None < s - raise error("Expected type error") + raise AssertionError("Expected type error") except TypeError: pass assert s != s.sub_val @@ -448,7 +438,9 @@ def TestStructs(vbtest): assert s.int_val == 0, "new struct inst initialized correctly!" s.int_val = -1 vbtest.SetStructSub(s) - assert vbtest.GetStructFunc().int_val == -1, "new struct didnt make the round trip!" + assert ( + vbtest.GetStructFunc().int_val == -1 + ), "new struct didn't make the round trip!" # Finally, test stand-alone structure arrays. s_array = vbtest.StructArrayProperty assert s_array is None, "Expected None from the uninitialized VB array" @@ -465,7 +457,7 @@ def TestStructs(vbtest): # Some error type checks. try: s.bad_attribute - raise RuntimeError("Could get a bad attribute") + raise AssertionError("Could get a bad attribute") except AttributeError: pass m = s.__members__ @@ -479,7 +471,7 @@ def TestStructs(vbtest): # Test attribute errors. try: s.foo - raise RuntimeError("Expected attribute error") + raise AssertionError("Expected attribute error") except AttributeError as exc: assert "foo" in str(exc), exc @@ -495,18 +487,16 @@ def TestStructs(vbtest): if repr(s) != expected: print("Expected repr:", expected) print("Actual repr :", repr(s)) - raise RuntimeError("repr() of record object failed") + raise AssertionError("repr() of record object failed") print("Struct/Record tests passed") def TestVBInterface(ob): t = ob.GetInterfaceTester(2) - if t.getn() != 2: - raise error("Initial value wrong") + assert t.getn() == 2, "Initial value wrong" t.setn(3) - if t.getn() != 3: - raise error("New value wrong") + assert t.getn() == 3, "New value wrong" def TestObjectSemantics(ob): @@ -527,12 +517,12 @@ def TestObjectSemantics(ob): assert None != ob try: ob < None - raise error("Expected type error") + raise AssertionError("Expected type error") except TypeError: pass try: None < ob - raise error("Expected type error") + raise AssertionError("Expected type error") except TypeError: pass diff --git a/com/win32comext/directsound/test/ds_test.py b/com/win32comext/directsound/test/ds_test.py index 1a4d5f94e..97f115a4e 100644 --- a/com/win32comext/directsound/test/ds_test.py +++ b/com/win32comext/directsound/test/ds_test.py @@ -35,13 +35,13 @@ def wav_header_unpack(data): datalength, ) = struct.unpack("<4sl4s4slhhllhh4sl", data) - if riff != b"RIFF": - raise ValueError("invalid wav header") + assert riff == b"RIFF", "invalid wav header" - if fmtsize != 16 or fmt != b"fmt " or data != b"data": - # fmt chuck is not first chunk, directly followed by data chuck - # It is nowhere required that they are, it is just very common - raise ValueError("cannot understand wav header") + # fmt chuck is not first chunk, directly followed by data chuck + # It is nowhere required that they are, it is just very common + assert ( + fmtsize == 16 and fmt == b"fmt " and data == b"data" + ), "cannot understand wav header" wfx = pywintypes.WAVEFORMATEX() wfx.wFormatTag = format diff --git a/isapi/test/extension_simple.py b/isapi/test/extension_simple.py index b7fe37b6a..bb4399025 100644 --- a/isapi/test/extension_simple.py +++ b/isapi/test/extension_simple.py @@ -47,7 +47,7 @@ def Dispatch(self, ecb): def test1(self, ecb): try: ecb.GetServerVariable("foo bar") - raise RuntimeError("should have failed!") + raise AssertionError("should have failed!") except ExtensionError as err: assert err.errno == winerror.ERROR_INVALID_INDEX, err return "worked!" @@ -82,10 +82,10 @@ def test_unicode_vars(self, ecb): return "This is IIS version %g - unicode only works in IIS6 and later" % ver us = ecb.GetServerVariable("UNICODE_SERVER_NAME") - if not isinstance(us, str): - raise RuntimeError("unexpected type!") - if us != str(ecb.GetServerVariable("SERVER_NAME")): - raise RuntimeError("Unicode and non-unicode values were not the same") + assert isinstance(us, str), "unexpected type!" + assert us == str( + ecb.GetServerVariable("SERVER_NAME") + ), "Unicode and non-unicode values were not the same" return "worked!" diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index 85d20587b..17256b75b 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -29,8 +29,8 @@ def applyHandlingSkips(func, *args): class TestSSPI(unittest.TestCase): def assertRaisesHRESULT(self, hr, func, *args): try: - return func(*args) - raise RuntimeError(f"expecting {hr} failure") + func(*args) + raise AssertionError(f"expecting {hr} failure") except win32security.error as exc: self.assertEqual(exc.winerror, hr) diff --git a/win32/test/test_win32api.py b/win32/test/test_win32api.py index 3f0ad31e5..5218d519e 100644 --- a/win32/test/test_win32api.py +++ b/win32/test/test_win32api.py @@ -63,7 +63,7 @@ def test1(self): # This used to leave a stale exception behind. def reg_operation(): hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name) - x = 3 / 0 # or a statement like: raise 'error' + x = 3 / 0 # or a statement like: raise Exception # do the test try: diff --git a/win32/test/test_win32crypt.py b/win32/test/test_win32crypt.py index 145a3df96..d5e315007 100644 --- a/win32/test/test_win32crypt.py +++ b/win32/test/test_win32crypt.py @@ -116,7 +116,7 @@ def checkCertFile(self, filename, expected_format): except ValueError: pass else: - raise RuntimeError("should not be able to close the context twice") + raise AssertionError("should not be able to close the context twice") def testCertBase64(self): self.checkCertFile( diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index 8ca2e8529..159c45e67 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -360,7 +360,7 @@ def testCompletionPortsMultiple(self): # Check that. try: win32file.CloseHandle(hv) - raise RuntimeError("Expected close to fail!") + raise AssertionError("Expected close to fail!") except win32file.error as details: self.assertEqual(details.winerror, winerror.ERROR_INVALID_HANDLE) @@ -868,7 +868,7 @@ def runner(): raise print("Failed to use port", self.addr, "trying another random one") else: - raise RuntimeError("Failed to find an available port to bind to.") + raise AssertionError("Failed to find an available port to bind to.") s1.listen(1) cli, addr = s1.accept() buf = 1 diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index 89d53b9ea..01b18caf2 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -28,7 +28,7 @@ def CheckNoOtherReaders(): # Reset everything so following tests still fail with this error! win32trace.TermRead() win32trace.TermWrite() - raise RuntimeError( + raise AssertionError( "An existing win32trace reader appears to be " "running - please stop this process and try again" ) diff --git a/win32/test/testall.py b/win32/test/testall.py index c66a89887..7862bc6f5 100644 --- a/win32/test/testall.py +++ b/win32/test/testall.py @@ -99,11 +99,10 @@ def __call__(self): 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( - f"{base} failed with exit code {rc}. Output is:\n{output}" - ) + assert ( + reconstituted is not None + ), f"{base} failed with exit code {rc}. Output is:\n{output}" + raise reconstituted def get_demo_tests():