forked from wntrblm/nox
/
test_sessions.py
972 lines (754 loc) · 31.7 KB
/
test_sessions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
# Copyright 2016 Alethea Katherine Flowers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import logging
import operator
import os
import sys
import tempfile
from pathlib import Path
from unittest import mock
import pytest
import nox.command
import nox.manifest
import nox.registry
import nox.sessions
import nox.virtualenv
from nox import _options
from nox.logger import logger
def test__normalize_path():
envdir = "envdir"
normalize = nox.sessions._normalize_path
assert normalize(envdir, "hello") == os.path.join("envdir", "hello")
assert normalize(envdir, b"hello") == os.path.join("envdir", "hello")
assert normalize(envdir, "hello(world)") == os.path.join("envdir", "hello-world")
assert normalize(envdir, "hello(world, meep)") == os.path.join(
"envdir", "hello-world-meep"
)
assert normalize(envdir, 'tests(interpreter="python2.7", django="1.10")') == (
os.path.join("envdir", "tests-interpreter-python2-7-django-1-10")
)
def test__normalize_path_hash():
envdir = "d" * (100 - len("bin/pythonX.Y") - 10)
norm_path = nox.sessions._normalize_path(envdir, "a-really-long-virtualenv-path")
assert "a-really-long-virtualenv-path" not in norm_path
assert len(norm_path) < 100
def test__normalize_path_give_up():
envdir = "d" * 100
norm_path = nox.sessions._normalize_path(envdir, "any-path")
assert "any-path" in norm_path
class TestSession:
def make_session_and_runner(self):
func = mock.Mock(spec=["python"], python="3.7")
runner = nox.sessions.SessionRunner(
name="test",
signatures=["test"],
func=func,
global_config=_options.options.namespace(
posargs=[],
error_on_external_run=False,
install_only=False,
invoked_from=os.getcwd(),
),
manifest=mock.create_autospec(nox.manifest.Manifest),
)
runner.venv = mock.create_autospec(nox.virtualenv.VirtualEnv)
runner.venv.env = {}
runner.venv.bin_paths = ["/no/bin/for/you"]
return nox.sessions.Session(runner=runner), runner
def test_create_tmp(self):
session, runner = self.make_session_and_runner()
with tempfile.TemporaryDirectory() as root:
runner.global_config.envdir = root
tmpdir = session.create_tmp()
assert session.env["TMPDIR"] == tmpdir
assert tmpdir.startswith(root)
def test_create_tmp_twice(self):
session, runner = self.make_session_and_runner()
with tempfile.TemporaryDirectory() as root:
runner.global_config.envdir = root
runner.venv.bin = bin
session.create_tmp()
tmpdir = session.create_tmp()
assert session.env["TMPDIR"] == tmpdir
assert tmpdir.startswith(root)
def test_properties(self):
session, runner = self.make_session_and_runner()
with tempfile.TemporaryDirectory() as root:
runner.global_config.envdir = root
assert session.name is runner.friendly_name
assert session.env is runner.venv.env
assert session.posargs == runner.global_config.posargs
assert session.virtualenv is runner.venv
assert session.bin_paths is runner.venv.bin_paths
assert session.bin is runner.venv.bin_paths[0]
assert session.python is runner.func.python
assert session.invoked_from is runner.global_config.invoked_from
assert session.cache_dir == Path(runner.global_config.envdir).joinpath(
".cache"
)
def test_no_bin_paths(self):
session, runner = self.make_session_and_runner()
runner.venv.bin_paths = None
with pytest.raises(
ValueError, match=r"^The environment does not have a bin directory\.$"
):
session.bin
assert session.bin_paths is None
def test_virtualenv_as_none(self):
session, runner = self.make_session_and_runner()
runner.venv = None
with pytest.raises(ValueError, match="virtualenv"):
_ = session.virtualenv
def test_interactive(self):
session, runner = self.make_session_and_runner()
with mock.patch("nox.sessions.sys.stdin.isatty") as m_isatty:
m_isatty.return_value = True
assert session.interactive is True
m_isatty.return_value = False
assert session.interactive is False
def test_explicit_non_interactive(self):
session, runner = self.make_session_and_runner()
with mock.patch("nox.sessions.sys.stdin.isatty") as m_isatty:
m_isatty.return_value = True
runner.global_config.non_interactive = True
assert session.interactive is False
def test_chdir(self, tmpdir):
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
current_cwd = os.getcwd()
session, _ = self.make_session_and_runner()
session.chdir(cdto)
assert os.getcwd() == cdto
os.chdir(current_cwd)
def test_invoked_from(self, tmpdir):
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
current_cwd = os.getcwd()
session, _ = self.make_session_and_runner()
session.chdir(cdto)
assert session.invoked_from == current_cwd
os.chdir(current_cwd)
def test_chdir_pathlib(self, tmpdir):
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
current_cwd = os.getcwd()
session, _ = self.make_session_and_runner()
session.chdir(Path(cdto))
assert os.getcwd() == cdto
os.chdir(current_cwd)
def test_run_bad_args(self):
session, _ = self.make_session_and_runner()
with pytest.raises(ValueError, match="arg"):
session.run()
def test_run_with_func(self):
session, _ = self.make_session_and_runner()
assert session.run(operator.add, 1, 2) == 3
def test_run_with_func_error(self):
session, _ = self.make_session_and_runner()
def raise_value_error():
raise ValueError("meep")
with pytest.raises(nox.command.CommandFailed):
assert session.run(raise_value_error)
def test_run_install_only(self, caplog):
caplog.set_level(logging.INFO)
session, runner = self.make_session_and_runner()
runner.global_config.install_only = True
with mock.patch.object(nox.command, "run") as run:
assert session.run("spam", "eggs") is None
run.assert_not_called()
assert "install-only" in caplog.text
def test_run_install_only_should_install(self):
session, runner = self.make_session_and_runner()
runner.global_config.install_only = True
with mock.patch.object(nox.command, "run") as run:
session.install("spam")
session.run("spam", "eggs")
run.assert_called_once_with(
("python", "-m", "pip", "install", "spam"),
env=mock.ANY,
external=mock.ANY,
paths=mock.ANY,
silent=mock.ANY,
)
def test_run_success(self):
session, _ = self.make_session_and_runner()
result = session.run(sys.executable, "-c", "print(123)")
assert result
def test_run_error(self):
session, _ = self.make_session_and_runner()
with pytest.raises(nox.command.CommandFailed):
session.run(sys.executable, "-c", "import sys; sys.exit(1)")
def test_run_overly_env(self):
session, runner = self.make_session_and_runner()
runner.venv.env["A"] = "1"
runner.venv.env["B"] = "2"
result = session.run(
sys.executable,
"-c",
'import os; print(os.environ["A"], os.environ["B"])',
env={"B": "3"},
silent=True,
)
assert result.strip() == "1 3"
def test_run_external_not_a_virtualenv(self):
# Non-virtualenv sessions should always allow external programs.
session, runner = self.make_session_and_runner()
runner.venv = nox.virtualenv.ProcessEnv()
with mock.patch("nox.command.run", autospec=True) as run:
session.run(sys.executable, "--version")
run.assert_called_once_with(
(sys.executable, "--version"), external=True, env=mock.ANY, paths=None
)
def test_run_external_condaenv(self):
# condaenv sessions should always allow conda.
session, runner = self.make_session_and_runner()
runner.venv = mock.create_autospec(nox.virtualenv.CondaEnv)
runner.venv.allowed_globals = ("conda",)
runner.venv.env = {}
runner.venv.bin_paths = ["/path/to/env/bin"]
runner.venv.create.return_value = True
with mock.patch("nox.command.run", autospec=True) as run:
session.run("conda", "--version")
run.assert_called_once_with(
("conda", "--version"),
external=True,
env=mock.ANY,
paths=["/path/to/env/bin"],
)
def test_run_external_with_error_on_external_run(self):
session, runner = self.make_session_and_runner()
runner.global_config.error_on_external_run = True
with pytest.raises(nox.command.CommandFailed, match="External"):
session.run(sys.executable, "--version")
def test_run_external_with_error_on_external_run_condaenv(self):
session, runner = self.make_session_and_runner()
runner.venv = mock.create_autospec(nox.virtualenv.CondaEnv)
runner.venv.env = {}
runner.venv.bin_paths = ["/path/to/env/bin"]
runner.global_config.error_on_external_run = True
with pytest.raises(nox.command.CommandFailed, match="External"):
session.run(sys.executable, "--version")
def test_run_always_bad_args(self):
session, _ = self.make_session_and_runner()
with pytest.raises(ValueError) as exc_info:
session.run_always()
exc_args = exc_info.value.args
assert exc_args == ("At least one argument required to run_always().",)
def test_run_always_success(self):
session, _ = self.make_session_and_runner()
assert session.run_always(operator.add, 1300, 37) == 1337
def test_run_always_install_only(self, caplog):
session, runner = self.make_session_and_runner()
runner.global_config.install_only = True
assert session.run_always(operator.add, 23, 19) == 42
@pytest.mark.parametrize(
("no_install", "reused", "run_called"),
[
(True, True, False),
(True, False, True),
(False, True, True),
(False, False, True),
],
)
def test_run_always_no_install(self, no_install, reused, run_called):
session, runner = self.make_session_and_runner()
runner.global_config.no_install = no_install
runner.venv._reused = reused
with mock.patch.object(nox.command, "run") as run:
session.run_always("python", "-m", "pip", "install", "requests")
assert run.called is run_called
def test_conda_install_bad_args(self):
session, runner = self.make_session_and_runner()
runner.venv = mock.create_autospec(nox.virtualenv.CondaEnv)
runner.venv.location = "dummy"
with pytest.raises(ValueError, match="arg"):
session.conda_install()
def test_conda_install_bad_args_odd_nb_double_quotes(self):
session, runner = self.make_session_and_runner()
runner.venv = mock.create_autospec(nox.virtualenv.CondaEnv)
runner.venv.location = "./not/a/location"
with pytest.raises(ValueError, match="odd number of quotes"):
session.conda_install('a"a')
def test_conda_install_bad_args_cannot_escape(self):
session, runner = self.make_session_and_runner()
runner.venv = mock.create_autospec(nox.virtualenv.CondaEnv)
runner.venv.location = "./not/a/location"
with pytest.raises(ValueError, match="Cannot escape"):
session.conda_install('a"o"<a')
def test_conda_install_not_a_condaenv(self):
session, runner = self.make_session_and_runner()
runner.venv = None
with pytest.raises(ValueError, match="conda environment"):
session.conda_install()
@pytest.mark.parametrize(
"auto_offline", [False, True], ids="auto_offline={}".format
)
@pytest.mark.parametrize("offline", [False, True], ids="offline={}".format)
@pytest.mark.parametrize("conda", ["conda", "mamba"], ids=str)
@pytest.mark.parametrize(
"channel",
["", "conda-forge", ["conda-forge", "bioconda"]],
ids=["default", "conda-forge", "bioconda"],
)
def test_conda_install(self, auto_offline, offline, conda, channel):
runner = nox.sessions.SessionRunner(
name="test",
signatures=["test"],
func=mock.sentinel.func,
global_config=_options.options.namespace(posargs=[]),
manifest=mock.create_autospec(nox.manifest.Manifest),
)
runner.venv = mock.create_autospec(nox.virtualenv.CondaEnv)
runner.venv.location = "/path/to/conda/env"
runner.venv.env = {}
runner.venv.is_offline = lambda: offline
runner.venv.conda_cmd = conda
class SessionNoSlots(nox.sessions.Session):
pass
session = SessionNoSlots(runner=runner)
with mock.patch.object(session, "_run", autospec=True) as run:
args = ["--offline"] if auto_offline and offline else []
if channel and isinstance(channel, str):
args.append(f"--channel={channel}")
else:
args += [f"--channel={c}" for c in channel]
session.conda_install(
"requests", "urllib3", auto_offline=auto_offline, channel=channel
)
run.assert_called_once_with(
conda,
"install",
"--yes",
*args,
"--prefix",
"/path/to/conda/env",
"requests",
"urllib3",
silent=True,
external="error",
)
@pytest.mark.parametrize(
("no_install", "reused", "run_called"),
[
(True, True, False),
(True, False, True),
(False, True, True),
(False, False, True),
],
)
def test_conda_venv_reused_with_no_install(self, no_install, reused, run_called):
session, runner = self.make_session_and_runner()
runner.venv = mock.create_autospec(nox.virtualenv.CondaEnv)
runner.venv.location = "/path/to/conda/env"
runner.venv.env = {}
runner.venv.is_offline = lambda: True
runner.venv.conda_cmd = "conda"
runner.global_config.no_install = no_install
runner.venv._reused = reused
with mock.patch.object(nox.command, "run") as run:
session.conda_install("baked beans", "eggs", "spam")
assert run.called is run_called
@pytest.mark.parametrize(
"version_constraint",
["no", "yes", "already_dbl_quoted"],
ids="version_constraint={}".format,
)
def test_conda_install_non_default_kwargs(self, version_constraint):
runner = nox.sessions.SessionRunner(
name="test",
signatures=["test"],
func=mock.sentinel.func,
global_config=_options.options.namespace(posargs=[]),
manifest=mock.create_autospec(nox.manifest.Manifest),
)
runner.venv = mock.create_autospec(nox.virtualenv.CondaEnv)
runner.venv.location = "/path/to/conda/env"
runner.venv.env = {}
runner.venv.is_offline = lambda: False
runner.venv.conda_cmd = "conda"
class SessionNoSlots(nox.sessions.Session):
pass
session = SessionNoSlots(runner=runner)
if version_constraint == "no":
pkg_requirement = passed_arg = "urllib3"
elif version_constraint == "yes":
pkg_requirement = "urllib3<1.25"
passed_arg = f'"{pkg_requirement}"'
elif version_constraint == "already_dbl_quoted":
pkg_requirement = passed_arg = '"urllib3<1.25"'
else:
raise ValueError(version_constraint)
with mock.patch.object(session, "_run", autospec=True) as run:
session.conda_install("requests", pkg_requirement, silent=False)
run.assert_called_once_with(
"conda",
"install",
"--yes",
"--prefix",
"/path/to/conda/env",
"requests",
# this will be double quoted if unquoted constraint is present
passed_arg,
silent=False,
external="error",
)
def test_install_bad_args_no_arg(self):
session, _ = self.make_session_and_runner()
with pytest.raises(ValueError, match="arg"):
session.install()
def test_install_not_a_virtualenv(self):
session, runner = self.make_session_and_runner()
runner.venv = None
with pytest.raises(ValueError, match="virtualenv"):
session.install()
def test_install(self):
runner = nox.sessions.SessionRunner(
name="test",
signatures=["test"],
func=mock.sentinel.func,
global_config=_options.options.namespace(posargs=[]),
manifest=mock.create_autospec(nox.manifest.Manifest),
)
runner.venv = mock.create_autospec(nox.virtualenv.VirtualEnv)
runner.venv.env = {}
class SessionNoSlots(nox.sessions.Session):
pass
session = SessionNoSlots(runner=runner)
with mock.patch.object(session, "_run", autospec=True) as run:
session.install("requests", "urllib3")
run.assert_called_once_with(
"python",
"-m",
"pip",
"install",
"requests",
"urllib3",
silent=True,
external="error",
)
def test_install_non_default_kwargs(self):
runner = nox.sessions.SessionRunner(
name="test",
signatures=["test"],
func=mock.sentinel.func,
global_config=_options.options.namespace(posargs=[]),
manifest=mock.create_autospec(nox.manifest.Manifest),
)
runner.venv = mock.create_autospec(nox.virtualenv.VirtualEnv)
runner.venv.env = {}
class SessionNoSlots(nox.sessions.Session):
pass
session = SessionNoSlots(runner=runner)
with mock.patch.object(session, "_run", autospec=True) as run:
session.install("requests", "urllib3", silent=False)
run.assert_called_once_with(
"python",
"-m",
"pip",
"install",
"requests",
"urllib3",
silent=False,
external="error",
)
def test_notify(self):
session, runner = self.make_session_and_runner()
session.notify("other")
runner.manifest.notify.assert_called_once_with("other", None)
session.notify("other", posargs=["--an-arg"])
runner.manifest.notify.assert_called_with("other", ["--an-arg"])
def test_posargs_are_not_shared_between_sessions(self, monkeypatch, tmp_path):
registry = {}
monkeypatch.setattr("nox.registry._REGISTRY", registry)
@nox.session(venv_backend="none")
def test(session):
session.posargs.extend(["-x"])
@nox.session(venv_backend="none")
def lint(session):
if "-x" in session.posargs:
raise RuntimeError("invalid option: -x")
config = _options.options.namespace(posargs=[])
manifest = nox.manifest.Manifest(registry, config)
assert manifest["test"].execute()
assert manifest["lint"].execute()
def test_log(self, caplog):
caplog.set_level(logging.INFO)
session, _ = self.make_session_and_runner()
session.log("meep")
assert "meep" in caplog.text
def test_warn(self, caplog):
caplog.set_level(logging.WARNING)
session, _ = self.make_session_and_runner()
session.warn("meep")
assert "meep" in caplog.text
def test_debug(self, caplog):
caplog.set_level(logging.DEBUG)
session, _ = self.make_session_and_runner()
session.debug("meep")
assert "meep" in caplog.text
def test_error(self, caplog):
caplog.set_level(logging.ERROR)
session, _ = self.make_session_and_runner()
with pytest.raises(nox.sessions._SessionQuit, match="meep"):
session.error("meep")
def test_error_no_log(self):
session, _ = self.make_session_and_runner()
with pytest.raises(nox.sessions._SessionQuit):
session.error()
def test_skip_no_log(self):
session, _ = self.make_session_and_runner()
with pytest.raises(nox.sessions._SessionSkip):
session.skip()
@pytest.mark.parametrize(
("no_install", "reused", "run_called"),
[
(True, True, False),
(True, False, True),
(False, True, True),
(False, False, True),
],
)
def test_session_venv_reused_with_no_install(self, no_install, reused, run_called):
session, runner = self.make_session_and_runner()
runner.global_config.no_install = no_install
runner.venv._reused = reused
with mock.patch.object(nox.command, "run") as run:
session.install("eggs", "spam")
assert run.called is run_called
def test___slots__(self):
session, _ = self.make_session_and_runner()
with pytest.raises(AttributeError):
session.foo = "bar"
with pytest.raises(AttributeError):
session.quux
def test___dict__(self):
session, _ = self.make_session_and_runner()
expected = {name: getattr(session, name) for name in session.__slots__}
assert session.__dict__ == expected
class TestSessionRunner:
def make_runner(self):
func = mock.Mock()
func.python = None
func.venv_backend = None
func.reuse_venv = False
runner = nox.sessions.SessionRunner(
name="test",
signatures=["test(1, 2)"],
func=func,
global_config=_options.options.namespace(
noxfile=os.path.join(os.getcwd(), "noxfile.py"),
envdir="envdir",
posargs=[],
reuse_existing_virtualenvs=False,
error_on_missing_interpreters=False,
),
manifest=mock.create_autospec(nox.manifest.Manifest),
)
return runner
def test_properties(self):
runner = self.make_runner()
assert runner.name == "test"
assert runner.signatures == ["test(1, 2)"]
assert runner.func is not None
assert callable(runner.func)
assert isinstance(runner.description, str)
assert runner.global_config.posargs == []
assert isinstance(runner.manifest, nox.manifest.Manifest)
def test_str_and_friendly_name(self):
runner = self.make_runner()
runner.signatures = ["test(1, 2)", "test(3, 4)"]
assert str(runner) == "Session(name=test, signatures=test(1, 2), test(3, 4))"
assert runner.friendly_name == "test(1, 2)"
def test_description_property_one_line(self):
def foo():
"""Just one line"""
runner = self.make_runner()
runner.func = foo
assert runner.description == "Just one line"
def test_description_property_multi_line(self):
def foo():
"""
Multiline
Extra description
"""
runner = self.make_runner()
runner.func = foo
assert runner.description == "Multiline"
def test_description_property_no_doc(self):
def foo():
pass
runner = self.make_runner()
runner.func = foo
assert runner.description is None
def test__create_venv_process_env(self):
runner = self.make_runner()
runner.func.python = False
runner._create_venv()
assert isinstance(runner.venv, nox.virtualenv.ProcessEnv)
@mock.patch("nox.virtualenv.VirtualEnv.create", autospec=True)
def test__create_venv(self, create):
runner = self.make_runner()
runner._create_venv()
create.assert_called_once_with(runner.venv)
assert isinstance(runner.venv, nox.virtualenv.VirtualEnv)
assert runner.venv.location.endswith(os.path.join("envdir", "test-1-2"))
assert runner.venv.interpreter is None
assert runner.venv.reuse_existing is False
@pytest.mark.parametrize(
"create_method,venv_backend,expected_backend",
[
("nox.virtualenv.VirtualEnv.create", None, nox.virtualenv.VirtualEnv),
(
"nox.virtualenv.VirtualEnv.create",
"virtualenv",
nox.virtualenv.VirtualEnv,
),
("nox.virtualenv.VirtualEnv.create", "venv", nox.virtualenv.VirtualEnv),
("nox.virtualenv.CondaEnv.create", "conda", nox.virtualenv.CondaEnv),
],
)
def test__create_venv_options(self, create_method, venv_backend, expected_backend):
runner = self.make_runner()
runner.func.python = "coolpython"
runner.func.reuse_venv = True
runner.func.venv_backend = venv_backend
with mock.patch(create_method, autospec=True) as create:
runner._create_venv()
create.assert_called_once_with(runner.venv)
assert isinstance(runner.venv, expected_backend)
assert runner.venv.interpreter == "coolpython"
assert runner.venv.reuse_existing is True
def test__create_venv_unexpected_venv_backend(self):
runner = self.make_runner()
runner.func.venv_backend = "somenewenvtool"
with pytest.raises(ValueError, match="venv_backend"):
runner._create_venv()
def make_runner_with_mock_venv(self):
runner = self.make_runner()
runner._create_venv = mock.Mock()
return runner
def test_execute_noop_success(self, caplog):
caplog.set_level(logging.DEBUG)
runner = self.make_runner_with_mock_venv()
result = runner.execute()
assert result
runner.func.assert_called_once_with(mock.ANY)
assert "Running session test(1, 2)" in caplog.text
def test_execute_quit(self):
runner = self.make_runner_with_mock_venv()
def func(session):
session.error("meep")
runner.func = func
result = runner.execute()
assert result.status == nox.sessions.Status.ABORTED
def test_execute_skip(self):
runner = self.make_runner_with_mock_venv()
def func(session):
session.skip("meep")
runner.func = func
result = runner.execute()
assert result.status == nox.sessions.Status.SKIPPED
def test_execute_with_manifest_null_session_func(self):
runner = self.make_runner()
runner.func = nox.manifest._null_session_func
result = runner.execute()
assert result.status == nox.sessions.Status.SKIPPED
assert "no parameters" in result.reason
def test_execute_skip_missing_interpreter(self):
runner = self.make_runner_with_mock_venv()
runner._create_venv.side_effect = nox.virtualenv.InterpreterNotFound("meep")
result = runner.execute()
assert result.status == nox.sessions.Status.SKIPPED
assert "meep" in result.reason
def test_execute_error_missing_interpreter(self):
runner = self.make_runner_with_mock_venv()
runner.global_config.error_on_missing_interpreters = True
runner._create_venv.side_effect = nox.virtualenv.InterpreterNotFound("meep")
result = runner.execute()
assert result.status == nox.sessions.Status.FAILED
assert "meep" in result.reason
def test_execute_failed(self):
runner = self.make_runner_with_mock_venv()
def func(session):
raise nox.command.CommandFailed()
runner.func = func
result = runner.execute()
assert result.status == nox.sessions.Status.FAILED
def test_execute_interrupted(self):
runner = self.make_runner_with_mock_venv()
def func(session):
raise KeyboardInterrupt()
runner.func = func
with pytest.raises(KeyboardInterrupt):
runner.execute()
def test_execute_exception(self):
runner = self.make_runner_with_mock_venv()
def func(session):
raise ValueError("meep")
runner.func = func
result = runner.execute()
assert result.status == nox.sessions.Status.FAILED
class TestResult:
def test_init(self):
result = nox.sessions.Result(
session=mock.sentinel.SESSION, status=mock.sentinel.STATUS
)
assert result.session == mock.sentinel.SESSION
assert result.status == mock.sentinel.STATUS
def test__bool_true(self):
for status in (nox.sessions.Status.SUCCESS, nox.sessions.Status.SKIPPED):
result = nox.sessions.Result(session=object(), status=status)
assert bool(result)
assert result.__bool__()
assert result.__nonzero__()
def test__bool_false(self):
for status in (nox.sessions.Status.FAILED, nox.sessions.Status.ABORTED):
result = nox.sessions.Result(session=object(), status=status)
assert not bool(result)
assert not result.__bool__()
assert not result.__nonzero__()
def test__imperfect(self):
result = nox.sessions.Result(object(), nox.sessions.Status.SUCCESS)
assert result.imperfect == "was successful"
result = nox.sessions.Result(object(), nox.sessions.Status.FAILED)
assert result.imperfect == "failed"
result = nox.sessions.Result(
object(), nox.sessions.Status.FAILED, reason="meep"
)
assert result.imperfect == "failed: meep"
def test__log_success(self):
result = nox.sessions.Result(object(), nox.sessions.Status.SUCCESS)
with mock.patch.object(logger, "success") as success:
result.log("foo")
success.assert_called_once_with("foo")
def test__log_warning(self):
result = nox.sessions.Result(object(), nox.sessions.Status.SKIPPED)
with mock.patch.object(logger, "warning") as warning:
result.log("foo")
warning.assert_called_once_with("foo")
def test__log_error(self):
result = nox.sessions.Result(object(), nox.sessions.Status.FAILED)
with mock.patch.object(logger, "error") as error:
result.log("foo")
error.assert_called_once_with("foo")
def test__serialize(self):
result = nox.sessions.Result(
session=argparse.Namespace(
signatures=["siggy"], name="namey", func=mock.Mock()
),
status=nox.sessions.Status.SUCCESS,
)
answer = result.serialize()
assert answer["name"] == "namey"
assert answer["result"] == "success"
assert answer["result_code"] == 1
assert answer["signatures"] == ["siggy"]