forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbootstrap_test.py
executable file
·1528 lines (1293 loc) · 55.2 KB
/
bootstrap_test.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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright 2016 The Kubernetes Authors.
#
# 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.
"""Tests for bootstrap."""
# pylint: disable=protected-access, attribute-defined-outside-init
import argparse
import json
import os
import select
import signal
import subprocess
import tempfile
import time
import unittest
import bootstrap
BRANCH = 'random_branch'
BUILD = 'random_build'
FAIL = ['/bin/bash', '-c', 'exit 1']
JOB = 'random_job'
PASS = ['/bin/bash', '-c', 'exit 0']
PULL = 12345
REPO = 'github.com/random_org/random_repo'
ROBOT = 'fake-service-account.json'
ROOT = '/random/root'
UPLOAD = 'fake-gs://fake-bucket'
class Stub(object):
"""Replace thing.param with replacement until exiting with."""
def __init__(self, thing, param, replacement):
self.thing = thing
self.param = param
self.replacement = replacement
self.old = getattr(thing, param)
setattr(thing, param, self.replacement)
def __enter__(self, *a, **kw):
return self.replacement
def __exit__(self, *a, **kw):
setattr(self.thing, self.param, self.old)
class FakeCall(object):
def __init__(self):
self.calls = []
def __call__(self, *a, **kw):
self.calls.append((a, kw))
class FakeSubprocess(object):
"""Keep track of calls."""
def __init__(self):
self.calls = []
self.file_data = []
self.output = {}
def __call__(self, cmd, *a, **kw):
self.calls.append((cmd, a, kw))
for arg in cmd:
if arg.startswith('/') and os.path.exists(arg):
self.file_data.append(open(arg).read())
if kw.get('output') and self.output.get(cmd[0]):
return self.output[cmd[0]].pop(0)
return None
# pylint: disable=invalid-name
def Pass(*_a, **_kw):
"""Do nothing."""
pass
def Truth(*_a, **_kw):
"""Always true."""
return True
def Bomb(*a, **kw):
"""Always raise."""
raise AssertionError('Should not happen', a, kw)
# pylint: enable=invalid-name
class ReadAllTest(unittest.TestCase):
endless = 0
ended = time.time() - 50
number = 0
end = -1
def fileno(self):
return self.end
def readline(self):
line = 'line %d\n' % self.number
self.number += 1
return line
def test_read_more(self):
"""Read lines until we clear the buffer, noting there may be more."""
lines = []
total = 10
def more_lines(*_a, **_kw):
if len(lines) < total:
return [self], [], []
return [], [], []
with Stub(select, 'select', more_lines):
done = bootstrap.read_all(self.endless, self, lines.append)
self.assertFalse(done)
self.assertEqual(total, len(lines))
expected = ['line %d' % d for d in range(total)]
self.assertEqual(expected, lines)
def test_read_expired(self):
"""Read nothing as we are expired, noting there may be more."""
lines = []
with Stub(select, 'select', lambda *a, **kw: ([], [], [])):
done = bootstrap.read_all(self.ended, self, lines.append)
self.assertFalse(done)
self.assertFalse(lines)
def test_read_end(self):
"""Note we reached the end of the stream."""
lines = []
with Stub(select, 'select', lambda *a, **kw: ([self], [], [])):
with Stub(self, 'readline', lambda: ''):
done = bootstrap.read_all(self.endless, self, lines.append)
self.assertTrue(done)
class TerminateTest(unittest.TestCase):
"""Tests for termiante()."""
pid = 1234
pgid = 5555
terminated = False
killed = False
def terminate(self):
self.terminated = True
def kill(self):
self.killed = True
def getpgid(self, pid):
self.got = pid
return self.pgid
def killpg(self, pgig, sig):
self.killed_pg = (pgig, sig)
def test_terminate_later(self):
"""Do nothing if end is in the future."""
timeout = bootstrap.terminate(time.time() + 50, self, False)
self.assertFalse(timeout)
def test_terminate_never(self):
"""Do nothing if end is zero."""
timeout = bootstrap.terminate(0, self, False)
self.assertFalse(timeout)
def test_terminate_terminate(self):
"""Terminate pid if after end and kill is false."""
timeout = bootstrap.terminate(time.time() - 50, self, False)
self.assertTrue(timeout)
self.assertFalse(self.killed)
self.assertTrue(self.terminated)
def test_terminate_kill(self):
"""Kill process group if after end and kill is true."""
with Stub(os, 'getpgid', self.getpgid), Stub(os, 'killpg', self.killpg):
timeout = bootstrap.terminate(time.time() - 50, self, True)
self.assertTrue(timeout)
self.assertFalse(self.terminated)
self.assertTrue(self.killed)
self.assertEqual(self.pid, self.got)
self.assertEqual(self.killed_pg, (self.pgid, signal.SIGKILL))
class SubprocessTest(unittest.TestCase):
"""Tests for call()."""
def test_stdin(self):
"""Will write to subprocess.stdin."""
with self.assertRaises(subprocess.CalledProcessError) as cpe:
bootstrap._call(0, ['/bin/bash'], stdin='exit 92')
self.assertEqual(92, cpe.exception.returncode)
def test_check_true(self):
"""Raise on non-zero exit codes if check is set."""
with self.assertRaises(subprocess.CalledProcessError):
bootstrap._call(0, FAIL, check=True)
bootstrap._call(0, PASS, check=True)
def test_check_default(self):
"""Default to check=True."""
with self.assertRaises(subprocess.CalledProcessError):
bootstrap._call(0, FAIL)
bootstrap._call(0, PASS)
@staticmethod
def test_check_false():
"""Never raise when check is not set."""
bootstrap._call(0, FAIL, check=False)
bootstrap._call(0, PASS, check=False)
def test_output(self):
"""Output is returned when requested."""
cmd = ['/bin/bash', '-c', 'echo hello world']
self.assertEqual(
'hello world\n', bootstrap._call(0, cmd, output=True))
def test_zombie(self):
with self.assertRaises(subprocess.CalledProcessError):
# make a zombie
bootstrap._call(0, ['/bin/bash', '-c', 'A=$BASHPID && ( kill -STOP $A ) & exit 1'])
class PullRefsTest(unittest.TestCase):
"""Tests for pull_ref, branch_ref, ref_has_shas, and pull_numbers."""
def test_multiple_no_shas(self):
"""Test master,1111,2222."""
self.assertEqual(
bootstrap.pull_ref('master,123,456'),
([
'master',
'+refs/pull/123/head:refs/pr/123',
'+refs/pull/456/head:refs/pr/456',
], [
'FETCH_HEAD',
'refs/pr/123',
'refs/pr/456',
]),
)
def test_pull_has_shas(self):
self.assertTrue(bootstrap.ref_has_shas('master:abcd'))
self.assertFalse(bootstrap.ref_has_shas('123'))
self.assertFalse(bootstrap.ref_has_shas(123))
self.assertFalse(bootstrap.ref_has_shas(None))
def test_pull_numbers(self):
self.assertListEqual(bootstrap.pull_numbers(123), ['123'])
self.assertListEqual(bootstrap.pull_numbers('master:abcd'), [])
self.assertListEqual(
bootstrap.pull_numbers('master:abcd,123:qwer,124:zxcv'),
['123', '124'])
def test_pull_ref(self):
self.assertEqual(
bootstrap.pull_ref('master:abcd,123:effe'),
(['master', '+refs/pull/123/head:refs/pr/123'], ['abcd', 'effe'])
)
self.assertEqual(
bootstrap.pull_ref('123'),
(['+refs/pull/123/merge'], ['FETCH_HEAD'])
)
def test_branch_ref(self):
self.assertEqual(
bootstrap.branch_ref('branch:abcd'),
(['branch'], ['abcd'])
)
self.assertEqual(
bootstrap.branch_ref('master'),
(['master'], ['FETCH_HEAD'])
)
class ConfigureSshKeyTest(unittest.TestCase):
"""Tests for configure_ssh_key()."""
def test_empty(self):
"""Do not change environ if no ssh key."""
fake_env = {}
with Stub(os, 'environ', fake_env):
with bootstrap.configure_ssh_key(''):
self.assertFalse(fake_env)
def test_full(self):
fake_env = {}
with Stub(os, 'environ', fake_env):
with bootstrap.configure_ssh_key('hello there'):
self.assertIn('GIT_SSH', fake_env)
with open(fake_env['GIT_SSH']) as fp:
buf = fp.read()
self.assertIn('hello there', buf)
self.assertIn('ssh ', buf)
self.assertIn(' -i ', buf)
self.assertFalse(fake_env) # Resets env
def test_full_old_value(self):
fake_env = {'GIT_SSH': 'random-value'}
old_env = dict(fake_env)
with Stub(os, 'environ', fake_env):
with bootstrap.configure_ssh_key('hello there'):
self.assertNotEqual(old_env, fake_env)
self.assertEqual(old_env, fake_env)
class CheckoutTest(unittest.TestCase):
"""Tests for checkout()."""
def test_clean(self):
"""checkout cleans and resets if asked to."""
fake = FakeSubprocess()
with Stub(os, 'chdir', Pass):
bootstrap.checkout(fake, REPO, REPO, None, PULL, clean=True)
self.assertTrue(any(
'clean' in cmd for cmd, _, _ in fake.calls if 'git' in cmd))
self.assertTrue(any(
'reset' in cmd for cmd, _, _ in fake.calls if 'git' in cmd))
def test_fetch_retries(self):
self.tries = 0
expected_attempts = 3
def third_time_charm(cmd, *_a, **_kw):
if 'fetch' not in cmd: # init/checkout are unlikely to fail
return
self.tries += 1
if self.tries != expected_attempts:
raise subprocess.CalledProcessError(128, cmd, None)
with Stub(os, 'chdir', Pass):
with Stub(time, 'sleep', Pass):
bootstrap.checkout(third_time_charm, REPO, REPO, None, PULL)
self.assertEqual(expected_attempts, self.tries)
def test_pull_ref(self):
"""checkout fetches the right ref for a pull."""
fake = FakeSubprocess()
with Stub(os, 'chdir', Pass):
bootstrap.checkout(fake, REPO, REPO, None, PULL)
expected_ref = bootstrap.pull_ref(PULL)[0][0]
self.assertTrue(any(
expected_ref in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))
def test_branch(self):
"""checkout fetches the right ref for a branch."""
fake = FakeSubprocess()
with Stub(os, 'chdir', Pass):
bootstrap.checkout(fake, REPO, REPO, BRANCH, None)
expected_ref = BRANCH
self.assertTrue(any(
expected_ref in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))
def test_repo(self):
"""checkout initializes and fetches the right repo."""
fake = FakeSubprocess()
with Stub(os, 'chdir', Pass):
bootstrap.checkout(fake, REPO, REPO, BRANCH, None)
expected_uri = 'https://%s' % REPO
self.assertTrue(any(
expected_uri in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))
def test_branch_xor_pull(self):
"""Either branch or pull specified, not both."""
with Stub(os, 'chdir', Bomb):
with self.assertRaises(ValueError):
bootstrap.checkout(Bomb, REPO, REPO, None, None)
with self.assertRaises(ValueError):
bootstrap.checkout(Bomb, REPO, REPO, BRANCH, PULL)
def test_happy(self):
"""checkout sanity check."""
fake = FakeSubprocess()
with Stub(os, 'chdir', Pass):
bootstrap.checkout(fake, REPO, REPO, BRANCH, None)
self.assertTrue(any(
'--tags' in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))
self.assertTrue(any(
'FETCH_HEAD' in cmd for cmd, _, _ in fake.calls
if 'checkout' in cmd))
def test_repo_path(self):
"""checkout repo to different local path."""
fake = FakeSubprocess()
repo_path = "foo/bar"
with Stub(os, 'chdir', Pass):
bootstrap.checkout(fake, REPO, repo_path, BRANCH, None)
expected_uri = 'https://%s' % REPO
self.assertTrue(any(
expected_uri in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))
self.assertTrue(any(
repo_path in cmd for cmd, _, _ in fake.calls if 'init' in cmd))
class ParseReposTest(unittest.TestCase):
def test_bare(self):
"""--bare works."""
args = bootstrap.parse_args(['--job=foo', '--bare'])
self.assertFalse(bootstrap.parse_repos(args))
def test_pull_branch_none(self):
"""args.pull and args.branch should be None"""
args = bootstrap.parse_args(['--job=foo', '--bare'])
self.assertIsNone(args.pull)
self.assertIsNone(args.branch)
def test_plain(self):
""""--repo=foo equals foo=master."""
args = bootstrap.parse_args(['--job=foo', '--repo=foo'])
self.assertEqual(
{'foo': ('master', '')},
bootstrap.parse_repos(args))
def test_branch(self):
"""--repo=foo=branch."""
args = bootstrap.parse_args(['--job=foo', '--repo=foo=this'])
self.assertEqual(
{'foo': ('this', '')},
bootstrap.parse_repos(args))
def test_branch_commit(self):
"""--repo=foo=branch:commit works."""
args = bootstrap.parse_args(['--job=foo', '--repo=foo=this:abcd'])
self.assertEqual(
{'foo': ('this:abcd', '')},
bootstrap.parse_repos(args))
def test_parse_repos(self):
"""--repo=foo=111,222 works"""
args = bootstrap.parse_args(['--job=foo', '--repo=foo=111,222'])
self.assertEqual(
{'foo': ('', '111,222')},
bootstrap.parse_repos(args))
def test_pull_branch(self):
"""--repo=foo=master,111,222 works"""
args = bootstrap.parse_args(['--job=foo', '--repo=foo=master,111,222'])
self.assertEqual(
{'foo': ('', 'master,111,222')},
bootstrap.parse_repos(args))
def test_pull_release_branch(self):
"""--repo=foo=release-3.14,&a-fancy%_branch+:abcd,222 works"""
args = bootstrap.parse_args(['--job=foo',
'--repo=foo=release-3.14,&a-fancy%_branch+:abcd,222'])
self.assertEqual(
{'foo': ('', 'release-3.14,&a-fancy%_branch+:abcd,222')},
bootstrap.parse_repos(args))
def test_pull_branch_commit(self):
"""--repo=foo=master,111,222 works"""
args = bootstrap.parse_args(['--job=foo',
'--repo=foo=master:aaa,111:bbb,222:ccc'])
self.assertEqual(
{'foo': ('', 'master:aaa,111:bbb,222:ccc')},
bootstrap.parse_repos(args))
def test_multi_repo(self):
"""--repo=foo=master,111,222 bar works"""
args = bootstrap.parse_args(['--job=foo',
'--repo=foo=master:aaa,111:bbb,222:ccc',
'--repo=bar'])
self.assertEqual(
{
'foo': ('', 'master:aaa,111:bbb,222:ccc'),
'bar': ('master', '')},
bootstrap.parse_repos(args))
class GSUtilTest(unittest.TestCase):
"""Tests for GSUtil."""
def test_upload_json(self):
fake = FakeSubprocess()
gsutil = bootstrap.GSUtil(fake)
gsutil.upload_json('fake_path', {'wee': 'fun'})
self.assertTrue(any(
'application/json' in a for a in fake.calls[0][0]))
self.assertEqual(fake.file_data, ['{\n "wee": "fun"\n}'])
def test_upload_text_cached(self):
fake = FakeSubprocess()
gsutil = bootstrap.GSUtil(fake)
gsutil.upload_text('fake_path', 'hello world', cached=True)
self.assertFalse(any(
'Cache-Control' in a and 'max-age' in a
for a in fake.calls[0][0]))
self.assertEqual(fake.file_data, ['hello world'])
def test_upload_text_default(self):
fake = FakeSubprocess()
gsutil = bootstrap.GSUtil(fake)
gsutil.upload_text('fake_path', 'hello world')
self.assertFalse(any(
'Cache-Control' in a and 'max-age' in a
for a in fake.calls[0][0]))
self.assertEqual(fake.file_data, ['hello world'])
def test_upload_text_uncached(self):
fake = FakeSubprocess()
gsutil = bootstrap.GSUtil(fake)
gsutil.upload_text('fake_path', 'hello world', cached=False)
self.assertTrue(any(
'Cache-Control' in a and 'max-age' in a
for a in fake.calls[0][0]))
self.assertEqual(fake.file_data, ['hello world'])
def test_upload_text_metalink(self):
fake = FakeSubprocess()
gsutil = bootstrap.GSUtil(fake)
gsutil.upload_text('txt', 'path', additional_headers=['foo: bar'])
self.assertTrue(any('foo: bar' in a for a in fake.calls[0][0]))
self.assertEqual(fake.file_data, ['path'])
class FakeGSUtil(object):
generation = 123
def __init__(self):
self.cats = []
self.jsons = []
self.stats = []
self.texts = []
def cat(self, *a, **kw):
self.cats.append((a, kw))
return 'this is not a list'
def stat(self, *a, **kw):
self.stats.append((a, kw))
return 'Generation: %s' % self.generation
def upload_text(self, *args, **kwargs):
self.texts.append((args, kwargs))
def upload_json(self, *args, **kwargs):
self.jsons.append((args, kwargs))
class GubernatorUriTest(unittest.TestCase):
def create_path(self, uri):
self.fake_path = FakePath()
self.fake_path.build_log = uri
return self.fake_path
def test_non_gs(self):
uri = 'hello/world'
self.assertEqual('hello', bootstrap.gubernator_uri(self.create_path(uri)))
def test_multiple_gs(self):
uri = 'gs://hello/gs://there'
self.assertEqual(
bootstrap.GUBERNATOR + '/hello/gs:',
bootstrap.gubernator_uri(self.create_path(uri)))
def test_gs(self):
uri = 'gs://blah/blah/blah.txt'
self.assertEqual(
bootstrap.GUBERNATOR + '/blah/blah',
bootstrap.gubernator_uri(self.create_path(uri)))
class AppendResultTest(unittest.TestCase):
"""Tests for append_result()."""
def test_new_job(self):
"""Stat fails when the job doesn't exist."""
gsutil = FakeGSUtil()
build = 123
version = 'v.interesting'
success = True
def fake_stat(*_a, **_kw):
raise subprocess.CalledProcessError(1, ['gsutil'], None)
gsutil.stat = fake_stat
bootstrap.append_result(gsutil, 'fake_path', build, version, success)
cache = gsutil.jsons[0][0][1]
self.assertEqual(1, len(cache))
def test_collision_cat(self):
"""cat fails if the cache has been updated."""
gsutil = FakeGSUtil()
build = 42
version = 'v1'
success = False
generations = ['555', '444']
orig_stat = gsutil.stat
def fake_stat(*a, **kw):
gsutil.generation = generations.pop()
return orig_stat(*a, **kw)
def fake_cat(_, gen):
if gen == '555': # Which version is requested?
return '[{"hello": 111}]'
raise subprocess.CalledProcessError(1, ['gsutil'], None)
with Stub(bootstrap, 'random_sleep', Pass):
with Stub(gsutil, 'stat', fake_stat):
with Stub(gsutil, 'cat', fake_cat):
bootstrap.append_result(
gsutil, 'fake_path', build, version, success)
self.assertIn('generation', gsutil.jsons[-1][1], gsutil.jsons)
self.assertEqual('555', gsutil.jsons[-1][1]['generation'], gsutil.jsons)
def test_collision_upload(self):
"""Test when upload_json tries to update an old version."""
gsutil = FakeGSUtil()
build = 42
version = 'v1'
success = False
generations = [555, 444]
orig = gsutil.upload_json
def fake_upload(path, cache, generation):
if generation == '555':
return orig(path, cache, generation=generation)
raise subprocess.CalledProcessError(128, ['gsutil'], None)
orig_stat = gsutil.stat
def fake_stat(*a, **kw):
gsutil.generation = generations.pop()
return orig_stat(*a, **kw)
def fake_cat(*_a, **_kw):
return '[{"hello": 111}]'
gsutil.stat = fake_stat
gsutil.upload_json = fake_upload
gsutil.cat = fake_cat
with Stub(bootstrap, 'random_sleep', Pass):
bootstrap.append_result(
gsutil, 'fake_path', build, version, success)
self.assertIn('generation', gsutil.jsons[-1][1], gsutil.jsons)
self.assertEqual('555', gsutil.jsons[-1][1]['generation'], gsutil.jsons)
def test_handle_junk(self):
gsutil = FakeGSUtil()
gsutil.cat = lambda *a, **kw: '!@!$!@$@!$'
build = 123
version = 'v.interesting'
success = True
bootstrap.append_result(gsutil, 'fake_path', build, version, success)
cache = gsutil.jsons[0][0][1]
self.assertEqual(1, len(cache))
self.assertIn(build, cache[0].values())
self.assertIn(version, cache[0].values())
def test_passed_is_bool(self):
build = 123
version = 'v.interesting'
def try_run(success):
gsutil = FakeGSUtil()
bootstrap.append_result(gsutil, 'fake_path', build, version, success)
cache = gsutil.jsons[0][0][1]
self.assertTrue(isinstance(cache[0]['passed'], bool))
try_run(1)
try_run(0)
try_run(None)
try_run('')
try_run('hello')
try_run('true')
def test_truncate(self):
old = json.dumps({n: True for n in range(100000)})
gsutil = FakeGSUtil()
build = 123
version = 'v.interesting'
success = True
bootstrap.append_result(gsutil, 'fake_path', build, version, success)
cache = gsutil.jsons[0][0][1]
self.assertLess(len(cache), len(old))
class FinishTest(unittest.TestCase):
"""Tests for finish()."""
def setUp(self):
self.stubs = [
Stub(bootstrap.GSUtil, 'upload_artifacts', Pass),
Stub(bootstrap, 'append_result', Pass),
Stub(os.path, 'isfile', Pass),
Stub(os.path, 'isdir', Pass),
]
def tearDown(self):
for stub in self.stubs:
with stub:
pass
def test_no_version(self):
gsutil = FakeGSUtil()
paths = FakePath()
success = True
artifacts = 'not-a-dir'
no_version = ''
version = 'should not have found it'
repos = repo({REPO: ('master', '')})
with Stub(bootstrap, 'metadata', lambda *a: {'random-meta': version}):
bootstrap.finish(gsutil, paths, success, artifacts,
BUILD, no_version, repos, FakeCall())
bootstrap.finish(gsutil, paths, success, artifacts, BUILD, no_version, repos, FakeCall())
calls = gsutil.jsons[-1]
# json data is second positional argument
self.assertNotIn('job-version', calls[0][1])
self.assertNotIn('version', calls[0][1])
self.assertTrue(calls[0][1].get('metadata'))
def test_metadata_version(self):
"""Test that we will extract version info from metadata."""
self.check_metadata_version('job-version')
self.check_metadata_version('version')
def check_metadata_version(self, key):
gsutil = FakeGSUtil()
paths = FakePath()
success = True
artifacts = 'not-a-dir'
no_version = ''
version = 'found it'
with Stub(bootstrap, 'metadata', lambda *a: {key: version}):
bootstrap.finish(gsutil, paths, success, artifacts, BUILD, no_version, REPO, FakeCall())
calls = gsutil.jsons[-1]
# Meta is second positional argument
self.assertEqual(version, calls[0][1].get('job-version'))
self.assertEqual(version, calls[0][1].get('version'))
def test_ignore_err_up_artifacts(self):
paths = FakePath()
gsutil = FakeGSUtil()
local_artifacts = None
build = 123
version = 'v1.terrible'
success = True
calls = []
with Stub(os.path, 'isdir', lambda _: True):
with Stub(os, 'walk', lambda d: [(True, True, True)]):
def fake_upload(*a, **kw):
calls.append((a, kw))
raise subprocess.CalledProcessError(1, ['fakecmd'], None)
gsutil.upload_artifacts = fake_upload
repos = repo({REPO: ('master', '')})
bootstrap.finish(
gsutil, paths, success, local_artifacts,
build, version, repos, FakeCall())
self.assertTrue(calls)
def test_ignore_error_uploadtext(self):
paths = FakePath()
gsutil = FakeGSUtil()
local_artifacts = None
build = 123
version = 'v1.terrible'
success = True
calls = []
with Stub(os.path, 'isdir', lambda _: True):
with Stub(os, 'walk', lambda d: [(True, True, True)]):
def fake_upload(*a, **kw):
calls.append((a, kw))
raise subprocess.CalledProcessError(1, ['fakecmd'], None)
gsutil.upload_artifacts = Pass
gsutil.upload_text = fake_upload
repos = repo({REPO: ('master', '')})
bootstrap.finish(
gsutil, paths, success, local_artifacts,
build, version, repos, FakeCall())
self.assertTrue(calls)
self.assertGreater(calls, 1)
def test_skip_upload_artifacts(self):
"""Do not upload artifacts dir if it doesn't exist."""
paths = FakePath()
gsutil = FakeGSUtil()
local_artifacts = None
build = 123
version = 'v1.terrible'
success = True
calls = []
with Stub(os.path, 'isdir', lambda _: False):
with Stub(bootstrap.GSUtil, 'upload_artifacts', Bomb):
repos = repo({REPO: ('master', '')})
bootstrap.finish(
gsutil, paths, success, local_artifacts,
build, version, repos, FakeCall())
self.assertFalse(calls)
class MetadataTest(unittest.TestCase):
def test_always_set_metadata(self):
repos = repo({REPO: ('master', '')})
meta = bootstrap.metadata(repos, 'missing-artifacts-dir', FakeCall())
self.assertIn('repo', meta)
self.assertEqual(REPO, meta['repo'])
def test_multi_repo(self):
repos = repo({REPO: ('foo', ''), 'other-repo': ('', '123,456')})
meta = bootstrap.metadata(repos, 'missing-artifacts-dir', FakeCall())
self.assertIn('repo', meta)
self.assertEqual(REPO, meta['repo'])
self.assertIn(REPO, meta.get('repos'))
self.assertEqual('foo', meta['repos'][REPO])
self.assertIn('other-repo', meta.get('repos'))
self.assertEqual('123,456', meta['repos']['other-repo'])
SECONDS = 10
def fake_environment(set_home=True, set_node=True, set_job=True,
set_jenkins_home=True, set_workspace=True,
set_artifacts=True, **kwargs):
if set_home:
kwargs.setdefault(bootstrap.HOME_ENV, '/fake/home-dir')
if set_node:
kwargs.setdefault(bootstrap.NODE_ENV, 'fake-node')
if set_job:
kwargs.setdefault(bootstrap.JOB_ENV, JOB)
if set_jenkins_home:
kwargs.setdefault(bootstrap.JENKINS_HOME_ENV, '/fake/home-dir')
if set_workspace:
kwargs.setdefault(bootstrap.WORKSPACE_ENV, '/fake/workspace')
if set_artifacts:
kwargs.setdefault(bootstrap.JOB_ARTIFACTS_ENV, '/fake/workspace/_artifacts')
return kwargs
class BuildNameTest(unittest.TestCase):
"""Tests for build_name()."""
def test_auto(self):
"""Automatically select a build if not done by user."""
with Stub(os, 'environ', fake_environment()) as fake:
bootstrap.build_name(SECONDS)
self.assertTrue(fake[bootstrap.BUILD_ENV])
def test_manual(self):
"""Respect user-selected build."""
with Stub(os, 'environ', fake_environment()) as fake:
truth = 'erick is awesome'
fake[bootstrap.BUILD_ENV] = truth
self.assertEqual(truth, fake[bootstrap.BUILD_ENV])
def test_unique(self):
"""New build every minute."""
with Stub(os, 'environ', fake_environment()) as fake:
bootstrap.build_name(SECONDS)
first = fake[bootstrap.BUILD_ENV]
del fake[bootstrap.BUILD_ENV]
bootstrap.build_name(SECONDS + 60)
self.assertNotEqual(first, fake[bootstrap.BUILD_ENV])
class SetupCredentialsTest(unittest.TestCase):
"""Tests for setup_credentials()."""
def setUp(self):
keys = {
bootstrap.GCE_KEY_ENV: 'fake-key',
bootstrap.SERVICE_ACCOUNT_ENV: 'fake-service-account.json',
}
self.env = fake_environment(**keys)
def test_norobot_noupload_noenv(self):
"""Can avoid setting up credentials."""
del self.env[bootstrap.SERVICE_ACCOUNT_ENV]
with Stub(os, 'environ', self.env):
bootstrap.setup_credentials(Bomb, None, None)
def test_upload_no_robot_raises(self):
del self.env[bootstrap.SERVICE_ACCOUNT_ENV]
with Stub(os, 'environ', self.env):
with self.assertRaises(ValueError):
bootstrap.setup_credentials(Pass, None, 'gs://fake')
def test_application_credentials(self):
"""Raise if GOOGLE_APPLICATION_CREDENTIALS does not exist."""
del self.env[bootstrap.SERVICE_ACCOUNT_ENV]
with Stub(os, 'environ', self.env) as fake:
gac = 'FAKE_CREDS.json'
fake['HOME'] = 'kansas'
with Stub(os.path, 'isfile', lambda p: p != gac):
with self.assertRaises(IOError):
bootstrap.setup_credentials(Pass, gac, UPLOAD)
with Stub(os.path, 'isfile', Truth):
call = lambda *a, **kw: 'robot'
bootstrap.setup_credentials(call, gac, UPLOAD)
# setup_creds should set SERVICE_ACCOUNT_ENV
self.assertEqual(gac, fake.get(bootstrap.SERVICE_ACCOUNT_ENV))
# now that SERVICE_ACCOUNT_ENV is set, it should try to activate
# this
with Stub(os.path, 'isfile', lambda p: p != gac):
with self.assertRaises(IOError):
bootstrap.setup_credentials(Pass, None, UPLOAD)
class SetupMagicEnvironmentTest(unittest.TestCase):
def test_home_workspace_on_jenkins(self):
"""WORKSPACE/HOME are set correctly for the Jenkins environment."""
env = fake_environment(set_jenkins_home=True, set_workspace=True)
cwd = '/fake/random-location'
old_home = env[bootstrap.HOME_ENV]
old_workspace = env[bootstrap.WORKSPACE_ENV]
with Stub(os, 'environ', env):
with Stub(os, 'getcwd', lambda: cwd):
bootstrap.setup_magic_environment(JOB, FakeCall())
self.assertIn(bootstrap.WORKSPACE_ENV, env)
self.assertNotEqual(
env[bootstrap.HOME_ENV], env[bootstrap.WORKSPACE_ENV])
self.assertNotEqual(old_home, env[bootstrap.HOME_ENV])
self.assertEqual(cwd, env[bootstrap.HOME_ENV])
self.assertEqual(old_workspace, env[bootstrap.WORKSPACE_ENV])
self.assertNotEqual(cwd, env[bootstrap.WORKSPACE_ENV])
def test_home_workspace_in_k8s(self):
"""WORKSPACE/HOME are set correctly for the kubernetes environment."""
env = fake_environment(set_jenkins_home=False, set_workspace=True)
cwd = '/fake/random-location'
old_home = env[bootstrap.HOME_ENV]
old_workspace = env[bootstrap.WORKSPACE_ENV]
with Stub(os, 'environ', env):
with Stub(os, 'getcwd', lambda: cwd):
bootstrap.setup_magic_environment(JOB, FakeCall())
self.assertIn(bootstrap.WORKSPACE_ENV, env)
self.assertNotEqual(
env[bootstrap.HOME_ENV], env[bootstrap.WORKSPACE_ENV])
self.assertEqual(old_home, env[bootstrap.HOME_ENV])
self.assertNotEqual(cwd, env[bootstrap.HOME_ENV])
self.assertEqual(old_workspace, env[bootstrap.WORKSPACE_ENV])
self.assertNotEqual(cwd, env[bootstrap.WORKSPACE_ENV])
def test_workspace_always_set(self):
"""WORKSPACE is set to cwd when unset in initial environment."""
env = fake_environment(set_workspace=False)
cwd = '/fake/random-location'
with Stub(os, 'environ', env):
with Stub(os, 'getcwd', lambda: cwd):
bootstrap.setup_magic_environment(JOB, FakeCall())
self.assertIn(bootstrap.WORKSPACE_ENV, env)
self.assertEqual(cwd, env[bootstrap.HOME_ENV])
self.assertEqual(cwd, env[bootstrap.WORKSPACE_ENV])
def test_job_env_mismatch(self):
env = fake_environment()
with Stub(os, 'environ', env):
self.assertNotEqual('this-is-a-job', env[bootstrap.JOB_ENV])
bootstrap.setup_magic_environment('this-is-a-job', FakeCall())
self.assertEqual('this-is-a-job', env[bootstrap.JOB_ENV])
def test_expected(self):
env = fake_environment()
del env[bootstrap.JOB_ENV]
del env[bootstrap.NODE_ENV]
with Stub(os, 'environ', env):
# call is only used to git show the HEAD commit, so give a fake
# timestamp in return
bootstrap.setup_magic_environment(JOB, lambda *a, **kw: '123456\n')
def check(name):
self.assertIn(name, env)
# Some of these are probably silly to check...
# TODO(fejta): remove as many of these from our infra as possible.
check(bootstrap.JOB_ENV)
check(bootstrap.CLOUDSDK_ENV)
check(bootstrap.BOOTSTRAP_ENV)
check(bootstrap.WORKSPACE_ENV)
self.assertNotIn(bootstrap.SERVICE_ACCOUNT_ENV, env)
self.assertEqual(env[bootstrap.SOURCE_DATE_EPOCH_ENV], '123456')
def test_node_present(self):
expected = 'whatever'
env = {bootstrap.NODE_ENV: expected}
with Stub(os, 'environ', env):
self.assertEqual(expected, bootstrap.node())
self.assertEqual(expected, env[bootstrap.NODE_ENV])
def test_node_missing(self):
env = {}
with Stub(os, 'environ', env):
expected = bootstrap.node()
self.assertTrue(expected)
self.assertEqual(expected, env[bootstrap.NODE_ENV])