test_imports.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os
  2. import json
  3. import subprocess
  4. import sys
  5. from click._compat import WIN
  6. IMPORT_TEST = b"""\
  7. try:
  8. import __builtin__ as builtins
  9. except ImportError:
  10. import builtins
  11. found_imports = set()
  12. real_import = builtins.__import__
  13. import sys
  14. def tracking_import(module, locals=None, globals=None, fromlist=None,
  15. level=0):
  16. rv = real_import(module, locals, globals, fromlist, level)
  17. if globals and globals['__name__'].startswith('click') and level == 0:
  18. found_imports.add(module)
  19. return rv
  20. builtins.__import__ = tracking_import
  21. import click
  22. rv = list(found_imports)
  23. import json
  24. click.echo(json.dumps(rv))
  25. """
  26. ALLOWED_IMPORTS = {
  27. "weakref",
  28. "os",
  29. "struct",
  30. "collections",
  31. "sys",
  32. "contextlib",
  33. "functools",
  34. "stat",
  35. "re",
  36. "codecs",
  37. "inspect",
  38. "itertools",
  39. "io",
  40. "threading",
  41. "colorama",
  42. "errno",
  43. "fcntl",
  44. "datetime",
  45. "pipes",
  46. }
  47. if WIN:
  48. ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])
  49. def test_light_imports():
  50. env = os.environ.copy()
  51. env["Y_PYTHON_ENTRY_POINT"] = ":main"
  52. c = subprocess.Popen(
  53. [sys.executable, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env,
  54. )
  55. rv = c.communicate(IMPORT_TEST)[0]
  56. if sys.version_info[0] != 2:
  57. rv = rv.decode("utf-8")
  58. imported = json.loads(rv)
  59. for module in imported:
  60. if module == "click" or module.startswith("click."):
  61. continue
  62. assert module in ALLOWED_IMPORTS