Exemplo n.º 1
0
def test_direct_invocation(testdir):
    test_file = testdir.makepyfile("""
        def test_foo():
            assert True
    """)
    plugin = JSONReport()
    res = pytest.main([test_file.strpath], plugins=[plugin])
    assert res == 0
    assert plugin.report['exitcode'] == 0
    assert plugin.report['summary']['total'] == 1

    report_path = testdir.tmpdir / 'foo_report.json'
    assert not report_path.exists()
    plugin.save_report(str(report_path))
    assert report_path.exists()
Exemplo n.º 2
0
def main():
    """
    Entry point for setup.py.
    Wrapper for a profiler if requested otherwise just call run() directly.
    If profiling is enabled we disable interactivity as it would wait for user
    input and influence the statistics. However the -r option still works.
    """
    _ensure_tests_requirements_installed()

    import pytest
    from pytest_jsonreport.plugin import JSONReport

    report = (True if '--report' in sys.argv else
              False if '--no-report' in sys.argv else None)
    if '-h' in sys.argv or '--help' in sys.argv:
        print(__doc__)
        sys.exit(0)
    elif all(['--json-report-file' not in arg for arg in sys.argv]):
        sys.argv.append('--json-report-file=none')
    # Use default traceback for nicer report display.
    sys.argv.append("--tb=native")
    # Cd into ObsPy's directory and run tests.
    with change_directory(Path(obspy.__file__).parent):
        plugin = JSONReport()
        status = pytest.main(plugins=[plugin])
    # Upload test report if tests were successfully run.
    # See https://docs.pytest.org/en/latest/reference/exit-codes.html
    if int(status) < 2:
        upload_json_report(report=report, data=plugin.report)
    sys.exit(status)
def test_direct_invocation(testdir):
    test_file = testdir.makepyfile("""
        def test_foo():
            assert True
    """)
    plugin = JSONReport()
    res = pytest.main([test_file.strpath], plugins=[plugin])
    assert res == 0
    assert plugin.report['exitcode'] == 0
Exemplo n.º 4
0
    def pytest_configure(self, config: Config):
        if not hasattr(config, '_tm4j_report'):
            self._config._tm4j_report = self

        self._load_config_params(config)

        # Activate json-report plugin for report generation
        plugin = JSONReport(config)
        config._json_report = plugin
        config.pluginmanager.register(plugin)
Exemplo n.º 5
0
def test_bug_37(testdir):
    """#37: Report is not accessible via config._json_report when pytest is run
    from code via pytest.main().
    """
    test_file = testdir.makepyfile("""
        def test_foo():
            assert True
    """)
    testdir.makeconftest("""
        def pytest_sessionfinish(session):
            assert session.config._json_report.report['exitcode'] == 0
    """)
    plugin = JSONReport()
    pytest.main([test_file.strpath], plugins=[plugin])
Exemplo n.º 6
0
    def _run_test(self, test, ssh_config):
        """Run the test on the image."""
        self.logger.info('Running test {name}'.format(name=test))

        options = []
        if self.early_exit:
            options.append('-x')

        args = '-v -s {} --json-report-file=none ' \
               '--ssh-config={} --hosts={} {}'.format(
                   ' '.join(options),
                   ssh_config,
                   self.instance_ip,
                   test
               )

        # Print output captured to log file for test run
        self.logger.debug('\nTest directories:\n{}\n'.format('\n'.join(
            self.test_dirs)))
        self.logger.debug('Arguments:\n{}\n'.format(args))

        cmds = shlex.split(args)
        num_retries = 0

        while num_retries < self.retry_count:
            plugin = JSONReport()

            try:
                with open(self.log_file, 'a') as log_file:
                    with ipa_utils.redirect_output(log_file):
                        result = pytest.main(cmds, plugins=[plugin])
            except Exception as error:
                result = 3  # See below for pytest error codes
                self.logger.exception(str(error))

            if result != 0:
                num_retries += 1
            else:
                break

        # If pytest has an error there will be no report but
        # we still want to process the error as a failure.
        # https://docs.pytest.org/en/latest/usage.html#possible-exit-codes
        if result in (2, 3, 4):
            self._process_test_results(0, 'pytest_error', 1)
        else:
            self._merge_results(plugin.report)

        return result
