I write unit tests, and I need to make fun of a method call so that in most cases it behaves like the method itself, except when the argument gets the special value "insert into". Here is a simplified production code:
class CommandServer(object): def __init__(self): self.rowcount = None def runSQL(self, sql): print "Do something useful" self.rowcount=5 return self class Process(object): def process(self): cs = CommandServer() cs.runSQL("create table tbl1(X VARCHAR2(10))") r = cs.runSQL("insert into tbl1 select * from tbl2") print "Number of rows: %s" % r.rowcount p = Process() p.process()
which prints
Do something useful Do something useful Number of rows: 5
I can make a mock version myself using the following code:
runSQL = CommandServer.runSQL def runSQLPatch(self, sql): if sql.lstrip().startswith('insert into'): print "Patched version in use" class res(object): rowcount = -1 return res else: return runSQL(self, sql) CommandServer.runSQL = runSQLPatch p = Process() p.process()
which prints
Do something useful Patched version in use Number of rows: -1
I want to use the mock library to accomplish the same thing (I believe this is the library included in python 3 ). How can i do this? (Python 2.6.2)
source share