簡體   English   中英

Python Configparser在單元測試下找不到部分?

[英]Python Configparser cannot find section under Unittest?

所以我必須測試一個配置文件。 在此配置文件中,將初始化ConfigParser實例,然后加載配置文件。

在單元測試中,我導入了此解析器文件,然后嘗試讀取此ConfigParse實例的節點。 但是隨后引發了一個錯誤,即找不到該節。

怎么會? 有辦法解決嗎?

編輯:所以單元測試只是導入配置文件。 配置文件的名稱稱為config。 該實例稱為p_config。在一個測試案例中,該實例的名稱如下:

config.p_config.get('section1','a')

配置文件看起來很標准。

import ConfigParser
p_config = ConfigParser.SafeConfigParser()
p_config.read("xxx.cfg")

所以我的配置文件看起來很像普通的Windows配置:

[section1]
a = 1
b = 2
[section2]
c = 2
d = 4

它引發的錯誤只是表明找不到部分:

ConfigParser.NoSectionError: No section: 'section1'

UnitTest的內容:

class TestConfigFile(TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass


    def test_example(self):
        print global_path_config.get('section1', 'a')

聽起來您正在設置測試配置對象,而沒有實際提供配置文件供測試讀取。

我假設您正在使用python unittest模塊。

您的命令行與運行項目和運行測試有何不同? 命令行可能是個問題。

例如,如果您使用python /path/to/file.py <--options> config.ini啟動程序,並使用python -m unittest /path/to/config/unittest -v啟動單元測試,則您的配置文件永遠不會被讀取。

setUp(self):您將需要使用配置文件位置來初始化對象。 我喜歡寫在很短的,假的配置文件setUp ,所以我可以很容易去除tearDown ,知道它究竟是如何與我的測試,不污染我的工作配置文件。

如果可以的話,我建議您放棄ConfigParser。 使用json文件進行配置

import json
from collections import OrderedDict

def read_config(file_json):
    with open(file_json, 'r') as filename:
        config = filename.read()
    return json.loads(config, object_pairs_hook=OrderedDict)

def write_config(config, file_json):
     data = json.dumps(config, indent=4)
     with open(file_json, 'w') as filename:
         filename.write(data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM