Skip to content

Instantly share code, notes, and snippets.

@DMRobertson
Created September 30, 2021 11:09
Show Gist options
  • Save DMRobertson/40fe186843a327658cbee31bb381e1b2 to your computer and use it in GitHub Desktop.
Save DMRobertson/40fe186843a327658cbee31bb381e1b2 to your computer and use it in GitHub Desktop.
Class and instance attributes in unittest.TestCase
from unittest import TestCase
class DMRTest(TestCase):
class_count = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.instance_count = 0
def test_foo(self):
self.class_count += 1
self.instance_count += 1
print(f"foo {self.class_count=} {self.instance_count=}")
def test_bar(self):
self.class_count += 2
self.instance_count += 2
print(f"bar {self.class_count=} {self.instance_count=}")
def test_baz(self):
self.class_count += 4
self.instance_count += 4
print(f"baz {self.class_count=} {self.instance_count=}")
"""
This yields:
/home/dmr/workspace/synapse/env/bin/python /home/dmr/.local/share/JetBrains/Toolbox/apps/PyCharm-C/ch-0/212.4746.96/plugins/python-ce/helpers/pycharm/_jb_trialtest_runner.py --target tests.util.test_dmr.DMRTest
Testing started at 12:08 ...
Launching trial with arguments --reporter=teamcity tests.util.test_dmr.DMRTest in /home/dmr/workspace/synapse
-------------------------------------------------------------------------------
Ran 3 tests in 0.008s
PASSED (successes=3)
Process finished with exit code 0
bar self.class_count=2 self.instance_count=2
baz self.class_count=4 self.instance_count=4
foo self.class_count=1 self.instance_count=1
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment