1from os.path import dirname
2import sys
3
4# When using tox, it can accidentally pick up a {pymssql,_mssql}.so file in the
5# root directory and then get ImportError because of incompatibility in Python
6# versions. By removing the root directory from the sys.path, it forces tox to
7# import the library from correct place in the tox virtualenv.
8if '.tox' in sys.executable:
9    root_dir = dirname(dirname(__file__))
10    sys.path.remove(root_dir)
11
12import decimal
13import os
14try:
15    # Python 2
16    from ConfigParser import ConfigParser
17except ImportError:
18    # Python 3
19    from configparser import ConfigParser
20
21import pytest
22
23import tests.helpers as th
24from .helpers import cfgpath, clear_db, get_app_lock, release_app_lock
25
26_parser = ConfigParser({
27    'server': 'localhost',
28    'username': 'sa',
29    'password': '',
30    'database': 'tempdb',
31    'port': '1433',
32    'ipaddress': '127.0.0.1',
33    'instance': '',
34})
35
36def pytest_addoption(parser):
37    parser.addoption(
38        "--pymssql-section",
39        type="string",
40        default=os.environ.get('PYMSSQL_TEST_CONFIG', 'DEFAULT'),
41        help="The name of the section to use from tests.cfg"
42    )
43
44def pytest_configure(config):
45    _parser.read(cfgpath)
46    section = config.getoption('--pymssql-section')
47
48    if not _parser.has_section(section) and section != 'DEFAULT':
49        raise ValueError('the tests.cfg file does not have section: %s' % section)
50
51    th.config.server = os.getenv('PYMSSQL_TEST_SERVER') or _parser.get(section, 'server')
52    th.config.user = os.getenv('PYMSSQL_TEST_USERNAME') or _parser.get(section, 'username')
53    th.config.password = os.getenv('PYMSSQL_TEST_PASSWORD') or _parser.get(section, 'password')
54    th.config.database = os.getenv('PYMSSQL_TEST_DATABASE') or _parser.get(section, 'database')
55    th.config.port = os.getenv('PYMSSQL_TEST_PORT') or _parser.get(section, 'port')
56    th.config.ipaddress = os.getenv('PYMSSQL_TEST_IPADDRESS') or _parser.get(section, 'ipaddress')
57    th.config.instance = os.getenv('PYMSSQL_TEST_INSTANCE') or _parser.get(section, 'instance')
58    th.config.orig_decimal_prec = decimal.getcontext().prec
59    th.mark_slow = pytest.mark.slow
60    th.skip_test = pytest.skip
61
62    get_app_lock()
63    clear_db()
64
65def pytest_unconfigure(config):
66    release_app_lock()
67