Search code examples
pythonnosenosetestsparameterized-unit-testnose-parameterized

How to access class property in decorator in Python?


I am trying to use a nose_parameterized test and want to use it for a unittest method.

from nose.tools import assert_equal
from nose_parameterized import parameterized
import unittest

Class TestFoo(unittest.TestCase):
      def setUp(self):
           self.user1 = "Bar"
           self.user2 = "Foo"

      @parameterized.expand([
               ("testuser1",self.user1,"Bar"),
               ("testuser2",self.user2,"Foo")
                ]
      def test_param(self,name,input,expected):
          assert_equal(input,expected)

But self is not defined in the decorator function. Is there a workaround for this? I know that I can use global class variables but I need to use variables in setUp.


Solution

  • One workaround would be to use a string containing the attribute name in the decorator, and getattr in the test function:

    @parameterized.expand([
               ("testuser1", "user1", "Bar"),
               ("testuser2", "user2", "Foo")
                ])
    def test_param(self, name, input, expected):
        assert_equal(getattr(self, input), expected)
    

    With this approach, test_param assumes that the value of its input argument is the attribute name whose value should be checked against expected.