写一个pytest的自动化框架代码
时间: 2023-05-29 20:07:34 浏览: 63
以下是一个简单的pytest自动化测试框架代码示例:
```python
import pytest
class TestCalculator:
def test_addition(self):
assert 2 + 2 == 4
def test_subtraction(self):
assert 4 - 2 == 2
def test_multiplication(self):
assert 2 * 2 == 4
def test_division(self):
assert 4 / 2 == 2
if __name__ == "__main__":
pytest.main()
```
在这个示例中,我们定义了一个名为TestCalculator的测试类,其中包含了四个测试用例。每个测试用例都是一个独立的函数,使用assert语句来验证预期结果是否等于实际结果。
最后,我们使用pytest.main()函数来运行所有测试用例。pytest会自动发现并执行所有以test_开头的测试用例函数,并输出测试结果。如果有任何测试用例失败,pytest会显示失败的详细信息。
相关问题
用pytest写一个接口自动化框架
当我们使用Python编写接口自动化框架时,pytest是一个非常流行的测试框架。下面是使用pytest编写接口自动化框架的一些步骤:
1. 安装pytest:在命令行中输入“pip install pytest”即可安装。
2. 创建测试文件:在项目中创建一个名为“test_*.py”的文件,其中“*”表示任何名称。在该文件中,我们可以编写测试用例。
3. 编写测试用例:在测试文件中,我们可以使用pytest提供的装饰器来标记测试用例。例如,使用“@pytest.mark.parametrize”装饰器来传递参数,使用“@pytest.mark.skip”装饰器来跳过某些测试用例等。
4. 运行测试用例:在命令行中输入“pytest”命令即可运行所有测试用例。我们也可以使用“pytest test_*.py”命令来运行特定的测试文件。
5. 生成测试报告:pytest可以生成各种格式的测试报告,例如HTML、JUnit XML等。我们可以使用“pytest-html”插件来生成HTML测试报告,使用“pytest-xdist”插件来并行运行测试用例等。
下面是一个简单的示例代码:
```
import pytest
import requests
@pytest.mark.parametrize("url, expected_status_code", [("http://www.baidu.com", 200), ("http://www.google.com", 200)])
def test_api(url, expected_status_code):
response = requests.get(url)
assert response.status_code == expected_status_code
```
这个示例代码中,我们使用了“@pytest.mark.parametrize”装饰器来传递参数,测试了百度和谷歌的首页是否可以正常访问。
用python+requests+pytest写一个接口自动化框架代码
以下是一个简单的接口自动化框架代码,使用了Python的requests和pytest库:
```
# -*- coding: utf-8 -*-
import requests
import pytest
class TestAPI:
@pytest.fixture()
def setup(self):
self.url = "http://api.example.com"
self.headers = {"Content-Type": "application/json"}
self.payload = {"param1": "value1", "param2": "value2"}
def test_api_1(self, setup):
# 发送POST请求
response = requests.post(self.url, headers=self.headers, json=self.payload)
assert response.status_code == 200
assert response.json()["result"] == "success"
def test_api_2(self, setup):
# 发送GET请求
response = requests.get(self.url, headers=self.headers, params=self.payload)
assert response.status_code == 200
assert response.json()["result"] == "success"
```
在这个例子中,我们定义了一个TestAPI类来存储所有的接口测试用例。我们使用pytest.fixture()装饰器来设置所有测试用例的公共数据,这些数据包括API的URL、请求头和请求参数。接下来,我们定义了两个测试用例,test_api_1和test_api_2,它们分别发送POST和GET请求,并验证服务器的响应是否符合预期。
注意:这个例子并不完整,在实际的接口自动化测试中,我们需要更多的测试用例来覆盖更多的接口,以及更多的断言来验证服务器的响应。