Merge pull request #9005 from makinacorpus/lint-fixes

Lint fixes
This commit is contained in:
Joseph Hall 2013-12-03 17:08:15 -08:00
commit 29b76829af
16 changed files with 148 additions and 68 deletions

View File

@ -6,21 +6,21 @@
# If not otherwise noted, the extensions in this package are licensed
# under the following license.
#
#
# Copyright (c) 2009 by the contributors (see AUTHORS file).
# All rights reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
@ -42,6 +42,7 @@ from sphinx.util.compat import Directive
CONTROL_HEIGHT = 30
def get_size(d, key):
if key not in d:
return None
@ -50,10 +51,14 @@ def get_size(d, key):
raise ValueError("invalid size %r" % d[key])
return int(m.group(1)), m.group(2) or "px"
def css(d):
return "; ".join(sorted("%s: %s" % kv for kv in d.iteritems()))
class youtube(nodes.General, nodes.Element): pass
class youtube(nodes.General, nodes.Element):
pass
def visit_youtube_node(self, node):
aspect = node["aspect"]
@ -105,9 +110,11 @@ def visit_youtube_node(self, node):
self.body.append(self.starttag(node, "iframe", **attrs))
self.body.append("</iframe>")
def depart_youtube_node(self, node):
pass
class YouTube(Directive):
has_content = True
required_arguments = 1
@ -132,6 +139,7 @@ class YouTube(Directive):
height = get_size(self.options, "height")
return [youtube(id=self.arguments[0], aspect=aspect, width=width, height=height)]
def setup(app):
app.add_node(youtube, html=(visit_youtube_node, depart_youtube_node))
app.add_directive("youtube", YouTube)

View File

@ -88,8 +88,8 @@ except NameError:
docs_basepath = os.path.abspath(os.path.dirname('.'))
addtl_paths = (
os.pardir, # salt itself (for autodoc)
'_ext', # custom Sphinx extensions
os.pardir, # salt itself (for autodoc)
'_ext', # custom Sphinx extensions
)
for path in addtl_paths:

View File

@ -9,7 +9,7 @@ from shutil import copy
from subprocess import check_call
parser = argparse.ArgumentParser(
description = 'Build salt rpms',
description='Build salt rpms',
)
parser.add_argument('buildid',
help='The build id to use i.e. the bit after the salt version in the package name',
@ -38,8 +38,8 @@ def srcfilter(ti):
return ti
with tarfile.open(join(rpmbuild, 'SOURCES/salt-%s.tar.gz' % salt_version), 'w|gz') as tf:
tf.add(src, arcname = 'salt-%s' % salt_version,
filter = srcfilter)
tf.add(src, arcname='salt-%s' % salt_version,
filter=srcfilter)
cmd = ['rpmbuild', '-bb',
@ -47,4 +47,4 @@ cmd = ['rpmbuild', '-bb',
'--define=buildid %s' % args.buildid,
'salt.spec']
print('Executing: %s' % ' '.join('"%s"' % c for c in cmd))
check_call(cmd, cwd = join(rpmbuild, 'SPECS'))
check_call(cmd, cwd=join(rpmbuild, 'SPECS'))

View File

@ -285,12 +285,12 @@ class SaltCall(parsers.SaltCallOptionParser):
if self.options.file_root:
# check if the argument is pointing to a file on disk
file_root = os.path.abspath(self.options.file_root)
self.config['file_roots'] = {'base': [file_root]}
self.config['file_roots'] = {'base': [file_root]}
if self.options.pillar_root:
# check if the argument is pointing to a file on disk
pillar_root = os.path.abspath(self.options.pillar_root)
self.config['pillar_roots'] = {'base': [pillar_root]}
self.config['pillar_roots'] = {'base': [pillar_root]}
if self.options.local:
self.config['file_client'] = 'local'

View File

@ -1146,7 +1146,7 @@ def login(url=None, username=None, password=None, email=None, *args, **kwargs):
salt '*' docker.login <container id>
'''
client = _get_client()
return client.login(url, username=username, password=password, email=email)
return client.login(url, username, password, email)
def search(term, *args, **kwargs):
@ -1725,7 +1725,7 @@ def push(repo, *args, **kwargs):
return status
def _run_wrapper(status, container, func, cmd, *args, **kwargs):
def _run_wrapper(status, container, func, cmd, *args, **kwargs):
'''
Wrapper to a cmdmod function

View File

@ -165,7 +165,7 @@ def traceroute(host):
'ip': traceline[2],
}
for x in range(0, len(delays)):
result['ms{0}'.format(x+1)] = delays[x]
result['ms{0}'.format(x + 1)] = delays[x]
except IndexError:
result = {}

View File

@ -178,7 +178,7 @@ def _set_status(m,
outlog_by_level += hr
for level, msg in m['logs']:
outlog += '\n{0}: {1}\n'.format(level.upper(), msg)
for logger in 'error', 'warn', 'info', 'debug':
for logger in 'error', 'warn', 'info', 'debug':
logs = m['logs_by_level'].get(logger, [])
if logs:
outlog_by_level += '\n{0}:\n'.format(logger.upper())
@ -860,6 +860,7 @@ def buildout(directory=".",
debug=debug)
# signal the decorator or our return
raise ResultTransmission(_merge_statuses([boot_ret, buildout_ret]))
return True # make pylint happy
def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()):
@ -874,7 +875,7 @@ def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()):
_valid(status, 'onlyif execution failed')
elif isinstance(onlyif, string_types):
if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0:
_valid(status, 'onlyif execution failed')
_valid(status, 'onlyif execution failed')
if unless is not None:
if not isinstance(unless, string_types):
if unless:

