使用外部数据文件的 Python 单元测试 [英] Python unit test that uses an external data file

查看:23
本文介绍了使用外部数据文件的 Python 单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在 Eclipse 中处理的 Python 项目,我有以下文件结构:

I have a Python project that I'm working on in Eclipse and I have the following file structure:

/Project
    /projectname
        module1.py
        module2.py 
        # etc.
    /test
        testModule1.py
        # etc.
        testdata.csv

在我的一个测试中,我创建了一个类的实例,将 'testdata.csv' 作为参数.该对象执行 open('testdata.csv') 并读取内容.

In one of my tests I create an instance of one of my classes giving 'testdata.csv' as a parameter. This object does open('testdata.csv') and reads the contents.

如果我只用 unittest 运行这个单一的测试文件,一切正常,文件被找到并正确读取.但是,如果我尝试运行所有单元测试(即通过右键单击 test 目录而不是单个测试文件来运行),我会收到找不到文件的错误.

If I run just this single test file with unittest everything works and the file is found and read properly. However if I try to run all my unit tests (i.e. run by right clicking the test directory rather than the individual test file), I get an error that file could not be found.

有什么办法可以解决这个问题(除了提供绝对路径,我不想这样做)?

Is there any way to get around this (other than providing an absolute path, which I'd prefer not to do)?

推荐答案

通常我做的是定义

THIS_DIR = os.path.dirname(os.path.abspath(__file__))

在每个测试模块的顶部.那么无论您在哪个工作目录中都没有关系 - 相对于测试模块所在的位置,文件路径始终相同.

at the top of each test module. Then it doesn't matter what working directory you're in - the file path is always the same relative to the where the test module sits.

然后我在我的测试(或测试设置)中使用类似的东西:

Then I use something like this is in my test (or test setup):

my_data_path = os.path.join(THIS_DIR, os.pardir, 'data_folder/data.csv')

或者在你的情况下,因为数据源在测试目录中:

Or in your case, since the data source is in the test directory:

my_data_path = os.path.join(THIS_DIR, 'testdata.csv')

用于现代python

from pathlib import Path

THIS_DIR = Path(__file__).parent

my_data_path = THIS_DIR.parent / 'data_folder/data.csv'

# or if it's in the same directory
my_data_path = THIS_DIR / 'testdata.csv'

这篇关于使用外部数据文件的 Python 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