Beispiel #1
0
def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

    # MyMoney Customization: run coverage.py around tests automatically
    try:
        command = sys.argv[1]
    except IndexError:
        command = "help"

    running_tests = (command == 'test')
    if running_tests:
        from coverage import Coverage
        cov = Coverage()
        cov.erase()
        cov.start()

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?") from exc
    execute_from_command_line(sys.argv)

    if running_tests:
        cov.stop()
        cov.save()
        covered = cov.report()
        if covered < 100:
            sys.exit(0)
class TestsSuite:
    CONFIG_FILE = ".coveragerc"

    is_tests_suite_run: bool = False
    console_log_level: LogLevelEnum = LogLevelEnum.INFO
    file_log_level: LogLevelEnum = LogLevelEnum.DEBUG
    log_file_path: str = None

    __coverage: Coverage = None
    __is_coverage: bool

    def __init__(self, is_coverage: bool = False):
        self.__coverage = Coverage(config_file=self.CONFIG_FILE)
        self.__is_coverage = is_coverage
        TestsSuite.is_tests_suite_run = True
        init_logger(self.console_log_level, self.file_log_level)

    def run_tests(self):
        if self.__is_coverage:
            self.__coverage.start()

        tests = unittest.TestLoader().discover(start_dir='.',
                                               pattern='*_test.py')
        unittest.TextTestRunner(verbosity=2).run(tests)

        if self.__is_coverage:
            self.__coverage.stop()

    def create_report(self):
        self.__coverage.report()
        self.__coverage.json_report()
        self.__coverage.html_report()

    def erase_data(self):
        self.__coverage.erase()
Beispiel #3
0
def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
    try:
        from django.core.management import execute_from_command_line
        from django.conf import settings

        # MyProject Customization: run coverage.py around tests automatically
        running_tests = (sys.argv[1] == 'test')
        if running_tests:
            from coverage import Coverage
            cov = Coverage()
            cov.erase()
            cov.start()

        if settings.DEBUG:
            if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
                import ptvsd
                ptvsd.enable_attach(address = ('0.0.0.0', 3500))
                print("Attached remote debugger")
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

    if running_tests:
        cov.stop()
        cov.save()
        covered = cov.report()
        if covered < 100:
            sys.exit(1)
Beispiel #4
0
def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django-graphql.settings')
    try:
        command = sys.argv[1]
    except IndexError:
        command = "help"

    running_tests = (command == 'test')
    if running_tests:
        from coverage import Coverage
        cov = Coverage()
        cov.erase()
        cov.start()

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?") from exc
    execute_from_command_line(sys.argv)

    if running_tests:
        cov.stop()
        cov.save()
        covered = cov.report()
        if covered < 100:
            sys.exit(1)
Beispiel #5
0
def run_tests():
    config = utils.get_config()
    cov_conf_file = config.get('file_locations',
                               'coverage_in_conf',
                               fallback='config/.coveragerc')
    cov_out_file = config.get('file_locations',
                              'coverage_out_dir',
                              fallback='coverage')

    cov = Coverage(config_file=cov_conf_file)
    cov.start()

    result = grab_test_results()
    if not result.wasSuccessful():
        print("Error running unit tests ...")
        exit(1)

    cov.stop()
    cov.save()
    print('Coverage Summary:')
    cov.report()
    cov.html_report(directory=cov_out_file)
    print('HTML version: file://{0}/{1}/index.html'.format(
        os.getcwd(), cov_out_file))
    cov.erase()
    exit(0)
Beispiel #6
0
class my_test(unittest.TestCase):
    def setUp(self):
        if not os.path.exists(self._testMethodName):
            os.system('mkdir %s' % self._testMethodName)
        # 这里依赖于命名规范,include指定要测试的文件
        if self._testMethodName.startswith("test_"):
            include_name = self._testMethodName[5:]
        self.cov = Coverage(include=['comm.py', '%s.py' % include_name])
        self.cov.start()
        return super().setUp()

    def test_add(self):
        cases = deal_case(read_file("add_test.txt", is_line=True))
        for case in cases:
            result = add(case[0], case[1])
            if 0 == result['code']:
                result = result['result']
                self.assertEqual(result, float(case[2]))
            elif 1 == result['code']:
                result = result['msg']
                self.assertEqual(result, case[2])

    def tearDown(self):
        self.cov.stop()
        self.cov.save()
        self.cov.html_report(directory='%s' % self._testMethodName)
        self.cov.erase()
        return super().tearDown()
Beispiel #7
0
def main():
    """ The main function, mainly functioning to do the main functional work
        (thanks pylint)
    """
    if len(sys.argv) > 1 and sys.argv[1] == 'cover':
        # FIXME - there are enough args now to need an arg parser
        cover = Coverage(
            branch=True,
            auto_data=True,
            omit=[
                "/usr/share/pyshared/*",
                "/usr/lib/python3/dist-packages/*",
            ],
        )
        min_percent = 0

        if len(sys.argv) > 2:
            min_percent = float(sys.argv[2])
    else:
        cover = False

    loader = unittest.defaultTestLoader
    runner = unittest.TextTestRunner(verbosity=2)

    if cover:
        cover.erase()
        cover.start()

    tests = loader.discover('.')

    # If we ever drop libraries into the 'lib' subdir defined in the above
    # sys.path.insert then we will need to discover their tests and add
    # them separately with the following:
    tests_lib = loader.discover('lib', top_level_dir='lib')
    tests.addTests(tests_lib)

    result = runner.run(tests)

    if cover:
        cover.stop()
        # the debian coverage package didnt include jquery.debounce.min.js
        # (and additionally, that thing is not packaged for debian elsewhere)
        try:
            cover.html_report()
        except Exception:
            pass
        percent = cover.report(show_missing=True)

        if min_percent > percent:
            err_fmt = "The coverage ({:.1f}% reached) fails to reach the minimum required ({}%)\n"  # noqa
            sys.stderr.write(err_fmt.format(percent, min_percent))
            exit(1)

    if not result.wasSuccessful():
        exit(1)
Beispiel #8
0
    def handle(self, *args, **kwargs):  # pragma: no cover
        cov = Coverage()
        cov.erase()
        cov.start()

        super().handle(*args, **kwargs)

        cov.stop()
        cov.save()
        covered = cov.report()
        if covered < 100:
            sys.exit(1)
Beispiel #9
0
    def run(self):
        import pytest

        cov = Coverage()
        cov.erase()
        cov.start()

        result = pytest.main()

        cov.stop()
        cov.save()
        cov.html_report(directory="covhtml")
        sys.exit(int(bool(len(result.failures) > 0 or len(result.errors) > 0)))
Beispiel #10
0
    def run(self):
        import pytest

        cov = Coverage()
        cov.erase()
        cov.start()

        result = pytest.main()

        cov.stop()
        cov.save()
        cov.html_report(directory="covhtml")
        sys.exit(int(bool(len(result.failures) > 0 or len(result.errors) > 0)))
Beispiel #11
0
    def handle(self, *args, **kwargs):  # pragma: no cover
        self.stdout.write('Run test with coverage..')
        cov = Coverage(branch=True, )
        cov.erase()
        cov.start()

        super().handle(*args, **kwargs)

        cov.stop()
        cov.save()
        covered = cov.report(skip_covered=True)
        if covered < 90:
            sys.exit(1)
