Wednesday, June 08, 2005

pre-built mock classes?

There is a (relatively) widely used technique in unit testing, called mock objects. There is even a pMock library which provides a Mock class for a Python environment.

 

Given the "duck typing" nature of the Python itself, it's pretty trivial to build mocks without using any pre-built libraries. What is less trivial and potentially more worthwhile is to have a library of “stock” mock objects.

 

For instance, I found myself re-implementing ConnectionStub class again and again for different projects. And there is no shortage of other good candidates as well: socket, web request/response, thread objects, etc. Someone on a Python mailing list asks whether anyone implemented a mock filesystem interface, for example.

 

Having a library of such mock classes, realizing widely-used and “heavy” interfaces may be a good idea.

 

The only real problem I can think of is whether it’s possible to make these mocks generic enough. Mocks often contain some (application-specific) hard-coded rules and data to realize desired behavior. For instance, socket mock may fail when user attempts to write a “foobar” string – and unit test will use this to check how code handle these kind of errors. These rules may be generalized but it may lead to mock classes becoming unwieldy.

 

Even keeping this problem in mind, it’s still a reasonable idea for a library, but obviously I’m biased.

 

What do you think?

4 Comments:

Blogger Kevin Dangoor said...

I think it's a good idea, and a good fit for Python. For many of the basics in the Python std lib, you can make good guesses (or at least flesh out things as you write your own tests) as to what people would like to do with their mocks.

For example, you could make a mock file-like object. Then, you can take over the open builtin to use your mock. With a file-like thing, you'd be interested in providing input data, or perhaps being able to capture the output. That all seems pretty reasonable, and something that more than one person would want!

Since Python is dynamically typed, it's a lot easier to put mocks in place for things, since the mock doesn't have to follow some preexisting inheritance hierarchy.

Some of the more complex mocks (think urllib2, etc.) could be *very* handy!

I'm pretty certain I'd contribute to such a project, but I have too much on my plate to kick it off right now. So, if you get one going, keep us posted!

5:09 PM  
Anonymous Anonymous said...

The following is part of my basetest.py which I import for every UnitTest.

I typically use NotQuiteNull as mock object and assign WasCalled to the method names the thing undertest needs

sorry about formatting,
njharman@knoggin.com

class Null:
""" Null objects always and reliably "do nothing" """
def __init__(self, *args, **kwargs): pass
def __call__(self, *args, **kwargs): return self
def __repr__(self): return "Null()"
def __nonzero__(self): return 0
def __str__(self): return ''
def __getattr__(self, name): return self
def __setattr__(self, name, value): return self
def __delattr__(self, name): return self


class NotQuiteNull:
""" NotQuiteNull objects mostly "do nothing" but they can have attributes set """
def __init__(self, *args, **kwargs): pass
def __call__(self, *args, **kwargs): return self
def __repr__(self): return "Null()"
def __nonzero__(self): return 0
def __str__(self): return ''
def __getattr__(self, name): return self
def __delattr__(self, name): return self

