web自动化中pytest框架的使用(一)---fixture

1、fixture是对测试用例执行的环境准备和清理,相当于unittest中的setUp/tearDown/setUpClass/tearDownClass作用

2、fixture的主要目的

  如测试用例运行时都需要进行登录和退出操作时,使用fixture后,可以只进行一次登录和退出操作,不需要每个用例执行时都进行登录和退出

3、如何使用fixture

  在测试函数之前加上@pytest.fixture

  1、需要在测试包下新建一个conftest.py文件,名字不能是其他的

    

  2、在该文件中写用例执行的前置条件和后置条件,首先需要声明他是一个fixture,@pytest.fixture

 1 import pytest
 2 from selenium import webdriver
 3 from TestDatas import Common_Datas as CD
 4 from PageObjects.login_page import LoginPage
 5 
 6 
 7 driver=None
 8 # 声明一个它是一个fixture
 9 # scope='class'表示access_web的作用域在类上,执行测试用例时,类只执行一次
10 @pytest.fixture(scope='class')
11 def access_web():
12     # 前置条件
13     global driver  #声明driver为全局变量
14     print("========所有测试用例之前的,整个测试用例只执行一次=========")
15     driver=webdriver.Chrome()
16     driver.maximize_window()
17     driver.get(CD.web_login_url)
18     # 实例化LoginPage类
19     lg=LoginPage(driver)
20     # yield 同时可以返回值(driver,lg),相当于return,在使用返回值的时候直接用函数名
21     yield (driver,lg)  ##前面是前置条件、后面是后置条件
22     # 后置条件
23     print("========所有测试用例之后的,整个测试用例只执行一次=========")
24     driver.quit()
25 @pytest.fixture()
26 # @pytest.fixture()表示函数默认作用域access_web的作用域在函数上,执行测试用例时,每个函数都执行一次
27 def refresh_page():
28     global driver
29     # 前置操作
30     yield
31     # 后置操作
32     driver.refresh()

  3、在函数中直接使用就可以,不需要引用py文件

  • access_web函数名直接接收返回值,使用函数名可以直接使用返回值
     1 from PageObjects.index_page import IndexPage
     2 from TestDatas import login_datas as LD
     3 import pytest
     4 
     5 # 使用access_web,作用域是类级别,类上只执行一次
     6 @pytest.mark.usefixtures("access_web")
     7 #使用refresh_page,作用域是函数级别,作用在每一个函数上
     8 @pytest.mark.usefixtures("refresh_page")
     9 class TestLogin:
    10     # # 正常用例--登录成功
    11     @pytest.mark.somke
    12     @pytest.mark.one
    13     def test_login_1_success(self,access_web):
    14         '''
    15         :param access_web: 使用access_web函数名称来接收conftest中access_web函数的返回值,返回值为元组形式yield (driver,lg),使用返回值直接用函数名和下表 eg:access_web[0],access_web[1],如果access_web函数中没有返回值,则无需传参
    16         :return:
    17         '''
    18         # 2、步骤
    19         # 调用login方法
    20         access_web[1].login(LD.success_data['user'],LD.success_data['pwd'])
    21         # 3、断言
    22         assert IndexPage(access_web[0]).isExist_logout_ele()
原文地址:https://www.cnblogs.com/wsk1988/p/12776857.html