Slaknation
Slaknation

Reputation: 1926

Python: Adding to class variable in setUp not working as expected

class TestHead(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.num = 0

    def setUp(self):
        self.num += 1

    def test1(self):
        print self.num

    def test2(self):
        print self.num

output:

1
1

I don't understand. The setUp should be ran after each test and all it does is increment self.num Shouldn't it be

1
2

Upvotes: 0

Views: 63

Answers (1)

Paul Becotte
Paul Becotte

Reputation: 9977

In python, a class variable is shadowed by an instance variable on creation- so self.num is an instance variable initialized by the class value. You could access TestHead.num to get a class singleton.

Upvotes: 2

Related Questions