views:

68

answers:

2

I have a utility class that stores methods that are useful for some unit test cases. I want these helper methods to be able to do asserts/fails/etc., but it seems I can't use those methods because they expect TestCase as their first argument ...

I want to be able to store the common methods outside of the testcase code and continue to use asserts in them, is that possible at all? They are ultimately used in testcase code.

I have something like:

unittest_foo.py:

import unittest
from common_methods import *
class TestPayments(unittest.TestCase):
 def test_0(self):
  common_method1("foo")

common_methods.py:

from unittest import TestCase
def common_method1():
    blah=stuff
    TestCase.failUnless(len(blah) > 5)
        ...
...

---> when the suite is run:

TypeError: unbound method failUnless() must be called with TestCase instance as first argument (got bool instance instead)
+1  A: 

Sounds like you want this, from the error at least ...

unittest_foo.py:

import unittest
from common_methods import *
class TestPayments(unittest.TestCase):
 def test_0(self):
  common_method1(self, "foo")

common_methods.py:

def common_method1( self, stuff ):
    blah=stuff
    self.failUnless(len(blah) > 5)
THC4k
+2  A: 

This is often accomplished with multiple inheritance:

common_methods.py:

class CommonMethods:
  def common_method1(self, stuff):
    blah=stuff
    self.failUnless(len(blah) > 5)
        ...
...

unittest_foo.py:

import unittest
from common_methods import CommonMethods
class TestPayments(unittest.TestCase, CommonMethods):
 def test_0(self):
  self.common_method1("foo")
Ned Batchelder
There is a convention to end names of such classes with "Mixin" e.g., CommonMethods -> TestMixin.
J.F. Sebastian