<commit_before>import os
import tempfile
import shutil
import subprocess
import time
import errno
import logging

import pytest

from pytest_server_fixtures import CONFIG
from pytest_fixture_config import requires_config

from .base import TestServer

log = logging.getLogger(__name__)


def _mongo_server():
    """ This does the actual work - there are several versions of this used
        with different scopes.
    """
    test_server = MongoTestServer()
    try:
        test_server.start()
        yield test_server
    finally:
        test_server.teardown()


@requires_config(CONFIG, ['mongo_bin'])
@pytest.yield_fixture(scope='function')
def mongo_server():
    """ Function-scoped MongoDB server started in a local thread.
        This also provides a temp workspace.
        We tear down, and cleanup mongos at the end of the test.

        For completeness, we tidy up any outstanding mongo temp directories
        at the start and end of each test session

        Attributes
        ----------
        api (`pymongo.MongoClient`)  : PyMongo Client API connected to this server
        .. also inherits all attributes from the `workspace` fixture
    """
    for server in _mongo_server():
        yield server


@requires_config(CONFIG, ['mongo_bin'])
@pytest.fixture(scope='session')
def mongo_server_sess():
    """ Same as mongo_server fixture, scoped as session instead.
    """
    for server in _mongo_server():
        yield server


@requires_config(CONFIG, ['mongo_bin'])
@pytest.fixture(scope='class')
def mongo_server_cls(request):
    """ Same as mongo_server fixture, scoped for test classes.
    """
    for server in _mongo_server():
        request.cls.mongo_server = server
        yield server


class MongoTestServer(TestServer):
    # Use a random port for Mongo, as we run tests in parallel
    random_port = True

    def __init__(self, **kwargs):
        mongod_dir = tempfile.mkdtemp(dir=self.get_base_dir())
        super(MongoTestServer, self).__init__(workspace=mongod_dir, delete=True, **kwargs)

    @staticmethod
    def get_base_dir():
        candidate_dir = os.environ.get('WORKSPACE', None)
        if not candidate_dir or not os.path.exists(candidate_dir):
            candidate_dir = os.environ.get('TMDDIR', '/tmp')

        candidate_dir = os.path.join(candidate_dir, 'mongo')
        if not os.path.exists(candidate_dir):
            try:
                os.makedirs(candidate_dir)
            except OSError as exc:  # Python >2.5
                if exc.errno == errno.EEXIST and os.path.isdir(candidate_dir):
                    pass
                else:
                    raise
        return candidate_dir

    @property
    def run_cmd(self):
        return ['%s/mongod' % CONFIG.mongo_bin,
                '--bind_ip=%s' % self.hostname,
                '--port=%s' % self.port,
                '--dbpath=%s' % self.workspace,
                '--nounixsocket',<commit_msg>Correct fixture config and tempdir for mongo server<commit_after>import os
import tempfile
import shutil
import subprocess
import time
import errno
import logging

import pytest

from pytest_server_fixtures import CONFIG
from pytest_fixture_config import yield_requires_config

from .base import TestServer

log = logging.getLogger(__name__)


def _mongo_server():
    """ This does the actual work - there are several versions of this used
        with different scopes.
    """
    test_server = MongoTestServer()
    try:
        test_server.start()
        yield test_server
    finally:
        test_server.teardown()


@yield_requires_config(CONFIG, ['mongo_bin'])
@pytest.yield_fixture(scope='function')
def mongo_server():
    """ Function-scoped MongoDB server started in a local thread.
        This also provides a temp workspace.
        We tear down, and cleanup mongos at the end of the test.

        For completeness, we tidy up any outstanding mongo temp directories
        at the start and end of each test session

        Attributes
        ----------
        api (`pymongo.MongoClient`)  : PyMongo Client API connected to this server
        .. also inherits all attributes from the `workspace` fixture
    """
    for server in _mongo_server():
        yield server


@yield_requires_config(CONFIG, ['mongo_bin'])
@pytest.yield_fixture(scope='session')
def mongo_server_sess():
    """ Same as mongo_server fixture, scoped as session instead.
    """
    for server in _mongo_server():
        yield server


@yield_requires_config(CONFIG, ['mongo_bin'])
@pytest.yield_fixture(scope='class')
def mongo_server_cls(request):
    """ Same as mongo_server fixture, scoped for test classes.
    """
    for server in _mongo_server():
        request.cls.mongo_server = server
        yield server


@yield_requires_config(CONFIG, ['mongo_bin'])
@pytest.yield_fixture(scope='module')
def mongo_server_module():
    """ Same as mongo_server fixture, scoped for test modules.
    """
    for server in _mongo_server():
        yield server


class MongoTestServer(TestServer):
    # Use a random port for Mongo, as we run tests in parallel
    random_port = True

    def __init__(self, **kwargs):
        mongod_dir = tempfile.mkdtemp(dir=self.get_base_dir())
        super(MongoTestServer, self).__init__(workspace=mongod_dir, delete=True, **kwargs)

    @staticmethod
    def get_base_dir():
        candidate_dir = os.environ.get('WORKSPACE', None)
        if not candidate_dir or not os.path.exists(candidate_dir):
            candidate_dir = os.environ.get('TMPDIR', '/tmp')

        candidate_dir = os.path.join(candidate_dir, 'mongo')
        if not os.path.exists(candidate_dir):
            try:
                os.makedirs(candidate_dir)
            except OSError as exc:  # Python >2.5
                if exc.errno == errno.EEXIST and os.path.isdir(candidate_dir):
                    pass
                else:
                    raise
        return candidate_dir

    @property
    def run_cmd(self):
        return ['%s/mongod' % CONFIG.mongo_bin,
                '--bind_ip=%s' % self.hostname,
                '--port=%s' % self.port,
                '--dbpath=%s' % self.workspace,
                '--nounixsocket',
{'fraction_non_alphanumeric': 0.09486102133160956, 'fraction_numerical': 0.0006464124111182935, 'mean_word_length': 2.651327433628319, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, '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': '368920', 'n_tokens_mistral': 1857, 'n_tokens_neox': 1803, 'n_words': 517}