pytest + requests + allure 接口自动化测试项目
编写测试用例,每个 py
都需要重复的导入 pytest、allure
等等,有点麻烦,所以用了一个偷懒小技巧。
遇到的问题
# test_demo.py
import pytest
import allure
from base_api import get_api_name
class TestDemo:
@pytest.mark.demo
@allure.title("test demo title")
def testcase(self):
pass
上面这三个是用例的基础导包,在每个测试用例内都需要写一遍,由于是公共的,我希望这些导包能统一管理,并且不需要重复导入。
这可能是个没卵用的需求,哈哈,瞎折腾呗
解决的方法
# testcase dir 目录结构如下
testcase
__init__.py
test_demo.py
test_demo2.py
1. 添加 __init__.py
文件
python 目录下的 __init__.py
文件,在 3.x 版本之前是用来标识包目录,后续版本不再强制要求必须创建该文件;如果目录下存在该文件,会在该目录被导入时自动进行初始化。
# __init__.py
import pytest
import allure
from api.base_api import get_api_name
__all__ = ["pytest", "allure", "get_api_name"]
__all__
是针对模块公开接口的一种约定,以提供了”白名单“的形式暴露接口。如果定义了__all__
,其他文件中使用 from xxx import *
导入该文件时,只会导入 __all__
列出的成员,可以其他成员都被排除在外。
2. 用例文件内模糊导入
# test_demo.py
from testcase import *
class TestDemo:
@pytest.mark.demo
@allure.title("test demo title")
def testcase(self):
pass
那么在用例中,通过 testcase
模糊导入,就可以使用 __init__.py
对外提供的包啦,解决重复导入的问题。
当然,这个办法只推荐导入公共包,而且是小范围使用,因为代码的可读性太差,别人会一脸懵逼。