5 use Civi\API\Exception\NotImplementedException
;
11 * This trait defines a number of helper functions for testing APIv3. Commonly
12 * used helpers include `callAPISuccess()`, `callAPIFailure()`,
13 * `assertAPISuccess()`, and `assertAPIFailure()`.
15 * This trait is intended for use with PHPUnit-based test cases.
20 * Get the api versions to test.
24 public function versionThreeAndFour() {
29 * Api version - easier to override than just a define
32 protected $_apiversion = 3;
35 * Check that api returned 'is_error' => 1
36 * else provide full message
37 * @param array $result
39 * @param array $valuesToExclude
40 * @param string $prefix
41 * Extra test to add to message.
43 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = [], $prefix = '') {
44 $valuesToExclude = array_merge($valuesToExclude, ['debug', 'xdebug', 'sequential']);
45 foreach ($valuesToExclude as $value) {
46 if (isset($result[$value])) {
47 unset($result[$value]);
49 if (isset($expected[$value])) {
50 unset($expected[$value]);
53 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
57 * Check that a deleted item has been deleted.
62 public function assertAPIDeleted($entity, $id) {
63 $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0);
67 * Check that api returned 'is_error' => 1.
69 * @param array $apiResult
71 * @param string $prefix
72 * Extra test to add to message.
73 * @param null $expectedError
75 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
76 if (!empty($prefix)) {
79 if ($expectedError && !empty($apiResult['is_error'])) {
80 $this->assertContains($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
82 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
83 $this->assertNotEmpty($apiResult['error_message']);
87 * Check that api returned 'is_error' => 0.
89 * @param array $apiResult
91 * @param string $prefix
92 * Extra test to add to message.
94 public function assertAPISuccess($apiResult, $prefix = '') {
95 if (!empty($prefix)) {
98 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
100 if (!empty($apiResult['debug_information'])) {
101 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
103 if (!empty($apiResult['trace'])) {
104 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
106 $this->assertEmpty(\CRM_Utils_Array
::value('is_error', $apiResult), $prefix . $errorMessage);
110 * This function exists to wrap api functions.
111 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
112 * @param string $entity
113 * @param string $action
114 * @param array $params
115 * @param string $expectedErrorMessage
117 * @param null $extraOutput
120 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
121 if (is_array($params)) {
123 'version' => $this->_apiversion
,
126 $result = $this->civicrm_api($entity, $action, $params);
127 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
132 * wrap api functions.
133 * so we can ensure they succeed & throw exceptions without litterering the test with checks
135 * @param string $entity
136 * @param string $action
137 * @param array $params
138 * @param mixed $checkAgainst
139 * Optional value to check result against, implemented for getvalue,.
140 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
141 * for getsingle the array is compared against an array passed in - the id is not compared (for
146 public function callAPISuccess($entity, $action, $params = [], $checkAgainst = NULL) {
147 $params = array_merge([
148 'version' => $this->_apiversion
,
153 switch (strtolower($action)) {
155 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
158 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
161 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
163 $result = $this->civicrm_api($entity, $action, $params);
164 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
169 * This function exists to wrap api getValue function & check the result
170 * so we can ensure they succeed & throw exceptions without litterering the test with checks
171 * There is a type check in this
173 * @param string $entity
174 * @param array $params
177 * @throws \CRM_Core_Exception
181 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
183 'version' => $this->_apiversion
,
186 $result = $this->civicrm_api($entity, 'getcount', $params);
187 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
188 throw new \
CRM_Core_Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
190 if (is_int($count)) {
191 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
197 * This function exists to wrap api getsingle function & check the result
198 * so we can ensure they succeed & throw exceptions without litterering the test with checks
200 * @param string $entity
201 * @param array $params
202 * @param array $checkAgainst
203 * Array to compare result against.
211 * @throws \CRM_Core_Exception
215 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
217 'version' => $this->_apiversion
,
219 $result = $this->civicrm_api($entity, 'getsingle', $params);
220 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
221 $unfilteredResult = $this->civicrm_api($entity, 'get', ['version' => $this->_apiversion
]);
222 throw new \
CRM_Core_Exception(
223 'Invalid getsingle result' . print_r($result, TRUE)
224 . "\n entity: $entity . \n params \n " . print_r($params, TRUE)
225 . "\n entities retrieved with blank params \n" . print_r($unfilteredResult, TRUE)
229 // @todo - have gone with the fn that unsets id? should we check id?
230 $this->checkArrayEquals($result, $checkAgainst);
236 * This function exists to wrap api getValue function & check the result
237 * so we can ensure they succeed & throw exceptions without litterering the test with checks
238 * There is a type check in this
240 * @param string $entity
241 * @param array $params
242 * @param string $type
243 * Per http://php.net/manual/en/function.gettype.php possible types.
253 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
255 'version' => $this->_apiversion
,
258 $result = $this->civicrm_api($entity, 'getvalue', $params);
259 if (is_array($result) && (!empty($result['is_error']) ||
isset($result['values']))) {
260 throw new \
Exception('Invalid getvalue result' . print_r($result, TRUE));
263 if ($type == 'integer') {
264 // api seems to return integers as strings
265 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
268 $this->assertType($type, $result, "returned result should have been of type $type but was ");
275 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
279 * @param array $params
282 public function civicrm_api($entity, $action, $params = []) {
283 if (\CRM_Utils_Array
::value('version', $params) == 4) {
284 return $this->runApi4Legacy($entity, $action, $params);
286 return civicrm_api($entity, $action, $params);
290 * Emulate v3 syntax so we can run api3 tests on v4
294 * @param array $v3Params
296 * @throws \API_Exception
297 * @throws \CiviCRM_API3_Exception
300 public function runApi4Legacy($v3Entity, $v3Action, $v3Params = []) {
301 $v4Entity = self
::convertEntityNameToApi4($v3Entity);
302 $v4Action = $v3Action = strtolower($v3Action);
303 $v4Params = ['checkPermissions' => isset($v3Params['check_permissions']) ?
(bool) $v3Params['check_permissions'] : FALSE];
304 $sequential = !empty($v3Params['sequential']);
305 $options = \
_civicrm_api3_get_options_from_params($v3Params, in_array($v4Entity, ['Contact', 'Participant', 'Event', 'Group', 'Contribution', 'Membership']));
306 $indexBy = in_array($v3Action, ['get', 'create', 'replace']) && !$sequential ?
'id' : NULL;
307 $onlyId = !empty($v3Params['format.only_id']);
308 $onlySuccess = !empty($v3Params['format.is_success']);
309 if (!empty($v3Params['filters']['is_current']) ||
!empty($v3Params['isCurrent'])) {
310 $v4Params['current'] = TRUE;
312 $language = !empty($v3Params['options']['language']) ?
$v3Params['options']['language'] : \CRM_Utils_Array
::value('option.language', $v3Params);
314 $v4Params['language'] = $language;
316 $toRemove = ['option.', 'return', 'api.', 'format.'];
319 foreach ($v3Params as $key => $val) {
320 foreach ($toRemove as $remove) {
321 if (strpos($key, $remove) === 0) {
322 if ($remove == 'api.') {
323 $chains[$key] = $val;
325 unset($v3Params[$key]);
330 $v3Fields = civicrm_api3($v3Entity, 'getfields', ['action' => $v3Action])['values'];
333 foreach ($v3Params as $key => $val) {
334 if ($val === 'null') {
335 $v3Params[$key] = NULL;
339 if ($v4Entity == 'Setting') {
341 $v4Params['domainId'] = \CRM_Utils_Array
::value('domain_id', $v3Params);
342 if ($v3Action == 'getfields') {
343 if (!empty($v3Params['name'])) {
344 $v3Params['filters']['name'] = $v3Params['name'];
346 foreach (\CRM_Utils_Array
::value('filters', $v3Params, []) as $filter => $val) {
347 $v4Params['where'][] = [$filter, '=', $val];
350 if ($v3Action == 'create') {
353 if ($v3Action == 'revert') {
354 $v4Params['select'] = (array) $v3Params['name'];
356 if ($v3Action == 'getvalue') {
357 $options['return'] = [$v3Params['name'] => 1];
360 \CRM_Utils_Array
::remove($v3Params, 'domain_id', 'name');
363 \CRM_Utils_Array
::remove($v3Params, 'options', 'debug', 'version', 'sort', 'offset', 'rowCount', 'check_permissions', 'sequential', 'filters', 'isCurrent');
365 // Work around ugly hack in v3 Domain api
366 if ($v4Entity == 'Domain') {
367 $v3Fields['version'] = ['name' => 'version', 'api.aliases' => ['domain_version']];
368 unset($v3Fields['domain_version']);
371 foreach ($v3Fields as $name => $field) {
372 // Resolve v3 aliases
373 foreach (\CRM_Utils_Array
::value('api.aliases', $field, []) as $alias) {
374 if (isset($v3Params[$alias])) {
375 $v3Params[$field['name']] = $v3Params[$alias];
376 unset($v3Params[$alias]);
379 // Convert custom field names
380 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
381 // Strictly speaking, using titles instead of names is incorrect, but it works for
382 // unit tests where names and titles are identical and saves an extra db lookup.
383 $custom[$field['groupTitle']][$field['title']] = $name;
384 $v4FieldName = $field['groupTitle'] . '.' . $field['title'];
385 if (isset($v3Params[$name])) {
386 $v3Params[$v4FieldName] = $v3Params[$name];
387 unset($v3Params[$name]);
389 if (isset($options['return'][$name])) {
390 $options['return'][$v4FieldName] = 1;
391 unset($options['return'][$name]);
398 $v4Params['select'] = ['row_count'];
399 // No break - keep processing as get
403 // No break - keep processing as get
405 if ($options['return'] && $v3Action !== 'getcount') {
406 $v4Params['select'] = array_keys($options['return']);
408 if ($options['limit'] && $v4Entity != 'Setting') {
409 $v4Params['limit'] = $options['limit'];
411 if ($options['offset']) {
412 $v4Params['offset'] = $options['offset'];
414 if ($options['sort']) {
415 foreach (explode(',', $options['sort']) as $sort) {
416 list($sortField, $sortDir) = array_pad(explode(' ', trim($sort)), 2, 'ASC');
417 $v4Params['orderBy'][$sortField] = $sortDir;
423 if (empty($v3Params['values'])) {
424 $v4Action = 'delete';
427 $v4Params['records'] = $v3Params['values'];
429 unset($v3Params['values']);
434 if (!empty($v3Params['id'])) {
435 $v4Action = 'update';
436 $v4Params['where'][] = ['id', '=', $v3Params['id']];
439 $v4Params['values'] = $v3Params;
440 unset($v4Params['values']['id']);
444 if (!empty($v3Params['id'])) {
445 $v4Params['where'][] = ['id', '=', $v3Params['id']];
451 $v4Action = 'getFields';
453 'where' => [['name', '=', $v3Params['field']]],
454 'loadOptions' => TRUE,
459 $v4Action = 'getFields';
460 if (!empty($v3Params['action']) ||
!empty($v3Params['api_action'])) {
461 $v4Params['action'] = !empty($v3Params['action']) ?
$v3Params['action'] : $v3Params['api_action'];
463 $indexBy = !$sequential ?
'name' : NULL;
467 // Ensure this api4 entity/action exists
469 $actionInfo = \
civicrm_api4($v4Entity, 'getActions', ['checkPermissions' => FALSE, 'where' => [['name', '=', $v4Action]]]);
471 catch (NotImplementedException
$e) {
472 // For now we'll mark the test incomplete if a v4 entity doesn't exit yet
473 $this->markTestIncomplete($e->getMessage());
475 if (!isset($actionInfo[0])) {
476 throw new \
Exception("Api4 $v4Entity $v4Action does not exist.");
479 // Migrate special params like fix_address
480 foreach ($actionInfo[0]['params'] as $v4ParamName => $paramInfo) {
481 // camelCase in api4, lower_case in api3
482 $v3ParamName = strtolower(preg_replace('/(?=[A-Z])/', '_$0', $v4ParamName));
483 if (isset($v3Params[$v3ParamName])) {
484 $v4Params[$v4ParamName] = $v3Params[$v3ParamName];
485 unset($v3Params[$v3ParamName]);
486 if ($paramInfo['type'][0] == 'bool') {
487 $v4Params[$v4ParamName] = (bool) $v4Params[$v4ParamName];
492 // Build where clause for 'getcount', 'getsingle', 'getvalue', 'get' & 'replace'
493 if ($v4Action == 'get' ||
$v3Action == 'replace') {
494 foreach ($v3Params as $key => $val) {
496 if (is_array($val) && count($val) == 1 && array_intersect_key($val, array_flip(\CRM_Core_DAO
::acceptedSQLOperators()))) {
497 foreach ($val as $op => $newVal) {
501 $v4Params['where'][] = [$key, $op, $val];
506 $result = \
civicrm_api4($v4Entity, $v4Action, $v4Params, $indexBy);
508 catch (\Exception
$e) {
509 return $onlySuccess ?
0 : [
511 'error_message' => $e->getMessage(),
516 if (($v3Action == 'getsingle' ||
$v3Action == 'getvalue') && count($result) != 1) {
517 return $onlySuccess ?
0 : [
519 'error_message' => "Expected one $v4Entity but found " . count($result),
520 'count' => count($result),
528 if ($v3Action == 'getcount') {
529 return $result->count();
533 return $result->first()['id'];
536 if ($v3Action == 'getvalue' && $v4Entity == 'Setting') {
537 return \CRM_Utils_Array
::value('value', $result->first());
540 if ($v3Action == 'getvalue') {
541 return \CRM_Utils_Array
::value(array_keys($options['return'])[0], $result->first());
544 // Mimic api3 behavior when using 'replace' action to delete all
545 if ($v3Action == 'replace' && $v4Action == 'delete') {
546 $result->exchangeArray([]);
549 if ($v3Action == 'getoptions') {
552 'count' => $result['options'] ?
count($result['options']) : 0,
553 'values' => $result['options'] ?
: [],
558 // Emulate the weird return format of api3 settings
559 if (($v3Action == 'get' ||
$v3Action == 'create') && $v4Entity == 'Setting') {
561 foreach ($result as $item) {
562 $settings[$item['domain_id']][$item['name']] = $item['value'];
564 $result->exchangeArray($sequential ?
array_values($settings) : $settings);
567 foreach ($result as $index => $row) {
569 foreach ($chains as $key => $params) {
570 $result[$index][$key] = $this->runApi4LegacyChain($key, $params, $v4Entity, $row, $sequential);
572 // Resolve custom field names
573 foreach ($custom as $group => $fields) {
574 if (isset($row[$group])) {
575 foreach ($fields as $field => $v3FieldName) {
576 if (isset($row[$group][$field])) {
577 $result[$index][$v3FieldName] = $row[$group][$field];
580 unset($result[$index][$group]);
585 if ($v3Action == 'getsingle') {
586 return $result->first();
592 'count' => count($result),
593 'values' => (array) $result,
594 'id' => is_object($result) && count($result) == 1 ? \CRM_Utils_Array
::value('id', $result->first()) : NULL,
600 * @param mixed $params
601 * @param string $mainEntity
602 * @param array $result
603 * @param bool $sequential
605 * @throws \API_Exception
607 protected function runApi4LegacyChain($key, $params, $mainEntity, $result, $sequential) {
608 // Handle an array of multiple calls using recursion
609 if (is_array($params) && isset($params[0]) && is_array($params[0])) {
611 foreach ($params as $chain) {
612 $results[] = $this->runApi4LegacyChain($key, $chain, $mainEntity, $result, $sequential);
617 // Handle single api call
618 list(, $chainEntity, $chainAction) = explode('.', $key);
619 $lcChainEntity = \
_civicrm_api_get_entity_name_from_camel($chainEntity);
620 $chainEntity = self
::convertEntityNameToApi4($chainEntity);
621 $lcMainEntity = \
_civicrm_api_get_entity_name_from_camel($mainEntity);
622 $params = is_array($params) ?
$params : [];
624 // Api3 expects this to be inherited
625 $params +
= ['sequential' => $sequential];
627 // Replace $value.field_name
628 foreach ($params as $name => $param) {
629 if (is_string($param) && strpos($param, '$value.') === 0) {
630 $param = substr($param, 7);
631 $params[$name] = \CRM_Utils_Array
::value($param, $result);
636 $getFields = civicrm_api4($chainEntity, 'getFields', ['select' => ['name']], 'name');
638 catch (NotImplementedException
$e) {
639 $this->markTestIncomplete($e->getMessage());
642 // Emulate the string-fu guesswork that api3 does
643 if ($chainEntity == $mainEntity && empty($params['id']) && !empty($result['id'])) {
644 $params['id'] = $result['id'];
646 elseif (empty($params['id']) && !empty($result[$lcChainEntity . '_id'])) {
647 $params['id'] = $result[$lcChainEntity . '_id'];
649 elseif (!empty($result['id']) && isset($getFields[$lcMainEntity . '_id']) && empty($params[$lcMainEntity . '_id'])) {
650 $params[$lcMainEntity . '_id'] = $result['id'];
652 return $this->runApi4Legacy($chainEntity, $chainAction, $params);
656 * Fix the naming differences between api3 & api4 entities.
658 * @param string $legacyName
661 public static function convertEntityNameToApi4($legacyName) {
662 $api4Name = \CRM_Utils_String
::convertStringToCamel($legacyName);
667 return \CRM_Utils_Array
::value($api4Name, $map, $api4Name);