verify the return value of a function
Roy Smith
roy at panix.com
Fri Jan 20 09:24:04 EST 2012
In article <mailman.4872.1327005963.27778.python-list at python.org>,
Jabba Laci <jabba.laci at gmail.com> wrote:
> Hi,
>
> In a unit test, I want to verify that a function returns a
> cookielib.LWPCookieJar object. What is the correct way of doing that?
jar = my_function_being_tested()
self.assertIsInstance(jar, cookielib.LWPCookieJar)
That works in 2.7. If you're using something older than 2.7, you'll
need to do:
self.assertTrue(isinstance(jar, cookielib.LWPCookieJar)
Alternatively, just download the 2.7 version of unittest and use that
(it works fine with 2.6, not sure about earlier than that).
> 3) isinstance(return_value, cookielib.LWPCookieJar) seems to be the
> best way, however somewhere I read that using isinstance is
> discouraged
Where did you read that, and in what context?
Compared to type(), isinstance() is an improvement because it correctly
handles subclasses. If you want a LWPCookieJar, you should be happy to
have somebody give you a subclass of LWPCookieJar (assuming they
correctly implemented the interface). Thus says the Church of Most
Corpulent Staticness and Type Bondage.
On the other hand, there are some (adherents of the Most Holy and
Loquacious Church of Duck Typing) who would say that testing for class
at all is a sin, and what you want to do is test that the object being
tested has the methods and attributes you expect.
Me, I'm somewhere in between. I believe that pinching it and seeing
what the quack sounds like is usually the right thing to do. On the
other hand, if you want to demand to see its Certificate of Duckiness,
you have a right to do that too.
More information about the Python-list
mailing list