4

When using Python's built-in unittest, there are at least 2 different ways to organize class-level settings, using setUpClass() or just use old-school class member. When to use one, and when another?

class TestFoo(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.foo = Foo(...)

    def test_blah(self):
        self.foo.do_something()
        ...

VS

class TestFoo(unittest.TestCase):

    foo = Foo(...)

    def test_blah(self):
        self.foo.do_something()
        ...
RayLuo
  • 17,257
  • 6
  • 88
  • 73
  • Does this answer your question? [When should I use setUpClass and when \_\_init\_\_?](https://stackoverflow.com/questions/18056464/when-should-i-use-setupclass-and-when-init) – tuomastik Oct 12 '20 at 08:16
  • Nope, the question you referenced to was about `setUpClass()` VS `__init__()`. My question here was about `setUpClass()` VS class member (without even using a `__init__()`). – RayLuo Oct 12 '20 at 22:11

1 Answers1

-1

In fact, the 2 snippets in the question above work largely the same, except when you are going to use the @skipUnless(condition) decorator.

SETTINGS = json.load(...)

@unittest.skipUnless("foo" in SETTINGS, "skipped")
class TestFoo(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.foo = Foo(SETTINGS["foo"])
# If SETTINGS["foo"] is undefined,
# this entire test class would be skipped

VS

SETTINGS = json.load(...)

@unittest.skipUnless("foo" in SETTINGS, "skipped")
class TestFoo(unittest.TestCase):

    foo = Foo(SETTINGS["foo"])
# This line will always be executed,
# BEFORE the skipUnless(...),
# so if SETTINGS["foo"] is undefined,
# there will be a runtime error here
RayLuo
  • 17,257
  • 6
  • 88
  • 73
  • 1
    `setUpClass` is also procedural and can do more than just assign class attributes. – Peter Wood Sep 24 '18 at 07:07
  • Like what, @PeterWood? I'd love to upvote a more comprehensive answer to this question. – Chris Keefe Sep 03 '21 at 22:14
  • For more-complex setup processes, setUpClass may improve readability. The scoping allows clearer signaling about which variables are temporary (`some_var`) and which are available for use in TestCases (e.g. `cls.some_var`). – Chris Keefe Sep 03 '21 at 22:33
  • @ChrisKeefe I don't remember what I was thinking 3 hours ago let alone 3 years. – Peter Wood Sep 03 '21 at 23:38