Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-test methods in a Python TestCase

Ok, as Google search isn't helping me in a while (even when using the correct keywords).

I have a class extending from TestCase in which I want to have some auxiliary methods that are not going to be executed as part of the test, they'll be used to generate some mocked objects, etc, auxiliary things for almost any test.

I know I could use the @skip decorator so unittest doesn't run a particular test method, but I think that's an ugly hack to use for my purpose, any tips?

Thanks in advance, community :D

like image 441
victorcampos Avatar asked Aug 05 '11 18:08

victorcampos


People also ask

How do you skip a test case in Python?

It is possible to skip individual test method or TestCase class, conditionally as well as unconditionally. The framework allows a certain test to be marked as an 'expected failure'. This test will 'fail' but will not be counted as failed in TestResult. Since skip() is a class method, it is prefixed by @ token.

How do you write a test case in Python?

Create a class called TestSum that inherits from the TestCase class. Convert the test functions into methods by adding self as the first argument. Change the assertions to use the self. assertEqual() method on the TestCase class.

How do you write test cases for exceptions in Python?

There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.


2 Answers

I believe that you don't have to do anything. Your helper methods should just not start with test_.

like image 58
J Lundberg Avatar answered Oct 13 '22 07:10

J Lundberg


The only methods that unittest will execute [1] are setUp, anything that starts with test, and tearDown [2], in that order. You can make helper methods and call them anything except for those three things, and they will not be executed by unittest.

You can think of setUp as __init__: if you're generating mock objects that are used by multiple tests, create them in setUp.

def setUp(self):     self.mock_obj = MockObj() 

[1]: This is not entirely true, but these are the main 3 groups of methods that you can concentrate on when writing tests.

[2]: For legacy reasons, unittest will execute both test_foo and testFoo, but test_foo is the preferred style these days. setUp and tearDown should appear as such.

like image 24
Brian Riley Avatar answered Oct 13 '22 07:10

Brian Riley