473,609 Members | 1,818 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unittest setup

hi all,

I noticed that setUp() and tearDown() is run before and after *earch*
test* method in my TestCase subclasses. I'd like to run them *once* for
each TestCase subclass. How do I do that.

thanks
paul

Sep 25 '05 #1
5 3566
paul kölle wrote:
hi all,

I noticed that setUp() and tearDown() is run before and after *earch*
test* method in my TestCase subclasses. I'd like to run them *once* for
each TestCase subclass. How do I do that.


Create a global/test instance flag.

Diez
Sep 25 '05 #2
Diez B. Roggisch wrote:
paul kölle wrote:
hi all,

I noticed that setUp() and tearDown() is run before and after *earch*
test* method in my TestCase subclasses. I'd like to run them *once* for
each TestCase subclass. How do I do that.

Create a global/test instance flag.


I'm not sure if I understood what you mean, I tried:

setup = 'down'

class BaseTest(unitte st.TestCase):
def setUp(self):
global setup
if setup == 'up':
print 'Not running setUp() again...'
return
...
all setup work goes here.
...
setup = 'up'
This didn't work, (tried to reset the flag in the last test* method to
'down', no dice)
and:

class BaseTest(unitte st.TestCase):
def __init__(self, ...):
unittest.TestCa se.__init__(sel f, ...)
self.setup = 'down'

def setUp(self):
if self.setup == 'up':
return
dowork
self.setup = 'up'

Failed also, I'm not sure why, __init__ was called way too often and
self.setup was always reset to 'down'. I finally gave up and created my
own method which I call in *every* test* method which is ugly, leads to
longer runtime and code duplication.
But at least it encouraged me to read the unittest docs more carefully.
Now I seem to understand that:

TestSuite.addTe st(TestCaseSubc lass('testSomet hing'))
TestSuite.addTe st(TestCaseSubc lass('testSomet hingOther'))

will create two instances of TestCaseSubclas s, so there is no way that
'testSomethingO ther' will ever see what 'testSomething' might have
created if all work is done with instance data right? Initially I
thought it goes like: "run setUp(), run all test* methods, run
tearDown()" and that is what the unittest docs call a "fixture"

<cite python 2.3 docs for unittest>
A test fixture represents the preparation needed to perform one or more
tests, and any associate cleanup actions.
</cite>

but further down:
<cite python 2.3 docs for unittest>
Each instance of the TestCase will only be used to run a single test
method, so a new fixture is created for each test.
</cite>

It seems to me my case is not that exotic, I thought it would be quite
natural to write the boilerplate stuff in setUp() and build on that to
step through the applications state with test* methods each building on
top of each other. Is that the wrong approach? Are there other
frameworks supporting such a style?

thanks
Paul

Sep 25 '05 #3
"paul kölle" <pa**@subsignal .org> wrote:

[snipped]

It seems to me my case is not that exotic, I thought it would be quite
natural to write the boilerplate stuff in setUp() and build on that to
step through the applications state with test* methods each building on
top of each other. Is that the wrong approach? Are there other
frameworks supporting such a style?


Yes, py.test: http://codespeak.net/py/current/doc/test.html.

George
Sep 26 '05 #4
[George Sakkis]
Yes, py.test: http://codespeak.net/py/current/doc/test.html.


The whole http://codespeak.net site contains many interesting projects,
which are all worth a good look!

However, there is a generic ``LICENSE`` file claiming copyrights on all
files, without explaining what the copyright conditions are. This file
also delegates copyright issues to individual files, which are usually
silent on the matter. Could this whole issue be clarified? Or did I
miss something I should not have?

--
François Pinard http://pinard.progiciels-bpi.ca
Sep 26 '05 #5
paul kölle wrote:
hi all,

I noticed that setUp() and tearDown() is run before and after *earch*
test* method in my TestCase subclasses. I'd like to run them *once* for
each TestCase subclass. How do I do that.


One way to do this is to make a TestSuite subclass that includes your startup and shutdown code.

For example I have some tests that rely on a webserver being started. I have a TestSuite that starts the server, runs the tests and stops the server. This way the server is only started once per test module. Here is the TestSuite class:

class CbServerTestSui te(unittest.Tes tSuite):
''' A test suite that starts an instance of CbServer for the suite '''
def __init__(self, testCaseClass):
unittest.TestSu ite.__init__(se lf)
self.addTest(un ittest.defaultT estLoader.loadT estsFromTestCas e(testCaseClass ))

def __call__(self, result):
CbServer.start( )
unittest.TestSu ite.__call__(se lf, result)
CbServer.stop()
I use it like this:

class MyTest(unittest .TestCase):
def testWhatever(se lf):
pass

def suite():
return CbServerTestSui te(MyTest)

if __name__=='__ma in__':
unittest.TextTe stRunner().run( suite())
This runs under Jython (Python 2.1); in more recent Python I think you can override TestSuite.run() instead of __call__().

Kent
Sep 30 '05 #6

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

Similar topics

5
2312
by: Will Stuyvesant | last post by:
I have a unittest testfile like this: ----------------------- test_mod.py --------------------- import sys sys.path.append('..') import unittest import mod class Test_rmlutils(unittest.TestCase):
2
2911
by: JAWS | last post by:
I get this error message when trying to run a unittest test with a dynamically created test method: Traceback (most recent call last): File "unittest.py", line 215, in __call__ testMethod() TypeError: ?() takes no arguments (1 given) I have no clue as to where the 1 given argument comes from...
0
2038
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
3
1786
by: Qiangning Hong | last post by:
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()
0
2304
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()
2
1614
by: Collin Winter | last post by:
While working on a test suite for unittest these past few weeks, I've run across some behaviours that, while not obviously wrong, don't strike me as quite right, either. Submitted for your consideration: 1) TestCase.tearDown() is only run if TestCase.setUp() succeeded. It seems to me that tearDown() should always be run, regardless of any failures in setUp() or the test method itself. The case I'm considering is something like this,...
1
3521
by: winston.yang | last post by:
I've read that unittest.main() can take an optional argv argument, and that if it is None, it will be assigned sys.argv. Is there a way to pass command line arguments through unittest.main() to the setUp method of a class derived from unittest.TestCase? Thank you in advance. Winston
0
1228
by: Nikolaus Rath | last post by:
Hello, I have a number of conceptually separate tests that nevertheless need a common, complicated and expensive setup. Unfortunately, unittest runs the setUp method once for each defined test, even if they're part of the same class as in class TwoTests(unittest.TestCase): def setUp(self):
1
3808
by: Jean-Paul Calderone | last post by:
On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath <nikolaus@rath.orgwrote: class TwoTests(unittest.TestCase): setUpResult = None def setUp(self): if self.setUpResult is None: self.setUpResult = computeIt() ...
0
8133
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
8083
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,...
0
8573
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8547
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8224
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
8406
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
7013
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...
1
6062
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5517
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();...

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.