View File

@ -331,7 +331,7 @@ def bootstrap_psexec(hosts='', master=None, version=None, arch='win32',
version = source_list[0][1]
arch = source_list[0][2]
installer_url = base_url+source_list[0][0]
installer_url = base_url + source_list[0][0]
# It's no secret that Windows is notoriously command-line hostile.
# Win 7 and newer can use PowerShell out of the box, but to reach
@ -390,9 +390,10 @@ objShell.Exec("{1}{2}")'''
# from a file. Glue it together line by line.
for x, y in ((vb_vcrunexec, vb_vcrun), (vb_saltexec, vb_salt)):
vb_lines = y.split('\n')
batch += '\ndel '+x+'\n@echo '+vb_lines[0]+' >'+x+'.vbs\n@echo ' + \
(' >>'+x+'.vbs\n@echo ').join(vb_lines[1:]) + \
' >>'+x+'.vbs\ncscript.exe /NoLogo '+x+'.vbs'
batch += '\ndel ' + x + '\n@echo ' + vb_lines[0] + ' >' + \
x + '.vbs\n@echo ' + \
(' >>' + x + '.vbs\n@echo ').join(vb_lines[1:]) + \
' >>' + x + '.vbs\ncscript.exe /NoLogo ' + x + '.vbs'
batch_path = tempfile.mkstemp(suffix='.bat')[1]
batch_file = open(batch_path, 'wb')
@ -400,7 +401,7 @@ objShell.Exec("{1}{2}")'''
batch_file.close()
for host in hosts.split(","):
argv = ['psexec', '\\\\'+host]
argv = ['psexec', '\\\\' + host]
if username:
argv += ['-u', username]
if password:

View File

@ -5,6 +5,7 @@ Module for running arbitrary tests
__virtualname__ = 'test'
def __virtual__():
return __virtualname__

View File

@ -3,6 +3,7 @@
import salt.utils.decorators
import time
def _fallbackfunc():
return False, 'fallback'
@ -13,22 +14,26 @@ def working_function():
'''
return True
@salt.utils.decorators.depends('time')
def depends():
ret = {'ret': True,
'time': time.time()}
return ret
@salt.utils.decorators.depends('time123')
def missing_depends():
return True
@salt.utils.decorators.depends('time', fallback_function=_fallbackfunc)
def depends_will_fallback():
ret = {'ret': True,
'time': time.time()}
return ret
@salt.utils.decorators.depends('time123', fallback_function=_fallbackfunc)
def missing_depends_will_fallback():
ret = {'ret': True,

View File

@ -610,7 +610,7 @@ fi
expected_result_simple = {
'cmd_|-A_|-echo A third_|-run': {
'__run_num__': 2,
'comment': 'Command "echo A third" run',
'comment': 'Command "echo A third" run',
'result': True},
'cmd_|-B_|-echo B first_|-run': {
'__run_num__': 0,
@ -636,7 +636,7 @@ fi
expected_result_simple2 = {
'cmd_|-A_|-echo A_|-run': {
'__run_num__': 1,
'comment': 'Command "echo A" run',
'comment': 'Command "echo A" run',
'result': True},
'cmd_|-B_|-echo B_|-run': {
'__run_num__': 2,
@ -658,7 +658,7 @@ fi
expected_result_complex = {
'cmd_|-A_|-echo A fourth_|-run': {
'__run_num__': 3,
'comment': 'Command "echo A fourth" run',
'comment': 'Command "echo A fourth" run',
'result': True},
'cmd_|-B_|-echo B first_|-run': {
'__run_num__': 0,

View File

@ -14,10 +14,12 @@ ensure_in_syspath('../../')
# Import Salt libs
from salt.modules import file as filemod
from salt.modules import config as configmod
from salt.modules import cmdmod
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.exceptions import CommandExecutionError
filemod.__salt__ = {
'config.manage_mode': configmod.manage_mode,
'cmd.run': cmdmod.run,
'cmd.run_all': cmdmod.run_all
}
@ -87,21 +89,24 @@ class FileReplaceTestCase(TestCase):
self.assertEqual(before_ctime, after_ctime)
def test_show_changes(self):
ret = filemod.replace(self.tfile.name, r'Etiam', 'Salticus',
show_changes=True)
ret = filemod.replace(self.tfile.name,
r'Etiam', 'Salticus',
show_changes=True)
self.assertTrue(ret.startswith('---')) # looks like a diff
def test_noshow_changes(self):
ret = filemod.replace(self.tfile.name, r'Etiam', 'Salticus',
show_changes=False)
ret = filemod.replace(self.tfile.name,
r'Etiam', 'Salticus',
show_changes=False)
self.assertIsInstance(ret, bool)
def test_re_str_flags(self):
# upper- & lower-case
filemod.replace(self.tfile.name, r'Etiam', 'Salticus',
flags=['MULTILINE', 'ignorecase'])
filemod.replace(self.tfile.name,
r'Etiam', 'Salticus',
flags=['MULTILINE', 'ignorecase'])
def test_re_int_flags(self):
filemod.replace(self.tfile.name, r'Etiam', 'Salticus', flags=10)
@ -136,7 +141,8 @@ class FileBlockReplaceTestCase(TestCase):
''')
def setUp(self):
self.tfile = tempfile.NamedTemporaryFile(delete=False, prefix='blockrepltmp')
self.tfile = tempfile.NamedTemporaryFile(delete=False,
prefix='blockrepltmp')
self.tfile.write(self.MULTILINE_STRING)
self.tfile.close()
manage_mode_mock = MagicMock()
@ -146,12 +152,23 @@ class FileBlockReplaceTestCase(TestCase):
os.remove(self.tfile.name)
def test_replace_multiline(self):
new_multiline_content = "Who's that then?\nWell, how'd you become king, then?\nWe found them. I'm not a witch.\nWe shall say 'Ni' again to you, if you do not appease us."
filemod.blockreplace(self.tfile.name, '#-- START BLOCK 1', '#-- END BLOCK 1', new_multiline_content, backup=False)
new_multiline_content = (
"Who's that then?\nWell, how'd you become king,"
"then?\nWe found them. I'm not a witch.\nWe shall"
"say 'Ni' again to you, if you do not appease us."
)
filemod.blockreplace(self.tfile.name,
'#-- START BLOCK 1',
'#-- END BLOCK 1',
new_multiline_content,
backup=False)
with open(self.tfile.name, 'rb') as fp:
filecontent = fp.read()
self.assertIn('#-- START BLOCK 1'+"\n"+new_multiline_content+"\n"+'#-- END BLOCK 1', filecontent)
self.assertIn('#-- START BLOCK 1'
+ "\n" + new_multiline_content
+ "\n"
+ '#-- END BLOCK 1', filecontent)
self.assertNotIn('old content part 1', filecontent)
self.assertNotIn('old content part 2', filecontent)
@ -169,12 +186,21 @@ class FileBlockReplaceTestCase(TestCase):
backup=False
)
with open(self.tfile.name, 'rb') as fp:
self.assertNotIn('#-- START BLOCK 2'+"\n"+new_content+"\n"+'#-- END BLOCK 2', fp.read())
self.assertNotIn('#-- START BLOCK 2'
+ "\n" + new_content + "\n"
+ '#-- END BLOCK 2', fp.read())
filemod.blockreplace(self.tfile.name, '#-- START BLOCK 2', '#-- END BLOCK 2', new_content, backup=False, append_if_not_found=True)
filemod.blockreplace(self.tfile.name,
'#-- START BLOCK 2',
'#-- END BLOCK 2',
new_content,
backup=False,
append_if_not_found=True)
with open(self.tfile.name, 'rb') as fp:
self.assertIn('#-- START BLOCK 2'+"\n"+new_content+"\n"+'#-- END BLOCK 2', fp.read())
self.assertIn('#-- START BLOCK 2'
+ "\n" + new_content
+ "\n" + '#-- END BLOCK 2', fp.read())
def test_replace_prepend(self):
new_content = "Well, I didn't vote for you."
@ -190,15 +216,30 @@ class FileBlockReplaceTestCase(TestCase):
backup=False
)
with open(self.tfile.name, 'rb') as fp:
self.assertNotIn('#-- START BLOCK 2'+"\n"+new_content+"\n"+'#-- END BLOCK 2', fp.read())
self.assertNotIn(
'#-- START BLOCK 2' + "\n"
+ new_content + "\n" + '#-- END BLOCK 2',
fp.read())
filemod.blockreplace(self.tfile.name, '#-- START BLOCK 2', '#-- END BLOCK 2', new_content, backup=False, prepend_if_not_found=True)
filemod.blockreplace(self.tfile.name,
'#-- START BLOCK 2', '#-- END BLOCK 2',
new_content,
backup=False,
prepend_if_not_found=True)
with open(self.tfile.name, 'rb') as fp:
self.assertTrue(fp.read().startswith('#-- START BLOCK 2'+"\n"+new_content+"\n"+'#-- END BLOCK 2'))
self.assertTrue(
fp.read().startswith(
'#-- START BLOCK 2'
+ "\n" + new_content
+ "\n" + '#-- END BLOCK 2'))
def test_replace_partial_marked_lines(self):
filemod.blockreplace(self.tfile.name, '// START BLOCK', '// END BLOCK', 'new content 1', backup=False)
filemod.blockreplace(self.tfile.name,
'// START BLOCK',
'// END BLOCK',
'new content 1',
backup=False)
with open(self.tfile.name, 'rb') as fp:
filecontent = fp.read()
@ -213,7 +254,10 @@ class FileBlockReplaceTestCase(TestCase):
fext = '.bak'
bak_file = '{0}{1}'.format(self.tfile.name, fext)
filemod.blockreplace(self.tfile.name, '// START BLOCK', '// END BLOCK', 'new content 2', backup=fext)
filemod.blockreplace(
self.tfile.name,
'// START BLOCK', '// END BLOCK', 'new content 2',
backup=fext)
self.assertTrue(os.path.exists(bak_file))
os.unlink(bak_file)
@ -222,31 +266,54 @@ class FileBlockReplaceTestCase(TestCase):
fext = '.bak'
bak_file = '{0}{1}'.format(self.tfile.name, fext)
filemod.blockreplace(self.tfile.name, '// START BLOCK', '// END BLOCK', 'new content 3', backup=False)
filemod.blockreplace(self.tfile.name,
'// START BLOCK', '// END BLOCK', 'new content 3',
backup=False)
self.assertFalse(os.path.exists(bak_file))
def test_no_modifications(self):
filemod.blockreplace(self.tfile.name, '// START BLOCK', '// END BLOCK', 'new content 4', backup=False)
filemod.blockreplace(self.tfile.name,
'// START BLOCK', '// END BLOCK',
'new content 4',
backup=False)
before_ctime = os.stat(self.tfile.name).st_mtime
filemod.blockreplace(self.tfile.name, '// START BLOCK', '// END BLOCK', 'new content 4', backup=False)
filemod.blockreplace(self.tfile.name,
'// START BLOCK',
'// END BLOCK',
'new content 4',
backup=False)
after_ctime = os.stat(self.tfile.name).st_mtime
self.assertEqual(before_ctime, after_ctime)
def test_dry_run(self):
before_ctime = os.stat(self.tfile.name).st_mtime
filemod.blockreplace(self.tfile.name, '// START BLOCK', '// END BLOCK', 'new content 5', dry_run=True)
filemod.blockreplace(self.tfile.name,
'// START BLOCK',
'// END BLOCK',
'new content 5',
dry_run=True)
after_ctime = os.stat(self.tfile.name).st_mtime
self.assertEqual(before_ctime, after_ctime)
def test_show_changes(self):
ret = filemod.blockreplace(self.tfile.name, '// START BLOCK', '// END BLOCK', 'new content 6', backup=False, show_changes=True)
ret = filemod.blockreplace(self.tfile.name,
'// START BLOCK',
'// END BLOCK',
'new content 6',
backup=False,
show_changes=True)
self.assertTrue(ret.startswith('---')) # looks like a diff
ret = filemod.blockreplace(self.tfile.name, '// START BLOCK', '// END BLOCK', 'new content 7', backup=False, show_changes=False)
ret = filemod.blockreplace(self.tfile.name,
'// START BLOCK',
'// END BLOCK',
'new content 7',
backup=False,
show_changes=False)
self.assertIsInstance(ret, bool)
@ -258,7 +325,7 @@ class FileBlockReplaceTestCase(TestCase):
'#-- START BLOCK UNFINISHED',
'#-- END BLOCK UNFINISHED',
'foobar',
backup=False
backup=False
)
@ -309,4 +376,7 @@ class FileModuleTestCase(TestCase):
if __name__ == '__main__':
from integration import run_tests
run_tests(FileModuleTestCase, FileReplaceTestCase, FileBlockReplaceTestCase, needs_daemon=False)
run_tests(FileModuleTestCase,
FileReplaceTestCase,
FileBlockReplaceTestCase,
needs_daemon=False)

