Вопрос

So I am trying to setup a unittest for a threaded class in python

The class looks like this:

@Singleton
class EventManager(threading.Thread):

    def __init__(self):
        self.__eventDict = {}
        self.__eventDictLock = threading.Lock()
        self.__eventQueue = Queue()
        self.__subscriberList = []
        threading.Thread.__init__(self)

    def run(self):
        while(True):
            if self.__eventQueue.qsize() > 0:
                self.__runEvent()
            else:
                time.sleep(1)

My unittest looks like this:

eventManager = EventManager.Instance()
eventManager.start()

class EventManagerTest(unittest.TestCase):

    #pre-test initialization
    def setUp(self):
        pass

    #post-test destruction
    def tearDown(self):
        pass

    def testRegisterEvent(self):
        global eventManager
        logger.debug("Entering testRegisterEvent()")

        eventManager.registerEvent("MyEvent")

        logger.debug("testRegisterEvent() appears to have successfully registered")
        self.assertIn("MyEvent", eventManager.__subscriberList)
        self.assertFalse( eventManager.__eventDict["MyEvent"])

And I'm getting an error like this:

ERROR: testRegisterEvent (__main__.EventManagerTest)
Traceback (most recent call last):
File "EventManager_Test.py", line 59, in testRegisterEvent
  self.assertIn("MyEvent", eventManager.__eventDict)
AttributeError: 'EventManager' object has no attribute '\_EventManagerTest\__eventDict'

Where is the _EventManagerTest__eventDict attribute coming from? That is not the attribute I'm calling and it's preventing me from running a unit test.

Это было полезно?

Решение

As __eventDict starts with two underscore, it is a private attribute, therefore its name is “mangled”, that's why the name changed.

The problem is not related to unittest, it is just that you are trying to access a private attribute.

To solve your problem, remove one (or two) underscore(s) at the beginning of the name of __eventDict to make it protected (or public).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top