# Copyright (c) 2009 Tim Freeman # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # (This is the standard MIT License, copied from # http://www.opensource.org/licenses/mit-license.php on 24 Apr 2007.) #desc Utilities for unit tests to call. import traceback import StringIO import sys def with_output_to_string(f): # Invoke the given function, with no arguments. # Return a dict with these keys: # result -- The value returned by f, or None if it raised an exception. # exception -- The exception raised by f, or None if it returned normally. # output -- The text written to sys.stdout during the time f was running. exception = None result = None o = sys.stdout stringio = StringIO.StringIO() sys.stdout = stringio try: result = f() except: exception = sys.exc_info()[1] sys.stdout = o return {"result":result, "exception":exception, "output":stringio.getvalue()} def expect_exception(f): # Invoke the given function. # Throw an exception if f returns normally, and return the exception if f # throws one. threw = False try: f() except: return sys.exc_info()[1] raise Exception("The function should have thrown an exception, " "but it didn't.") def assert_equals(v1, v2): # Experiments show that assert does not compute its second # argument when the first argument is True. assert v1 == v2, "Should have been equal: %r, %r" % (v1, v2) def assert_in(v1, v2): """Assert that v1 is in v2, and print useful information if we fail.""" assert v1 in v2, "%r should have been in %r" % (v1, v2) # Put print_exc and print_stack here so I don't have to keep going # back to the documentation to remember how to spell them. def print_exc(): traceback.print_exc() def print_stack(): traceback.print_stack()