REF Update CiviCRM default PEAR Error handling to be exception rather than just PEAR_...
[civicrm-core.git] / Civi / Test / CiviTestListenerPHPUnit7.php
CommitLineData
8851bdf5
SL
1<?php
2
3namespace 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 */
17class CiviTestListenerPHPUnit7 implements \PHPUnit\Framework\TestListener {
18
19 use \PHPUnit\Framework\TestListenerDefaultImplementation;
20
8851bdf5
SL
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);
8851bdf5
SL
46 }
47
48 if ($test instanceof HeadlessInterface) {
49 $this->bootHeadless($test);
50 }
51
52 if ($test instanceof HookInterface) {
53 // Note: bootHeadless() indirectly resets any hooks, which means that hook_civicrm_config
54 // is unsubscribable. However, after bootHeadless(), we're free to subscribe to hooks again.
55 $this->registerHooks($test);
56 }
57
58 if ($test instanceof TransactionalInterface) {
59 $this->tx = new \CRM_Core_Transaction(TRUE);
60 $this->tx->rollback();
61 }
62 else {
63 $this->tx = NULL;
64 }
65 }
66
67 public function endTest(\PHPUnit\Framework\Test $test, float $time): void {
68 if ($test instanceof TransactionalInterface) {
69 $this->tx->rollback()->commit();
70 $this->tx = NULL;
71 }
72 if ($test instanceof HookInterface) {
73 \CRM_Utils_Hook::singleton()->reset();
74 }
75 if ($this->isCiviTest($test)) {
76 error_reporting(E_ALL & ~E_NOTICE);
77 $this->errorScope = NULL;
78 }
79 }
80
81 /**
82 * @param HeadlessInterface|\PHPUnit\Framework\Test $test
83 */
84 protected function bootHeadless($test) {
85 if (CIVICRM_UF !== 'UnitTests') {
86 throw new \RuntimeException('HeadlessInterface requires CIVICRM_UF=UnitTests');
87 }
88
89 // Hrm, this seems wrong. Shouldn't we be resetting the entire session?
90 $session = \CRM_Core_Session::singleton();
91 $session->set('userID', NULL);
92 $test->setUpHeadless();
93
94 \CRM_Utils_System::flushCache();
95 \Civi::reset();
96 \CRM_Core_Session::singleton()->set('userID', NULL);
97 // ugh, performance
98 $config = \CRM_Core_Config::singleton(TRUE, TRUE);
99
100 if (property_exists($config->userPermissionClass, 'permissions')) {
101 $config->userPermissionClass->permissions = NULL;
102 }
103 }
104
105 /**
106 * @param \Civi\Test\HookInterface $test
107 * @return array
108 * Array(string $hookName => string $methodName)).
109 */
110 protected function findTestHooks(HookInterface $test) {
111 $class = get_class($test);
112 if (!isset($this->cache[$class])) {
113 $funcs = [];
114 foreach (get_class_methods($class) as $func) {
115 if (preg_match('/^hook_/', $func)) {
116 $funcs[substr($func, 5)] = $func;
117 }
118 }
119 $this->cache[$class] = $funcs;
120 }
121 return $this->cache[$class];
122 }
123
124 /**
125 * @param \PHPUnit\Framework\Test $test
126 * @return bool
127 */
128 protected function isCiviTest(\PHPUnit\Framework\Test $test) {
129 return $test instanceof HookInterface || $test instanceof HeadlessInterface;
130 }
131
132 /**
133 * Find any hook functions in $test and register them.
134 *
135 * @param \Civi\Test\HookInterface $test
136 */
137 protected function registerHooks(HookInterface $test) {
138 if (CIVICRM_UF !== 'UnitTests') {
139 // This is not ideal -- it's just a side-effect of how hooks and E2E tests work.
140 // We can temporarily subscribe to hooks in-process, but for other processes, it gets messy.
141 throw new \RuntimeException('CiviHookTestInterface requires CIVICRM_UF=UnitTests');
142 }
143 \CRM_Utils_Hook::singleton()->reset();
144 /** @var \CRM_Utils_Hook_UnitTests $hooks */
145 $hooks = \CRM_Utils_Hook::singleton();
146 foreach ($this->findTestHooks($test) as $hook => $func) {
147 $hooks->setHook($hook, [$test, $func]);
148 }
149 }
150
151 /**
152 * The first time we come across HeadlessInterface or EndToEndInterface, we'll
153 * try to autoboot.
154 *
155 * Once the system is booted, there's nothing we can do -- we're stuck with that
156 * environment. (Thank you, prolific define()s!) If there's a conflict between a
157 * test-class and the active boot-level, then we'll have to bail.
158 *
159 * @param array $byInterface
160 * List of test classes, keyed by major interface (HeadlessInterface vs EndToEndInterface).
161 */
162 protected function autoboot($byInterface) {
163 if (defined('CIVICRM_UF')) {
164 // OK, nothing we can do. System has booted already.
165 }
166 elseif (!empty($byInterface['HeadlessInterface'])) {
167 putenv('CIVICRM_UF=UnitTests');
168 // phpcs:disable
169 eval($this->cv('php:boot --level=full', 'phpcode'));
170 // phpcs:enable
171 }
172 elseif (!empty($byInterface['EndToEndInterface'])) {
173 putenv('CIVICRM_UF=');
174 // phpcs:disable
175 eval($this->cv('php:boot --level=full', 'phpcode'));
176 // phpcs:enable
177 }
178
179 $blurb = "Tip: Run the headless tests and end-to-end tests separately, e.g.\n"
180 . " $ phpunit5 --group headless\n"
181 . " $ phpunit5 --group e2e \n";
182
183 if (!empty($byInterface['HeadlessInterface']) && CIVICRM_UF !== 'UnitTests') {
184 $testNames = implode(', ', array_keys($byInterface['HeadlessInterface']));
185 throw new \RuntimeException("Suite includes headless tests ($testNames) which require CIVICRM_UF=UnitTests.\n\n$blurb");
186 }
187 if (!empty($byInterface['EndToEndInterface']) && CIVICRM_UF === 'UnitTests') {
188 $testNames = implode(', ', array_keys($byInterface['EndToEndInterface']));
189 throw new \RuntimeException("Suite includes end-to-end tests ($testNames) which do not support CIVICRM_UF=UnitTests.\n\n$blurb");
190 }
191 }
192
193 /**
194 * Call the "cv" command.
195 *
196 * This duplicates the standalone `cv()` wrapper that is recommended in bootstrap.php.
197 * This duplication is necessary because `cv()` is optional, and downstream implementers
198 * may alter, rename, or omit the wrapper, and (by virtue of its role in bootstrap) there
199 * it is impossible to define it centrally.
200 *
201 * @param string $cmd
202 * The rest of the command to send.
203 * @param string $decode
204 * Ex: 'json' or 'phpcode'.
205 * @return string
206 * Response output (if the command executed normally).
207 * @throws \RuntimeException
208 * If the command terminates abnormally.
209 */
210 protected function cv($cmd, $decode = 'json') {
211 $cmd = 'cv ' . $cmd;
212 $descriptorSpec = [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => STDERR];
213 $oldOutput = getenv('CV_OUTPUT');
214 putenv("CV_OUTPUT=json");
215 $process = proc_open($cmd, $descriptorSpec, $pipes, __DIR__);
216 putenv("CV_OUTPUT=$oldOutput");
217 fclose($pipes[0]);
218 $result = stream_get_contents($pipes[1]);
219 fclose($pipes[1]);
220 if (proc_close($process) !== 0) {
221 throw new \RuntimeException("Command failed ($cmd):\n$result");
222 }
223 switch ($decode) {
224 case 'raw':
225 return $result;
226
227 case 'phpcode':
228 // If the last output is /*PHPCODE*/, then we managed to complete execution.
229 if (substr(trim($result), 0, 12) !== "/*BEGINPHP*/" || substr(trim($result), -10) !== "/*ENDPHP*/") {
230 throw new \RuntimeException("Command failed ($cmd):\n$result");
231 }
232 return $result;
233
234 case 'json':
235 return json_decode($result, 1);
236
237 default:
238 throw new \RuntimeException("Bad decoder format ($decode)");
239 }
240 }
241
242 /**
243 * @param $tests
244 * @return array
245 */
246 protected function indexTestsByInterface($tests) {
247 $byInterface = ['HeadlessInterface' => [], 'EndToEndInterface' => []];
248 foreach ($tests as $test) {
249 /** @var \PHPUnit\Framework\Test $test */
250 if ($test instanceof HeadlessInterface) {
251 $byInterface['HeadlessInterface'][get_class($test)] = 1;
252 }
253 if ($test instanceof EndToEndInterface) {
254 $byInterface['EndToEndInterface'][get_class($test)] = 1;
255 }
256 }
257 return $byInterface;
258 }
259
260 /**
261 * Ensure that any tests have sensible groups, e.g.
262 *
263 * `HeadlessInterface` ==> `group headless`
264 * `EndToEndInterface` ==> `group e2e`
265 *
266 * @param array $byInterface
267 */
268 protected function validateGroups($byInterface) {
269 foreach ($byInterface['HeadlessInterface'] as $className => $nonce) {
270 $clazz = new \ReflectionClass($className);
271 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
272 if (strpos($docComment, "@group headless\n") === FALSE) {
273 echo "WARNING: Class $className implements HeadlessInterface. It should declare \"@group headless\".\n";
274 }
275 if (strpos($docComment, "@group e2e\n") !== FALSE) {
276 echo "WARNING: Class $className implements HeadlessInterface. It should not declare \"@group e2e\".\n";
277 }
278 }
279 foreach ($byInterface['EndToEndInterface'] as $className => $nonce) {
280 $clazz = new \ReflectionClass($className);
281 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
282 if (strpos($docComment, "@group e2e\n") === FALSE) {
283 echo "WARNING: Class $className implements EndToEndInterface. It should declare \"@group e2e\".\n";
284 }
285 if (strpos($docComment, "@group headless\n") !== FALSE) {
286 echo "WARNING: Class $className implements EndToEndInterface. It should not declare \"@group headless\".\n";
287 }
288 }
289 }
290
291}