【问题标题】:FIle Not Found - Python Unit Test未找到文件 - Python 单元测试
【发布时间】:2019-04-17 21:34:40
【问题描述】:

我有一个 python 代码要测试。这是一个简单的代码。文件夹结构如下。

.
├── code
│   ├── conf.json
│   ├── __init__.py
│   └── a.py
└── test
    ├── __init__.py
    ├── a_test.py

a.py 中的代码:

import json

conf_path = "conf.json"

def run():
    with open(conf_oath,'r') as f:
         conf = json.load(f)
    print(conf)

a_test.py 中的代码:

import unittest
from os import sys, path
sys.path.append('../code')

from code import a

class Test(unittest.TestCase):

      def test_run():
          conf = a.run()
          print(conf)

if __name__ == '__main__':
   unittest.main()

当我运行 python -m unittest test.a_test 时,我收到以下错误 -

No such file or directory: 'conf.json'

我哪里错了?如何解决这个问题?

【问题讨论】:

  • 'conf.json' 是相对于当前工作目录解析的,而不是 a.py 存储的目录。

标签: python python-unittest


【解决方案1】:

文件的路径是相对于您执行测试的位置而不是测试文件所在的位置。您可以改为使用 os 库获取文件的完整路径。

import json
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
conf_path = os.path.join(dir_path, 'conf.json')

def run():
    with open(conf_path, 'r') as f:
         conf = json.load(f)
    print(conf)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2016-03-16
    • 2013-06-07
    • 2012-08-17
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多