如何在诗歌中使用nox?

时间:2020-01-16 11:24:41

标签: python pytest python-poetry

我想在由nox管理的项目中使用poetry

不好的是在nox会话中安装dev依赖项。

我有noxfile.py,如下所示:

import nox
from nox.sessions import Session
from pathlib import Path

__dir__ = Path(__file__).parent.absolute()


@nox.session(python=PYTHON)
def test(session: Session):
    session.install(str(__dir__))  # I want to use dev dependency here
    session.run("pytest")

如何在nox会话中安装dev依赖项?

2 个答案:

答案 0 :(得分:3)

当前,session.install在外壳程序中仅支持runs pip,不支持poetryinstall。您可以使用更通用的方法poetry激活session.run

示例:

@nox.session(python=False)
def tests(session):
    session.run('poetry', 'shell')
    session.run('poetry', 'install')
    session.run('pytest')

设置会话时,您可以通过禁用python virtualenv(python=False)的创建并使用poetry激活poetry shell来创建所有内容。

答案 1 :(得分:2)

经过一番尝试和错误,与我在@Yann的回答中所说的相反,似乎poetry忽略了VIRTUAL_ENV传递的nox变量。

受克劳迪奥·乔洛维奇(Claudio Jolowicz)精彩的系列Hypermodern Python的启发,我通过以下方法解决了这个问题:

@nox.session(python=PYTHON)
def test(session: Session) -> None:
    """
    Run unit tests.

    Arguments:
        session: The Session object.
    """
    args = session.posargs or ["--cov"]
    session.install(".")
    install_with_constraints(
        session,
        "coverage[toml]",
        "pytest",
        "pytest-cov",
        "pytest-mock",
        "pytest-flask",
    )
    session.run("pytest", *args)

在这里,我只是使用pip安装PEP517软件包。

不幸的是,通过pip安装的PEP517不支持可编辑的(“ -e”)开关。

仅供参考:install_with_constraints是我从Claudio借用的功能,经过编辑可在Windows上使用:

def install_with_constraints(
    session: Session, *args: str, **kwargs: Any
) -> None:
    """
    Install packages constrained by Poetry's lock file.

    This function is a wrapper for nox.sessions.Session.install. It
    invokes pip to install packages inside of the session's virtualenv.
    Additionally, pip is passed a constraints file generated from
    Poetry's lock file, to ensure that the packages are pinned to the
    versions specified in poetry.lock. This allows you to manage the
    packages as Poetry development dependencies.

    Arguments:
        session: The Session object.
        args: Command-line arguments for pip.
        kwargs: Additional keyword arguments for Session.install.
    """
    req_path = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
    session.run(
        "poetry",
        "export",
        "--dev",
        "--format=requirements.txt",
        f"--output={req_path}",
        external=True,
    )
    session.install(f"--constraint={req_path}", *args, **kwargs)
    os.unlink(req_path)