当前位置: 首页>>代码示例>>Python>>正文


Python TeamcityServiceMessages.testFailed方法代码示例

本文整理汇总了Python中teamcity.messages.TeamcityServiceMessages.testFailed方法的典型用法代码示例。如果您正苦于以下问题:Python TeamcityServiceMessages.testFailed方法的具体用法?Python TeamcityServiceMessages.testFailed怎么用?Python TeamcityServiceMessages.testFailed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在teamcity.messages.TeamcityServiceMessages的用法示例。


在下文中一共展示了TeamcityServiceMessages.testFailed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_test_failed

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
def test_test_failed():
    stream = StreamStub()
    messages = TeamcityServiceMessages(output=stream, now=lambda: fixed_date)
    messages.testFailed(testName='only a test', message='some message', details='details')
    assert stream.observed_output.strip() == textwrap.dedent("""\
        ##teamcity[testFailed timestamp='2000-11-02T10:23:01.556' details='details' message='some message' name='only a test']
        """).strip().encode('utf-8')
开发者ID:cmakara,项目名称:teamcity-messages,代码行数:9,代码来源:messages_test.py

示例2: EchoTeamCityMessages

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
class EchoTeamCityMessages(object):
    def __init__(self, ):
        self.tw = py.io.TerminalWriter(py.std.sys.stdout)
        self.teamcity = TeamcityServiceMessages(self.tw)
        self.currentSuite = None

    def format_names(self, name):
        split = '.py'
        file, testname = name.split(split, 1)
        if not testname:
            testname = file
            file = 'NO_TEST_FILE_FOUND'
        testname = testname.replace("::()::", ".")
        testname = testname.replace("::", ".")
        testname = testname.strip(".")
        return "".join([file, split]), testname

    def pytest_runtest_logstart(self, nodeid, location):
        file, testname = self.format_names(nodeid)
        if not file == self.currentSuite:
            if self.currentSuite:
                self.teamcity.testSuiteFinished(self.currentSuite)
            self.currentSuite = file
            self.teamcity.testSuiteStarted(self.currentSuite)
        self.teamcity.testStarted(testname)

    def pytest_runtest_logreport(self, report):
        file, testname = self.format_names(report.nodeid)
        
        if report.when == "call":
            for (secname, data) in report.sections:
                if 'stdout' in secname:
                    self.teamcity.testStdOut(testname, out=data)
                elif 'stderr' in secname:
                    self.teamcity.testStdErr(testname, out=data)
        
        if report.passed:
            if report.when == "call":  # ignore setup/teardown
                duration = timedelta(seconds=report.duration)
                self.teamcity.testFinished(testname, testDuration=duration)
        elif report.failed:
            if report.when == "call":
                self.teamcity.testFailed(testname, str(report.location), str(report.longrepr))
                duration = timedelta(seconds=report.duration)
                self.teamcity.testFinished(testname, testDuration=duration)  # report finished after the failure
        elif report.skipped:
            self.teamcity.testIgnored(testname, str(report.longrepr))
            self.teamcity.testFinished(testname)  # report finished after the skip

    def pytest_sessionfinish(self, session, exitstatus, __multicall__):
        if self.currentSuite:
            self.teamcity.testSuiteFinished(self.currentSuite)
开发者ID:curzona,项目名称:teamcity-python,代码行数:54,代码来源:pytest_plugin.py

示例3: TeamcityTestResult

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
class TeamcityTestResult(TestResult):
    def __init__(self, stream=sys.stdout):
        TestResult.__init__(self)

        self.output = stream
        
        self.createMessages()

    def createMessages(self):
        self.messages = TeamcityServiceMessages(self.output)
    
    def formatErr(self, err):
        exctype, value, tb = err
        return ''.join(traceback.format_exception(exctype, value, tb))
    
    def getTestName(self, test):
        return test.shortDescription() or str(test)

    def addSuccess(self, test, *k):
        TestResult.addSuccess(self, test)
        
        self.output.write("ok\n")
        
    def addError(self, test, err, *k):
        TestResult.addError(self, test, err)
        
        err = self.formatErr(err)
        
        self.messages.testFailed(self.getTestName(test),
            message='Error', details=err)
            
    def addFailure(self, test, err, *k):
        TestResult.addFailure(self, test, err)

        err = self.formatErr(err)
        
        self.messages.testFailed(self.getTestName(test),
            message='Failure', details=err)

    def startTest(self, test):
        self.messages.testStarted(self.getTestName(test))
        
    def stopTest(self, test):
        self.messages.testFinished(self.getTestName(test))
开发者ID:aaronb-inova,项目名称:teamcity-python,代码行数:46,代码来源:unittestpy.py

