<commit_before>'''py.test fixtures for Pyramid.

http://pyramid.readthedocs.org/en/latest/narr/testing.html
'''
import logging
import pytest
import webtest
import os
import tempfile
import subprocess
import time

from pyramid.request import apply_request_extensions
from pyramid.testing import DummyRequest, setUp, tearDown
from pyramid.threadlocal import get_current_registry, manager as threadlocal_manager
from snovault import DBSESSION, ROOT, UPGRADER
from snovault.elasticsearch import ELASTIC_SEARCH
from .. import main
from .conftest_settings import make_app_settings_dictionary


# Done in pytest.ini now.
#
# pytest_plugins = [
#     'encoded.tests.datafixtures',
#     'snovault.tests.serverfixtures',
# ]


@pytest.fixture(autouse=True)
def autouse_external_tx(external_tx):
    pass


@pytest.fixture(scope='session')
def app_settings(request, wsgi_server_host_port, conn, DBSession):
    settings = make_app_settings_dictionary()
    settings['auth0.audiences'] = 'http://%s:%s' % wsgi_server_host_port
    # add some here for file testing
    settings[DBSESSION] = DBSession
    return settings


def pytest_configure():
    logging.basicConfig(format='%(message)s')
    logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)

    class Shorten(logging.Filter):
        max_len = 500

        def filter(self, record):
            if record.msg == '%r':
                record.msg = record.msg % record.args
                record.args = ()
            if len(record.msg) > self.max_len:
                record.msg = record.msg[:self.max_len] + '...'
            return True

    logging.getLogger('sqlalchemy.engine.base.Engine').addFilter(Shorten())


@pytest.yield_fixture
def config():
    # From https://docs.pylonsproject.org/projects/pyramid/en/latest/api/testing.html#pyramid.testing.setUp
    # setUp:
    #   Set Pyramid registry and request thread locals for the duration of a single unit test.
    #   Use this function in the setUp method of a unittest test case which directly or indirectly uses:
    #     * any method of the pyramid.config.Configurator object returned by this function.
    #     * the pyramid.threadlocal.get_current_registry() or pyramid.threadlocal.get_current_request() functions.
    # tearDown:
    #   Undo the effects of pyramid.testing.setUp(). Use this function in the tearDown method of a unit test
    #   that uses pyramid.testing.setUp() in its setUp method.
    #
    # The recommended use with unittest can be found here:
    # https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/testing.html#test-set-up-and-tear-down
    #   class MyTest(unittest.TestCase):
    #     def setUp(self):
    #       self.config = testing.setUp()
    #     def tearDown(self):
    #       testing.tearDown()
    # This is the approximate equivalent in pyTest:

    # TODO: Reonsider whether this setup/teardown is being done correctly
    #  Then again, this fixture might not be used at all. I inserted this here and it didn't fail the tests:
    #     raise Exception("fixture config used")
    #  -kmp 28-Jun-2020
    the_config = setUp()
    yield the_config
    tearDown()


@pytest.yield_fixture
def threadlocals(request, dummy_request, registry):
    threadlocal_manager.push({'request': dummy_request, 'registry': registry})
    yield dummy_request
    threadlocal_manager.pop()


class MyDummyRequest(DummyRequest):
    def remove_conditional_headers(self):
        pass

    def _get_registry(self):
        if self._registry is None:
            return get_current_registry()
        return self._registry

    def _set_registry(self, registry):
        self.__dict__['registry'] = registry

    def _del_registry(self):
        self._registry = None

    registry = property(_get_registry, _set_registry, _del_registry)


@pytest.fixture
def dummy_request(root, registry, app):
    request = app.request_factory.blank('/dummy')
    request.root = root
    request.registry = registry
    request._stats = {}
    request.invoke_subrequest = app.invoke_subrequest
    apply_request_extensions(request)
    return request


@pytest.fixture(scope='session')
def app(app_settings):
    '''WSGI application level functional testing.
    '''
    return main({}, **app_settings)


@pytest.fixture
def registry(app):
    return app.registry<commit_msg>src/encoded/tests/conftest.py: remove the unused 'config' fixture.<commit_after>"""py.test fixtures for Pyramid.

http://pyramid.readthedocs.org/en/latest/narr/testing.html
"""

import datetime as datetime_module
import logging
import os
import pkg_resources
import pytest
import webtest

from dcicutils.qa_utils import notice_pytest_fixtures
from pyramid.request import apply_request_extensions
from pyramid.testing import DummyRequest
from pyramid.threadlocal import get_current_registry, manager as threadlocal_manager
from snovault import DBSESSION, ROOT, UPGRADER
from snovault.elasticsearch import ELASTIC_SEARCH, create_mapping
from snovault.util import generate_indexer_namespace_for_testing
from .. import main
from .conftest_settings import make_app_settings_dictionary


# Done in pytest.ini now.
#
# pytest_plugins = [
#     'encoded.tests.datafixtures',
#     'snovault.tests.serverfixtures',
# ]


@pytest.fixture(autouse=True)
def autouse_external_tx(external_tx):
    pass


@pytest.fixture(scope='session')
def app_settings(request, wsgi_server_host_port, conn, DBSession):
    settings = make_app_settings_dictionary()
    settings['auth0.audiences'] = 'http://%s:%s' % wsgi_server_host_port
    # add some here for file testing
    settings[DBSESSION] = DBSession
    return settings


def pytest_configure():
    logging.basicConfig(format='%(message)s')
    logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)

    class Shorten(logging.Filter):
        max_len = 500

        def filter(self, record):
            if record.msg == '%r':
                record.msg = record.msg % record.args
                record.args = ()
            if len(record.msg) > self.max_len:
                record.msg = record.msg[:self.max_len] + '...'
            return True

    logging.getLogger('sqlalchemy.engine.base.Engine').addFilter(Shorten())


@pytest.yield_fixture
def threadlocals(request, dummy_request, registry):
    threadlocal_manager.push({'request': dummy_request, 'registry': registry})
    yield dummy_request
    threadlocal_manager.pop()


class MyDummyRequest(DummyRequest):
    def remove_conditional_headers(self):
        pass

    def _get_registry(self):
        if self._registry is None:
            return get_current_registry()
        return self._registry

    def _set_registry(self, registry):
        self.__dict__['registry'] = registry

    def _del_registry(self):
        self._registry = None

    registry = property(_get_registry, _set_registry, _del_registry)


@pytest.fixture
def dummy_request(root, registry, app):
    request = app.request_factory.blank('/dummy')
    request.root = root
    request.registry = registry
    request._stats = {}
    request.invoke_subrequest = app.invoke_subrequest
    apply_request_extensions(request)
    return request


@pytest.fixture(scope='session')
def app(app_settings):
    """WSGI application level functional testing.
    """
    return main({}, **app_settings)


@pytest.fixture
def registry(app):
    return app.registry
{'fraction_non_alphanumeric': 0.09719956498096792, 'fraction_numerical': 0.0019032082653616096, 'mean_word_length': 3.6533839342188488, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2242675', 'n_tokens_mistral': 2252, 'n_tokens_neox': 2182, 'n_words': 522}