From b10d5f34ea644e2896d33a08448fbd654c24bc72 Mon Sep 17 00:00:00 2001 From: jctanner Date: Mon, 15 Jan 2018 10:49:35 -0500 Subject: [PATCH] Extend validate-modules to check the next to last line (#34819) * Add validation for the next to last line of a module * Fix last error code * Reduce to a single conditional * Fix conditionals * Move the final warnings statement to main() in mysql_replication --- .../dev_guide/testing_validate-modules.rst | 1 + .../database/mysql/mysql_replication.py | 3 ++- test/sanity/validate-modules/main.py | 24 +++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/docs/docsite/rst/dev_guide/testing_validate-modules.rst b/docs/docsite/rst/dev_guide/testing_validate-modules.rst index 70ccc5008a..24e375d1f9 100644 --- a/docs/docsite/rst/dev_guide/testing_validate-modules.rst +++ b/docs/docsite/rst/dev_guide/testing_validate-modules.rst @@ -70,6 +70,7 @@ Errors ``DOCUMENTATION``/``EXAMPLES``/``RETURN``/``ANSIBLE_METADATA`` 107 Imports should be directly below ``DOCUMENTATION``/``EXAMPLES``/``RETURN``/``ANSIBLE_METADATA`` 108 GPLv3 license header should be the :ref:`short form ` for new modules + 109 Next to last line is not ``if __name__ == "__main__":`` .. --------- ------------------- **2xx** **Imports** diff --git a/lib/ansible/modules/database/mysql/mysql_replication.py b/lib/ansible/modules/database/mysql/mysql_replication.py index 6cff3efac3..dcc035ce70 100644 --- a/lib/ansible/modules/database/mysql/mysql_replication.py +++ b/lib/ansible/modules/database/mysql/mysql_replication.py @@ -359,7 +359,8 @@ def main(): else: module.exit_json(msg="Slave already reset", changed=False) + warnings.simplefilter("ignore") + if __name__ == '__main__': main() - warnings.simplefilter("ignore") diff --git a/test/sanity/validate-modules/main.py b/test/sanity/validate-modules/main.py index 4d87bfa2f2..c1ed89cdf3 100755 --- a/test/sanity/validate-modules/main.py +++ b/test/sanity/validate-modules/main.py @@ -518,6 +518,30 @@ class ModuleValidator(Validator): bodies.extend(if_bodies) for child in bodies: + + # validate that the next to last line is 'if __name__ == "__main__"' + if child.lineno == (self.length - 1): + + mainchecked = False + try: + if isinstance(child, ast.If) and \ + child.test.left.id == '__name__' and \ + len(child.test.ops) == 1 and \ + isinstance(child.test.ops[0], ast.Eq) and \ + child.test.comparators[0].s == '__main__': + mainchecked = True + except Exception: + pass + + if not mainchecked: + self.reporter.error( + path=self.object_path, + code=109, + msg='Next to last line should be: if __name__ == "__main__":', + line=child.lineno + ) + + # validate that the final line is a call to main() if isinstance(child, ast.Expr): if isinstance(child.value, ast.Call): if (isinstance(child.value.func, ast.Name) and