From 243879f5c51fc45f03491bcb78765945ddf76be8 Mon Sep 17 00:00:00 2001 From: Ihar Hrachyshka Date: Fri, 1 Aug 2014 15:42:51 +0200 Subject: [PATCH] Added hacking check for jsonutils jsonutils provides some additional features in comparison to pure json or simplejson modules. For example, on Python 2.6, it automatically switches to simplejson that provides significant performance boost. So let's enforce usage of the module in replacement to stdlib json. Change-Id: I86ed6cd3316dd4da5e1b10b36a3ddba3739316d3 --- nova/hacking/checks.py | 18 ++++++++++++++++++ nova/tests/test_hacking.py | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/nova/hacking/checks.py b/nova/hacking/checks.py index 707e629d51..a1dd61419a 100644 --- a/nova/hacking/checks.py +++ b/nova/hacking/checks.py @@ -286,6 +286,23 @@ def check_explicit_underscore_import(logical_line, filename): yield(0, "N323: Found use of _() without explicit import of _ !") +def use_jsonutils(logical_line, filename): + # the code below that path is not meant to be executed from neutron + # tree where jsonutils module is present, so don't enforce its usage + # for this subdirectory + if "plugins/xenserver" in filename: + return + + msg = "N323: jsonutils.%(fun)s must be used instead of json.%(fun)s" + + if "json." in logical_line: + json_funcs = ['dumps', 'dump', 'loads', 'load'] + for f in json_funcs: + pos = logical_line.find('json.%s' % f) + if pos != -1: + return (pos, msg % {'fun': f}) + + def factory(register): register(import_no_db_in_virt) register(no_db_session_in_public_api) @@ -303,3 +320,4 @@ def factory(register): register(validate_log_translations) register(no_mutable_default_args) register(check_explicit_underscore_import) + register(use_jsonutils) diff --git a/nova/tests/test_hacking.py b/nova/tests/test_hacking.py index 2db0936680..f6f796b138 100644 --- a/nova/tests/test_hacking.py +++ b/nova/tests/test_hacking.py @@ -217,3 +217,24 @@ class HackingTestCase(test.NoDBTestCase): self.assertEqual(len(list(checks.check_explicit_underscore_import( "msg = _('My message')", "cinder/tests/other_files3.py"))), 0) + + def test_use_jsonutils(self): + def __get_msg(fun): + msg = ("N323: jsonutils.%(fun)s must be used instead of " + "json.%(fun)s" % {'fun': fun}) + return (0, msg) + + for method in ('dump', 'dumps', 'load', 'loads'): + self.assertEqual( + __get_msg(method), + checks.use_jsonutils("json.%s" % method, + "./nova/virt/xenapi/driver.py")) + self.assertIsNone( + checks.use_jsonutils("json.%s" % method, + "./plugins/xenserver/script.py")) + self.assertIsNone( + checks.use_jsonutils("jsonx.%s" % method, + "./nova/virt/xenapi/driver.py")) + self.assertIsNone( + checks.use_jsonutils("json.dumb", + "./nova/virt/xenapi/driver.py"))