473,785 Members | 2,823 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unittest help

I want to apply TDD (test driven development) on my project. I am
working on a class like this (in plan):

# file: myclass.py
import _extmod

class MyClass(object) :
def __init__(self):
self.handle = _extmod.open()

def __del__(self):
_extmod.close(s elf.handle)

def some_stuff(self ):
_extmod.foobar( self.handle)

...

As you see, it is an OO wrapper on _extmod, which is a pyrex extension
module. The question is: how to unittest this class? As the _extmod
is hardware-dependent, I want to use a mock class to replace it in unit
test. But how can I let myclass in unittest to import the mock class?
Like the following:

class MyClassTest(uni ttest.TestCase) :
def setUp(self):
import myclass
import mocklib
myclass.change_ extmod(mocklib. MockExtMod())
self.testobj = myclass.MyClass () # here MyClass.__init_ _ will
call the open
# method of MockExtMod class
instead of
# _extmod.open()
...

How to implement the change_extmod? (Or maybe my idea is totally
wrong?)

Jul 18 '05 #1
3 1792
* "Qiangning Hong" <ho****@gmail.c om> wrote:
I want to apply TDD (test driven development) on my project. I am
working on a class like this (in plan):

# file: myclass.py
import _extmod

class MyClass(object) :
def __init__(self):
self.handle = _extmod.open()

def __del__(self):
_extmod.close(s elf.handle)

def some_stuff(self ):
_extmod.foobar( self.handle)

...

As you see, it is an OO wrapper on _extmod, which is a pyrex extension
module. The question is: how to unittest this class? As the _extmod
is hardware-dependent, I want to use a mock class to replace it in unit
test. But how can I let myclass in unittest to import the mock class?


You need to design for testability, meaning in this case, that your class could
to do something like this:

class MyClass(object) :
def __init__(self):
self._loadExtmo d()
self.handle = self._extmod.op en()

def __del__(self):
self._extmod.cl ose(self.handle )

def _loadExtmod(sel f):
import _extmod
self._extmod = extmod

def some_stuff(self ):
self._extmod.fo obar(self.handl e)

Now just overload _loadExtmod and provide the mock class there.

HTH, nd
Jul 18 '05 #2
Qiangning Hong wrote:
As you see, it is an OO wrapper on _extmod, which is a pyrex extension
module. The question is: how to unittest this class? As the _extmod
is hardware-dependent, I want to use a mock class to replace it in unit
test. But how can I let myclass in unittest to import the mock class?
Like the following:

class MyClassTest(uni ttest.TestCase) :
def setUp(self):
import myclass
import mocklib
myclass.change_ extmod(mocklib. MockExtMod())
self.testobj = myclass.MyClass () # here MyClass.__init_ _ will
call the open
# method of MockExtMod class
instead of
# _extmod.open()
...

How to implement the change_extmod? (Or maybe my idea is totally
wrong?)


One way is simply to do:

def setUp(self):
import myclass
self.real_extmo d = myclass._extmod
myclass._extmod = mocklib.MockExt Mod()
self.testobj = myclass.MyClass ()

def tearDown(self):
import myclass
if hasattr(self, testobj):
del self.testobj
myclass._extmod = self.real_extmo d

This can be less intrusive than passing the mock object to a constructor,
but it depends very much on the way the objects are used: changing global
state for a unit test is a risky business, for example if an exception is
thrown then tearDown would be called *before* your __del__ method is
invoked. You can work round this by ensuring that the _extmod value is
saved in your instance but that takes you pretty much back to André Malo's
suggestion.

BTW, accessing a global variable from a __del__ method is a bad idea
generally: there is no guarantee that the global variable will still be set
if __del__ is called during program exit.

Jul 18 '05 #3
Duncan Booth wrote:
Qiangning Hong wrote:

As you see, it is an OO wrapper on _extmod, which is a pyrex extension
module. The question is: how to unittest this class? As the _extmod
is hardware-dependent, I want to use a mock class to replace it in unit
test. But how can I let myclass in unittest to import the mock class?
Like the following:
Given: # file: myclass.py
import _extmod
class MyClass(object) :
def __init__(self):
self.handle = _extmod.open()
...


One other way to do your unit test stuff is:
# file: test_myclass.py

import sys, bogus_extmod # First, get the fake hardware
sys.modules['_extmod'] = bogus_extmod # then make that active

import myclass, unittest # and now do all you normally would do
...
class SimplestTests(u nittest.TestCas e):
...

Note that the "module switch" must happen very early (probably at
the top of the main program).

--Scott David Daniels
Sc***********@A cm.Org

Jul 18 '05 #4

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

Similar topics

3
1958
by: EricN | last post by:
I like to use unittest. However, when my QA Manager shows up in my cube and says "Give me evidence that all your unit tests passed", I have nothing to provide. I'd like to log the unittest results (verbose mode) somehow. I'm open: logger module, stdmsg redirect, whatever. Thanks.
0
1289
by: Danny Shevitz | last post by:
Why doesn't the following code snippet work? The error is ImportError: No module named myTestCase2 TIA, Danny %<--------------------------------------------------------------------
0
2054
by: Remy Blank | last post by:
Ok, here we go. I added the possibility for tests using the unittest.py framework to be skipped. Basically, I added two methods to TestCase: TestCase.skip(msg): skips unconditionally TestCase.skipIf(expr, msg): skips if expr is true These can be called either in setUp() or in the test methods. I also added reporting of skipped tests to TestResult, _TextTestResult and
1
1511
by: Thomas Heller | last post by:
I'm trying to integrate some doctest tests with unittest. The tests must be exposed as one or more subclasses of unittest.TestCase, so I'm collecting them with a call to doctest.DocTestSuite(), and then add them to a TestCase class I have created. The tests seem to run, but they always seem to succeed - I have no idea why. Any ideas? Thomas ---snip---
41
10295
by: Roy Smith | last post by:
I've used the standard unittest (pyunit) module on a few projects in the past and have always thought it basicly worked fine but was just a little too complicated for what it did. I'm starting a new project now and I'm thinking of trying py.test (http://codespeak.net/py/current/doc/test.html). It looks pretty cool from the docs. Is there anybody out there who has used both packages and can give a comparative review?
4
1475
by: ajikoe | last post by:
Hello I found something strange in my unittest : This code is ok (will report error ): class MyTest1(unittest.TestCase): def runTest(self): self.assertEqual(2,3) pass
3
3435
by: David Vincent | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hello I'm hoping to get some insight into a situation that seems odd to me. My Python experience is limited; I've just started using the unittest module. I've had some experience with unit test support in other languages.
2
2457
by: Oleg Paraschenko | last post by:
Hello, I decided to re-use functionality of "unittest" module for my purposes. More precisely, I have a list of folders. For each folder, code should enter to the folder, execute a command and assert the output. It's reasonable to use "unittest" here, but the problem is that "unittest" doesn't support (== I haven't found how) dynamic creation of tests. I thought it would be very easy, but due to lack of closures in Python (more...
0
2317
by: Chris Fonnesbeck | last post by:
I have built the following unit test, observing the examples laid out in the python docs: class testMCMC(unittest.TestCase): def setUp(self): # Create an instance of the sampler self.sampler = DisasterSampler()
0
9645
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9952
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8976
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6740
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2880
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.