web自动化实现登录的几种方式

目录

前言

一、python+unittest框架实现登录功能

二、python+selenium实现登录功能

三、python+requests库实现登录功能


前言

今天主要想介绍python语言+不同的自动化测试框架的结合方式来模拟登录功能。想了解自动化测试框架的同学不要错过哦!


一、python+unittest框架实现登录功能

1.封装公共方法

在common目录下封装方法,具体代码如下:

import requests
class RequestHandler:
    def __init__(self):
        """session管理器"""
        self.session = requests.session()

    def visit(self,method,url,params = None,data=None,json=None,headers=None):
        result = self.session.request(method,url,params=params,data=data,json=json,headers=headers,verify=False)
        try:
            #返回json结果
            print(result)
            return result.json()
        except Exception:
            return 'not json'
    def close_session(self):
        self.session.close()

2.调用

创建文件:test_login.py,在文件中可结合allure报告实现登录的不同场景。具体代码如下:

import unittest
import allure
import os
import pytest
from common.requests_handler import RequestHandler

@allure.epic("web自动化")
@allure.feature("登录功能")

class TestLogin(unittest.TestCase):
    def setUp(self):
        #请求类实例化
        self.req = RequestHandler()

    def tearDown(self):
        self.req.close_session()


    @allure.severity("critical")
    @allure.title("正确的用户名、密码登录")
    def test_login_success(self):
        """
        正确的用户名、密码
        """
        with allure.step("step1:输入正确的用户名、密码"):
            print("输入正确的用户名、密码")
        with allure.step("step2:校验登录结果:登录成功"):
            print("登录成功")
        login_url = 'https://example.com/login'
        body = {
            "name":"test",
            "password":"test1234"
        }

        res = self.req.visit('post',login_url,json=body)
        #根据请求结果中的code进行断言
        print(res)
        self.assertEqual(0,res['code'])


    @allure.title("错误的用户名、正确的密码登录")
    def test_login_wrong_name(self):
        """
        错误的用户名、正确的密码
        """

        with allure.step("step1:输入错误的用户名、正确的密码"):
            print("输入错误的用户名、正确的密码")
        with allure.step("step2:校验登录结果:登录失败,报错提示:用户不存在"):
            print("登录失败")

         login_url = 'https://example.com/login'
         body = {
             "name":"test1",
             "password":"test1234"
         }


        res = self.req.visit('post', login_url, json=body)
        # 根据请求结果中的code进行断言
        self.assertEqual(16020, res['code'])
        #根据请求结果中的message进行断言
        self.assertEqual("用户不存在",res['message'])


    @allure.title("正确的用户名、错误的密码登录")
    def test_login_wrong_pwd(self):
        """
        正确的用户名、错误的密码
        """

        with allure.step("step1:输入正确的用户名、错误的密码"):
            print("输入正确的用户名、错误的密码")
        with allure.step("step2:校验登录结果:登录失败,报错提示:账号有误,登录失败"):
            print("登录失败")

         login_url = 'https://example.com/login'
         body = {
             "name":"test",
             "password":"test12"
         }


        res = self.req.visit('post', login_url, json=body)
        # 根据请求结果中的code进行断言
        self.assertEqual(16002, res['code'])
        #根据请求结果中的message进行断言
        self.assertEqual("账号有误,登录失败",res['message'])


