| OLD | NEW |
| (Empty) |
| 1 #!/usr/bin/env python | |
| 2 # Copyright 2015 The Chromium Authors. All rights reserved. | |
| 3 # Use of this source code is governed by a BSD-style license that can be | |
| 4 # found in the LICENSE file. | |
| 5 | |
| 6 """Tests that recipes are on their best behavior. | |
| 7 | |
| 8 Checks that recipes only import modules from a whitelist. Imports are | |
| 9 generally not safe in recipes if they depend on the platform, since | |
| 10 e.g. you can run a recipe simulation for a Windows recipe on Linux. | |
| 11 """ | |
| 12 | |
| 13 # TODO(luqui): Implement lint for recipe modules also. | |
| 14 | |
| 15 import re | |
| 16 import os | |
| 17 import sys | |
| 18 import types | |
| 19 | |
| 20 | |
| 21 MODULES_WHITELIST = [ | |
| 22 r'base64', | |
| 23 r'collections', | |
| 24 r'contextlib', | |
| 25 r'datetime', | |
| 26 r'json', | |
| 27 r'math', | |
| 28 r're', | |
| 29 r'urlparse', | |
| 30 ] | |
| 31 | |
| 32 | |
| 33 class ImportViolationError(Exception): | |
| 34 pass | |
| 35 | |
| 36 | |
| 37 class TestFailure(Exception): | |
| 38 pass | |
| 39 | |
| 40 | |
| 41 def ImportsTest(recipe_path, recipe_name, whitelist, universe): | |
| 42 """Tests that recipe_name only uses allowed imports. | |
| 43 | |
| 44 Returns a list of errors, or an empty list if there are no errors (duh). | |
| 45 """ | |
| 46 | |
| 47 recipe = universe.load_recipe(recipe_name) | |
| 48 for attr in dir(recipe): | |
| 49 val = getattr(recipe, attr) | |
| 50 if isinstance(val, types.ModuleType): | |
| 51 module_name = val.__name__ | |
| 52 for pattern in whitelist: | |
| 53 if pattern.match(val.__name__): | |
| 54 break | |
| 55 else: | |
| 56 yield ('In %s:\n' | |
| 57 ' Non-whitelisted import of %s' % | |
| 58 (recipe_path, module_name)) | |
| 59 | |
| 60 | |
| 61 def main(universe, whitelist=[]): | |
| 62 whitelist = map(re.compile, MODULES_WHITELIST + whitelist) | |
| 63 | |
| 64 errors = [] | |
| 65 for recipe_path, recipe_name in universe.loop_over_recipes(): | |
| 66 errors.extend(ImportsTest(recipe_path, recipe_name, whitelist, universe)) | |
| 67 | |
| 68 if errors: | |
| 69 raise TestFailure('\n'.join(map(str, errors))) | |
| 70 | |
| OLD | NEW |