Exemple #1
0
def session(*args: Any, **kwargs: Any) -> Any:
    """Drop-in replacement for the :func:`nox.session` decorator.

    Use this decorator instead of ``@nox.session``. Session functions are passed
    :class:`Session` instead of :class:`nox.sessions.Session`; otherwise, the
    decorators work exactly the same.

    Args:
        args: Positional arguments are forwarded to ``nox.session``.
        kwargs: Keyword arguments are forwarded to ``nox.session``.

    Returns:
        The decorated session function.
    """
    if not args:
        return functools.partial(session, **kwargs)

    [function] = args

    @functools.wraps(function)
    def wrapper(session: nox.Session, *_args, **_kwargs) -> None:
        proxy = Session(session)
        function(proxy, *_args, **_kwargs)

    return nox.session(wrapper, **kwargs)  # type: ignore[call-overload]
Exemple #2
0
    def _decorator(f):
        s_name = name if name is not None else f.__name__
        for pyv, _param in product(all_python, all_params):
            if (pyv, _param) not in envs:
                # create a dummy folder to avoid creating a useless venv ?
                env_dir = Path(".nox") / ("%s-%s-%s-%s" % (s_name, pyv.replace('.', '-'), grid_param_name, _param))
                env_dir.mkdir(parents=True, exist_ok=True)

        # check the signature of f
        foo_sig = signature(f)
        missing = env_contents_names - set(foo_sig.parameters)
        if len(missing) > 0:
            raise ValueError("Session function %r does not contain environment parameter(s) %r" % (f.__name__, missing))

        # modify the exposed signature if needed
        new_sig = None
        if len(env_contents_names) > 0:
            new_sig = remove_signature_parameters(foo_sig, *env_contents_names)

        if has_parameter:
            if grid_param_name in foo_sig.parameters:
                raise ValueError("Internal error, this parameter has a reserved name: %r" % grid_param_name)
            else:
                new_sig = add_signature_parameters(new_sig, last=(grid_param_name,))

        @wraps(f, new_sig=new_sig)
        def _f_wrapper(**kwargs):
            # find the session arg
            session = kwargs['session']    # type: Session

            # get the versions to use for this environment
            try:
                if has_parameter:
                    grid_param = kwargs.pop(grid_param_name)
                    params_dct = envs[(session.python, grid_param)]
                else:
                    params_dct = envs[session.python]
            except KeyError:
                # Skip this session, it is a dummy one
                nox_logger.warning(
                    "Skipping configuration, this is not supported in python version %r" % session.python)
                return

            # inject the parameters in the args:
            kwargs.update(params_dct)

            # finally execute the session
            return f(**kwargs)

        if has_parameter:
            _f_wrapper = nox.parametrize(grid_param_name, all_params)(_f_wrapper)

        _f_wrapper = nox.session(python=all_python, reuse_venv=reuse_venv, name=name,
                                 venv_backend=venv_backend, venv_params=venv_params)(_f_wrapper)
        return _f_wrapper