示例4: get_file_results

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
    def get_file_results(self):
        self._deferred_print.sort()

        messages = TeamcityServiceMessages()

        normalized_filename = self.filename.replace("\\", "/")

        suite_name = 'pep8: %s' % normalized_filename
        messages.testSuiteStarted(suite_name)
        for line_number, offset, code, text, doc in self._deferred_print:
            position = '%(path)s:%(row)d:%(col)d' % {
                'path': normalized_filename,
                'row': self.line_offset + line_number,
                'col': offset + 1,
            }

            error_message = '%s: %s' % (code, text)
            test_name = '%s: %s' % (code, position)

            messages.testStarted(test_name)

            if line_number > len(self.lines):
                line = ''
            else:
                line = self.lines[line_number - 1]

            details = [
                line.rstrip(),
                re.sub(r'\S', ' ', line[:offset]) + '^',
            ]

            if doc:
                details.append(doc.strip())

            details = '\n'.join(details)

            messages.testFailed(test_name, error_message, details)
            messages.testFinished(test_name)
        messages.testSuiteFinished(suite_name)
        return self.file_errors
开发者ID:capgelka,项目名称:teamcity-messages,代码行数:42,代码来源:flake8_plugin.py

示例5: format

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
    def format(self, error):
        normalized_filename = error.filename.replace("\\", "/")
        position = '%s:%d:%d' % (
            normalized_filename, error.line_number, error.column_number)
        error_message = '%s %s' % (error.code, error.text)
        test_name = 'pep8: %s: %s' % (position, error_message)

        line = error.physical_line
        offset = error.column_number
        details = [
            line.rstrip(),
            re.sub(r'\S', ' ', line[:offset]) + '^',
        ]
        details = '\n'.join(details)

        bytesio = BytesIO()
        messages = TeamcityServiceMessages(output=bytesio)

        messages.testStarted(test_name)
        messages.testFailed(test_name, error_message, details)
        messages.testFinished(test_name)

        return bytesio.getvalue().decode('UTF-8')
开发者ID:,项目名称:,代码行数:25,代码来源:

示例6: EchoTeamCityMessages

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
class EchoTeamCityMessages(object):
    def __init__(self, ):
        self.tw = py.io.TerminalWriter(py.std.sys.stdout)
        self.teamcity = TeamcityServiceMessages(self.tw)
        self.currentSuite = None


    def format_names(self, name):
        if name.find("::") > 0:
            file, testname = name.split("::", 1)
        else:
            file, testname = name, "top_level"

        testname = testname.replace("::()::", ".")
        testname = testname.replace("::", ".")
        testname = testname.strip(".")
        file = file.replace(".", "_").replace(os.sep, ".").replace("/", ".")
        return file, testname


    def pytest_runtest_logstart(self, nodeid, location):
        file, testname = self.format_names(nodeid)
        if not file == self.currentSuite:
            if self.currentSuite:
                self.teamcity.testSuiteFinished(self.currentSuite)
            self.currentSuite = file
            self.teamcity.testSuiteStarted(self.currentSuite)
        self.teamcity.testStarted(testname)


    def pytest_runtest_logreport(self, report):
        file, testname = self.format_names(report.nodeid)
        if report.passed:
            if report.when == "call":  # ignore setup/teardown
                duration = timedelta(seconds=report.duration)
                self.teamcity.testFinished(testname, testDuration=duration)
        elif report.failed:
            if report.when in ("call", "setup"):
                self.teamcity.testFailed(testname, str(report.location), str(report.longrepr))
                duration = timedelta(seconds=report.duration)
                self.teamcity.testFinished(testname, testDuration=duration)  # report finished after the failure
            elif report.when == "teardown":
                name = testname + "_teardown"
                self.teamcity.testStarted(name)
                self.teamcity.testFailed(name, str(report.location), str(report.longrepr))
                self.teamcity.testFinished(name)
        elif report.skipped:
            self.teamcity.testIgnored(testname, str(report.longrepr))
            self.teamcity.testFinished(testname)  # report finished after the skip


    def pytest_collectreport(self, report):
        if report.failed:
            file, testname = self.format_names(report.nodeid)

            name = file + "_collect"
            self.teamcity.testStarted(name)
            self.teamcity.testFailed(name, str(report.location), str(report.longrepr))
            self.teamcity.testFinished(name)

    def pytest_sessionfinish(self, session, exitstatus, __multicall__):
        if self.currentSuite:
            self.teamcity.testSuiteFinished(self.currentSuite)
开发者ID:AlexeyYurchuk,项目名称:teamcity-python,代码行数:65,代码来源:pytest_plugin.py

