conftest.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python
  2. # Licensed to Cloudera, Inc. under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. Cloudera, Inc. licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import pytest
  18. from django.conf import settings
  19. from desktop.lib import django_mako
  20. from django.utils.translation import deactivate
  21. from mako.template import Template
  22. from types import SimpleNamespace
  23. class _TestState(object):
  24. pass
  25. @pytest.fixture(scope='session', autouse=True)
  26. def setup_test_environment(debug=None):
  27. """
  28. Perform global pre-test setup, such as installing the instrumented template
  29. renderer and setting the email backend to the locmem email backend.
  30. """
  31. if hasattr(_TestState, 'saved_data'):
  32. # Executing this function twice would overwrite the saved values.
  33. raise RuntimeError(
  34. "setup_test_environment() was already called and can't be called "
  35. "again without first calling teardown_test_environment()."
  36. )
  37. if debug is None:
  38. debug = settings.DEBUG
  39. saved_data = SimpleNamespace()
  40. _TestState.saved_data = saved_data
  41. saved_data.allowed_hosts = settings.ALLOWED_HOSTS
  42. # Add the default host of the test client.
  43. settings.ALLOWED_HOSTS = list(settings.ALLOWED_HOSTS) + ['testserver']
  44. saved_data.debug = settings.DEBUG
  45. settings.DEBUG = debug
  46. django_mako.render_to_string = django_mako.render_to_string_test
  47. deactivate()
  48. yield
  49. teardown_test_environment()
  50. def teardown_test_environment():
  51. # Teardown test environment
  52. """
  53. Perform any global post-test teardown, such as restoring the original
  54. template renderer and restoring the email sending functions.
  55. """
  56. saved_data = _TestState.saved_data
  57. settings.ALLOWED_HOSTS = saved_data.allowed_hosts
  58. settings.DEBUG = saved_data.debug
  59. django_mako.render_to_string = django_mako.render_to_string_normal
  60. del _TestState.saved_data