2017-06-06 16 views
1

我有一個測試案例,在setUp中,我創建了一個對象,我想在模塊uuid中模擬函數uuid4。現在如何在測試用例中模擬uuid代?

TEST_UUIDS = ['uuid_{}'.format(i) for i in range(10000)] 
UUID_POOL = iter(TEST_UUIDS) 

def generate_uuid() -> str: 
    return next(UUID_POOL) 

class MyTestCase(TestCase): 

    def setUp(self, **kwargs): 
     self._create_my_object 

    @patch.object(uuid, 'uuid4', generate_uuid) 
    def _create_my_object(self): 
     # Create an object using a uuid 

我的問題是,當我運行寫兩個測試案例,創建對象第二次,它得到其他的UUID是第一次。因此,結果取決於測試類中測試用例的數量和它們運行的​​順序,這是我不想要的。

  • 這是嘲笑uuid發電機的最好方法嗎?
  • 如何在每次setUp(或tearDown)調用時重置或重新創建迭代器?

回答

2

答案比我想的要簡單:只是不要使用迭代器!相反,請將uuids列表設置爲模擬的side_effect。在`side_effect`

TEST_UUIDS = ['uuid_{}'.format(i) for i in range(10000)] 

class MyTestCase(TestCase): 

    def setUp(self, **kwargs): 
     self._create_my_object 

    @patch.object(uuid, 'uuid4', side_effect=TEST_UUIDS) 
    def _create_my_object(self): 
     # Create an object using a uuid 
+0

更多細節可以在這裏找到:https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect –

相關問題