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