<commit_before># -*- coding: utf-8 -*-
# vispy: testskip
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""Test running functions"""

from __future__ import print_function

import sys
import os
from os import path as op
from copy import deepcopy
from functools import partial

from ..util import use_log_level, run_subprocess
from ..util.ptime import time
from ._testing import SkipTest, has_application, nottest


_line_sep = '-' * 70


def _get_import_dir():
    import_dir = op.abspath(op.join(op.dirname(__file__), '..'))
    up_dir = op.join(import_dir, '..')
    if (op.isfile(op.join(up_dir, 'setup.py')) and
            op.isdir(op.join(up_dir, 'vispy')) and
            op.isdir(op.join(up_dir, 'examples'))):
        dev = True
    else:
        dev = False
    return import_dir, dev


_unit_script = """
try:
    import pytest as tester
except ImportError:
    import nose as tester
try:
    import faulthandler
    faulthandler.enable()
except Exception:
    pass

raise SystemExit(tester.main(%r))
"""


def _unit(mode, extra_arg_string, coverage=False):
    """Run unit tests using a particular mode"""
    import_dir = _get_import_dir()[0]
    cwd = op.abspath(op.join(import_dir, '..'))
    extra_args = [''] + extra_arg_string.split(' ')
    del extra_arg_string
    use_pytest = False
    try:
        import pytest  # noqa, analysis:ignore
        use_pytest = True
    except ImportError:
        try:
            import nose  # noqa, analysis:ignore
        except ImportError:
            raise SkipTest('Skipping unit tests, pytest not installed')

    if mode == 'nobackend':
        msg = 'Running tests with no backend'
        if use_pytest:
            extra_args += ['-m', '"not vispy_app_test"']
        else:
            extra_args += ['-a', '"!vispy_app_test"']
    else:
        msg = 'Running tests with %s backend' % mode
        if use_pytest:
            extra_args += ['-m', 'vispy_app_test']
        else:
            extra_args += ['-a', 'vispy_app_test']
    if coverage and use_pytest:
        extra_args += ['--cov', 'vispy', '--no-cov-on-fail']
    # make a call to "python" so that it inherits whatever the system
    # thinks is "python" (e.g., virtualenvs)
    extra_arg_string = ' '.join(extra_args)
    insert = extra_arg_string if use_pytest else extra_args
    extra_args += [import_dir]  # positional argument
    cmd = [sys.executable, '-c', _unit_script % insert]
    env = deepcopy(os.environ)

    # We want to set this for all app backends plus "nobackend" to
    # help ensure that app tests are appropriately decorated
    env.update(dict(_VISPY_TESTING_APP=mode, VISPY_IGNORE_OLD_VERSION='true'))
    env_str = '_VISPY_TESTING_APP=%s ' % mode
    if len(msg) > 0:
        msg = ('%s\n%s:\n%s%s'
               % (_line_sep, msg, env_str, extra_arg_string))
        print(msg)
    sys.stdout.flush()
    return_code = run_subprocess(cmd, return_code=True, cwd=cwd,
                                 env=env, stdout=None, stderr=None)[2]
    if return_code:
        raise RuntimeError('unit failure (%s)' % return_code)
    if coverage:
        # Running a py.test with coverage will wipe out any files that
        # exist as .coverage or .coverage.*. It should work to pass
        # COVERAGE_FILE env var when doing run_subprocess above, but
        # it does not. Therefore we instead use our own naming scheme,
        # and in Travis when we combine them, use COVERAGE_FILE with the
        # `coverage combine` command.
        out_name = op.join(cwd, '.vispy-coverage.%s' % mode)
        if op.isfile(out_name):
            os.remove(out_name)
        os.rename(op.join(cwd, '.coverage'), out_name)


def _docs():
    """test docstring paramters
    using vispy/utils/tests/test_docstring_parameters.py"""
    print("warning: this imports vispy from the vispy installation. it is"
          " recommended to setup vispy using 'python setup.py develop'"
          " so that the latest sources are used automatically")
    try:
        # this should always be importable
        from vispy.util.tests import test_docstring_parameters
        print("Running docstring test...")
        test_docstring_parameters.test_docstring_parameters()
    except AssertionError as docstring_violations:
        # the test harness expects runtime errors,
        # not AssertionError. So wrap the AssertionError
        # that is thrown by test_docstring_parameters()
        # with a RuntimeError
        raise RuntimeError(docstring_violations)


def _flake():
    """Test flake8"""
    orig_dir = os.getcwd()
    import_dir, dev = _get_import_dir()
    os.chdir(op.join(import_dir, '..'))
    if dev:
        sys.argv[1:] = ['vispy', 'examples', 'make']
    else:
        sys.argv[1:] = [op.basename(import_dir)]
    sys.argv.append('--ignore=E226,E241,E265,E266,W291,W293,W503')
    sys.argv.append('--exclude=six.py,ordereddict.py,glfw.py,'
                    '_proxy.py,_es2.py,_gl2.py,_pyopengl2.py,'
                    '_constants.py,png.py,decorator.py,ipy_inputhook.py,'
                    'experimental,wiki,_old,mplexporter.py,cubehelix.py')<commit_msg>fix capitalization. use heuristic to check if docs is run from a develop setup<commit_after># -*- coding: utf-8 -*-
# vispy: testskip
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""Test running functions"""

from __future__ import print_function

