Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a re-usable (parametrized) unittest.TestCase method [duplicate]

Possible Duplicate:
How to generate dynamic (parametrized) unit tests in python?

I'm writing tests using the unittest package, and I want to avoid repeated code. I am going to carry out a number of tests which all require a very similar method, but with only one value different each time. A simplistic and useless example would be:

class ExampleTestCase(unittest.TestCase):      def test_1(self):         self.assertEqual(self.somevalue, 1)      def test_2(self):         self.assertEqual(self.somevalue, 2)      def test_3(self):         self.assertEqual(self.somevalue, 3)      def test_4(self):         self.assertEqual(self.somevalue, 4) 

Is there a way to write the above example without repeating all the code each time, but instead writing a generic method, e.g.

    def test_n(self, n):         self.assertEqual(self.somevalue, n) 

and telling unittest to try this test with different inputs?

like image 632
astrofrog Avatar asked Nov 04 '09 20:11

astrofrog


1 Answers

Some of the tools available for doing parametrized tests in Python are:

  • Nose test generators (only for function tests, not TestCase classes)
  • nose-parametrized by by David Wolever (also for TestCase classes)
  • Unittest template by Boris Feld
  • Parametrized tests in py.test
  • parametrized-testcase by Austin Bingham
  • DDT (Data Driven Tests) by Carles Barrobés, for UnitTests
like image 94
akaihola Avatar answered Oct 04 '22 10:10

akaihola