在子文件夹中使用

在子文件夹中使用

本文介绍了在子文件夹中使用 pytest where test的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python pytest 来运行我的单元测试.我的项目文件夹是:

I'm using python pytest to run my unit tests.My project folders are:

Main - 包含数据文件:A.txt

Main - contains data file: A.txt

Main\Tests - 我运行 pytest 的文件夹

Main\Tests - the folder from which I run pytest

Main\Tests\A_test - 包含测试文件的文件夹

Main\Tests\A_test - folder that contains a test file

A_test 文件夹中的测试使用文件 A.txt(位于 Main 文件夹中).

The test in A_test folder uses the file A.txt (that is in Main folder).

我的问题是,当我运行 py.test 时,测试失败,因为它找不到 A.txt.

My problem is that when I run py.test the test fails because it can't find A.txt.

我发现这是因为 pytest 在运行测试时使用了路径 Main\Test 而不是将路径更改为 Main\Tests\A_test(我是在测试文件中打开 A.txt 时使用相对路径)

I found out that it is because pytest uses the path Main\Test when running the test instead of changing the path to Main\Tests\A_test (I'm using relative path when opening A.txt inside the test file)

我的问题:有没有办法让 pytest 将目录更改为它为每个测试执行的测试的文件夹?这样测试中的相对路径仍然有效吗?

My question: is there a way to make pytest change directory to the folder of the test it executes for each test? so that relative paths inside the tests will still work?

有没有其他通用的方法来解决它?(我不想把所有东西都改成绝对路径之类的,这也是一个例子,在现实生活中我有数百个测试).

Is there some other generic way to solve it? (I don't want to change everything to absolute paths or something like this, also this is an example, in real life I have several hundreds tests).

谢谢,

诺姆

推荐答案

嗯,我有点解决了,不确定这是最好的方法,但它正在工作:

Well I kind of solved it, not sure it is the best way but it is working:

在每个测试中:

  1. 我检查测试是从它的目录还是从 \Main\Tests
  2. 如果它是从 \Main\Tests 执行的,那么我 chdir\Main\Tests\A_test
  1. I check if the test is being executed from it directory or from \Main\Tests
  2. If it is being executed from \Main\Tests then I chdir to \Main\Tests\A_test

我在 def setUpClass 方法下执行此操作.

I do this under the def setUpClass method.

例如:

@classmethod
def setUpClass(cls):
    if (os.path.exists(os.path.join(os.curdir, "A_test"))):
        os.chdir("A_test")

无论是从 Tests 文件夹(使用 pytest)还是从 A_test 文件夹(通过 pycharm)执行,这都会使测试通过

This makes the test pass no matter if it is executed from Tests folder (with pytest) or from A_test folder (through pycharm)

这篇关于在子文件夹中使用 pytest where test的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:09