import sys
import os
import warnings
from os import path as op
from copy import deepcopy
from functools import partial

from ..util import use_log_level, run_subprocess
from ..util.ptime import time
from ._testing import SkipTest, has_application, nottest


_line_sep = '-' * 70


def _get_import_dir():
    import_dir = op.abspath(op.join(op.dirname(__file__), '..'))
    up_dir = op.join(import_dir, '..')
    if (op.isfile(op.join(up_dir, 'setup.py')) and
            op.isdir(op.join(up_dir, 'vispy')) and
            op.isdir(op.join(up_dir, 'examples'))):
        dev = True
    else:
        dev = False
    return import_dir, dev


_unit_script = """
try:
    import pytest as tester
except ImportError:
    import nose as tester
try:
    import faulthandler
    faulthandler.enable()
except Exception:
    pass

raise SystemExit(tester.main(%r))
"""


def _unit(mode, extra_arg_string, coverage=False):
    """Run unit tests using a particular mode"""
    import_dir = _get_import_dir()[0]
    cwd = op.abspath(op.join(import_dir, '..'))
    extra_args = [''] + extra_arg_string.split(' ')
    del extra_arg_string
    use_pytest = False
    try:
        import pytest  # noqa, analysis:ignore
        use_pytest = True
    except ImportError:
        try:
            import nose  # noqa, analysis:ignore
        except ImportError:
            raise SkipTest('Skipping unit tests, pytest not installed')

    if mode == 'nobackend':
        msg = 'Running tests with no backend'
        if use_pytest:
            extra_args += ['-m', '"not vispy_app_test"']
        else:
            extra_args += ['-a', '"!vispy_app_test"']
    else:
        msg = 'Running tests with %s backend' % mode
        if use_pytest:
            extra_args += ['-m', 'vispy_app_test']
        else:
            extra_args += ['-a', 'vispy_app_test']
    if coverage and use_pytest:
        extra_args += ['--cov', 'vispy', '--no-cov-on-fail']
    # make a call to "python" so that it inherits whatever the system
    # thinks is "python" (e.g., virtualenvs)
    extra_arg_string = ' '.join(extra_args)
    insert = extra_arg_string if use_pytest else extra_args
    extra_args += [import_dir]  # positional argument
    cmd = [sys.executable, '-c', _unit_script % insert]
    env = deepcopy(os.environ)

    # We want to set this for all app backends plus "nobackend" to
    # help ensure that app tests are appropriately decorated
    env.update(dict(_VISPY_TESTING_APP=mode, VISPY_IGNORE_OLD_VERSION='true'))
    env_str = '_VISPY_TESTING_APP=%s ' % mode
    if len(msg) > 0:
        msg = ('%s\n%s:\n%s%s'
               % (_line_sep, msg, env_str, extra_arg_string))
        print(msg)
    sys.stdout.flush()
    return_code = run_subprocess(cmd, return_code=True, cwd=cwd,
                                 env=env, stdout=None, stderr=None)[2]
    if return_code:
        raise RuntimeError('unit failure (%s)' % return_code)
    if coverage:
        # Running a py.test with coverage will wipe out any files that
        # exist as .coverage or .coverage.*. It should work to pass
        # COVERAGE_FILE env var when doing run_subprocess above, but
        # it does not. Therefore we instead use our own naming scheme,
        # and in Travis when we combine them, use COVERAGE_FILE with the
        # `coverage combine` command.
        out_name = op.join(cwd, '.vispy-coverage.%s' % mode)
        if op.isfile(out_name):
            os.remove(out_name)
        os.rename(op.join(cwd, '.coverage'), out_name)


def _docs():
    """test docstring paramters
    using vispy/utils/tests/test_docstring_parameters.py"""
    dev = _get_import_dir()[1]

    if not dev:
        warnings.warn("Docstring test imports Vispy from"
                      " Vispy's installation. It is"
                      " recommended to setup Vispy using"
                      " 'python setup.py develop'"
                      " so that the latest sources are used automatically")
    try:
        # this should always be importable
        from vispy.util.tests import test_docstring_parameters
        print("Running docstring test...")
        test_docstring_parameters.test_docstring_parameters()
    except AssertionError as docstring_violations:
        # the test harness expects runtime errors,
        # not AssertionError. So wrap the AssertionError
        # that is thrown by test_docstring_parameters()
        # with a RuntimeError
        raise RuntimeError(docstring_violations)


def _flake():
    """Test flake8"""
    orig_dir = os.getcwd()
    import_dir, dev = _get_import_dir()
    os.chdir(op.join(import_dir, '..'))
    if dev:
        sys.argv[1:] = ['vispy', 'examples', 'make']
    else:
        sys.argv[1:] = [op.basename(import_dir)]
    sys.argv.append('--ignore=E226,E241,E265,E266,W291,W293,W503')
    sys.argv.append('--exclude=six.py,ordereddict.py,glfw.py,'
                    '_proxy.py,_es2.py,_gl2.py,_pyopengl2.py,'
                    '_constants.py,png.py,decorator.py,ipy_inputhook.py,'
                    'experimental,wiki,_old,mplexporter.py,cubehelix.py')
{'fraction_non_alphanumeric': 0.1124952812382031, 'fraction_numerical': 0.007078142695356738, 'mean_word_length': 2.687195546276966, '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': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6312838', 'n_tokens_mistral': 3433, 'n_tokens_neox': 3348, 'n_words': 908}