如何使用@pytest.fixture测试写入文件操作

问题描述 投票:0回答:1

我正在用 python 练习单元测试,但遇到了一个问题 我有一个包含读/写文件操作的模块

我的项目结构是这样的

。名称_项目:

    --src
        -palindromoClass.py
        -lerEscreveArquivo.py
        -main.py
    --tests
        -test_palindromo.py
import os

def abreArquivo(nomeArquivo:str)-\>list\[str\]:

    if not os.path.exists(nomeArquivo):
        raise Exception("Arquivo inexistente")
    
    arquivo = open(nomeArquivo,"r")
    
    return arquivo.readlines()

def escreveArquivo(nomeArquivo:str, entradaDado:str)-\>None:

    with open(nomeArquivo,"a") as file:
        file.write(entradaDado)
        file.write("\n")
        file.close()

测试文件:

import pytest
from src.lerEscreveArquivo import *
from src.palindromoClass import *
from unittest.mock import MagicMock
from pytest import raises

@pytest.fixture()
def mock_open(monkeypatch):
    mock_file = MagicMock()
    mock_file.readlines = MagicMock(return_value = "test line")
    mock_open = MagicMock(return_value = mock_file)
    monkeypatch.setattr("builtins.open",mock_open)
    return mock_open

def test_LerArquivo(mock_open, monkeypatch):
    mock_exists = MagicMock(return_value = True)
    monkeypatch.setattr("os.path.exists",mock_exists)
    result = abreArquivo("blah")
    mock_open.assert_called_once_with("blah","r")
    assert result == "test line"

def test_throwsExceptionWithBadFile(mock_open, monkeypatch):
    mock_exists = MagicMock(return_value = False)
    monkeypatch.setattr("os.path.exists",mock_exists)
    with raises(Exception):
        result = abreArquivo("blah")

我的问题是如何进行单元测试:

def escreveArquivo(nomeArquivo:str, entradaDado:str)->None: 

?? 我在互联网上进行了长时间的搜索,但我找不到正确测试此功能的方法 答案涵盖的内容不适用于这种情况

我打算构建一个可以使用@pytest.fixture并设置模拟操作和monkeypatch属性的测试

python mocking pytest
1个回答
0
投票

这可能就是你想要的

import pytest
import builtins
from unittest.mock import mock_open

def abreArquivo(nomeArquivo:str)->list[str]:
    try:
        with open(nomeArquivo,"r") as arquivo:
            return arquivo.readlines()
    except FileNotFoundError as e:
        raise RuntimeError("Arquivo inexistente") from e


def test_LerArquivo(monkeypatch):
    m = mock_open(read_data="test line\n")
    monkeypatch.setattr(builtins, "open", m)
    result = abreArquivo("blah")
    m.assert_called_once_with("blah","r")
    assert result == ["test line\n"]
© www.soinside.com 2019 - 2024. All rights reserved.