示例7: TeamcityTestResult

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
class TeamcityTestResult(TestResult):
    separator2 = "\n"

    def __init__(self, stream=_real_stdout, descriptions=None, verbosity=None):
        super(TeamcityTestResult, self).__init__()

        self.test_started_datetime_map = {}
        self.failed_tests = set()
        self.subtest_failures = {}
        self.messages = TeamcityServiceMessages(stream)

    def get_test_id(self, test):
        if is_string(test):
            return test

        # Force test_id for doctests
        if get_class_fullname(test) != "doctest.DocTestCase":
            desc = test.shortDescription()
            if desc and desc != test.id():
                return "%s (%s)" % (test.id(), desc.replace('.', '_'))

        return test.id()

    def addSuccess(self, test):
        super(TeamcityTestResult, self).addSuccess(test)

    def addExpectedFailure(self, test, err):
        super(TeamcityTestResult, self).addExpectedFailure(test, err)

        err = convert_error_to_string(err)
        test_id = self.get_test_id(test)

        self.messages.testIgnored(test_id, message="Expected failure: " + err, flowId=test_id)

    def addSkip(self, test, reason=""):
        if sys.version_info >= (2, 7):
            super(TeamcityTestResult, self).addSkip(test, reason)

        test_id = self.get_test_id(test)

        if reason:
            reason_str = ": " + reason
        else:
            reason_str = ""
        self.messages.testIgnored(test_id, message="Skipped" + reason_str, flowId=test_id)

    def addUnexpectedSuccess(self, test):
        super(TeamcityTestResult, self).addUnexpectedSuccess(test)

        test_id = self.get_test_id(test)
        self.messages.testFailed(test_id, message='Failure',
                                 details="Test should not succeed since it's marked with @unittest.expectedFailure",
                                 flowId=test_id)

    def addError(self, test, err, *k):
        super(TeamcityTestResult, self).addError(test, err)

        if get_class_fullname(test) == "unittest.suite._ErrorHolder":
            # This is a standalone error

            test_name = test.id()
            # patch setUpModule (__main__) -> __main__.setUpModule
            test_name = re.sub(r'^(.*) \((.*)\)$', r'\2.\1', test_name)

            self.messages.testStarted(test_name, flowId=test_name)
            self.report_fail(test_name, 'Failure', err)
            self.messages.testFinished(test_name, flowId=test_name)
        elif get_class_fullname(err[0]) == "unittest2.case.SkipTest":
            message = ""
            if hasattr(err[1], "message"):
                message = getattr(err[1], "message", "")
            elif hasattr(err[1], "args"):
                message = getattr(err[1], "args", [""])[0]
            self.addSkip(test, message)
        else:
            self.report_fail(test, 'Error', err)

    def addFailure(self, test, err, *k):
        super(TeamcityTestResult, self).addFailure(test, err)

        self.report_fail(test, 'Failure', err)

    def addSubTest(self, test, subtest, err):
        super(TeamcityTestResult, self).addSubTest(test, subtest, err)

        test_id = self.get_test_id(test)

        if err is not None:
            if issubclass(err[0], test.failureException):
                self.add_subtest_failure(test_id, self.get_test_id(subtest), err)
                self.messages.testStdErr(test_id, out="%s: failure\n" % self.get_test_id(subtest), flowId=test_id)
            else:
                self.add_subtest_failure(test_id, self.get_test_id(subtest), err)
                self.messages.testStdErr(test_id, out="%s: error\n" % self.get_test_id(subtest), flowId=test_id)
        else:
            self.messages.testStdOut(test_id, out="%s: ok\n" % self.get_test_id(subtest), flowId=test_id)

    def add_subtest_failure(self, test_id, subtest_id, err):
        fail_array = self.subtest_failures.get(test_id, [])
        fail_array.append("%s:\n%s" % (subtest_id, convert_error_to_string(err)))
#.........这里部分代码省略.........
开发者ID:lewisc,项目名称:teamcity-python,代码行数:103,代码来源:unittestpy.py

示例8: TeamcityReport

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]

