utils.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from __future__ import annotations
  2. from typing import Callable
  3. from traceback import print_tb
  4. from click.core import Command as ClickCommand
  5. def check_command_ran_without_error(result):
  6. print(result)
  7. assert result.exit_code == 0, print_tb(
  8. result.exc_info[2]
  9. ) # run command without errors
  10. def to_flags(cli_input: dict) -> list:
  11. """Turn dictionary of CLI input into a list of CLI flags ready for use in FlaskCliRunner.invoke().
  12. Example:
  13. cli_input = {
  14. "year": 2020,
  15. "country": "NL",
  16. }
  17. cli_flags = to_flags(cli_input) # ["--year", 2020, "--country", "NL"]
  18. runner = app.test_cli_runner()
  19. result = runner.invoke(some_cli_function, to_flags(cli_input))
  20. """
  21. return [
  22. item
  23. for sublist in zip(
  24. [f"--{key.replace('_', '-')}" for key in cli_input.keys()],
  25. cli_input.values(),
  26. )
  27. for item in sublist
  28. ]
  29. def get_click_commands(module) -> list[Callable]:
  30. return [
  31. getattr(module, attr)
  32. for attr in dir(module)
  33. if type(getattr(module, attr)) == ClickCommand
  34. ]