亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

需要從 lxml.etree 模塊模擬 ElementTree 類的 write() 方法

需要從 lxml.etree 模塊模擬 ElementTree 類的 write() 方法

慕婉清6462132 2021-10-10 16:31:27
我正在編寫一個方法,該方法使用 lxml.etree 中 ElementTree 類的 write 方法。在編寫我的測試時,我想模擬一下,這樣單元測試就不會向我的驅動器寫一堆東西。我文件中的代碼看起來像這樣    # myapp\gla.py    from lxml.etree import Element, ElementTree    def my_func(element):        root = Element(element)        xml = ElementTree(root)        xml.write('path_to_file')測試看起來像這樣:    # tests\test_gla.py    from unittest import patch    from myapp.gla import my_func    @patch('myapp.gla.ElementTree.write')    def test_my_func(self, mock_write):        my_func('rootElement')        mock_write.assert_called_once()我明白了    Traceback (most recent call last):      File "C:\Anaconda2\envs\py36\lib\unittest\mock.py", line 1171, in patched        arg = patching.__enter__()      File "C:\Anaconda2\envs\py36\lib\unittest\mock.py", line 1243, in __enter__        original, local = self.get_original()      File "C:\Anaconda2\envs\py36\lib\unittest\mock.py", line 1217, in get_original        "%s does not have the attribute %r" % (target, name)    AttributeError: <cyfunction ElementTree at 0x000001FFB4430BC8> does not have the attribute 'write'
查看完整描述

2 回答

?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

找到了我自己的問題的答案。


像這樣重新編寫測試:


# tests\test_gla.py

from unittest import patch, MagicMock

from myapp.gla import my_func


@patch('myapp.gla.ElementTree')

def test_my_func(self, mock_write):

    mock_write().write = MagicMock()

    my_func('rootElement')

    mock_write().write.assert_called_once()


查看完整回答
反對 回復 2021-10-10
?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

ElementTree是一個函數,而不是一個類型。它返回一個類型的對象,_ElementTree它具有函數write。

我還沒有測試過這個(我不太了解/關于模擬的任何事情),但我懷疑

 @patch('myapp.gla._ElementTree.write')

應該可以工作(盡管您可能還需要_ElementTree自己導入)。


查看完整回答
反對 回復 2021-10-10
  • 2 回答
  • 0 關注
  • 343 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號