Ejemplo n.º 1
0
def pytest_collection_modifyitems(config: pytest.Config,
                                  items: list[pytest.Function]) -> None:
    """Convert command line options to markers."""
    # Add skip_primer_external mark
    if not config.getoption("--primer-external"):
        skip_primer_external = pytest.mark.skip(
            reason="need --primer-external option to run")
        for item in items:
            if "primer_external_batch_one" in item.keywords:
                item.add_marker(skip_primer_external)

    # Add skip_primer_stdlib mark
    if not config.getoption("--primer-stdlib"):
        skip_primer_stdlib = pytest.mark.skip(
            reason="need --primer-stdlib option to run")
        for item in items:
            if "primer_stdlib" in item.keywords:
                item.add_marker(skip_primer_stdlib)

    # Add skip_cpu_cores mark
    if _cpu_count() < 2:
        skip_cpu_cores = pytest.mark.skip(
            reason="Need 2 or more cores for test to be meaningful")
        for item in items:
            if "needs_two_cores" in item.keywords:
                item.add_marker(skip_cpu_cores)
Ejemplo n.º 2
0
def pytest_configure(config: Config):
    markers = [
        f'order(index): mark a fixture to be evaluated in a certain order',
        f'early: mark a fixture to be evaluated earlier than others (order index {DEFAULT_EARLY_ORDER})',
        f'late: mark a fixture to be evaluated later than others (order index {DEFAULT_LATE_ORDER})',
    ]

    for marker in markers:
        config.addinivalue_line('markers', marker)
Ejemplo n.º 3
0
def klippy_session(session_args: Dict[str, pathlib.Path],
                   pytestconfig: pytest.Config) -> Iterator[KlippyProcess]:
    pytestconfig.stash[need_klippy_restart] = False
    kpath = pytestconfig.getoption('klipper_path', "~/klipper")
    kexec = pytestconfig.getoption('klipper_exec', None)
    if kexec is None:
        kexec = sys.executable
    exec = pathlib.Path(kexec).expanduser()
    klipper_path = pathlib.Path(kpath).expanduser()
    base_cmd = f"{exec} {klipper_path}/klippy/klippy.py "
    kproc = KlippyProcess(base_cmd, session_args)
    kproc.start()
    yield kproc
    kproc.stop()
Ejemplo n.º 4
0
def pytest_collection_modifyitems(items: List[pytest.Function], config: pytest.Config):
    initial_size = len(items)
    conditions = []
    filtered, skipped = 0, 0

    options = dict(
        standalone="PL_RUN_STANDALONE_TESTS",
        min_cuda_gpus="PL_RUN_CUDA_TESTS",
        slow="PL_RUN_SLOW_TESTS",
        ipu="PL_RUN_IPU_TESTS",
    )
    if os.getenv(options["standalone"], "0") == "1" and os.getenv(options["min_cuda_gpus"], "0") == "1":
        # special case: we don't have a CPU job for standalone tests, so we shouldn't run only cuda tests.
        # by deleting the key, we avoid filtering out the CPU tests
        del options["min_cuda_gpus"]

    for kwarg, env_var in options.items():
        # this will compute the intersection of all tests selected per environment variable
        if os.getenv(env_var, "0") == "1":
            conditions.append(env_var)
            for i, test in reversed(list(enumerate(items))):  # loop in reverse, since we are going to pop items
                already_skipped = any(marker.name == "skip" for marker in test.own_markers)
                if already_skipped:
                    # the test was going to be skipped anyway, filter it out
                    items.pop(i)
                    skipped += 1
                    continue
                has_runif_with_kwarg = any(
                    marker.name == "skipif" and marker.kwargs.get(kwarg) for marker in test.own_markers
                )
                if not has_runif_with_kwarg:
                    # the test has `@RunIf(kwarg=True)`, filter it out
                    items.pop(i)
                    filtered += 1

    if config.option.verbose >= 0 and (filtered or skipped):
        writer = config.get_terminal_writer()
        writer.write(
            f"\nThe number of tests has been filtered from {initial_size} to {initial_size - filtered} after the"
            f" filters {conditions}.\n{skipped} tests are marked as unconditional skips.\nIn total, {len(items)} tests"
            " will run.\n",
            flush=True,
            bold=True,
            purple=True,  # oh yeah, branded pytest messages
        )
