当前位置: 首页>移动开发>正文

接口自动化中如何保持登陆状态(鉴权)

1. 使用cookie

获得上一个接口的res.cookies,在下一个接口中传入cookies

# 开发时间:2023/11/2 17:24
import re

import requests


class TestCookieJianQuan:
    csrf_token = ''
    csrf_cookie = ''

    def test_goto_index(self):
        url = "http://47.107.116.139/phpwind"

        res = requests.get(url=url)
        TestCookieJianQuan.csrf_token = re.search('name="csrf_token" value="(.*?)"', res.text).group(1)
        TestCookieJianQuan.csrf_cookie = res.cookies

    def test_login_phpwind(self):
        url = 'http://47.107.116.139/phpwind/index.php?m=u&c=login&a=dorun'
        headers = {
            "Accept": "application/json, text/javascript, /; q=0.01",
            "x-Requested-With": "XMLHttpRequest"
        }
        datas = {
            "username": "elaine",
            "password": "elaine123",
            "csrf_token": TestCookieJianQuan.csrf_token,
            "back_url": "http://47.107.116.139/phpwind/",
            "invite": "",
        }
        requests.post(url=url, json=datas, headers=headers, cookies=TestCookieJianQuan.csrf_cookie)

2. 使用requests.session()

import requests

session = requests.session()
response_1 = session.request(method='get', url="https://httpbin.org/cookies/set/session_cookie/12345678")
print(response_1.json())
response_2 = session.request(method='get', url="https://httpbin.org/cookies")
print(response_2.json())

session = requests.Session()
response_1 = session.get("https://httpbin.org/cookies/set/session_cookie/12345678")
print(response_1.json())
response_2 = session.get("https://httpbin.org/cookies")
print(response_2.json())
{'cookies': {'session_cookie': '12345678'}}
{'cookies': {'session_cookie': '12345678'}}
{'cookies': {'session_cookie': '12345678'}}
{'cookies': {'session_cookie': '12345678'}}

3. 使用token

import requests

data = {
    "username": "13687300226",
    "password": "123456"
}
rs = requests.post("http://novel.hctestedu.com/user/login", data=data)
print(rs.json())
token = rs.json()["data"]["token"]
params = {"curr": 1,
          "limit": 10}

headers = {
    "Authorization": token
}
rs1 = requests.get("http://novel.hctestedu.com/user/listBookShelfByPage",
                   params=params,
                   headers=headers)
print(rs1.json())

rs2 = requests.get("http://novel.hctestedu.com/user/listBookShelfByPage",
                   params=params)
print(rs2.json())
{'code': '200', 'msg': 'SUCCESS', 'data': {'token': 'eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE3MDQwODU0MzYsInN1YiI6IntcImlkXCI6MTQ1MTE0OTM5MDg1MDMyNjUyOCxcInVzZXJuYW1lXCI6XCIxMzY4NzMwMDIyNlwiLFwibmlja05hbWVcIjpcIjEzNjg3MzAwMjI2XCJ9IiwiY3JlYXRlZCI6MTcwMzQ4MDYzNjgyN30.uvUJ4KNEwD8vnSC6coJDEp-eGcVR4rx1TSe-vuAtDN3mEbKTRpFVuKSp9RQRsCe950RNWJG3uYS6ZlAIAB_5Sg'}}
{'code': '200', 'msg': 'SUCCESS', 'data': {'pageNum': '1', 'pageSize': '10', 'total': '76', 'list': [{'id': None, 'userId': None, 'bookId': '1808'}]}}
{'code': '1001', 'msg': '未登录或登陆失效!', 'data': None}

4. session和token结合

import requests

data = {
    "username": "13687300226",
    "password": "123456"
}
rs = requests.post("http://novel.hctestedu.com/user/login", data=data)
print(rs.json())
token = rs.json()["data"]["token"]

session = requests.session()
session.headers.update({"Authorization": token})

params = {"curr": 1,
          "limit": 10}
rs1 = session.get("http://novel.hctestedu.com/user/listBookShelfByPage",
                   params=params)
print(rs1.json())

5. 在自动化测试中的应用

在conftest.py里写登陆,在用例里写功能用例

# conftest.py
# 开发时间:2023/12/25 10:58
import pytest
import requests


@pytest.fixture(scope="session", autouse=True)
def login():
    session = requests.session()

    data = {
        "username": "13687300226",
        "password": "123456"
    }
    rs = session.post("http://novel.hctestedu.com/user/login", data=data)
    print(rs.json())
    token = rs.json()["data"]["token"]

    session.headers.update({"Authorization": token})
    return session

# test_case_001.py
# 开发时间:2023/12/25 10:58
def test_case(login):
    session = login
    params = {"curr": 1,
              "limit": 10}
    rs1 = session.get("http://novel.hctestedu.com/user/listBookShelfByPage",
                      params=params)
    print(rs1.json())


https://www.xamrdz.com/mobile/42y1995847.html

相关文章: