Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use Python unit test assertions outside of a TestCase?

I need to create a fake helper class to be used in unit tests (injected into tested classes). Is there some way to use TestCase assertions in such class?

I would like to use the assertions for some common checks performed by the Fake class. Something like:

class FakeFoo(object):    def do_foo(self, a, b):     assertNotNull(a)     ... 
like image 737
Jan Wrobel Avatar asked Aug 06 '13 15:08

Jan Wrobel


People also ask

Why are assertions used in unit testing Python?

Python testing framework uses Python's built-in assert() function which tests a particular condition. If the assertion fails, an AssertionError will be raised. The testing framework will then identify the test as Failure. Other exceptions are treated as Error.


1 Answers

You can create a instance of unittest.TestCase() and call the methods on that.

import unittest  tc = unittest.TestCase() tc.assertIsNotNone(a) 

On older Python versions (Python 2.7 and earlier, 3.0, 3.1) you need to you pass in the name of an existing method on the class TestCase class (normally it's passed the name of a test method on a subclass). __init__ will do in this case:

tc = unittest.TestCase('__init__') tc.assertIsNotNone(a) 

However, you are probably looking for a good Mock library instead. mock would be a good choice.

Another option is to use pytest, which augments assert statements to provide the same or more context as unittest.TestCase() assertion methods; you'd simply write assert a is not None.

like image 162
Martijn Pieters Avatar answered Sep 23 '22 19:09

Martijn Pieters