forked from SCons/scons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnvironmentTests.py
More file actions
4339 lines (3642 loc) · 160 KB
/
Copy pathEnvironmentTests.py
File metadata and controls
4339 lines (3642 loc) · 160 KB
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
# MIT License
#
# Copyright The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import SCons.compat
import copy
import io
import os
import sys
import unittest
from collections import UserDict as UD, UserList as UL, deque
import TestCmd
import SCons.Warnings
from SCons.Environment import (
Environment,
NoSubstitutionProxy,
OverrideEnvironment,
SubstitutionEnvironment,
)
from SCons.Util import CLVar
from SCons.SConsign import current_sconsign_filename
def diff_env(env1, env2):
s1 = "env1 = {\n"
s2 = "env2 = {\n"
d = {}
for k in list(env1._dict.keys()) + list(env2._dict.keys()):
d[k] = None
for k in sorted(d.keys()):
if k in env1:
if k in env2:
if env1[k] != env2[k]:
s1 = s1 + " " + repr(k) + " : " + repr(env1[k]) + "\n"
s2 = s2 + " " + repr(k) + " : " + repr(env2[k]) + "\n"
else:
s1 = s1 + " " + repr(k) + " : " + repr(env1[k]) + "\n"
elif k in env2:
s2 = s2 + " " + repr(k) + " : " + repr(env2[k]) + "\n"
s1 = s1 + "}\n"
s2 = s2 + "}\n"
return s1 + s2
def diff_dict(d1, d2):
s1 = "d1 = {\n"
s2 = "d2 = {\n"
d = {}
for k in list(d1.keys()) + list(d2.keys()):
d[k] = None
for k in sorted(d.keys()):
if k in d1:
if k in d2:
if d1[k] != d2[k]:
s1 = s1 + " " + repr(k) + " : " + repr(d1[k]) + "\n"
s2 = s2 + " " + repr(k) + " : " + repr(d2[k]) + "\n"
else:
s1 = s1 + " " + repr(k) + " : " + repr(d1[k]) + "\n"
elif k in d2:
s2 = s2 + " " + repr(k) + " : " + repr(d2[k]) + "\n"
s1 = s1 + "}\n"
s2 = s2 + "}\n"
return s1 + s2
called_it = {}
built_it = {}
class Builder(SCons.Builder.BuilderBase):
"""A dummy Builder class for testing purposes. "Building"
a target is simply setting a value in the dictionary.
"""
def __init__(self, name = None) -> None:
self.name = name
def __call__(self, env, target=None, source=None, **kw) -> None:
global called_it
called_it['target'] = target
called_it['source'] = source
called_it.update(kw)
def execute(self, target = None, **kw) -> None:
global built_it
built_it[target] = 1
scanned_it = {}
class Scanner:
"""A dummy Scanner class for testing purposes. "Scanning"
a target is simply setting a value in the dictionary.
"""
def __init__(self, name, skeys=[]) -> None:
self.name = name
self.skeys = skeys
def __call__(self, filename) -> None:
global scanned_it
scanned_it[filename] = 1
def __eq__(self, other):
try:
return self.__dict__ == other.__dict__
except AttributeError:
return False
def get_skeys(self, env):
return self.skeys
def __str__(self) -> str:
return self.name
class DummyNode:
def __init__(self, name) -> None:
self.name = name
def __str__(self) -> str:
return self.name
def rfile(self):
return self
def get_subst_proxy(self):
return self
def test_tool( env ) -> None:
env['_F77INCFLAGS'] = '${_concat(INCPREFIX, F77PATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}'
class TestEnvironmentFixture:
def TestEnvironment(self, *args, **kw):
if not kw or 'tools' not in kw:
kw['tools'] = [test_tool]
default_keys = { 'CC' : 'cc',
'CCFLAGS' : '-DNDEBUG',
'ENV' : { 'TMP' : '/tmp' } }
for key, value in default_keys.items():
if key not in kw:
kw[key] = value
if 'BUILDERS' not in kw:
static_obj = SCons.Builder.Builder(action = {},
emitter = {},
suffix = '.o',
single_source = 1)
kw['BUILDERS'] = {'Object' : static_obj}
static_obj.add_action('.cpp', 'fake action')
env = Environment(*args, **kw)
return env
class SubstitutionTestCase(unittest.TestCase):
def test___init__(self) -> None:
"""Test initializing a SubstitutionEnvironment."""
env = SubstitutionEnvironment()
assert '__env__' not in env
def test___cmp__(self) -> None:
"""Test comparing SubstitutionEnvironments."""
env1 = SubstitutionEnvironment(XXX = 'x')
env2 = SubstitutionEnvironment(XXX = 'x')
env3 = SubstitutionEnvironment(XXX = 'xxx')
env4 = SubstitutionEnvironment(XXX = 'x', YYY = 'x')
with self.subTest():
self.assertEqual(env1, env2)
with self.subTest():
self.assertNotEqual(env1, env3)
with self.subTest():
self.assertNotEqual(env1, env4)
def test___delitem__(self) -> None:
"""Test deleting a variable from a SubstitutionEnvironment."""
env1 = SubstitutionEnvironment(XXX = 'x', YYY = 'y')
env2 = SubstitutionEnvironment(XXX = 'x')
del env1['YYY']
self.assertEqual(env1, env2)
def test___getitem__(self) -> None:
"""Test fetching a variable from a SubstitutionEnvironment."""
env = SubstitutionEnvironment(XXX = 'x')
assert env['XXX'] == 'x', env['XXX']
def test___setitem__(self) -> None:
"""Test setting a variable in a SubstitutionEnvironment."""
env1 = SubstitutionEnvironment(XXX = 'x')
env2 = SubstitutionEnvironment(XXX = 'x', YYY = 'y')
env1['YYY'] = 'y'
self.assertEqual(env1, env2)
def test_get(self) -> None:
"""Test the SubstitutionEnvironment get() method."""
env = SubstitutionEnvironment(XXX = 'x')
assert env.get('XXX') == 'x', env.get('XXX')
assert env.get('YYY') is None, env.get('YYY')
def test_contains(self) -> None:
"""Test the SubstitutionEnvironment __contains__() method."""
env = SubstitutionEnvironment(XXX = 'x')
assert 'XXX' in env
assert 'YYY' not in env
def test_keys(self) -> None:
"""Test the SubstitutionEnvironment keys() method."""
testdata = {'XXX': 'x', 'YYY': 'y'}
env = SubstitutionEnvironment(**testdata)
keys = list(env.keys())
assert len(keys) == 2, keys
for k in testdata.keys():
assert k in keys, keys
def test_values(self) -> None:
"""Test the SubstitutionEnvironment values() method."""
testdata = {'XXX': 'x', 'YYY': 'y'}
env = SubstitutionEnvironment(**testdata)
values = list(env.values())
assert len(values) == 2, values
for v in testdata.values():
assert v in values, values
def test_items(self) -> None:
"""Test the SubstitutionEnvironment items() method."""
testdata = {'XXX': 'x', 'YYY': 'y'}
env = SubstitutionEnvironment(**testdata)
items = list(env.items())
assert len(items) == 2, items
for k, v in testdata.items():
assert (k, v) in items, items
def test_setdefault(self) -> None:
"""Test the SubstitutionEnvironment setdefault() method."""
env = SubstitutionEnvironment(XXX = 'x')
assert env.setdefault('XXX', 'z') == 'x', env['XXX']
assert env.setdefault('YYY', 'y') == 'y', env['YYY']
assert 'YYY' in env
def test_arg2nodes(self) -> None:
"""Test the arg2nodes method."""
env = SubstitutionEnvironment()
dict = {}
class X(SCons.Node.Node):
pass
def Factory(name, directory = None, create: int = 1, dict=dict, X=X):
if name not in dict:
dict[name] = X()
dict[name].name = name
return dict[name]
nodes = env.arg2nodes("Util.py UtilTests.py", Factory)
assert len(nodes) == 1, nodes
assert isinstance(nodes[0], X)
assert nodes[0].name == "Util.py UtilTests.py", nodes[0].name
nodes = env.arg2nodes(["Util.py", "UtilTests.py"], Factory)
assert len(nodes) == 2, nodes
assert isinstance(nodes[0], X)
assert isinstance(nodes[1], X)
assert nodes[0].name == "Util.py", nodes[0].name
assert nodes[1].name == "UtilTests.py", nodes[1].name
n1 = Factory("Util.py")
nodes = env.arg2nodes([n1, "UtilTests.py"], Factory)
assert len(nodes) == 2, nodes
assert isinstance(nodes[0], X)
assert isinstance(nodes[1], X)
assert nodes[0].name == "Util.py", nodes[0].name
assert nodes[1].name == "UtilTests.py", nodes[1].name
class SConsNode(SCons.Node.Node):
pass
nodes = env.arg2nodes(SConsNode())
assert len(nodes) == 1, nodes
assert isinstance(nodes[0], SConsNode), nodes[0]
class OtherNode:
pass
nodes = env.arg2nodes(OtherNode())
assert len(nodes) == 1, nodes
assert isinstance(nodes[0], OtherNode), nodes[0]
def lookup_a(str, F=Factory):
if str[0] == 'a':
n = F(str)
n.a = 1
return n
else:
return None
def lookup_b(str, F=Factory):
if str[0] == 'b':
n = F(str)
n.b = 1
return n
else:
return None
env_ll = SubstitutionEnvironment()
env_ll.lookup_list = [lookup_a, lookup_b]
nodes = env_ll.arg2nodes(['aaa', 'bbb', 'ccc'], Factory)
assert len(nodes) == 3, nodes
assert nodes[0].name == 'aaa', nodes[0]
assert nodes[0].a == 1, nodes[0]
assert not hasattr(nodes[0], 'b'), nodes[0]
assert nodes[1].name == 'bbb'
assert not hasattr(nodes[1], 'a'), nodes[1]
assert nodes[1].b == 1, nodes[1]
assert nodes[2].name == 'ccc'
assert not hasattr(nodes[2], 'a'), nodes[1]
assert not hasattr(nodes[2], 'b'), nodes[1]
def lookup_bbbb(str, F=Factory):
if str == 'bbbb':
n = F(str)
n.bbbb = 1
return n
else:
return None
def lookup_c(str, F=Factory):
if str[0] == 'c':
n = F(str)
n.c = 1
return n
else:
return None
nodes = env.arg2nodes(['bbbb', 'ccc'], Factory,
[lookup_c, lookup_bbbb, lookup_b])
assert len(nodes) == 2, nodes
assert nodes[0].name == 'bbbb'
assert not hasattr(nodes[0], 'a'), nodes[1]
assert not hasattr(nodes[0], 'b'), nodes[1]
assert nodes[0].bbbb == 1, nodes[1]
assert not hasattr(nodes[0], 'c'), nodes[0]
assert nodes[1].name == 'ccc'
assert not hasattr(nodes[1], 'a'), nodes[1]
assert not hasattr(nodes[1], 'b'), nodes[1]
assert not hasattr(nodes[1], 'bbbb'), nodes[0]
assert nodes[1].c == 1, nodes[1]
def test_arg2nodes_target_source(self) -> None:
"""Test the arg2nodes method with target= and source= keywords
"""
targets = [DummyNode('t1'), DummyNode('t2')]
sources = [DummyNode('s1'), DummyNode('s2')]
env = SubstitutionEnvironment()
nodes = env.arg2nodes(['${TARGET}-a',
'${SOURCE}-b',
'${TARGETS[1]}-c',
'${SOURCES[1]}-d'],
DummyNode,
target=targets,
source=sources)
names = [n.name for n in nodes]
assert names == ['t1-a', 's1-b', 't2-c', 's2-d'], names
def test_gvars(self) -> None:
"""Test the base class gvars() method"""
env = SubstitutionEnvironment()
gvars = env.gvars()
assert gvars == {}, gvars
def test_lvars(self) -> None:
"""Test the base class lvars() method"""
env = SubstitutionEnvironment()
lvars = env.lvars()
assert lvars == {}, lvars
def test_subst(self) -> None:
"""Test substituting construction variables within strings
Check various combinations, including recursive expansion
of variables into other variables.
"""
env = SubstitutionEnvironment(AAA = 'a', BBB = 'b')
mystr = env.subst("$AAA ${AAA}A $BBBB $BBB")
assert mystr == "a aA b", mystr
# Changed the tests below to reflect a bug fix in
# subst()
env = SubstitutionEnvironment(AAA = '$BBB', BBB = 'b', BBBA = 'foo')
mystr = env.subst("$AAA ${AAA}A ${AAA}B $BBB")
assert mystr == "b bA bB b", mystr
env = SubstitutionEnvironment(AAA = '$BBB', BBB = '$CCC', CCC = 'c')
mystr = env.subst("$AAA ${AAA}A ${AAA}B $BBB")
assert mystr == "c cA cB c", mystr
# Lists:
env = SubstitutionEnvironment(AAA = ['a', 'aa', 'aaa'])
mystr = env.subst("$AAA")
assert mystr == "a aa aaa", mystr
# Tuples:
env = SubstitutionEnvironment(AAA = ('a', 'aa', 'aaa'))
mystr = env.subst("$AAA")
assert mystr == "a aa aaa", mystr
t1 = DummyNode('t1')
t2 = DummyNode('t2')
s1 = DummyNode('s1')
s2 = DummyNode('s2')
env = SubstitutionEnvironment(AAA = 'aaa')
s = env.subst('$AAA $TARGET $SOURCES', target=[t1, t2], source=[s1, s2])
assert s == "aaa t1 s1 s2", s
s = env.subst('$AAA $TARGETS $SOURCE', target=[t1, t2], source=[s1, s2])
assert s == "aaa t1 t2 s1", s
# Test callables in the SubstitutionEnvironment
def foo(target, source, env, for_signature):
assert str(target) == 't', target
assert str(source) == 's', source
return env["FOO"]
env = SubstitutionEnvironment(BAR=foo, FOO='baz')
t = DummyNode('t')
s = DummyNode('s')
subst = env.subst('test $BAR', target=t, source=s)
assert subst == 'test baz', subst
# Test not calling callables in the SubstitutionEnvironment
if 0:
# This will take some serious surgery to subst() and
# subst_list(), so just leave these tests out until we can
# do that.
def bar(arg) -> None:
pass
env = SubstitutionEnvironment(BAR=bar, FOO='$BAR')
subst = env.subst('$BAR', call=None)
assert subst is bar, subst
subst = env.subst('$FOO', call=None)
assert subst is bar, subst
def test_subst_kw(self) -> None:
"""Test substituting construction variables within dictionaries"""
env = SubstitutionEnvironment(AAA = 'a', BBB = 'b')
kw = env.subst_kw({'$AAA' : 'aaa', 'bbb' : '$BBB'})
assert len(kw) == 2, kw
assert kw['a'] == 'aaa', kw['a']
assert kw['bbb'] == 'b', kw['bbb']
def test_subst_list(self) -> None:
"""Test substituting construction variables in command lists
"""
env = SubstitutionEnvironment(AAA = 'a', BBB = 'b')
l = env.subst_list("$AAA ${AAA}A $BBBB $BBB")
assert l == [["a", "aA", "b"]], l
# Changed the tests below to reflect a bug fix in
# subst()
env = SubstitutionEnvironment(AAA = '$BBB', BBB = 'b', BBBA = 'foo')
l = env.subst_list("$AAA ${AAA}A ${AAA}B $BBB")
assert l == [["b", "bA", "bB", "b"]], l
env = SubstitutionEnvironment(AAA = '$BBB', BBB = '$CCC', CCC = 'c')
l = env.subst_list("$AAA ${AAA}A ${AAA}B $BBB")
assert l == [["c", "cA", "cB", "c"]], l
env = SubstitutionEnvironment(AAA = '$BBB', BBB = '$CCC', CCC = [ 'a', 'b\nc' ])
lst = env.subst_list([ "$AAA", "B $CCC" ])
assert lst == [[ "a", "b"], ["c", "B a", "b"], ["c"]], lst
t1 = DummyNode('t1')
t2 = DummyNode('t2')
s1 = DummyNode('s1')
s2 = DummyNode('s2')
env = SubstitutionEnvironment(AAA = 'aaa')
s = env.subst_list('$AAA $TARGET $SOURCES', target=[t1, t2], source=[s1, s2])
assert s == [["aaa", "t1", "s1", "s2"]], s
s = env.subst_list('$AAA $TARGETS $SOURCE', target=[t1, t2], source=[s1, s2])
assert s == [["aaa", "t1", "t2", "s1"]], s
# Test callables in the SubstitutionEnvironment
def foo(target, source, env, for_signature):
assert str(target) == 't', target
assert str(source) == 's', source
return env["FOO"]
env = SubstitutionEnvironment(BAR=foo, FOO='baz')
t = DummyNode('t')
s = DummyNode('s')
lst = env.subst_list('test $BAR', target=t, source=s)
assert lst == [['test', 'baz']], lst
# Test not calling callables in the SubstitutionEnvironment
if 0:
# This will take some serious surgery to subst() and
# subst_list(), so just leave these tests out until we can
# do that.
def bar(arg) -> None:
pass
env = SubstitutionEnvironment(BAR=bar, FOO='$BAR')
subst = env.subst_list('$BAR', call=None)
assert subst is bar, subst
subst = env.subst_list('$FOO', call=None)
assert subst is bar, subst
def test_subst_path(self) -> None:
"""Test substituting a path list
"""
class MyProxy:
def __init__(self, val) -> None:
self.val = val
def get(self):
return self.val + '-proxy'
class MyNode:
def __init__(self, val) -> None:
self.val = val
def get_subst_proxy(self):
return self
def __str__(self) -> str:
return self.val
class MyObj:
def get(self):
return self
env = SubstitutionEnvironment(FOO='foo',
BAR='bar',
LIST=['one', 'two'],
PROXY=MyProxy('my1'))
r = env.subst_path('$FOO')
assert r == ['foo'], r
r = env.subst_path(['$FOO', 'xxx', '$BAR'])
assert r == ['foo', 'xxx', 'bar'], r
r = env.subst_path(['$FOO', '$LIST', '$BAR'])
assert list(map(str, r)) == ['foo', 'one two', 'bar'], r
r = env.subst_path(['$FOO', '$TARGET', '$SOURCE', '$BAR'])
assert r == ['foo', '', '', 'bar'], r
r = env.subst_path(['$FOO', '$TARGET', '$BAR'], target=MyNode('ttt'))
assert list(map(str, r)) == ['foo', 'ttt', 'bar'], r
r = env.subst_path(['$FOO', '$SOURCE', '$BAR'], source=MyNode('sss'))
assert list(map(str, r)) == ['foo', 'sss', 'bar'], r
n = MyObj()
r = env.subst_path(['$PROXY', MyProxy('my2'), n])
assert r == ['my1-proxy', 'my2-proxy', n], r
class StringableObj:
def __init__(self, s) -> None:
self.s = s
def __str__(self) -> str:
return self.s
env = SubstitutionEnvironment(FOO=StringableObj("foo"),
BAR=StringableObj("bar"))
r = env.subst_path([ "${FOO}/bar", "${BAR}/baz" ])
assert r == [ "foo/bar", "bar/baz" ], r
r = env.subst_path([ "bar/${FOO}", "baz/${BAR}" ])
assert r == [ "bar/foo", "baz/bar" ], r
r = env.subst_path([ "bar/${FOO}/bar", "baz/${BAR}/baz" ])
assert r == [ "bar/foo/bar", "baz/bar/baz" ], r
def test_subst_target_source(self) -> None:
"""Test the base environment subst_target_source() method"""
env = SubstitutionEnvironment(AAA = 'a', BBB = 'b')
mystr = env.subst_target_source("$AAA ${AAA}A $BBBB $BBB")
assert mystr == "a aA b", mystr
def test_backtick(self) -> None:
"""Test the backtick() method for capturing command output"""
env = SubstitutionEnvironment()
test = TestCmd.TestCmd(workdir = '')
test.write('stdout.py', """\
import sys
sys.stdout.write('this came from stdout.py\\n')
sys.exit(0)
""")
test.write('stderr.py', """\
import sys
sys.stderr.write('this came from stderr.py\\n')
sys.exit(0)
""")
test.write('fail.py', """\
import sys
sys.exit(1)
""")
test.write('echo.py', """\
import os, sys
sys.stdout.write(os.environ['ECHO'] + '\\n')
sys.exit(0)
""")
save_stderr = sys.stderr
python = '"' + sys.executable + '"'
try:
sys.stderr = io.StringIO()
cmd = '%s %s' % (python, test.workpath('stdout.py'))
output = env.backtick(cmd)
errout = sys.stderr.getvalue()
assert output == 'this came from stdout.py\n', output
assert errout == '', errout
sys.stderr = io.StringIO()
cmd = '%s %s' % (python, test.workpath('stderr.py'))
output = env.backtick(cmd)
errout = sys.stderr.getvalue()
assert output == '', output
assert errout == 'this came from stderr.py\n', errout
sys.stderr = io.StringIO()
cmd = '%s %s' % (python, test.workpath('fail.py'))
try:
env.backtick(cmd)
except OSError as e:
assert str(e) == f'{cmd!r} exited 1', str(e)
else:
self.fail("did not catch expected OSError")
sys.stderr = io.StringIO()
cmd = '%s %s' % (python, test.workpath('echo.py'))
env['ENV'] = os.environ.copy()
env['ENV']['ECHO'] = 'this came from ECHO'
output = env.backtick(cmd)
errout = sys.stderr.getvalue()
assert output == 'this came from ECHO\n', output
assert errout == '', errout
finally:
sys.stderr = save_stderr
def test_AddMethod(self) -> None:
"""Test the AddMethod() method"""
env = SubstitutionEnvironment(FOO = 'foo')
def func(self):
return 'func-' + self['FOO']
assert not hasattr(env, 'func')
env.AddMethod(func)
r = env.func()
assert r == 'func-foo', r
assert not hasattr(env, 'bar')
env.AddMethod(func, 'bar')
r = env.bar()
assert r == 'func-foo', r
def func2(self, arg: str=''):
return 'func2-' + self['FOO'] + arg
env.AddMethod(func2)
r = env.func2()
assert r == 'func2-foo', r
r = env.func2('-xxx')
assert r == 'func2-foo-xxx', r
env.AddMethod(func2, 'func')
r = env.func()
assert r == 'func2-foo', r
r = env.func('-yyy')
assert r == 'func2-foo-yyy', r
# Test that clones of clones correctly re-bind added methods.
env1 = Environment(FOO = '1')
env1.AddMethod(func2)
env2 = env1.Clone(FOO = '2')
env3 = env2.Clone(FOO = '3')
env4 = env3.Clone(FOO = '4')
r = env1.func2()
assert r == 'func2-1', r
r = env2.func2()
assert r == 'func2-2', r
r = env3.func2()
assert r == 'func2-3', r
r = env4.func2()
assert r == 'func2-4', r
# Test that clones don't re-bind an attribute that the user set.
env1 = Environment(FOO = '1')
env1.AddMethod(func2)
def replace_func2() -> str:
return 'replace_func2'
env1.func2 = replace_func2
env2 = env1.Clone(FOO = '2')
r = env2.func2()
assert r == 'replace_func2', r
# Test clone rebinding if using global AddMethod.
env1 = Environment(FOO='1')
SCons.Util.AddMethod(env1, func2)
r = env1.func2()
assert r == 'func2-1', r
r = env1.func2('-xxx')
assert r == 'func2-1-xxx', r
env2 = env1.Clone(FOO='2')
r = env2.func2()
assert r == 'func2-2', r
def test_Override(self) -> None:
"""Test overriding construction variables"""
env = SubstitutionEnvironment(ONE=1, TWO=2, THREE=3, FOUR=4)
assert env['ONE'] == 1, env['ONE']
assert env['TWO'] == 2, env['TWO']
assert env['THREE'] == 3, env['THREE']
assert env['FOUR'] == 4, env['FOUR']
env2 = env.Override({'TWO' : '10',
'THREE' :'x $THREE y',
'FOUR' : ['x', '$FOUR', 'y']})
assert env2['ONE'] == 1, env2['ONE']
assert env2['TWO'] == '10', env2['TWO']
assert env2['THREE'] == 'x 3 y', env2['THREE']
assert env2['FOUR'] == ['x', 4, 'y'], env2['FOUR']
assert env['ONE'] == 1, env['ONE']
assert env['TWO'] == 2, env['TWO']
assert env['THREE'] == 3, env['THREE']
assert env['FOUR'] == 4, env['FOUR']
env2.Replace(ONE = "won")
assert env2['ONE'] == "won", env2['ONE']
assert env['ONE'] == 1, env['ONE']
def test_ParseFlags(self) -> None:
"""Test the ParseFlags() method
"""
env = SubstitutionEnvironment()
empty = {
'ASFLAGS' : [],
'CFLAGS' : [],
'CCFLAGS' : [],
'CXXFLAGS' : [],
'CPPDEFINES' : [],
'CPPFLAGS' : [],
'CPPPATH' : [],
'FRAMEWORKPATH' : [],
'FRAMEWORKS' : [],
'LIBPATH' : [],
'LIBS' : [],
'LINKFLAGS' : [],
'RPATH' : [],
}
d = env.ParseFlags(None)
assert d == empty, d
d = env.ParseFlags('')
assert d == empty, d
d = env.ParseFlags([])
assert d == empty, d
s = (
"-I/usr/include/fum -I bar -X "
'-I"C:\\Program Files\\ASCEND\\include" '
"-L/usr/fax -L foo -lxxx -l yyy "
'-L"C:\\Program Files\\ASCEND" -lascend '
"-Wa,-as -Wl,-link "
"-Wl,-rpath=rpath1 "
"-Wl,-R,rpath2 "
"-Wl,-Rrpath3 "
"-Wp,-cpp "
"-std=c99 "
"-std=c++0x "
"-framework Carbon "
"-frameworkdir=fwd1 "
"-Ffwd2 "
"-F fwd3 "
"-dylib_file foo-dylib "
"-pthread "
"-fmerge-all-constants "
"-fopenmp "
"-mno-cygwin -mwindows "
"-arch i386 "
"-isysroot /tmp "
"-iquote /usr/include/foo1 "
"-isystem /usr/include/foo2 "
"-idirafter /usr/include/foo3 "
"-imacros /usr/include/foo4 "
"-include /usr/include/foo5 "
"--param l1-cache-size=32 --param l2-cache-size=6144 "
"+DD64 "
"-DFOO -DBAR=value -D BAZ "
"-fsanitize=memory "
"-fsanitize-address-use-after-return "
"-stdlib=libc++"
)
d = env.ParseFlags(s)
assert d['ASFLAGS'] == ['-as'], d['ASFLAGS']
assert d['CFLAGS'] == ['-std=c99']
assert d['CCFLAGS'] == ['-X', '-Wa,-as',
'-pthread', '-fmerge-all-constants',
'-fopenmp', '-mno-cygwin',
('-arch', 'i386'), ('-isysroot', '/tmp'),
('-iquote', '/usr/include/foo1'),
('-isystem', '/usr/include/foo2'),
('-idirafter', '/usr/include/foo3'),
('-imacros', env.fs.File('/usr/include/foo4')),
('-include', env.fs.File('/usr/include/foo5')),
('--param', 'l1-cache-size=32'), ('--param', 'l2-cache-size=6144'),
'+DD64',
'-fsanitize=memory',
'-fsanitize-address-use-after-return'], repr(d['CCFLAGS'])
assert d['CXXFLAGS'] == ['-std=c++0x', '-stdlib=libc++'], repr(d['CXXFLAGS'])
assert d['CPPDEFINES'] == ['FOO', ['BAR', 'value'], 'BAZ'], d['CPPDEFINES']
assert d['CPPFLAGS'] == ['-Wp,-cpp'], d['CPPFLAGS']
assert d['CPPPATH'] == ['/usr/include/fum',
'bar',
'C:\\Program Files\\ASCEND\\include'], d['CPPPATH']
assert d['FRAMEWORKPATH'] == ['fwd1', 'fwd2', 'fwd3'], d['FRAMEWORKPATH']
assert d['FRAMEWORKS'] == ['Carbon'], d['FRAMEWORKS']
assert d['LIBPATH'] == ['/usr/fax',
'foo',
'C:\\Program Files\\ASCEND'], d['LIBPATH']
LIBS = list(map(str, d['LIBS']))
assert LIBS == ['xxx', 'yyy', 'ascend'], (d['LIBS'], LIBS)
assert d['LINKFLAGS'] == ['-Wl,-link',
'-dylib_file', 'foo-dylib',
'-pthread', '-fmerge-all-constants', '-fopenmp',
'-mno-cygwin', '-mwindows',
('-arch', 'i386'),
('-isysroot', '/tmp'),
'+DD64',
'-fsanitize=memory',
'-fsanitize-address-use-after-return'], repr(d['LINKFLAGS'])
assert d['RPATH'] == ['rpath1', 'rpath2', 'rpath3'], d['RPATH']
def test_MergeFlags(self) -> None:
"""Test the MergeFlags() method."""
env = SubstitutionEnvironment()
# does not set flag if value empty
env.MergeFlags('')
assert 'CCFLAGS' not in env, env['CCFLAGS']
# merges value if flag did not exist
env.MergeFlags('-X')
assert env['CCFLAGS'] == ['-X'], env['CCFLAGS']
# avoid SubstitutionEnvironment for these, has no .Append method,
# which is needed for unique=False test
env = Environment(CCFLAGS="")
# merge with existing but empty flag
env.MergeFlags('-X')
assert env['CCFLAGS'] == ['-X'], env['CCFLAGS']
# default Unique=True enforces no dupes
env.MergeFlags('-X')
assert env['CCFLAGS'] == ['-X'], env['CCFLAGS']
# Unique=False allows dupes
env.MergeFlags('-X', unique=False)
assert env['CCFLAGS'] == ['-X', '-X'], env['CCFLAGS']
# merge from a dict with list values
env = SubstitutionEnvironment(B='b')
env.MergeFlags({'A': ['aaa'], 'B': ['bb', 'bbb']})
assert env['A'] == ['aaa'], env['A']
assert env['B'] == ['b', 'bb', 'bbb'], env['B']
# issue #2961: merge from a dict with string values
env = SubstitutionEnvironment(B='b')
env.MergeFlags({'A': 'aaa', 'B': 'bb bbb'})
assert env['A'] == ['aaa'], env['A']
assert env['B'] == ['b', 'bb', 'bbb'], env['B']
# issue #4231: CPPDEFINES can be a deque, tripped up merge logic
env = Environment(CPPDEFINES=deque(['aaa', 'bbb']))
env.MergeFlags({'CPPDEFINES': 'ccc'})
self.assertEqual(env['CPPDEFINES'], deque(['aaa', 'bbb', 'ccc']))
# issue #3665: if merging dict which is a compound object
# (i.e. value can be lists, etc.), the value object should not
# be modified. per the issue, this happened if key not in env.
env = SubstitutionEnvironment()
try:
del env['CFLAGS'] # just to be sure
except KeyError:
pass
flags = {'CFLAGS': ['-pipe', '-pthread', '-g']}
import copy
saveflags = copy.deepcopy(flags)
env.MergeFlags(flags)
self.assertEqual(flags, saveflags)
class BaseTestCase(unittest.TestCase,TestEnvironmentFixture):
reserved_variables = [
'CHANGED_SOURCES',
'CHANGED_TARGETS',
'SOURCE',
'SOURCES',
'TARGET',
'TARGETS',
'UNCHANGED_SOURCES',
'UNCHANGED_TARGETS',
]
def test___init__(self) -> None:
"""Test construction Environment creation
Create two with identical arguments and check that
they compare the same.
"""
env1 = self.TestEnvironment(XXX = 'x', YYY = 'y')
env2 = self.TestEnvironment(XXX = 'x', YYY = 'y')
assert env1 == env2, diff_env(env1, env2)
assert '__env__' not in env1
assert '__env__' not in env2
def test_variables(self) -> None:
"""Test that variables only get applied once."""
class FakeOptions:
def __init__(self, key, val) -> None:
self.calls = 0
self.key = key
self.val = val
def keys(self):
return [self.key]
def Update(self, env) -> None:
env[self.key] = self.val
self.calls = self.calls + 1
o = FakeOptions('AAA', 'fake_opt')
env = Environment(variables=o, AAA='keyword_arg')
assert o.calls == 1, o.calls
assert env['AAA'] == 'fake_opt', env['AAA']
def test_get(self) -> None:
"""Test the get() method."""
env = self.TestEnvironment(aaa = 'AAA')
x = env.get('aaa')
assert x == 'AAA', x
x = env.get('aaa', 'XXX')
assert x == 'AAA', x
x = env.get('bbb')
assert x is None, x
x = env.get('bbb', 'XXX')
assert x == 'XXX', x
def test_Builder_calls(self) -> None:
"""Test Builder calls through different environments
"""
global called_it
b1 = Builder()
b2 = Builder()
env = Environment()
env.Replace(BUILDERS = { 'builder1' : b1,
'builder2' : b2 })
called_it = {}
env.builder1('in1')
assert called_it['target'] is None, called_it
assert called_it['source'] == ['in1'], called_it