Pytest @pytest.fixture

示例:

# -*-encoding: utf-8 -*-

‘‘‘
多个测试用例执行, 但是每个用例 对初始化和清除 的要求不同 ,可以使用@pytest.fixture()

fixture(scope=‘‘,params=None,autouse=False,ids=None,name=None)

    scope四组参数的意义:
    function: 每个方法都会执行一次
    class: 每个类都会执行一次,类中有多个方法调用,只在第一个方法调用时执行
    module: 一个.py文件执行一次,一个.py文件可能包含多个类和方法
    package/session: 多个文件调用一次,可以跨.py文件

‘‘‘


# -*-coding: utf-8 -*-

from selenium import webdriver
import pytest
import time
search_list1 = [小米,小米手机]
search_list2 = [小米10s,红米,耳机]

@pytest.fixture(scope=module,autouse=True)
def first():
    print(正在执行初始化)
    global driver
    driver = webdriver.Chrome()
    driver.get(https://www.mi.com/)
    time.sleep(2)
    yield   # 调用到这里时停止, 下次调用时直接执行后面的语句
    last()

def last():
    print(正在执行清除)
    global driver
    driver.quit()
@pytest.mark.parametrize(item,search_list1)
def test_search_keywords(item):
    global driver
    driver.find_element_by_css_selector(#search).clear()
    driver.find_element_by_css_selector(#search).send_keys(item+\n)
    time.sleep(2)
    elements = driver.find_elements_by_css_selector(.goods-list .title)
    good_list = [element.text for element in elements]
    for i in good_list:
        assert item in i

@pytest.mark.parametrize(item,search_list2)
def test_search_keywords(item):
    global driver
    driver.find_element_by_css_selector(#search).clear()
    driver.find_element_by_css_selector(#search).send_keys(item+\n)
    time.sleep(2)
    elements = driver.find_elements_by_css_selector(.goods-list .title)
    good_list = [element.text for element in elements]
    for i in good_list:
        assert item in i

if __name__ == __main__:
    pytest.main([test_scripts03.py,-s])

 

Pytest @pytest.fixture

上一篇:JavaScript简易缩放程序


下一篇:HTML5打造的炫酷本地音乐播放器-喵喵Player