Enable hacking check H233

* H233  Python 3.x incompatible use of print operator

Change-Id: I7b4b0a68f4dbf9f53833a3264601bcd631bf006e
This commit is contained in:
Christian Berendt 2014-07-28 22:26:27 +02:00
parent fb0f1b564c
commit 3d9fa1ed33
10 changed files with 72 additions and 72 deletions

View File

@ -586,7 +586,7 @@ def run_check(name, path=None):
for instance in instances: for instance in instances:
check.check(instance) check.check(instance)
if check.has_events(): if check.has_events():
print "Events:\n" print("Events:\n")
pprint(check.get_events(), indent=4) pprint(check.get_events(), indent=4)
print "Metrics:\n" print("Metrics:\n")
pprint(check.get_metrics(), indent=4) pprint(check.get_metrics(), indent=4)

View File

@ -656,88 +656,88 @@ def _test():
return x * x return x * x
def work(seconds): def work(seconds):
print "[%d] Start to work for %fs..." % (thread.get_ident(), seconds) print("[%d] Start to work for %fs..." % (thread.get_ident(), seconds))
time.sleep(seconds) time.sleep(seconds)
print "[%d] Work done (%fs)." % (thread.get_ident(), seconds) print("[%d] Work done (%fs)." % (thread.get_ident(), seconds))
return "%d slept %fs" % (thread.get_ident(), seconds) return "%d slept %fs" % (thread.get_ident(), seconds)
# Test copy/pasted from multiprocessing # Test copy/pasted from multiprocessing
pool = Pool(9) # start 4 worker threads pool = Pool(9) # start 4 worker threads
result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
print result.get(timeout=1) # prints "100" unless slow computer print(result.get(timeout=1)) # prints "100" unless slow computer
print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]"
it = pool.imap(f, range(10)) it = pool.imap(f, range(10))
print it.next() # prints "0" print(it.next()) # prints "0"
print it.next() # prints "1" print(it.next()) # prints "1"
print it.next(timeout=1) # prints "4" unless slow computer print(it.next(timeout=1)) # prints "4" unless slow computer
# Test apply_sync exceptions # Test apply_sync exceptions
result = pool.apply_async(time.sleep, (3,)) result = pool.apply_async(time.sleep, (3,))
try: try:
print result.get(timeout=1) # raises `TimeoutError` print(result.get(timeout=1)) # raises `TimeoutError`
except TimeoutError: except TimeoutError:
print "Good. Got expected timeout exception." print("Good. Got expected timeout exception.")
else: else:
assert False, "Expected exception !" assert False, "Expected exception !"
print result.get() print(result.get())
def cb(s): def cb(s):
print "Result ready: %s" % s print("Result ready: %s" % s)
# Test imap() # Test imap()
for res in pool.imap(work, xrange(10, 3, -1), chunksize=4): for res in pool.imap(work, xrange(10, 3, -1), chunksize=4):
print "Item:", res print("Item:", res)
# Test imap_unordered() # Test imap_unordered()
for res in pool.imap_unordered(work, xrange(10, 3, -1)): for res in pool.imap_unordered(work, xrange(10, 3, -1)):
print "Item:", res print("Item:", res)
# Test map_async() # Test map_async()
result = pool.map_async(work, xrange(10), callback=cb) result = pool.map_async(work, xrange(10), callback=cb)
try: try:
print result.get(timeout=1) # raises `TimeoutError` print(result.get(timeout=1)) # raises `TimeoutError`
except TimeoutError: except TimeoutError:
print "Good. Got expected timeout exception." print("Good. Got expected timeout exception.")
else: else:
assert False, "Expected exception !" assert False, "Expected exception !"
print result.get() print(result.get())
# Test imap_async() # Test imap_async()
result = pool.imap_async(work, xrange(3, 10), callback=cb) result = pool.imap_async(work, xrange(3, 10), callback=cb)
try: try:
print result.get(timeout=1) # raises `TimeoutError` print(result.get(timeout=1)) # raises `TimeoutError`
except TimeoutError: except TimeoutError:
print "Good. Got expected timeout exception." print("Good. Got expected timeout exception.")
else: else:
assert False, "Expected exception !" assert False, "Expected exception !"
for i in result.get(): for i in result.get():
print "Item:", i print("Item:", i)
print "### Loop again:" print("### Loop again:")
for i in result.get(): for i in result.get():
print "Item2:", i print("Item2:", i)
# Test imap_unordered_async() # Test imap_unordered_async()
result = pool.imap_unordered_async(work, xrange(10, 3, -1), callback=cb) result = pool.imap_unordered_async(work, xrange(10, 3, -1), callback=cb)
try: try:
print result.get(timeout=1) # raises `TimeoutError` print(result.get(timeout=1)) # raises `TimeoutError`
except TimeoutError: except TimeoutError:
print "Good. Got expected timeout exception." print("Good. Got expected timeout exception.")
else: else:
assert False, "Expected exception !" assert False, "Expected exception !"
for i in result.get(): for i in result.get():
print "Item1:", i print("Item1:", i)
for i in result.get(): for i in result.get():
print "Item2:", i print("Item2:", i)
r = result.get() r = result.get()
for i in r: for i in r:
print "Item3:", i print("Item3:", i)
for i in r: for i in r:
print "Item4:", i print("Item4:", i)
for i in r: for i in r:
print "Item5:", i print("Item5:", i)
# #
# The case for the exceptions # The case for the exceptions
@ -748,9 +748,9 @@ def _test():
time.sleep(3) time.sleep(3)
try: try:
for i in result.get(): for i in result.get():
print "Got item:", i print("Got item:", i)
except IOError: except IOError:
print "Good. Got expected exception:" print("Good. Got expected exception:")
traceback.print_exc() traceback.print_exc()
# Exceptions in imap_async() # Exceptions in imap_async()
@ -758,14 +758,14 @@ def _test():
time.sleep(3) time.sleep(3)
try: try:
for i in result.get(): for i in result.get():
print "Got item:", i print("Got item:", i)
except IOError: except IOError:
print "Good. Got expected exception:" print("Good. Got expected exception:")
traceback.print_exc() traceback.print_exc()
# Stop the test: need to stop the pool !!! # Stop the test: need to stop the pool !!!
pool.terminate() pool.terminate()
print "End of tests" print("End of tests")
if __name__ == "__main__": if __name__ == "__main__":
_test() _test()

