Localisation updates from https://translatewiki.net.
[mediawiki.git] / tests / phpunit / suites / SuiteEventsTrait.php
blob87524d2f03889e32ce40c85e3f904acbc9de329d
1 <?php
3 use PHPUnit\Framework\SkippedTestError;
4 use PHPUnit\Framework\SkippedTestSuiteError;
5 use PHPUnit\Framework\SyntheticError;
6 use PHPUnit\Framework\TestResult;
8 /**
9 * Trait that returns to PHPUnit test suites the support for setUp/tearDown events that
10 * was removed in PHPUnit 8.
12 * @since 1.35
14 trait SuiteEventsTrait {
15 /**
16 * @inheritDoc
18 public function run( ?TestResult $result = null ): TestResult {
19 // setUp / tearDown handling based on code in TestSuite::run()
20 // (except in the parent only beforeClass / afterClass are run)
21 $result ??= $this->createResult();
23 // Don't run events if there are no tests (T292239)
24 if ( count( $this ) === 0 ) {
25 return $result;
28 $calls = 0;
29 if ( is_callable( [ $this, 'setUp' ] ) ) {
30 $calls++;
31 try {
32 $this->setUp();
33 } catch ( SkippedTestSuiteError $error ) {
34 $result->startTestSuite( $this );
35 foreach ( $this->tests() as $test ) {
36 $result->startTest( $test );
37 $result->addFailure( $test, $error, 0 );
38 $result->endTest( $test, 0 );
40 $result->endTestSuite( $this );
41 return $result;
42 } catch ( \Throwable $t ) {
43 $errorAdded = false;
44 $result->startTestSuite( $this );
45 foreach ( $this->tests() as $test ) {
46 if ( $result->shouldStop() ) {
47 break;
49 $result->startTest( $test );
50 if ( !$errorAdded ) {
51 $result->addError( $test, $t, 0 );
52 $errorAdded = true;
53 } else {
54 $result->addFailure(
55 $test,
56 new SkippedTestError( 'Test skipped because of an error in setUp method' ),
60 $result->endTest( $test, 0 );
62 $result->endTestSuite( $this );
63 return $result;
67 $result = parent::run( $result );
69 if ( is_callable( [ $this, 'tearDown' ] ) ) {
70 $calls++;
71 try {
72 $this->tearDown();
73 } catch ( \Throwable $t ) {
74 $message = "Exception in tearDown" . \PHP_EOL . $t->getMessage();
75 $error = new SyntheticError( $message, 0, $t->getFile(), $t->getLine(), $t->getTrace() );
76 $placeholderTest = clone $this->testAt( 0 );
77 $placeholderTest->setName( 'tearDown' );
78 // Unlike in parent implementation, $result->endTestSuite() has
79 // already been invoked by parent::run, so we need to reopen
80 // the test suite
81 $result->startTestSuite( $this );
82 $result->startTest( $placeholderTest );
83 $result->addFailure( $placeholderTest, $error, 0 );
84 $result->endTest( $placeholderTest, 0 );
85 $result->endTestSuite( $this );
88 if ( !$calls ) {
89 throw new LogicException(
90 get_class( $this )
91 . " uses neither setUp() nor tearDown(), so it doesn't need SuiteEventsTrait"
94 return $result;