<commit_before># -*- coding: utf-8 -*-
# vispy: testskip
# Copyright (c) 2014, 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_backend, has_application, nottest


_line_sep = '-' * 70


def _get_root_dir():
    root_dir = os.getcwd()
    if (op.isfile(op.join(root_dir, 'setup.py')) and
            op.isdir(op.join(root_dir, 'vispy'))):
        dev = True
    else:
        root_dir = op.abspath(op.join(op.dirname(__file__), '..', '..'))
        dev = True if op.isfile(op.join(root_dir, 'setup.py')) else False
    return root_dir, dev


_nose_script = """
# Code inspired by original nose plugin:
# https://nose.readthedocs.org/en/latest/plugins/cover.html

import nose
from nose.plugins.base import Plugin


class MutedCoverage(Plugin):
    '''Make a silent coverage report using Ned Batchelder's coverage module.'''

    def configure(self, options, conf):
        Plugin.configure(self, options, conf)
        self.enabled = True
        try:
            from coverage import coverage
        except ImportError:
            self.enabled = False
            self.cov = None
            print('Module "coverage" not installed, code coverage will not '
                  'be available')
        else:
            self.enabled = True
            self.cov = coverage(auto_data=False, branch=True, data_suffix=None,
                                source=['vispy'])

    def begin(self):
        self.cov.load()
        self.cov.start()

    def report(self, stream):
        self.cov.stop()
        self.cov.combine()
        self.cov.save()


try:
    import faulthandler
    faulthandler.enable()
except Exception:
    pass

nose.main(argv=%r%s)
"""


def _nose(mode, extra_arg_string):
    """Run nosetests using a particular mode"""
    cwd = os.getcwd()  # this must be done before nose import
    try:
        import nose  # noqa, analysis:ignore
    except ImportError:
        print('Skipping nosetests, nose not installed')
        raise SkipTest()

    if mode == 'nobackend':
        msg = 'Running tests with no backend'
        extra_arg_string = '-a !vispy_app_test ' + extra_arg_string
        extra_arg_string = '-e experimental -e wiki ' + extra_arg_string
        coverage = True
    elif mode == 'singlefile':
        fname = extra_arg_string.split(' ')[0]
        assert op.isfile(fname)
        msg = 'Running tests for individual file'
        coverage = False
    else:
        with use_log_level('warning', print_msg=False):
            has, why_not = has_backend(mode, out=['why_not'])
        if not has:
            msg = ('Skipping tests for backend %s, not found (%s)'
                   % (mode, why_not))
            print(_line_sep + '\n' + msg + '\n' + _line_sep + '\n')
            raise SkipTest(msg)
        msg = 'Running tests with %s backend' % mode
        extra_arg_string = '-a vispy_app_test ' + extra_arg_string
        coverage = True
    coverage = ', addplugins=[MutedCoverage()]' if coverage else ''
    args = ['nosetests'] + extra_arg_string.strip().split(' ')
    # make a call to "python" so that it inherits whatever the system
    # thinks is "python" (e.g., virtualenvs)
    cmd = [sys.executable, '-c', _nose_script % (args, coverage)]
    env = deepcopy(os.environ)
    if mode in ('singlefile',):
        env_str = ''
    else:
        # 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))
        env_str = '_VISPY_TESTING_APP=%s ' % mode
    if len(msg) > 0:
        msg = ('%s\n%s:\n%s%s'
               % (_line_sep, msg, env_str, ' '.join(args)))
        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('Nose failure (%s)' % return_code)


def _flake():
    """Test flake8"""
    orig_dir = os.getcwd()
    root_dir, dev = _get_root_dir()
    os.chdir(root_dir)
    if dev:
        sys.argv[1:] = ['vispy', 'examples', 'make']
    else:
        sys.argv[1:] = ['vispy']
    sys.argv.append('--ignore=E226,E241,E265,W291,W293')
    sys.argv.append('--exclude=six.py,py24_ordereddict.py,glfw.py,'
                    '_proxy.py,_es2.py,_desktop.py,_pyopengl.py,'
                    '_constants.py,png.py,decorator.py,'
                    'experimental,wiki,_old')
    try:
        from flake8.main import main
    except ImportError:
        print('Skipping flake8 test, flake8 not installed')
    else:
        print('Running flake8... ')  # if end='', first error gets ugly
        sys.stdout.flush()
        try:
            main()
        except SystemExit as ex:
            if ex.code in (None, 0):
                pass  # do not exit yet, we want to print a success msg
            else:
                raise RuntimeError('flake8 failed')
    finally:
        os.chdir(orig_dir)


def _check_line_endings():
    """Check all files in the repository for CR characters"""
    if sys.platform == 'win32':
        print('Skipping line endings check on Windows')
        sys.stdout.flush()
        return
    print('Running line endings check... ')
    sys.stdout.flush()
    report = []<commit_msg>Disabling formatting checks for inputhook.py, copied from the iPython 3.x branch.<commit_after># -*- coding: utf-8 -*-
# vispy: testskip
# Copyright (c) 2014, 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_backend, has_application, nottest


