-
Notifications
You must be signed in to change notification settings - Fork 330
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
make es_metrics test helper usable with unittest
- Loading branch information
Showing
2 changed files
with
49 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import contextlib | ||
from unittest import mock | ||
|
||
from django.core.management import call_command | ||
from elasticsearch import exceptions as es_exceptions | ||
from elasticsearch_dsl.connections import connections | ||
from elasticsearch_metrics.registry import registry as es_metrics_registry | ||
|
||
from website import settings as website_settings | ||
|
||
|
||
@contextlib.contextmanager | ||
def es_metrics_temps(es6_client=None): | ||
if es6_client is None: | ||
connections.create_connection(hosts=[website_settings.ELASTIC6_URI]) | ||
es6_client = connections.get_connection() | ||
_temp_prefix = 'temp_metrics_' | ||
_temp_wildcard = f'{_temp_prefix}*' | ||
|
||
def _teardown_es_temps(): | ||
es6_client.indices.delete(index=_temp_wildcard) | ||
try: | ||
es6_client.indices.delete_template(_temp_wildcard) | ||
except es_exceptions.NotFoundError: | ||
pass | ||
|
||
@contextlib.contextmanager | ||
def _mock_metric_names(): | ||
with contextlib.ExitStack() as _exit: | ||
for _metric_class in es_metrics_registry.get_metrics(): | ||
_exit.enter_context(mock.patch.object( | ||
_metric_class, | ||
'_template_name', # also used to construct index names | ||
f'{_temp_prefix}{_metric_class._template_name}', | ||
)) | ||
_exit.enter_context(mock.patch.object( | ||
_metric_class, | ||
'_template', # a wildcard string for indexes and templates | ||
f'{_temp_prefix}{_metric_class._template}', | ||
)) | ||
yield | ||
|
||
_teardown_es_temps() | ||
with _mock_metric_names(): | ||
call_command('sync_metrics') | ||
yield | ||
_teardown_es_temps() |