Noxfile
Nox Default in a name called noxfile.py Find the configuration in the file . Running nox when , You can use --noxfile Parameter to specify other files .
Define the session
Format :session(func=None, python=None, py=None, reuse_venv=None, name=None, venv_backend=None), Specify the decorated function as a session .
Nox Conversation is through being @nox.session The standard of decoration Python Function to configure . for example :
import nox
@nox.session
def tests(session):
session.run('pytest')
Conversation description
You can use the document string to add a description to the session . The first line will show... When the session is listed . for example :
import nox
@nox.session
def tests(session):
"""Run the test suite."""
session.run('pytest')
nox --list The command will show :
$ nox --list
Available sessions:
* tests -> Run the test suite.
Session name
By default ,Nox Use the name of the decorated function as the name of the session . This is very effective for most projects , however , if necessary , You can also use @nox.session Of name The parameter comes from defining the name of the session . for example :
import nox
@nox.session(name="custom-name")
def a_very_long_function_name(session):
print("Hello!")
nox --list The command will show :
$ nox --list
Available sessions:
* custom-name
You can tell nox Run the session with a custom name :
$ nox --session "custom-name"
Hello!
Configure the virtualenv
By default ,Nox Create a new... For each session virtualenv when , Will use Nox The same interpreter used . If you use Python 3.6 Installed nox, be nox Will be used by default in all sessions Python 3.6.
By giving @nox.session Appoint python Parameters ( Or its alias py), You can tell nox Use different Python Interpreter / edition :
@nox.session(python='2.7')
def tests(session):
pass
You can also tell Nox The use of multiple Python The interpreter runs your session .Nox A separate... Will be created for each interpreter specified virtualenv And run the session . for example , The following session will run twice —— One time use Python 2.7, One time use Python 3.6:
@nox.session(python=['2.7', '3.6'])
def tests(session):
pass
When you provide a version number ,Nox It will automatically add python To determine the name of the executable . however ,Nox You can also accept the full executable name . If you want to use pypy To test , for example :
@nox.session(python=['2.7', '3.6', 'pypy-6.0'])
def tests(session):
pass
When preparing your conversation ,Nox A separate session will be created for each interpreter . You can run nox --list When I see these conversations . For example, this Noxfile:
@nox.session(python=['2.7', '3.5', '3.6', '3.7'])
def tests(session):
pass
Will generate these conversations :
* tests-2.7
* tests-3.5
* tests-3.6
* tests-3.7
Be careful , This extension occurs before parameterization , So you can still parameterize sessions of multiple interpreters .
If you want to completely disable creation virtualenv, You can set python Parameter is False:
@nox.session(python=False)
def tests(session):
pass
Last , You can also specify reuse every time virtualenv, Instead of recreating :
@nox.session(
python=['2.7', '3.6'],
reuse_venv=True)
def tests(session):
pass
Pass the parameters into the session
It's often useful to pass parameters into a test session . Here is a simple example , Demonstrates how to use parameters to test specific files :
@nox.session
def test(session):
session.install('pytest')
if session.posargs:
test_files = session.posargs
else:
test_files = ['test_a.py', 'test_b.py']
session.run('pytest', *test_files)
Now if you run :
nox
that nox Will run :
pytest test_a.py test_b.py
But if you run :
nox -- test_c.py
that nox Will run :
pytest test_c.py
Parameterized session
The parameters of the session can be nox.parametrize() Decorator for parameterization . Here is a typical parametric installation Django Example of version :
@nox.session
@nox.parametrize('django', ['1.9', '2.0'])
def tests(session, django):
session.install(f'django=={django}')
session.run('pytest')
When you run nox when , It creates two different sessions :
$ nox
nox > Running session tests(django='1.9')
nox > pip install django==1.9
...
nox > Running session tests(djano='2.0')
nox > pip install django==2.0
nox.parametrize() The interface and usage of pytest Parameterization of Similar .
Format :parametrize(arg_names, arg_values_list, ids=None)
The function is to parameterize a session .
take arg_values_list The list is assigned to the corresponding arg_names, Add a new call to the decorated session function . Parameterization is performed during session discovery , Every call serves as nox A single session of .
Parameters :
You can also stack decorators , Make it generate a session that combines parameters , for example :
@nox.session
@nox.parametrize('django', ['1.9', '2.0'])
@nox.parametrize('database', ['postgres', 'mysql'])
def tests(session, django, database):
...
If you run nox —list, You will see that it generates the following session set :
* tests(database='postgres', django='1.9')
* tests(database='mysql', django='1.9')
* tests(database='postgres', django='2.0')
* tests(database='mysql', django='2.0')
If you just want to run a parameterized session , see also " Specify the parameterized session " part .
Friendly names for parameterized sessions
The name of the automatically generated parameterized session , Such as tests(django='1.9', database='postgres'), Use keywords to filter , It can also be long and difficult to deal with .
In this scenario , It can provide auxiliary customization for parameterized sessions id . These two examples are equivalent :
@nox.session
@nox.parametrize('django',
['1.9', '2.0'],
ids=['old', 'new'])
def tests(session, django):
...
@nox.session
@nox.parametrize('django', [
nox.param('1.9', id='old'),
nox.param('2.0', id='new'),
])
def tests(session, django):
...
When running nox --list when , You will see their new id:
* tests(old)
* tests(new)
You can use it. nox --sessions "tests(old)", And so on .
This also applies to stack parameterization .id It was combined during the combination . for example :
@nox.session
@nox.parametrize(
'django',
['1.9', '2.0'],
ids=["old", "new"])
@nox.parametrize(
'database',
['postgres', 'mysql'],
ids=["psql", "mysql"])
def tests(session, django, database):
...
function nox --list It will generate these conversations :
* tests(psql, old)
* tests(mysql, old)
* tests(psql, new)
* tests(mysql, new)
Conversation object
Nox Will use Session Class to call your session function .
class Session(runner) ¶
The session object is passed to each user-defined session function .
This is Nox The main way to install packages and run commands in a session .
bin¶——virtualenv Of bin Catalog
cd(dir)¶——chdir() An alias for
chdir(dir)¶—— Change the current working directory
conda_install(
args,
*kwargs)¶
call conda install To install packages in a session environment .
Install the package directly :
session.conda_install('pandas')
session.conda_install('numpy', 'scipy')
session.conda_install('--channel=conda-forge', 'dask==2.1.0')
according to requirements.txt File to install the package :
session.conda_install('--file', 'requirements.txt')
session.conda_install('--file', 'requirements-dev.txt')
Don't destroy conda Installed dependencies install packages :
session.install('.', '--no-deps')
# Install in editable mode.
session.install('-e', '.', '--no-deps')
The rest of the keyword parameters follow run() identical .
env¶—— A dictionary of environment variables , To all orders .
error(
args,
*kwargs)¶—— Abort the session immediately and log an error at will .
install(
args,
*kwargs)¶ —— call pip In conversation virtualenv Inner installation package .
Direct installation package :
session.install('pytest')
session.install('requests', 'mock')
session.install('requests[security]==2.9.1')
according to requirements.txt File to install the package :
session.install('-r', 'requirements.txt')
session.install('-r', 'requirements-dev.txt')
Install the current package :
session.install('.')
# Install in editable mode.
session.install('-e', '.')
The rest of the keyword parameters follow run() identical .
interactive¶ —— If Nox Run... In an interactive session , Then return to True, Otherwise return to False.
log(
args,
*kwargs)¶—— Output a log during the session .
notify(target)¶ —— Put the given session at the end of the queue .
This method is idempotent ; Multiple notifications of the same session are invalid .
Parameters :target (Union[str, Callable])—— Sessions that need notification . This specifies the appropriate string ( And nox -s Use the same ) Or use function objects .
Command must install string list specified , for example :
session.run('pytest', '-k', 'fast', 'tests/')
session.run('flake8', '--import-order-style=google')
You can't pass everything as a string . for example , You can't do that :session.run('pytest -k fast tests/')
You can use it. env Set environment variables for commands :
session.run(
'bash', '-c', 'echo $SOME_ENV',
env={'SOME_ENV': 'Hello'})
You can still use it success_codes , tell nox Treat non-zero exit code as success . for example , If you want to pytest Of “tests discovered, but none selected” Mistakes are regarded as success :
session.run(
'pytest', '-k', 'not slow',
success_codes=[0, 5])
stay Windows On , image del Such built-in commands cannot be called directly , But you can use cmd /c To call them :
session.run('cmd', '/c', 'del', 'docs/modules.rst')
Parameters :
env (dict or None)—— Environment variable dictionary for exposing to commands . By default , Pass all environment variables .
silent (bool) —— Silent command output , Unless the order fails . The default is False.
success_codes (list, tuple, or None)—— A series of return codes considered successful . By default , Only 0 Considered a success .
external (bool) —— If False( The default value is ), So don't virtualenv The program in the path will give an alarm . If True, No alarm will be given . These alarms can be used --error-on-external-run Turn it into an error . This pair doesn't have virtualenv The conversation has no effect on .
skip(
args,
*kwargs)¶ —— Jump out of the conversation immediately , And randomly record an alarm .
virtualenv¶ —— Run all commands virtualenv.
modify Noxfile Medium Nox Behavior
Nox There are various command line parameters , Can be used to modify its behavior . Some of them can also be found in Noxfile Use in nox.options Appoint . for example , If you want to Nox Of virtualenvs Store in a different directory , You don't need to pass it on to nox:
import nox
nox.options.envdir = ".cache"
@nox.session
def tests(session):
...
perhaps , If you want to provide a set of sessions that run by default :
import nox
nox.options.sessions = ["lint", "tests-3.6"]
...
The following options can be found in Noxfile It is specified in :
Calling nox when , Any option specified on the command line takes precedence over Noxfile The options specified in . If you specify... On the command line --sessions or --keywords, So in Noxfile Both options specified in will be ignored .
The above is all the content shared this time , Want to know more python Welcome to official account :Python Programming learning circle , send out “J” Free access to , Daily dry goods sharing