module - pytest,有什么方法可以包含测试文件或测试文件列表?
问题描述
我正在寻找有关以下情况的最佳实践建议:
- 我正在使用 pytest 在我的 IAC 部署上运行集成测试
- 我的 IAC 代码库的结构如下:
myapp
|
|_roles
| |_role1
| |_role2
|_resources
|_tomcat
|_java
我想为我的测试文件使用相同的结构。测试目前分为文件匹配角色(role1,role2):
tests
|
|_roles
|_test_role1.py
|_test_role2.py
这导致重复的代码,例如:
role1 是一个 tomcat 基础应用程序,
role2 保存纯 java 代码,
所以在两个测试文件(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 知识使我远离实际的解决方案。
谢谢
解决方案
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/
推荐阅读
- python - 当我尝试运行 container.inside() 方法时,Jenkins 挂起
- haskell - 如何从列表中删除一个元素及其所有重复项?
- excel - sql表名中的空格
- java - 在 Activity 中点击 Fragment
- c# - 如何在 ASP.NET Core 中动态过滤 Razor 页面的视图模型?
- powershell - Powershell 在 pgp 解密时失败
- multithreading - 为什么 CNiButton 不能从除主线程之外的线程更改?
- r - 在R中按日期添加索引列
- java - 从文件 Java 8 中读取行并介于两者之间的最佳方法
- r - 将 foverlaps 与 POSIXct 对象一起使用时遇到问题 - 可能是由于小数秒?