UI Automation Framework: pytest

问题

1. 使用pycharm,test文件和page文件分别在不同的目录下(testCases-test_sanity.py, pageObjects-hote_search_results_page.py),test文件引用page文件import pageObjects.hotel_search_Results_page.py,运行pytest的时候总是提示找不到pageObjects

  • 方法一,在import之前添加两句#

    import sys
    sys.path.append("E:\python_expedia") //项目根路径

  • 方法二,运行执行case的命令前,先运行set PYTHONPATH=E:\python_expedia

总结

pytest测试数据参数化的方法

1. 使用@pytest.fixture(), 测试数据与测试case在同一个文件

# practice_is_leap_year1.py

def is_leap_year(year):
    if isinstance(year, int) is not True:
        raise TypeError("year is not int")
    elif year == 0:
        raise ValueError("year shouldn't be 0")
    elif abs(year) != year:
        raise ValueError("year should be positiye number")
    elif(year%4 == 0 and year%100 !=0 or year%400 ==0):
        print("%d is leaf year" % year)
        return True
    else:
        return False
View Code
# practice_is_leap_year2.py

import pytest
import practice_is_leap_year1

is_leap = [4, 40, 400, 800, 1996, 2996]
is_not_leap = [1, 100, 500, 1000, 1999, 3000]
is_valueerror = [0, -4, -100]
is_typeerror = ['-4', 'ins']

@pytest.fixture(params=is_leap)
def is_leap(request):
    return request.param
@pytest.fixture(params=is_typeerror)
def is_typeerror(request):
    return request.param

def test_is_leap(is_leap):
    assert practice_is_leap_year1.is_leap_year(is_leap) == True

def test_is_typeerror(is_typeerror):
    with pytest.raises(TypeError):
        practice_is_leap_year1.is_leap_year(is_typeerror)
View Code

2. 使用conftest.py文件,是测试数据与测试case分离

# conftest.py

is_leap = [4, 40, 400, 800, 1996, 2996]
is_not_leap = [1, 100, 500, 1000, 1999, 3000]
is_valueerror = [0, -4, -100]
is_typeerror = ['-4', 'ins']
@pytest.fixture(params=is_leap)
def is_leap_conftest(request):
    return request.param
@pytest.fixture(params=is_typeerror)
def is_typeerror_conftest(request):
    return request.param
View Code
# practice_is_leap_year3.py

import pytest
import practice_is_leap_year1

class TestData:

    def test_is_leap(self, is_leap_conftest):
        assert practice_is_leap_year1.is_leap_year(is_leap_conftest) == True

    def test_is_typeerror(self, is_typeerror_conftest):
        with pytest.raises(TypeError):
            practice_is_leap_year1.is_leap_year(is_typeerror_conftest)
View Code

 3. 使用@pytest.mark.parametrize(),可以让同一条case用不同的测试数据跑多次

# practice_is_leap_year4.py
import pytest
import practice_is_leap_year1

@pytest.mark.parametrize('year, expected', ([1, False], [1996, True]))
def test_is_leap(self, year, expected):
    assert practice_is_leap_year1.is_leap_year(year) == expected
View Code

pytest并行运行测试

使用插件pytest-xdist

1. pip install pytest-xdist

2. 执行case时命令行参数:

  • -n 并行数量

pytest生成html测试报告

使用插件pytest-html

1. pip install pytest-html

2. 执行case时命令行参数 pytest --html=report.html

3. 上面生成的报告,css是独立的,分享报告的时候样式会丢失,为了更好的分享发邮件展示报告,可以把css样式合并到html里  pytest --html=report.html --self-contained-html

猜你喜欢

转载自www.cnblogs.com/lj8023wh/p/10456270.html