| 527 | TestResult = unittest.TestResult |
| 528 | |
| 529 | class _TestResult(TestResult): |
| 530 | # note: _TestResult is a pure representation of results. |
| 531 | # It lacks the output and reporting ability compares to unittest._TextTestResult. |
| 532 | |
| 533 | def __init__(self, verbosity=1): |
| 534 | TestResult.__init__(self) |
| 535 | self.stdout0 = None |
| 536 | self.stderr0 = None |
| 537 | self.success_count = 0 |
| 538 | self.failure_count = 0 |
| 539 | self.error_count = 0 |
| 540 | self.verbosity = verbosity |
| 541 | |
| 542 | # result is a list of result in 4 tuple |
| 543 | # ( |
| 544 | # result code (0: success; 1: fail; 2: error), |
| 545 | # TestCase object, |
| 546 | # Test output (byte string), |
| 547 | # stack trace, |
| 548 | # ) |
| 549 | self.result = [] |
| 550 | |
| 551 | |
| 552 | def startTest(self, test): |
| 553 | TestResult.startTest(self, test) |
| 554 | # just one buffer for both stdout and stderr |
| 555 | self.outputBuffer = io.StringIO() |
| 556 | stdout_redirector.fp = self.outputBuffer |
| 557 | stderr_redirector.fp = self.outputBuffer |
| 558 | self.stdout0 = sys.stdout |
| 559 | self.stderr0 = sys.stderr |
| 560 | sys.stdout = stdout_redirector |
| 561 | sys.stderr = stderr_redirector |
| 562 | |
| 563 | |
| 564 | def complete_output(self): |
| 565 | """ |
| 566 | Disconnect output redirection and return buffer. |
| 567 | Safe to call multiple times. |
| 568 | """ |
| 569 | if self.stdout0: |
| 570 | sys.stdout = self.stdout0 |
| 571 | sys.stderr = self.stderr0 |
| 572 | self.stdout0 = None |
| 573 | self.stderr0 = None |
| 574 | return self.outputBuffer.getvalue() |
| 575 | |
| 576 | |
| 577 | def stopTest(self, test): |
| 578 | # Usually one of addSuccess, addError or addFailure would have been called. |
| 579 | # But there are some path in unittest that would bypass this. |
| 580 | # We must disconnect stdout in stopTest(), which is guaranteed to be called. |
| 581 | self.complete_output() |
| 582 | |
| 583 | |
| 584 | def addSuccess(self, test): |
| 585 | self.success_count += 1 |
| 586 | TestResult.addSuccess(self, test) |