Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pythonic在pytest中引入多个不同文件路径的方法_Python_Variables_Module_Pytest_Filepath - Fatal编程技术网

Pythonic在pytest中引入多个不同文件路径的方法

Pythonic在pytest中引入多个不同文件路径的方法,python,variables,module,pytest,filepath,Python,Variables,Module,Pytest,Filepath,我有一个pytest脚本,它有大约20个不同的测试。每个测试收集数据并将数据存储在指定的文件路径中。每个文件路径在每个测试中单独定义。例如: def test_1(): gfx = open('path/to/file_1') do something def test_2(): focus = open('path/to/file_2') do something def test_3(): data = open('path/to_1/file_3') do something 问题是

我有一个pytest脚本,它有大约20个不同的测试。每个测试收集数据并将数据存储在指定的文件路径中。每个文件路径在每个测试中单独定义。例如:

def test_1():
gfx = open('path/to/file_1')
do something

def test_2():
focus = open('path/to/file_2')
do something

def test_3():
data = open('path/to_1/file_3')
do something
问题是,我正在将这些脚本传输到新服务器。显然,这个服务器现在有不同的目录,与我以前定义的目录不匹配

我的问题是,为pytest引入文件路径的最具python风格的方式是什么?最好定义易于修改的变量吗?还是有更好的办法


如果需要更多信息或清晰度,请告诉我。

这可能是显而易见的,但一般来说,为了避免此类问题,测试应包括所需的数据。如果数据(文件)很大,也许您可以为您的测试创建一个最小的示例?这将是最干净的解决方案

如果不可能,例如,最小数据(文件)仍然太大,并且单独存储,因此路径的确切位置可能因机器而异。我将使用一个环境变量,在这里设置基本路径——正如您在注释中所建议的那样

import os

try:
    test_data_base_path = os.environ['test_data_base_path']
except KeyError:
    print('Could not get environment variable "test_data_base_path". '
          'This is needed for the tests!')
    raise


def test_1():
    gfx = open(os.path.join(test_data_base_path, 'subfolder', 'to', 'file_1'))
    # do something

def test_2():
    focus = open(os.path.join(test_data_base_path, 'subfolder', 'to', 'file_2'))
    # do something

# ...

如何设置
test\u data\u base\u path
环境变量取决于您运行测试的方式。如果您在全球范围内需要它,您可以通过操作系统来实现。如果您通过IDE启动测试,通常可以直接在那里进行设置。

所有测试的路径是否相同?如果是,是否将该路径作为pytest的命令行选项?基本路径为/user/name/Desktop/folder相同,但之后每个测试的路径不同。这就是为什么我认为应该为基本路径设置一个变量,然后在每个测试中添加路径的其余部分。我已经用一个正确的例子更新了总结。这似乎是我一直在思考的解决方案,但无法思考如何去做。我需要试一试。我真的很感谢你的快速反应!