Beispiel #12
0
def run_test_suite():

    cov = Coverage(config_file=True)
    cov.erase()
    cov.start()

    # Announce the test suite
    sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
    sys.stdout.write(colored(text="python-xirsys", color="green", attrs=["bold"]))
    sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))

    # Announce test run
    print(colored(text="Step 1: Running unit tests.\n", color="yellow", attrs=["bold"]))

    test_suite = TestLoader().discover(str(Path("tests").absolute()))
    result = TextTestRunner(verbosity=1).run(test_suite)

    if not result.wasSuccessful():
        sys.exit(len(result.failures) + len(result.errors))

    # Announce coverage run
    print(colored(text="\nStep 2: Generating coverage results.\n", color="yellow", attrs=["bold"]))

    cov.stop()
    percentage = round(cov.report(show_missing=True), 2)
    cov.html_report(directory='cover')
    cov.save()

    if percentage < TESTS_THRESHOLD:
        print(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
                           "WAS {old}%, IS NOW {new}%.\n".format(old=TESTS_THRESHOLD, new=percentage),
                           color="red", attrs=["bold"]))
        sys.exit(1)

    # Announce flake8 run
    sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors.\n\n", color="yellow", attrs=["bold"]))

    print("pep8 errors:")
    print("----------------------------------------------------------------------")

    from subprocess import call
    flake_result = call(["flake8", ".", "--count"])
    if flake_result != 0:
        print("pep8 errors detected.")
        print(colored(text="\nYOUR CHANGES HAVE INTRODUCED PEP8 ERRORS!\n", color="red", attrs=["bold"]))
        sys.exit(flake_result)
    else:
        print("None")

    # Announce success
    print(colored(text="\nTests completed successfully with no errors. Congrats!", color="green", attrs=["bold"]))
Beispiel #13
0
def run_test_suite():

    cov = Coverage(config_file=True)
    cov.erase()
    cov.start()

    # Announce the test suite
    sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
    sys.stdout.write(colored(text="python-doc-inherit", color="green", attrs=["bold"]))
    sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))

    # Announce test run
    print(colored(text="Step 1: Running unit tests.\n", color="yellow", attrs=["bold"]))

    test_suite = TestLoader().discover(str(Path("tests").absolute()))
    result = TextTestRunner(verbosity=1).run(test_suite)

    if not result.wasSuccessful():
        sys.exit(len(result.failures) + len(result.errors))

    # Announce coverage run
    print(colored(text="\nStep 2: Generating coverage results.\n", color="yellow", attrs=["bold"]))

    cov.stop()
    percentage = round(cov.report(show_missing=True), 2)
    cov.html_report(directory='cover')
    cov.save()

    if percentage < TESTS_THRESHOLD:
        print(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
                           "WAS {old}%, IS NOW {new}%.\n".format(old=TESTS_THRESHOLD, new=percentage),
                           color="red", attrs=["bold"]))
        sys.exit(1)

    # Announce flake8 run
    sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors.\n\n", color="yellow", attrs=["bold"]))

    print("pep8 errors:")
    print("----------------------------------------------------------------------")

    from subprocess import call
    flake_result = call(["flake8", ".", "--count"])
    if flake_result != 0:
        print("pep8 errors detected.")
        print(colored(text="\nYOUR CHANGES HAVE INTRODUCED PEP8 ERRORS!\n", color="red", attrs=["bold"]))
        sys.exit(flake_result)
    else:
        print("None")

    # Announce success
    print(colored(text="\nTests completed successfully with no errors. Congrats!", color="green", attrs=["bold"]))
Beispiel #14
0
    def __erase(self):
        """
        Private slot to handle the erase context menu action.
        
        This method erases the collected coverage data that is
        stored in the .coverage file.
        """
        cover = Coverage(data_file=self.cfn)
        cover.load()
        cover.erase()

        self.reloadButton.setEnabled(False)
        self.resultList.clear()
        self.summaryList.clear()
Beispiel #15
0
    def run(self):
        tests = unittest.TestLoader().discover("tests", pattern="*[t|T]est*.py")
        runner = unittest.TextTestRunner(verbosity=1)

        cov = Coverage()
        cov.erase()
        cov.start()

        result = runner.run(tests)

        cov.stop()
        cov.save()
        cov.html_report(directory="covhtml")
        sys.exit(int(bool(len(result.failures) > 0 or len(result.errors) > 0)))
Beispiel #16
0
def test_py3(module):
    futurize(module)
    fix_patterns(module)
    result, elapsed = run_destral(module)
    py3 = int(result == 0)
    cov = Coverage()
    try:
        cov.load()
        cov_per = cov.report()
        cov.erase()
    except Exception:
        cov_per = 0

    update_module(module, py3, coverage=cov_per, test_time=elapsed)
Beispiel #17
0
def coverage(ctx, html):
    """输出覆盖率测试"""
    cov = Coverage(source=["app", "commands", "routes/", "models"],
                   omit=["*__init__*"])
    cov.start()
    # 触发测试命令
    ctx.invoke(test)
    cov.stop()
    cov.save()

    click.echo('Coverage summary:')
    cov.report()
    if html:
        cov.html_report(directory="reports/coverage/")
    cov.erase()
Beispiel #18
0
def coverage(packages,
             output_stream=sys.stdout,
             coverage_file=None,
             xml_enabled=None,
             xml_file=None):
    """
    Context manager that activates coverage on the specified packages.

    Modules in the packages that are already loaded are removed and nosetest will load
    them again with coverage instrumentation when they are needed.

    :param packages: list of packages
    :param output_stream: the stream to write the results to
    :param coverage_file: the coverage file. If not specified coverage will use the default .coverage file
    :param xml_enabled: enable XML coverage report
    :param xml_file: the XML coverage report file. If not specified coverage will use the defualt coverage.xml file
    :return: instance of coverage.Coverage
    """
    source = {}
    for module_name, module in [
        (module_name, module)
            for module_name, module in list(sys.modules.items())
            if in_any_package(module_name, packages)
    ]:
        source[module_name] = module
        del sys.modules[module_name]

    cover = Coverage(data_file=coverage_file, auto_data=False, branch=False)
    cover.combine()
    cover.erase()
    cover.start()
    yield cover

    for module_name, module in [
        (module_name, module)
            for module_name, module in list(sys.modules.items())
            if in_any_package(module_name, packages)
    ]:
        source[module_name] = module

    cover.stop()
    cover.combine()
    cover.save()
    cover.report(list(source.values()), file=output_stream, show_missing=True)

    if xml_enabled:
        cover.xml_report(list(source.values()), xml_file)
Beispiel #19
0
def main():
    """ The main function, mainly functioning to do the main functional work
        (thanks pylint)
    """
    if len(sys.argv) > 1 and sys.argv[1] == 'cover':
        # FIXME - there are enough args now to need an arg parser
        cover = Coverage(branch=True, auto_data=True)
        min_percent = 0

        if len(sys.argv) > 2:
            min_percent = float(sys.argv[2])
    else:
        cover = False

    loader = unittest.defaultTestLoader
    runner = unittest.TextTestRunner(verbosity=2)

    if cover:
        cover.erase()
        cover.start()

    tests = loader.discover('.')
    tests_lib = loader.discover('lib', top_level_dir='lib')
    tests.addTests(tests_lib)
    result = runner.run(tests)

    if cover:
        cover.stop()
        # the debian coverage package didnt include jquery.debounce.min.js
        # (and additionally, that thing is not packaged for debian elsewhere)
        try:
            cover.html_report()
        except:  # noqa pylint: disable=bare-except
            pass
        # TODO - reconfirm that this packaging issue is still the case
        #        if it is not, remove the try..except
        #        if it is, add the specific exception

        percent = cover.report(show_missing=True)

        if min_percent > percent:
            print("The coverage ({:.1f}% reached) fails to reach the "
                  "minimum required ({}%)\n".format(percent, min_percent))
            exit(1)

    if not result.wasSuccessful():
        exit(1)
Beispiel #20
0
class Testmon(object):
    coverage_stack = []

    def __init__(self, rootdir="", testmon_labels=None, cov_plugin=None):
        if testmon_labels is None:
            testmon_labels = set(["singleprocess"])
        self.rootdir = rootdir
        self.testmon_labels = testmon_labels
        self.cov = None
        self.setup_coverage(not ("singleprocess" in testmon_labels), cov_plugin)

    def setup_coverage(self, subprocess, cov_plugin=None):
        params = {
            "include": [os.path.join(self.rootdir, "*")],
            "omit": _get_python_lib_paths(),
        }



        self.cov = Coverage(
            data_file=getattr(self, "sub_cov_file", None), config_file=False, **params
        )
        self.cov._warn_no_data = False


    def start(self):

        Testmon.coverage_stack.append(self.cov)
        self.cov.erase()
        self.cov.start()


    def stop(self):
        self.cov.stop()
        Testmon.coverage_stack.pop()

    def stop_and_save(self, testmon_data: TestmonData, rootdir, nodeid, result):
        self.stop()
        if hasattr(self, "sub_cov_file"):
            self.cov.combine()
        node_data = testmon_data.node_data_from_cov(self.cov, nodeid)
        testmon_data.write_node_data(nodeid, node_data, result)

    def close(self):
        if hasattr(self, "sub_cov_file"):
            os.remove(self.sub_cov_file + "_rc")
        os.environ.pop("COVERAGE_PROCESS_START", None)
