summaryrefslogtreecommitdiff
path: root/lib/spack/spack/test/cmd/commands.py
blob: 68d28f5684352d95a0828f5efbf6959d714f83ba (plain) (blame)
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
# Copyright 2013-2024 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

import filecmp
import os
import shutil
import subprocess

import pytest

import spack.cmd
import spack.main
import spack.paths
from spack.cmd.commands import _dest_to_fish_complete, _positional_to_subroutine

commands = spack.main.SpackCommand("commands", subprocess=True)

parser = spack.main.make_argument_parser()
spack.main.add_all_commands(parser)


def test_names():
    """Test default output of spack commands."""
    out1 = commands().strip().split("\n")
    assert out1 == spack.cmd.all_commands()
    assert "rm" not in out1

    out2 = commands("--aliases").strip().split("\n")
    assert out1 != out2
    assert "rm" in out2

    out3 = commands("--format=names").strip().split("\n")
    assert out1 == out3


def test_subcommands():
    """Test subcommand traversal."""
    out1 = commands("--format=subcommands")
    assert "spack mirror create" in out1
    assert "spack buildcache list" in out1
    assert "spack repo add" in out1
    assert "spack pkg diff" in out1
    assert "spack url parse" in out1
    assert "spack view symlink" in out1
    assert "spack rm" not in out1
    assert "spack compiler add" not in out1

    out2 = commands("--aliases", "--format=subcommands")
    assert "spack mirror create" in out2
    assert "spack buildcache list" in out2
    assert "spack repo add" in out2
    assert "spack pkg diff" in out2
    assert "spack url parse" in out2
    assert "spack view symlink" in out2
    assert "spack rm" in out2
    assert "spack compiler add" in out2


@pytest.mark.not_on_windows("subprocess not supported on Windows")
def test_override_alias():
    """Test that spack commands cannot be overriden by aliases."""

    install = spack.main.SpackCommand("install", subprocess=True)
    instal = spack.main.SpackCommand("instal", subprocess=True)

    out = install(fail_on_error=False, global_args=["-c", "config:aliases:install:find"])
    assert "install requires a package argument or active environment" in out
    assert "Alias 'install' (mapping to 'find') attempts to override built-in command" in out

    out = install(fail_on_error=False, global_args=["-c", "config:aliases:foo bar:find"])
    assert "Alias 'foo bar' (mapping to 'find') contains a space, which is not supported" in out

    out = instal(fail_on_error=False, global_args=["-c", "config:aliases:instal:find"])
    assert "install requires a package argument or active environment" not in out


def test_rst():
    """Do some simple sanity checks of the rst writer."""
    out1 = commands("--format=rst")
    assert "spack mirror create" in out1
    assert "spack buildcache list" in out1
    assert "spack repo add" in out1
    assert "spack pkg diff" in out1
    assert "spack url parse" in out1
    assert "spack view symlink" in out1
    assert "spack rm" not in out1
    assert "spack compiler add" not in out1

    out2 = commands("--aliases", "--format=rst")
    assert "spack mirror create" in out2
    assert "spack buildcache list" in out2
    assert "spack repo add" in out2
    assert "spack pkg diff" in out2
    assert "spack url parse" in out2
    assert "spack view symlink" in out2
    assert "spack rm" in out2
    assert "spack compiler add" in out2


def test_rst_with_input_files(tmpdir):
    filename = tmpdir.join("file.rst")
    with filename.open("w") as f:
        f.write(
            """
.. _cmd-spack-fetch:
cmd-spack-list:
.. _cmd-spack-stage:
_cmd-spack-install:
.. _cmd-spack-patch:
"""
        )

    out = commands("--format=rst", str(filename))
    for name in ["fetch", "stage", "patch"]:
        assert (":ref:`More documentation <cmd-spack-%s>`" % name) in out

    for name in ["list", "install"]:
        assert (":ref:`More documentation <cmd-spack-%s>`" % name) not in out


def test_rst_with_header(tmpdir):
    local_commands = spack.main.SpackCommand("commands")
    fake_header = "this is a header!\n\n"

    filename = tmpdir.join("header.txt")
    with filename.open("w") as f:
        f.write(fake_header)

    out = local_commands("--format=rst", "--header", str(filename))
    assert out.startswith(fake_header)

    with pytest.raises(spack.main.SpackCommandError):
        local_commands("--format=rst", "--header", "asdfjhkf")


def test_rst_update(tmpdir):
    update_file = tmpdir.join("output")

    commands("--update", str(update_file))
    assert update_file.exists()


