5 use Civi\API\Exception\NotImplementedException
;
7 require_once 'api/v3/utils.php';
12 * This trait defines a number of helper functions for testing APIv3. Commonly
13 * used helpers include `callAPISuccess()`, `callAPIFailure()`,
14 * `assertAPISuccess()`, and `assertAPIFailure()`.
16 * This trait is intended for use with PHPUnit-based test cases.
21 * Get the api versions to test.
25 public function versionThreeAndFour() {
33 * Api version - easier to override than just a define
36 protected $_apiversion = 3;
39 * Check that api returned 'is_error' => 1
40 * else provide full message
41 * @param array $result
43 * @param array $valuesToExclude
44 * @param string $prefix
45 * Extra test to add to message.
47 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = [], $prefix = '') {
48 $valuesToExclude = array_merge($valuesToExclude, ['debug', 'xdebug', 'sequential']);
49 foreach ($valuesToExclude as $value) {
50 if (isset($result[$value])) {
51 unset($result[$value]);
53 if (isset($expected[$value])) {
54 unset($expected[$value]);
57 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
61 * Check that a deleted item has been deleted.
66 public function assertAPIDeleted($entity, $id) {
67 $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0);
71 * Check that api returned 'is_error' => 1.
73 * @param array $apiResult
75 * @param string $prefix
76 * Extra test to add to message.
77 * @param null $expectedError
79 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
80 if (!empty($prefix)) {
83 if ($expectedError && !empty($apiResult['is_error'])) {
84 $this->assertStringContainsString($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
86 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
87 $this->assertNotEmpty($apiResult['error_message']);
91 * Check that api returned 'is_error' => 0.
93 * @param array $apiResult
95 * @param string $prefix
96 * Extra test to add to message.
98 public function assertAPISuccess($apiResult, $prefix = '') {
99 if (!empty($prefix)) {
102 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
104 if (!empty($apiResult['debug_information'])) {
105 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
107 if (!empty($apiResult['trace'])) {
108 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
110 $this->assertEmpty($apiResult['is_error'] ??
NULL, $prefix . $errorMessage);
114 * This function exists to wrap api functions.
115 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
116 * @param string $entity
117 * @param string $action
118 * @param array $params
119 * @param string $expectedErrorMessage
121 * @param null $extraOutput
124 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
125 if (is_array($params)) {
127 'version' => $this->_apiversion
,
131 $result = $this->civicrm_api($entity, $action, $params);
133 catch (\API_Exception
$e) {
134 // api v4 call failed and threw an exception.
137 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
142 * wrap api functions.
143 * so we can ensure they succeed & throw exceptions without litterering the test with checks
145 * @param string $entity
146 * @param string $action
147 * @param array $params
148 * @param mixed $checkAgainst
149 * Optional value to check result against, implemented for getvalue,.
150 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
151 * for getsingle the array is compared against an array passed in - the id is not compared (for
156 public function callAPISuccess($entity, $action, $params = [], $checkAgainst = NULL) {
157 $params = array_merge([
158 'version' => $this->_apiversion
,
163 switch (strtolower($action)) {
165 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
168 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
171 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
173 $result = $this->civicrm_api($entity, $action, $params);
174 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
179 * This function exists to wrap api getValue function & check the result
180 * so we can ensure they succeed & throw exceptions without littering the test with checks
181 * There is a type check in this
183 * @param string $entity
184 * @param array $params
189 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
191 'version' => $this->_apiversion
,
194 $result = $this->civicrm_api($entity, 'getcount', $params);
195 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
196 $this->fail('Invalid getcount result : ' . print_r($result, TRUE) . ' type :' . gettype($result));
198 if (is_int($count)) {
199 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
205 * This function exists to wrap api getsingle function & check the result
206 * so we can ensure they succeed & throw exceptions without litterering the test with checks
208 * @param string $entity
209 * @param array $params
210 * @param array $checkAgainst
211 * Array to compare result against.
221 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
223 'version' => $this->_apiversion
,
225 if (!empty($this->isGetSafe
) && !isset($params['return'])) {
226 $params['return'] = 'id';
228 $result = $this->civicrm_api($entity, 'getsingle', $params);
229 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
230 $unfilteredResult = $this->civicrm_api($entity, 'get', ['version' => $this->_apiversion
]);
232 'Invalid getsingle result' . print_r($result, TRUE)
233 . "\n entity: $entity . \n params \n " . print_r($params, TRUE)
234 . "\n entities retrieved with blank params \n" . print_r($unfilteredResult, TRUE)
238 // @todo - have gone with the fn that unsets id? should we check id?
239 $this->checkArrayEquals($result, $checkAgainst);
245 * This function wraps the getValue api and checks the result.
247 * @param string $entity
248 * @param array $params
249 * @param string $type
250 * Per http://php.net/manual/en/function.gettype.php possible types.
260 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
262 'version' => $this->_apiversion
,
264 $result = $this->civicrm_api($entity, 'getvalue', $params);
265 if (is_array($result) && (!empty($result['is_error']) ||
isset($result['values']))) {
266 $this->fail('Invalid getvalue result' . print_r($result, TRUE));
269 if ($type === 'integer') {
270 // api seems to return integers as strings
271 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
274 $this->assertType($type, $result, "returned result should have been of type $type but was ");
281 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
285 * @param array $params
288 public function civicrm_api($entity, $action, $params = []) {
289 if (($params['version'] ??
0) == 4) {
290 return $this->runApi4Legacy($entity, $action, $params);
292 return civicrm_api($entity, $action, $params);
296 * Emulate v3 syntax so we can run api3 tests on v4
300 * @param array $v3Params
302 * @throws \API_Exception
303 * @throws \CiviCRM_API3_Exception
306 public function runApi4Legacy($v3Entity, $v3Action, $v3Params = []) {
307 $v4Entity = \CRM_Core_DAO_AllCoreTables
::convertEntityNameToCamel($v3Entity);
308 $v4Action = $v3Action = strtolower($v3Action);
309 $v4Params = ['checkPermissions' => isset($v3Params['check_permissions']) ?
(bool) $v3Params['check_permissions'] : FALSE];
310 $sequential = !empty($v3Params['sequential']);
311 $options = \
_civicrm_api3_get_options_from_params($v3Params, in_array($v4Entity, ['Contact', 'Participant', 'Event', 'Group', 'Contribution', 'Membership']));
312 $indexBy = in_array($v3Action, ['get', 'create', 'replace']) && !$sequential ?
'id' : NULL;
313 $onlyId = !empty($v3Params['format.only_id']);
314 $onlySuccess = !empty($v3Params['format.is_success']);
315 if (!empty($v3Params['filters']['is_current']) ||
!empty($v3Params['isCurrent'])) {
316 $v3Params['is_current'] = 1;
317 unset($v3Params['filters']['is_current'], $v3Params['isCurrent']);
319 $language = $v3Params['options']['language'] ??
$v3Params['option.language'] ??
NULL;
321 $v4Params['language'] = $language;
323 $toRemove = ['option.', 'return', 'api.', 'format.'];
324 $chains = $custom = [];
325 foreach ($v3Params as $key => $val) {
326 foreach ($toRemove as $remove) {
327 if (strpos($key, $remove) === 0) {
328 if ($remove == 'api.') {
329 $chains[$key] = $val;
331 unset($v3Params[$key]);
336 $v3Fields = civicrm_api3($v3Entity, 'getfields', ['action' => $v3Action])['values'];
339 foreach ($v3Params as $key => $val) {
340 if ($val === 'null') {
341 $v3Params[$key] = NULL;
345 if ($v4Entity == 'Setting') {
347 $v4Params['domainId'] = $v3Params['domain_id'] ??
NULL;
348 if ($v3Action == 'getfields') {
349 if (!empty($v3Params['name'])) {
350 $v3Params['filters']['name'] = $v3Params['name'];
352 foreach ($v3Params['filters'] ??
[] as $filter => $val) {
353 $v4Params['where'][] = [$filter, '=', $val];
356 if ($v3Action == 'create') {
359 if ($v3Action == 'revert') {
360 $v4Params['select'] = (array) $v3Params['name'];
362 if ($v3Action == 'getvalue') {
363 $options['return'] = [$v3Params['name'] => 1];
366 \CRM_Utils_Array
::remove($v3Params, 'domain_id', 'name');
369 \CRM_Utils_Array
::remove($v3Params, 'options', 'debug', 'version', 'sort', 'offset', 'rowCount', 'check_permissions', 'sequential', 'filters', 'isCurrent');
371 // Work around ugly hack in v3 Domain api
372 if ($v4Entity == 'Domain') {
373 $v3Fields['version'] = ['name' => 'version', 'api.aliases' => ['domain_version']];
374 unset($v3Fields['domain_version']);
377 foreach ($v3Fields as $name => $field) {
378 // Resolve v3 aliases
379 foreach ($field['api.aliases'] ??
[] as $alias) {
380 if (isset($v3Params[$alias])) {
381 $v3Params[$field['name']] = $v3Params[$alias];
382 unset($v3Params[$alias]);
385 // Convert custom field names
386 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
387 // Strictly speaking, using titles instead of names is incorrect, but it works for
388 // unit tests where names and titles are identical and saves an extra db lookup.
389 $custom[$field['groupTitle']][$field['title']] = $name;
390 $v4FieldName = $field['groupTitle'] . '.' . $field['title'];
391 if (isset($v3Params[$name])) {
392 $v3Params[$v4FieldName] = $v3Params[$name];
393 unset($v3Params[$name]);
395 if (isset($options['return'][$name])) {
396 $options['return'][$v4FieldName] = 1;
397 unset($options['return'][$name]);
401 if ($name === 'option_group_id' && isset($v3Params[$name]) && !is_numeric($v3Params[$name])) {
402 // This is a per field hack (bad) but we can't solve everything at once
403 // & a cleverer way turned out to be too much for this round.
404 // Being in the test class it's tested....
405 $v3Params['option_group_id.name'] = $v3Params['option_group_id'];
406 unset($v3Params['option_group_id']);
408 if (isset($field['pseudoconstant'], $v3Params[$name]) && $field['type'] === \CRM_Utils_Type
::T_INT
&& !is_numeric($v3Params[$name]) && is_string($v3Params[$name])) {
409 $v3Params[$name] = \CRM_Core_PseudoConstant
::getKey(\CRM_Core_DAO_AllCoreTables
::getFullName($v4Entity), $name, $v3Params[$name]);
415 $v4Params['select'] = ['row_count'];
416 // No break - keep processing as get
420 // No break - keep processing as get
422 if ($options['return'] && $v3Action !== 'getcount') {
423 $v4Params['select'] = array_keys($options['return']);
424 // Ensure id field is returned as v3 always expects it
425 if ($v4Entity != 'Setting' && !in_array('id', $v4Params['select'])) {
426 $v4Params['select'][] = 'id';
429 if ($options['limit'] && $v4Entity != 'Setting') {
430 $v4Params['limit'] = $options['limit'];
432 if ($options['offset']) {
433 $v4Params['offset'] = $options['offset'];
435 if ($options['sort']) {
436 foreach (explode(',', $options['sort']) as $sort) {
437 [$sortField, $sortDir] = array_pad(explode(' ', trim($sort)), 2, 'ASC');
438 $v4Params['orderBy'][$sortField] = $sortDir;
444 if (empty($v3Params['values'])) {
445 $v4Action = 'delete';
448 $v4Params['records'] = $v3Params['values'];
450 unset($v3Params['values']);
455 if (!empty($v3Params['id'])) {
456 $v4Action = 'update';
457 $v4Params['where'][] = ['id', '=', $v3Params['id']];
460 $v4Params['values'] = $v3Params;
461 unset($v4Params['values']['id']);
465 if (isset($v3Params['id'])) {
466 $v4Params['where'][] = ['id', '=', $v3Params['id']];
472 $v4Action = 'getFields';
474 'where' => [['name', '=', $v3Params['field']]],
475 'loadOptions' => TRUE,
480 $v4Action = 'getFields';
481 if (!empty($v3Params['action']) ||
!empty($v3Params['api_action'])) {
482 $v4Params['action'] = !empty($v3Params['action']) ?
$v3Params['action'] : $v3Params['api_action'];
484 $indexBy = !$sequential ?
'name' : NULL;
488 // Ensure this api4 entity/action exists
490 $actionInfo = \
civicrm_api4($v4Entity, 'getActions', ['checkPermissions' => FALSE, 'where' => [['name', '=', $v4Action]]]);
492 catch (NotImplementedException
$e) {
493 // For now we'll mark the test incomplete if a v4 entity doesn't exit yet
494 $this->markTestIncomplete($e->getMessage());
496 if (!isset($actionInfo[0])) {
497 throw new \
Exception("Api4 $v4Entity $v4Action does not exist.");
500 // Migrate special params like fix_address
501 foreach ($actionInfo[0]['params'] as $v4ParamName => $paramInfo) {
502 // camelCase in api4, lower_case in api3
503 $v3ParamName = strtolower(preg_replace('/(?=[A-Z])/', '_$0', $v4ParamName));
504 if (isset($v3Params[$v3ParamName])) {
505 $v4Params[$v4ParamName] = $v3Params[$v3ParamName];
506 unset($v3Params[$v3ParamName]);
507 if ($paramInfo['type'][0] == 'bool') {
508 $v4Params[$v4ParamName] = (bool) $v4Params[$v4ParamName];
513 // Build where clause for 'getcount', 'getsingle', 'getvalue', 'get' & 'replace'
514 if ($v4Action == 'get' ||
$v3Action == 'replace') {
515 foreach ($v3Params as $key => $val) {
517 if (is_array($val) && count($val) == 1 && array_intersect_key($val, array_flip(\CRM_Core_DAO
::acceptedSQLOperators()))) {
518 foreach ($val as $op => $newVal) {
522 $v4Params['where'][] = [$key, $op, $val];
527 $result = \
civicrm_api4($v4Entity, $v4Action, $v4Params, $indexBy);
529 catch (\Exception
$e) {
530 return $onlySuccess ?
0 : [
532 'error_message' => $e->getMessage(),
537 if (($v3Action == 'getsingle' ||
$v3Action == 'getvalue' ||
$v3Action == 'delete') && count($result) != 1) {
538 return $onlySuccess ?
0 : [
540 'error_message' => "Expected one $v4Entity but found " . count($result),
541 'count' => count($result),
549 if ($v3Action == 'getcount') {
550 return $result->count();
554 return $result->first()['id'];
557 if ($v3Action == 'getvalue' && $v4Entity == 'Setting') {
558 return $result->first()['value'] ??
NULL;
561 if ($v3Action == 'getvalue') {
562 $returnKey = array_keys($options['return'])[0];
563 return $result->first()[$returnKey] ??
NULL;
566 // Mimic api3 behavior when using 'replace' action to delete all
567 if ($v3Action == 'replace' && $v4Action == 'delete') {
568 $result->exchangeArray([]);
571 if ($v3Action == 'getoptions') {
574 'count' => $result['options'] ?
count($result['options']) : 0,
575 'values' => $result['options'] ?
: [],
580 // Emulate the weird return format of api3 settings
581 if (($v3Action == 'get' ||
$v3Action == 'create') && $v4Entity == 'Setting') {
583 foreach ($result as $item) {
584 $settings[$item['domain_id']][$item['name']] = $item['value'];
586 $result->exchangeArray($sequential ?
array_values($settings) : $settings);
589 foreach ($result as $index => $row) {
591 foreach ($chains as $key => $params) {
592 $result[$index][$key] = $this->runApi4LegacyChain($key, $params, $v4Entity, $row, $sequential);
594 // Resolve custom field names
595 foreach ($custom as $group => $fields) {
596 foreach ($fields as $field => $v3FieldName) {
597 if (isset($row["$group.$field"])) {
598 $result[$index][$v3FieldName] = $row["$group.$field"];
599 unset($result[$index]["$group.$field"]);
605 if ($v3Action == 'getsingle') {
606 return $result->first();
612 'count' => count($result),
613 'values' => (array) $result,
614 'id' => is_object($result) && count($result) == 1 ?
($result->first()['id'] ??
NULL) : NULL,
620 * @param mixed $params
621 * @param string $mainEntity
622 * @param array $result
623 * @param bool $sequential
625 * @throws \API_Exception
627 protected function runApi4LegacyChain($key, $params, $mainEntity, $result, $sequential) {
628 // Handle an array of multiple calls using recursion
629 if (is_array($params) && isset($params[0]) && is_array($params[0])) {
631 foreach ($params as $chain) {
632 $results[] = $this->runApi4LegacyChain($key, $chain, $mainEntity, $result, $sequential);
637 // Handle single api call
638 list(, $chainEntity, $chainAction) = explode('.', $key);
639 $lcChainEntity = \CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($chainEntity);
640 $chainEntity = \CRM_Core_DAO_AllCoreTables
::convertEntityNameToCamel($chainEntity);
641 $lcMainEntity = \CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($mainEntity);
642 $params = is_array($params) ?
$params : [];
644 // Api3 expects this to be inherited
645 $params +
= ['sequential' => $sequential];
647 // Replace $value.field_name
648 foreach ($params as $name => $param) {
649 if (is_string($param) && strpos($param, '$value.') === 0) {
650 $param = substr($param, 7);
651 $params[$name] = $result[$param] ??
NULL;
656 $getFields = civicrm_api4($chainEntity, 'getFields', ['select' => ['name']], 'name');
658 catch (NotImplementedException
$e) {
659 $this->markTestIncomplete($e->getMessage());
662 // Emulate the string-fu guesswork that api3 does
663 if ($chainEntity == $mainEntity && empty($params['id']) && !empty($result['id'])) {
664 $params['id'] = $result['id'];
666 elseif (empty($params['id']) && !empty($result[$lcChainEntity . '_id'])) {
667 $params['id'] = $result[$lcChainEntity . '_id'];
669 elseif (!empty($result['id']) && isset($getFields[$lcMainEntity . '_id']) && empty($params[$lcMainEntity . '_id'])) {
670 $params[$lcMainEntity . '_id'] = $result['id'];
672 return $this->runApi4Legacy($chainEntity, $chainAction, $params);