Exemplo n.º 7
0
def cli(tasks, disable_verbose, answer, debug):
    """
    Запустить тесты для заданий TASKS. По умолчанию запустятся все тесты.

    Примеры запуска:

    \b
        ptest            запустить все тесты для текущего раздела
        ptest 1,2a,5     запустить тесты для заданий 1, 2a и 5
        ptest 1,2a-c,5   запустить тесты для заданий 1, 2a, 2b, 2c и 5
        ptest 1,2*       запустить тесты для заданий 1, все задания 2 с буквами и без
        ptest 1,3-5      запустить тесты для заданий 1, 3, 4, 5
        ptest 1-5 -a     запустить тесты и записать ответы на задания,
                         которые прошли тесты, в файлы answer_task_x.py

    Флаг -d отключает подробный вывод pytest, который включен по умолчанию.
    Флаг -a записывает ответы в файлы answer_task_x.py, если тесты проходят.
    """
    if not debug:
        sys.excepthook = exception_handler

    json_plugin = JSONReport()
    pytest_args_common = ["--json-report-file=none", "--disable-warnings"]

    if disable_verbose:
        pytest_args = [*pytest_args_common, "--tb=short"]
    else:
        pytest_args = [*pytest_args_common, "-vv"]

    # если добавлен флаг -a нет смысла выводить traceback,
    # так как скорее всего задания уже проверены предыдущими запусками.
    if answer:
        pytest_args = [*pytest_args_common, "--tb=no"]

    # запуск pytest
    if tasks == "all":
        pytest.main(pytest_args, plugins=[json_plugin])
    else:
        pytest.main(tasks + pytest_args, plugins=[json_plugin])

    # получить результаты pytest в формате JSON
    passed_tasks = parse_json_report(json_plugin.report)

    # скопировать ответы в файлы answer_task_x.py
    if passed_tasks and answer:
        copy_answers(passed_tasks)
Exemplo n.º 8
0
def cli(tasks, disable_verbose, answer, debug):
    """
    Run tests for TASKS. By default, all tests will run.

    Examples of running pyneng:

    \b
        pyneng            run all tests for current chapter
        pyneng 1,2a,5     run tests for tasks 1, 2a и 5
        pyneng 1,2a-c,5   run tests for tasks 1, 2a, 2b, 2c и 5
        pyneng 1,2*       run tests for tasks 1, all tasks 2
        pyneng 1,3-5      run tests for tasks 1, 3, 4, 5
        pyneng 1-5 -a     run test and get answers

    The -d flag disables verbose output from pytest, which is enabled by default.
    The -a flag writes answers to the answer_task_x.py files if the tests pass.
    """
    if not debug:
        sys.excepthook = exception_handler

    json_plugin = JSONReport()
    pytest_args_common = ["--json-report-file=none", "--disable-warnings"]

    if disable_verbose:
        pytest_args = [*pytest_args_common, "--tb=short"]
    else:
        pytest_args = [*pytest_args_common, "-vv"]

    if answer:
        pytest_args = [*pytest_args_common, "--tb=no"]

    if tasks == "all":
        pytest.main(pytest_args, plugins=[json_plugin])
    else:
        pytest.main(tasks + pytest_args, plugins=[json_plugin])

    passed_tasks = parse_json_report(json_plugin.report)

    if passed_tasks and answer:
        copy_answers(passed_tasks)
