6 * Class CiviTestListener
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.
13 * @see EndToEndInterface
14 * @see HeadlessInterface
17 class CiviTestListenerPHPUnit7
implements \PHPUnit\Framework\TestListener
{
19 use \PHPUnit\Framework\TestListenerDefaultImplementation
;
23 * Ex: $cache['Some_Test_Class']['civicrm_foobar'] = 'hook_civicrm_foobar';
24 * Array(string $testClass => Array(string $hookName => string $methodName)).
29 * @var \CRM_Core_Transaction|null
33 public function startTestSuite(\PHPUnit\Framework\TestSuite
$suite): void
{
34 $byInterface = $this->indexTestsByInterface($suite->tests());
35 $this->validateGroups($byInterface);
36 $this->autoboot($byInterface);
39 public function endTestSuite(\PHPUnit\Framework\TestSuite
$suite): void
{
43 public function startTest(\PHPUnit\Framework\Test
$test): void
{
44 if ($this->isCiviTest($test)) {
45 error_reporting(E_ALL
);
48 if ($test instanceof HeadlessInterface
) {
49 $this->bootHeadless($test);
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);
58 if ($test instanceof TransactionalInterface
) {
59 $this->tx
= new \
CRM_Core_Transaction(TRUE);
60 $this->tx
->rollback();
67 public function endTest(\PHPUnit\Framework\Test
$test, float $time): void
{
68 if ($test instanceof TransactionalInterface
) {
69 $this->tx
->rollback()->commit();
72 if ($test instanceof HookInterface
) {
73 \CRM_Utils_Hook
::singleton()->reset();
75 \CRM_Utils_Time
::resetTime();
76 if ($this->isCiviTest($test)) {
77 error_reporting(E_ALL
& ~E_NOTICE
);
78 $this->errorScope
= NULL;
83 * @param HeadlessInterface|\PHPUnit\Framework\Test $test
85 protected function bootHeadless($test) {
86 if (CIVICRM_UF
!== 'UnitTests') {
87 throw new \
RuntimeException('HeadlessInterface requires CIVICRM_UF=UnitTests');
90 // Hrm, this seems wrong. Shouldn't we be resetting the entire session?
91 $session = \CRM_Core_Session
::singleton();
92 $session->set('userID', NULL);
93 $test->setUpHeadless();
95 \CRM_Utils_System
::flushCache();
97 \CRM_Core_Session
::singleton()->set('userID', NULL);
99 $config = \CRM_Core_Config
::singleton(TRUE, TRUE);
101 if (property_exists($config->userPermissionClass
, 'permissions')) {
102 $config->userPermissionClass
->permissions
= NULL;
107 * @param \Civi\Test\HookInterface $test
109 * Array(string $hookName => string $methodName)).
111 protected function findTestHooks(HookInterface
$test) {
112 $class = get_class($test);
113 if (!isset($this->cache
[$class])) {
115 foreach (get_class_methods($class) as $func) {
116 if (preg_match('/^hook_/', $func)) {
117 $funcs[substr($func, 5)] = $func;
120 $this->cache
[$class] = $funcs;
122 return $this->cache
[$class];
126 * @param \PHPUnit\Framework\Test $test
129 protected function isCiviTest(\PHPUnit\Framework\Test
$test) {
130 return $test instanceof HookInterface ||
$test instanceof HeadlessInterface
;
134 * Find any hook functions in $test and register them.
136 * @param \Civi\Test\HookInterface $test
138 protected function registerHooks(HookInterface
$test) {
139 if (CIVICRM_UF
!== 'UnitTests') {
140 // This is not ideal -- it's just a side-effect of how hooks and E2E tests work.
141 // We can temporarily subscribe to hooks in-process, but for other processes, it gets messy.
142 throw new \
RuntimeException('CiviHookTestInterface requires CIVICRM_UF=UnitTests');
144 \CRM_Utils_Hook
::singleton()->reset();
145 /** @var \CRM_Utils_Hook_UnitTests $hooks */
146 $hooks = \CRM_Utils_Hook
::singleton();
147 foreach ($this->findTestHooks($test) as $hook => $func) {
148 $hooks->setHook($hook, [$test, $func]);
153 * The first time we come across HeadlessInterface or EndToEndInterface, we'll
156 * Once the system is booted, there's nothing we can do -- we're stuck with that
157 * environment. (Thank you, prolific define()s!) If there's a conflict between a
158 * test-class and the active boot-level, then we'll have to bail.
160 * @param array $byInterface
161 * List of test classes, keyed by major interface (HeadlessInterface vs EndToEndInterface).
163 protected function autoboot($byInterface) {
164 if (defined('CIVICRM_UF')) {
165 // OK, nothing we can do. System has booted already.
167 elseif (!empty($byInterface['HeadlessInterface'])) {
168 putenv('CIVICRM_UF=UnitTests');
170 eval($this->cv('php:boot --level=full', 'phpcode'));
173 elseif (!empty($byInterface['EndToEndInterface'])) {
174 putenv('CIVICRM_UF=');
176 eval($this->cv('php:boot --level=full', 'phpcode'));
180 $blurb = "Tip: Run the headless tests and end-to-end tests separately, e.g.\n"
181 . " $ phpunit5 --group headless\n"
182 . " $ phpunit5 --group e2e \n";
184 if (!empty($byInterface['HeadlessInterface']) && CIVICRM_UF
!== 'UnitTests') {
185 $testNames = implode(', ', array_keys($byInterface['HeadlessInterface']));
186 throw new \
RuntimeException("Suite includes headless tests ($testNames) which require CIVICRM_UF=UnitTests.\n\n$blurb");
188 if (!empty($byInterface['EndToEndInterface']) && CIVICRM_UF
=== 'UnitTests') {
189 $testNames = implode(', ', array_keys($byInterface['EndToEndInterface']));
190 throw new \
RuntimeException("Suite includes end-to-end tests ($testNames) which do not support CIVICRM_UF=UnitTests.\n\n$blurb");
195 * Call the "cv" command.
197 * This duplicates the standalone `cv()` wrapper that is recommended in bootstrap.php.
198 * This duplication is necessary because `cv()` is optional, and downstream implementers
199 * may alter, rename, or omit the wrapper, and (by virtue of its role in bootstrap) there
200 * it is impossible to define it centrally.
203 * The rest of the command to send.
204 * @param string $decode
205 * Ex: 'json' or 'phpcode'.
207 * Response output (if the command executed normally).
208 * @throws \RuntimeException
209 * If the command terminates abnormally.
211 protected function cv($cmd, $decode = 'json') {
213 $descriptorSpec = [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => STDERR
];
214 $oldOutput = getenv('CV_OUTPUT');
215 putenv("CV_OUTPUT=json");
216 $process = proc_open($cmd, $descriptorSpec, $pipes, __DIR__
);
217 putenv("CV_OUTPUT=$oldOutput");
219 $result = stream_get_contents($pipes[1]);
221 if (proc_close($process) !== 0) {
222 throw new \
RuntimeException("Command failed ($cmd):\n$result");
229 // If the last output is /*PHPCODE*/, then we managed to complete execution.
230 if (substr(trim($result), 0, 12) !== "/*BEGINPHP*/" ||
substr(trim($result), -10) !== "/*ENDPHP*/") {
231 throw new \
RuntimeException("Command failed ($cmd):\n$result");
236 return json_decode($result, 1);
239 throw new \
RuntimeException("Bad decoder format ($decode)");
247 protected function indexTestsByInterface($tests) {
248 $byInterface = ['HeadlessInterface' => [], 'EndToEndInterface' => []];
249 foreach ($tests as $test) {
250 /** @var \PHPUnit\Framework\Test $test */
251 if ($test instanceof HeadlessInterface
) {
252 $byInterface['HeadlessInterface'][get_class($test)] = 1;
254 if ($test instanceof EndToEndInterface
) {
255 $byInterface['EndToEndInterface'][get_class($test)] = 1;
262 * Ensure that any tests have sensible groups, e.g.
264 * `HeadlessInterface` ==> `group headless`
265 * `EndToEndInterface` ==> `group e2e`
267 * @param array $byInterface
269 protected function validateGroups($byInterface) {
270 foreach ($byInterface['HeadlessInterface'] as $className => $nonce) {
271 $clazz = new \
ReflectionClass($className);
272 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
273 if (strpos($docComment, "@group headless\n") === FALSE) {
274 echo "WARNING: Class $className implements HeadlessInterface. It should declare \"@group headless\".\n";
276 if (strpos($docComment, "@group e2e\n") !== FALSE) {
277 echo "WARNING: Class $className implements HeadlessInterface. It should not declare \"@group e2e\".\n";
280 foreach ($byInterface['EndToEndInterface'] as $className => $nonce) {
281 $clazz = new \
ReflectionClass($className);
282 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
283 if (strpos($docComment, "@group e2e\n") === FALSE) {
284 echo "WARNING: Class $className implements EndToEndInterface. It should declare \"@group e2e\".\n";
286 if (strpos($docComment, "@group headless\n") !== FALSE) {
287 echo "WARNING: Class $className implements EndToEndInterface. It should not declare \"@group headless\".\n";