#.........这里部分代码省略.........

    def _captureStandardOutput_value(self):
        if self._capture_plugin_enabled():
            return 'false'
        else:
            return 'true'

    def report_started(self, test):
        test_id = self.get_test_id(test)

        self.test_started_datetime_map[test_id] = datetime.datetime.now()
        self.messages.testStarted(test_id, captureStandardOutput=self._captureStandardOutput_value(), flowId=test_id)

    def report_fail(self, test, fail_type, err):
        # workaround nose bug on python 3
        if is_string(err[1]):
            err = (err[0], Exception(err[1]), err[2])

        test_id = self.get_test_id(test)

        details = convert_error_to_string(err)

        start_index = details.find(_captured_output_start_marker)
        end_index = details.find(_captured_output_end_marker)

        if 0 <= start_index < end_index:
            # do not log test output twice, see report_finish for actual output handling
            details = details[:start_index] + details[end_index + len(_captured_output_end_marker):]

        try:
            error = err[1]
            if isinstance(error, EqualsAssertionError):
                details = convert_error_to_string(err, 2)
                self.messages.testFailed(test_id, message=error.msg, details=details, flowId=test_id, comparison_failure=error)
                return
        except Exception:
            pass
        self.messages.testFailed(test_id, message=fail_type, details=details, flowId=test_id)

    def report_finish(self, test):
        test_id = self.get_test_id(test)

        if test_id in self.test_started_datetime_map:
            time_diff = datetime.datetime.now() - self.test_started_datetime_map[test_id]
            self.messages.testFinished(test_id, testDuration=time_diff, flowId=test_id)
        else:
            self.messages.testFinished(test_id, flowId=test_id)

    def prepareTestLoader(self, loader):
        """Insert ourselves into loader calls to count tests.
        The top-level loader call often returns lazy results, like a LazySuite.
        This is a problem, as we would destroy the suite by iterating over it
        to count the tests. Consequently, we monkey-patch the top-level loader
        call to do the load twice: once for the actual test running and again
        to yield something we can iterate over to do the count.

        from https://github.com/erikrose/nose-progressive/
        :type loader: nose.loader.TestLoader
        """

        # TODO: If there's ever a practical need, also patch loader.suiteClass
        # or even TestProgram.createTests. createTests seems to be main top-
        # level caller of loader methods, and nose.core.collector() (which
        # isn't even called in nose) is an alternate one.
        #
        # nose 1.3.4 contains required fix:
开发者ID:JetBrains,项目名称:teamcity-messages,代码行数:70,代码来源:nose_report.py

示例9: TeamcityReport

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
class TeamcityReport(object):
    name = 'teamcity-report'
    score = 10000

    def __init__(self):
        super(TeamcityReport, self).__init__()

        self.messages = TeamcityServiceMessages(_real_stdout)
        self.test_started_datetime_map = {}
        self.enabled = False

    def get_test_id(self, test):
        if is_string(test):
            return test

        # Handle special "tests"
        test_class_name = get_class_fullname(test)
        if test_class_name == CONTEXT_SUITE_FQN:
            if inspect.ismodule(test.context):
                module_name = test.context.__name__
                return module_name + "." + test.error_context
            elif inspect.isclass(test.context):
                class_name = get_class_fullname(test.context)
                return class_name + "." + test.error_context

        test_id = test.id()

        real_test = getattr(test, "test", test)
        real_test_class_name = get_class_fullname(real_test)

        test_arg = getattr(real_test, "arg", tuple())
        if (type(test_arg) is tuple or type(test_arg) is list) and len(test_arg) > 0:
            # As written in nose.case.FunctionTestCase#__str__ or nose.case.MethodTestCase#__str__
            test_arg_str = "%s" % (test_arg,)
            if test_id.endswith(test_arg_str):
                # Replace '.' in test args with '_' to preserve test hierarchy on TeamCity
                test_id = test_id[:len(test_id) - len(test_arg_str)] + test_arg_str.replace('.', '_')

        # Force test_id for doctests
        if real_test_class_name != "doctest.DocTestCase" and real_test_class_name != "nose.plugins.doctests.DocTestCase":
            desc = test.shortDescription()
            if desc and desc != test.id():
                return "%s (%s)" % (test_id, desc.replace('.', '_'))

        return test_id

    def configure(self, options, conf):
        self.enabled = is_running_under_teamcity()

    def options(self, parser, env=os.environ):
        pass

    def report_fail(self, test, fail_type, err):
        # workaround nose bug on python 3
        if is_string(err[1]):
            err = (err[0], Exception(err[1]), err[2])

        test_id = self.get_test_id(test)

        details = convert_error_to_string(err)

        start_index = details.find(_captured_output_start_marker)
        end_index = details.find(_captured_output_end_marker)

        if 0 <= start_index < end_index:
            captured_output = details[start_index + len(_captured_output_start_marker):end_index]
            details = details[:start_index] + details[end_index + len(_captured_output_end_marker):]

            for chunk in split_output(limit_output(captured_output)):
                self.messages.testStdOut(test_id, chunk, flowId=test_id)

        self.messages.testFailed(test_id, message=fail_type, details=details, flowId=test_id)

    def addError(self, test, err):
        test_class_name = get_class_fullname(test)
        test_id = self.get_test_id(test)

        if issubclass(err[0], SkipTest):
            self.messages.testIgnored(test_id, message=("SKIPPED: %s" % str(err[1])), flowId=test_id)
        elif issubclass(err[0], DeprecatedTest):
            self.messages.testIgnored(test_id, message="Deprecated", flowId=test_id)
        elif test_class_name == CONTEXT_SUITE_FQN:
            self.messages.testStarted(test_id, captureStandardOutput='true', flowId=test_id)
            self.report_fail(test, 'error in ' + test.error_context + ' context', err)
            self.messages.testFinished(test_id, flowId=test_id)
        else:
            self.report_fail(test, 'Error', err)

    def addFailure(self, test, err):
        self.report_fail(test, 'Failure', err)

    def startTest(self, test):
        test_id = self.get_test_id(test)

        self.test_started_datetime_map[test_id] = datetime.datetime.now()
        self.messages.testStarted(test_id, captureStandardOutput='true', flowId=test_id)

    def addSuccess(self, test):
        test_id = self.get_test_id(test)

