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
;
22 * @var \CRM_Core_TemporaryErrorScope
28 * Ex: $cache['Some_Test_Class']['civicrm_foobar'] = 'hook_civicrm_foobar';
29 * Array(string $testClass => Array(string $hookName => string $methodName)).
34 * @var \CRM_Core_Transaction|null
38 public function startTestSuite(\PHPUnit\Framework\TestSuite
$suite): void
{
39 $byInterface = $this->indexTestsByInterface($suite->tests());
40 $this->validateGroups($byInterface);
41 $this->autoboot($byInterface);
44 public function endTestSuite(\PHPUnit\Framework\TestSuite
$suite): void
{
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();
54 if ($test instanceof HeadlessInterface
) {
55 $this->bootHeadless($test);
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);
64 if ($test instanceof TransactionalInterface
) {
65 $this->tx
= new \
CRM_Core_Transaction(TRUE);
66 $this->tx
->rollback();
73 public function endTest(\PHPUnit\Framework\Test
$test, float $time): void
{
74 if ($test instanceof TransactionalInterface
) {
75 $this->tx
->rollback()->commit();
78 if ($test instanceof HookInterface
) {
79 \CRM_Utils_Hook
::singleton()->reset();
81 if ($this->isCiviTest($test)) {
82 error_reporting(E_ALL
& ~E_NOTICE
);
83 $this->errorScope
= NULL;
88 * @param HeadlessInterface|\PHPUnit\Framework\Test $test
90 protected function bootHeadless($test) {
91 if (CIVICRM_UF
!== 'UnitTests') {
92 throw new \
RuntimeException('HeadlessInterface requires CIVICRM_UF=UnitTests');
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();
100 \CRM_Utils_System
::flushCache();
102 \CRM_Core_Session
::singleton()->set('userID', NULL);
104 $config = \CRM_Core_Config
::singleton(TRUE, TRUE);
106 if (property_exists($config->userPermissionClass
, 'permissions')) {
107 $config->userPermissionClass
->permissions
= NULL;
112 * @param \Civi\Test\HookInterface $test
114 * Array(string $hookName => string $methodName)).
116 protected function findTestHooks(HookInterface
$test) {
117 $class = get_class($test);
118 if (!isset($this->cache
[$class])) {
120 foreach (get_class_methods($class) as $func) {
121 if (preg_match('/^hook_/', $func)) {
122 $funcs[substr($func, 5)] = $func;
125 $this->cache
[$class] = $funcs;
127 return $this->cache
[$class];
131 * @param \PHPUnit\Framework\Test $test
134 protected function isCiviTest(\PHPUnit\Framework\Test
$test) {
135 return $test instanceof HookInterface ||
$test instanceof HeadlessInterface
;
139 * Find any hook functions in $test and register them.
141 * @param \Civi\Test\HookInterface $test
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');
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]);
158 * The first time we come across HeadlessInterface or EndToEndInterface, we'll
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.
165 * @param array $byInterface
166 * List of test classes, keyed by major interface (HeadlessInterface vs EndToEndInterface).
168 protected function autoboot($byInterface) {
169 if (defined('CIVICRM_UF')) {
170 // OK, nothing we can do. System has booted already.
172 elseif (!empty($byInterface['HeadlessInterface'])) {
173 putenv('CIVICRM_UF=UnitTests');
175 eval($this->cv('php:boot --level=full', 'phpcode'));
178 elseif (!empty($byInterface['EndToEndInterface'])) {
179 putenv('CIVICRM_UF=');
181 eval($this->cv('php:boot --level=full', 'phpcode'));
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";
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");
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");
200 * Call the "cv" command.
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.
208 * The rest of the command to send.
209 * @param string $decode
210 * Ex: 'json' or 'phpcode'.
212 * Response output (if the command executed normally).
213 * @throws \RuntimeException
214 * If the command terminates abnormally.
216 protected function cv($cmd, $decode = 'json') {
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");
224 $result = stream_get_contents($pipes[1]);
226 if (proc_close($process) !== 0) {
227 throw new \
RuntimeException("Command failed ($cmd):\n$result");
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");
241 return json_decode($result, 1);
244 throw new \
RuntimeException("Bad decoder format ($decode)");
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;
259 if ($test instanceof EndToEndInterface
) {
260 $byInterface['EndToEndInterface'][get_class($test)] = 1;
267 * Ensure that any tests have sensible groups, e.g.
269 * `HeadlessInterface` ==> `group headless`
270 * `EndToEndInterface` ==> `group e2e`
272 * @param array $byInterface
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";
281 if (strpos($docComment, "@group e2e\n") !== FALSE) {
282 echo "WARNING: Class $className implements HeadlessInterface. It should not declare \"@group e2e\".\n";
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";
291 if (strpos($docComment, "@group headless\n") !== FALSE) {
292 echo "WARNING: Class $className implements EndToEndInterface. It should not declare \"@group headless\".\n";