473,594 Members | 2,663 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Questions on unittest behaviour

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.tearDo wn() 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, ie, a multi-part setUp():
def setUp(self)
lock_file(testf ile) # open_socket(), connect_to_data base(), etc

something_that_ raises_an_excep tion()

def tearDown(self):
if file_is_locked( testfile):
unlock_file(tes tfile)
In this pseudo-code example, the file won't be unlocked if some later
operation in setUp() raises an exception. I propose that
TestCase.run() be changed to always run tearDown(), even if setUp()
raise an exception.

I'm undecided if this is a new feature (so it should go in for 2.6) or
a bug fix; I'm leaning toward the latter.

2) The TestLoader.test MethodPrefix attribute currently allows anything
to be assigned to it, including invalid objects and the empty string.
While the former will cause errors to be raised when one of
TestLoader's loadTestsFrom*( ) methods is called, the empty string will
raise no exception; rather, the loadTestsFrom*( ) methods will
interpret every possible attribute as being a test method, e.g.,
meaning you get things like assertEqual(), failUnlessEqual (), etc,
when TestLoader.load TestsFromTestCa se() is run.

I propose protecting testMethodPrefi x with a property that validates
the assigned value, restricting input to non-empty instances of str. I
see this as a bug fix that should go in before 2.5-final.

3) TestLoader.load TestsFromTestCa se() accepts objects that are not
test cases and will happily look for appropriately-named methods on
any object you give it. This flexibility should be documented, or
proper input validation should be done (a bug fix for 2.5).

4) TestLoader.load TestsFromName() (and by extension,
loadTestsFromNa mes(), too) raises an AttributeError if the name is the
empty string because -- as it correctly asserts -- the object does not
contain an attribute named ''. I recommend that this be tested for and
ValueError be raised (bug fix for 2.5).

This of course leads into the question of how much input validation
should be done on these names. Should loadTestsFrom{N ame,Names}() make
sure the names are valid attribute names, or is this overkill?

5) When TestLoader.load TestsFrom{Name, Names}() are given a name that
resolves to a classmethod on a TestCase subclass, the method is not
invoked. From the docs:
The specifier name is a ``dotted name'' that may resolve either to a module, a test
case class, a TestSuite instance, a test method within a test case class, or a
callable object which returns a TestCase or TestSuite instance.
It is not documented which of these tests takes priority: is the
classmethod "a test method within a test case class" or is it a
callable? The same issue applies to staticmethods as well.
Once I get answers to these questions, I can finish off the last few
bits of the test suite and have it ready for 2.5-final.

Thanks,
Collin Winter
Aug 19 '06 #1
2 1612
In article <ma************ *************** ************@py thon.org>,
"Collin Winter" <co*****@gmail. comwrote:
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.tearDo wn() 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.
I look at setUp() as a constructor. It's the constructor's job to either
completely construct an object, or clean up after itself. With your
example:
def setUp(self)
lock_file(testf ile) # open_socket(), connect_to_data base(), etc

something_that_ raises_an_excep tion()

def tearDown(self):
if file_is_locked( testfile):
unlock_file(tes tfile)
It would be cleaner to just do:

def setUp(self):
lock_file()
try:
something_that_ raises_an_excep tion()
except
unlock_file()
raise
In this pseudo-code example, the file won't be unlocked if some later
operation in setUp() raises an exception. I propose that
TestCase.run() be changed to always run tearDown(), even if setUp()
raise an exception.
While this might simplify setUp() methods, it complicates tearDown()s,
because now they can't be sure what environment they're running in. One
way or the other, somebody has to deal with exceptions in setUp(). Keeping
the exception handling code as close to the source of the exception seems
like the right thing to do.
Aug 19 '06 #2

Collin Winter wrote:
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.tearDo wn() 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.
I'm undecided if this is a new feature (so it should go in for 2.6) or
a bug fix; I'm leaning toward the latter.
I strongly disagree. First, this is the documented behavior
for all xUnit ports (see jUnit), second, it's the responsibility
of a routine to clean up for itself.
2) The TestLoader.test MethodPrefix attribute currently allows anything
to be assigned to it, including invalid objects and the empty string.
While the former will cause errors to be raised when one of
TestLoader's loadTestsFrom*( ) methods is called, the empty string will
raise no exception; rather, the loadTestsFrom*( ) methods will
interpret every possible attribute as being a test method, e.g.,
meaning you get things like assertEqual(), failUnlessEqual (), etc,
when TestLoader.load TestsFromTestCa se() is run.

