Merge pull request #20168 from larssandergreen/add-recurring-filter-to-contribution...
[civicrm-core.git] / Civi / Test / CiviTestListenerPHPUnit7.php
1 <?php
2
3 namespace Civi\Test;
4
5 /**
6 * Class CiviTestListener
7 * @package Civi\Test
8 *
9 * CiviTestListener participates in test-execution, looking for test-classes
10 * which have certain tags. If the tags are found, the listener will perform
11 * additional setup/teardown logic.
12 *
13 * @see EndToEndInterface
14 * @see HeadlessInterface
15 * @see HookInterface
16 */
17 class CiviTestListenerPHPUnit7 implements \PHPUnit\Framework\TestListener {
18
19 use \PHPUnit\Framework\TestListenerDefaultImplementation;
20
21 /**
22 * @var array
23 * Ex: $cache['Some_Test_Class']['civicrm_foobar'] = 'hook_civicrm_foobar';
24 * Array(string $testClass => Array(string $hookName => string $methodName)).
25 */
26 private $cache = [];
27
28 /**
29 * @var \CRM_Core_Transaction|null
30 */
31 private $tx;
32
33 public function startTestSuite(\PHPUnit\Framework\TestSuite $suite): void {
34 $byInterface = $this->indexTestsByInterface($suite->tests());
35 $this->validateGroups($byInterface);
36 $this->autoboot($byInterface);
37 }
38
39 public function endTestSuite(\PHPUnit\Framework\TestSuite $suite): void {
40 $this->cache = [];
41 }
42
43 public function startTest(\PHPUnit\Framework\Test $test): void {
44 if ($this->isCiviTest($test)) {
45 error_reporting(E_ALL);
46 $GLOBALS['CIVICRM_TEST_CASE'] = $test;
47 }
48
49 if ($test instanceof HeadlessInterface) {
50 $this->bootHeadless($test);
51 }
52
53 if ($test instanceof TransactionalInterface) {
54 $this->tx = new \CRM_Core_Transaction(TRUE);
55 $this->tx->rollback();
56 }
57 else {
58 $this->tx = NULL;
59 }
60 }
61
62 public function endTest(\PHPUnit\Framework\Test $test, float $time): void {
63 if ($test instanceof TransactionalInterface) {
64 $this->tx->rollback()->commit();
65 $this->tx = NULL;
66 }
67 if ($test instanceof HookInterface) {
68 \CRM_Utils_Hook::singleton()->reset();
69 }
70 \CRM_Utils_Time::resetTime();
71 if ($this->isCiviTest($test)) {
72 unset($GLOBALS['CIVICRM_TEST_CASE']);
73 error_reporting(E_ALL & ~E_NOTICE);
74 $this->errorScope = NULL;
75 }
76 }
77
78 /**
79 * @param HeadlessInterface|\PHPUnit\Framework\Test $test
80 */
81 protected function bootHeadless($test) {
82 if (CIVICRM_UF !== 'UnitTests') {
83 throw new \RuntimeException('HeadlessInterface requires CIVICRM_UF=UnitTests');
84 }
85
86 // Hrm, this seems wrong. Shouldn't we be resetting the entire session?
87 $session = \CRM_Core_Session::singleton();
88 $session->set('userID', NULL);
89 $test->setUpHeadless();
90
91 \CRM_Utils_System::flushCache();
92 \Civi::reset();
93 \CRM_Core_Session::singleton()->set('userID', NULL);
94 // ugh, performance
95 $config = \CRM_Core_Config::singleton(TRUE, TRUE);
96
97 if (property_exists($config->userPermissionClass, 'permissions')) {
98 $config->userPermissionClass->permissions = NULL;
99 }
100 }
101
102 /**
103 * @param \PHPUnit\Framework\Test $test
104 * @return bool
105 */
106 protected function isCiviTest(\PHPUnit\Framework\Test $test) {
107 return $test instanceof HookInterface || $test instanceof HeadlessInterface;
108 }
109
110 /**
111 * The first time we come across HeadlessInterface or EndToEndInterface, we'll
112 * try to autoboot.
113 *
114 * Once the system is booted, there's nothing we can do -- we're stuck with that
115 * environment. (Thank you, prolific define()s!) If there's a conflict between a
116 * test-class and the active boot-level, then we'll have to bail.
117 *
118 * @param array $byInterface
119 * List of test classes, keyed by major interface (HeadlessInterface vs EndToEndInterface).
120 */
121 protected function autoboot($byInterface) {
122 if (defined('CIVICRM_UF')) {
123 // OK, nothing we can do. System has booted already.
124 }
125 elseif (!empty($byInterface['HeadlessInterface'])) {
126 putenv('CIVICRM_UF=UnitTests');
127 // phpcs:disable
128 eval($this->cv('php:boot --level=full', 'phpcode'));
129 // phpcs:enable
130 }
131 elseif (!empty($byInterface['EndToEndInterface'])) {
132 putenv('CIVICRM_UF=');
133 // phpcs:disable
134 eval($this->cv('php:boot --level=full', 'phpcode'));
135 // phpcs:enable
136 }
137
138 $blurb = "Tip: Run the headless tests and end-to-end tests separately, e.g.\n"
139 . " $ phpunit5 --group headless\n"
140 . " $ phpunit5 --group e2e \n";
141
142 if (!empty($byInterface['HeadlessInterface']) && CIVICRM_UF !== 'UnitTests') {
143 $testNames = implode(', ', array_keys($byInterface['HeadlessInterface']));
144 throw new \RuntimeException("Suite includes headless tests ($testNames) which require CIVICRM_UF=UnitTests.\n\n$blurb");
145 }
146 if (!empty($byInterface['EndToEndInterface']) && CIVICRM_UF === 'UnitTests') {
147 $testNames = implode(', ', array_keys($byInterface['EndToEndInterface']));
148 throw new \RuntimeException("Suite includes end-to-end tests ($testNames) which do not support CIVICRM_UF=UnitTests.\n\n$blurb");
149 }
150 }
151
152 /**
153 * Call the "cv" command.
154 *
155 * This duplicates the standalone `cv()` wrapper that is recommended in bootstrap.php.
156 * This duplication is necessary because `cv()` is optional, and downstream implementers
157 * may alter, rename, or omit the wrapper, and (by virtue of its role in bootstrap) there
158 * it is impossible to define it centrally.
159 *
160 * @param string $cmd
161 * The rest of the command to send.
162 * @param string $decode
163 * Ex: 'json' or 'phpcode'.
164 * @return string
165 * Response output (if the command executed normally).
166 * @throws \RuntimeException
167 * If the command terminates abnormally.
168 */
169 protected function cv($cmd, $decode = 'json') {
170 $cmd = 'cv ' . $cmd;
171 $descriptorSpec = [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => STDERR];
172 $oldOutput = getenv('CV_OUTPUT');
173 putenv("CV_OUTPUT=json");
174 $process = proc_open($cmd, $descriptorSpec, $pipes, __DIR__);
175 putenv("CV_OUTPUT=$oldOutput");
176 fclose($pipes[0]);
177 $result = stream_get_contents($pipes[1]);
178 fclose($pipes[1]);
179 if (proc_close($process) !== 0) {
180 throw new \RuntimeException("Command failed ($cmd):\n$result");
181 }
182 switch ($decode) {
183 case 'raw':
184 return $result;
185
186 case 'phpcode':
187 // If the last output is /*PHPCODE*/, then we managed to complete execution.
188 if (substr(trim($result), 0, 12) !== "/*BEGINPHP*/" || substr(trim($result), -10) !== "/*ENDPHP*/") {
189 throw new \RuntimeException("Command failed ($cmd):\n$result");
190 }
191 return $result;
192
193 case 'json':
194 return json_decode($result, 1);
195
196 default:
197 throw new \RuntimeException("Bad decoder format ($decode)");
198 }
199 }
200
201 /**
202 * @param $tests
203 * @return array
204 */
205 protected function indexTestsByInterface($tests) {
206 $byInterface = ['HeadlessInterface' => [], 'EndToEndInterface' => []];
207 foreach ($tests as $test) {
208 /** @var \PHPUnit\Framework\Test $test */
209 if ($test instanceof HeadlessInterface) {
210 $byInterface['HeadlessInterface'][get_class($test)] = 1;
211 }
212 if ($test instanceof EndToEndInterface) {
213 $byInterface['EndToEndInterface'][get_class($test)] = 1;
214 }
215 }
216 return $byInterface;
217 }
218
219 /**
220 * Ensure that any tests have sensible groups, e.g.
221 *
222 * `HeadlessInterface` ==> `group headless`
223 * `EndToEndInterface` ==> `group e2e`
224 *
225 * @param array $byInterface
226 */
227 protected function validateGroups($byInterface) {
228 foreach ($byInterface['HeadlessInterface'] as $className => $nonce) {
229 $clazz = new \ReflectionClass($className);
230 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
231 if (strpos($docComment, "@group headless\n") === FALSE) {
232 echo "WARNING: Class $className implements HeadlessInterface. It should declare \"@group headless\".\n";
233 }
234 if (strpos($docComment, "@group e2e\n") !== FALSE) {
235 echo "WARNING: Class $className implements HeadlessInterface. It should not declare \"@group e2e\".\n";
236 }
237 }
238 foreach ($byInterface['EndToEndInterface'] as $className => $nonce) {
239 $clazz = new \ReflectionClass($className);
240 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
241 if (strpos($docComment, "@group e2e\n") === FALSE) {
242 echo "WARNING: Class $className implements EndToEndInterface. It should declare \"@group e2e\".\n";
243 }
244 if (strpos($docComment, "@group headless\n") !== FALSE) {
245 echo "WARNING: Class $className implements EndToEndInterface. It should not declare \"@group headless\".\n";
246 }
247 }
248 }
249
250 }