473,569 Members | 2,704 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python automatic testing: mocking an imported module?

Heyas

So we have the following situation: we have a testee.py that we want
to automatically test out and verifiy that it is worthy of being
deployed. We want our tester.py to test the code for testee.py
without changing the code for testee.py. testee.py has a module in it
that we want to mock in some tests and in others use the real module.

/foo.py: (real module)
class bar:
def __init__(self):
"I am real"

/foo_fake/foo.py: (fake module)
class bar:
def ___init__(self) :
"I am a banana"

/testee.py:
import foo
foo.bar()

/tester.py:
from foo_fake import foo
foo.bar() # prints I am a banana
testee.py # also prints I am a banana
import foo
foo.bar() # prints I am real
testee.py # also prints I am real
This isnt working as we would like, does anyone have any tips on how
to get something like this working?

Mar 27 '07 #1
6 3457
On Mar 27, 6:18 pm, "Silfheed" <silfh...@gmail .comwrote:
Heyas

So we have the following situation: we have a testee.py that we want
to automatically test out and verifiy that it is worthy of being
deployed. We want our tester.py to test the code for testee.py
without changing the code for testee.py. testee.py has a module in it
that we want to mock in some tests and in others use the real module.
I think you mean "testee.py *imports* a module", rather than "has a
module in it". Semantics but I was thrown off by this at first.

Why not write tests for the module that testee.py imports (here called
"foo.py")? If you write out the tests and foo.py passes to spec, then
you should feel confident it will work correctly with testee.py. Never
trust it; always play paranoid coder, but feel comfortable enough
using it.

After all, why should you feel comfortable using modules in the
standard library? Nobody guarantees bugs don't still lurk in there
(heck, c.l.p just found one in pdb today), however, they have unit
tests out the wazzoo that demonstrate, to the best of our knowledge,
the module works to spec. If that approach is good enough for the
standard library, wouldn't it be good enough for you?

Chris

Mar 28 '07 #2
"Silfheed" <si******@gmail .comwrites:
So we have the following situation: we have a testee.py that we want
to automatically test out and verifiy that it is worthy of being
deployed.
This is sometimes called the "module under test". I wish there was a
more succinct name in common usage.
We want our tester.py to test the code for testee.py
without changing the code for testee.py.
This is called a "unit test" for the module.
testee.py has a module in it
Looking at your example, testee.py *imports* a module; it doesn't
contain another one.
that we want to mock in some tests and in othemodule.
Excellent idea.
===== foo.py =====
class Bar(object):
def __init__(self):
self.name = "bar"
=====

===== dostuff.py =====
import foo

def get_bar():
return foo.Bar()
=====

===== test_dostuff.py =====
import dostuff

class Mock_foo_module (object):
""" Mock object for foo module """

class Bar(object):
def __init__(self):
self.name = "banana"

def test_dostuff_ge t_bar_should_cr eate_bar():
""" The dostuff.get_bar function should create a new Bar """
dostuff.foo = Mock_foo_module ()
test_bar = dostuff.get_bar ()
if not test_bar.name == "banana":
raise AssertionError( "test_bar.n ame should be banana")
=====

This is simply using an instance of a class (Mock_foo_modul e) to be a
mock 'module' object. That mock module has the required 'Bar'
attribute, bound to a class; so the 'dostuff' module's 'foo' attribute
can be replaced with our mock module object for the purpose of the
test.

The mock module's Bar class behaves in an idiomatic way (setting the
'name' attribute of its instance to a known value) that we use to
check whether the 'dostuff' module actually used our mock module.

This can be extended to mock any module interface you like, and then
confirm that the module under test has actually used the module as
expected.