Beispiel #21
0
def test_with_coverage():
    """ Runs the Unit Tests with Coverage. """
    # Configure Code Coverage Reports
    if app.config.get('FLASK_COVERAGE'):
        from coverage import Coverage
        # Start coverage engine, enable branch coverage analytics
        # Limit analysis to files inside application package.
        cov = Coverage(branch=True, include='myapp/*')
        cov.start()
        import unittest
        tests = unittest.TestLoader().discover('tests')
        unittest.TextTestRunner(verbosity=2).run(tests)
        cov.stop()
        cov.save()
        print('Coverage Summary')
        cov.report()
        cov.html_report(directory='covhtml')
        cov.erase()
def main():
    """ The main function, mainly functioning to do the main functional work
        (thanks pylint)
    """
    if len(sys.argv) > 1 and sys.argv[1] == 'cover':
        # FIXME - there are enough args now to need an arg parser
        cover = Coverage(branch=True, auto_data=True)
        min_percent = 0

        if len(sys.argv) > 2:
            min_percent = float(sys.argv[2])
    else:
        cover = False

    loader = unittest.defaultTestLoader
    runner = unittest.TextTestRunner(verbosity=2)

    if cover:
        cover.erase()
        cover.start()

    tests = loader.discover('.')
    tests_lib = loader.discover('lib', top_level_dir='lib')
    tests.addTests(tests_lib)
    result = runner.run(tests)

    if cover:
        cover.stop()
        # the debian coverage package didnt include jquery.debounce.min.js
        # (and additionally, that thing is not packaged for debian elsewhere)
        try:
            cover.html_report()
        except:
            pass
        percent = cover.report(show_missing=True)

        if min_percent > percent:
            print("The coverage ({:.1f}% reached) fails to reach the "
                  "minimum required ({}%)\n".format(percent, min_percent))
            exit(1)

    if not result.wasSuccessful():
        exit(1)
Beispiel #23
0
def main():
    args = _parse_args()
    logging.basicConfig(level=logging.DEBUG if args.verbose else logging.ERROR)

    cov = None
    if not args.no_coverage:
        from coverage import Coverage

        cov = Coverage(cover_pylib=False)
        cov.start()

    if not args.no_defaults:
        load_default_plugins()
        dr.load_components("insights.parsers", "insights.combiners")

    load_packages(parse_plugins(args.plugins))
    _handle_config(args.config)

    start_session(args.paths, args.cd, __coverage=cov, kernel=args.kernel)
    if cov:
        cov.stop()
        cov.erase()
Beispiel #24
0
def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
    # ******* CREDIT ***********
    # https://adamj.eu/tech/2019/04/30/getting-a-django-application-to-100-percent-coverage/
    # MyProject Customization: run coverage.py around tests automatically

    try:
        command = sys.argv[1]
    except IndexError:
        command = "help"

    running_tests = (command == 'test')
    if running_tests:
        from coverage import Coverage
        cov = Coverage()
        cov.erase()
        cov.start()

    # **************************
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?") from exc
    execute_from_command_line(sys.argv)

    # ****************************
    if running_tests:
        cov.stop()
        cov.save()
        # see credits in README.md for the next line
        cov.html_report(directory='covhtml')
        covered = cov.report()
        if covered < 100:
            sys.exit(1)
def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SmartClassroom.settings")

    if ReturnedOSName == "win32":
        os.system("title Smart Classroom Django Server Handler")
        os.system("CLS")
    elif ReturnedOSName == "linux":
        pass
    else:
        exit(-1)

    print("Smart Classroom Django Server Handler | < Django Project Caller >")
    print(
        '02/29/2020 | By Janrey "CodexLink" Licas | http://github.com/CodexLink\n'
    )
    print("In Collaboration with")
    print("    - Ronald Langaoan Jr. |> Hardware Designer and Manager")
    print(
        "    - Janos Angelo Jantoc |> Hardware Designer and Assistant Programmer"
    )
    print("    - Joshua Santos |> Hardware Manager and Builder")
    print("    - Johnell Casey Murillo Panotes |> Hardware Assistant\n")

    if sys.argv[1] == "test":
        print("\n - Coverage Report Activated!")
        from coverage import Coverage
        print("| - Coverage > Importing...")
        baseCov = Coverage()
        print("| - Coverage > Initializing...")
        baseCov.erase()
        print("| - Coverage > Erasing Recent Reports...")
        baseCov.start()
        print("| - Coverage > Code Coverage Start!")

    try:
        from django.core.management import execute_from_command_line

    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?") from exc
    execute_from_command_line(sys.argv)

    if sys.argv[1] == "test":
        baseCov.stop()
        baseCov.save()
        baseCovReport = baseCov.report()
        print("\n | - Coverage > Report Saved.")
        baseCov.html_report()
        if baseCovReport < reqCovPercentage:
            print(
                "\n | - Coverage > Code Coverage Completed But Fails To Meet Required Passing Rate of {0}%..."
                .format(reqCovPercentage))
        else:
            print(
                "\n | - Coverage > Code Coverage Completed and Passed Above Required Passing Rate of {0}%!"
                .format(reqCovPercentage))

        print("\n | - Coverage > Done~!\n")
        sys.exit(0)
Beispiel #26
0
#!/usr/bin/env python

import os
import sys

from django.core import management


# Point to the correct settings for testing
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'


if __name__ == "__main__":
    testing = 'test' in sys.argv

    if testing:
        from coverage import Coverage
        cov = Coverage()
        cov.erase()
        cov.start()

    management.execute_from_command_line()

    if testing:
        cov.stop()
        cov.save()
        cov.report()
def start():
    global cov
    cov = Coverage(config_file=flag_file)
    register_handler()
    cov.erase()
    cov.start()
Beispiel #28
0
class Testmon(object):
    coverage_stack = []

    def __init__(self, rootdir="", testmon_labels=None, cov_plugin=None):
        if testmon_labels is None:
            testmon_labels = {"singleprocess"}
        self.rootdir = rootdir
        self.testmon_labels = testmon_labels
        self.cov = None
        self.setup_coverage(not ("singleprocess" in testmon_labels), cov_plugin)

    def setup_coverage(self, subprocess, cov_plugin=None):
        params = {
            "include": [os.path.join(self.rootdir, "*")],
            "omit": _get_python_lib_paths(),
        }

        self.cov = Coverage(
            data_file=getattr(self, "sub_cov_file", None), config_file=False, **params
        )
        self.cov._warn_no_data = False

    def start(self):

        Testmon.coverage_stack.append(self.cov)
        self.cov.erase()
        self.cov.start()

    def stop(self):
        self.cov.stop()
        Testmon.coverage_stack.pop()

    def stop_and_save(self, testmon_data: TestmonData, nodeid, result):
        self.stop()
        if hasattr(self, "sub_cov_file"):
            self.cov.combine()
        measured_files = get_measured_relfiles(
            self.rootdir, self.cov, home_file(nodeid)
        )
        node_data = testmon_data.node_data_from_cov(measured_files)
        nodes_fingerprints = testmon_data.node_data2records(node_data)
        nodes_fingerprints.append(
            {
                "filename": LIBRARIES_KEY,
                "checksum": testmon_data.libraries,
                "mtime": None,
                "fingerprint": checksums_to_blob(
                    encode_lines([testmon_data.libraries])
                ),
            }
        )
        testmon_data.db.insert_node_fingerprints(
            nodeid,
            nodes_fingerprints,
            result,
        )

    def close(self):
        if hasattr(self, "sub_cov_file"):
            os.remove(self.sub_cov_file + "_rc")
        os.environ.pop("COVERAGE_PROCESS_START", None)
