2016-05-17 59 views
2

我有一個測試如下:如何使用mock_open和Python UnitTest裝飾器?

import mock 

# other test code, test suite class declaration here 

@mock.patch("other_file.another_method") 
@mock.patch("other_file.open", new=mock.mock_open(read=["First line", "Second line"]) 
def test_file_open_and_read(self, mock_open_method, mock_another_method): 
    self.assertTrue(True) # Various assertions. 

,我發現了以下錯誤:

TypeError: test_file_open_and_read() takes exactly 3 arguments (2 given)

我想指定我想與mock.mock_open被嘲笑其他文件的__builtin__.open方法而不是mock.MagicMock,這是patch裝飾器的默認行爲。我怎樣才能做到這一點?

回答

2

您錯過了open內建的參數create

@mock.patch("other_file.open", new=mock.mock_open(read=["First line", "Second line"], create=True) 
+0

修補builtins時,這不是必需的,文檔說「版本3.5中已更改:如果您在模塊中修補builtins,則不需要傳遞create = True,它將默認添加。我仍然得到同樣的錯誤。 – YPCrumble

1

應該使用new_callable而不是new。也就是說,

@mock.patch("other_file.open", new_callable=mock.mock_open) 
def test_file_open_and_read(self, mock_open_method): 
    # assert on the number of times open().write was called. 
    self.assertEqual(mock_open_method().write.call_count, 
        num_write_was_called) 

注意,我們傳遞的功能手柄mock.mock_opennew_callable,而不是生成的對象。這允許我們做來訪問write函數,就像mock_open顯示文檔中的示例一樣。