View File

@ -45,5 +45,5 @@ if __name__ == '__main__':
check, instances = HDFSCheck.from_yaml('./hdfs.yaml') check, instances = HDFSCheck.from_yaml('./hdfs.yaml')
for instance in instances: for instance in instances:
check.check(instance) check.check(instance)
print "Events: %r" % check.get_events() print("Events: %r" % check.get_events())
print "Metrics: %r" % check.get_metrics() print("Metrics: %r" % check.get_metrics())

View File

@ -255,21 +255,21 @@ def main():
check_name = args[1] check_name = args[1]
try: try:
# Try the old-style check first # Try the old-style check first
print getattr(collector.checks.collector, check_name)(log).check(agentConfig) print(getattr(collector.checks.collector, check_name)(log).check(agentConfig))
except Exception: except Exception:
# If not an old-style check, try checks_d # If not an old-style check, try checks_d
checks = load_check_directory(agentConfig) checks = load_check_directory(agentConfig)
for check in checks['initialized_checks']: for check in checks['initialized_checks']:
if check.name == check_name: if check.name == check_name:
check.run() check.run()
print check.get_metrics() print(check.get_metrics())
print check.get_events() print(check.get_events())
if len(args) == 3 and args[2] == 'check_rate': if len(args) == 3 and args[2] == 'check_rate':
print "Running 2nd iteration to capture rate metrics" print("Running 2nd iteration to capture rate metrics")
time.sleep(1) time.sleep(1)
check.run() check.run()
print check.get_metrics() print(check.get_metrics())
print check.get_events() print(check.get_events())
elif 'configcheck' == command or 'configtest' == command: elif 'configcheck' == command or 'configtest' == command:
osname = get_os() osname = get_os()
@ -280,11 +280,11 @@ def main():
check_yaml(conf_path) check_yaml(conf_path)
except Exception as e: except Exception as e:
all_valid = False all_valid = False
print "%s contains errors:\n %s" % (basename, e) print("%s contains errors:\n %s" % (basename, e))
else: else:
print "%s is valid" % basename print("%s is valid" % basename)
if all_valid: if all_valid:
print "All yaml files passed. You can now run the Monitoring agent." print("All yaml files passed. You can now run the Monitoring agent.")
return 0 return 0
else: else:
print("Fix the invalid yaml files above in order to start the Monitoring agent. " print("Fix the invalid yaml files above in order to start the Monitoring agent. "
@ -295,16 +295,16 @@ def main():
elif 'jmx' == command: elif 'jmx' == command:
if len(args) < 2 or args[1] not in JMX_LIST_COMMANDS.keys(): if len(args) < 2 or args[1] not in JMX_LIST_COMMANDS.keys():
print "#" * 80 print("#" * 80)
print "JMX tool to be used to help configuring your JMX checks." print("JMX tool to be used to help configuring your JMX checks.")
print "See http://docs.datadoghq.com/integrations/java/ for more information" print("See http://docs.datadoghq.com/integrations/java/ for more information")
print "#" * 80 print("#" * 80)
print "\n" print("\n")
print "You have to specify one of the following command:" print("You have to specify one of the following command:")
for command, desc in JMX_LIST_COMMANDS.iteritems(): for command, desc in JMX_LIST_COMMANDS.iteritems():
print " - %s [OPTIONAL: LIST OF CHECKS]: %s" % (command, desc) print(" - %s [OPTIONAL: LIST OF CHECKS]: %s" % (command, desc))
print "Example: sudo /etc/init.d/monasca-agent jmx list_matching_attributes tomcat jmx solr" print("Example: sudo /etc/init.d/monasca-agent jmx list_matching_attributes tomcat jmx solr")
print "\n" print("\n")
else: else:
jmx_command = args[1] jmx_command = args[1]
@ -319,8 +319,8 @@ def main():
checks_list, checks_list,
reporter="console") reporter="console")
if not should_run: if not should_run:
print "Couldn't find any valid JMX configuration in your conf.d directory: %s" % confd_directory print("Couldn't find any valid JMX configuration in your conf.d directory: %s" % confd_directory)
print "Have you enabled any JMX check ?" print("Have you enabled any JMX check ?")
return 0 return 0