#.........这里部分代码省略.........
开发者ID:lewisc,项目名称:teamcity-python,代码行数:103,代码来源:nose_report.py

示例10: TeamcityTestResult

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]

#.........这里部分代码省略.........
            else:
                reason_str = ": " + to_unicode(reason)
        else:
            reason_str = ""

        test_class_name = get_class_fullname(test)
        if test_class_name == "unittest.case._SubTest" or test_class_name == "unittest2.case._SubTest":
            parent_test = test.test_case
            parent_test_id = self.get_test_id(parent_test)
            subtest = test

            block_id = self.get_subtest_block_id(parent_test, subtest)

            self.messages.subTestBlockOpened(block_id, subTestResult="Skip", flowId=parent_test_id)
            self.messages.testStdOut(parent_test_id, out="SubTest skipped" + reason_str + "\n", flowId=parent_test_id)
            self.messages.blockClosed(block_id, flowId=parent_test_id)
        else:
            test_id = self.get_test_id(test)

            if test_id not in self.test_started_datetime_map:
                # Test ignored without startTest. Handle start and finish events ourselves
                self.messages.testStarted(test_id, flowId=test_id)
                self.messages.testIgnored(test_id, message="Skipped" + reason_str, flowId=test_id)
                self.messages.testFinished(test_id, flowId=test_id)
            else:
                self.messages.testIgnored(test_id, message="Skipped" + reason_str, flowId=test_id)

    def addUnexpectedSuccess(self, test):
        _super = super(TeamcityTestResult, self)
        if hasattr(_super, "addUnexpectedSuccess"):
            _super.addUnexpectedSuccess(test)

        test_id = self.get_test_id(test)
        self.messages.testFailed(test_id, message='Failure',
                                 details="Test should not succeed since it's marked with @unittest.expectedFailure",
                                 flowId=test_id)

    def addError(self, test, err, *k):
        super(TeamcityTestResult, self).addError(test, err)

        test_class = get_class_fullname(test)
        if test_class in _ERROR_HOLDERS_FQN:
            # This is a standalone error
            test_id = self.get_test_id(test)

            self.messages.testStarted(test_id, flowId=test_id)
            self.report_fail(test, 'Failure', err)
            self.messages.testFinished(test_id, flowId=test_id)
        elif get_class_fullname(err[0]) == "unittest2.case.SkipTest":
            message = ""
            if hasattr(err[1], "message"):
                message = getattr(err[1], "message", "")
            elif hasattr(err[1], "args"):
                message = getattr(err[1], "args", [""])[0]
            self.addSkip(test, message)
        else:
            self.report_fail(test, 'Error', err)

    def addFailure(self, test, err, *k):
        super(TeamcityTestResult, self).addFailure(test, err)

        self.report_fail(test, 'Failure', err)

    def addSubTest(self, test, subtest, err):
        _super = super(TeamcityTestResult, self)
        if hasattr(_super, "addSubTest"):
开发者ID:JetBrains,项目名称:teamcity-messages,代码行数:70,代码来源:unittestpy.py

