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