"""pytestでフィクスチャやフック(テスト実行前後に差し込む処理)を管理するモジュール"""
import os
from datetime import datetime

import boto3
import pytest
from moto import mock_s3
from py.xml import html  # type: ignore

from . import docstring_parser


@pytest.fixture
def aws_credentials():
    """Mocked AWS Credentials for moto."""
    os.environ["AWS_ACCESS_KEY_ID"] = "testing"
    os.environ["AWS_SECRET_ACCESS_KEY"] = "testing"
    os.environ["AWS_SECURITY_TOKEN"] = "testing"
    os.environ["AWS_SESSION_TOKEN"] = "testing"


@pytest.fixture
def s3_client(aws_credentials):
    with mock_s3():
        conn = boto3.client("s3", region_name="us-east-1")
        yield conn


# 以下、レポート出力用の設定

def pytest_html_report_title(report):
    # レポートタイトル
    report.title = "CRMデータ連携 CRMデータ取得機能 単体機能テスト結果報告書"


def pytest_html_results_table_header(cells):
    del cells[2:]
    cells.insert(3, html.th("Cases"))
    cells.insert(4, html.th("Arranges"))
    cells.insert(5, html.th("Expects"))
    cells.append(html.th("Time", class_="sortable time", col="time"))


def pytest_html_results_table_row(report, cells):
    del cells[2:]
    cells.insert(3, html.td(html.pre(report.cases)))  # 「テスト内容」をレポートに出力
    cells.insert(4, html.td(html.pre(report.arranges)))  # 「期待結果」をレポートに出力
    cells.insert(5, html.td(html.pre(report.expects)))  # 「期待結果」をレポートに出力
    cells.append(html.td(datetime.now(), class_="col-time"))  # ついでに「時間」もレポートに出力


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    docstring = docstring_parser.parse(str(item.function.__doc__))
    report.cases = docstring.get("Cases", '')  # 「テスト内容」を`report`に追加
    report.arranges = docstring.get("Arranges", '')  # 「準備作業」を`report`に追加
    report.expects = docstring.get("Expects", '')  # 「期待結果」を`report`に追加


def pytest_addoption(parser):
    parser.addoption(
        "--walk-through", action="store_true", default=False, help="run walk through tests"
    )


def pytest_configure(config):
    config.addinivalue_line("markers", "slow: mark test as slow to run")


def pytest_collection_modifyitems(config, items):
    skip_slow = pytest.mark.skip(reason="need --walk-through option to run")
    if config.getoption("--walk-through"):
        [item.add_marker(skip_slow) for item in items if "walk_through" not in item.keywords]
        return
    for item in items:
        if "walk_through" in item.keywords:
            item.add_marker(skip_slow)
