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
);
46 $GLOBALS['CIVICRM_TEST_CASE'] = $test;
49 if ($test instanceof HeadlessInterface
) {
50 $this->bootHeadless($test);
53 if ($test instanceof TransactionalInterface
) {
54 $this->tx
= new \
CRM_Core_Transaction(TRUE);
55 $this->tx
->rollback();
62 public function endTest(\PHPUnit\Framework\Test
$test, float $time): void
{
63 if ($test instanceof TransactionalInterface
) {
64 $this->tx
->rollback()->commit();
67 if ($test instanceof HookInterface
) {
68 \CRM_Utils_Hook
::singleton()->reset();
70 \CRM_Utils_Time
::resetTime();
71 if ($this->isCiviTest($test)) {
72 unset($GLOBALS['CIVICRM_TEST_CASE']);
73 error_reporting(E_ALL
& ~E_NOTICE
);
74 $this->errorScope
= NULL;
79 * @param HeadlessInterface|\PHPUnit\Framework\Test $test
81 protected function bootHeadless($test) {
82 if (CIVICRM_UF
!== 'UnitTests') {
83 throw new \
RuntimeException('HeadlessInterface requires CIVICRM_UF=UnitTests');
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 $test->setUpHeadless();
91 \CRM_Utils_System
::flushCache();
93 \CRM_Core_Session
::singleton()->set('userID', NULL);
95 $config = \CRM_Core_Config
::singleton(TRUE, TRUE);
97 if (property_exists($config->userPermissionClass
, 'permissions')) {
98 $config->userPermissionClass
->permissions
= NULL;
103 * @param \PHPUnit\Framework\Test $test
106 protected function isCiviTest(\PHPUnit\Framework\Test
$test) {
107 return $test instanceof HookInterface ||
$test instanceof HeadlessInterface
;
111 * The first time we come across HeadlessInterface or EndToEndInterface, we'll
114 * Once the system is booted, there's nothing we can do -- we're stuck with that
115 * environment. (Thank you, prolific define()s!) If there's a conflict between a
116 * test-class and the active boot-level, then we'll have to bail.
118 * @param array $byInterface
119 * List of test classes, keyed by major interface (HeadlessInterface vs EndToEndInterface).
121 protected function autoboot($byInterface) {
122 if (defined('CIVICRM_UF')) {
123 // OK, nothing we can do. System has booted already.
125 elseif (!empty($byInterface['HeadlessInterface'])) {
126 putenv('CIVICRM_UF=UnitTests');
128 eval($this->cv('php:boot --level=full', 'phpcode'));
131 elseif (!empty($byInterface['EndToEndInterface'])) {
132 putenv('CIVICRM_UF=');
134 eval($this->cv('php:boot --level=full', 'phpcode'));
138 $blurb = "Tip: Run the headless tests and end-to-end tests separately, e.g.\n"
139 . " $ phpunit5 --group headless\n"
140 . " $ phpunit5 --group e2e \n";
142 if (!empty($byInterface['HeadlessInterface']) && CIVICRM_UF
!== 'UnitTests') {
143 $testNames = implode(', ', array_keys($byInterface['HeadlessInterface']));
144 throw new \
RuntimeException("Suite includes headless tests ($testNames) which require CIVICRM_UF=UnitTests.\n\n$blurb");
146 if (!empty($byInterface['EndToEndInterface']) && CIVICRM_UF
=== 'UnitTests') {
147 $testNames = implode(', ', array_keys($byInterface['EndToEndInterface']));
148 throw new \
RuntimeException("Suite includes end-to-end tests ($testNames) which do not support CIVICRM_UF=UnitTests.\n\n$blurb");
153 * Call the "cv" command.
155 * This duplicates the standalone `cv()` wrapper that is recommended in bootstrap.php.
156 * This duplication is necessary because `cv()` is optional, and downstream implementers
157 * may alter, rename, or omit the wrapper, and (by virtue of its role in bootstrap) there
158 * it is impossible to define it centrally.
161 * The rest of the command to send.
162 * @param string $decode
163 * Ex: 'json' or 'phpcode'.
165 * Response output (if the command executed normally).
166 * @throws \RuntimeException
167 * If the command terminates abnormally.
169 protected function cv($cmd, $decode = 'json') {
171 $descriptorSpec = [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => STDERR
];
172 $oldOutput = getenv('CV_OUTPUT');
173 putenv("CV_OUTPUT=json");
174 $process = proc_open($cmd, $descriptorSpec, $pipes, __DIR__
);
175 putenv("CV_OUTPUT=$oldOutput");
177 $result = stream_get_contents($pipes[1]);
179 if (proc_close($process) !== 0) {
180 throw new \
RuntimeException("Command failed ($cmd):\n$result");
187 // If the last output is /*PHPCODE*/, then we managed to complete execution.
188 if (substr(trim($result), 0, 12) !== "/*BEGINPHP*/" ||
substr(trim($result), -10) !== "/*ENDPHP*/") {
189 throw new \
RuntimeException("Command failed ($cmd):\n$result");
194 return json_decode($result, 1);
197 throw new \
RuntimeException("Bad decoder format ($decode)");
205 protected function indexTestsByInterface($tests) {
206 $byInterface = ['HeadlessInterface' => [], 'EndToEndInterface' => []];
207 foreach ($tests as $test) {
208 /** @var \PHPUnit\Framework\Test $test */
209 if ($test instanceof HeadlessInterface
) {
210 $byInterface['HeadlessInterface'][get_class($test)] = 1;
212 if ($test instanceof EndToEndInterface
) {
213 $byInterface['EndToEndInterface'][get_class($test)] = 1;
220 * Ensure that any tests have sensible groups, e.g.
222 * `HeadlessInterface` ==> `group headless`
223 * `EndToEndInterface` ==> `group e2e`
225 * @param array $byInterface
227 protected function validateGroups($byInterface) {
228 foreach ($byInterface['HeadlessInterface'] as $className => $nonce) {
229 $clazz = new \
ReflectionClass($className);
230 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
231 if (strpos($docComment, "@group headless\n") === FALSE) {
232 echo "WARNING: Class $className implements HeadlessInterface. It should declare \"@group headless\".\n";
234 if (strpos($docComment, "@group e2e\n") !== FALSE) {
235 echo "WARNING: Class $className implements HeadlessInterface. It should not declare \"@group e2e\".\n";
238 foreach ($byInterface['EndToEndInterface'] as $className => $nonce) {
239 $clazz = new \
ReflectionClass($className);
240 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
241 if (strpos($docComment, "@group e2e\n") === FALSE) {
242 echo "WARNING: Class $className implements EndToEndInterface. It should declare \"@group e2e\".\n";
244 if (strpos($docComment, "@group headless\n") !== FALSE) {
245 echo "WARNING: Class $className implements EndToEndInterface. It should not declare \"@group headless\".\n";