--
\ "A politician is an animal which can sit on a fence and yet |
`\ keep both ears to the ground." -- Henry L. Mencken |
_o__) |
Ben Finney
Mar 28 '07 #3
Silfheed wrote:
So we have the following situation: we have a testee.py that we want
to automatically test out and verifiy that it is worthy of being
deployed. We want our tester.py to test the code for testee.py
without changing the code for testee.py. testee.py has a module in it
that we want to mock in some tests and in others use the real module.

/foo.py: (real module)
class bar:
def __init__(self):
"I am real"

/foo_fake/foo.py: (fake module)
class bar:
def ___init__(self) :
"I am a banana"

/testee.py:
import foo
foo.bar()

/tester.py:
from foo_fake import foo
foo.bar() # prints I am a banana
testee.py # also prints I am a banana
import foo
foo.bar() # prints I am real
testee.py # also prints I am real
This isnt working as we would like, does anyone have any tips on how
to get something like this working?
You can put foo_fake.foo into sys.modules as foo:

import sys
from foo_fake import foo

assert "foo" not in sys.modules
sys.modules["foo"] = foo

foo.bar() # prints I am a banana
import foo
foo.bar() # prints I am a banana

Peter

Mar 28 '07 #4

"Silfheed" <si******@gmail .comwrote in message
news:11******** **************@ l77g2000hsb.goo glegroups.com.. .
Heyas

So we have the following situation: we have a testee.py that we want
to automatically test out and verifiy that it is worthy of being
deployed. We want our tester.py to test the code for testee.py
without changing the code for testee.py. testee.py has a module in it
that we want to mock in some tests and in others use the real module.

/foo.py: (real module)
class bar:
def __init__(self):
"I am real"

/foo_fake/foo.py: (fake module)
class bar:
def ___init__(self) :
"I am a banana"

/testee.py:
import foo
foo.bar()

/tester.py:
from foo_fake import foo
foo.bar() # prints I am a banana
testee.py # also prints I am a banana
import foo
foo.bar() # prints I am real
testee.py # also prints I am real
This isnt working as we would like, does anyone have any tips on how
to get something like this working?
If you add the foo_fake directory to the front of sys.path, "import foo"
will import the foo.py in foo_fake directory before the one in the local
directory.

# unverified code
import sys
sys.path.append (0,'foo_fake') # add foo_fake to front of path
import foo
foo.bar()
execfile('teste e.py')
sys.path.pop(0) # remove foo_fake
reload(foo)
foo.bar()
execfile('teste e.py')

-Mark

Mar 28 '07 #5
On Mar 27, 9:13 pm, "Chris Lasher" <chris.las...@g mail.comwrote:
On Mar 27, 6:18 pm, "Silfheed" <silfh...@gmail .comwrote:
Heyas
So we have the following situation: we have a testee.py that we want
to automatically test out and verifiy that it is worthy of being
deployed. We want our tester.py to test the code for testee.py
without changing the code for testee.py. testee.py has a module in it
that we want to mock in some tests and in others use the real module.

I think you mean "testee.py *imports* a module", rather than "has a
module in it". Semantics but I was thrown off by this at first.

Why not write tests for the module that testee.py imports (here called
"foo.py")? If you write out the tests and foo.py passes to spec, then
you should feel confident it will work correctly with testee.py. Never
trust it; always play paranoid coder, but feel comfortable enough
using it.

After all, why should you feel comfortable using modules in the
standard library? Nobody guarantees bugs don't still lurk in there
(heck, c.l.p just found one inpdbtoday),
A slight correction. At present it looks like the bug is in Python,
and its handling after setting the current frame's f_lineno when it
refers to byte code offset 0, not pdb. And if you scan c.l.p for
another oddity in pdb with respect to tracebacks, there is possibly
another bug in Python (not strictly pdb).
however, they have unit
tests out the wazzoo that demonstrate, to the best of our knowledge,
the module works to spec.
Actually, as far as I know pdb *doesn't* have any unit tests! (pydb
does though ;-)

But all this nit-picking aside, I do agree with what you have to say
most whole heartedly. (And I'd say maybe a couple more unit tests for
Python to cover these bugs are in order.)
If that approach is good enough for the
standard library, wouldn't it be good enough for you?

Chris

Mar 29 '07 #6
Wow, that works great! Thanks all!

On Mar 28, 12:02 am, Ben Finney <bignose+hate s-s...@benfinney. id.au>
wrote:
"Silfheed" <silfh...@gmail .comwrites:
===== foo.py =====
class Bar(object):
def __init__(self):
self.name = "bar"
=====

===== dostuff.py =====
import foo

def get_bar():
return foo.Bar()
=====

===== test_dostuff.py =====
import dostuff

class Mock_foo_module (object):
""" Mock object for foo module """

class Bar(object):
def __init__(self):
self.name = "banana"

def test_dostuff_ge t_bar_should_cr eate_bar():
""" The dostuff.get_bar function should create a new Bar """
dostuff.foo = Mock_foo_module ()
test_bar = dostuff.get_bar ()
if not test_bar.name == "banana":
raise AssertionError( "test_bar.n ame should be banana")
=====

This is simply using an instance of a class (Mock_foo_modul e) to be a
mock 'module' object. That mock module has the required 'Bar'
attribute, bound to a class; so the 'dostuff' module's 'foo' attribute
can be replaced with our mock module object for the purpose of the
test.

The mock module's Bar class behaves in an idiomatic way (setting the
'name' attribute of its instance to a known value) that we use to
check whether the 'dostuff' module actually used our mock module.

This can be extended to mock any module interface you like, and then
confirm that the module under test has actually used the module as
expected.

--
\ "A politician is an animal which can sit on a fence and yet |
`\ keep both ears to the ground." -- Henry L. Mencken |
_o__) |
Ben Finney

Mar 30 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
2186
by: stephen.mayer | last post by:
Anyone know which is faster? I'm a PHP programmer but considering getting into Python ... did searches on Google but didn't turn much up on this. Thanks! Stephen
10
3670
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. Andrew dalke@dalkescientific.com
13
2074
by: John Dann | last post by:
A Python newbie, but some basic understanding of how classes, objects etc work in eg VB.Net. However, I'm struggling a little to translate this knowledge into the Python context. I'm trying to teach myself this aspect of Python by working up a trial project, part of which calls for pulling in data from a serial data connection at regular...
20
2406
by: earthwormgaz | last post by:
Hello, I'm after doing some C++ unit testing, I'm using CppUnit. I like the look of RudeMocks, but it doesn't work for Solaris/Sparc, so its no good to me sadly. So, I have class A, and it uses classes B and C. B and C have methods A uses, but they're not virtual, and I don't want to hack the code so that they are just to allow Unit...
0
7698
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1213
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
937
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.