forked from saltstack/salt
/
test_file.py
3811 lines (3415 loc) · 147 KB
/
test_file.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
# -*- coding: utf-8 -*-
'''
Tests for the file state
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
import re
import sys
import shutil
import stat
import tempfile
import textwrap
import filecmp
log = logging.getLogger(__name__)
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from tests.support.paths import BASE_FILES, FILES, TMP, TMP_STATE_TREE
from tests.support.helpers import (
destructiveTest,
skip_if_not_root,
with_system_user_and_group,
with_tempdir,
with_tempfile,
Webserver,
destructiveTest
)
from tests.support.mixins import SaltReturnAssertsMixin
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
HAS_PWD = True
try:
import pwd
except ImportError:
HAS_PWD = False
HAS_GRP = True
try:
import grp
except ImportError:
HAS_GRP = False
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
IS_WINDOWS = salt.utils.platform.is_windows()
BINARY_FILE = b'GIF89a\x01\x00\x01\x00\x80\x00\x00\x05\x04\x04\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;'
if IS_WINDOWS:
FILEPILLAR = 'C:\\Windows\\Temp\\filepillar-python'
FILEPILLARDEF = 'C:\\Windows\\Temp\\filepillar-defaultvalue'
FILEPILLARGIT = 'C:\\Windows\\Temp\\filepillar-bar'
else:
FILEPILLAR = '/tmp/filepillar-python'
FILEPILLARDEF = '/tmp/filepillar-defaultvalue'
FILEPILLARGIT = '/tmp/filepillar-bar'
def _test_managed_file_mode_keep_helper(testcase, local=False):
'''
DRY helper function to run the same test with a local or remote path
'''
name = os.path.join(TMP, 'scene33')
grail_fs_path = os.path.join(BASE_FILES, 'grail', 'scene33')
grail = 'salt://grail/scene33' if not local else grail_fs_path
# Get the current mode so that we can put the file back the way we
# found it when we're done.
grail_fs_mode = int(testcase.run_function('file.get_mode', [grail_fs_path]), 8)
initial_mode = 0o770
new_mode_1 = 0o600
new_mode_2 = 0o644
# Set the initial mode, so we can be assured that when we set the mode
# to "keep", we're actually changing the permissions of the file to the
# new mode.
ret = testcase.run_state(
'file.managed',
name=name,
mode=oct(initial_mode),
source=grail,
)
if IS_WINDOWS:
testcase.assertSaltFalseReturn(ret)
return
testcase.assertSaltTrueReturn(ret)
try:
# Update the mode on the fileserver (pass 1)
os.chmod(grail_fs_path, new_mode_1)
ret = testcase.run_state(
'file.managed',
name=name,
mode='keep',
source=grail,
)
testcase.assertSaltTrueReturn(ret)
managed_mode = stat.S_IMODE(os.stat(name).st_mode)
testcase.assertEqual(oct(managed_mode), oct(new_mode_1))
# Update the mode on the fileserver (pass 2)
# This assures us that if the file in file_roots was originally set
# to the same mode as new_mode_1, we definitely get an updated mode
# this time.
os.chmod(grail_fs_path, new_mode_2)
ret = testcase.run_state(
'file.managed',
name=name,
mode='keep',
source=grail,
)
testcase.assertSaltTrueReturn(ret)
managed_mode = stat.S_IMODE(os.stat(name).st_mode)
testcase.assertEqual(oct(managed_mode), oct(new_mode_2))
except Exception:
raise
finally:
# Set the mode of the file in the file_roots back to what it
# originally was.
os.chmod(grail_fs_path, grail_fs_mode)
class FileTest(ModuleCase, SaltReturnAssertsMixin):
'''
Validate the file state
'''
def tearDown(self):
'''
remove files created in previous tests
'''
user = 'salt'
if user in str(self.run_function('user.list_users', [user])):
self.run_function('user.delete', [user])
for path in (FILEPILLAR, FILEPILLARDEF, FILEPILLARGIT):
try:
os.remove(path)
except OSError as exc:
if exc.errno != os.errno.ENOENT:
log.error('Failed to remove %s: %s', path, exc)
def test_symlink(self):
'''
file.symlink
'''
name = os.path.join(TMP, 'symlink')
tgt = os.path.join(TMP, 'target')
# Windows must have a source directory to link to
if IS_WINDOWS and not os.path.isdir(tgt):
os.mkdir(tgt)
# Windows cannot create a symlink if it already exists
if IS_WINDOWS and self.run_function('file.is_link', [name]):
self.run_function('file.remove', [name])
ret = self.run_state('file.symlink', name=name, target=tgt)
self.assertSaltTrueReturn(ret)
def test_test_symlink(self):
'''
file.symlink test interface
'''
name = os.path.join(TMP, 'symlink2')
tgt = os.path.join(TMP, 'target')
ret = self.run_state('file.symlink', test=True, name=name, target=tgt)
self.assertSaltNoneReturn(ret)
def test_absent_file(self):
'''
file.absent
'''
name = os.path.join(TMP, 'file_to_kill')
with salt.utils.files.fopen(name, 'w+') as fp_:
fp_.write('killme')
ret = self.run_state('file.absent', name=name)
self.assertSaltTrueReturn(ret)
self.assertFalse(os.path.isfile(name))
def test_absent_dir(self):
'''
file.absent
'''
name = os.path.join(TMP, 'dir_to_kill')
if not os.path.isdir(name):
# left behind... Don't fail because of this!
os.makedirs(name)
ret = self.run_state('file.absent', name=name)
self.assertSaltTrueReturn(ret)
self.assertFalse(os.path.isdir(name))
def test_absent_link(self):
'''
file.absent
'''
name = os.path.join(TMP, 'link_to_kill')
tgt = '{0}.tgt'.format(name)
# Windows must have a source directory to link to
if IS_WINDOWS and not os.path.isdir(tgt):
os.mkdir(tgt)
if not self.run_function('file.is_link', [name]):
self.run_function('file.symlink', [tgt, name])
ret = self.run_state('file.absent', name=name)
try:
self.assertSaltTrueReturn(ret)
self.assertFalse(self.run_function('file.is_link', [name]))
finally:
if self.run_function('file.is_link', [name]):
self.run_function('file.remove', [name])
@with_tempfile()
def test_test_absent(self, name):
'''
file.absent test interface
'''
with salt.utils.files.fopen(name, 'w+') as fp_:
fp_.write('killme')
ret = self.run_state('file.absent', test=True, name=name)
self.assertSaltNoneReturn(ret)
self.assertTrue(os.path.isfile(name))
def test_managed(self):
'''
file.managed
'''
name = os.path.join(TMP, 'grail_scene33')
ret = self.run_state(
'file.managed', name=name, source='salt://grail/scene33'
)
src = os.path.join(BASE_FILES, 'grail', 'scene33')
with salt.utils.files.fopen(src, 'r') as fp_:
master_data = fp_.read()
with salt.utils.files.fopen(name, 'r') as fp_:
minion_data = fp_.read()
self.assertEqual(master_data, minion_data)
self.assertSaltTrueReturn(ret)
def test_managed_file_mode(self):
'''
file.managed, correct file permissions
'''
desired_mode = 504 # 0770 octal
name = os.path.join(TMP, 'grail_scene33')
ret = self.run_state(
'file.managed', name=name, mode='0770', source='salt://grail/scene33'
)
if IS_WINDOWS:
expected = 'The \'mode\' option is not supported on Windows'
self.assertEqual(ret[list(ret)[0]]['comment'], expected)
self.assertSaltFalseReturn(ret)
return
resulting_mode = stat.S_IMODE(
os.stat(name).st_mode
)
self.assertEqual(oct(desired_mode), oct(resulting_mode))
self.assertSaltTrueReturn(ret)
def test_managed_file_mode_keep(self):
'''
Test using "mode: keep" in a file.managed state
'''
_test_managed_file_mode_keep_helper(self, local=False)
def test_managed_file_mode_keep_local_source(self):
'''
Test using "mode: keep" in a file.managed state, with a local file path
as the source.
'''
_test_managed_file_mode_keep_helper(self, local=True)
def test_managed_file_mode_file_exists_replace(self):
'''
file.managed, existing file with replace=True, change permissions
'''
initial_mode = 504 # 0770 octal
desired_mode = 384 # 0600 octal
name = os.path.join(TMP, 'grail_scene33')
ret = self.run_state(
'file.managed', name=name, mode=oct(initial_mode), source='salt://grail/scene33'
)
if IS_WINDOWS:
expected = 'The \'mode\' option is not supported on Windows'
self.assertEqual(ret[list(ret)[0]]['comment'], expected)
self.assertSaltFalseReturn(ret)
return
resulting_mode = stat.S_IMODE(
os.stat(name).st_mode
)
self.assertEqual(oct(initial_mode), oct(resulting_mode))
name = os.path.join(TMP, 'grail_scene33')
ret = self.run_state(
'file.managed', name=name, replace=True, mode=oct(desired_mode), source='salt://grail/scene33'
)
resulting_mode = stat.S_IMODE(
os.stat(name).st_mode
)
self.assertEqual(oct(desired_mode), oct(resulting_mode))
self.assertSaltTrueReturn(ret)
def test_managed_file_mode_file_exists_noreplace(self):
'''
file.managed, existing file with replace=False, change permissions
'''
initial_mode = 504 # 0770 octal
desired_mode = 384 # 0600 octal
name = os.path.join(TMP, 'grail_scene33')
ret = self.run_state(
'file.managed', name=name, replace=True, mode=oct(initial_mode), source='salt://grail/scene33'
)
if IS_WINDOWS:
expected = 'The \'mode\' option is not supported on Windows'
self.assertEqual(ret[list(ret)[0]]['comment'], expected)
self.assertSaltFalseReturn(ret)
return
ret = self.run_state(
'file.managed', name=name, replace=False, mode=oct(desired_mode), source='salt://grail/scene33'
)
resulting_mode = stat.S_IMODE(
os.stat(name).st_mode
)
self.assertEqual(oct(desired_mode), oct(resulting_mode))
self.assertSaltTrueReturn(ret)
def test_managed_file_with_grains_data(self):
'''
Test to ensure we can render grains data into a managed
file.
'''
grain_path = os.path.join(TMP, 'file-grain-test')
self.run_function('grains.set', ['grain_path', grain_path])
state_file = 'file-grainget'
self.run_function('state.sls', [state_file])
self.assertTrue(os.path.exists(grain_path))
with salt.utils.files.fopen(grain_path, 'r') as fp_:
file_contents = fp_.readlines()
if salt.utils.platform.is_windows():
match = '^minion\r\n'
else:
match = '^minion\n'
self.assertTrue(re.match(match, file_contents[0]))
def test_managed_file_with_pillar_sls(self):
'''
Test to ensure pillar data in sls file
is rendered properly and file is created.
'''
state_name = 'file-pillarget'
ret = self.run_function('state.sls', [state_name])
self.assertSaltTrueReturn(ret)
# Check to make sure the file was created
check_file = self.run_function('file.file_exists', [FILEPILLAR])
self.assertTrue(check_file)
def test_managed_file_with_pillardefault_sls(self):
'''
Test to ensure when pillar data is not available
in sls file with pillar.get it uses the default
value.
'''
state_name = 'file-pillardefaultget'
ret = self.run_function('state.sls', [state_name])
self.assertSaltTrueReturn(ret)
# Check to make sure the file was created
check_file = self.run_function('file.file_exists', [FILEPILLARDEF])
self.assertTrue(check_file)
@skip_if_not_root
def test_managed_dir_mode(self):
'''
Tests to ensure that file.managed creates directories with the
permissions requested with the dir_mode argument
'''
desired_mode = 511 # 0777 in octal
name = os.path.join(TMP, 'a', 'managed_dir_mode_test_file')
desired_owner = 'nobody'
ret = self.run_state(
'file.managed',
name=name,
source='salt://grail/scene33',
mode=600,
makedirs=True,
user=desired_owner,
dir_mode=oct(desired_mode) # 0777
)
if IS_WINDOWS:
expected = 'The \'mode\' option is not supported on Windows'
self.assertEqual(ret[list(ret)[0]]['comment'], expected)
self.assertSaltFalseReturn(ret)
return
resulting_mode = stat.S_IMODE(
os.stat(os.path.join(TMP, 'a')).st_mode
)
resulting_owner = pwd.getpwuid(os.stat(os.path.join(TMP, 'a')).st_uid).pw_name
self.assertEqual(oct(desired_mode), oct(resulting_mode))
self.assertSaltTrueReturn(ret)
self.assertEqual(desired_owner, resulting_owner)
def test_test_managed(self):
'''
file.managed test interface
'''
name = os.path.join(TMP, 'grail_not_not_scene33')
ret = self.run_state(
'file.managed', test=True, name=name, source='salt://grail/scene33'
)
self.assertSaltNoneReturn(ret)
self.assertFalse(os.path.isfile(name))
def test_managed_show_changes_false(self):
'''
file.managed test interface
'''
name = os.path.join(TMP, 'grail_not_scene33')
with salt.utils.files.fopen(name, 'wb') as fp_:
fp_.write(b'test_managed_show_changes_false\n')
ret = self.run_state(
'file.managed', name=name, source='salt://grail/scene33',
show_changes=False
)
changes = next(six.itervalues(ret))['changes']
self.assertEqual('<show_changes=False>', changes['diff'])
@skipIf(IS_WINDOWS, 'Don\'t know how to fix for Windows')
def test_managed_escaped_file_path(self):
'''
file.managed test that 'salt://|' protects unusual characters in file path
'''
funny_file = salt.utils.files.mkstemp(prefix='?f!le? n@=3&', suffix='.file type')
funny_file_name = os.path.split(funny_file)[1]
funny_url = 'salt://|' + funny_file_name
funny_url_path = os.path.join(BASE_FILES, funny_file_name)
state_name = 'funny_file'
state_file_name = state_name + '.sls'
state_file = os.path.join(BASE_FILES, state_file_name)
state_key = 'file_|-{0}_|-{0}_|-managed'.format(funny_file)
self.addCleanup(os.remove, state_file)
self.addCleanup(os.remove, funny_file)
self.addCleanup(os.remove, funny_url_path)
with salt.utils.files.fopen(funny_url_path, 'w'):
pass
with salt.utils.files.fopen(state_file, 'w') as fp_:
fp_.write(textwrap.dedent('''\
{0}:
file.managed:
- source: {1}
- makedirs: True
'''.format(funny_file, funny_url)))
ret = self.run_function('state.sls', [state_name])
self.assertTrue(ret[state_key]['result'])
def test_managed_contents(self):
'''
test file.managed with contents that is a boolean, string, integer,
float, list, and dictionary
'''
state_name = 'file-FileTest-test_managed_contents'
state_filename = state_name + '.sls'
state_file = os.path.join(BASE_FILES, state_filename)
managed_files = {}
state_keys = {}
for typ in ('bool', 'str', 'int', 'float', 'list', 'dict'):
fd_, managed_files[typ] = tempfile.mkstemp()
# Release the handle so they can be removed in Windows
try:
os.close(fd_)
except OSError as exc:
if exc.errno != errno.EBADF:
raise exc
state_keys[typ] = 'file_|-{0} file_|-{1}_|-managed'.format(typ, managed_files[typ])
try:
with salt.utils.files.fopen(state_file, 'w') as fd_:
fd_.write(textwrap.dedent('''\
bool file:
file.managed:
- name: {bool}
- contents: True
str file:
file.managed:
- name: {str}
- contents: Salt was here.
int file:
file.managed:
- name: {int}
- contents: 340282366920938463463374607431768211456
float file:
file.managed:
- name: {float}
- contents: 1.7518e-45 # gravitational coupling constant
list file:
file.managed:
- name: {list}
- contents: [1, 1, 2, 3, 5, 8, 13]
dict file:
file.managed:
- name: {dict}
- contents:
C: charge
P: parity
T: time
'''.format(**managed_files)))
ret = self.run_function('state.sls', [state_name])
for typ in state_keys:
self.assertTrue(ret[state_keys[typ]]['result'])
self.assertIn('diff', ret[state_keys[typ]]['changes'])
finally:
os.remove(state_file)
for typ in managed_files:
os.remove(managed_files[typ])
@skip_if_not_root
@skipIf(IS_WINDOWS, 'Windows does not support "mode" kwarg. Skipping.')
@skipIf(not salt.utils.path.which('visudo'), 'sudo is missing')
def test_managed_check_cmd(self):
'''
Test file.managed passing a basic check_cmd kwarg. See Issue #38111.
'''
r_group = 'root'
if salt.utils.platform.is_darwin():
r_group = 'wheel'
try:
ret = self.run_state(
'file.managed',
name='/tmp/sudoers',
user='root',
group=r_group,
mode=440,
check_cmd='visudo -c -s -f'
)
self.assertSaltTrueReturn(ret)
self.assertInSaltComment('Empty file', ret)
self.assertEqual(ret['file_|-/tmp/sudoers_|-/tmp/sudoers_|-managed']['changes'],
{'new': 'file /tmp/sudoers created', 'mode': '0440'})
finally:
# Clean Up File
if os.path.exists('/tmp/sudoers'):
os.remove('/tmp/sudoers')
def test_managed_local_source_with_source_hash(self):
'''
Make sure that we enforce the source_hash even with local files
'''
name = os.path.join(TMP, 'local_source_with_source_hash')
local_path = os.path.join(BASE_FILES, 'grail', 'scene33')
actual_hash = '567fd840bf1548edc35c48eb66cdd78bfdfcccff'
if salt.utils.platform.is_windows():
# CRLF vs LF causes a differnt hash on windows
actual_hash = 'f658a0ec121d9c17088795afcc6ff3c43cb9842a'
# Reverse the actual hash
bad_hash = actual_hash[::-1]
def remove_file():
try:
os.remove(name)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
def do_test(clean=False):
for proto in ('file://', ''):
source = proto + local_path
log.debug('Trying source %s', source)
try:
ret = self.run_state(
'file.managed',
name=name,
source=source,
source_hash='sha1={0}'.format(bad_hash))
self.assertSaltFalseReturn(ret)
ret = ret[next(iter(ret))]
# Shouldn't be any changes
self.assertFalse(ret['changes'])
# Check that we identified a hash mismatch
self.assertIn(
'does not match actual checksum', ret['comment'])
ret = self.run_state(
'file.managed',
name=name,
source=source,
source_hash='sha1={0}'.format(actual_hash))
self.assertSaltTrueReturn(ret)
finally:
if clean:
remove_file()
remove_file()
log.debug('Trying with nonexistant destination file')
do_test()
log.debug('Trying with destination file already present')
with salt.utils.files.fopen(name, 'w'):
pass
try:
do_test(clean=False)
finally:
remove_file()
def test_managed_local_source_does_not_exist(self):
'''
Make sure that we exit gracefully when a local source doesn't exist
'''
name = os.path.join(TMP, 'local_source_does_not_exist')
local_path = os.path.join(BASE_FILES, 'grail', 'scene99')
for proto in ('file://', ''):
source = proto + local_path
log.debug('Trying source %s', source)
ret = self.run_state(
'file.managed',
name=name,
source=source)
self.assertSaltFalseReturn(ret)
ret = ret[next(iter(ret))]
# Shouldn't be any changes
self.assertFalse(ret['changes'])
# Check that we identified a hash mismatch
self.assertIn(
'does not exist', ret['comment'])
def test_managed_source_hash_indifferent_case(self):
'''
Test passing a source_hash as an uppercase hash.
This is a regression test for Issue #38914 and Issue #48230 (test=true use).
'''
name = os.path.join(TMP, 'source_hash_indifferent_case')
state_name = 'file_|-{0}_|' \
'-{0}_|-managed'.format(name)
local_path = os.path.join(BASE_FILES, 'hello_world.txt')
actual_hash = 'c98c24b677eff44860afea6f493bbaec5bb1c4cbb209c6fc2bbb47f66ff2ad31'
if salt.utils.platform.is_windows():
# CRLF vs LF causes a differnt hash on windows
actual_hash = '92b772380a3f8e27a93e57e6deeca6c01da07f5aadce78bb2fbb20de10a66925'
uppercase_hash = actual_hash.upper()
try:
# Lay down tmp file to test against
self.run_state(
'file.managed',
name=name,
source=local_path,
source_hash=actual_hash
)
# Test uppercase source_hash: should return True with no changes
ret = self.run_state(
'file.managed',
name=name,
source=local_path,
source_hash=uppercase_hash
)
assert ret[state_name]['result'] is True
assert ret[state_name]['pchanges'] == {}
assert ret[state_name]['changes'] == {}
# Test uppercase source_hash using test=true
# Should return True with no changes
ret = self.run_state(
'file.managed',
name=name,
source=local_path,
source_hash=uppercase_hash,
test=True
)
assert ret[state_name]['result'] is True
assert ret[state_name]['pchanges'] == {}
assert ret[state_name]['changes'] == {}
finally:
# Clean Up File
if os.path.exists(name):
os.remove(name)
@with_tempfile(create=False)
def test_managed_latin1_diff(self, name):
'''
Tests that latin-1 file contents are represented properly in the diff
'''
# Lay down the initial file
ret = self.run_state(
'file.managed',
name=name,
source='salt://issue-48777/old.html')
ret = ret[next(iter(ret))]
assert ret['result'] is True, ret
# Replace it with the new file and check the diff
ret = self.run_state(
'file.managed',
name=name,
source='salt://issue-48777/new.html')
ret = ret[next(iter(ret))]
assert ret['result'] is True, ret
diff_lines = ret['changes']['diff'].split('\n')
assert '+räksmörgås' in diff_lines, diff_lines
def test_directory(self):
'''
file.directory
'''
name = os.path.join(TMP, 'a_new_dir')
ret = self.run_state('file.directory', name=name)
self.assertSaltTrueReturn(ret)
self.assertTrue(os.path.isdir(name))
def test_directory_symlink_dry_run(self):
'''
Ensure that symlinks are followed when file.directory is run with
test=True
'''
try:
tmp_dir = os.path.join(TMP, 'pgdata')
sym_dir = os.path.join(TMP, 'pg_data')
if IS_WINDOWS:
self.run_function('file.mkdir', [tmp_dir, 'Administrators'])
else:
os.mkdir(tmp_dir, 0o700)
self.run_function('file.symlink', [tmp_dir, sym_dir])
if IS_WINDOWS:
ret = self.run_state(
'file.directory', test=True, name=sym_dir,
follow_symlinks=True, win_owner='Administrators')
else:
ret = self.run_state(
'file.directory', test=True, name=sym_dir,
follow_symlinks=True, mode=700)
self.assertSaltTrueReturn(ret)
finally:
if os.path.isdir(tmp_dir):
self.run_function('file.remove', [tmp_dir])
if os.path.islink(sym_dir):
self.run_function('file.remove', [sym_dir])
@skip_if_not_root
@skipIf(IS_WINDOWS, 'Mode not available in Windows')
def test_directory_max_depth(self):
'''
file.directory
Test the max_depth option by iteratively increasing the depth and
checking that no changes deeper than max_depth have been attempted
'''
def _get_oct_mode(name):
'''
Return a string octal representation of the permissions for name
'''
return salt.utils.files.normalize_mode(oct(os.stat(name).st_mode & 0o777))
top = os.path.join(TMP, 'top_dir')
sub = os.path.join(top, 'sub_dir')
subsub = os.path.join(sub, 'sub_sub_dir')
dirs = [top, sub, subsub]
initial_mode = '0111'
changed_mode = '0555'
if not os.path.isdir(subsub):
os.makedirs(subsub, int(initial_mode, 8))
try:
for depth in range(0, 3):
ret = self.run_state('file.directory',
name=top,
max_depth=depth,
dir_mode=changed_mode,
recurse=['mode'])
self.assertSaltTrueReturn(ret)
for changed_dir in dirs[0:depth+1]:
self.assertEqual(changed_mode,
_get_oct_mode(changed_dir))
for untouched_dir in dirs[depth+1:]:
self.assertEqual(initial_mode,
_get_oct_mode(untouched_dir))
finally:
shutil.rmtree(top)
def test_test_directory(self):
'''
file.directory
'''
name = os.path.join(TMP, 'a_not_dir')
ret = self.run_state('file.directory', test=True, name=name)
self.assertSaltNoneReturn(ret)
self.assertFalse(os.path.isdir(name))
@with_tempdir()
def test_directory_clean(self, base_dir):
'''
file.directory with clean=True
'''
name = os.path.join(base_dir, 'directory_clean_dir')
os.mkdir(name)
strayfile = os.path.join(name, 'strayfile')
with salt.utils.files.fopen(strayfile, 'w'):
pass
straydir = os.path.join(name, 'straydir')
if not os.path.isdir(straydir):
os.makedirs(straydir)
with salt.utils.files.fopen(os.path.join(straydir, 'strayfile2'), 'w'):
pass
ret = self.run_state('file.directory', name=name, clean=True)
self.assertSaltTrueReturn(ret)
self.assertFalse(os.path.exists(strayfile))
self.assertFalse(os.path.exists(straydir))
self.assertTrue(os.path.isdir(name))
@skipIf(salt.utils.platform.is_windows(), 'Skip on windows')
@with_tempdir()
def test_directory_clean_exclude(self, base_dir):
'''
file.directory with clean=True and exclude_pat set
Skipped on windows because clean and exclude_pat not supported by
salt.sates.file._check_directory_win
'''
name = os.path.join(base_dir, 'directory_clean_dir')
if not os.path.isdir(name):
os.makedirs(name)
strayfile = os.path.join(name, 'strayfile')
with salt.utils.files.fopen(strayfile, 'w'):
pass
straydir = os.path.join(name, 'straydir')
if not os.path.isdir(straydir):
os.makedirs(straydir)
strayfile2 = os.path.join(straydir, 'strayfile2')
with salt.utils.files.fopen(strayfile2, 'w'):
pass
keepfile = os.path.join(straydir, 'keepfile')
with salt.utils.files.fopen(keepfile, 'w'):
pass
exclude_pat = 'E@^straydir(|/keepfile)$'
if IS_WINDOWS:
exclude_pat = 'E@^straydir(|\\\\keepfile)$'
ret = self.run_state('file.directory',
name=name,
clean=True,
exclude_pat=exclude_pat)
self.assertSaltTrueReturn(ret)
self.assertFalse(os.path.exists(strayfile))
self.assertFalse(os.path.exists(strayfile2))
self.assertTrue(os.path.exists(keepfile))
@with_tempdir()
def test_test_directory_clean_exclude(self, base_dir):
'''
file.directory with test=True, clean=True and exclude_pat set
'''
name = os.path.join(base_dir, 'directory_clean_dir')
os.mkdir(name)
strayfile = os.path.join(name, 'strayfile')
with salt.utils.files.fopen(strayfile, 'w'):
pass
straydir = os.path.join(name, 'straydir')
if not os.path.isdir(straydir):
os.makedirs(straydir)
strayfile2 = os.path.join(straydir, 'strayfile2')
with salt.utils.files.fopen(strayfile2, 'w'):
pass
keepfile = os.path.join(straydir, 'keepfile')
with salt.utils.files.fopen(keepfile, 'w'):
pass
exclude_pat = 'E@^straydir(|/keepfile)$'
if IS_WINDOWS:
exclude_pat = 'E@^straydir(|\\\\keepfile)$'
ret = self.run_state('file.directory',
test=True,
name=name,
clean=True,
exclude_pat=exclude_pat)
comment = next(six.itervalues(ret))['comment']
self.assertSaltNoneReturn(ret)
self.assertTrue(os.path.exists(strayfile))
self.assertTrue(os.path.exists(strayfile2))
self.assertTrue(os.path.exists(keepfile))
self.assertIn(strayfile, comment)
self.assertIn(strayfile2, comment)
self.assertNotIn(keepfile, comment)
def test_directory_clean_require_in(self):
'''
file.directory test with clean=True and require_in file
'''
state_name = 'file-FileTest-test_directory_clean_require_in'
state_filename = state_name + '.sls'
state_file = os.path.join(BASE_FILES, state_filename)
directory = tempfile.mkdtemp()
self.addCleanup(lambda: shutil.rmtree(directory))
wrong_file = os.path.join(directory, "wrong")
with salt.utils.files.fopen(wrong_file, "w") as fp:
fp.write("foo")
good_file = os.path.join(directory, "bar")
with salt.utils.files.fopen(state_file, 'w') as fp:
self.addCleanup(lambda: os.remove(state_file))
fp.write(textwrap.dedent('''\
some_dir:
file.directory:
- name: {directory}
- clean: true
{good_file}:
file.managed:
- require_in:
- file: some_dir
'''.format(directory=directory, good_file=good_file)))
ret = self.run_function('state.sls', [state_name])
self.assertTrue(os.path.exists(good_file))
self.assertFalse(os.path.exists(wrong_file))
def test_directory_clean_require_in_with_id(self):
'''
file.directory test with clean=True and require_in file with an ID
different from the file name
'''
state_name = 'file-FileTest-test_directory_clean_require_in_with_id'
state_filename = state_name + '.sls'
state_file = os.path.join(BASE_FILES, state_filename)
directory = tempfile.mkdtemp()
self.addCleanup(lambda: shutil.rmtree(directory))
wrong_file = os.path.join(directory, "wrong")
with salt.utils.files.fopen(wrong_file, "w") as fp:
fp.write("foo")