python接口自动化+request库+pytest框架+PO模式封装实现登录获取token
时间: 2023-09-10 09:05:43 浏览: 82
好的,下面是一个简单的示例代码:
1. 安装依赖库
```
pip install requests
pip install pytest
```
2. 创建项目结构
```
.
├── api
│ ├── __init__.py
│ └── login.py
├── case
│ ├── __init__.py
│ └── test_login.py
├── common
│ ├── __init__.py
│ └── utils.py
└── pytest.ini
```
3. 编写代码
api/login.py
```python
import requests
class LoginApi:
def __init__(self):
self.url = 'http://localhost:8080/api/login'
def login(self, username, password):
payload = {
'username': username,
'password': password
}
response = requests.post(self.url, json=payload)
return response.json().get('data').get('token')
```
common/utils.py
```python
import pytest
from api.login import LoginApi
@pytest.fixture(scope='session')
def token():
api = LoginApi()
return api.login('test', '123456')
```
case/test_login.py
```python
def test_login(token):
assert token is not None
```
4. 运行测试
在项目根目录下运行以下命令:
```
pytest
```
输出结果:
```
============================= test session starts =============================
platform darwin -- Python 3.8.5, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: /Users/username/project
collected 1 item
case/test_login.py . [100%]
============================== 1 passed in 0.17s ==============================
```
这样就完成了一个简单的接口自动化测试,并且封装了登录获取 token 的 API 和使用了 pytest 的 fixture 机制。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)