I propose protecting testMethodPrefi x with a property that validates
the assigned value, restricting input to non-empty instances of str. I
see this as a bug fix that should go in before 2.5-final.
Several points. First, since it's been this way since day one and
nobody has complained, it's not a bug. That means it's a feature,
and 2.5 is in a complete, absolute, utter, total and thorough
feature freeze. This is not the place to get Guido's attention. As
far as I'm aware, he doesn't read this newsgroup.

On the other hand, you might be working with the crew on
pythondev; I only read the summaries. If you are, then you
already know what I mentioned above. If you aren't, your
odds of getting a new test suite into 2.5 final are somewhere
on the far side of zero.
3) TestLoader.load TestsFromTestCa se() accepts objects that are not
test cases and will happily look for appropriately-named methods on
any object you give it. This flexibility should be documented, or
proper input validation should be done (a bug fix for 2.5).
I'm pretty sure I use this. Making it go away would cause
me to have to find another way around the misbegotten
prefix selection mechanism. There's a lot of discussion
around something that's called "behavior driven development"
which is neither here nor there other than that group of people
considers the whole notion of a name with a fixed element to
be a problem with constructing really meaningful test names.
4) TestLoader.load TestsFromName() (and by extension,
loadTestsFromNa mes(), too) raises an AttributeError if the name is the
empty string because -- as it correctly asserts -- the object does not
contain an attribute named ''. I recommend that this be tested for and
ValueError be raised (bug fix for 2.5).
Prior point about 2.5 being in a freeze. Take it to the pythondev
mailing list if you really want action. As far as I'm concerned,
this is a "so what." There are much deeper issues with unittest
than this.
This of course leads into the question of how much input validation
should be done on these names. Should loadTestsFrom{N ame,Names}() make
sure the names are valid attribute names, or is this overkill?
What _I_ want is a method of selecting tests from a class
that doesn't depend on pattern matching the name.
I've got it rigged to not do that, and I feel that my names
are now significantly better.
5) When TestLoader.load TestsFrom{Name, Names}() are given a name that
resolves to a classmethod on a TestCase subclass, the method is not
invoked. From the docs:
The specifier name is a ``dotted name'' that may resolve either to a module, a test
case class, a TestSuite instance, a test method within a test case class, or a
callable object which returns a TestCase or TestSuite instance.

It is not documented which of these tests takes priority: is the
classmethod "a test method within a test case class" or is it a
callable? The same issue applies to staticmethods as well.
These are all new since pyUnit (renamed to unittest for inclusion
into the standard library) was written. My viewpoint is that it's a
feature that's looking for a use case.

As I intimated above, my current practice is to not use the supplied
mechanism for locating tests. I don't use it for locating test classes
either.
Once I get answers to these questions, I can finish off the last few
bits of the test suite and have it ready for 2.5-final.
Answers? On this list? I'm not even sure you can get
coherent opinions here.

John Roth
>
Thanks,
Collin Winter
Aug 19 '06 #3

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

Similar topics

12
2572
by: Paul Moore | last post by:
One of the things I really dislike about Unittest (compared, say, to a number of adhoc testing tricks I've used in the past, and to Perl's "standard" testing framework) is that the testcase-as-a-class model tends to imply a relatively high granularity in testing. A good example of this comes from "Dive Into Python" (http://diveintopython.org) section 7.3. Here, the author has written a module which converts numbers to Roman numerals. The...
0
2036
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
1501
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
10260
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?
2
1223
by: Antoon Pardon | last post by:
I'm writing a class with a lot of dictionary like behaviour. I was wondering whether a unittest for dictionaries already exists somewhere so that I could use it as a start for a unittest for my class. -- Antoon Pardon
3
3424
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
2447
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
2303
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()
3
1969
by: Paul Moore | last post by:
My normal testing consists of a tests.py script using unittest, with the basic if __name__ == '__main__': unittest.main() incantation to get things going. But I now want to incorporate some other tests (specifically, a text file containing doctests) and I find that there is no gradual process
0
7882
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
8259
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...
1
8016
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
8244
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
6669
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
5836
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
5415
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();...
1
2391
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1487
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.