Beispiel #29
0
class CoverageScript(object):
    """The command-line interface to coverage.py."""
    def __init__(self):
        self.global_option = False
        self.coverage = None

    def command_line(self, argv):
        """The bulk of the command line interface to coverage.py.

        `argv` is the argument list to process.

        Returns 0 if all is well, 1 if something went wrong.

        """
        # Collect the command-line options.
        if not argv:
            show_help(topic='minimum_help')
            return OK

        # The command syntax we parse depends on the first argument.  Global
        # switch syntax always starts with an option.
        self.global_option = argv[0].startswith('-')
        if self.global_option:
            parser = GlobalOptionParser()
        else:
            parser = CMDS.get(argv[0])
            if not parser:
                show_help("Unknown command: '%s'" % argv[0])
                return ERR
            argv = argv[1:]

        ok, options, args = parser.parse_args_ok(argv)
        if not ok:
            return ERR

        # Handle help and version.
        if self.do_help(options, args, parser):
            return OK

        # Listify the list options.
        source = unshell_list(options.source)
        omit = unshell_list(options.omit)
        include = unshell_list(options.include)
        debug = unshell_list(options.debug)
        contexts = unshell_list(options.contexts)

        # Do something.
        self.coverage = Coverage(
            data_suffix=options.parallel_mode,
            cover_pylib=options.pylib,
            timid=options.timid,
            branch=options.branch,
            config_file=options.rcfile,
            source=source,
            omit=omit,
            include=include,
            debug=debug,
            concurrency=options.concurrency,
            check_preimported=True,
            context=options.context,
        )

        if options.action == "debug":
            return self.do_debug(args)

        elif options.action == "erase":
            self.coverage.erase()
            return OK

        elif options.action == "run":
            return self.do_run(options, args)

        elif options.action == "combine":
            if options.append:
                self.coverage.load()
            data_dirs = args or None
            self.coverage.combine(data_dirs, strict=True)
            self.coverage.save()
            return OK

        # Remaining actions are reporting, with some common options.
        report_args = dict(
            morfs=unglob_args(args),
            ignore_errors=options.ignore_errors,
            omit=omit,
            include=include,
            contexts=contexts,
        )

        # We need to be able to import from the current directory, because
        # plugins may try to, for example, to read Django settings.
        sys.path.insert(0, '')

        self.coverage.load()

        total = None
        if options.action == "report":
            total = self.coverage.report(show_missing=options.show_missing,
                                         skip_covered=options.skip_covered,
                                         **report_args)
        elif options.action == "annotate":
            self.coverage.annotate(directory=options.directory, **report_args)
        elif options.action == "html":
            total = self.coverage.html_report(
                directory=options.directory,
                title=options.title,
                skip_covered=options.skip_covered,
                show_contexts=options.show_contexts,
                **report_args)
        elif options.action == "xml":
            outfile = options.outfile
            total = self.coverage.xml_report(outfile=outfile, **report_args)

        if total is not None:
            # Apply the command line fail-under options, and then use the config
            # value, so we can get fail_under from the config file.
            if options.fail_under is not None:
                self.coverage.set_option("report:fail_under",
                                         options.fail_under)

            fail_under = self.coverage.get_option("report:fail_under")
            precision = self.coverage.get_option("report:precision")
            if should_fail_under(total, fail_under, precision):
                return FAIL_UNDER

        return OK

    def do_help(self, options, args, parser):
        """Deal with help requests.

        Return True if it handled the request, False if not.

        """
        # Handle help.
        if options.help:
            if self.global_option:
                show_help(topic='help')
            else:
                show_help(parser=parser)
            return True

        if options.action == "help":
            if args:
                for a in args:
                    parser = CMDS.get(a)
                    if parser:
                        show_help(parser=parser)
                    else:
                        show_help(topic=a)
            else:
                show_help(topic='help')
            return True

        # Handle version.
        if options.version:
            show_help(topic='version')
            return True

        return False

    def do_run(self, options, args):
        """Implementation of 'coverage run'."""

        if not args:
            if options.module:
                # Specified -m with nothing else.
                show_help("No module specified for -m")
                return ERR
            command_line = self.coverage.get_option("run:command_line")
            if command_line is not None:
                args = shlex.split(command_line)
                if args and args[0] == "-m":
                    options.module = True
                    args = args[1:]
        if not args:
            show_help("Nothing to do.")
            return ERR

        if options.append and self.coverage.get_option("run:parallel"):
            show_help("Can't append to data files in parallel mode.")
            return ERR

        if options.concurrency == "multiprocessing":
            # Can't set other run-affecting command line options with
            # multiprocessing.
            for opt_name in [
                    'branch', 'include', 'omit', 'pylib', 'source', 'timid'
            ]:
                # As it happens, all of these options have no default, meaning
                # they will be None if they have not been specified.
                if getattr(options, opt_name) is not None:
                    show_help(
                        "Options affecting multiprocessing must only be specified "
                        "in a configuration file.\n"
                        "Remove --{} from the command line.".format(opt_name))
                    return ERR

        runner = PyRunner(args, as_module=bool(options.module))
        runner.prepare()

        if options.append:
            self.coverage.load()

        # Run the script.
        self.coverage.start()
        code_ran = True
        try:
            runner.run()
        except NoSource:
            code_ran = False
            raise
        finally:
            self.coverage.stop()
            if code_ran:
                self.coverage.save()

        return OK

    def do_debug(self, args):
        """Implementation of 'coverage debug'."""

        if not args:
            show_help("What information would you like: config, data, sys?")
            return ERR

        for info in args:
            if info == 'sys':
                sys_info = self.coverage.sys_info()
                print(info_header("sys"))
                for line in info_formatter(sys_info):
                    print(" %s" % line)
            elif info == 'data':
                self.coverage.load()
                data = self.coverage.get_data()
                print(info_header("data"))
                print("path: %s" % self.coverage.get_data().data_filename())
                if data:
                    print("has_arcs: %r" % data.has_arcs())
                    summary = line_counts(data, fullpath=True)
                    filenames = sorted(summary.keys())
                    print("\n%d files:" % len(filenames))
                    for f in filenames:
                        line = "%s: %d lines" % (f, summary[f])
                        plugin = data.file_tracer(f)
                        if plugin:
                            line += " [%s]" % plugin
                        print(line)
                else:
                    print("No data collected")
            elif info == 'config':
                print(info_header("config"))
                config_info = self.coverage.config.__dict__.items()
                for line in info_formatter(config_info):
                    print(" %s" % line)
            else:
                show_help("Don't know what you mean by %r" % info)
                return ERR

        return OK
