473,794 Members | 2,804 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unittest.TestCa se, lambda and __getitem__

So, GvR said a few times that he would like to get rid of lambda in
Python 3000. Not to start up that war again, but I'm trying to
eliminate unnecessary lambdas from my code, and I ran into a case
using unittest.TestCa se that I don't really know how to deal with.

Previously, I had written some code like:

self.assertRais es(ValueError, lambda: method(arg1, arg2))

This was a simple fix because assertRaises takes *args and **kwds, so
I fixed it to look like:

self.assertRais es(ValueError, method, arg1, arg2)

which is much cleaner anyway (and what I should have been doing from
the start). Where I get uneasy is when I run into code like:

self.assertRais es(ValueError, lambda: obj[index])

Presumably, I could write this as:

self.assertRais es(ValueError, obj.__getitem__ , index)

I guess this makes me uneasy because I'm not entirely certain that
obj[item] is *always* translated to obj.__getitem__ (index). Is it?
That is, is there any way that obj[item] would get translated into a
different method call?

Or is there a better/clearer way of handling this kind of test case?

Thanks,

Steve
--
You can wordify anything if you just verb it.
- Bucky Katt, Get Fuzzy
Jul 18 '05 #1
7 2298
Steven Bethard <st************ @gmail.com> wrote:
...
Previously, I had written some code like:

self.assertRais es(ValueError, lambda: method(arg1, arg2))

This was a simple fix because assertRaises takes *args and **kwds, so
I fixed it to look like:

self.assertRais es(ValueError, method, arg1, arg2)

which is much cleaner anyway (and what I should have been doing from
Agreed.
the start). Where I get uneasy is when I run into code like:

self.assertRais es(ValueError, lambda: obj[index])

Presumably, I could write this as:

self.assertRais es(ValueError, obj.__getitem__ , index)

I guess this makes me uneasy because I'm not entirely certain that
obj[item] is *always* translated to obj.__getitem__ (index). Is it?
Yes.
That is, is there any way that obj[item] would get translated into a
different method call?
No.
Or is there a better/clearer way of handling this kind of test case?


Sure:

def wrong_indexing( ): return obj[index]
self.assertRais es(ValueError, wrong_indexing)

Whatever you can do with self.assertRais es(X, lambda: YZT) you can
(essentially idenfically) do with the two statements:

def anyname(): return YZT
self.assertRais es(X, anyname)

If you have a series of slightly different lambdas on several
assertRaises calls, you can reuse the same name (if that makes sense),
since another def for the same name simply rebinds the name, just like
multiple successive assignments to the same name would. Often you may
respect "once, and only once" better by factoring several lambdas into a
single def with an argument or two, of course. But for a mechanical
transformation changing each lambda into one def works just fine, and I
think it's preferable in terms of reliability to delving into internals
to find out what special methods get called when.

Besides, the delving approach may be far from trivial if you ever try to
translate something like lambda:x+y since in THAT case you cannot
necessarily tell what method gets called on what object (__add__ on x,
or __radd__ on y?) -- here you might try operator.add, but what then
about lambda:x+y*z ...?
Alex

Jul 18 '05 #2
Alex Martelli <aleaxit <at> yahoo.com> writes:
Steven Bethard <steven.betha rd <at> gmail.com> wrote:
Or is there a better/clearer way of handling this kind of test case?


Sure:

def wrong_indexing( ): return obj[index]
self.assertRais es(ValueError, wrong_indexing)


Yeah, I guess I was just begging someone to give me that response. ;)

First, I have to mention that I'd probably have to write your code as

def wrong_indexing( ):
return obj[index]
self.assertRais es(ValueError, wrong_indexing)

because GvR has also commented that he wishes he hadn't allowed the one-
line "if: statement" syntax, so by analogy, I assume he'd also rather no one-
line def statement. So I'm stuck replacing a single line with three... I was
hoping to avoid this... (Of course, if I have a bunch of obj[index] type
calls, I can average the additional line cost over all of these by making the
function suitably general.)