View File

@ -4,9 +4,6 @@
import os
import tempfile
import urllib2
import textwrap
from distutils.dir_util import copy_tree
# Import Salt Testing libs
from salttesting import TestCase
@ -14,7 +11,6 @@ from salttesting.helpers import (
ensure_in_syspath,
requires_network,
)
from salttesting.mock import MagicMock
ensure_in_syspath('../../')
import integration
@ -23,7 +19,6 @@ import shutil
# Import Salt libs
from salt.modules import zcbuildout as buildout
from salt.modules import cmdmod as cmd
from salt.exceptions import CommandExecutionError, SaltInvocationError
ROOT = os.path.join(integration.FILES, 'file', 'base', 'buildout')
@ -106,6 +101,7 @@ class BuildoutTestCase(Base):
@buildout._salt_callback
def callback2(a, b=1):
raise Exception('foo')
return 1 # make pylint happy
ret1 = callback1(1, b=3)
self.assertEqual(ret1['status'], True)

View File

@ -3,8 +3,6 @@ import os
import tempfile
import textwrap
from distutils.dir_util import copy_tree
# Import third party libs
import yaml
@ -77,16 +75,16 @@ class BuildoutTestCase(Base):
def test_installed(self):
b_dir = os.path.join(self.tdir, 'b')
ret = buildout.installed(b_dir, onlyif='/bin/false')
self.assertEqual(ret['comment'], '\nonlyif execution failed')
self.assertEqual(ret['result'], True)
self.assertEqual(ret['comment'], '\nonlyif execution failed')
self.assertEqual(ret['result'], True)
self.assertTrue('/b' in ret['name'])
b_dir = os.path.join(self.tdir, 'b')
ret = buildout.installed(b_dir, unless='/bin/true')
self.assertEqual(ret['comment'], '\nunless execution succeeded')
self.assertEqual(ret['result'], True)
self.assertEqual(ret['comment'], '\nunless execution succeeded')
self.assertEqual(ret['result'], True)
self.assertTrue('/b' in ret['name'])
ret = buildout.installed(b_dir)
self.assertEqual(ret['result'], True)
self.assertEqual(ret['result'], True)
self.assertTrue('OUTPUT:' in ret['comment'])
self.assertTrue('Log summary:' in ret['comment'])