【问题标题】:How do I import a py module which reads data from a json file?如何导入从 json 文件读取数据的 py 模块?
【发布时间】:2023-03-18 21:20:02
【问题描述】:

我是 pytest 测试的新手,我正在尝试测试一个包含类和函数的 python 模块 main.py,它还读取一个静态 config.json 文件。当我为我的 pytest 导入主模块并运行我的测试时,我收到一个错误,即找不到 json 文件。我希望再次对我在 main.py 中定义的类运行一个简单的测试,并且不需要 config.json 数据。

我尝试将我的 pytest 放在项目目录的不同部分,但没有帮助。我还尝试从我的程序创建一个包,包括对 MANIFEST.in 文件中的 config.json 文件的引用,并且我的 config.json 文件与我的包一起安装,但我仍然遇到了与配置文件相同的问题找不到。

我的目录

Project
   src 
      code
         main.py
         config.json
         tests
            test_main.py

我的 pytest test_main.py:

import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')

import pytest
from main import Reservation

@pytest.mark.runme
def test_reservation():
    starttime = "2019-05-03 12:30"
    booktime = "2019-05-02 8:00"
    newreservation = Reservation("002", "manicure", "normal", starttime, booktime, 1, 30)
    assert newreservation.get_serv_name() == "manicure"

来自 main.py 第 436 行:

with open('config.json', 'rt') as fin:
    config = json.load(fin)
    business_name = config['business_name']

我希望能够从 main.py 导入 Reservation 类并对其运行测试,但我收到一个错误,即找不到 config.json 文件:

pytest 错误:

==================================== ERRORS ====================================
___________ ERROR collecting src/MiYE/tests/test_u01_load_clients.py ___________
test_main.py:6: in <module>
    from main import Reservation
../main.py:436: in <module>
    with open('config.json', 'rt') as fin:
E   FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
=============================== warnings summary ===============================

顺便说一句,当我将 main.py 作为常规 python 文件(不是导入的模块)运行时,我可以成功访问文件 config.json。此外,当测试从 /test 移动到代码目录时,问题仍然存在。

【问题讨论】:

  • 您可能正在寻找import json
  • 您需要指定绝对路径,而不是相对路径。 __file__ 是模块的绝对路径。
  • 导入 json 没有帮助。
  • @MisterMiyagi,我从 test_main.py 中注释掉了前 3 行,但我得到了同样的错误。

标签: python-3.x import module pytest


【解决方案1】:

假设您有如下示例数据 json:

{ "url" : "http://www.example.com",
"username": "user1"

}

您可以使用以下代码从 json 文件中提取数据:

with open('path /example.json') as json_file:
                    data = json.load(json_file)

username = data['username']



【讨论】:

    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 2013-07-29
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多