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