示例11: TeamcityFormatter

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
class TeamcityFormatter(Formatter):
    """
    Stateful TC reporter.
    Since we can't fetch all steps from the very beginning (even skipped tests are reported)
    we store tests and features on each call.

    To hook into test reporting override _report_suite_started and/or _report_test_started
    """

    def __init__(self, stream_opener, config):
        super(TeamcityFormatter, self).__init__(stream_opener, config)
        assert version.LooseVersion(behave_version) >= version.LooseVersion("1.2.6"), "Only 1.2.6+ is supported"
        self._messages = TeamcityServiceMessages()

        self.__feature = None
        self.__scenario = None
        self.__steps = deque()
        self.__scenario_opened = False
        self.__feature_opened = False

        self.__test_start_time = None

    def feature(self, feature):
        assert isinstance(feature, Feature)
        assert not self.__feature, "Prev. feature not closed"
        self.__feature = feature

    def scenario(self, scenario):
        assert isinstance(scenario, Scenario)
        self.__scenario = scenario
        self.__scenario_opened = False
        self.__steps.clear()

    def step(self, step):
        assert isinstance(step, Step)
        self.__steps.append(step)

    def match(self, match):
        if not self.__feature_opened:
            self._report_suite_started(self.__feature, _suite_name(self.__feature))
            self.__feature_opened = True

        if not self.__scenario_opened:
            self._report_suite_started(self.__scenario, _suite_name(self.__scenario))
            self.__scenario_opened = True

        assert self.__steps, "No steps left"

        step = self.__steps.popleft()
        self._report_test_started(step, _step_name(step))
        self.__test_start_time = datetime.datetime.now()

    def _report_suite_started(self, suite, suite_name):
        """
        :param suite: behave suite
        :param suite_name: suite name that must be reported, be sure to use it instead of suite.name

        """
        self._messages.testSuiteStarted(suite_name)

    def _report_test_started(self, test, test_name):
        """
        Suite name is always stripped, be sure to strip() it too
        :param test: behave test
        :param test_name: test name that must be reported, be sure to use it instead of test.name
        """
        self._messages.testStarted(test_name)

    def result(self, step):
        assert isinstance(step, Step)
        step_name = _step_name(step)
        if step.status == Status.failed:
            try:
                error = traceback.format_exc(step.exc_traceback)
                if error != step.error_message:
                    self._messages.testStdErr(step_name, error)
            except Exception:
                pass  # exception shall not prevent error message
            self._messages.testFailed(step_name, message=step.error_message)

        if step.status == Status.undefined:
            self._messages.testFailed(step_name, message="Undefined")

        if step.status == Status.skipped:
            self._messages.testIgnored(step_name)

        self._messages.testFinished(step_name, testDuration=datetime.datetime.now() - self.__test_start_time)

        if not self.__steps:
            self.__close_scenario()
        elif step.status in [Status.failed, Status.undefined]:
            # Broken background/undefined step stops whole scenario

            reason = "Undefined step" if step.status == Status.undefined else "Prev. step failed"
            self.__skip_rest_of_scenario(reason)

    def __skip_rest_of_scenario(self, reason):
        while self.__steps:
            step = self.__steps.popleft()
            self._report_test_started(step, _step_name(step))
#.........这里部分代码省略.........
开发者ID:JetBrains,项目名称:teamcity-messages,代码行数:103,代码来源:jb_behave_formatter.py

示例12: TeamcityTestResult

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
class TeamcityTestResult(unittest.TestResult):
    def __init__(self, stream=sys.stdout):
        super(TeamcityTestResult, self).__init__()

        self.output = stream
        self.test_started_datetime = datetime.datetime.now()
        self.test_name = None
        self.messages = None
        self.createMessages()

        self.test_succeeded = False
        self.subtest_errors = []
        self.subtest_failures = []

    def createMessages(self):
        self.messages = TeamcityServiceMessages(self.output)

    def formatErr(self, err):
        try:
            exctype, value, tb = err
            return ''.join(traceback.format_exception(exctype, value, tb))
        except Exception:
            tb = traceback.format_exc()
            return "*FAILED TO GET TRACEBACK*: " + tb

    def getTestName(self, test):
        desc = test.shortDescription()
        if desc:
            return "%s (%s)" % (test.id(), desc)
        return test.id()

    def addSuccess(self, test, *args):
        super(TeamcityTestResult, self).addSuccess(test)

        self.output.write("ok\n")

    def addError(self, test, err, *k):
        super(TeamcityTestResult, self).addError(test, err)

        err = self.formatErr(err)
        if self.getTestName(test) != self.test_name:
            sys.stderr.write("INTERNAL ERROR: addError(%s) outside of test\n" % self.getTestName(test))
            sys.stderr.write("Error: %s\n" % err)
            return

        self.test_succeeded = False
        self.messages.testFailed(self.getTestName(test), message='Error', details=err)

    def addFailure(self, test, err, *k):
        # workaround nose bug on python 3
        if _is_string(err[1]):
            err = (err[0], Exception(err[1]), err[2])

        super(TeamcityTestResult, self).addFailure(test, err)

        err = self.formatErr(err)
        if self.getTestName(test) != self.test_name:
            sys.stderr.write("INTERNAL ERROR: addFailure(%s) outside of test\n" % self.getTestName(test))
            sys.stderr.write("Error: %s\n" % err)
            return

        self.test_succeeded = False
        self.messages.testFailed(self.getTestName(test), message='Failure', details=err)

    def addSkip(self, test, reason):
        super(TeamcityTestResult, self).addSkip(test, reason)
        
        if self.getTestName(test) != self.test_name:
            sys.stderr.write("INTERNAL ERROR: addSkip(%s) outside of test\n" % self.getTestName(test))
            sys.stderr.write("Reason: %s\n" % reason)
            return

        self.messages.testIgnored(self.getTestName(test), reason)

    def addExpectedFailure(self, test, err):
        super(TeamcityTestResult, self).addExpectedFailure(test, err)

        if self.getTestName(test) != self.test_name:
            err = self.formatErr(err)
            sys.stderr.write("INTERNAL ERROR: addExpectedFailure(%s) outside of test\n" % self.getTestName(test))
            sys.stderr.write("Error: %s\n" % err)
            return

        self.output.write("ok (failure expected)\n")

    def addUnexpectedSuccess(self, test):
        super(TeamcityTestResult, self).addUnexpectedSuccess(test)

        if self.getTestName(test) != self.test_name:
            sys.stderr.write("INTERNAL ERROR: addUnexpectedSuccess(%s) outside of test\n" % self.getTestName(test))
            return

        self.test_succeeded = False
        self.messages.testFailed(self.getTestName(test), message='Unexpected success')

    def addSubTest(self, test, subtest, err):
        super(TeamcityTestResult, self).addSubTest(test, subtest, err)

        if err is not None:
            if issubclass(err[0], test.failureException):
