conftest.py 2.59 KB
# -*- coding: utf-8 -*-
# @Time    :  2021/1/22 16:11
# @Author  :  Young Lee
# @Email   :  young_lee2017@163.com

import pytest
import configparser
import os


def pytest_addoption(parser):
    parser.addini('overall_skips', type='linelist', default=[], help='skip all markers if the specified one failed')
    parser.addini('patriarch_skips', type='linelist', default=[], help='skip some markers if first one failed')
    parser.addini('group_skips', type='linelist', default=[], help='skip some markers of group if one failed')


def gain_skips(cfg, item='pytest'):
    raw = configfile.get(item, cfg).split('\n')
    return [x for x in raw if x]


current_dir = os.path.dirname(os.path.abspath(__file__))
ini_path = os.path.join(current_dir, 'pytest.ini')
configfile = configparser.ConfigParser()
configfile.read(ini_path)
overall_skips = gain_skips('overall_skips')
patriarch_skips = gain_skips('patriarch_skips')
group_skips = gain_skips('group_skips')


def add_failedmarkers(item, markers):
    if markers:
        item.session.failedmarkers.extend(markers)
        item.session.failedmarkers = list(set(item.session.failedmarkers))


def pytest_sessionstart(session):
    session.failedmarkers = []
    session.skip_all_flag = False
    session.patriarch_skip_flag = {skip: 1 for skip in patriarch_skips}


def pytest_runtest_makereport(item, call):
    if not item.session.skip_all_flag:
        patriarch_markers = [marker.name for marker in item.iter_markers() if marker.name in patriarch_skips]
        for marker in patriarch_markers:
            number = item.session.patriarch_skip_flag[marker]
            if number < 2:
                number += 1
                item.session.patriarch_skip_flag[marker] = number
            elif number == 2:
                if call.excinfo:
                    add_failedmarkers(item, patriarch_markers)
                number += 1
                item.session.patriarch_skip_flag[marker] = number

        if call.excinfo is not None:
            overall_markers = [marker.name for marker in item.iter_markers() if marker.name in overall_skips]
            if overall_markers:
                item.session.skip_all_flag = True
                return
            group_markers = [marker.name for marker in item.iter_markers() if marker.name in group_skips]
            add_failedmarkers(item, group_markers)


def pytest_runtest_setup(item):
    if item.session.skip_all_flag:
        pytest.skip(f"Dependency Skip")

    markers = [marker.name for marker in item.iter_markers()]
    for marker in markers:
        if marker in item.session.failedmarkers:
            pytest.skip(f"Dependency Skip")