0

During testing, I would like to visualise a running enumeration of the tests. Example code:

import unittest
from functions import function_a, function_b

class TestFunctions(unittest.TestCase):

    counter = 0

    def test_function_a(self):
        self.counter += 1
        print(f"\nTest {self.counter}: 'function_a'"
        # some code to test function_a
        print("\t...done!")

    def test_function_b(self):
        self.counter += 1
        print(f"\nTest {self.counter}: 'function_b'"
        # some code to test function_b
        print("\t...done!")

if __name__ == "__main__":
    unittest.main()

Expected output:


Test 1: 'function_a'
        ...done!
.
Test 2: 'function_b'
        ...done!
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Actual output:


Test 1: 'function_a'
        ...done!
.
Test 1: 'function_b'
        ...done!
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

i.e., self.counter gets updated once in each method call, but I guess then it's being re-initialised each time in between method calls.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Stromael
  • 168
  • 1
  • 9
  • Have you tried using https://docs.python.org/3/library/unittest.html#setupclass-and-teardownclass – jonrsharpe Jan 17 '20 at 09:28
  • 3
    Your assumption is true. But you would be able to achieve the desired functionality when accessing the class attribute with TestFunctions.counter instead of self.counter – Felix Kleine Bösing Jan 17 '20 at 09:29
  • @FelixKleineBösing thanks! Why does this work? – Stromael Jan 17 '20 at 09:56
  • 1
    @Stromael Setting the attribute with self.counter doesn´t work because for each test_method a new object of the TestClass is initialized. You are accessing the instance attribute counter with self while TestFunctions.counter accesses the class attribute that is shared among all objects of the class TestFunctions and the class itself. For more information, see the post that is linked in the closing tag above your post. – Felix Kleine Bösing Jan 17 '20 at 10:05

0 Answers0