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
|
# Copyright 2013-2022 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 itertools as it
import json
import os
import sys
import pytest
import llnl.util.filesystem as fs
import spack.ci as ci
import spack.ci_needs_workaround as cinw
import spack.ci_optimization as ci_opt
import spack.config as cfg
import spack.environment as ev
import spack.error
import spack.main as spack_main
import spack.paths as spack_paths
import spack.spec as spec
import spack.util.gpg
import spack.util.spack_yaml as syaml
@pytest.fixture
def tmp_scope():
"""Creates a temporary configuration scope"""
base_name = 'internal-testing-scope'
current_overrides = set(
x.name for x in
cfg.config.matching_scopes(r'^{0}'.format(base_name)))
num_overrides = 0
scope_name = base_name
while scope_name in current_overrides:
scope_name = '{0}{1}'.format(base_name, num_overrides)
num_overrides += 1
with cfg.override(cfg.InternalConfigScope(scope_name)):
yield scope_name
def test_urlencode_string():
s = 'Spack Test Project'
s_enc = ci.url_encode_string(s)
assert(s_enc == 'Spack+Test+Project')
@pytest.mark.skipif(sys.platform == 'win32',
reason="Not supported on Windows (yet)")
def test_import_signing_key(mock_gnupghome):
signing_key_dir = spack_paths.mock_gpg_keys_path
signing_key_path = os.path.join(signing_key_dir, 'package-signing-key')
with open(signing_key_path) as fd:
signing_key = fd.read()
# Just make sure this does not raise any exceptions
ci.import_signing_key(signing_key)
def test_configure_compilers(mutable_config):
def assert_missing(config):
assert('install_missing_compilers' not in config or
config['install_missing_compilers'] is False)
def assert_present(config):
assert('install_missing_compilers' in config and
config['install_missing_compilers'] is True)
original_config = cfg.get('config')
assert_missing(original_config)
ci.configure_compilers('FIND_ANY', scope='site')
second_config = cfg.get('config')
assert_missing(second_config)
ci.configure_compilers('INSTALL_MISSING')
last_config = cfg.get('config')
assert_present(last_config)
@pytest.mark.skipif(sys.platform == 'win32',
reason="Not supported on Windows (yet)")
def test_get_concrete_specs(config, mutable_mock_env_path, mock_packages):
e = ev.create('test1')
e.add('dyninst')
e.concretize()
dyninst_hash = None
hash_dict = {}
with e as active_env:
for s in active_env.all_specs():
hash_dict[s.name] = s.build_hash()
if s.name == 'dyninst':
dyninst_hash = s.build_hash()
assert(dyninst_hash)
dep_builds = 'libdwarf;libelf'
spec_map = ci.get_concrete_specs(
active_env, dyninst_hash, 'dyninst', dep_builds, 'NONE')
assert('root' in spec_map and 'deps' in spec_map)
concrete_root = spec_map['root']
assert(concrete_root.build_hash() == dyninst_hash)
concrete_deps = spec_map['deps']
for key, obj in concrete_deps.items():
assert(obj.build_hash() == hash_dict[key])
s = spec.Spec('dyninst')
print('nonconc spec name: {0}'.format(s.name))
spec_map = ci.get_concrete_specs(
active_env, s.name, s.name, dep_builds, 'FIND_ANY')
assert('root' in spec_map and 'deps' in spec_map)
class FakeWebResponder(object):
def __init__(self, response_code=200, content_to_read=[]):
self._resp_code = response_code
self._content = content_to_read
self._read = [False for c in content_to_read]
def open(self, request):
return self
def getcode(self):
return self._resp_code
def read(self, length=None):
if len(self._content) <= 0:
return None
if not self._read[-1]:
return_content = self._content[-1]
if length:
self._read[-1] = True
else:
self._read.pop()
self._content.pop()
return return_content
self._read.pop()
self._content.pop()
return None
@pytest.mark.maybeslow
def test_register_cdash_build(monkeypatch):
build_name = 'Some pkg'
base_url = 'http://cdash.fake.org'
project = 'spack'
site = 'spacktests'
track = 'Experimental'
response_obj = {
'buildid': 42
}
fake_responder = FakeWebResponder(
content_to_read=[json.dumps(response_obj)])
monkeypatch.setattr(ci, 'build_opener', lambda handler: fake_responder)
build_id, build_stamp = ci.register_cdash_build(
build_name, base_url, project, site, track)
assert(build_id == 42)
@pytest.mark.skipif(sys.platform == 'win32',
reason="Not supported on Windows (yet)")
def test_relate_cdash_builds(config, mutable_mock_env_path, mock_packages,
monkeypatch, capfd):
e = ev.create('test1')
e.add('dyninst')
e.concretize()
dyninst_hash = None
hash_dict = {}
with e as active_env:
for s in active_env.all_specs():
hash_dict[s.name] = s.build_hash()
if s.name == 'dyninst':
dyninst_hash = s.build_hash()
assert(dyninst_hash)
dep_builds = 'libdwarf;libelf'
spec_map = ci.get_concrete_specs(
active_env, dyninst_hash, 'dyninst', dep_builds, 'NONE')
assert('root' in spec_map and 'deps' in spec_map)
cdash_api_url = 'http://cdash.fake.org'
job_build_id = '42'
cdash_project = 'spack'
cdashids_mirror_url = 'https://my.fake.mirror'
dep_cdash_ids = {
'libdwarf': 1,
'libelf': 2
}
monkeypatch.setattr(ci, 'read_cdashid_from_mirror',
lambda s, u: dep_cdash_ids.pop(s.name))
fake_responder = FakeWebResponder(
content_to_read=['libdwarf', 'libelf'])
monkeypatch.setattr(ci, 'build_opener', lambda handler: fake_responder)
ci.relate_cdash_builds(spec_map, cdash_api_url, job_build_id,
cdash_project, [cdashids_mirror_url])
assert(not dep_cdash_ids)
dep_cdash_ids = {
'libdwarf': 1,
'libelf': 2
}
fake_responder._resp_code = 400
ci.relate_cdash_builds(spec_map, cdash_api_url, job_build_id,
cdash_project, [cdashids_mirror_url])
out, err = capfd.readouterr()
assert('Warning: Relate builds' in err)
assert('failed' in err)
dep_cdash_ids = {}
# Just make sure passing None for build id doesn't result in any
# calls to "read_cdashid_from_mirror"
ci.relate_cdash_builds(spec_map, cdash_api_url, None, cdash_project,
[cdashids_mirror_url])
@pytest.mark.skipif(sys.platform == 'win32',
reason="Not supported on Windows (yet)")
def test_read_write_cdash_ids(config, tmp_scope, tmpdir, mock_packages):
working_dir = tmpdir.join('working_dir')
mirror_dir = working_dir.join('mirror')
mirror_url = 'file://{0}'.format(mirror_dir.strpath)
mirror_cmd = spack_main.SpackCommand('mirror')
mirror_cmd('add', '--scope', tmp_scope, 'test_mirror', mirror_url)
mock_spec = spec.Spec('archive-files').concretized()
orig_cdashid = '42'
ci.write_cdashid_to_mirror(orig_cdashid, mock_spec, mirror_url)
# Now read it back
read_cdashid = ci.read_cdashid_from_mirror(mock_spec, mirror_url)
assert(str(read_cdashid) == orig_cdashid)
def test_download_and_extract_artifacts(tmpdir, monkeypatch):
os.environ['GITLAB_PRIVATE_TOKEN'] = 'faketoken'
url = 'https://www.nosuchurlexists.itsfake/artifacts.zip'
working_dir = os.path.join(tmpdir.strpath, 'repro')
test_artifacts_path = os.path.join(
spack_paths.test_path, 'data', 'ci', 'gitlab', 'artifacts.zip')
with open(test_artifacts_path, 'rb') as fd:
fake_responder = FakeWebResponder(content_to_read=[fd.read()])
monkeypatch.setattr(ci, 'build_opener', lambda handler: fake_responder)
ci.download_and_extract_artifacts(url, working_dir)
found_zip = fs.find(working_dir, 'artifacts.zip')
assert(len(found_zip) == 0)
found_install = fs.find(working_dir, 'install.sh')
assert(len(found_install) == 1)
fake_responder._resp_code = 400
with pytest.raises(spack.error.SpackError):
ci.download_and_extract_artifacts(url, working_dir)
def test_setup_spack_repro_version(tmpdir, capfd, last_two_git_commits,
monkeypatch):
c1, c2 = last_two_git_commits
repro_dir = os.path.join(tmpdir.strpath, 'repro')
spack_dir = os.path.join(repro_dir, 'spack')
os.makedirs(spack_dir)
prefix_save = spack.paths.prefix
monkeypatch.setattr(spack.paths, 'prefix', '/garbage')
ret = ci.setup_spack_repro_version(repro_dir, c2, c1)
out, err = capfd.readouterr()
assert(not ret)
assert('Unable to find the path' in err)
monkeypatch.setattr(spack.paths, 'prefix', prefix_save)
monkeypatch.setattr(spack.util.executable, 'which', lambda cmd: None)
ret = ci.setup_spack_repro_version(repro_dir, c2, c1)
out, err = capfd.readouterr()
assert(not ret)
assert('requires git' in err)
class mock_git_cmd(object):
def __init__(self, *args, **kwargs):
self.returncode = 0
self.check = None
def __call__(self, *args, **kwargs):
if self.check:
self.returncode = self.check(*args, **kwargs)
else:
self.returncode = 0
git_cmd = mock_git_cmd()
monkeypatch.setattr(spack.util.executable, 'which', lambda cmd: git_cmd)
git_cmd.check = lambda *a, **k: 1 if len(a) > 2 and a[2] == c2 else 0
ret = ci.setup_spack_repro_version(repro_dir, c2, c1)
out, err = capfd.readouterr()
assert(not ret)
assert('Missing commit: {0}'.format(c2) in err)
git_cmd.check = lambda *a, **k: 1 if len(a) > 2 and a[2] == c1 else 0
ret = ci.setup_spack_repro_version(repro_dir, c2, c1)
out, err = capfd.readouterr()
assert(not ret)
assert('Missing commit: {0}'.format(c1) in err)
git_cmd.check = lambda *a, **k: 1 if a[0] == 'clone' else 0
ret = ci.setup_spack_repro_version(repro_dir, c2, c1)
out, err = capfd.readouterr()
assert(not ret)
assert('Unable to clone' in err)
git_cmd.check = lambda *a, **k: 1 if a[0] == 'checkout' else 0
ret = ci.setup_spack_repro_version(repro_dir, c2, c1)
out, err = capfd.readouterr()
assert(not ret)
assert('Unable to checkout' in err)
git_cmd.check = lambda *a, **k: 1 if 'merge' in a else 0
ret = ci.setup_spack_repro_version(repro_dir, c2, c1)
out, err = capfd.readouterr()
assert(not ret)
assert('Unable to merge {0}'.format(c1) in err)
@pytest.mark.parametrize(
"obj, proto",
[
({}, []),
],
)
def test_ci_opt_argument_checking(obj, proto):
"""Check that matches() and subkeys() return False when `proto` is not a dict."""
assert not ci_opt.matches(obj, proto)
assert not ci_opt.subkeys(obj, proto)
@pytest.mark.parametrize(
"yaml",
[
{'extends': 1},
],
)
def test_ci_opt_add_extends_non_sequence(yaml):
"""Check that add_extends() exits if 'extends' is not a sequence."""
yaml_copy = yaml.copy()
ci_opt.add_extends(yaml, None)
assert yaml == yaml_copy
def test_ci_workarounds():
fake_root_spec = 'x' * 544
fake_spack_ref = 'x' * 40
common_variables = {
'SPACK_COMPILER_ACTION': 'NONE',
'SPACK_IS_PR_PIPELINE': 'False',
}
common_before_script = [
'git clone "https://github.com/spack/spack"',
' && '.join((
'pushd ./spack',
'git checkout "{ref}"'.format(ref=fake_spack_ref),
'popd')),
'. "./spack/share/spack/setup-env.sh"'
]
def make_build_job(name, deps, stage, use_artifact_buildcache, optimize,
use_dependencies):
variables = common_variables.copy()
variables['SPACK_JOB_SPEC_PKG_NAME'] = name
result = {
'stage': stage,
'tags': ['tag-0', 'tag-1'],
'artifacts': {
'paths': [
'jobs_scratch_dir',
'cdash_report',
name + '.spec.json',
name + '.cdashid',
name
],
'when': 'always'
},
'retry': {'max': 2, 'when': ['always']},
'after_script': ['rm -rf "./spack"'],
'script': ['spack ci rebuild'],
'image': {'name': 'spack/centos7', 'entrypoint': ['']}
}
if optimize:
result['extends'] = ['.c0', '.c1']
else:
variables['SPACK_ROOT_SPEC'] = fake_root_spec
result['before_script'] = common_before_script
result['variables'] = variables
if use_dependencies:
result['dependencies'] = (
list(deps) if use_artifact_buildcache
else [])
else:
result['needs'] = [
{'job': dep, 'artifacts': use_artifact_buildcache}
for dep in deps]
return {name: result}
def make_rebuild_index_job(
use_artifact_buildcache, optimize, use_dependencies):
result = {
'stage': 'stage-rebuild-index',
'script': 'spack buildcache update-index -d s3://mirror',
'tags': ['tag-0', 'tag-1'],
'image': {'name': 'spack/centos7', 'entrypoint': ['']},
'after_script': ['rm -rf "./spack"'],
}
if optimize:
result['extends'] = '.c0'
else:
result['before_script'] = common_before_script
return {'rebuild-index': result}
def make_factored_jobs(optimize):
return {
'.c0': {'before_script': common_before_script},
'.c1': {'variables': {'SPACK_ROOT_SPEC': fake_root_spec}}
} if optimize else {}
def make_stage_list(num_build_stages):
return {
'stages': (
['-'.join(('stage', str(i))) for i in range(num_build_stages)]
+ ['stage-rebuild-index'])}
def make_yaml_obj(use_artifact_buildcache, optimize, use_dependencies):
result = {}
result.update(make_build_job(
'pkg-a', [], 'stage-0', use_artifact_buildcache, optimize,
use_dependencies))
result.update(make_build_job(
'pkg-b', ['pkg-a'], 'stage-1', use_artifact_buildcache, optimize,
use_dependencies))
result.update(make_build_job(
'pkg-c', ['pkg-a', 'pkg-b'], 'stage-2', use_artifact_buildcache,
optimize, use_dependencies))
result.update(make_rebuild_index_job(
use_artifact_buildcache, optimize, use_dependencies))
result.update(make_factored_jobs(optimize))
result.update(make_stage_list(3))
return result
# test every combination of:
# use artifact buildcache: true or false
# run optimization pass: true or false
# convert needs to dependencies: true or false
for use_ab in (False, True):
original = make_yaml_obj(
use_artifact_buildcache=use_ab,
optimize=False,
use_dependencies=False)
for opt, deps in it.product(*(((False, True),) * 2)):
# neither optimizing nor converting needs->dependencies
if not (opt or deps):
# therefore, nothing to test
continue
predicted = make_yaml_obj(
use_artifact_buildcache=use_ab,
optimize=opt,
use_dependencies=deps)
actual = original.copy()
if opt:
actual = ci_opt.optimizer(actual)
if deps:
actual = cinw.needs_to_dependencies(actual)
predicted = syaml.dump_config(
ci_opt.sort_yaml_obj(predicted), default_flow_style=True)
actual = syaml.dump_config(
ci_opt.sort_yaml_obj(actual), default_flow_style=True)
assert(predicted == actual)
def test_get_spec_filter_list(mutable_mock_env_path, config, mutable_mock_repo):
"""Test that given an active environment and list of touched pkgs,
we get the right list of possibly-changed env specs"""
e1 = ev.create('test')
e1.add('mpileaks')
e1.add('hypre')
e1.concretize()
"""
Concretizing the above environment results in the following graphs:
mpileaks -> mpich (provides mpi virtual dep of mpileaks)
-> callpath -> dyninst -> libelf
-> libdwarf -> libelf
-> mpich (provides mpi dep of callpath)
hypre -> openblas-with-lapack (provides lapack and blas virtual deps of hypre)
"""
touched = ['libdwarf']
# traversing both directions from libdwarf in the graphs depicted
# above results in the following possibly affected env specs:
# mpileaks, callpath, dyninst, libdwarf, and libelf. Unaffected
# specs are mpich, plus hypre and it's dependencies.
affected_specs = ci.get_spec_filter_list(e1, touched)
affected_pkg_names = set([s.name for s in affected_specs])
expected_affected_pkg_names = set(['mpileaks',
'callpath',
'dyninst',
'libdwarf',
'libelf'])
assert affected_pkg_names == expected_affected_pkg_names
|