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 CiviTestListener
extends \PHPUnit_Framework_BaseTestListener
{
19 * @var \CRM_Core_TemporaryErrorScope
25 * Ex: $cache['Some_Test_Class']['civicrm_foobar'] = 'hook_civicrm_foobar';
26 * Array(string $testClass => Array(string $hookName => string $methodName)).
28 private $cache = array();
31 * @var \CRM_Core_Transaction|NULL
35 public function startTestSuite(\PHPUnit_Framework_TestSuite
$suite) {
36 $byInterface = $this->indexTestsByInterface($suite->tests());
37 $this->validateGroups($byInterface);
38 $this->autoboot($byInterface);
41 public function endTestSuite(\PHPUnit_Framework_TestSuite
$suite) {
42 $this->cache
= array();
45 public function startTest(\PHPUnit_Framework_Test
$test) {
46 if ($this->isCiviTest($test)) {
47 error_reporting(E_ALL
);
48 $this->errorScope
= \CRM_Core_TemporaryErrorScope
::useException();
51 if ($test instanceof HeadlessInterface
) {
52 $this->bootHeadless($test);
55 if ($test instanceof HookInterface
) {
56 // Note: bootHeadless() indirectly resets any hooks, which means that hook_civicrm_config
57 // is unsubscribable. However, after bootHeadless(), we're free to subscribe to hooks again.
58 $this->registerHooks($test);
61 if ($test instanceof TransactionalInterface
) {
62 $this->tx
= new \
CRM_Core_Transaction(TRUE);
63 $this->tx
->rollback();
70 public function endTest(\PHPUnit_Framework_Test
$test, $time) {
71 if ($test instanceof TransactionalInterface
) {
72 $this->tx
->rollback()->commit();
75 if ($test instanceof HookInterface
) {
76 \CRM_Utils_Hook
::singleton()->reset();
78 if ($this->isCiviTest($test)) {
79 error_reporting(E_ALL
& ~E_NOTICE
);
80 $this->errorScope
= NULL;
85 * @param HeadlessInterface|\PHPUnit_Framework_Test $test
87 protected function bootHeadless($test) {
88 if (CIVICRM_UF
!== 'UnitTests') {
89 throw new \
RuntimeException('HeadlessInterface requires CIVICRM_UF=UnitTests');
92 // Hrm, this seems wrong. Shouldn't we be resetting the entire session?
93 $session = \CRM_Core_Session
::singleton();
94 $session->set('userID', NULL);
96 $test->setUpHeadless();
98 \CRM_Utils_System
::flushCache();
100 \CRM_Core_Session
::singleton()->set('userID', NULL);
101 $config = \CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
103 if (property_exists($config->userPermissionClass
, 'permissions')) {
104 $config->userPermissionClass
->permissions
= NULL;
109 * @param \Civi\Test\HookInterface $test
111 * Array(string $hookName => string $methodName)).
113 protected function findTestHooks(HookInterface
$test) {
114 $class = get_class($test);
115 if (!isset($this->cache
[$class])) {
117 foreach (get_class_methods($class) as $func) {
118 if (preg_match('/^hook_/', $func)) {
119 $funcs[substr($func, 5)] = $func;
122 $this->cache
[$class] = $funcs;
124 return $this->cache
[$class];
128 * @param \PHPUnit_Framework_Test $test
131 protected function isCiviTest(\PHPUnit_Framework_Test
$test) {
132 return $test instanceof HookInterface ||
$test instanceof HeadlessInterface
;
136 * Find any hook functions in $test and register them.
138 * @param \Civi\Test\HookInterface $test
140 protected function registerHooks(HookInterface
$test) {
141 if (CIVICRM_UF
!== 'UnitTests') {
142 // This is not ideal -- it's just a side-effect of how hooks and E2E tests work.
143 // We can temporarily subscribe to hooks in-process, but for other processes, it gets messy.
144 throw new \
RuntimeException('CiviHookTestInterface requires CIVICRM_UF=UnitTests');
146 \CRM_Utils_Hook
::singleton()->reset();
147 /** @var \CRM_Utils_Hook_UnitTests $hooks */
148 $hooks = \CRM_Utils_Hook
::singleton();
149 foreach ($this->findTestHooks($test) as $hook => $func) {
150 $hooks->setHook($hook, array($test, $func));
155 * The first time we come across HeadlessInterface or EndToEndInterface, we'll
158 * Once the system is booted, there's nothing we can do -- we're stuck with that
159 * environment. (Thank you, prolific define()s!) If there's a conflict between a
160 * test-class and the active boot-level, then we'll have to bail.
162 * @param array $byInterface
163 * List of test classes, keyed by major interface (HeadlessInterface vs EndToEndInterface).
165 protected function autoboot($byInterface) {
166 if (defined('CIVICRM_UF')) {
167 // OK, nothing we can do. System has booted already.
169 elseif (!empty($byInterface['HeadlessInterface'])) {
170 putenv('CIVICRM_UF=UnitTests');
171 eval($this->cv('php:boot --level=full', 'phpcode'));
173 elseif (!empty($byInterface['EndToEndInterface'])) {
174 putenv('CIVICRM_UF=');
175 eval($this->cv('php:boot --level=full', 'phpcode'));
178 $blurb = "Tip: Run the headless tests and end-to-end tests separately, e.g.\n"
179 . " $ phpunit5 --group headless\n"
180 . " $ phpunit5 --group e2e \n";
182 if (!empty($byInterface['HeadlessInterface']) && CIVICRM_UF
!== 'UnitTests') {
183 $testNames = implode(', ', array_keys($byInterface['HeadlessInterface']));
184 throw new \
RuntimeException("Suite includes headless tests ($testNames) which require CIVICRM_UF=UnitTests.\n\n$blurb");
186 if (!empty($byInterface['EndToEndInterface']) && CIVICRM_UF
=== 'UnitTests') {
187 $testNames = implode(', ', array_keys($byInterface['EndToEndInterface']));
188 throw new \
RuntimeException("Suite includes end-to-end tests ($testNames) which do not support CIVICRM_UF=UnitTests.\n\n$blurb");
193 * Call the "cv" command.
195 * This duplicates the standalone `cv()` wrapper that is recommended in bootstrap.php.
196 * This duplication is necessary because `cv()` is optional, and downstream implementers
197 * may alter, rename, or omit the wrapper, and (by virtue of its role in bootstrap) there
198 * it is impossible to define it centrally.
201 * The rest of the command to send.
202 * @param string $decode
203 * Ex: 'json' or 'phpcode'.
205 * Response output (if the command executed normally).
206 * @throws \RuntimeException
207 * If the command terminates abnormally.
209 protected function cv($cmd, $decode = 'json') {
211 $descriptorSpec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => STDERR
);
212 $oldOutput = getenv('CV_OUTPUT');
213 putenv("CV_OUTPUT=json");
214 $process = proc_open($cmd, $descriptorSpec, $pipes, __DIR__
);
215 putenv("CV_OUTPUT=$oldOutput");
217 $result = stream_get_contents($pipes[1]);
219 if (proc_close($process) !== 0) {
220 throw new \
RuntimeException("Command failed ($cmd):\n$result");
227 // If the last output is /*PHPCODE*/, then we managed to complete execution.
228 if (substr(trim($result), 0, 12) !== "/*BEGINPHP*/" ||
substr(trim($result), -10) !== "/*ENDPHP*/") {
229 throw new \
RuntimeException("Command failed ($cmd):\n$result");
234 return json_decode($result, 1);
237 throw new \
RuntimeException("Bad decoder format ($decode)");
245 protected function indexTestsByInterface($tests) {
246 $byInterface = array('HeadlessInterface' => array(), 'EndToEndInterface' => array());
247 foreach ($tests as $test) {
248 /** @var \PHPUnit_Framework_Test $test */
249 if ($test instanceof HeadlessInterface
) {
250 $byInterface['HeadlessInterface'][get_class($test)] = 1;
252 if ($test instanceof EndToEndInterface
) {
253 $byInterface['EndToEndInterface'][get_class($test)] = 1;
260 * Ensure that any tests have sensible groups, e.g.
262 * `HeadlessInterface` ==> `group headless`
263 * `EndToEndInterface` ==> `group e2e`
265 * @param array $byInterface
267 protected function validateGroups($byInterface) {
268 foreach ($byInterface['HeadlessInterface'] as $className => $nonce) {
269 $clazz = new \
ReflectionClass($className);
270 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
271 if (strpos($docComment, "@group headless\n") === FALSE) {
272 echo "WARNING: Class $className implements HeadlessInterface. It should declare \"@group headless\".\n";
274 if (strpos($docComment, "@group e2e\n") !== FALSE) {
275 echo "WARNING: Class $className implements HeadlessInterface. It should not declare \"@group e2e\".\n";
278 foreach ($byInterface['EndToEndInterface'] as $className => $nonce) {
279 $clazz = new \
ReflectionClass($className);
280 $docComment = str_replace("\r\n", "\n", $clazz->getDocComment());
281 if (strpos($docComment, "@group e2e\n") === FALSE) {
282 echo "WARNING: Class $className implements EndToEndInterface. It should declare \"@group e2e\".\n";
284 if (strpos($docComment, "@group headless\n") !== FALSE) {
285 echo "WARNING: Class $className implements EndToEndInterface. It should not declare \"@group headless\".\n";