test_imports.py 1.4 KB

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