简体   繁体   English

在 python (pytest) 测试中使用资源文件

[英]Using resource files in python (pytest) tests

Could someone tell me what the correct way of dealing with resource files in pytest?有人能告诉我在 pytest 中处理资源文件的正确方法是什么吗?

I have a habit of creating a resources directory just under the package (src) directory and another under the test branch我有一个习惯,就是在package(src)目录下创建一个resources目录,在test分支下创建一个

root---package---resource_dir
     |         |-file1.py
     |         |-file2.py
     |
     |-test-- resource_dir-
            |              |-config1.csv
            |              |-config2.csv
            |-test1.py
            |-test2.py

If I want to access these files from within my tests what is the pythonic way of doing so?如果我想从我的测试中访问这些文件,pythonic 的方法是什么? Up to now I have been using relative file paths but that solution isn't great.到目前为止,我一直在使用相对文件路径,但该解决方案并不好。 Is there a solution similar to the Java resources solution?是否有类似于 Java 资源解决方案的解决方案?

One way I have found to do this is using pkg_resources.我发现这样做的一种方法是使用 pkg_resources。 This has the ability to search through your package for files.这可以在您的包中搜索文件。 So, for example, if you want to print the contents of a file that is in the test resources directory you could do the following:因此,例如,如果您想打印测试资源目录中文件的内容,您可以执行以下操作:

import pkg_resources
config_file = open(pkg_resources.resource_filename('test.resources','config.csv'),'r')
    for line in config_file:
        print(line)

    print(">>>End of File")

please note that all directories and subdirectories need to be pacakges (ie the init .py file must be present, even if its empty).请注意,所有目录和子目录都必须是 pacakges(即init .py 文件必须存在,即使它是空的)。

I would add the root folder and test/resource_dir to the sys.path.我会将根文件夹和 test/resource_dir 添加到 sys.path。 This will allow you to always include resources in the exact same way no matter what the directory structure of your test folder currently looks like.这将允许您始终以完全相同的方式包含资源,无论您的测试文件夹当前的目录结构如何。

Adding the root folder to sys.path also helps create consistency between the test runner and normal execution, and will allow your tests to directly reference resources from root/package/resource_directory .将根文件夹添加到 sys.path 还有助于在测试运行程序和正常执行之间建立一致性,并允许您的测试直接从root/package/resource_directory引用root/package/resource_directory

Adding test/resource_dir to sys.path allows tests to directly reference resources from test/resource_dir .test/resource_dir添加到 sys.path 允许测试直接从test/resource_dir引用test/resource_dir

For some sample code on how to set this up, see Option B on this answer , but with replacing the lib folder for resource_dir .有关如何设置的一些示例代码,请参阅此答案中的选项 B,但要替换resource_dirlib文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM