Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_get_url_file(self):
'''
cp.get_url with file:// source given
'''
tgt = ''
src = os.path.join('file://', paths.FILES, 'file', 'base', 'file.big')
ret = self.run_function(
'cp.get_url',
[
src,
tgt,
])
with salt.utils.files.fopen(ret, 'r') as scene:
data = salt.utils.stringutils.to_unicode(scene.read())
self.assertIn('KNIGHT: They\'re nervous, sire.', data)
self.assertNotIn('bacon', data)
def test_obj_serialization(self):
'''
Test object serialization.
:return:
'''
obj = FoobarEntity()
obj.foo = 123
obj.bar = 'test entity'
obj.spam = 0.123
descr = OrderedDict([tuple(elm.split(':')) for elm in ["foo:int", "bar:str", "spam:float"]])
assert obj._serialize(descr) == [123, 'test entity', 0.123]
def prepare_ssh_access(options):
print_bulleted(options, 'Prepare SSH Access to Bootstrapped VM')
generate_ssh_keypair(options)
if options.test_interactive:
cloud_config = salt.config.cloud_config('/etc/salt/cloud') # TODO Is this always the case?
# Determine which provider we are using by looking it up in the profile
vm_provider = cloud_config['profiles'][options.vm_source]['provider'].split(':')[0]
# Finally, we can get the provider password
provider_password = cloud_config['providers']['linode']['linode']['password']
# Using the password, we can construct a data structure for a salt-ssh roster
roster_data = {options.vm_name: {
'host': get_minion_ip_address(options, sync=False),
'passwd': provider_password}}
# FIXME Perms!
if not os.path.exists('/tmp/.jenkins_ssh'):
os.mkdir('/tmp/.jenkins_ssh')
with open('/tmp/.jenkins_ssh/roster', 'w') as roster_fh:
yaml.dump(roster_data, stream=roster_fh)
wait=1,
tag='salt/beacon/minion/status',
match_type='startswith',
)
if sub_event is None:
sub_event = sub_master_listener.get_event(
full=True,
wait=1,
tag='salt/beacon/minion/status',
match_type='startswith',
)
if event and sub_event:
break
log.debug('Status events received: %s, %s', event, sub_event)
with salt.utils.files.fopen(file_path, 'w') as f:
pass
start = time.time()
# Now in successful case this test will get results at most in 2 loop intervals.
# Waiting for 2 loops intervals + some seconds to the hardware stupidity.
stop_at = start + self.mm_minion_opts['loop_interval'] * 2 + 60
event = sub_event = None
while True:
if time.time() > stop_at:
break
if not event:
event = master_listener.get_event(
full=True,
wait=1,
tag='salt/beacon/minion/inotify/' + self.tmpdir,
match_type='startswith',
self.run_function(
'git.push',
[self.admin_repo],
remote='origin',
ref=branch,
user=user,
)
with salt.utils.files.fopen(
os.path.join(self.admin_repo, 'top.sls'), 'w') as fp_:
fp_.write(textwrap.dedent('''\
base:
'*':
- foo
'''))
with salt.utils.files.fopen(
os.path.join(self.admin_repo, 'foo.sls'), 'w') as fp_:
fp_.write(textwrap.dedent('''\
branch: master
mylist:
- master
mydict:
master: True
nested_list:
- master
nested_dict:
master: True
'''))
# Add another file to be referenced using git_pillar_includes
with salt.utils.files.fopen(
os.path.join(self.admin_repo, 'bar.sls'), 'w') as fp_:
fp_.write('included_pillar: True\n')
def test_mac_group_add(self):
'''
Tests the add group function
'''
try:
self.run_function('group.add', [ADD_GROUP, 3456])
group_info = self.run_function('group.info', [ADD_GROUP])
self.assertEqual(group_info['name'], ADD_GROUP)
except CommandExecutionError:
self.run_function('group.delete', [ADD_GROUP])
raise
def setUpClass(cls):
if not os.path.isdir(RUNTIME_VARS.TMP):
os.makedirs(RUNTIME_VARS.TMP)
cls.root = os.path.join(RUNTIME_VARS.BASE_FILES, 'buildout')
cls.rdir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
cls.tdir = os.path.join(cls.rdir, 'test')
for idx, url in six.iteritems(buildout._URL_VERSIONS):
log.debug('Downloading bootstrap from %s', url)
dest = os.path.join(
cls.rdir, '{0}_bootstrap.py'.format(idx)
)
try:
download_to(url, dest)
except URLError:
log.debug('Failed to download %s', url)
# creating a new setuptools install
cls.ppy_st = os.path.join(cls.rdir, 'psetuptools')
if salt.utils.platform.is_windows():
cls.bin_st = os.path.join(cls.ppy_st, 'Scripts')
cls.py_st = os.path.join(cls.bin_st, 'python')
else:
cls.bin_st = os.path.join(cls.ppy_st, 'bin')
cls.py_st = os.path.join(cls.bin_st, 'python')
def test_present_when_domain_exists(self):
self.conn.describe_elasticsearch_domain.return_value = {'DomainStatus': domain_ret}
cfg = {}
for k, v in six.iteritems(domain_ret):
cfg[k] = {'Options': v}
cfg['AccessPolicies'] = {'Options': '{"a": "b"}'}
self.conn.describe_elasticsearch_domain_config.return_value = {'DomainConfig': cfg}
self.conn.update_elasticsearch_domain_config.return_value = {'DomainConfig': cfg}
result = self.salt_states['boto_elasticsearch_domain.present'](
'domain present',
**domain_ret)
self.assertTrue(result['result'])
self.assertEqual(result['changes'], {'new': {'AccessPolicies': {}}, 'old': {'AccessPolicies': {'a': 'b'}}})
def test_autosign_grains_accept(self):
grain_file_path = os.path.join(self.autosign_grains_dir, 'test_grain')
with salt.utils.files.fopen(grain_file_path, 'w') as f:
f.write(salt.utils.stringutils.to_str('#invalid_value\ncheese'))
os.chmod(grain_file_path, self.autosign_file_permissions)
self.run_call('test.ping -l quiet') # get minon to try to authenticate itself again
self.assertIn('minion', self.run_key('-l acc'))
'''
Test the (mis-)behaviour of file.replace as described in #18612:
Using 'prepend_if_not_found' or 'append_if_not_found' resulted in
an infinitely growing file as 'file.replace' didn't check beforehand
whether the changes had already been done to the file
# Case description:
The tested file contains one commented line
The commented line should be uncommented in the end, nothing else should change
'''
test_name = 'test_replace_issue_18612'
path_test = os.path.join(TMP, test_name)
with salt.utils.files.fopen(path_test, 'w+') as fp_test_:
fp_test_.write('# en_US.UTF-8')
ret = []
for x in range(0, 3):
ret.append(self.run_state('file.replace',
name=path_test, pattern='^# en_US.UTF-8$', repl='en_US.UTF-8', append_if_not_found=True))
try:
# ensure, the number of lines didn't change, even after invoking 'file.replace' 3 times
with salt.utils.files.fopen(path_test, 'r') as fp_test_:
self.assertTrue((sum(1 for _ in fp_test_) == 1))
# ensure, the replacement succeeded
with salt.utils.files.fopen(path_test, 'r') as fp_test_:
self.assertTrue(fp_test_.read().startswith('en_US.UTF-8'))