python 如何为这个模拟的上下文管理器和ZipFile编写一个正确的测试?

f1tvaqid  于 2023-01-29  发布在  Python
关注(0)|答案(1)|浏览(110)

我应该如何编写这个测试?我已经尝试了列出的各种选项,但每个选项都返回相同的失败测试:

import zipfile
from mock import Mock, patch    

def unzip_file(fp):
    with zipfile.ZipFile(fp, 'r') as z:
        z.extractall('dir')
    
    
@patch('zipfile.ZipFile')
def test_unzip_file(m_zipfile):

    # I have tried the following...
    
    # m_zipfile.__enter__.extractall = Mock()
    # m_zipfile.extractall = Mock()
    # m_zipfile.return_value.__enter__.return_value = Mock()
    m_zipfile.return_value.__enter__.return_value.extractall = Mock()

    unzip_file('test')

    m_zipfile.assert_called_with('test', 'r')  # this test passes
    m_zipfile.extractall.assert_called_with('dir')  # this test fails

我尝试使用this answer作为指导,但我仍然不知道如何正确地做到这一点。我们代码中的实际函数更复杂,有额外的参数,但我尝试首先从基础开始。
失败...

E           AssertionError: expected call not found.
E           Expected: extractall('dir')
E           Actual: not called.
qco9c6ql

qco9c6ql1#

已经非常接近了,只需要在上下文管理器中引用mock来进行Assert

@patch('zipfile.ZipFile')
def test_unzip_file(m_zipfile):
    m_extractall = Mock()
    m_zipfile.return_value.__enter__.return_value.extractall = m_extractall

    unzip_file('test')

    m_zipfile.assert_called_with('test', 'r')  # this test passes
    m_extractall.assert_called_with('dir') # and this one does, too

相关问题