首页 > 解决方案 > pytest,有什么方法可以包含测试文件或测试文件列表?

问题描述

我正在寻找有关以下情况的最佳实践建议:

  myapp
      |
      |_roles
      |    |_role1
      |    |_role2
      |_resources
           |_tomcat
           |_java

我想为我的测试文件使用相同的结构。测试目前分为文件匹配角色(role1,role2):

  tests
      |
      |_roles
           |_test_role1.py
           |_test_role2.py

这导致重复的代码,例如:

所以在两个测试文件(test_role1.py 和 test_role2.py)中都会有一个 java 测试函数。

如果我可以将 dir 结构添加为:

  tests
      |
      |_roles
      |    |_test_role1.py
      |    |_test_role2.py
      |
      |_resources
           |_test_tomcat.py
           |_test_java.py

然后我可以“包含/导入” test_java.py 函数以在 test_role1.py 和 test_role2.py 中使用它们,而无需复制代码......

实现这一目标的最佳方法是什么?

我已经在使用固定装置(在 conftest.py 中定义),我觉得我的重复代码的解决方案是固定装置或测试模块,但我糟糕的 python / pytest 知识使我远离实际的解决方案。

谢谢

标签: modulepytestfixtures

解决方案


If you don't mind running your tests as a module, you could turn your Python files into packages by placing a file called 'init.py' in the root of the project, in the directory with the code to be tested and in the directory with the testing code.

You can then perform relative imports to access the functions you need: eg to access "_test_java.py" from "_test_role2.py"

from ../_roles  import _test_java

A single dot represent the current directory. Two dots represents the parent directory.

You will need to use the -m flag when calling your code so Python understands you are running a module with relative imports.

In your case you might consider performing the messy relative imports in conftest.py

This post explains the above in more detail: http://blog.habnab.it/blog/2013/07/21/python-packages-and-you/


推荐阅读