#.........这里部分代码省略.........
开发者ID:ralphje,项目名称:teamcity-python,代码行数:103,代码来源:unittestpy.py

示例13: EchoTeamCityMessages

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]

#.........这里部分代码省略.........

        if message is None:
            message = self.format_location(report.location)

        self.ensure_test_start_reported(test_id)
        if report_output:
            self.report_test_output(report, test_id)

        diff_error = None
        try:
            err_message = str(report.longrepr.reprcrash.message)
            diff_name = diff_tools.EqualsAssertionError.__name__
            # There is a string like "foo.bar.DiffError: [serialized_data]"
            if diff_name in err_message:
                serialized_data = err_message[err_message.index(diff_name) + len(diff_name) + 1:]
                diff_error = diff_tools.deserialize_error(serialized_data)

            # AssertionError is patched in py.test, we can try to fetch diff from it
            # In general case message starts with "AssertionError: ", but can also starts with "assert" for top-level
            # function. To support both cases we unify them
            if err_message.startswith("assert"):
                err_message = "AssertionError: " + err_message
            if err_message.startswith("AssertionError:"):
                diff_error = fetch_diff_error_from_message(err_message, self.swap_diff)
        except Exception:
            pass

        if diff_error:
            # Cut everything after postfix: it is internal view of DiffError
            strace = str(report.longrepr)
            data_postfix = "_ _ _ _ _"
            if data_postfix in strace:
                strace = strace[0:strace.index(data_postfix)]
            self.teamcity.testFailed(test_id, diff_error.msg if diff_error.msg else message, strace,
                                     flowId=test_id,
                                     comparison_failure=diff_error
                                     )
        else:
            self.teamcity.testFailed(test_id, message, str(report.longrepr), flowId=test_id)
        self.report_test_finished(test_id, duration)

    def report_test_skip(self, test_id, report):
        if type(report.longrepr) is tuple and len(report.longrepr) == 3:
            reason = report.longrepr[2]
        else:
            reason = str(report.longrepr)

        if hasattr(report, 'duration'):
            duration = timedelta(seconds=report.duration)
        else:
            duration = None

        self.ensure_test_start_reported(test_id)
        self.report_test_output(report, test_id)
        self.teamcity.testIgnored(test_id, reason, flowId=test_id)
        self.report_test_finished(test_id, duration)

    def pytest_runtest_logreport(self, report):
        """
        :type report: _pytest.runner.TestReport
        """
        test_id = self.format_test_id(report.nodeid, report.location)

        duration = timedelta(seconds=report.duration)

        if report.passed:
开发者ID:amaurymedeiros,项目名称:intellij-community,代码行数:70,代码来源:pytest_plugin.py

