Debian Codegraph @

tests/u/scripts/test_cylc.py

raw
1 #!/usr/bin/env python3
2 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
3 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 import os
19 import sys
20 from types import SimpleNamespace
21 from typing import Callable
22 from unittest.mock import Mock
23
24 import pytest
25
26 from cylc.flow.scripts.cylc import iter_commands, pythonpath_manip
27
28
29 @pytest.fixture
30 def mock_entry_points(monkeypatch: pytest.MonkeyPatch):
31 """Mock a range of entry points."""
32 def _load_fail(*args, **kwargs):
33 raise ModuleNotFoundError('foo')
34
35 def _resolve_ok(*args, **kwargs):
36 return Mock()
37
38 def _require_ok(*args, **kwargs):
39 return
40
41 def _mocked_entry_points(include_bad: bool = False):
42 commands = {
43 # an entry point with all dependencies installed:
44 'good': SimpleNamespace(
45 name='good',
46 module='os.path',
47 load=_resolve_ok,
48 extras=[],
49 dist=SimpleNamespace(name='a'),
50 ),
51 # an entry point with optional dependencies missing:
52 'missing': SimpleNamespace(
53 name='missing',
54 module='not.a.python.module', # force an import error
55 load=_load_fail,
56 extras=[],
57 dist=SimpleNamespace(name='foo'),
58 ),
59 }
60 if include_bad:
61 # an entry point with non-optional dependencies unexpectedly
62 # missing:
63 commands['bad'] = SimpleNamespace(
64 name='bad',
65 module='not.a.python.module',
66 load=_load_fail,
67 require=_require_ok,
68 extras=[],
69 dist=SimpleNamespace(name='d'),
70 )
71 monkeypatch.setattr('cylc.flow.scripts.cylc.COMMANDS', commands)
72
73 return _mocked_entry_points
74
75
76 def test_iter_commands(mock_entry_points):
77 """Test listing commands works ok.
78
79 It should exclude commands with missing optional dependencies.
80 """
81 mock_entry_points()
82 commands = list(iter_commands())
83 assert [i[0] for i in commands] == ['good']
84
85
86 def test_iter_commands_bad(mock_entry_points):
87 """Test listing commands doesn't fail on import error."""
88 mock_entry_points(include_bad=True)
89 list(iter_commands())
90
91
92 def test_execute_cmd(
93 mock_entry_points,
94 capsys: pytest.CaptureFixture,
95 ):
96 """It should fail with a warning for commands with missing dependencies."""
97 # (stop IDEs reporting code as unreachable in this test)
98 execute_cmd: Callable
99 from cylc.flow.scripts.cylc import execute_cmd
100
101 mock_entry_points(include_bad=True)
102
103 # the "good" entry point should exit 0 (exit with no args)
104 assert execute_cmd('good') == 0
105 assert capsys.readouterr().err == ''
106
107 # the "missing" entry point should exit 1 with a warning to stderr
108 assert execute_cmd('missing') == 1
109 assert capsys.readouterr().err.strip() == (
110 '"cylc missing" requires "foo"\n\nModuleNotFoundError: foo'
111 )
112
113 # the "bad" entry point should log an error
114 assert execute_cmd('bad') == 1
115
116 stderr = capsys.readouterr().err.strip()
117 assert '"cylc bad" requires "d"' in stderr
118 assert 'ModuleNotFoundError: foo' in stderr
119
120
121 def test_pythonpath_manip(monkeypatch):
122 """pythonpath_manip removes items in PYTHONPATH from sys.path
123
124 and adds items from CYLC_PYTHONPATH
125 """
126
127 # Local CYLC_PYTHONPATH can mess with this test.
128 monkeypatch.delenv('CYLC_PYTHONPATH', raising=False)
129
130 monkeypatch.setenv('PYTHONPATH', '/remove1:/remove2')
131 monkeypatch.setattr('sys.path', ['/leave-alone', '/remove1', '/remove2'])
132 pythonpath_manip()
133 # ... we don't change PYTHONPATH
134 assert os.environ['PYTHONPATH'] == '/remove1:/remove2'
135 # ... but we do remove PYTHONPATH items from sys.path, and don't remove
136 # items there not in PYTHONPATH
137 assert sys.path == ['/leave-alone']
138 # If CYLC_PYTHONPATH is set we retrieve its contents and
139 # add them to the sys.path:
140 monkeypatch.setenv('CYLC_PYTHONPATH', '/add1:/add2')
141 pythonpath_manip()
142 assert sys.path == ['/add1', '/add2', '/leave-alone']