Regardless, your analogy between obj[index] and an arbitrary mathematical
expression was helpful. It clarifies that, what I really want is an anonymous
code block...

Hmm... Well, if this is really the only option, I'll probably leave these
lambdas until I absolutely have to remove them...

Steve

Jul 18 '05 #3
Steven Bethard <st************ @gmail.com> wrote:
Alex Martelli <aleaxit <at> yahoo.com> writes:
Steven Bethard <steven.betha rd <at> gmail.com> wrote:
Or is there a better/clearer way of handling this kind of test case?
Sure:

def wrong_indexing( ): return obj[index]
self.assertRais es(ValueError, wrong_indexing)


Yeah, I guess I was just begging someone to give me that response. ;)

First, I have to mention that I'd probably have to write your code as

def wrong_indexing( ):
return obj[index]
self.assertRais es(ValueError, wrong_indexing)

because GvR has also commented that he wishes he hadn't allowed the one-
line "if: statement" syntax, so by analogy, I assume he'd also rather no one-
line def statement. So I'm stuck replacing a single line with three... I was


I don't think the two issues are comparable. Consider the PEP:

http://www.python.org/peps/pep-3000.html

which, while of course still very tentative, DOES express Guido's
current plans for the future, non-backwards-compatible Python 3000.

"The lambda statement" is first on the list of things "to be removed".
(Of course, there IS no such thing -- it's not a statement -- but I hope
that's just a minor error in the PEP;-).

There is no indication on the PEP that Guido means to remove the ability
to use a single line such as def name(): return 23. The PEP does pick
up many specific changes coming from the 'Regrets' document,
http://www.python.org/doc/essays/ppt...honRegrets.pdf , and
specifically points to that document; but the PEP does not mention as
planned changes any of the lexical issues in the Regrets document (use
of \ for continuation, one-line if, use of tabs). Until further notice
I think this means these lexical aspects aren't going away.
hoping to avoid this... (Of course, if I have a bunch of obj[index] type
calls, I can average the additional line cost over all of these by making the
function suitably general.)

Regardless, your analogy between obj[index] and an arbitrary mathematical
expression was helpful. It clarifies that, what I really want is an anonymous
code block...
It generally is: lambda isn't a block and def isn't anonymous -- given
the tiny investment required to cook up a name for def, I think this
means def is much closer than lambda to what you want. When you change
lambdas to defs you often find that the modest effort of naming is
actually USEFUL, since it helps clarify your code, and sometimes you get
to generalize and better apply "once and only once".

All in all I think changing lambdas into defs is a worthy endeavour and
enhances your code. And if it should ever turn out in the future that
you do need a line break after the : in "def name(): ...", it's a
trivial and totally mechanical transformation with any editor (or an
auxiliary Python script), no effort at all. So I wouldn't let that
distant prospect worry me in the slightest.

Hmm... Well, if this is really the only option, I'll probably leave these
lambdas until I absolutely have to remove them...


I've never seen a syntax proposed for an "anonymous def" that Guido
would find in the least acceptable, if that's what you mean. I still
think that perfectly ordinary defs are fine, and better than lambdas,
but of course it's your code so it's your decision.
Alex
Jul 18 '05 #4
Steven Bethard <st************ @gmail.com> wrote:
self.assertRais es(ValueError, lambda: obj[index])

Presumably, I could write this as:

self.assertRais es(ValueError, obj.__getitem__ , index)


I'm with you, I don't like the idea of calling __getitem__ directly,
because you're not testing what you want to test; you're testing
something one step removed. Yes, it's a small step, but the idea in
unit testing is to test as small a thing as possible.

I think you need to just create a little function and call it:

def tryIndex (object, index):
return obj [index]

self.assertRais es (ValueError, tryIndex, object, index)

Another possibility would be:

self.assertRais es (ValueError, eval ("object [index]"))

From a readability/understandabili ty standpoint, I think I like the eval
version better.
Jul 18 '05 #5
Roy Smith wrote:
.... I think you need to just create a little function and call it:

def tryIndex (object, index):
return obj [index]


For python 2.4 and beyond, the function is called operator.getite m,
so I'd call it getitem.

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

Jul 18 '05 #6
Alex Martelli <aleaxit <at> yahoo.com> writes:

There is no indication on the PEP that Guido means to remove the ability
to use a single line such as def name(): return 23.
Yeah, I noticed the if thing wasn't in the PEP, but it is in the Wiki at
http://www.python.org/moin/Python3_2e0. 'Course the Wiki is really just
things he's been quoted as saying -- presumably the PEP is thing that he's
been quoted as saying and intends to pursue...

Regardless, I personally can't bring myself to write one-line defs. ;)
All in all I think changing lambdas into defs is a worthy endeavour and
enhances your code.
Yeah, I actually did end up changing some of them. For example, one of my
testing methods now looks something like:

def getitem(obj, item):
return obj[item]

self.assertRais es(IndexError, getitem, myobj, -10)
self.assertRais es(IndexError, getitem, myobj, 9)
....
self.assertRais es(IndexError, getitem, myobj2, -5)
self.assertRais es(IndexError, getitem, myobj2, 4)
....

It does make sense in situations like this when you're repeating the same kind
of code a number of times, and because it's apparent from the code that
getitem does in fact execute obj[item], I feel more comfortable with this than
something like operator.getite m where I can't see what code is really executed.
And if it should ever turn out in the future that
you do need a line break after the : in "def name(): ...", it's a
trivial and totally mechanical transformation. ..


Good point.
Hmm... Well, if this is really the only option, I'll probably leave these
lambdas until I absolutely have to remove them...


I've never seen a syntax proposed for an "anonymous def" that Guido
would find in the least acceptable, if that's what you mean.


No, I wasn't actually expecting anonymous defs. They've come up so many times
without ever being accepted that I expect they won't ever make it into the
language. All-in-all, I don't really consider this a loss. Really,
assertRaises is the only time I've really wanted them, and only because
testing code often has lots of special cases that don't necessarily generalize
well.

STeve

Steve

Jul 18 '05 #7
Scott David Daniels <Sc***********@ Acm.Org> wrote:
Roy Smith wrote:
.... I think you need to just create a little function and call it:

def tryIndex (object, index):
return obj [index]


For python 2.4 and beyond, the function is called operator.getite m,
so I'd call it getitem.


It's named just the same way in 2.3:

kallisti:~ alex$ python2.3
Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright" , "credits" or "license" for more information.
import operator
operator.getite m <built-in function getitem>


What's new in 2.4 is operator.itemge tter, a subtle higher-order
function...
Alex
Jul 18 '05 #8

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

Similar topics

12
2586
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
1261
by: Tero Saarni | last post by:
Hi, I have a module with several test case classes which each have several test methods: class Foo(unittest.TestCase): def testMethod1(self): def testMethod2(self): class Bar(unittest.TestCase):
0
1290
by: Danny Shevitz | last post by:
Why doesn't the following code snippet work? The error is ImportError: No module named myTestCase2 TIA, Danny %<--------------------------------------------------------------------
3
1988
by: Jan Decaluwe | last post by:
I'm working on a unit test for a finite state machine (FSM). The FSM behavior is specified in a dictionary called transitionTable. It has a key per state with a tuple of possible transitions as the corresponding value. A transition is defined as a number of input values, a next state, and a documentation string. I want to test each possible transition in a separate test method. For a particular transition, a test method could look as...
8
1826
by: Remy Blank | last post by:
Hello unittest users, In a project I am working on, I have a series of tests that have to be run as root, and others as a normal user. One solution is to separate the tests into two different files, and run the right one. I don't like this too much, as I prefer to group tests by "function". Another solution is to build the test suite differently, depending
0
2055
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
1514
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---
5
3577
by: paul kölle | last post by:
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
0
2319
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
9672
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
9519
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
10213
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
10163
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
10000
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...
1
7538
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
6779
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
5436
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...
1
4113
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

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.