if __name__ == '__main__':
    pytest.main(['-vs', 'test_login.py', '--clean-alluredir', '--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

二、python+selenium实现登录功能

1.selenium自动化

创建文件test_login.py文件,结合allure+selenium实现登录并获取cookies传递给后面的请求。具体代码如下:

import allure
import pytest
import os,time
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
timestamp = time.time()



@allure.feature("web自动化测试")
@allure.title("登录")
def test_login():

    """
    采用selenium框架登录获取cookie成功
    """

    driver = webdriver.Chrome()
    # 窗口最大化
    driver.maximize_window()
    # 打开网页
    driver.get("https://example.com")
    time.sleep(2)

    #刷新页面
    driver.refresh()
    #截屏
    driver.get_screenshot_as_file("D:\\test\\1.jpg")
    # 实例化 By 类的对象
    by_xpath = By.XPATH
    # 元素获取及点击
    # 使用by_xpath 对象调用 xpath 方法
    driver.find_element(by=by_xpath, value="//input[@id = 'identifier']").send_keys("填具体的用户名")
    driver.find_element(by=by_xpath, value="//input[@id = 'password']").send_keys("填密码")
    driver.find_element(by=by_xpath, value=("//button[@class = 'ant-btn ant-btn-primary sc-htpNat guSfSS']")).click()
    time.sleep(5)

    #获取cookies
    cookies = driver.get_cookies()
    for cookie in cookies:
        print("%s -> %s" %(cookie['name'],cookie['value']))

    #cookies做拼接
    cookies_list = [cookie["name"] + "=" + cookie["value"] for cookie in driver.get_cookies()]
    cookies = ';'.join(it for it in cookies_list)
    print(cookies)


    """新建文件夹"""

    createDir_url = '具体新建文件url'
    body = {
        "bucket": "common",
        "project_id": project_id,
        "path": "test-mkdir",
        "zone": zone
    }
    headers = {
        'Cookie': f'{cookies}',
        'X-Box-Fe-Token': Token
    }
    res = requests.post(createDir_url, headers=headers, json=body)
    resp = res.json()
    print(resp)
    assert (0,resp['code'])

     """删除文件夹"""
    deleteDir_url = '具体删除url'
    body = {
        "bucket": "common",
        "project_id": project_id,
        "path": "test-mkdir",
        "zone": zone
    }
    headers = {
        'Cookie': f'{cookies}',
        'X-Box-Fe-Token': Token
    }
    res = requests.delete(deleteDir_url, headers=headers, json=body)
    data = res.json()
    print(data)
    assert (0,data['code'])

    #关闭浏览器
    driver.quit()

if  __name__ == '__main__':
    pytest.main(['-vs', 'test_login.py', '--clean-alluredir', '--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

三、python+requests库实现登录功能

1.封装公共方法

首先在common文件夹下封装公共方法,具体代码如下:

#!/usr/bin/env python
# _*_coding:utf-8_*_
import requests

from log.log_record import log_print


def post_main(url, data, header):
    """
     post请求
     :param url:
     :param data:
     :param header:
     :return:
    """
    try:
        res = requests.post(url=url, json=data, headers=header)
        return res.json()
    except Exception as e:
        log_print().error(f"接口请求错误,请求参数:{data},请求Url:{url},请求结果:{res.json()}")


def get_main(url, header):
    """
    get请求
    :param url:
    :param header:
    :param param:
    :return:
    """
    try:
        res = requests.get(url=url, headers=header)
        return res.json()
    except Exception as e:
        log_print().info(f"接口请求错误,请求Url:{url},请求结果:{res.json()}")


def run_main(method, url, header, data=None):
    """
    被调用主request
    :param method:
    :param url:
    :param header:
    :param data:
    :param file:
    :return:
    """
    try:
        res = None
        if method == 'post' or method == 'POST' or method == 'Post':
            res = post_main(url, data, header)
        elif method == 'get' or method == 'GET' or method == 'Get':
            res = get_main(url, header)
        else:
            log_print().error(f"请求方法:{method}格式错误")
        return res
    except Exception as e:
        log_print().error(f"请求方法报错{e}")


if __name__ == '__main__':
    pass

2.调用

创建test_login.py文件,调用requests库方法实现登录。具体代码如下:

import requests
 
url = 'https://example.com/login'
data = {
    'username': 'admin',
    'password': '123456',
}

response = requests.post(url, data=data)
print(response.content.decode("utf-8"))
headers = response.headers
print(headers.get('Set-Cookie'))

介绍了上述内容,你学废了吗?

web自动化实现登录的几种方式_第1张图片

你可能感兴趣的:(自动化技术,前端,自动化,python)