2017-07-14 101 views
0

对于我的新Python项目,我也跟着下面的目录结构所建议,http://docs.python-guide.org/en/latest/writing/structure/FileNotFoundError:运行单元测试蟒蛇

Project 
     solution 
      __init__.py 
      trial.txt 
      trial.py 
     tests 
      __init__.py 
      test.py 

trial.py's demo读取trial.text,并执行一些操作

with open("trial.txt") as f: 
    f.readlines() 

代码作品和测试工作正常,当我运行它从project目录

test抛出文件上trial.txt未找到错误从tests目录中运行时

我还添加了一个上下文模块用于tests

import os 
import sys 
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../solution'))) 

import trial 
+1

尝试指定包之前加入这个固定我的目录的这个例子? – bendl

+0

这里https://pythoncentral.io/how-to-create-a-python-package/ – babygame0ver

+0

@AkshayKathpal但我想测试和主代码在单独的文件夹 –

回答

0

你可以这样做是为了写

制作一个python脚本,在解决方案目录中,并将其命名为

name -> __init__.py 

import trial 

并保存此文件中的解决方案目录

现在从test.py 像这样一个在这里尝试进口解决方案

from Solution import trial 
trial.main() 

但是确保代码在trial.py文件中的一些功能,如main(),然后你可以调用像

trial.main() 

为了更好地理解看到

enter image description here

enter image description here

The file data.py and __init__.py are in the same directory. You can see here and try to solve. 
+0

'FileNotFoundError:[Errno 2]没有这样的文件或目录:'trial.txt'' Still在导入时读取文件时仍然存在错误 –

+0

我在我的系统上测试过它 – babygame0ver

+0

我从'tests'文件夹内运行'test.py',当我打印'os.getcwd()'我得到这个''/ home/Bhavani/skcript/tests' –

0

通过打开文件

file_path = (os.path.dirname(__file__))+"/trail.txt" 
with open(filepath,"r") as f: 
    f.readlines()