setuponly.py 2.7 KB

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