Exemple #3
0
def nox_session_with_grid(python=None,
                          py=None,
                          envs: Mapping[str, Mapping[str, Any]] = None,
                          reuse_venv: Optional[bool] = None,
                          name: Optional[str] = None,
                          venv_backend: Any = None,
                          venv_params: Any = None,
                          grid_param_name: str = None,
                          **kwargs):
    """
    Since nox is not yet capable to define a build matrix with python and parameters mixed in the same parametrize
    this implements it with a dirty hack.
    To remove when https://github.com/theacodes/nox/pull/404 is complete

    :param envs:
    :param env_python_key:
    :return:
    """
    if envs is None:
        # Fast track default to @nox.session
        return nox.session(python=python,
                           py=py,
                           reuse_venv=reuse_venv,
                           name=name,
                           venv_backend=venv_backend,
                           venv_params=venv_params,
                           **kwargs)
    else:
        # Current limitation : session param names can be 'python' or 'py' only
        if py is not None or python is not None:
            raise ValueError(
                "`python` session argument can not be provided both directly and through the "
                "`env` with `session_param_names`")

    # First examine the env and collect the parameter values for python
    all_python = []
    all_params = []

    env_contents_names = None
    has_parameter = None
    for env_id, env_params in envs.items():
        # consistency checks for the env_id
        if has_parameter is None:
            has_parameter = isinstance(env_id, tuple)
        else:
            if has_parameter != isinstance(env_id, tuple):
                raise ValueError(
                    "All keys in env should be tuples, or not be tuples. Error for %r"
                    % env_id)

        # retrieve python version and parameter
        if not has_parameter:
            if env_id not in all_python:
                all_python.append(env_id)
        else:
            if len(env_id) != 2:
                raise ValueError("Only a size-2 tuple can be used as env id")
            py_id, param_id = env_id
            if py_id not in all_python:
                all_python.append(py_id)
            if param_id not in all_params:
                all_params.append(param_id)

        # consistency checks for the dict contents.
        if env_contents_names is None:
            env_contents_names = set(env_params.keys())
        else:
            if env_contents_names != set(env_params.keys()):
                raise ValueError(
                    "Environment %r parameters %r does not match parameters in the first environment: %r"
                    % (env_id, env_contents_names, set(env_params.keys())))

    if has_parameter and not grid_param_name:
        raise ValueError(
            "You must provide a grid parameter name when the env keys are tuples."
        )

    def _decorator(f):
        s_name = name if name is not None else f.__name__
        for pyv, _param in product(all_python, all_params):
            if (pyv, _param) not in envs:
                # create a dummy folder to avoid creating a useless venv ?
                env_dir = Path(".nox") / (
                    "%s-%s-%s-%s" %
                    (s_name, pyv.replace('.', '-'), grid_param_name, _param))
                env_dir.mkdir(parents=True, exist_ok=True)

        # check the signature of f
        foo_sig = signature(f)
        missing = env_contents_names - set(foo_sig.parameters)
        if len(missing) > 0:
            raise ValueError(
                "Session function %r does not contain environment parameter(s) %r"
                % (f.__name__, missing))

        # modify the exposed signature if needed
        new_sig = None
        if len(env_contents_names) > 0:
            new_sig = remove_signature_parameters(foo_sig, *env_contents_names)

        if has_parameter:
            if grid_param_name in foo_sig.parameters:
                raise ValueError(
                    "Internal error, this parameter has a reserved name: %r" %
                    grid_param_name)
            else:
                new_sig = add_signature_parameters(new_sig,
                                                   last=(grid_param_name, ))

        @wraps(f, new_sig=new_sig)
        def _f_wrapper(**kwargs):
            # find the session arg
            session = kwargs['session']  # type: Session

            # get the versions to use for this environment
            try:
                if has_parameter:
                    grid_param = kwargs.pop(grid_param_name)
                    params_dct = envs[(session.python, grid_param)]
                else:
                    params_dct = envs[session.python]
            except KeyError:
                # Skip this session, it is a dummy one
                nox_logger.warning(
                    "Skipping configuration, this is not supported in python version %r"
                    % session.python)
                return

            # inject the parameters in the args:
            kwargs.update(params_dct)

            # finally execute the session
            return f(**kwargs)

        if has_parameter:
            _f_wrapper = nox.parametrize(grid_param_name,
                                         all_params)(_f_wrapper)

        _f_wrapper = nox.session(python=all_python,
                                 reuse_venv=reuse_venv,
                                 name=name,
                                 venv_backend=venv_backend,
                                 venv_params=venv_params)(_f_wrapper)
        return _f_wrapper

    return _decorator
    OUTFILE = os.path.join(".nox", "reqs.txt")

    session.install("pipenv")
    reqs = subprocess.check_output(["pipenv", "lock", "--dev", "-r"])

    with open(OUTFILE, "wb+") as f:
        f.write(reqs)

    session.install("-r", OUTFILE)


if os.environ.get("CI"):
    # On CI, we allow it to set the Python version
    nox_session = nox.session
else:
    nox_session = nox.session(python=["3.6", "3.7", "3.8"])


@nox_session
@nox.parametrize("django", ["2.2", "3.0"])
@nox.parametrize("drf", ["3.10", "3.11"])
def test(session: Session, django: str, drf: str) -> None:
    """Run unit tests."""
    install_pipenv_requirements(session)
    session.install(f"django=={django}")
    session.install(f"djangorestframework=={drf}")
    session.run(
        "py.test",
        "--flake8",
        "--cov=rest_framework_json_schema",
        "--cov-append",
Exemple #5
0
    assert examples_dir.exists

    examples = []
    for item in examples_dir.iterdir():
        if not item.is_dir():
            continue
        example_json = Path(item, "example.json")
        if example_json.exists() and example_json.is_file():
            examples.append(item.name)
    return examples


EXAMPLES = get_all_example_names()


def example(session: Session, name: str = None):
    if name is None:
        session.log("There are no examples.")
        return
    example_run(session, name)


# Only create the actual example session, when there are examples present
if EXAMPLES:

    example = nox.parametrize("name", EXAMPLES)(example)
    example = nox.session(example, python=["3.5", "3.6", "3.7"])

else:
    example = nox.session(example)