Beispiel #30
0
def run_test_suite(args):
    enable_coverage = not args.no_coverage
    tests = args.tests

    if enable_coverage:
        cov = Coverage(config_file=True)
        cov.erase()
        cov.start()

    test_db_name = os.environ.get('DJSTRIPE_TEST_DB_NAME', 'djstripe')
    test_db_user = os.environ.get('DJSTRIPE_TEST_DB_USER', 'postgres')
    test_db_pass = os.environ.get('DJSTRIPE_TEST_DB_PASS', '')

    settings.configure(
        DEBUG=True,
        SECRET_KEY="djstripe",
        SITE_ID=1,
        TIME_ZONE="UTC",
        USE_TZ=True,
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.postgresql_psycopg2",
                "NAME": test_db_name,
                "USER": test_db_user,
                "PASSWORD": test_db_pass,
                "HOST": "localhost",
                "PORT": "",
            },
        },
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [],
                'APP_DIRS': True,
                'OPTIONS': {
                    'context_processors': [
                        'django.contrib.auth.context_processors.auth',
                    ],
                },
            },
        ],
        ROOT_URLCONF="tests.test_urls",
        INSTALLED_APPS=[
            "django.contrib.admin", "django.contrib.auth",
            "django.contrib.contenttypes", "django.contrib.sessions",
            "django.contrib.sites", "jsonfield", "djstripe", "tests",
            "tests.apps.testapp"
        ],
        MIDDLEWARE=("django.contrib.sessions.middleware.SessionMiddleware",
                    "django.contrib.auth.middleware.AuthenticationMiddleware",
                    "django.contrib.messages.middleware.MessageMiddleware"),
        STRIPE_PUBLIC_KEY=os.environ.get("STRIPE_PUBLIC_KEY", ""),
        STRIPE_SECRET_KEY=os.environ.get("STRIPE_SECRET_KEY", ""),
        DJSTRIPE_PLANS={
            "test0": {
                "stripe_plan_id": "test_id_0",
                "name": "Test Plan 0",
                "description": "A test plan",
                "price": 1000,  # $10.00
                "currency": "usd",
                "interval": "month"
            },
            "test": {
                "stripe_plan_id": "test_id",
                "name": "Test Plan 1",
                "description": "Another test plan",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            },
            "test2": {
                "stripe_plan_id": "test_id_2",
                "name": "Test Plan 2",
                "description": "Yet Another test plan",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_deletion": {
                "stripe_plan_id": "test_id_3",
                "name": "Test Plan 3",
                "description": "Test plan for deletion.",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_trial": {
                "stripe_plan_id": "test_id_4",
                "name": "Test Plan 4",
                "description": "Test plan for trails.",
                "price": 7000,  # $70.00
                "currency": "usd",
                "interval": "month",
                "trial_period_days": 7
            },
            "unidentified_test_plan": {
                "name": "Unidentified Test Plan",
                "description": "A test plan with no ID.",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            }
        },
        DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=(
            "(admin)", "test_url_name",
            "testapp_namespaced:test_url_namespaced", "fn:/test_fnmatch*"),
        DJSTRIPE_USE_NATIVE_JSONFIELD=os.environ.get("USE_NATIVE_JSONFIELD",
                                                     "") == "1",
        DJSTRIPE_SUBSCRIPTION_REDIRECT="test_url_subscribe",
        DJSTRIPE_WEBHOOK_VALIDATION="retrieve_event",
    )

    # Avoid AppRegistryNotReady exception
    # http://stackoverflow.com/questions/24793351/django-appregistrynotready
    if hasattr(django, "setup"):
        django.setup()

    # Announce the test suite
    sys.stdout.write(
        colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
    sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"]))
    sys.stdout.write(
        colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))

    # Announce test run
    sys.stdout.write(
        colored(text="Step 1: Running unit tests.\n\n",
                color="yellow",
                attrs=["bold"]))

    # Hack to reset the global argv before nose has a chance to grab it
    # http://stackoverflow.com/a/1718407/1834570
    args = sys.argv[1:]
    sys.argv = sys.argv[0:1]

    # Add the ability to run tests on executable files. This is important when running tests on WSL, where permissions
    # are dictated by Windows instead of Unix.
    sys.argv += ["--exe"]

    from django_nose import NoseTestSuiteRunner

    test_runner = NoseTestSuiteRunner(verbosity=1, keepdb=False, failfast=True)
    failures = test_runner.run_tests(tests)

    if failures:
        sys.exit(failures)

    if enable_coverage:
        # Announce coverage run
        sys.stdout.write(
            colored(text="\nStep 2: Generating coverage results.\n\n",
                    color="yellow",
                    attrs=["bold"]))

        cov.stop()
        percentage = round(cov.report(show_missing=True), 2)
        cov.html_report(directory='cover')
        cov.save()

        if percentage < TESTS_THRESHOLD:
            sys.stderr.write(
                colored(
                    text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
                    "WAS {old}%, IS NOW {new}%.\n\n".format(
                        old=TESTS_THRESHOLD, new=percentage),
                    color="red",
                    attrs=["bold"]))
            sys.exit(1)
    else:
        # Announce disabled coverage run
        sys.stdout.write(
            colored(text="\nStep 2: Generating coverage results [SKIPPED].",
                    color="yellow",
                    attrs=["bold"]))

    # Announce success
    if enable_coverage:
        sys.stdout.write(
            colored(
                text=
                "\nTests completed successfully with no errors. Congrats!\n",
                color="green",
                attrs=["bold"]))
    else:
        sys.stdout.write(
            colored(
                text=
                "\nTests completed successfully, but some step(s) were skipped!\n",
                color="green",
                attrs=["bold"]))
        sys.stdout.write(
            colored(text="Don't push without running the skipped step(s).\n",
                    color="red",
                    attrs=["bold"]))
Beispiel #31
0
def run_test_suite(args):
    enable_coverage = not args.no_coverage
    tests = args.tests

    if enable_coverage:
        cov = Coverage(config_file=True)
        cov.erase()
        cov.start()

    settings.configure(
        DEBUG=True,
        USE_TZ=True,
        TIME_ZONE="UTC",
        SITE_ID=1,
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.postgresql_psycopg2",
                "NAME": "djstripe",
                "USER": "******",
                "PASSWORD": "",
                "HOST": "localhost",
                "PORT": "",
            },
        },
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [],
                'APP_DIRS': True,
                'OPTIONS': {
                    'context_processors': [
                        'django.contrib.auth.context_processors.auth',
                    ],
                },
            },
        ],
        ROOT_URLCONF="tests.test_urls",
        INSTALLED_APPS=[
            "django.contrib.admin",
            "django.contrib.auth",
            "django.contrib.contenttypes",
            "django.contrib.sessions",
            "django.contrib.sites",
            "jsonfield",
            "djstripe",
            "tests",
            "tests.apps.testapp"
        ],
        MIDDLEWARE=(
            "django.contrib.sessions.middleware.SessionMiddleware",
            "django.contrib.auth.middleware.AuthenticationMiddleware",
            "django.contrib.messages.middleware.MessageMiddleware"
        ),
        STRIPE_PUBLIC_KEY=os.environ.get("STRIPE_PUBLIC_KEY", ""),
        STRIPE_SECRET_KEY=os.environ.get("STRIPE_SECRET_KEY", ""),
        DJSTRIPE_PLANS={
            "test0": {
                "stripe_plan_id": "test_id_0",
                "name": "Test Plan 0",
                "description": "A test plan",
                "price": 1000,  # $10.00
                "currency": "usd",
                "interval": "month"
            },
            "test": {
                "stripe_plan_id": "test_id",
                "name": "Test Plan 1",
                "description": "Another test plan",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            },
            "test2": {
                "stripe_plan_id": "test_id_2",
                "name": "Test Plan 2",
                "description": "Yet Another test plan",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_deletion": {
                "stripe_plan_id": "test_id_3",
                "name": "Test Plan 3",
                "description": "Test plan for deletion.",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_trial": {
                "stripe_plan_id": "test_id_4",
                "name": "Test Plan 4",
                "description": "Test plan for trails.",
                "price": 7000,  # $70.00
                "currency": "usd",
                "interval": "month",
                "trial_period_days": 7
            },
            "unidentified_test_plan": {
                "name": "Unidentified Test Plan",
                "description": "A test plan with no ID.",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            }
        },
        DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=(
            "(admin)",
            "test_url_name",
            "testapp_namespaced:test_url_namespaced",
            "fn:/test_fnmatch*"
        ),
        DJSTRIPE_USE_NATIVE_JSONFIELD=os.environ.get("USE_NATIVE_JSONFIELD", "") == "1",
    )

    # Avoid AppRegistryNotReady exception
    # http://stackoverflow.com/questions/24793351/django-appregistrynotready
    if hasattr(django, "setup"):
        django.setup()

    # Announce the test suite
    sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
    sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"]))
    sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))

    # Announce test run
    sys.stdout.write(colored(text="Step 1: Running unit tests.\n\n", color="yellow", attrs=["bold"]))

    # Hack to reset the global argv before nose has a chance to grab it
    # http://stackoverflow.com/a/1718407/1834570
    args = sys.argv[1:]
    sys.argv = sys.argv[0:1]

    from django_nose import NoseTestSuiteRunner

    test_runner = NoseTestSuiteRunner(verbosity=1, keepdb=True, failfast=True)
    failures = test_runner.run_tests(tests)

    if failures:
        sys.exit(failures)

    if enable_coverage:
        # Announce coverage run
        sys.stdout.write(colored(text="\nStep 2: Generating coverage results.\n\n", color="yellow", attrs=["bold"]))

        cov.stop()
        percentage = round(cov.report(show_missing=True), 2)
        cov.html_report(directory='cover')
        cov.save()

        if percentage < TESTS_THRESHOLD:
            sys.stderr.write(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
                                     "WAS {old}%, IS NOW {new}%.\n\n".format(old=TESTS_THRESHOLD, new=percentage),
                                     color="red", attrs=["bold"]))
            sys.exit(1)
    else:
        # Announce disabled coverage run
        sys.stdout.write(colored(text="\nStep 2: Generating coverage results [SKIPPED].",
                                 color="yellow", attrs=["bold"]))

    # Announce success
    if enable_coverage:
        sys.stdout.write(colored(text="\nTests completed successfully with no errors. Congrats!\n",
                                 color="green", attrs=["bold"]))
    else:
        sys.stdout.write(colored(text="\nTests completed successfully, but some step(s) were skipped!\n",
                                 color="green", attrs=["bold"]))
        sys.stdout.write(colored(text="Don't push without running the skipped step(s).\n",
                                 color="red", attrs=["bold"]))
