Merge pull request #24500 from msteed/py3-unittests-2

Continued unit test py3 compat
This commit is contained in:
Thomas S Hatch 2015-06-08 15:52:21 -06:00
commit 4c8e8a4ce9
11 changed files with 156 additions and 147 deletions

View File

@ -5,15 +5,15 @@ Module for fetching artifacts from Artifactory
# Import python libs
from __future__ import absolute_import
import urllib2
import os
import xml.etree.ElementTree as ET
from urllib2 import HTTPError
import logging
# Import Salt libs
import salt.utils
import salt.ext.six.moves.http_client # pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext.six.moves import urllib # pylint: disable=no-name-in-module
from salt.ext.six.moves.urllib.error import HTTPError, URLError # pylint: disable=no-name-in-module
log = logging.getLogger(__name__)
@ -219,7 +219,7 @@ def _get_artifact_metadata_url(artifactory_url, repository, group_id, artifact_i
def _get_artifact_metadata_xml(artifactory_url, repository, group_id, artifact_id):
artifact_metadata_url = _get_artifact_metadata_url(artifactory_url=artifactory_url, repository=repository, group_id=group_id, artifact_id=artifact_id)
try:
artifact_metadata_xml = urllib2.urlopen(artifact_metadata_url).read()
artifact_metadata_xml = urllib.request.urlopen(artifact_metadata_url).read()
except HTTPError as http_error:
message = 'Could not fetch data from url: {url}, HTTPError: {error}'
raise Exception(message.format(url=artifact_metadata_url, error=http_error))
@ -257,7 +257,7 @@ def _get_snapshot_version_metadata_url(artifactory_url, repository, group_id, ar
def _get_snapshot_version_metadata_xml(artifactory_url, repository, group_id, artifact_id, version):
snapshot_version_metadata_url = _get_snapshot_version_metadata_url(artifactory_url=artifactory_url, repository=repository, group_id=group_id, artifact_id=artifact_id, version=version)
try:
snapshot_version_metadata_xml = urllib2.urlopen(snapshot_version_metadata_url).read()
snapshot_version_metadata_xml = urllib.request.urlopen(snapshot_version_metadata_url).read()
except HTTPError as http_error:
message = 'Could not fetch data from url: {url}, HTTPError: {error}'
raise Exception(message.format(url=snapshot_version_metadata_url, error=http_error))
@ -320,14 +320,14 @@ def __save_artifact(artifact_url, target_file):
log.debug('Downloading: {url} -> {target_file}'.format(url=artifact_url, target_file=target_file))
try:
f = urllib2.urlopen(artifact_url)
f = urllib.request.urlopen(artifact_url)
with salt.utils.fopen(target_file, "wb") as local_file:
local_file.write(f.read())
result['status'] = True
result['comment'] = __append_comment(('Artifact downloaded from URL: {0}'.format(artifact_url)), result['comment'])
result['changes']['downloaded_file'] = target_file
result['target_file'] = target_file
except (HTTPError, urllib2.URLError) as e:
except (HTTPError, URLError) as e:
result['status'] = False
result['comment'] = __get_error_comment(e, artifact_url)
@ -351,7 +351,7 @@ def __download(request_url):
content = None
comment = None
try:
url = urllib2.urlopen(request_url)
url = urllib.request.urlopen(request_url)
content = url.read()
success = True
except HTTPError as e:

View File

@ -214,11 +214,11 @@ def _raise_error_routes(iface, option, expected):
def _read_file(path):
'''
Reads and returns the contents of a file
Reads and returns the contents of a text file
'''
try:
with salt.utils.flopen(path, 'rb') as contents:
return contents.readlines()
return [salt.utils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''

View File

@ -52,7 +52,7 @@ def __execute_cmd(command):
cmd = __salt__['cmd.run_all']('racadm {0}'.format(command))
if cmd['retcode'] != 0:
log.warn('racadm return an exit code \'{0}\'.'.format(cmd['retcode']))
log.warning('racadm return an exit code \'{0}\'.'.format(cmd['retcode']))
return False
return True
@ -71,7 +71,7 @@ def system_info():
cmd = __salt__['cmd.run_all']('racadm getsysinfo')
if cmd['retcode'] != 0:
log.warn('racadm return an exit code \'{0}\'.'.format(cmd['retcode']))
log.warning('racadm return an exit code \'{0}\'.'.format(cmd['retcode']))
return __parse_drac(cmd['stdout'])
@ -90,7 +90,7 @@ def network_info():
cmd = __salt__['cmd.run_all']('racadm getniccfg')
if cmd['retcode'] != 0:
log.warn('racadm return an exit code \'{0}\'.'.format(cmd['retcode']))
log.warning('racadm return an exit code \'{0}\'.'.format(cmd['retcode']))
return __parse_drac(cmd['stdout'])
@ -107,7 +107,7 @@ def nameservers(*ns):
salt dell drac.nameservers ns1.example.com ns2.example.com
'''
if len(ns) > 2:
log.warn('racadm only supports two nameservers')
log.warning('racadm only supports two nameservers')
return False
for i in range(1, len(ns) + 1):
@ -177,8 +177,7 @@ def list_users():
cfgUserAdmin -i {0}'.format(idx))
if cmd['retcode'] != 0:
log.warn('racadm return an exit \
code \'{0}\'.'.format(cmd['retcode']))
log.warning('racadm return an exit code \'{0}\'.'.format(cmd['retcode']))
for user in cmd['stdout'].splitlines():
if not user.startswith('cfg'):
@ -219,7 +218,7 @@ def delete_user(username, uid=None):
cfgUserAdminUserName -i {0} ""'.format(uid))
else:
log.warn('\'{0}\' does not exist'.format(username))
log.warning('\'{0}\' does not exist'.format(username))
return False
return True
@ -244,7 +243,7 @@ def change_password(username, password, uid=None):
return __execute_cmd('config -g cfgUserAdmin -o \
cfgUserAdminPassword -i {0} {1}'.format(uid, password))
else:
log.warn('\'{0}\' does not exist'.format(username))
log.warning('\'{0}\' does not exist'.format(username))
return False
return True
@ -278,7 +277,7 @@ def create_user(username, password, permissions, users=None):
users = list_users()
if username in users:
log.warn('\'{0}\' already exists'.format(username))
log.warning('\'{0}\' already exists'.format(username))
return False
for idx in six.iterkeys(users):
@ -294,13 +293,13 @@ def create_user(username, password, permissions, users=None):
# Configure users permissions
if not set_permissions(username, permissions, uid):
log.warn('unable to set user permissions')
log.warning('unable to set user permissions')
delete_user(username, uid)
return False
# Configure users password
if not change_password(username, password, uid):
log.warn('unable to set user password')
log.warning('unable to set user password')
delete_user(username, uid)
return False
@ -463,8 +462,8 @@ def server_pxe():
if __execute_cmd('config -g cfgServerInfo -o cfgServerBootOnce 1'):
return server_reboot
else:
log.warn('failed to set boot order')
log.warning('failed to set boot order')
return False
log.warn('failed to to configure PXE boot')
log.warning('failed to to configure PXE boot')
return False

View File

@ -1319,8 +1319,8 @@ def line(path, content, match=None, mode=None, location=None,
if before is None and after is None and not match:
match = content
body = salt.utils.fopen(path, mode='rb').read()
body_before = hashlib.sha256(body).hexdigest()
body = salt.utils.fopen(path, mode='r').read()
body_before = hashlib.sha256(salt.utils.to_bytes(body)).hexdigest()
after = _regex_to_static(body, after)
before = _regex_to_static(body, before)
match = _regex_to_static(body, match)
@ -1447,7 +1447,7 @@ def line(path, content, match=None, mode=None, location=None,
"Unable to ensure line without knowing "
"where to put it before and/or after.")
changed = body_before != hashlib.sha256(body).hexdigest()
changed = body_before != hashlib.sha256(salt.utils.to_bytes(body)).hexdigest()
if backup and changed:
try:
@ -1460,10 +1460,10 @@ def line(path, content, match=None, mode=None, location=None,
if changed:
if show_changes:
changes_diff = ''.join(difflib.unified_diff(salt.utils.fopen(path, 'rb').readlines(), body.splitlines()))
changes_diff = ''.join(difflib.unified_diff(salt.utils.fopen(path, 'r').readlines(), body.splitlines()))
fh_ = None
try:
fh_ = salt.utils.atomicfile.atomic_open(path, 'wb')
fh_ = salt.utils.atomicfile.atomic_open(path, 'w')
fh_.write(body)
finally:
if fh_:
@ -1656,7 +1656,7 @@ def replace(path,
try:
# Use a read-only handle to open the file
with salt.utils.fopen(path,
mode='rb',
mode='r',
buffering=bufsize) as r_file:
for line in r_file:
result, nrepl = re.subn(cpattern, repl, line, count)
@ -1700,12 +1700,12 @@ def replace(path,
try:
# Open the file in write mode
with salt.utils.fopen(path,
mode='wb',
mode='w',
buffering=bufsize) as w_file:
try:
# Open the temp file in read mode
with salt.utils.fopen(temp_file,
mode='rb',
mode='r',
buffering=bufsize) as r_file:
for line in r_file:
result, nrepl = re.subn(cpattern, repl,
@ -1746,7 +1746,7 @@ def replace(path,
raise CommandExecutionError("Exception: {0}".format(exc))
# write new content in the file while avoiding partial reads
try:
fh_ = salt.utils.atomicfile.atomic_open(path, 'wb')
fh_ = salt.utils.atomicfile.atomic_open(path, 'w')
for line in new_file:
fh_.write(line)
finally:
@ -1898,7 +1898,7 @@ def blockreplace(path,
try:
fi_file = fileinput.input(path,
inplace=False, backup=False,
bufsize=1, mode='rb')
bufsize=1, mode='r')
for line in fi_file:
result = line
@ -1984,7 +1984,7 @@ def blockreplace(path,
# write new content in the file while avoiding partial reads
try:
fh_ = salt.utils.atomicfile.atomic_open(path, 'wb')
fh_ = salt.utils.atomicfile.atomic_open(path, 'w')
for line in new_file:
fh_.write(line)
finally:
@ -2250,23 +2250,25 @@ def append(path, *args, **kwargs):
else:
args = [kwargs['args']]
with salt.utils.fopen(path, "r+") as ofile:
# Make sure we have a newline at the end of the file
# Make sure we have a newline at the end of the file. Do this in binary
# mode so SEEK_END with nonzero offset will work.
with salt.utils.fopen(path, 'rb+') as ofile:
linesep = salt.utils.to_bytes(os.linesep)
try:
ofile.seek(-1, os.SEEK_END)
ofile.seek(-len(linesep), os.SEEK_END)
except IOError as exc:
if exc.errno == errno.EINVAL or exc.errno == errno.ESPIPE:
if exc.errno in (errno.EINVAL, errno.ESPIPE):
# Empty file, simply append lines at the beginning of the file
pass
else:
raise
else:
if ofile.read(1) != '\n':
if ofile.read(len(linesep)) != linesep:
ofile.seek(0, os.SEEK_END)
ofile.write('\n')
else:
ofile.seek(0, os.SEEK_END)
# Append lines
ofile.write(linesep)
# Append lines in text mode
with salt.utils.fopen(path, 'r+') as ofile:
ofile.seek(0, os.SEEK_END)
for line in args:
ofile.write('{0}\n'.format(line))
@ -2507,7 +2509,7 @@ def truncate(path, length):
salt '*' file.truncate /path/to/file 512
'''
path = os.path.expanduser(path)
with salt.utils.fopen(path, 'r+') as seek_fh:
with salt.utils.fopen(path, 'rb+') as seek_fh:
seek_fh.truncate(int(length))
@ -3566,8 +3568,8 @@ def check_file_meta(
changes['diff'] = bdiff
else:
with contextlib.nested(
salt.utils.fopen(sfn, 'rb'),
salt.utils.fopen(name, 'rb')) as (src, name_):
salt.utils.fopen(sfn, 'r'),
salt.utils.fopen(name, 'r')) as (src, name_):
slines = src.readlines()
nlines = name_.readlines()
changes['diff'] = \
@ -3582,8 +3584,8 @@ def check_file_meta(
tmp_.write(str(contents))
# Compare the static contents with the named file
with contextlib.nested(
salt.utils.fopen(tmp, 'rb'),
salt.utils.fopen(name, 'rb')) as (src, name_):
salt.utils.fopen(tmp, 'r'),
salt.utils.fopen(name, 'r')) as (src, name_):
slines = src.readlines()
nlines = name_.readlines()
if ''.join(nlines) != ''.join(slines):
@ -3783,8 +3785,8 @@ def manage_file(name,
ret['changes']['diff'] = bdiff
else:
with contextlib.nested(
salt.utils.fopen(sfn, 'rb'),
salt.utils.fopen(real_name, 'rb')) as (src, name_):
salt.utils.fopen(sfn, 'r'),
salt.utils.fopen(real_name, 'r')) as (src, name_):
slines = src.readlines()
nlines = name_.readlines()
@ -3811,8 +3813,8 @@ def manage_file(name,
# Compare contents of files to know if we need to replace
with contextlib.nested(
salt.utils.fopen(tmp, 'rb'),
salt.utils.fopen(real_name, 'rb')) as (src, name_):
salt.utils.fopen(tmp, 'r'),
salt.utils.fopen(real_name, 'r')) as (src, name_):
slines = src.readlines()
nlines = name_.readlines()
different = ''.join(slines) != ''.join(nlines)

View File

@ -161,8 +161,7 @@ def apply_(path, id_=None, config=None, approve_key=True, install=True,
.format(salt.syspaths.BOOTSTRAP))
res = False
else:
log.warn('No useful action performed on '
'{0}'.format(mpt))
log.warning('No useful action performed on {0}'.format(mpt))
res = False
_umount(mpt, ftype)

View File

@ -6,6 +6,9 @@ Create and verify ANSI X9.31 RSA signatures using OpenSSL libcrypto
# python libs
from __future__ import absolute_import
# salt libs
import salt.utils
# 3rd-party libs
from ctypes import cdll, c_char_p, c_int, c_void_p, pointer, create_string_buffer
from ctypes.util import find_library
@ -67,6 +70,7 @@ class RSAX931Signer(object):
:param str keydata: The RSA private key in PEM format
'''
keydata = salt.utils.to_bytes(keydata, 'ascii')
self._bio = libcrypto.BIO_new_mem_buf(keydata, len(keydata))
self._rsa = c_void_p(libcrypto.RSA_new())
if not libcrypto.PEM_read_bio_RSAPrivateKey(self._bio, pointer(self._rsa), None, None):
@ -86,6 +90,7 @@ class RSAX931Signer(object):
'''
# Allocate a buffer large enough for the signature. Freed by ctypes.
buf = create_string_buffer(libcrypto.RSA_size(self._rsa))
msg = salt.utils.to_bytes(msg)
size = libcrypto.RSA_private_encrypt(len(msg), msg, buf, self._rsa, RSA_X931_PADDING)
if size < 0:
raise ValueError('Unable to encrypt message')
@ -102,6 +107,7 @@ class RSAX931Verifier(object):
:param str pubdata: The RSA public key in PEM format
'''
pubdata = salt.utils.to_bytes(pubdata, 'ascii')
self._bio = libcrypto.BIO_new_mem_buf(pubdata, len(pubdata))
self._rsa = c_void_p(libcrypto.RSA_new())
if not libcrypto.PEM_read_bio_RSA_PUBKEY(self._bio, pointer(self._rsa), None, None):
@ -122,6 +128,7 @@ class RSAX931Verifier(object):
'''
# Allocate a buffer large enough for the signature. Freed by ctypes.
buf = create_string_buffer(libcrypto.RSA_size(self._rsa))
signed = salt.utils.to_bytes(signed)
size = libcrypto.RSA_public_decrypt(len(signed), signed, buf, self._rsa, RSA_X931_PADDING)
if size < 0:
raise ValueError('Unable to decrypt message')

View File

@ -249,8 +249,10 @@ class BtrfsTestCase(TestCase):
with patch.dict(btrfs.__salt__, {'cmd.run_all': mock}):
mock = MagicMock(return_value={'/dev/sda3': {'type': 'ext4'}})
with patch.object(salt.utils.fsutils, '_blkid_output', mock):
self.assertDictEqual(btrfs.convert('/dev/sda3', permanent=True),
ret)
mock = MagicMock(return_value={'/dev/sda3': [{'mount_point': None}]})
with patch.object(salt.utils.fsutils, '_get_mounts', mock):
self.assertDictEqual(btrfs.convert('/dev/sda3', permanent=True),
ret)
def test_convert_device_error(self):
'''

View File

@ -92,7 +92,7 @@ class DebApacheTestCase(TestCase):
'''
mock = MagicMock(side_effect=Exception('error'))
with patch.dict(deb_apache.__salt__, {'cmd.retcode': mock}):
self.assertEqual(deb_apache.a2ensite('saltstack.com').message,
self.assertEqual(str(deb_apache.a2ensite('saltstack.com')),
'error')
# 'a2dissite' function tests: 4
@ -136,7 +136,7 @@ class DebApacheTestCase(TestCase):
'''
mock = MagicMock(side_effect=Exception('error'))
with patch.dict(deb_apache.__salt__, {'cmd.retcode': mock}):
self.assertEqual(deb_apache.a2dissite('saltstack.com').message,
self.assertEqual(str(deb_apache.a2dissite('saltstack.com')),
'error')
# 'check_mod_enabled' function tests: 3
@ -203,7 +203,7 @@ class DebApacheTestCase(TestCase):
'''
mock = MagicMock(side_effect=Exception('error'))
with patch.dict(deb_apache.__salt__, {'cmd.retcode': mock}):
self.assertEqual(deb_apache.a2enmod('vhost_alias').message,
self.assertEqual(str(deb_apache.a2enmod('vhost_alias')),
'error')
# 'a2dismod' function tests: 4
@ -247,7 +247,7 @@ class DebApacheTestCase(TestCase):
'''
mock = MagicMock(side_effect=Exception('error'))
with patch.dict(deb_apache.__salt__, {'cmd.retcode': mock}):
self.assertEqual(deb_apache.a2dismod('vhost_alias').message,
self.assertEqual(str(deb_apache.a2dismod('vhost_alias')),
'error')

View File

@ -53,7 +53,7 @@ class FileReplaceTestCase(TestCase):
''')
def setUp(self):
self.tfile = tempfile.NamedTemporaryFile(delete=False)
self.tfile = tempfile.NamedTemporaryFile(delete=False, mode='w+')
self.tfile.write(self.MULTILINE_STRING)
self.tfile.close()
@ -63,7 +63,7 @@ class FileReplaceTestCase(TestCase):
def test_replace(self):
filemod.replace(self.tfile.name, r'Etiam', 'Salticus', backup=False)
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
self.assertIn('Salticus', fp.read())
def test_replace_append_if_not_found(self):
@ -78,26 +78,26 @@ class FileReplaceTestCase(TestCase):
base = 'foo=1\nbar=2'
expected = '{base}\n{repl}\n'.format(base=base, **args)
# File ending with a newline, no match
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
tfile.write(base + '\n')
tfile.flush()
filemod.replace(tfile.name, **args)
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), expected)
# File not ending with a newline, no match
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile('w+') as tfile:
tfile.write(base)
tfile.flush()
filemod.replace(tfile.name, **args)
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), expected)
# A newline should not be added in empty files
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile('w+') as tfile:
filemod.replace(tfile.name, **args)
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), args['repl'] + '\n')
# Using not_found_content, rather than repl
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile('w+') as tfile:
args['not_found_content'] = 'baz=3'
expected = '{base}\n{not_found_content}\n'.format(base=base, **args)
tfile.write(base)
@ -106,7 +106,7 @@ class FileReplaceTestCase(TestCase):
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), expected)
# not appending if matches
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile('w+') as tfile:
base = 'foo=1\n#baz=42\nbar=2\n'
expected = 'foo=1\nbaz=42\nbar=2\n'
tfile.write(base)
@ -203,7 +203,8 @@ class FileBlockReplaceTestCase(TestCase):
def setUp(self):
self.tfile = tempfile.NamedTemporaryFile(delete=False,
prefix='blockrepltmp')
prefix='blockrepltmp',
mode='w+')
self.tfile.write(self.MULTILINE_STRING)
self.tfile.close()
manage_mode_mock = MagicMock()
@ -224,7 +225,7 @@ class FileBlockReplaceTestCase(TestCase):
new_multiline_content,
backup=False)
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
filecontent = fp.read()
self.assertIn('#-- START BLOCK 1'
+ "\n" + new_multiline_content
@ -246,7 +247,7 @@ class FileBlockReplaceTestCase(TestCase):
append_if_not_found=False,
backup=False
)
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
self.assertNotIn('#-- START BLOCK 2'
+ "\n" + new_content + "\n"
+ '#-- END BLOCK 2', fp.read())
@ -258,7 +259,7 @@ class FileBlockReplaceTestCase(TestCase):
backup=False,
append_if_not_found=True)
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
self.assertIn('#-- START BLOCK 2'
+ "\n" + new_content
+ "\n" + '#-- END BLOCK 2', fp.read())
@ -278,21 +279,21 @@ class FileBlockReplaceTestCase(TestCase):
block = '{marker_start}\n{content}\n{marker_end}\n'.format(**args)
expected = base + '\n' + block
# File ending with a newline
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
tfile.write(base + '\n')
tfile.flush()
filemod.blockreplace(tfile.name, **args)
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), expected)
# File not ending with a newline
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
tfile.write(base)
tfile.flush()
filemod.blockreplace(tfile.name, **args)
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), expected)
# A newline should not be added in empty files
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
filemod.blockreplace(tfile.name, **args)
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), block)
@ -310,7 +311,7 @@ class FileBlockReplaceTestCase(TestCase):
prepend_if_not_found=False,
backup=False
)
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
self.assertNotIn(
'#-- START BLOCK 2' + "\n"
+ new_content + "\n" + '#-- END BLOCK 2',
@ -322,7 +323,7 @@ class FileBlockReplaceTestCase(TestCase):
backup=False,
prepend_if_not_found=True)
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
self.assertTrue(
fp.read().startswith(
'#-- START BLOCK 2'
@ -336,7 +337,7 @@ class FileBlockReplaceTestCase(TestCase):
'new content 1',
backup=False)
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
filecontent = fp.read()
self.assertIn('new content 1', filecontent)
self.assertNotIn('to be removed', filecontent)
@ -426,7 +427,7 @@ class FileBlockReplaceTestCase(TestCase):
class FileModuleTestCase(TestCase):
def test_sed_limit_escaped(self):
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
tfile.write(SED_CONTENT)
tfile.seek(0, 0)
@ -437,7 +438,7 @@ class FileModuleTestCase(TestCase):
filemod.sed(path, before, after, limit=limit)
with salt.utils.fopen(path, 'rb') as newfile:
with salt.utils.fopen(path, 'r') as newfile:
self.assertEqual(
SED_CONTENT.replace(before, ''),
newfile.read()
@ -449,21 +450,21 @@ class FileModuleTestCase(TestCase):
newlines at end of file.
'''
# File ending with a newline
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
tfile.write('foo\n')
tfile.flush()
filemod.append(tfile.name, 'bar')
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), 'foo\nbar\n')
# File not ending with a newline
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
tfile.write('foo')
tfile.flush()
filemod.append(tfile.name, 'bar')
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), 'foo\nbar\n')
# A newline should not be added in empty files
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
filemod.append(tfile.name, 'bar')
with salt.utils.fopen(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), 'bar\n')
@ -473,7 +474,7 @@ class FileModuleTestCase(TestCase):
Check various hash file formats.
'''
# With file name
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
tfile.write('rc.conf ef6e82e4006dee563d98ada2a2a80a27\n')
tfile.write(
'ead48423703509d37c4a90e6a0d53e143b6fc268 example.tar.gz\n')
@ -490,7 +491,7 @@ class FileModuleTestCase(TestCase):
'hash_type': 'sha1'
})
# Solohash - no file name (Maven repo checksum file format)
with tempfile.NamedTemporaryFile() as tfile:
with tempfile.NamedTemporaryFile(mode='w+') as tfile:
tfile.write('ead48423703509d37c4a90e6a0d53e143b6fc268\n')
tfile.flush()
result = filemod.extract_hash(tfile.name, '', '/testfile')

