# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
"""Tests runner."""

# Standard library imports
import os
import sys

# Third party imports
import pytest
import qtpy

qtpy

# Constants
HERE = os.path.dirname(os.path.abspath(__file__))
MAC = sys.platform == 'darwin'
WIN = os.name == 'nt'
LINUX = sys.platform.startswith('linux')
PYTEST_XDIST = True

PY2 = sys.version_info.major == 2
PY3 = sys.version_info.major == 3

try:
    import xdist
    xdist
except ImportError:
    PYTEST_XDIST = False


def update_covarage_rc():
    """Add no cover lines based on operating system."""
    coverage_path = os.path.join(HERE, '.coveragerc')
    coverage_rc_content = """# This file is autogenerated by runscripts.py
# Do not make changes here!!!
[run]
omit =
    */tests/*
    */external/*
    */app/Navigator.app/*
[report]
fail_under = 0
show_missing = true
skip_covered = true
exclude_lines =
    pragma: no cover
    def local_test():
    if __name__ == .__main__.:"""

    updated_content = coverage_rc_content
    if WIN:
        updated_content += '\n    pragma: no cover unix'
        updated_content += '\n    pragma: no cover mac'
        updated_content += '\n    pragma: no cover linux'
    elif MAC:
        updated_content += '\n    pragma: no cover win'
        updated_content += '\n    pragma: no cover linux'
    elif LINUX:
        updated_content += '\n    pragma: no cover win'
        updated_content += '\n    pragma: no cover mac'

    if PY2:
        updated_content += '\n    pragma: no cover py3'
    elif PY3:
        updated_content += '\n    pragma: no cover py2'

    print('\nUpdating .coveragerc with:')
    print('--------------------------')
    print(updated_content)
    with open(coverage_path, 'w') as f:
        f.write(updated_content)


update_covarage_rc()

if 'pre-commit' in sys.argv:
    pytest_args = [
        'anaconda_navigator', '-q', '--disable-warnings', '--cov-report', 'term',
        '--cov=anaconda_navigator', '--cov-fail-under=54',
    ]
else:
    pytest_args = [
        '-x',
        'anaconda_navigator',
        '-rw',
        '--durations=10',
        '--cov=anaconda_navigator',
        '--cov-report',
        'term-missing',
    ]

if PYTEST_XDIST:
    pytest_args.extend(['-n', '1'])
print('\nPytest arguments:')
print('-----------------')
print(pytest_args)
print('\n\n')
sys.exit(pytest.main(pytest_args))