Beispiel #32
0
def run_test_suite(args):
    skip_utc = args.skip_utc
    enable_coverage = not args.no_coverage
    enable_pep8 = not args.no_pep8

    if enable_coverage:
        cov = Coverage(config_file=True)
        cov.erase()
        cov.start()

    settings.configure(
        DJSTRIPE_TESTS_SKIP_UTC=skip_utc,
        TIME_ZONE='America/Los_Angeles',
        DEBUG=True,
        USE_TZ=True,
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.postgresql_psycopg2",
                "NAME": "djstripe",
                "USER": "",
                "PASSWORD": "",
                "HOST": "",
                "PORT": "",
            },
        },
        ROOT_URLCONF="tests.test_urls",
        INSTALLED_APPS=[
            "django.contrib.admin", "django.contrib.auth",
            "django.contrib.contenttypes", "django.contrib.sessions",
            "django.contrib.sites", "jsonfield", "djstripe", "tests",
            "tests.apps.testapp"
        ],
        MIDDLEWARE_CLASSES=(
            "django.contrib.sessions.middleware.SessionMiddleware",
            "django.contrib.auth.middleware.AuthenticationMiddleware",
            "django.contrib.messages.middleware.MessageMiddleware"),
        SITE_ID=1,
        STRIPE_PUBLIC_KEY=os.environ.get("STRIPE_PUBLIC_KEY", ""),
        STRIPE_SECRET_KEY=os.environ.get("STRIPE_SECRET_KEY", ""),
        DJSTRIPE_PLANS={
            "test0": {
                "stripe_plan_id": "test_id_0",
                "name": "Test Plan 0",
                "description": "A test plan",
                "price": 1000,  # $10.00
                "currency": "usd",
                "interval": "month"
            },
            "test": {
                "stripe_plan_id": "test_id",
                "name": "Test Plan 1",
                "description": "Another test plan",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            },
            "test2": {
                "stripe_plan_id": "test_id_2",
                "name": "Test Plan 2",
                "description": "Yet Another test plan",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_deletion": {
                "stripe_plan_id": "test_id_3",
                "name": "Test Plan 3",
                "description": "Test plan for deletion.",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_trial": {
                "stripe_plan_id": "test_id_4",
                "name": "Test Plan 4",
                "description": "Test plan for trails.",
                "price": 7000,  # $70.00
                "currency": "usd",
                "interval": "month",
                "trial_period_days": 7
            },
            "unidentified_test_plan": {
                "name": "Unidentified Test Plan",
                "description": "A test plan with no ID.",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            }
        },
        DJSTRIPE_PLAN_HIERARCHY={
            "bronze": {
                "level": 1,
                "plans": [
                    "test0",
                    "test",
                ]
            },
            "silver": {
                "level": 2,
                "plans": [
                    "test2",
                    "test_deletion",
                ]
            },
            "gold": {
                "level": 3,
                "plans": [
                    "test_trial",
                    "unidentified_test_plan",
                ]
            },
        },
        DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=(
            "(admin)",
            "test_url_name",
            "testapp_namespaced:test_url_namespaced",
        ),
    )

    # Avoid AppRegistryNotReady exception
    # http://stackoverflow.com/questions/24793351/django-appregistrynotready
    if hasattr(django, "setup"):
        django.setup()

    # Announce the test suite
    sys.stdout.write(
        colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
    sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"]))
    sys.stdout.write(
        colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))

    # Announce test run
    sys.stdout.write(
        colored(text="Step 1: Running unit tests.\n\n",
                color="yellow",
                attrs=["bold"]))

    # Hack to reset the global argv before nose has a chance to grab it
    # http://stackoverflow.com/a/1718407/1834570
    args = sys.argv[1:]
    sys.argv = sys.argv[0:1]

    from django_nose import NoseTestSuiteRunner

    test_runner = NoseTestSuiteRunner(verbosity=1)
    failures = test_runner.run_tests(["."])

    if failures:
        sys.exit(failures)

    if enable_coverage:
        # Announce coverage run
        sys.stdout.write(
            colored(text="\nStep 2: Generating coverage results.\n\n",
                    color="yellow",
                    attrs=["bold"]))

        cov.stop()
        percentage = round(cov.report(show_missing=True), 2)
        cov.html_report(directory='cover')
        cov.save()

        if percentage < TESTS_THRESHOLD:
            sys.stderr.write(
                colored(
                    text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
                    "WAS {old}%, IS NOW {new}%.\n\n".format(
                        old=TESTS_THRESHOLD, new=percentage),
                    color="red",
                    attrs=["bold"]))
            sys.exit(1)
    else:
        # Announce disabled coverage run
        sys.stdout.write(
            colored(text="\nStep 2: Generating coverage results [SKIPPED].",
                    color="yellow",
                    attrs=["bold"]))

    if enable_pep8:
        # Announce flake8 run
        sys.stdout.write(
            colored(text="\nStep 3: Checking for pep8 errors.\n\n",
                    color="yellow",
                    attrs=["bold"]))

        print("pep8 errors:")
        print(
            "----------------------------------------------------------------------"
        )

        from subprocess import call
        flake_result = call(["flake8", ".", "--count"])
        if flake_result != 0:
            sys.stderr.write("pep8 errors detected.\n")
            sys.stderr.write(
                colored(text="\nYOUR CHANGES HAVE INTRODUCED PEP8 ERRORS!\n\n",
                        color="red",
                        attrs=["bold"]))
            sys.exit(flake_result)
        else:
            print("None")
    else:
        # Announce disabled coverage run
        sys.stdout.write(
            colored(text="\nStep 3: Checking for pep8 errors [SKIPPED].\n",
                    color="yellow",
                    attrs=["bold"]))

    # Announce success
    if enable_coverage and enable_pep8:
        sys.stdout.write(
            colored(
                text=
                "\nTests completed successfully with no errors. Congrats!\n",
                color="green",
                attrs=["bold"]))
    else:
        sys.stdout.write(
            colored(
                text=
                "\nTests completed successfully, but some step(s) were skipped!\n",
                color="green",
                attrs=["bold"]))
        sys.stdout.write(
            colored(text="Don't push without running the skipped step(s).\n",
                    color="red",
                    attrs=["bold"]))