View File

@ -48,7 +48,7 @@ empty_option=
maxDiff = None
def setUp(self):
self.tfile = tempfile.NamedTemporaryFile(delete=False)
self.tfile = tempfile.NamedTemporaryFile(delete=False, mode='w+')
self.tfile.write(self.TEST_FILE_CONTENT)
self.tfile.close()
@ -122,7 +122,7 @@ empty_option=
ini.set_option(self.tfile.name, {
'SectionB': {'test3': 'new value 3B'},
})
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
file_content = fp.read()
self.assertIn('\nempty_option=\n', file_content,
'empty_option was not preserved')
@ -131,7 +131,7 @@ empty_option=
ini.set_option(self.tfile.name, {
'SectionB': {'test3': 'new value 3B'},
})
with salt.utils.fopen(self.tfile.name, 'rb') as fp:
with salt.utils.fopen(self.tfile.name, 'r') as fp:
file_content = fp.read()
self.assertEqual('''\
# Comment on the first line

View File

@ -5,7 +5,6 @@ Test the RSA ANSI X9.31 signer and verifier
# python libs
from __future__ import absolute_import
import textwrap
# salt testing libs
from salttesting import TestCase
@ -19,68 +18,68 @@ from salt.utils.rsax931 import RSAX931Signer, RSAX931Verifier
class RSAX931Test(TestCase):
privkey_data = textwrap.dedent('''\
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA75GR6ZTv5JOv90Vq8tKhKC7YQnhDIo2hM0HVziTEk5R4UQBW
a0CKytFMbTONY2msEDwX9iA0x7F5Lgj0X8eD4ZMsYqLzqjWMekLC8bjhxc+EuPo9
Dygu3mJ2VgRC7XhlFpmdo5NN8J2E7B/CNB3R4hOcMMZNZdi0xLtFoTfwU61UPfFX
14mV2laqLbvDEfQLJhUTDeFFV8EN5Z4H1ttLP3sMXJvc3EvM0JiDVj4l1TWFUHHz
eFgCA1Im0lv8i7PFrg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BLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA75GR6ZTv5JOv90Vq8tKh
KC7YQnhDIo2hM0HVziTEk5R4UQBWa0CKytFMbTONY2msEDwX9iA0x7F5Lgj0X8eD
4ZMsYqLzqjWMekLC8bjhxc+EuPo9Dygu3mJ2VgRC7XhlFpmdo5NN8J2E7B/CNB3R
4hOcMMZNZdi0xLtFoTfwU61UPfFX14mV2laqLbvDEfQLJhUTDeFFV8EN5Z4H1ttL
P3sMXJvc3EvM0JiDVj4l1TWFUHHzeFgCA1Im0lv8i7PFrgW7nyMfK9uDSsUmIp7k
6ai4tVzwkTmV5PsriP1ju88Lo3MB4/sUmDv/JmlZ9YyzTO3Po8Uz3Aeq9HJWyBWH
AQIDAQAB
-----END PUBLIC KEY-----''')
pubkey_data = (
'-----BEGIN PUBLIC KEY-----\n'
'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA75GR6ZTv5JOv90Vq8tKh\n'
'KC7YQnhDIo2hM0HVziTEk5R4UQBWa0CKytFMbTONY2msEDwX9iA0x7F5Lgj0X8eD\n'
'4ZMsYqLzqjWMekLC8bjhxc+EuPo9Dygu3mJ2VgRC7XhlFpmdo5NN8J2E7B/CNB3R\n'
'4hOcMMZNZdi0xLtFoTfwU61UPfFX14mV2laqLbvDEfQLJhUTDeFFV8EN5Z4H1ttL\n'
'P3sMXJvc3EvM0JiDVj4l1TWFUHHzeFgCA1Im0lv8i7PFrgW7nyMfK9uDSsUmIp7k\n'
'6ai4tVzwkTmV5PsriP1ju88Lo3MB4/sUmDv/JmlZ9YyzTO3Po8Uz3Aeq9HJWyBWH\n'
'AQIDAQAB\n'
'-----END PUBLIC KEY-----')
hello_world = 'hello, world'
hello_world = b'hello, world'
hello_world_sig = \
'\x63\xa0\x70\xd2\xe4\xd4\x6b\x8a\xa2\x59\x27\x5f\x00\x69' \
'\x1e\x3c\x50\xed\x50\x13\x09\x80\xe3\x47\x4e\x14\xb5\x7c' \
'\x07\x26\x4e\x20\x74\xea\x0e\xf8\xda\xff\x1e\x57\x8c\x67' \
'\x76\x73\xaa\xea\x0f\x0a\xe7\xa2\xe3\x88\xfc\x09\x87\x36' \
'\x01\x3a\xb7\x4c\x40\xe0\xf4\x54\xc5\xf1\xaa\xb2\x1d\x7f' \
'\xb6\xd3\xa8\xdd\x28\x69\x8b\x88\xe4\x42\x1e\x48\x3e\x1f' \
'\xe2\x2b\x3c\x7c\x85\x11\xe9\x59\xd7\xf3\xc2\x21\xd3\x55' \
'\xcb\x9c\x3c\x93\xcc\x20\xdf\x64\x81\xd0\x0d\xbf\x8e\x8d' \
'\x47\xec\x1d\x9e\x27\xec\x12\xed\x8b\x5f\xd6\x1d\xec\x8d' \
'\x77\x5a\x58\x8a\x24\xb6\x0f\x12\xb7\x51\xef\x7d\x85\x0f' \
'\x49\x39\x02\x81\x15\x08\x70\xd6\xe0\x0b\x31\xff\x5f\xf9' \
'\xd1\x92\x38\x59\x8c\x22\x9c\xbb\xbf\xcf\x85\x34\xe2\x47' \
'\xf5\xe2\xaa\xb4\x62\x33\x3c\x13\x78\x33\x87\x08\x9e\xb5' \
'\xbc\x5d\xc1\xbf\x79\x7c\xfa\x5f\x06\x6a\x3b\x17\x40\x09' \
'\xb9\x09\xbf\x32\xc3\x00\xe2\xbc\x91\x77\x14\xa5\x23\xf5' \
'\xf5\xf1\x09\x12\x38\xda\x3b\x6a\x82\x81\x7b\x5e\x1c\xcb' \
'\xaa\x36\x9b\x08\x36\x03\x14\x96\xa3\x31\x39\x59\x16\x75' \
'\xc9\xb6\x66\x94\x1b\x97\xff\xc8\xa1\xe3\x21\x35\x23\x06' \
'\x4c\x9b\xf4\xee'
hello_world_sig = (
b'\x63\xa0\x70\xd2\xe4\xd4\x6b\x8a\xa2\x59\x27\x5f\x00\x69'
b'\x1e\x3c\x50\xed\x50\x13\x09\x80\xe3\x47\x4e\x14\xb5\x7c'
b'\x07\x26\x4e\x20\x74\xea\x0e\xf8\xda\xff\x1e\x57\x8c\x67'
b'\x76\x73\xaa\xea\x0f\x0a\xe7\xa2\xe3\x88\xfc\x09\x87\x36'
b'\x01\x3a\xb7\x4c\x40\xe0\xf4\x54\xc5\xf1\xaa\xb2\x1d\x7f'
b'\xb6\xd3\xa8\xdd\x28\x69\x8b\x88\xe4\x42\x1e\x48\x3e\x1f'
b'\xe2\x2b\x3c\x7c\x85\x11\xe9\x59\xd7\xf3\xc2\x21\xd3\x55'
b'\xcb\x9c\x3c\x93\xcc\x20\xdf\x64\x81\xd0\x0d\xbf\x8e\x8d'
b'\x47\xec\x1d\x9e\x27\xec\x12\xed\x8b\x5f\xd6\x1d\xec\x8d'
b'\x77\x5a\x58\x8a\x24\xb6\x0f\x12\xb7\x51\xef\x7d\x85\x0f'
b'\x49\x39\x02\x81\x15\x08\x70\xd6\xe0\x0b\x31\xff\x5f\xf9'
b'\xd1\x92\x38\x59\x8c\x22\x9c\xbb\xbf\xcf\x85\x34\xe2\x47'
b'\xf5\xe2\xaa\xb4\x62\x33\x3c\x13\x78\x33\x87\x08\x9e\xb5'
b'\xbc\x5d\xc1\xbf\x79\x7c\xfa\x5f\x06\x6a\x3b\x17\x40\x09'
b'\xb9\x09\xbf\x32\xc3\x00\xe2\xbc\x91\x77\x14\xa5\x23\xf5'
b'\xf5\xf1\x09\x12\x38\xda\x3b\x6a\x82\x81\x7b\x5e\x1c\xcb'
b'\xaa\x36\x9b\x08\x36\x03\x14\x96\xa3\x31\x39\x59\x16\x75'
b'\xc9\xb6\x66\x94\x1b\x97\xff\xc8\xa1\xe3\x21\x35\x23\x06'
b'\x4c\x9b\xf4\xee')
def test_signer(self):
with self.assertRaises(ValueError):
@ -105,7 +104,7 @@ class RSAX931Test(TestCase):
with self.assertRaises(ValueError):
verifier.verify('')
with self.assertRaises(ValueError):
verifier.verify(RSAX931Test.hello_world_sig + 'junk')
verifier.verify(RSAX931Test.hello_world_sig + b'junk')
msg = verifier.verify(RSAX931Test.hello_world_sig)
self.assertEqual(RSAX931Test.hello_world, msg)