-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathfiletools.py
4141 lines (3472 loc) · 195 KB
/
filetools.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
# #
# Copyright 2012-2025 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
# #
"""
Unit tests for filetools.py
@author: Toon Willems (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Stijn De Weirdt (Ghent University)
@author: Ward Poelmans (Ghent University)
@author: Maxime Boissonneault (Compute Canada, Universite Laval)
"""
import datetime
import filecmp
import glob
import logging
import os
import re
import shutil
import stat
import sys
import tempfile
import textwrap
import time
import types
from io import StringIO
from test.framework.github import requires_github_access
from test.framework.utilities import EnhancedTestCase, TestLoaderFiltered, init_config
from unittest import TextTestRunner
from urllib import request
import easybuild.tools.filetools as ft
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.config import IGNORE, ERROR, WARN, build_option, update_build_option
from easybuild.tools.multidiff import multidiff
from easybuild.tools.run import run_shell_cmd
from easybuild.tools.systemtools import LINUX, get_os_type
class FileToolsTest(EnhancedTestCase):
""" Testcase for filetools module """
class_names = [
('GCC', 'EB_GCC'),
('7zip', 'EB_7zip'),
('Charm++', 'EB_Charm_plus__plus_'),
('DL_POLY_Classic', 'EB_DL_underscore_POLY_underscore_Classic'),
('0_foo+0x0x#-$__', 'EB_0_underscore_foo_plus_0x0x_hash__minus__dollar__underscore__underscore_'),
]
def setUp(self):
"""Test setup."""
super(FileToolsTest, self).setUp()
self.orig_filetools_std_urllib_urlopen = ft.std_urllib.urlopen
if ft.HAVE_REQUESTS:
self.orig_filetools_requests_get = ft.requests.get
self.orig_filetools_HAVE_REQUESTS = ft.HAVE_REQUESTS
def tearDown(self):
"""Cleanup."""
super(FileToolsTest, self).tearDown()
ft.std_urllib.urlopen = self.orig_filetools_std_urllib_urlopen
ft.HAVE_REQUESTS = self.orig_filetools_HAVE_REQUESTS
if ft.HAVE_REQUESTS:
ft.requests.get = self.orig_filetools_requests_get
def test_extract_cmd(self):
"""Test various extract commands."""
tests = [
('test.zip', "unzip -qq test.zip"),
('/some/path/test.tar', "tar xf /some/path/test.tar"),
('test.tar.gz', "tar xzf test.tar.gz"),
('test.TAR.GZ', "tar xzf test.TAR.GZ"),
('test.tgz', "tar xzf test.tgz"),
('test.gtgz', "tar xzf test.gtgz"),
('test.bz2', "bunzip2 -c test.bz2 > test"),
('/some/path/test.bz2', "bunzip2 -c /some/path/test.bz2 > test"),
('test.tbz', "tar xjf test.tbz"),
('test.tbz2', "tar xjf test.tbz2"),
('test.tb2', "tar xjf test.tb2"),
('test.tar.bz2', "tar xjf test.tar.bz2"),
('test.gz', "gunzip -c test.gz > test"),
('untar.gz', "gunzip -c untar.gz > untar"),
("/some/path/test.gz", "gunzip -c /some/path/test.gz > test"),
('test.xz', "unxz test.xz"),
('test.tar.xz', "unset TAPE; unxz test.tar.xz --stdout | tar x"),
('test.txz', "unset TAPE; unxz test.txz --stdout | tar x"),
('test.iso', "7z x test.iso"),
('test.tar.Z', "tar xzf test.tar.Z"),
('test.foo.bar.sh', "cp -dR test.foo.bar.sh ."),
# check whether extension is stripped correct to determine name of target file
# cfr. https://github.com/easybuilders/easybuild-framework/pull/3705
('testbz2.bz2', "bunzip2 -c testbz2.bz2 > testbz2"),
('testgz.gz', "gunzip -c testgz.gz > testgz"),
]
for (fn, expected_cmd) in tests:
cmd = ft.extract_cmd(fn)
self.assertEqual(expected_cmd, cmd)
self.assertEqual("unzip -qq -o test.zip", ft.extract_cmd('test.zip', True))
error_pattern = "test.foo has unknown file extension"
self.assertErrorRegex(EasyBuildError, error_pattern, ft.extract_cmd, 'test.foo')
def test_find_extension(self):
"""Test find_extension function."""
tests = [
('test.zip', '.zip'),
('/some/path/test.tar', '.tar'),
('test.tar.gz', '.tar.gz'),
('test.TAR.GZ', '.TAR.GZ'),
('test.tgz', '.tgz'),
('test.gtgz', '.gtgz'),
('test.bz2', '.bz2'),
('/some/path/test.bz2', '.bz2'),
('test.tbz', '.tbz'),
('test.tbz2', '.tbz2'),
('test.tb2', '.tb2'),
('test.tar.bz2', '.tar.bz2'),
('test.gz', '.gz'),
('untar.gz', '.gz'),
("/some/path/test.gz", '.gz'),
('test.xz', '.xz'),
('test.tar.xz', '.tar.xz'),
('test.txz', '.txz'),
('test.iso', '.iso'),
('test.tar.Z', '.tar.Z'),
('test.foo.bar.sh', '.sh'),
]
for (fn, expected_ext) in tests:
cmd = ft.find_extension(fn)
self.assertEqual(expected_ext, cmd)
def test_convert_name(self):
"""Test convert_name function."""
name = ft.convert_name("test+test-test.mpi")
self.assertEqual(name, "testplustestmintestmpi")
name = ft.convert_name("test+test-test.mpi", True)
self.assertEqual(name, "TESTPLUSTESTMINTESTMPI")
def test_find_base_dir(self):
"""test if we find the correct base dir"""
tmpdir = tempfile.mkdtemp()
foodir = os.path.join(tmpdir, 'foo')
os.mkdir(foodir)
os.mkdir(os.path.join(tmpdir, '.bar'))
os.mkdir(os.path.join(tmpdir, 'easybuild'))
os.chdir(tmpdir)
self.assertTrue(os.path.samefile(foodir, ft.find_base_dir()))
def test_find_glob_pattern(self):
"""test find_glob_pattern function"""
tmpdir = tempfile.mkdtemp()
os.mkdir(os.path.join(tmpdir, 'python2.7'))
os.mkdir(os.path.join(tmpdir, 'python2.7', 'include'))
os.mkdir(os.path.join(tmpdir, 'python3.5m'))
os.mkdir(os.path.join(tmpdir, 'python3.5m', 'include'))
self.assertEqual(ft.find_glob_pattern(os.path.join(tmpdir, 'python2.7*')),
os.path.join(tmpdir, 'python2.7'))
self.assertEqual(ft.find_glob_pattern(os.path.join(tmpdir, 'python2.7*', 'include')),
os.path.join(tmpdir, 'python2.7', 'include'))
self.assertEqual(ft.find_glob_pattern(os.path.join(tmpdir, 'python3.5*')),
os.path.join(tmpdir, 'python3.5m'))
self.assertEqual(ft.find_glob_pattern(os.path.join(tmpdir, 'python3.5*', 'include')),
os.path.join(tmpdir, 'python3.5m', 'include'))
self.assertEqual(ft.find_glob_pattern(os.path.join(tmpdir, 'python3.6*'), False), None)
self.assertErrorRegex(EasyBuildError, "Was expecting exactly", ft.find_glob_pattern,
os.path.join(tmpdir, 'python3.6*'))
self.assertErrorRegex(EasyBuildError, "Was expecting exactly", ft.find_glob_pattern,
os.path.join(tmpdir, 'python*'))
def test_encode_class_name(self):
"""Test encoding of class names."""
for (class_name, encoded_class_name) in self.class_names:
self.assertEqual(ft.encode_class_name(class_name), encoded_class_name)
self.assertEqual(ft.encode_class_name(ft.decode_class_name(encoded_class_name)), encoded_class_name)
def test_decode_class_name(self):
"""Test decoding of class names."""
for (class_name, encoded_class_name) in self.class_names:
self.assertEqual(ft.decode_class_name(encoded_class_name), class_name)
self.assertEqual(ft.decode_class_name(ft.encode_class_name(class_name)), class_name)
def test_patch_perl_script_autoflush(self):
"""Test patching Perl script for autoflush."""
fh, fp = tempfile.mkstemp()
os.close(fh)
perl_lines = [
"$!/usr/bin/perl",
"use strict;",
"print hello",
"",
"print hello again",
]
perltxt = '\n'.join(perl_lines)
ft.write_file(fp, perltxt)
ft.patch_perl_script_autoflush(fp)
txt = ft.read_file(fp)
self.assertTrue(len(txt.split('\n')) == len(perl_lines) + 4)
self.assertTrue(txt.startswith(perl_lines[0] + "\n\nuse IO::Handle qw();\nSTDOUT->autoflush(1);"))
for line in perl_lines[1:]:
self.assertIn(line, txt)
os.remove(fp)
os.remove("%s.eb.orig" % fp)
def test_which(self):
"""Test which function for locating commands."""
python = ft.which('python')
self.assertTrue(python and os.path.exists(python) and os.path.isabs(python))
invalid_cmd = 'i_really_do_not_expect_a_command_with_a_name_like_this_to_be_available'
path = ft.which(invalid_cmd)
self.assertIsNone(path)
path = ft.which(invalid_cmd, on_error=IGNORE)
self.assertIsNone(path)
error_msg = "Could not find command '%s'" % invalid_cmd
self.assertErrorRegex(EasyBuildError, error_msg, ft.which, invalid_cmd, on_error=ERROR)
os.environ['PATH'] = '%s:%s' % (self.test_prefix, os.environ['PATH'])
# put a directory 'foo' in place (should be ignored by 'which')
foo = os.path.join(self.test_prefix, 'foo')
ft.mkdir(foo)
ft.adjust_permissions(foo, stat.S_IRUSR | stat.S_IXUSR)
# put executable file 'bar' in place
bar = os.path.join(self.test_prefix, 'bar')
ft.write_file(bar, '#!/bin/bash')
ft.adjust_permissions(bar, stat.S_IRUSR | stat.S_IXUSR)
self.assertEqual(ft.which('foo'), None)
self.assertTrue(os.path.samefile(ft.which('bar'), bar))
# add another location to 'bar', which should only return the first location by default
barbis = os.path.join(self.test_prefix, 'more', 'bar')
ft.write_file(barbis, '#!/bin/bash')
ft.adjust_permissions(barbis, stat.S_IRUSR | stat.S_IXUSR)
os.environ['PATH'] = '%s:%s' % (os.environ['PATH'], os.path.dirname(barbis))
self.assertTrue(os.path.samefile(ft.which('bar'), bar))
# test getting *all* locations to specified command
res = ft.which('bar', retain_all=True)
self.assertEqual(len(res), 2)
self.assertTrue(os.path.samefile(res[0], bar))
self.assertTrue(os.path.samefile(res[1], barbis))
# both read/exec permissions must be available
# if read permissions are removed for first hit, second hit is found instead
ft.adjust_permissions(bar, stat.S_IRUSR, add=False)
self.assertTrue(os.path.samefile(ft.which('bar'), barbis))
# likewise for read permissions
ft.adjust_permissions(bar, stat.S_IRUSR, add=True)
self.assertTrue(os.path.samefile(ft.which('bar'), bar))
ft.adjust_permissions(bar, stat.S_IXUSR, add=False)
self.assertTrue(os.path.samefile(ft.which('bar'), barbis))
# if read permission on other 'bar' are also removed, nothing is found anymore
ft.adjust_permissions(barbis, stat.S_IRUSR, add=False)
self.assertEqual(ft.which('bar'), None)
# checking of read/exec permissions can be disabled via 'check_perms'
self.assertTrue(os.path.samefile(ft.which('bar', check_perms=False), bar))
def test_checksums(self):
"""Test checksum functionality."""
fp = os.path.join(self.test_prefix, 'test.txt')
ft.write_file(fp, "easybuild\n")
known_checksums = {
'sha256': '1c49562c4b404f3120a3fa0926c8d09c99ef80e470f7de03ffdfa14047960ea5',
'sha512': '7610f6ce5e91e56e350d25c917490e4815f7986469fafa41056698aec256733e'
'b7297da8b547d5e74b851d7c4e475900cec4744df0f887ae5c05bf1757c224b4',
}
old_log_level = ft._log.getEffectiveLevel()
ft._log.setLevel(logging.DEBUG)
# make sure checksums computation/verification is correct
for checksum_type, checksum in known_checksums.items():
self.assertEqual(ft.compute_checksum(fp, checksum_type=checksum_type), checksum)
with self.log_to_testlogfile():
self.assertTrue(ft.verify_checksum(fp, (checksum_type, checksum)))
self.assertIn('Computed ' + checksum_type, ft.read_file(self.logfile))
# Passing precomputed checksums reuses it
with self.log_to_testlogfile():
computed_checksums = {checksum_type: checksum}
self.assertTrue(ft.verify_checksum(fp, (checksum_type, checksum), computed_checksums))
self.assertIn('Precomputed ' + checksum_type, ft.read_file(self.logfile))
# If the type isn't contained the checksum will be computed
with self.log_to_testlogfile():
computed_checksums = {'doesnt exist': 'checksum'}
self.assertTrue(ft.verify_checksum(fp, (checksum_type, checksum), computed_checksums))
self.assertIn('Computed ' + checksum_type, ft.read_file(self.logfile))
ft._log.setLevel(old_log_level)
# default checksum type is SHA256
self.assertEqual(ft.compute_checksum(fp), known_checksums['sha256'])
# SHA256 checksums can be verified without specifying type
self.assertTrue(ft.verify_checksum(fp, known_checksums['sha256']))
# providing non-matching SHA256 checksums results in failed verification
self.assertFalse(ft.verify_checksum(fp, '7167b64b1ca062b9674ffef46f9325db7167b64b1ca062b9674ffef46f9325db'))
# checksum of length 32 is assumed to be MD5, length 64 to be SHA256, other lengths not allowed
# checksum of length other than 32/64 yields an error
error_pattern = r"Length of checksum '.*' \(\d+\) does not match with either MD5 \(32\) or SHA256 \(64\)"
for checksum in ['tooshort', 'inbetween32and64charactersisnotgoodeither', known_checksums['sha256'] + 'foo']:
self.assertErrorRegex(EasyBuildError, error_pattern, ft.verify_checksum, fp, checksum)
# make sure faulty checksums are reported
broken_checksums = {typ: (val[:-3] + 'foo') for typ, val in known_checksums.items()}
for checksum_type, checksum in broken_checksums.items():
self.assertFalse(ft.compute_checksum(fp, checksum_type=checksum_type) == checksum)
self.assertFalse(ft.verify_checksum(fp, (checksum_type, checksum)))
# sha256 is default
self.assertFalse(ft.compute_checksum(fp) == broken_checksums['sha256'])
self.assertFalse(ft.verify_checksum(fp, broken_checksums['sha256']))
# test specify alternative checksums
alt_checksums = ('7167b64b1ca062b9674ffef46f9325db7167b64b1ca062b9674ffef46f9325db', known_checksums['sha256'])
self.assertTrue(ft.verify_checksum(fp, alt_checksums))
alt_checksums = (known_checksums['sha256'],)
self.assertTrue(ft.verify_checksum(fp, alt_checksums))
alt_checksums = ('7167b64b1ca062b9674ffef46f9325db7167b64b1ca062b9674ffef46f9325db', broken_checksums['sha256'])
self.assertFalse(ft.verify_checksum(fp, alt_checksums))
# Check dictionary
alt_checksums = (known_checksums['sha256'],)
self.assertTrue(ft.verify_checksum(fp, {os.path.basename(fp): known_checksums['sha256']}))
# None is accepted
self.assertTrue(ft.verify_checksum(fp, {os.path.basename(fp): None}))
faulty_dict = {'wrong-name': known_checksums['sha256']}
self.assertErrorRegex(EasyBuildError,
"Missing checksum for " + os.path.basename(fp) + " in .*wrong-name.*",
ft.verify_checksum, fp, faulty_dict)
# check whether missing checksums are enforced
build_options = {
'enforce_checksums': True,
}
init_config(build_options=build_options)
self.assertErrorRegex(EasyBuildError, "Missing checksum for", ft.verify_checksum, fp, None)
self.assertTrue(ft.verify_checksum(fp, known_checksums['sha256']))
# Test dictionary-type checksums
self.assertErrorRegex(EasyBuildError, "Missing checksum for", ft.verify_checksum,
fp, {os.path.basename(fp): None})
for checksum in [known_checksums[x] for x in ['sha256']]:
dict_checksum = {os.path.basename(fp): checksum, 'foo': 'baa'}
self.assertTrue(ft.verify_checksum(fp, dict_checksum))
del dict_checksum[os.path.basename(fp)]
self.assertErrorRegex(EasyBuildError, "Missing checksum for", ft.verify_checksum, fp, dict_checksum)
def test_deprecated_checksums(self):
"""Test checksum functionality."""
fp = os.path.join(self.test_prefix, 'test.txt')
ft.write_file(fp, "easybuild\n")
known_checksums = {
'adler32': '0x379257805',
'crc32': '0x1457143216',
'md5': '7167b64b1ca062b9674ffef46f9325db',
'sha1': 'db05b79e09a4cc67e9dd30b313b5488813db3190',
}
self.allow_deprecated_behaviour()
self.mock_stderr(True) # just to capture deprecation warning
# make sure checksums computation/verification is correct
for checksum_type, checksum in known_checksums.items():
self.assertEqual(ft.compute_checksum(fp, checksum_type=checksum_type), checksum)
self.assertTrue(ft.verify_checksum(fp, (checksum_type, checksum)))
# MD5 checksums can be verified without specifying type
self.assertTrue(ft.verify_checksum(fp, known_checksums['md5']))
# providing non-matching MD5 checksums results in failed verification
self.assertFalse(ft.verify_checksum(fp, '1c49562c4b404f3120a3fa0926c8d09c'))
# checksum of length 32 is assumed to be MD5, length 64 to be SHA256, other lengths not allowed
# checksum of length other than 32/64 yields an error
error_pattern = r"Length of checksum '.*' \(\d+\) does not match with either MD5 \(32\) or SHA256 \(64\)"
for checksum in ['tooshort', 'inbetween32and64charactersisnotgoodeither', known_checksums['md5'] + 'foo']:
self.assertErrorRegex(EasyBuildError, error_pattern, ft.verify_checksum, fp, checksum)
# make sure faulty checksums are reported
broken_checksums = {typ: (val[:-3] + 'foo') for typ, val in known_checksums.items()}
for checksum_type, checksum in broken_checksums.items():
self.assertFalse(ft.compute_checksum(fp, checksum_type=checksum_type) == checksum)
self.assertFalse(ft.verify_checksum(fp, (checksum_type, checksum)))
self.assertFalse(ft.verify_checksum(fp, broken_checksums['md5']))
# test specify alternative checksums
alt_checksums = ('fecf50db81148786647312bbd3b5c740', '2c829facaba19c0fcd81f9ce96bef712',
'840078aeb4b5d69506e7c8edae1e1b89', known_checksums['md5'])
self.assertTrue(ft.verify_checksum(fp, alt_checksums))
alt_checksums = ('840078aeb4b5d69506e7c8edae1e1b89', known_checksums['md5'], '2c829facaba19c0fcd81f9ce96bef712')
self.assertTrue(ft.verify_checksum(fp, alt_checksums))
alt_checksums = (known_checksums['md5'], '840078aeb4b5d69506e7c8edae1e1b89', '2c829facaba19c0fcd81f9ce96bef712')
self.assertTrue(ft.verify_checksum(fp, alt_checksums))
# check whether missing checksums are enforced
build_options = {
'enforce_checksums': True,
}
init_config(build_options=build_options)
self.assertErrorRegex(EasyBuildError, "Missing checksum for", ft.verify_checksum, fp, None)
self.assertTrue(ft.verify_checksum(fp, known_checksums['md5']))
# Test dictionary-type checksums
for checksum in [known_checksums[x] for x in ['md5']]:
dict_checksum = {os.path.basename(fp): checksum, 'foo': 'baa'}
self.assertTrue(ft.verify_checksum(fp, dict_checksum))
del dict_checksum[os.path.basename(fp)]
self.assertErrorRegex(EasyBuildError, "Missing checksum for", ft.verify_checksum, fp, dict_checksum)
self.mock_stderr(False)
def test_common_path_prefix(self):
"""Test get common path prefix for a list of paths."""
self.assertEqual(ft.det_common_path_prefix(['/foo/bar/foo', '/foo/bar/baz', '/foo/bar/bar']), '/foo/bar')
self.assertEqual(ft.det_common_path_prefix(['/foo/bar/', '/foo/bar/baz', '/foo/bar']), '/foo/bar')
self.assertEqual(ft.det_common_path_prefix(['/foo/bar', '/foo']), '/foo')
self.assertEqual(ft.det_common_path_prefix(['/foo/bar/']), '/foo/bar')
self.assertEqual(ft.det_common_path_prefix(['/foo/bar', '/bar', '/foo']), None)
self.assertEqual(ft.det_common_path_prefix(['foo', 'bar']), None)
self.assertEqual(ft.det_common_path_prefix(['foo']), None)
self.assertEqual(ft.det_common_path_prefix([]), None)
def test_normalize_path(self):
"""Test normalize_path"""
self.assertEqual(ft.normalize_path(''), '')
self.assertEqual(ft.normalize_path('/'), '/')
self.assertEqual(ft.normalize_path('//'), '//')
self.assertEqual(ft.normalize_path('///'), '/')
self.assertEqual(ft.normalize_path('/foo/bar/baz'), '/foo/bar/baz')
self.assertEqual(ft.normalize_path('/foo//bar/././baz/'), '/foo/bar/baz')
self.assertEqual(ft.normalize_path('foo//bar/././baz/'), 'foo/bar/baz')
self.assertEqual(ft.normalize_path('//foo//bar/././baz/'), '//foo/bar/baz')
self.assertEqual(ft.normalize_path('///foo//bar/././baz/'), '/foo/bar/baz')
self.assertEqual(ft.normalize_path('////foo//bar/././baz/'), '/foo/bar/baz')
self.assertEqual(ft.normalize_path('/././foo//bar/././baz/'), '/foo/bar/baz')
self.assertEqual(ft.normalize_path('//././foo//bar/././baz/'), '//foo/bar/baz')
def test_is_parent_path(self):
"""Test is_parent_path"""
self.assertTrue(ft.is_parent_path('/foo/bar', '/foo/bar/test0'))
self.assertTrue(ft.is_parent_path('/foo/bar', '/foo/bar/test0/test1'))
self.assertTrue(ft.is_parent_path('/foo/bar', '/foo/bar'))
self.assertFalse(ft.is_parent_path('/foo/bar/test0', '/foo/bar'))
self.assertFalse(ft.is_parent_path('/foo/bar', '/foo/test'))
# Check that trailing slashes are ignored
self.assertTrue(ft.is_parent_path('/foo/bar/', '/foo/bar'))
self.assertTrue(ft.is_parent_path('/foo/bar', '/foo/bar/'))
self.assertTrue(ft.is_parent_path('/foo/bar/', '/foo/bar/'))
# Check that is also accepts relative paths
self.assertTrue(ft.is_parent_path('foo/bar', 'foo/bar/test0'))
self.assertTrue(ft.is_parent_path('foo/bar', 'foo/bar/test0/test1'))
self.assertTrue(ft.is_parent_path('foo/bar', 'foo/bar'))
self.assertFalse(ft.is_parent_path('foo/bar/test0', 'foo/bar'))
self.assertFalse(ft.is_parent_path('foo/bar', 'foo/test'))
# Check that relative paths are accounted
self.assertTrue(ft.is_parent_path('foo/../baz', 'bar/../baz'))
# Check that symbolic links are accounted
ft.mkdir(os.path.join(self.test_prefix, 'base'))
ft.mkdir(os.path.join(self.test_prefix, 'base', 'concrete'))
ft.symlink(
os.path.join(self.test_prefix, 'base', 'concrete'),
os.path.join(self.test_prefix, 'base', 'link')
)
self.assertTrue(
ft.is_parent_path(
os.path.join(self.test_prefix, 'base', 'link'),
os.path.join(self.test_prefix, 'base', 'concrete', 'file')
)
)
def test_det_file_size(self):
"""Test det_file_size function."""
self.assertEqual(ft.det_file_size({'Content-Length': '12345'}), 12345)
# missing content length, or invalid value
self.assertEqual(ft.det_file_size({}), None)
self.assertEqual(ft.det_file_size({'Content-Length': 'foo'}), None)
test_url = 'https://github.com/easybuilders/easybuild-framework/raw/develop/'
test_url += 'test/framework/sandbox/sources/toy/toy-0.0.tar.gz'
expected_size = 273
# also try with actual HTTP header
try:
fh = request.urlopen(test_url)
self.assertEqual(ft.det_file_size(fh.info()), expected_size)
fh.close()
# also try using requests, which is used as a fallback in download_file
try:
import requests
res = requests.get(test_url)
self.assertEqual(ft.det_file_size(res.headers), expected_size)
res.close()
except ImportError:
pass
except request.URLError:
print("Skipping online test for det_file_size (working offline)")
def test_download_file(self):
"""Test download_file function."""
fn = 'toy-0.0.tar.gz'
target_location = os.path.join(self.test_buildpath, 'some', 'subdir', fn)
# provide local file path as source URL
test_dir = os.path.abspath(os.path.dirname(__file__))
toy_source_dir = os.path.join(test_dir, 'sandbox', 'sources', 'toy')
source_url = 'file://%s/%s' % (toy_source_dir, fn)
with self.mocked_stdout_stderr():
res = ft.download_file(fn, source_url, target_location)
self.assertEqual(res, target_location, "'download' of local file works")
downloads = glob.glob(target_location + '*')
self.assertEqual(len(downloads), 1)
# non-existing files result in None return value
with self.mocked_stdout_stderr():
self.assertEqual(ft.download_file(fn, 'file://%s/nosuchfile' % test_dir, target_location), None)
# install broken proxy handler for opening local files
# this should make urlopen use this broken proxy for downloading from a file:// URL
proxy_handler = request.ProxyHandler({'file': 'file://%s/nosuchfile' % test_dir})
request.install_opener(request.build_opener(proxy_handler))
# downloading over a broken proxy results in None return value (failed download)
# this tests whether proxies are taken into account by download_file
with self.mocked_stdout_stderr():
self.assertEqual(ft.download_file(fn, source_url, target_location), None,
"download over broken proxy fails")
# modify existing download so we can verify re-download
ft.write_file(target_location, '')
# restore a working file handler, and retest download of local file
request.install_opener(request.build_opener(request.FileHandler()))
with self.mocked_stdout_stderr():
res = ft.download_file(fn, source_url, target_location)
self.assertEqual(res, target_location, "'download' of local file works after removing broken proxy")
# existing file was re-downloaded, so a backup should have been created of the existing file
downloads = glob.glob(target_location + '*')
self.assertEqual(len(downloads), 2)
backup = [d for d in downloads if os.path.basename(d) != fn][0]
self.assertEqual(ft.read_file(backup), '')
self.assertEqual(ft.compute_checksum(target_location), ft.compute_checksum(os.path.join(toy_source_dir, fn)))
# make sure specified timeout is parsed correctly (as a float, not a string)
opts = init_config(args=['--download-timeout=5.3'])
init_config(build_options={'download_timeout': opts.download_timeout})
target_location = os.path.join(self.test_prefix, 'jenkins_robots.txt')
url = 'https://raw.githubusercontent.com/easybuilders/easybuild-framework/master/README.rst'
try:
request.urlopen(url)
with self.mocked_stdout_stderr():
res = ft.download_file(fn, url, target_location)
self.assertEqual(res, target_location, "download with specified timeout works")
except request.URLError:
print("Skipping timeout test in test_download_file (working offline)")
# check whether disabling trace output works
target_location = os.path.join(self.test_prefix, 'test.txt')
with self.mocked_stdout_stderr():
ft.download_file(fn, source_url, target_location, forced=True, trace=False)
stdout = self.get_stdout()
self.assertEqual(stdout, '')
ft.remove_file(target_location)
# also test behaviour of download_file under --dry-run
build_options = {
'extended_dry_run': True,
'silent': False,
}
init_config(build_options=build_options)
target_location = os.path.join(self.test_prefix, 'foo')
if os.path.exists(target_location):
shutil.rmtree(target_location)
self.mock_stdout(True)
path = ft.download_file(fn, source_url, target_location)
txt = self.get_stdout()
self.mock_stdout(False)
self.assertEqual(path, target_location)
self.assertNotExists(target_location)
self.assertTrue(re.match("file written: .*/foo", txt))
with self.mocked_stdout_stderr():
ft.download_file(fn, source_url, target_location, forced=True)
self.assertExists(target_location)
self.assertTrue(os.path.samefile(path, target_location))
def test_download_file_requests_fallback(self):
"""Test fallback to requests in download_file function."""
url = 'https://raw.githubusercontent.com/easybuilders/easybuild-framework/master/README.rst'
fn = 'README.rst'
target = os.path.join(self.test_prefix, fn)
# replaceurlopen with function that raises SSL error
def fake_urllib_open(*args, **kwargs):
error_msg = "<urlopen error [Errno 1] _ssl.c:510: error:12345:"
error_msg += "SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure>"
raise IOError(error_msg)
ft.std_urllib.urlopen = fake_urllib_open
# if requests is available, file is downloaded
if ft.HAVE_REQUESTS:
with self.mocked_stdout_stderr():
res = ft.download_file(fn, url, target)
self.assertTrue(res and os.path.exists(res))
self.assertIn("https://easybuild.io", ft.read_file(res))
# without requests being available, error is raised
ft.HAVE_REQUESTS = False
self.assertErrorRegex(EasyBuildError, "SSL issues with urllib2", ft.download_file, fn, url, target)
# replaceurlopen with function that raises HTTP error 403
def fake_urllib_open(*args, **kwargs):
raise ft.std_urllib.HTTPError(url, 403, "Forbidden", "", StringIO())
ft.std_urllib.urlopen = fake_urllib_open
# if requests is available, file is downloaded
if ft.HAVE_REQUESTS:
with self.mocked_stdout_stderr():
res = ft.download_file(fn, url, target)
self.assertTrue(res and os.path.exists(res))
self.assertIn("https://easybuild.io", ft.read_file(res))
# without requests being available, error is raised
ft.HAVE_REQUESTS = False
self.assertErrorRegex(EasyBuildError, "SSL issues with urllib2", ft.download_file, fn, url, target)
def test_download_file_insecure(self):
"""
Test downloading of file via insecure URL
"""
self.assertFalse(build_option('insecure_download'))
# replace urlopen with function that raises IOError
def fake_urllib_open(url, *args, **kwargs):
if kwargs.get('context') is None:
error_msg = " <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] "
error_msg += "certificate verify failed (_ssl.c:618)>"
raise IOError(error_msg)
return self.orig_filetools_std_urllib_urlopen(url, *args, **kwargs)
fn = 'toy-0.0.eb'
test_dir = os.path.abspath(os.path.dirname(__file__))
toy_dir = os.path.join(test_dir, 'easyconfigs', 'test_ecs', 't', 'toy')
url = 'file://%s/%s' % (toy_dir, fn)
ft.std_urllib.urlopen = fake_urllib_open
target_path = os.path.join(self.test_prefix, fn)
# first try without allowing insecure downloads (default)
with self.mocked_stdout_stderr():
res = ft.download_file(fn, url, target_path)
self.assertEqual(res, None)
update_build_option('insecure_download', True)
self.mock_stdout(True)
self.mock_stderr(True)
res = ft.download_file(fn, url, target_path)
stderr = self.get_stderr()
self.mock_stdout(False)
self.mock_stderr(False)
self.assertIn("WARNING: Not checking server certificates while downloading toy-0.0.eb", stderr)
self.assertExists(res)
with self.mocked_stdout_stderr():
self.assertTrue(ft.read_file(res).startswith("name = 'toy'"))
# also test insecure download via requests fallback
if ft.HAVE_REQUESTS:
# need to use actual URL here, requests doesn't like file:// URLs
url = 'https://raw.githubusercontent.com/easybuilders/easybuild-framework/master/README.rst'
fn = os.path.basename(url)
target_path = os.path.join(self.test_prefix, fn)
# replace urlopen with function that raises HTTP error 403
def fake_urllib_open(url, *args, **kwargs):
raise ft.std_urllib.HTTPError(url, 403, "Forbidden", "", StringIO())
ft.std_urllib.urlopen = fake_urllib_open
def fake_requests_get(url, *args, **kwargs):
verify = kwargs.get('verify')
if verify:
raise IOError("failing SSL certificate!")
return self.orig_filetools_requests_get(url, *args, **kwargs)
ft.requests.get = fake_requests_get
update_build_option('insecure_download', False)
with self.mocked_stdout_stderr():
res = ft.download_file(fn, url, target_path)
self.assertEqual(res, None)
update_build_option('insecure_download', True)
self.mock_stderr(True)
self.mock_stdout(True)
res = ft.download_file(fn, url, target_path)
stderr = self.get_stderr()
self.mock_stderr(False)
self.mock_stdout(False)
self.assertIn("WARNING: Not checking server certificates while downloading README.rst", stderr)
self.assertExists(res)
self.assertIn("https://easybuild.io", ft.read_file(res))
def test_mkdir(self):
"""Test mkdir function."""
def check_mkdir(path, error=None, **kwargs):
"""Create specified directory with mkdir, and check for correctness."""
if error is None:
ft.mkdir(path, **kwargs)
self.assertTrue(os.path.exists(path) and os.path.isdir(path), "Directory %s exists" % path)
else:
self.assertErrorRegex(EasyBuildError, error, ft.mkdir, path, **kwargs)
foodir = os.path.join(self.test_prefix, 'foo')
barfoodir = os.path.join(self.test_prefix, 'bar', 'foo')
check_mkdir(foodir)
# no error on existing paths
check_mkdir(foodir)
# no recursion by defaults, requires parents=True
check_mkdir(barfoodir, error="Failed.*No such file or directory")
check_mkdir(barfoodir, parents=True)
check_mkdir(os.path.join(barfoodir, 'bar', 'foo', 'trolololol'), parents=True)
# group ID and sticky bits are disabled by default
self.assertFalse(os.stat(foodir).st_mode & (stat.S_ISGID | stat.S_ISVTX), "no gid/sticky bit %s" % foodir)
self.assertFalse(os.stat(barfoodir).st_mode & (stat.S_ISGID | stat.S_ISVTX), "no gid/sticky bit %s" % barfoodir)
# setting group ID bit works
giddir = os.path.join(foodir, 'gid')
check_mkdir(giddir, set_gid=True)
self.assertTrue(os.stat(giddir).st_mode & stat.S_ISGID, "gid bit set %s" % giddir)
self.assertFalse(os.stat(giddir).st_mode & stat.S_ISVTX, "no sticky bit %s" % giddir)
# setting stciky bit works
stickydir = os.path.join(barfoodir, 'sticky')
check_mkdir(stickydir, sticky=True)
self.assertFalse(os.stat(stickydir).st_mode & stat.S_ISGID, "no gid bit %s" % stickydir)
self.assertTrue(os.stat(stickydir).st_mode & stat.S_ISVTX, "sticky bit set %s" % stickydir)
# setting both works, bits are set for all new subdirectories
stickygiddirs = [os.path.join(foodir, 'new')]
stickygiddirs.append(os.path.join(stickygiddirs[-1], 'sticky'))
stickygiddirs.append(os.path.join(stickygiddirs[-1], 'and'))
stickygiddirs.append(os.path.join(stickygiddirs[-1], 'gid'))
check_mkdir(stickygiddirs[-1], parents=True, set_gid=True, sticky=True)
for subdir in stickygiddirs:
gid_or_sticky = stat.S_ISGID | stat.S_ISVTX
self.assertEqual(os.stat(subdir).st_mode & gid_or_sticky, gid_or_sticky, "gid bit set %s" % subdir)
# existing parent dirs are untouched, no sticky/group ID bits set
self.assertFalse(os.stat(foodir).st_mode & (stat.S_ISGID | stat.S_ISVTX), "no gid/sticky bit %s" % foodir)
self.assertFalse(os.stat(barfoodir).st_mode & (stat.S_ISGID | stat.S_ISVTX), "no gid/sticky bit %s" % barfoodir)
def test_path_matches(self):
"""Test path_matches function."""
# set up temporary directories
path1 = os.path.join(self.test_prefix, 'path1')
ft.mkdir(path1)
path2 = os.path.join(self.test_prefix, 'path2')
ft.mkdir(path1)
symlink = os.path.join(self.test_prefix, 'symlink')
os.symlink(path1, symlink)
missing = os.path.join(self.test_prefix, 'missing')
self.assertFalse(ft.path_matches(missing, [path1, path2]))
self.assertFalse(ft.path_matches(path1, [missing]))
self.assertFalse(ft.path_matches(path1, [missing, path2]))
self.assertFalse(ft.path_matches(path2, [missing, symlink]))
self.assertTrue(ft.path_matches(path1, [missing, symlink]))
def test_is_readable(self):
"""Test is_readable"""
test_file = os.path.join(self.test_prefix, 'test.txt')
self.assertFalse(ft.is_readable(test_file))
ft.write_file(test_file, 'test')
self.assertTrue(ft.is_readable(test_file))
os.chmod(test_file, 0)
self.assertFalse(ft.is_readable(test_file))
def test_symlink_resolve_path(self):
"""Test symlink and resolve_path function"""
# write_file and read_file tests are elsewhere. so not getting their states
test_dir = os.path.join(os.path.realpath(self.test_prefix), 'test')
ft.mkdir(test_dir)
link_dir = os.path.join(self.test_prefix, 'linkdir')
ft.symlink(test_dir, link_dir)
self.assertTrue(os.path.islink(link_dir))
self.assertExists(link_dir)
test_file = os.path.join(link_dir, 'test.txt')
ft.write_file(test_file, "test123")
# creating the link file
link = os.path.join(self.test_prefix, 'test.link')
ft.symlink(test_file, link)
# checking if file is symlink
self.assertTrue(os.path.islink(link))
self.assertExists(link_dir)
self.assertTrue(os.path.samefile(os.path.join(self.test_prefix, 'test', 'test.txt'), link))
# test symlink when it already exists and points to the same path
ft.symlink(test_file, link)
# test symlink when it already exists but points to a different path
test_file2 = os.path.join(link_dir, 'test2.txt')
ft.write_file(test_file, "test123")
self.assertErrorRegex(EasyBuildError,
"Trying to symlink %s to %s, but the symlink already exists and points to %s." %
(test_file2, link, test_file),
ft.symlink, test_file2, link)
# test resolve_path
self.assertEqual(test_dir, ft.resolve_path(link_dir))
self.assertEqual(os.path.join(os.path.realpath(self.test_prefix), 'test', 'test.txt'), ft.resolve_path(link))
self.assertEqual(ft.read_file(link), "test123")
self.assertErrorRegex(EasyBuildError, "Resolving path .* failed", ft.resolve_path, None)
def test_remove_symlinks(self):
"""Test remove valid and invalid symlinks"""
# creating test file
fp = os.path.join(self.test_prefix, 'test.txt')
txt = "test_my_link_file"
ft.write_file(fp, txt)
# creating the symlink
link = os.path.join(self.test_prefix, 'test.link')
ft.symlink(fp, link) # test if is symlink is valid is done elsewhere
# Attempting to remove a valid symlink
ft.remove_file(link)
self.assertFalse(os.path.islink(link))
self.assertNotExists(link)
# Testing the removal of invalid symlinks
# Restoring the symlink and removing the file, this way the symlink is invalid
ft.symlink(fp, link)
ft.remove_file(fp)
# attempting to remove the invalid symlink
ft.remove_file(link)
self.assertFalse(os.path.islink(link))
self.assertNotExists(link)
def test_read_write_file(self):
"""Test reading/writing files."""
# Test different "encodings"
ascii_file = os.path.join(self.test_prefix, 'ascii.txt')
txt = 'Hello World\nFoo bar'
ft.write_file(ascii_file, txt)
self.assertEqual(ft.read_file(ascii_file), txt)
binary_file = os.path.join(self.test_prefix, 'binary.txt')
txt = b'Hello World\x12\x00\x01\x02\x03\nFoo bar'
ft.write_file(binary_file, txt)
self.assertEqual(ft.read_file(binary_file, mode='rb'), txt)
utf8_file = os.path.join(self.test_prefix, 'utf8.txt')
txt = b'Hyphen: \xe2\x80\x93\nEuro sign: \xe2\x82\xac\na with dots: \xc3\xa4'
if sys.version_info[0] == 3:
txt_decoded = txt.decode('utf-8')
else:
txt_decoded = txt
# Must work as binary and string
ft.write_file(utf8_file, txt)
self.assertEqual(ft.read_file(utf8_file), txt_decoded)
ft.write_file(utf8_file, txt_decoded)
self.assertEqual(ft.read_file(utf8_file), txt_decoded)
# Test append
fp = os.path.join(self.test_prefix, 'test.txt')
txt = "test123"
ft.write_file(fp, txt)
self.assertEqual(ft.read_file(fp), txt)
txt2 = '\n'.join(['test', '123'])
ft.write_file(fp, txt2, append=True)
self.assertEqual(ft.read_file(fp), txt + txt2)
# test backing up of existing file
ft.write_file(fp, 'foo', backup=True)
self.assertEqual(ft.read_file(fp), 'foo')
test_files = glob.glob(fp + '*')
self.assertEqual(len(test_files), 2)
backup1 = [x for x in test_files if os.path.basename(x) != 'test.txt'][0]
self.assertEqual(ft.read_file(backup1), txt + txt2)
ft.write_file(fp, 'bar', append=True, backup=True)
self.assertEqual(ft.read_file(fp), 'foobar')
test_files = glob.glob(fp + '*')
self.assertEqual(len(test_files), 3)
backup2 = [x for x in test_files if x != backup1 and os.path.basename(x) != 'test.txt'][0]
self.assertEqual(ft.read_file(backup1), txt + txt2)
self.assertEqual(ft.read_file(backup2), 'foo')
# tese use of 'verbose' to make write_file print location of backed up file
self.mock_stdout(True)
ft.write_file(fp, 'foo', backup=True, verbose=True)
stdout = self.get_stdout()
self.mock_stdout(False)
regex = re.compile("^== Backup of .*/test.txt created at .*/test.txt.bak_[0-9]*")
self.assertTrue(regex.search(stdout), "Pattern '%s' found in: %s" % (regex.pattern, stdout))
# by default, write_file will just blindly overwrite an already existing file
self.assertExists(fp)
ft.write_file(fp, 'blah')
self.assertEqual(ft.read_file(fp), 'blah')
# blind overwriting can be disabled via 'overwrite'
error = "File exists, not overwriting it without --force: %s" % fp
self.assertErrorRegex(EasyBuildError, error, ft.write_file, fp, 'blah', always_overwrite=False)
self.assertErrorRegex(EasyBuildError, error, ft.write_file, fp, 'blah', always_overwrite=False, backup=True)
# use of --force ensuring that file gets written regardless of whether or not it exists already
build_options = {'force': True}
init_config(build_options=build_options)
ft.write_file(fp, 'overwrittenbyforce', always_overwrite=False)
self.assertEqual(ft.read_file(fp), 'overwrittenbyforce')
ft.write_file(fp, 'overwrittenbyforcewithbackup', always_overwrite=False, backup=True)
self.assertEqual(ft.read_file(fp), 'overwrittenbyforcewithbackup')
# also test behaviour of write_file under --dry-run
build_options = {
'extended_dry_run': True,
'silent': False,
}
init_config(build_options=build_options)
foo = os.path.join(self.test_prefix, 'foo.txt')
self.mock_stdout(True)
ft.write_file(foo, 'bar')
txt = self.get_stdout()
self.mock_stdout(False)
self.assertNotExists(foo)