View File

@ -326,10 +326,10 @@ def main():
logging.getLogger().setLevel(logging.ERROR) logging.getLogger().setLevel(logging.ERROR)
return ForwarderStatus.print_latest_status() return ForwarderStatus.print_latest_status()
elif command == 'help': elif command == 'help':
print usage print(usage)
else: else:
print "Unknown command: %s" % command print("Unknown command: %s" % command)
print usage print(usage)
return -1 return -1
return 0 return 0

View File

@ -4,16 +4,16 @@ import traceback
def shell(): def shell():
from config import get_version from config import get_version
print """ print("""
Datadog Agent v%s - Python Shell Datadog Agent v%s - Python Shell
""" % (get_version()) """ % (get_version()))
while True: while True:
cmd = raw_input('>>> ') cmd = raw_input('>>> ')
try: try:
exec(cmd) exec(cmd)
except Exception as e: except Exception as e:
print traceback.format_exc(e) print(traceback.format_exc(e))
if __name__ == "__main__": if __name__ == "__main__":
shell() shell()

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import logging import logging
import unittest import unittest
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
@ -100,7 +101,7 @@ class TailTestCase(unittest.TestCase):
def _write_log(self, log_data): def _write_log(self, log_data):
for data in log_data: for data in log_data:
print >> self.log_file, data print(data, file=self.log_file)
self.log_file.flush() self.log_file.flush()
def tearDown(self): def tearDown(self):
@ -469,7 +470,7 @@ class TestNagiosPerfData(TailTestCase):
def _write_nagios_config(self, config_data): def _write_nagios_config(self, config_data):
for data in config_data: for data in config_data:
print >> self.nagios_config, data print(data, file=self.nagios_config)
self.nagios_config.flush() self.nagios_config.flush()
def tearDown(self): def tearDown(self):

View File

@ -82,16 +82,16 @@ class TestPostfix(unittest.TestCase):
out_count = check.get_metrics() out_count = check.get_metrics()
# output what went in... per queue # output what went in... per queue
print print()
for queue, count in self.in_count.iteritems(): for queue, count in self.in_count.iteritems():
print 'Test messges put into', queue, '= ', self.in_count[queue][0] print('Test messges put into', queue, '= ', self.in_count[queue][0])
# output postfix.py dd-agent plugin counts... per queue # output postfix.py dd-agent plugin counts... per queue
print print()
for tuple in out_count: for tuple in out_count:
queue = tuple[3]['dimensions'][0].split(':')[1] queue = tuple[3]['dimensions'][0].split(':')[1]
self.assertEquals(int(tuple[2]), int(self.in_count[queue][0])) self.assertEquals(int(tuple[2]), int(self.in_count[queue][0]))
print 'Test messages counted by dd-agent for', queue, '= ', tuple[2] print('Test messages counted by dd-agent for', queue, '= ', tuple[2])
# #
# uncomment this to see the raw dd-agent metric output # uncomment this to see the raw dd-agent metric output

View File

@ -108,7 +108,7 @@ class PseudoAgent(object):
w = Watchdog(5) w = Watchdog(5)
w.reset() w.reset()
x = url.urlopen("http://localhost:31834") x = url.urlopen("http://localhost:31834")
print "ERROR Net call returned", x print("ERROR Net call returned", x)
return True return True
@staticmethod @staticmethod

View File

@ -23,7 +23,6 @@ commands = {posargs}
# TODO: ignored checks should be enabled in the future # TODO: ignored checks should be enabled in the future
# H201 no 'except:' at least use 'except Exception:' # H201 no 'except:' at least use 'except Exception:'
# H202 assertRaises Exception too broad # H202 assertRaises Exception too broad
# H233 Python 3.x incompatible use of print operator
# H234 assertEquals is deprecated, use assertEqual # H234 assertEquals is deprecated, use assertEqual
# H237 module is removed in Python # H237 module is removed in Python
# H301 one import per line # H301 one import per line
@ -38,6 +37,6 @@ commands = {posargs}
# F401 module imported but unused # F401 module imported but unused
# F821 undefined name # F821 undefined name
# F841 local variable is assigned to but never used # F841 local variable is assigned to but never used
ignore = E501,H201,H202,H233,H234,H237,H301,H305,H306,H307,H401,H402,H403,H404,H405,H904,F401,F403,F821,F841 ignore = E501,H201,H202,H234,H237,H301,H305,H306,H307,H401,H402,H403,H404,H405,H904,F401,F403,F821,F841
show-source = True show-source = True
exclude=.venv,.git,.tox,dist,*egg,build exclude=.venv,.git,.tox,dist,*egg,build