Beispiel #33
0
def run_test_suite(args):
    skip_utc = args.skip_utc
    enable_coverage = not args.no_coverage
    enable_pep8 = not args.no_pep8

    if enable_coverage:
        cov = Coverage(config_file=True)
        cov.erase()
        cov.start()

    settings.configure(
        DJSTRIPE_TESTS_SKIP_UTC=skip_utc,
        TIME_ZONE='America/Los_Angeles',
        DEBUG=True,
        USE_TZ=True,
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.postgresql_psycopg2",
                "NAME": "djstripe",
                "USER": "",
                "PASSWORD": "",
                "HOST": "",
                "PORT": "",
            },
        },
        ROOT_URLCONF="tests.test_urls",
        INSTALLED_APPS=[
            "django.contrib.admin",
            "django.contrib.auth",
            "django.contrib.contenttypes",
            "django.contrib.sessions",
            "django.contrib.sites",
            "jsonfield",
            "djstripe",
            "tests",
            "tests.apps.testapp"
        ],
        MIDDLEWARE_CLASSES=(
            "django.contrib.sessions.middleware.SessionMiddleware",
            "django.contrib.auth.middleware.AuthenticationMiddleware",
            "django.contrib.messages.middleware.MessageMiddleware"
        ),
        SITE_ID=1,
        STRIPE_PUBLIC_KEY=os.environ.get("STRIPE_PUBLIC_KEY", ""),
        STRIPE_SECRET_KEY=os.environ.get("STRIPE_SECRET_KEY", ""),
        DJSTRIPE_PLANS={
            "test0": {
                "stripe_plan_id": "test_id_0",
                "name": "Test Plan 0",
                "description": "A test plan",
                "price": 1000,  # $10.00
                "currency": "usd",
                "interval": "month"
            },
            "test": {
                "stripe_plan_id": "test_id",
                "name": "Test Plan 1",
                "description": "Another test plan",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            },
            "test2": {
                "stripe_plan_id": "test_id_2",
                "name": "Test Plan 2",
                "description": "Yet Another test plan",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_deletion": {
                "stripe_plan_id": "test_id_3",
                "name": "Test Plan 3",
                "description": "Test plan for deletion.",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_trial": {
                "stripe_plan_id": "test_id_4",
                "name": "Test Plan 4",
                "description": "Test plan for trails.",
                "price": 7000,  # $70.00
                "currency": "usd",
                "interval": "month",
                "trial_period_days": 7
            },
            "unidentified_test_plan": {
                "name": "Unidentified Test Plan",
                "description": "A test plan with no ID.",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            }
        },
        DJSTRIPE_PLAN_HIERARCHY = {
            "bronze": {
                "level": 1,
                "plans": [
                    "test0",
                    "test",
                ]
            },
            "silver": {
                "level": 2,
                "plans": [
                    "test2",
                    "test_deletion",
                ]
            },
            "gold": {
                "level": 3,
                "plans": [
                    "test_trial",
                    "unidentified_test_plan",
                ]
            },
        },
        DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=(
            "(admin)",
            "test_url_name",
            "testapp_namespaced:test_url_namespaced",
        ),
    )

    # Avoid AppRegistryNotReady exception
    # http://stackoverflow.com/questions/24793351/django-appregistrynotready
    if hasattr(django, "setup"):
        django.setup()

    # Announce the test suite
    sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
    sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"]))
    sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))

    # Announce test run
    sys.stdout.write(colored(text="Step 1: Running unit tests.\n\n", color="yellow", attrs=["bold"]))

    # Hack to reset the global argv before nose has a chance to grab it
    # http://stackoverflow.com/a/1718407/1834570
    args = sys.argv[1:]
    sys.argv = sys.argv[0:1]

    from django_nose import NoseTestSuiteRunner

    test_runner = NoseTestSuiteRunner(verbosity=1)
    failures = test_runner.run_tests(["."])

    if failures:
        sys.exit(failures)

    if enable_coverage:
        # Announce coverage run
        sys.stdout.write(colored(text="\nStep 2: Generating coverage results.\n\n", color="yellow", attrs=["bold"]))

        cov.stop()
        percentage = round(cov.report(show_missing=True), 2)
        cov.html_report(directory='cover')
        cov.save()

        if percentage < TESTS_THRESHOLD:
            sys.stderr.write(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
                                     "WAS {old}%, IS NOW {new}%.\n\n".format(old=TESTS_THRESHOLD, new=percentage),
                                     color="red", attrs=["bold"]))
            sys.exit(1)
    else:
        # Announce disabled coverage run
        sys.stdout.write(colored(text="\nStep 2: Generating coverage results [SKIPPED].", color="yellow", attrs=["bold"]))

    if enable_pep8:
        # Announce flake8 run
        sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors.\n\n", color="yellow", attrs=["bold"]))

        print("pep8 errors:")
        print("----------------------------------------------------------------------")

        from subprocess import call
        flake_result = call(["flake8", ".", "--count"])
        if flake_result != 0:
            sys.stderr.write("pep8 errors detected.\n")
            sys.stderr.write(colored(text="\nYOUR CHANGES HAVE INTRODUCED PEP8 ERRORS!\n\n", color="red", attrs=["bold"]))
            sys.exit(flake_result)
        else:
            print("None")
    else:
        # Announce disabled coverage run
        sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors [SKIPPED].\n", color="yellow", attrs=["bold"]))

    # Announce success
    if enable_coverage and enable_pep8:
        sys.stdout.write(colored(text="\nTests completed successfully with no errors. Congrats!\n", color="green", attrs=["bold"]))
    else:
        sys.stdout.write(colored(text="\nTests completed successfully, but some step(s) were skipped!\n", color="green", attrs=["bold"]))
        sys.stdout.write(colored(text="Don't push without running the skipped step(s).\n", color="red", attrs=["bold"]))
Beispiel #34
0
class CodeCoverage(object):
    """
        Code Coverage radish extension
    """
    OPTIONS = [
        ('--with-coverage', 'enable code coverage'),
        ('--cover-packages=<cover_packages>', 'specify source code package'),
        ('--cover-append', 'append coverage data to previous collected data'),
        ('--cover-config-file=<cover_config_file>', 'specify coverage config file [default: .coveragerc]'),
        ('--cover-branches', 'include branch coverage in report'),
        ('--cover-erase', 'erase previously collected coverage data'),
        ('--cover-min-percentage=<cover_min_percentage>', 'fail if the given minimum coverage percentage is not reached'),
        ('--cover-html=<cover_html_dir>', 'specify a directory where to store HTML coverage report'),
        ('--cover-xml=<cover_xml_file>', 'specify a file where to store XML coverage report')
    ]
    LOAD_IF = staticmethod(lambda config: config.with_coverage)
    LOAD_PRIORITY = 70

    def __init__(self):
        before.all(self.coverage_start)
        after.all(self.coverage_stop)

        if world.config.cover_packages:
            self.cover_packages = world.config.cover_packages.split(",")
        else:
            self.cover_packages = []

        self.coverage = None
        self.modules_on_init = set(sys.modules.keys())

    def coverage_start(self, features, marker):
        """
        Start the coverage measurement
        """
        # if no explicit modules are specified we just
        # use the ones loaded from radish's basedir.
        # During the plugin init the basedir modules are
        # not loaded yet, but they are during the start method.
        # Thus, we are safe to consider the difference between the
        # two for coverage measurement.
        if not self.cover_packages:
            source = list(set(sys.modules.keys()).difference(self.modules_on_init))
        else:
            source = self.cover_packages

        self.coverage = Coverage(source=source,
                                 config_file=world.config.cover_config_file,
                                 branch=world.config.cover_branches)
        if world.config.cover_erase:
            self.coverage.combine()
            self.coverage.erase()

        if world.config.cover_append:
            self.coverage.load()
        self.coverage.start()

    def coverage_stop(self, features, marker):
        """
        Stop the coverage measurement
        and create report
        """
        self.coverage.stop()
        self.coverage.combine()
        self.coverage.save()
        self.coverage.report(file=sys.stdout)

        if world.config.cover_html:
            self.coverage.html_report(directory=world.config.cover_html)

        if world.config.cover_xml:
            self.coverage.xml_report(outfile=world.config.cover_xml)

        if world.config.cover_min_percentage:
            report = StringIO()
            self.coverage.report(file=report)
            match = re.search(r'^TOTAL\s+(.*)$', report.getvalue(), re.MULTILINE)
            if not match:
                raise RadishError('Failed to find total percentage in coverage report')

            total_percentage = int(match.groups()[0].split()[-1][:-1])
            if total_percentage < int(world.config.cover_min_percentage):
                raise RadishError('Failed to reach minimum expected coverage of {0}% (reached: {1}%)'.format(
                    world.config.cover_min_percentage, total_percentage))
