Using the mock library to fix the class method

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)

+4
source share
1 answer

To be completely understandable, it is only included in python 3.3 (which I'm so glad to know, thanks!).

Otherwise, a template that you can use is

 from mock import patch with patch.object(CommandServer, 'runSQL') as runSQL: class res(object): rowcount = -1 runSQL.return_value = res p = Process() p.process() for c in runSQL.call_list: assert c[1].lstrip().startswith('insert into') is True 

But this will cover all cases, not just cases when you send 'insert into' . This may give you a hint about where to look, but otherwise I don’t think that what you are looking for is possible with a layout.

+1
source

All Articles