_line_sep = '-' * 70


def _get_root_dir():
    root_dir = os.getcwd()
    if (op.isfile(op.join(root_dir, 'setup.py')) and
            op.isdir(op.join(root_dir, 'vispy'))):
        dev = True
    else:
        root_dir = op.abspath(op.join(op.dirname(__file__), '..', '..'))
        dev = True if op.isfile(op.join(root_dir, 'setup.py')) else False
    return root_dir, dev


_nose_script = """
# Code inspired by original nose plugin:
# https://nose.readthedocs.org/en/latest/plugins/cover.html

import nose
from nose.plugins.base import Plugin


class MutedCoverage(Plugin):
    '''Make a silent coverage report using Ned Batchelder's coverage module.'''

    def configure(self, options, conf):
        Plugin.configure(self, options, conf)
        self.enabled = True
        try:
            from coverage import coverage
        except ImportError:
            self.enabled = False
            self.cov = None
            print('Module "coverage" not installed, code coverage will not '
                  'be available')
        else:
            self.enabled = True
            self.cov = coverage(auto_data=False, branch=True, data_suffix=None,
                                source=['vispy'])

    def begin(self):
        self.cov.load()
        self.cov.start()

    def report(self, stream):
        self.cov.stop()
        self.cov.combine()
        self.cov.save()


try:
    import faulthandler
    faulthandler.enable()
except Exception:
    pass

nose.main(argv=%r%s)
"""


def _nose(mode, extra_arg_string):
    """Run nosetests using a particular mode"""
    cwd = os.getcwd()  # this must be done before nose import
    try:
        import nose  # noqa, analysis:ignore
    except ImportError:
        print('Skipping nosetests, nose not installed')
        raise SkipTest()

    if mode == 'nobackend':
        msg = 'Running tests with no backend'
        extra_arg_string = '-a !vispy_app_test ' + extra_arg_string
        extra_arg_string = '-e experimental -e wiki ' + extra_arg_string
        coverage = True
    elif mode == 'singlefile':
        fname = extra_arg_string.split(' ')[0]
        assert op.isfile(fname)
        msg = 'Running tests for individual file'
        coverage = False
    else:
        with use_log_level('warning', print_msg=False):
            has, why_not = has_backend(mode, out=['why_not'])
        if not has:
            msg = ('Skipping tests for backend %s, not found (%s)'
                   % (mode, why_not))
            print(_line_sep + '\n' + msg + '\n' + _line_sep + '\n')
            raise SkipTest(msg)
        msg = 'Running tests with %s backend' % mode
        extra_arg_string = '-a vispy_app_test ' + extra_arg_string
        coverage = True
    coverage = ', addplugins=[MutedCoverage()]' if coverage else ''
    args = ['nosetests'] + extra_arg_string.strip().split(' ')
    # make a call to "python" so that it inherits whatever the system
    # thinks is "python" (e.g., virtualenvs)
    cmd = [sys.executable, '-c', _nose_script % (args, coverage)]
    env = deepcopy(os.environ)
    if mode in ('singlefile',):
        env_str = ''
    else:
        # 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))
        env_str = '_VISPY_TESTING_APP=%s ' % mode
    if len(msg) > 0:
        msg = ('%s\n%s:\n%s%s'
               % (_line_sep, msg, env_str, ' '.join(args)))
        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('Nose failure (%s)' % return_code)


def _flake():
    """Test flake8"""
    orig_dir = os.getcwd()
    root_dir, dev = _get_root_dir()
    os.chdir(root_dir)
    if dev:
        sys.argv[1:] = ['vispy', 'examples', 'make']
    else:
        sys.argv[1:] = ['vispy']
    sys.argv.append('--ignore=E226,E241,E265,W291,W293')
    sys.argv.append('--exclude=six.py,py24_ordereddict.py,glfw.py,'
                    '_proxy.py,_es2.py,_desktop.py,_pyopengl.py,'
                    '_constants.py,png.py,decorator.py,inputhook.py,'
                    'experimental,wiki,_old')
    try:
        from flake8.main import main
    except ImportError:
        print('Skipping flake8 test, flake8 not installed')
    else:
        print('Running flake8... ')  # if end='', first error gets ugly
        sys.stdout.flush()
        try:
            main()
        except SystemExit as ex:
            if ex.code in (None, 0):
                pass  # do not exit yet, we want to print a success msg
            else:
                raise RuntimeError('flake8 failed')
    finally:
        os.chdir(orig_dir)


def _check_line_endings():
    """Check all files in the repository for CR characters"""
    if sys.platform == 'win32':
        print('Skipping line endings check on Windows')
        sys.stdout.flush()
        return
    print('Running line endings check... ')
    sys.stdout.flush()
    report = []
{'fraction_non_alphanumeric': 0.11915949995566982, 'fraction_numerical': 0.00700416703608476, 'mean_word_length': 2.354148082069581, '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': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3484290', 'n_tokens_mistral': 3573, 'n_tokens_neox': 3461, 'n_words': 962}