首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中模拟configparser.ConfigParser读取方法?

如何在python中模拟configparser.ConfigParser读取方法?
EN

Stack Overflow用户
提问于 2021-08-20 15:40:48
回答 1查看 973关注 0票数 1

我正在和python一起工作,并且对它很陌生。我试图为我的类方法编写单元测试,在这个方法中,我们使用configparse来获取位于特定路径上的配置文件细节。

在进行单元测试时,它作为KeyError 上给了我一个错误

code解析器的代码类似于

代码语言:javascript
复制
 algor_conf = configparser.ConfigParser()
 self.algor_conf.read('./path')
 self.algor_conf['DynamicProgramingParamaters']['wealth_state_total']

有人能帮我嘲笑一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-21 04:35:18

这里有一些解决办法给你。您可以随意选择最适合您需要的6种(命名为test_mock1 to test_mock6)。

src.py

代码语言:javascript
复制
import configparser


class MyClass:
    def my_method(self):
        self.algor_conf = configparser.ConfigParser()
        self.algor_conf.read('./path')
        return self.algor_conf['DynamicProgramingParamaters']['wealth_state_total']

test_src.py

代码语言:javascript
复制
import configparser
from unittest.mock import patch

import pytest

from src import MyClass


def custom_get_item(key):
    if key == 'DynamicProgramingParamaters':
        return {'wealth_state_total': 'Just a test 3!'}
    else:
        raise KeyError(str(key))


class CustomConfigParser1(configparser.ConfigParser):
    def __getitem__(self, key):
        if key == 'DynamicProgramingParamaters':
            return {'wealth_state_total': 'Just a test 4!'}
        else:
            raise KeyError(str(key))


class CustomConfigParser2(configparser.ConfigParser):
    def read(self, filenames, *args, **kwargs):
        # Intercept the calls to configparser -> read and replace it to read from your test data
        if './path' == filenames:
            # Option 1: If you want to manually write the configuration here
            self.read_string("[DynamicProgramingParamaters]\nwealth_state_total = Just a test 5!")

            # Option 2: If you have a test configuration file
            # super().read("./test_path")
        else:
            super().read(filenames, *args, **kwargs)



@pytest.fixture
def amend_read(mocker):  # Requires https://pypi.org/project/pytest-mock/ but you can also change this to just use the builtin unittest.mock
    original_func = configparser.ConfigParser.read

    def updated_func(self, filenames, *args, **kwargs):
        # Intercept the calls to configparser -> read and replace it to read from your test data
        if './path' == filenames:
            # Option 1: If you want to manually write the configuration here
            self.read_string("[DynamicProgramingParamaters]\nwealth_state_total = Just a test 6!")

            # Option 2: If you have a test configuration file
            # original_func.read(self, "./test_path")

            return

        return original_func(self, filenames, *args, **kwargs)

    mocker.patch('configparser.ConfigParser.read', new=updated_func)


@patch('configparser.ConfigParser')
def test_mock1(config_parser):
    # If you just want to mock the configparser without doing anything to its processing results
    obj = MyClass()
    result = obj.my_method()
    print(result)


@patch('configparser.ConfigParser.__getitem__', return_value={'wealth_state_total': 'Just a test 2!'})
def test_mock2(config_parser):
    # Change the returned value of configparser['DynamicProgramingParamaters']['wealth_state_total']
    obj = MyClass()
    result = obj.my_method()
    print(result)


@patch('configparser.ConfigParser.__getitem__', side_effect=custom_get_item)
def test_mock3(config_parser):
    # Same as test_mock2 only that we instead used a function to write the return
    obj = MyClass()
    result = obj.my_method()
    print(result)


@patch('configparser.ConfigParser', side_effect=CustomConfigParser1)
def test_mock4(config_parser):
    # Same as test_mock3 only that we instead used a class to write the return
    obj = MyClass()
    result = obj.my_method()
    print(result)


@patch('configparser.ConfigParser', side_effect=CustomConfigParser2)
def test_mock5(config_parser):
    # If have a configuration file for your test data, use this.
    obj = MyClass()
    result = obj.my_method()
    print(result)


def test_mock6(amend_read):
    # Same as test_mock5 only that we instead used a function to write the return
    obj = MyClass()
    result = obj.my_method()
    print(result)

输出

代码语言:javascript
复制
$ pytest -rP
test_mock.py ......                                                                                                                                                                      [100%]

============================================================================================ PASSES ============================================================================================
__________________________________________________________________________________________ test_mock1 __________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
<MagicMock name='ConfigParser().__getitem__().__getitem__()' id='140151691208160'>
__________________________________________________________________________________________ test_mock2 __________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
Just a test 2!
__________________________________________________________________________________________ test_mock3 __________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
Just a test 3!
__________________________________________________________________________________________ test_mock4 __________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
Just a test 4!
__________________________________________________________________________________________ test_mock5 __________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
Just a test 5!
__________________________________________________________________________________________ test_mock6 __________________________________________________________________________________________
------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------
Just a test 6!
====================================================================================== 6 passed in 0.03s =======================================================================================
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68864769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档