Exemplo n.º 9
0
def main():
    """
    Entry point for setup.py.
    Wrapper for a profiler if requested otherwise just call run() directly.
    If profiling is enabled we disable interactivity as it would wait for user
    input and influence the statistics. However the -r option still works.
    """
    if '-h' in sys.argv or '--help' in sys.argv:
        print(__doc__)
        sys.exit(0)
    try:
        import pytest
        from pytest_jsonreport.plugin import JSONReport
    except ImportError:
        msg = ("\nObsPy's test suite uses pytest and pytest-json-report. "
               "Please install these packages before using obspy-runtests. "
               "Example with pip:\n"
               "\t$ pip install pytest pytest-json-report\n\n"
               "Additional optional test requirements can be used and "
               "installed with:\n"
               "\t$ pip install obspy[tests]\n")
        sys.exit(msg)
    # hack to get rid of internal pytest warning, see
    # https://github.com/pytest-dev/pytest-cov/issues/148
    import pytest_jsonreport
    pytest_jsonreport.__doc__ = 'PYTEST_DONT_REWRITE'
    # Cd into ObsPy's directory and run tests.
    with change_directory(Path(__file__).parent.parent):
        plugin = JSONReport()
        status = pytest.main(plugins=[plugin])
    # Upload test report if tests were successfully run.
    # See https://docs.pytest.org/en/latest/reference/exit-codes.html
    if int(status) < 2:
        report = (True if '--report' in sys.argv else
                  False if '--no-report' in sys.argv else None)
        upload_json_report(report=report, data=plugin.report)
    sys.exit(status)
def cli(tasks, disable_verbose, answer, check, debug):
    """
    Запустить тесты для заданий TASKS. По умолчанию запустятся все тесты.

    Примеры запуска:

    \b
        ptest            запустить все тесты для текущего раздела
        ptest 1,2a,5     запустить тесты для заданий 1, 2a и 5
        ptest 1,2a-c,5   запустить тесты для заданий 1, 2a, 2b, 2c и 5
        ptest 1,2*       запустить тесты для заданий 1, все задания 2 с буквами и без
        ptest 1,3-5      запустить тесты для заданий 1, 3, 4, 5
        ptest 1-5 -a     запустить тесты и записать ответы на задания,
                         которые прошли тесты, в файлы answer_task_x.py
        ptest 1-5 -c     запустить тесты и сдать на проверку задания,
                         которые прошли тесты.
        ptest -a -c      запустить все тесты, записать ответы на задания
                         и сдать на проверку задания, которые прошли тесты.

    Флаг -d отключает подробный вывод pytest, который включен по умолчанию.
    Флаг -a записывает ответы в файлы answer_task_x.py, если тесты проходят.
    Флаг -c сдает на проверку задания (пишет комментарий на github)
    для которых прошли тесты.
    Для сдачи заданий на проверку надо сгенерировать токен github.
    Подробнее в инструкции: https://pyneng.github.io/docs/ptest-prepare/
    """
    if not debug:
        sys.excepthook = exception_handler

    json_plugin = JSONReport()
    pytest_args_common = ["--json-report-file=none", "--disable-warnings", "--no-hints"]

    if disable_verbose:
        pytest_args = [*pytest_args_common, "--tb=short"]
    else:
        pytest_args = [*pytest_args_common, "-vv"]

    # если добавлен флаг -a или -c нет смысла выводить traceback,
    # так как скорее всего задания уже проверены предыдущими запусками.
    if answer or check:
        pytest_args = [*pytest_args_common, "--tb=no"]

    # запуск pytest
    if tasks == "all":
        pytest.main(pytest_args, plugins=[json_plugin])
    else:
        pytest.main(tasks + pytest_args, plugins=[json_plugin])

    # получить результаты pytest в формате JSON
    passed_tasks = parse_json_report(json_plugin.report)

    if passed_tasks:
        # скопировать ответы в файлы answer_task_x.py
        if answer:
            copy_answers(passed_tasks)

        # сдать задания на проверку через github API
        if check:
            token = os.environ.get("GITHUB_TOKEN")
            if not token:
                raise PtestError(
                    red(
                        "Для сдачи заданий на проверку надо сгенерировать токен github. "
                        "Подробнее в инструкции: https://pyneng.github.io/docs/ptest-prepare/"
                    )
                )
            send_tasks_to_check(passed_tasks)
Exemplo n.º 11
0
def pytest_configure(config):
    plugin = JSONReport()
    config.pluginmanager.register(plugin)
Exemplo n.º 12
0
def runSelfTest():
    filename = f'output/{t()}report.json'
    plugin = JSONReport()
    pytest.main(['../tests/test_log.py'], plugins=[plugin])
    log(plugin.report)
    plugin.save_report(filename)