import pathlib
import pytest


def pytest_addoption(parser):
    """Register custom command line options.

    An initialization hook called by pytest to register options.
    This implementation registers an option to set an output path
    for data that is generated by tests. Test data would normally be
    stored in a temporary location and removed when tests have run.
    If a custom output path is provided it will not be deleted and
    can be used to save test data for later inspection or usage.
    """
    parser.addoption("--test-data-output-path", default=None)


@pytest.fixture(scope="session")
def f_test_data_output_path(pytestconfig, tmp_path_factory):
    """Path for data generated by tests.

    Creates output path for tests generating data. Unless specified
    on command line, a temporary path will be used, which is deleted
    after tests are run.
    """
    p = pytestconfig.getoption("test_data_output_path")
    if p is None:
        p = tmp_path_factory.mktemp("testdata")
    else:
        p = pathlib.Path().cwd() / pathlib.Path(p)
        if not p.exists():
            p.mkdir()
    return p
