“动动小手,点点关注呗~”
在接口自动化测试领域,pytest 框架凭借其强大的功能和灵活性成为众多测试人员的首选。其中,fixture(固件)与 conftest.py 文件的配合使用,为实现测试用例的前后置操作提供了一种优雅且高效的解决方案。
本文将深入探讨如何运用 fixture 固件结合 conftest.py 文件实现接口自动化测试中的前后置功能,并通过丰富的代码示例展示其在不同场景下的具体应用。
一、理解 fixture 固件和 conftest.py 文件
(一)fixture 固件
fixture 是 pytest 中用于设置测试前置条件、提供测试数据或资源的一种机制。它本质上是一个函数,通过装饰器@pytest.fixture进行定义。fixture 可以返回任何对象,例如数据库连接、HTTP 会话、测试数据等,供测试用例使用。在测试用例执行完毕后,还可以执行一些清理操作。
(二)conftest.py 文件
conftest.py 是 pytest 框架中的一个特殊文件,它用于存放共享的 fixture、钩子函数等。该文件不需要显式导入,pytest 会自动识别并加载其中的内容。通过将通用的 fixture 定义在 conftest.py 文件中,可以实现多个测试文件共享这些 fixture,提高代码的复用性。
二、简单的前后置场景:创建和清理 HTTP 会话
假设我们有多个接口测试用例,每个测试用例都需要一个 HTTP 会话来发送请求。我们可以使用 fixture 在 conftest.py 文件中创建和管理这个 HTTP 会话。
(一)conftest.py 文件内容
import pytestimport requests@pytest.fixturedef api_session(): session = requests.Session() yield session session.close()
(二)测试用例文件(test_api.py)
def test_get_user(api_session): url = "http://example.com/api/user" response = api_session.get(url) assert response.status_code == 200def test_create_user(api_session): url = "http://example.com/api/user" data = {"name": "test"} response = api_session.post(url, json=data) assert response.status_code == 201
在上述代码中,api_session是定义在 conftest.py 文件中的 fixture。它创建了一个requests.Session对象,并通过yield语句将其传递给测试用例。测试用例执行完毕后,yield语句之后的代码会关闭这个会话。test_get_user和test_create_user两个测试用例都依赖于api_session,从而实现了 HTTP 会话的复用。
三、复杂前后置场景:用户登录与注销
在实际的接口自动化测试中,很多接口需要用户先登录获取令牌(token),然后在后续请求中携带该令牌进行身份验证。测试结束后,可能还需要进行注销操作。我们可以通过 fixture 和 conftest.py 文件来实现这一系列前后置操作。
(一)conftest.py 文件内容
import pytestimport requests@pytest.fixturedef login(): url = "http://example.com/api/login" data = {"username": "test", "password": "test"} response = requests.post(url, json=data) assert response.status_code == 200 token = response.json()["token"] yield token # 后置操作:注销用户 logout_url = "http://example.com/api/logout" headers = {"Authorization": f"Bearer {token}"} requests.post(logout_url, headers=headers)@pytest.fixturedef api_request_with_token(login): def _api_request_with_token(url, method='GET', **kwargs): headers = kwargs.pop('headers', {}) headers['Authorization'] = f'Bearer {login}' session = requests.Session() try: if method == 'GET': response = session.get(url, headers=headers, **kwargs) elif method == 'POST': response = session.post(url, headers=headers, **kwargs) # 其他方法同理 response.raise_for_status() return response.json() finally: session.close() return _api_request_with_token
(二)测试用例文件(test_protected_api.py)
def test_protected_api(api_request_with_token): url = "http://example.com/api/protected" response_data = api_request_with_token(url) assert response_data["message"] == "访问成功"
在这个例子中,loginfixture 负责用户登录并获取令牌,通过yield语句将令牌传递给其他 fixture 或测试用例。在测试用例执行完毕后,loginfixture 会执行yield语句之后的代码,进行用户注销操作。api_request_with_tokenfixture 依赖于loginfixture,它使用获取到的令牌构造带有身份验证的 HTTP 请求。test_protected_api测试用例使用api_request_with_tokenfixture 来访问需要身份验证的接口。
四、前后置与测试类结合
如果测试用例是以类的形式组织的,我们同样可以使用 fixture 和 conftest.py 文件来实现类级别的前后置操作。
(一)conftest.py 文件内容
import pytestimport requests@pytest.fixture(scope='class')def class_level_setup_teardown(): print("类级别前置操作,例如创建数据库连接") # 可以在这里进行一些初始化操作 yield print("类级别后置操作,例如关闭数据库连接")
(二)测试用例文件(test_class_api.py)
import pytestclass TestClassAPI: @pytest.mark.usefixtures('class_level_setup_teardown') def test_class_method_1(self): print("执行测试方法1") assert True @pytest.mark.usefixtures('class_level_setup_teardown') def test_class_method_2(self): print("执行测试方法2") assert True
在上述代码中,class_level_setup_teardownfixture 的作用域被设置为class,这意味着在TestClassAPI类中的所有测试方法执行前,会执行yield语句之前的代码(类级别前置操作);在所有测试方法执行完毕后,会执行yield语句之后的代码(类级别后置操作)。通过@pytest.mark.usefixtures装饰器,测试类中的方法可以使用这个 fixture。
五、总结
通过 fixture 固件结合 conftest.py 文件,我们可以在接口自动化测试中轻松实现各种复杂的前后置操作。这种方式不仅提高了代码的复用性和可维护性,还使得测试用例的结构更加清晰。无论是简单的资源创建与清理,还是复杂的多步骤业务流程模拟,都能通过合理设计 fixture 来完成。希望本文的内容能帮助你更好地掌握这一强大的功能,在接口自动化测试工作中更加得心应手。
领取专属 10元无门槛券
私享最新 技术干货