Beispiel #35
0
    def test_create_dir(self):
        pass

    def test_upload(self):
        pass

    def test_rename(self):
        pass

    def test_del_file(self):
        pass

    def test_change_plan(self):
        pass


if __name__ == '__main__':
    try:
        unittest.main()
    except:
        pass
    cov.stop()
    cov.save()
    print("\n\nCoverage Report:\n")
    cov.report()
    print("HTML version: " +
          os.path.join(basedir, "htmlcov/coverage/index.html"))
    cov.html_report(directory='htmlcov/coverage')
    cov.erase()
Beispiel #36
0
class CoverageScript(object):
    """The command-line interface to coverage.py."""

    def __init__(self):
        self.global_option = False
        self.coverage = None

    def command_line(self, argv):
        """The bulk of the command line interface to coverage.py.

        `argv` is the argument list to process.

        Returns 0 if all is well, 1 if something went wrong.

        """
        # Collect the command-line options.
        if not argv:
            show_help(topic='minimum_help')
            return OK

        # The command syntax we parse depends on the first argument.  Global
        # switch syntax always starts with an option.
        self.global_option = argv[0].startswith('-')
        if self.global_option:
            parser = GlobalOptionParser()
        else:
            parser = CMDS.get(argv[0])
            if not parser:
                show_help("Unknown command: '%s'" % argv[0])
                return ERR
            argv = argv[1:]

        ok, options, args = parser.parse_args_ok(argv)
        if not ok:
            return ERR

        # Handle help and version.
        if self.do_help(options, args, parser):
            return OK

        # Listify the list options.
        source = unshell_list(options.source)
        omit = unshell_list(options.omit)
        include = unshell_list(options.include)
        debug = unshell_list(options.debug)

        # Do something.
        self.coverage = Coverage(
            data_suffix=options.parallel_mode,
            cover_pylib=options.pylib,
            timid=options.timid,
            branch=options.branch,
            config_file=options.rcfile,
            source=source,
            omit=omit,
            include=include,
            debug=debug,
            concurrency=options.concurrency,
            check_preimported=True,
            context=options.context,
            )

        if options.action == "debug":
            return self.do_debug(args)

        elif options.action == "erase":
            self.coverage.erase()
            return OK

        elif options.action == "run":
            return self.do_run(options, args)

        elif options.action == "combine":
            if options.append:
                self.coverage.load()
            data_dirs = args or None
            self.coverage.combine(data_dirs, strict=True)
            self.coverage.save()
            return OK

        # Remaining actions are reporting, with some common options.
        report_args = dict(
            morfs=unglob_args(args),
            ignore_errors=options.ignore_errors,
            omit=omit,
            include=include,
            )

        # We need to be able to import from the current directory, because
        # plugins may try to, for example, to read Django settings.
        sys.path.insert(0, '')

        self.coverage.load()

        total = None
        if options.action == "report":
            total = self.coverage.report(
                show_missing=options.show_missing,
                skip_covered=options.skip_covered,
                **report_args
                )
        elif options.action == "annotate":
            self.coverage.annotate(directory=options.directory, **report_args)
        elif options.action == "html":
            total = self.coverage.html_report(
                directory=options.directory,
                title=options.title,
                skip_covered=options.skip_covered,
                **report_args
                )
        elif options.action == "xml":
            outfile = options.outfile
            total = self.coverage.xml_report(outfile=outfile, **report_args)

        if total is not None:
            # Apply the command line fail-under options, and then use the config
            # value, so we can get fail_under from the config file.
            if options.fail_under is not None:
                self.coverage.set_option("report:fail_under", options.fail_under)

            fail_under = self.coverage.get_option("report:fail_under")
            precision = self.coverage.get_option("report:precision")
            if should_fail_under(total, fail_under, precision):
                return FAIL_UNDER

        return OK

    def do_help(self, options, args, parser):
        """Deal with help requests.

        Return True if it handled the request, False if not.

        """
        # Handle help.
        if options.help:
            if self.global_option:
                show_help(topic='help')
            else:
                show_help(parser=parser)
            return True

        if options.action == "help":
            if args:
                for a in args:
                    parser = CMDS.get(a)
                    if parser:
                        show_help(parser=parser)
                    else:
                        show_help(topic=a)
            else:
                show_help(topic='help')
            return True

        # Handle version.
        if options.version:
            show_help(topic='version')
            return True

        return False

    def do_run(self, options, args):
        """Implementation of 'coverage run'."""

        if not args:
            if options.module:
                # Specified -m with nothing else.
                show_help("No module specified for -m")
                return ERR
            command_line = self.coverage.get_option("run:command_line")
            if command_line is not None:
                args = shlex.split(command_line)
                if args and args[0] == "-m":
                    options.module = True
                    args = args[1:]
        if not args:
            show_help("Nothing to do.")
            return ERR

        if options.append and self.coverage.get_option("run:parallel"):
            show_help("Can't append to data files in parallel mode.")
            return ERR

        if options.concurrency == "multiprocessing":
            # Can't set other run-affecting command line options with
            # multiprocessing.
            for opt_name in ['branch', 'include', 'omit', 'pylib', 'source', 'timid']:
                # As it happens, all of these options have no default, meaning
                # they will be None if they have not been specified.
                if getattr(options, opt_name) is not None:
                    show_help(
                        "Options affecting multiprocessing must only be specified "
                        "in a configuration file.\n"
                        "Remove --{} from the command line.".format(opt_name)
                    )
                    return ERR

        runner = PyRunner(args, as_module=bool(options.module))
        runner.prepare()

        if options.append:
            self.coverage.load()

        # Run the script.
        self.coverage.start()
        code_ran = True
        try:
            runner.run()
        except NoSource:
            code_ran = False
            raise
        finally:
            self.coverage.stop()
            if code_ran:
                self.coverage.save()

        return OK

    def do_debug(self, args):
        """Implementation of 'coverage debug'."""

        if not args:
            show_help("What information would you like: config, data, sys?")
            return ERR

        for info in args:
            if info == 'sys':
                sys_info = self.coverage.sys_info()
                print(info_header("sys"))
                for line in info_formatter(sys_info):
                    print(" %s" % line)
            elif info == 'data':
                self.coverage.load()
                data = self.coverage.get_data()
                print(info_header("data"))
                print("path: %s" % self.coverage.get_data().data_filename())
                if data:
                    print("has_arcs: %r" % data.has_arcs())
                    summary = line_counts(data, fullpath=True)
                    filenames = sorted(summary.keys())
                    print("\n%d files:" % len(filenames))
                    for f in filenames:
                        line = "%s: %d lines" % (f, summary[f])
                        plugin = data.file_tracer(f)
                        if plugin:
                            line += " [%s]" % plugin
                        print(line)
                else:
                    print("No data collected")
            elif info == 'config':
                print(info_header("config"))
                config_info = self.coverage.config.__dict__.items()
                for line in info_formatter(config_info):
                    print(" %s" % line)
            else:
                show_help("Don't know what you mean by %r" % info)
                return ERR

        return OK
Beispiel #37
0
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sequoia.settings")
    try:
        from django.core.management import execute_from_command_line

    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?") from exc

    # Code coverage is handled here because of a bug with Django and nose that
    # hasn't been fixed after years.
    IS_TESTING = 'test' in sys.argv

    if IS_TESTING:
        from coverage import Coverage
        COV = Coverage()
        COV.erase()
        COV.start()

    execute_from_command_line(sys.argv)

    if IS_TESTING:
        COV.stop()
        COV.save()
        COV.report()
        COV.html_report(directory='htmlcov')
        COV.xml_report()