79113202

Date: 2024-10-22 09:00:15
Score: 1
Natty:
Report link

I got something like this to work in my code using a singleton instance. I hope this resembles what you are looking for. I did not test your code because there is some API call involved (allegedly), but a different version of this worked on my computer.

import unittest

class TestFoo(unittest.TestCase):

    # Singletons have a use after-all
   _instance = None

   def __new__(cls, *args, **kwargs):
       if not cls._instance:
           cls._instance = super().__new__(cls)
       return cls._instance

    @classmethod
    def setUpClass(cls):
        cls.foo = cls.make_foo(name='bar')
        # How would I assert that cls.foo['name'] == 'bar'?
        # The following does not work, as the assertEquals function is not a class method
        # cls.assertEquals(cls.foo['name'], 'bar')
        cls._instance.assertEquals(cls.foo['name'], 'bar')

    @classmethod
    def make_foo(cls, name):
        # Calls a POST API to create a resource in the database
        return {'name': name}

    def test_foo_0(self):
        # Do something with cls.foo
        pass

    def test_foo_1(self):
        # do something else with cls.foo
        pass

P.S. If somebody else would like to test this code and subsequently clean up my answer, I would be grateful to you.

Reasons:
  • RegEx Blacklisted phrase (2): I would be grateful
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Leonid