Ejemplo n.º 5
0
def path_args(
        request: pytest.FixtureRequest, session_args: Dict[str, pathlib.Path],
        pytestconfig: pytest.Config) -> Iterator[Dict[str, pathlib.Path]]:
    path_marker = request.node.get_closest_marker("run_paths")
    paths: Dict[str, Any] = {
        "moonraker_conf": "base_server.conf",
        "secrets": "secrets.ini",
        "printer_cfg": "base_printer.cfg",
        "klippy_uds": None,
    }
    if path_marker is not None:
        paths.update(path_marker.kwargs)
    tmp_path = session_args["temp_path"]
    cfg_path = session_args["config_path"]
    mconf_dest = session_args["moonraker.conf"]
    mconf_asset = ASSETS.joinpath(f"moonraker/{paths['moonraker_conf']}")
    pcfg_asset = ASSETS.joinpath(f"klipper/{paths['printer_cfg']}")
    last_uds = session_args["klippy_uds_path"]
    if paths["klippy_uds"] is not None:
        tmp_uds = tmp_path.joinpath(paths["klippy_uds"])
        session_args["klippy_uds_path"] = tmp_uds
    if (not mconf_asset.samefile(session_args["mconf_asset"])
            or paths["klippy_uds"] is not None):
        session_args['mconf_asset'] = mconf_asset
        interpolate_config(mconf_asset, mconf_dest, session_args)
    if not pcfg_asset.samefile(session_args["pcfg_asset"]):
        pcfg_dest = session_args["printer.cfg"]
        session_args["pcfg_asset"] = pcfg_asset
        interpolate_config(pcfg_asset, pcfg_dest, session_args)
        pytestconfig.stash[need_klippy_restart] = True
    if paths["secrets"] != session_args["secrets_path"].name:
        secrets_asset = ASSETS.joinpath(f"moonraker/{paths['secrets']}")
        secrets_dest = tmp_path.joinpath(paths['secrets'])
        shutil.copy(secrets_asset, secrets_dest)
        session_args["secrets_path"] = secrets_dest
    if "moonraker_log" in paths:
        log_path = session_args["log_path"]
        session_args['moonraker.log'] = log_path.joinpath(
            paths["moonraker_log"])
    bkp_dest: pathlib.Path = cfg_path.joinpath(".moonraker.conf.bkp")
    if "moonraker_bkp" in paths:
        bkp_source = ASSETS.joinpath("moonraker/base_server.conf")
        bkp_dest = cfg_path.joinpath(paths["moonraker_bkp"])
        interpolate_config(bkp_source, bkp_dest, session_args)
    if "database" in paths:
        db_source = ASSETS.joinpath(f"moonraker/{paths['database']}")
        db_dest = session_args["database_path"]
        db_args = {"input": str(db_source), "destination": db_dest}
        dbtool.restore(db_args)
    yield session_args
    log = session_args.pop("moonraker.log", None)
    if log is not None and log.is_file():
        log.unlink()
    if bkp_dest.is_file():
        bkp_dest.unlink()
    for item in session_args["database_path"].iterdir():
        if item.is_file():
            item.unlink()
    session_args["klippy_uds_path"] = last_uds
    if paths["klippy_uds"] is not None:
        # restore the original uds path
        interpolate_config(mconf_asset, mconf_dest, session_args)
Ejemplo n.º 6
0
def klippy(klippy_session: KlippyProcess, pytestconfig: pytest.Config):
    if pytestconfig.stash[need_klippy_restart]:
        pytestconfig.stash[need_klippy_restart] = False
        klippy_session.restart()
    return klippy_session
Ejemplo n.º 7
0
def pytest_unconfigure(config: Config) -> None:
    for path in config.getini("pythonpath"):
        path_str = str(path)
        if path_str in sys.path:
            sys.path.remove(path_str)
Ejemplo n.º 8
0
def pytest_load_initial_conftests(early_config: Config) -> None:
    # `pythonpath = a b` will set `sys.path` to `[a, b, x, y, z, ...]`
    for path in reversed(early_config.getini("pythonpath")):
        sys.path.insert(0, str(path))