class WasCalled:
""" Used to replace of method/func. Remembers if it was called, how often and with which parameters. ""
def __init__(self, returnThis = None):
self.called = 0
self.args = ()
self.kwargs = {}
self.returnThis = returnThis

def __call__(self, *args, **kwargs):
self.called += 1
self.args = args
self.kwargs = kwargs
return self.returnThis

def wasCalled( self ):
return self.called > 0

def wasCalledWith( self, *args, **kwargs):
if not self.wasCalled():
return False
#try to do what they mean
if type(args) == type(list()):
args = tuple(args)
elif type(args) != type(tuple()):
args = (args,)
return args == self.args and kwargs == self.kwargs

def calledWith(self):
return (self.args, self.kwargs)

def clearCalled(self):
self.called = 0
self.args = ()
self.kwargs = {}

10:22 AM  
Blogger haroldsr04ednelson said...

Hot News From The Automotive Lending Industry!!

+++++++++Current Profile+++++++++
InterFinancial Holdings, Corp (IFLH)
Current Price $0.036
+++++++++++++++++++++++++++++

Is this an undiscovered gem priced to go higher!!
Please read the following Announcement in its Entirety and Consider the Possibilities�
Watch this One to Trade!

IFLH announces Senator David Cain has joined its Board of Directors!!

IFLH volume trading is beginning to surge with landslide Announcement. The value of this
stock appears poised for growth! This one should not remain on the ground floor for long.

BREAKING NEWS!!
InterFinancial Holdings, Corp. (OTC Pink Sheets: IFLH - News) announced that they have added
David Cain to their board of directors. David Cain is currently the Chairman of the advisory
board to TTI (Texas Transportation Institute). Senator Cain represented Senate District 2 for
eight years in the Texas Senate and Chaired the Senate State Affairs Subcommittee on
Transportation and served nine terms in the Texas House of Representatives for District 107.

During his twelve years as Chairman of the House Committee on Transportation, Senator Cain�s
efforts on behalf of the people of Texas have been widely recognized. He was named to Texas
Monthly Magazine�s list of Ten Best Legislators, the Dallas Morning News said he was one of
the outstanding legislators of the 73rd session, and the Texas Department of Transportation
awarded him the Russell H. Perry Award in 1995 for his efforts to gain public awareness of
the need for and benefits of transportation facilities in the State of Texas.

Jeffrey C. Bruteyn, Managing Director, stated, We at InterFinancial are proud to have such a
widely recognized Senator join our board and oversee out automotive lending division. His
affiliations and connections to the automotive industry will be invaluable to our company.
Senator Cain will be instrumental in expediting our approval to use a government issued Seller
Finance License.

Seller Finance Licenses are very difficult to obtain and are usually reserved for the Big Boys
with heavy lobbyists. These licenses are highly coveted because it allows the finance company
to collect the entire down payment, instead of paying a portion of it to the taxing authority.
This dramatically helps a finance company�s bottom line if the buyer defaults on the loan.

With the new GPS tracking systems being installed on every car to dramatically improve
repossessions and with Senator Cain on the Board of Directors, InterFinancial Holdings
is ready to take their business to the next level.

Conclusion:

The examples above show the Awesome, Earning Potential of little known Companies
That Explode onto Investor�s Radar Screens. This stock will not be a Secret for long.
Then You May Feel the Desire to Act Right Now! And Please Watch This One Trade!!
GO IFLH!

All statements made are our express opinion only and should be treated as such. We may own,
take position and sell any securities mentioned at any time. Any statements that express or
involve discussions with respect to predictions, goals, expectations, beliefs, plans,
projections, objectives, assumptions or future events or performance are not statements of
historical fact and may be "forward looking statements." Forward looking statements are based
on expectations, estimates and projections at the time the statements are made that involve a
number of risks and uncertainties which could cause actual results or events to differ materially
from those presently anticipated. This newsletter was paid four thousand dollars from a party
(IR Marketing). Forward looking statements in this action may be identified through the use of
words such as: "projects", "foresee", "expects". in compliance with Section 17(.b), we disclose
the holding of IF LH shares prior to the publication of this report. Be aware of an inherent
conflict of interest resulting from such holdings due to our intent to profit from the liquidation
of these shares. Shares may be sold at any time, even after positive statements have been made
regarding the above company. Since we own shares, there is an inherent conflict of interest in
our statements and opinions. Readers of this publication are cautioned not to place undue reliance
on forward-looking statements, which are based on certain assumptions and expectations involving
various risks and uncertainties that could cause results to differ materially from those set forth
in the forward- looking statements. This is not solicitation to buy or sell stocks, this text is
for informational purpose only and you should seek professional advice from registered financial
advisor before you do anything related with buying or selling stocks, penny stocks are very high
risk and you can lose your entire investment.

1:14 PM  
Anonymous Anonymous said...

"I just came across your blog about **keyword** and wanted to drop you a note telling you how impressed I was with the information you have posted here. I also have a web site & blog about penny stock pick so I know what I'm talking about when I say your site is top-notch! Keep up the great work, you are providing a great resource on the Internet here!"

3:16 AM  

Post a Comment

<< Home