我正在编写单元测试,我需要模拟一个方法调用,以便在大多数情况下它表现为方法本身,除非参数获得特殊值“插入”。这是一个简化的生产代码:
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()
哪个打印
Do something useful
Do something useful
Number of rows: 5
我可以使用以下代码自己制作一个模拟版本:
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()
哪个打印
Do something useful
Patched version in use
Number of rows: -1
我想使用mock
库来完成同样的事情(我相信这是python 3中包含的库)。我怎样才能做到这一点?(Python 2.6.2)