setuponly.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from __future__ import absolute_import, division, print_function
  2. import pytest
  3. import sys
  4. def pytest_addoption(parser):
  5. group = parser.getgroup("debugconfig")
  6. group.addoption(
  7. "--setuponly",
  8. "--setup-only",
  9. action="store_true",
  10. help="only setup fixtures, do not execute tests.",
  11. )
  12. group.addoption(
  13. "--setupshow",
  14. "--setup-show",
  15. action="store_true",
  16. help="show setup of fixtures while executing tests.",
  17. )
  18. @pytest.hookimpl(hookwrapper=True)
  19. def pytest_fixture_setup(fixturedef, request):
  20. yield
  21. config = request.config
  22. if config.option.setupshow:
  23. if hasattr(request, "param"):
  24. # Save the fixture parameter so ._show_fixture_action() can
  25. # display it now and during the teardown (in .finish()).
  26. if fixturedef.ids:
  27. if callable(fixturedef.ids):
  28. fixturedef.cached_param = fixturedef.ids(request.param)
  29. else:
  30. fixturedef.cached_param = fixturedef.ids[request.param_index]
  31. else:
  32. fixturedef.cached_param = request.param
  33. _show_fixture_action(fixturedef, "SETUP")
  34. def pytest_fixture_post_finalizer(fixturedef):
  35. if hasattr(fixturedef, "cached_result"):
  36. config = fixturedef._fixturemanager.config
  37. if config.option.setupshow:
  38. _show_fixture_action(fixturedef, "TEARDOWN")
  39. if hasattr(fixturedef, "cached_param"):
  40. del fixturedef.cached_param
  41. def _show_fixture_action(fixturedef, msg):
  42. config = fixturedef._fixturemanager.config
  43. capman = config.pluginmanager.getplugin("capturemanager")
  44. if capman:
  45. capman.suspend_global_capture()
  46. out, err = capman.read_global_capture()
  47. tw = config.get_terminal_writer()
  48. tw.line()
  49. tw.write(" " * 2 * fixturedef.scopenum)
  50. tw.write(
  51. "{step} {scope} {fixture}".format(
  52. step=msg.ljust(8), # align the output to TEARDOWN
  53. scope=fixturedef.scope[0].upper(),
  54. fixture=fixturedef.argname,
  55. )
  56. )
  57. if msg == "SETUP":
  58. deps = sorted(arg for arg in fixturedef.argnames if arg != "request")
  59. if deps:
  60. tw.write(" (fixtures used: {})".format(", ".join(deps)))
  61. if hasattr(fixturedef, "cached_param"):
  62. tw.write("[{}]".format(fixturedef.cached_param))
  63. if capman:
  64. capman.resume_global_capture()
  65. sys.stdout.write(out)
  66. sys.stderr.write(err)
  67. @pytest.hookimpl(tryfirst=True)
  68. def pytest_cmdline_main(config):
  69. if config.option.setuponly:
  70. config.option.setupshow = True