def test_update_with_header(tmpdir):
    update_file = tmpdir.join("output")

    commands("--update", str(update_file))
    assert update_file.exists()
    fake_header = "this is a header!\n\n"

    filename = tmpdir.join("header.txt")
    with filename.open("w") as f:
        f.write(fake_header)

    commands("--update", str(update_file), "--header", str(filename))


@pytest.mark.xfail
def test_no_pipe_error():
    """Make sure we don't see any pipe errors when piping output."""

    proc = subprocess.Popen(
        ["spack", "commands", "--format=rst"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )

    # Call close() on stdout to cause a broken pipe
    proc.stdout.close()
    proc.wait()
    stderr = proc.stderr.read().decode("utf-8")

    assert "Broken pipe" not in stderr


def test_bash_completion():
    """Test the bash completion writer."""
    out1 = commands("--format=bash")

    # Make sure header not included
    assert "_bash_completion_spack() {" not in out1
    assert "_all_packages() {" not in out1

    # Make sure subcommands appear
    assert "_spack_remove() {" in out1
    assert "_spack_compiler_find() {" in out1

    # Make sure aliases don't appear
    assert "_spack_rm() {" not in out1
    assert "_spack_compiler_add() {" not in out1

    # Make sure options appear
    assert "-h --help" in out1

    # Make sure subcommands are called
    for function in _positional_to_subroutine.values():
        assert function in out1

    out2 = commands("--aliases", "--format=bash")

    # Make sure aliases appear
    assert "_spack_rm() {" in out2
    assert "_spack_compiler_add() {" in out2


def test_fish_completion():
    """Test the fish completion writer."""
    out1 = commands("--format=fish")

    # Make sure header not included
    assert "function __fish_spack_argparse" not in out1
    assert "complete -c spack --erase" not in out1

    # Make sure subcommands appear
    assert "__fish_spack_using_command remove" in out1
    assert "__fish_spack_using_command compiler find" in out1

    # Make sure aliases don't appear
    assert "__fish_spack_using_command rm" not in out1
    assert "__fish_spack_using_command compiler add" not in out1

    # Make sure options appear
    assert "-s h -l help" in out1

    # Make sure subcommands are called
    for complete_cmd in _dest_to_fish_complete.values():
        assert complete_cmd in out1

    out2 = commands("--aliases", "--format=fish")

    # Make sure aliases appear
    assert "__fish_spack_using_command rm" in out2
    assert "__fish_spack_using_command compiler add" in out2


@pytest.mark.parametrize("shell", ["bash", "fish"])
def test_update_completion_arg(shell, tmpdir, monkeypatch):
    """Test the update completion flag."""

    tmpdir.join(shell).mkdir()
    mock_infile = tmpdir.join(shell).join(f"spack-completion.{shell}")
    mock_outfile = tmpdir.join(f"spack-completion.{shell}")

    mock_args = {
        shell: {
            "aliases": True,
            "format": shell,
            "header": str(mock_infile),
            "update": str(mock_outfile),
        }
    }

    # make a mock completion file missing the --update-completion argument
    real_args = spack.cmd.commands.update_completion_args
    shutil.copy(real_args[shell]["header"], mock_args[shell]["header"])
    with open(real_args[shell]["update"]) as old:
        old_file = old.read()
        with open(mock_args[shell]["update"], "w") as mock:
            mock.write(old_file.replace("update-completion", ""))

    monkeypatch.setattr(spack.cmd.commands, "update_completion_args", mock_args)

    local_commands = spack.main.SpackCommand("commands")
    # ensure things fail if --update-completion isn't specified alone
    with pytest.raises(spack.main.SpackCommandError):
        local_commands("--update-completion", "-a")

    # ensure arg is restored
    assert "update-completion" not in mock_outfile.read()
    local_commands("--update-completion")
    assert "update-completion" in mock_outfile.read()


# Note: this test is never expected to be supported on Windows
@pytest.mark.not_on_windows("Shell completion script generator fails on windows")
@pytest.mark.parametrize("shell", ["bash", "fish"])
def test_updated_completion_scripts(shell, tmpdir):
    """Make sure our shell tab completion scripts remain up-to-date."""

    msg = (
        "It looks like Spack's command-line interface has been modified. "
        "Please update Spack's shell tab completion scripts by running:\n\n"
        "    spack commands --update-completion\n\n"
        "and adding the changed files to your pull request."
    )

    header = os.path.join(spack.paths.share_path, shell, f"spack-completion.{shell}")
    script = "spack-completion.{0}".format(shell)
    old_script = os.path.join(spack.paths.share_path, script)
    new_script = str(tmpdir.join(script))

    commands("--aliases", "--format", shell, "--header", header, "--update", new_script)

    assert filecmp.cmp(old_script, new_script), msg