示例14: TeamcityTestResult

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]
class TeamcityTestResult(TestResult):
    def __init__(self, stream=sys.stdout):
        TestResult.__init__(self)

        self.output = stream
        self.test_started_datetime = None
        self.test_name = None

        self.createMessages()

    def createMessages(self):
        self.messages = TeamcityServiceMessages(self.output)

    def formatErr(self, err):
        try:
            exctype, value, tb = err
            return ''.join(traceback.format_exception(exctype, value, tb))
        except:
            tb = traceback.format_exc()
            return "*FAILED TO GET TRACEBACK*: " + tb

    def getTestName(self, test):
        return test.shortDescription() or str(test)

    def addSuccess(self, test, *k):
        TestResult.addSuccess(self, test)

        self.output.write("ok\n")

    def addError(self, test, err, *k):
        TestResult.addError(self, test, err)

        err = self.formatErr(err)
        if self.getTestName(test) != self.test_name:
            sys.stderr.write("INTERNAL ERROR: addError(%s) outside of test\n" % self.getTestName(test))
            sys.stderr.write("Error: %s\n" % err)
            return

        self.messages.testFailed(self.getTestName(test),
                                 message='Error', details=err)

    def addSkip(self, test, reason):
        TestResult.addSkip(self, test, reason)
        self.output.write("skipped %s - %s\n" % (self.getTestName(test), reason))
        #TODO: "testIgnored" should be replaced by "testSkipped" when implemented
        self.messages.testIgnored(self.getTestName(test), reason)

    def addFailure(self, test, err, *k):
        # workaround nose bug on python 3
        if _is_string(err[1]):
            err = (err[0], Exception(err[1]), err[2])

        TestResult.addFailure(self, test, err)

        err = self.formatErr(err)
        if self.getTestName(test) != self.test_name:
            sys.stderr.write("INTERNAL ERROR: addFailure(%s) outside of test\n" % self.getTestName(test))
            sys.stderr.write("Error: %s\n" % err)
            return

        self.messages.testFailed(self.getTestName(test),
                                 message='Failure', details=err)

    def startTest(self, test):
        self.test_started_datetime = datetime.datetime.now()
        self.test_name = self.getTestName(test)
        self.messages.testStarted(self.test_name)

    def stopTest(self, test):
        time_diff = datetime.datetime.now() - self.test_started_datetime
        if self.getTestName(test) != self.test_name:
            sys.stderr.write("INTERNAL ERROR: stopTest(%s) after startTest(%s)" % (self.getTestName(test), self.test_name))
        self.messages.testFinished(self.test_name, time_diff)
        self.test_name = None
开发者ID:oantoshchenko,项目名称:teamcity-python,代码行数:76,代码来源:unittestpy.py

示例15: EchoTeamCityMessages

# 需要导入模块: from teamcity.messages import TeamcityServiceMessages [as 别名]
# 或者: from teamcity.messages.TeamcityServiceMessages import testFailed [as 别名]

#.........这里部分代码省略.........
                return True
        return False

    def report_test_output(self, report, test_id):
        for (secname, data) in report.sections:
            if report.when not in secname:
                continue
            if not data:
                continue

            if 'stdout' in secname:
                for chunk in split_output(limit_output(data)):
                    self.teamcity.testStdOut(test_id, out=chunk, flowId=test_id)
            elif 'stderr' in secname:
                for chunk in split_output(limit_output(data)):
                    self.teamcity.testStdErr(test_id, out=chunk, flowId=test_id)

    def report_test_finished(self, test_id, duration=None):
        self.teamcity.testFinished(test_id, testDuration=duration, flowId=test_id)
        self.test_start_reported_mark.remove(test_id)

    def report_test_failure(self, test_id, report, message=None, report_output=True):
        if hasattr(report, 'duration'):
            duration = timedelta(seconds=report.duration)
        else:
            duration = None

        if message is None:
            message = self.format_location(report.location)

        self.ensure_test_start_reported(test_id)
        if report_output:
            self.report_test_output(report, test_id)
        self.teamcity.testFailed(test_id, message, str(report.longrepr), flowId=test_id)
        self.report_test_finished(test_id, duration)

    def pytest_runtest_logreport(self, report):
        """
        :type report: _pytest.runner.TestReport
        """
        test_id = self.format_test_id(report.nodeid, report.location)

        duration = timedelta(seconds=report.duration)

        if report.passed:
            # Do not report passed setup/teardown if no output
            if report.when == 'call':
                self.ensure_test_start_reported(test_id)
                self.report_test_output(report, test_id)
                self.report_test_finished(test_id, duration)
            else:
                if self.report_has_output(report):
                    block_name = "test " + report.when
                    self.teamcity.blockOpened(block_name, flowId=test_id)
                    self.report_test_output(report, test_id)
                    self.teamcity.blockClosed(block_name, flowId=test_id)
        elif report.failed:
            if report.when == 'call':
                self.report_test_failure(test_id, report)
            elif report.when == 'setup':
                if self.report_has_output(report):
                    self.teamcity.blockOpened("test setup", flowId=test_id)
                    self.report_test_output(report, test_id)
                    self.teamcity.blockClosed("test setup", flowId=test_id)

                self.report_test_failure(test_id, report, message="test setup failed", report_output=False)
开发者ID:,项目名称:,代码行数:70,代码来源:


注:本文中的teamcity.messages.TeamcityServiceMessages.testFailed方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。