3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Test that the core actions for APIv3 entities comply with standard syntax+behavior.
15 * By default, this tests all API entities. To only test specific entities, call phpunit with
16 * environment variable SYNTAX_CONFORMANCE_ENTITIES, e.g.
18 * env SYNTAX_CONFORMANCE_ENTITIES="Contact Event" ./scripts/phpunit api_v3_SyntaxConformanceTest
20 * @package CiviCRM_APIv3
21 * @subpackage API_Core
24 class api_v3_SyntaxConformanceTest
extends CiviUnitTestCase
{
25 protected $_apiversion = 3;
29 * e.g. $this->deletes['CRM_Contact_DAO_Contact'][] = $contactID;
31 protected $deletableTestObjects;
34 * This test case doesn't require DB reset.
37 public $DBResetRequired = FALSE;
42 * Map custom group entities to civicrm components.
45 protected static $componentMap = [
46 'Contribution' => 'CiviContribute',
47 'Membership' => 'CiviMember',
48 'Participant' => 'CiviEvent',
49 'Event' => 'CiviEvent',
51 'Pledge' => 'CiviPledge',
52 'Grant' => 'CiviGrant',
53 'Campaign' => 'CiviCampaign',
54 'Survey' => 'CiviCampaign',
60 * There are two types of missing APIs:
61 * Those that are to be implemented
62 * (in some future version when someone steps in -hint hint-). List the entities in toBeImplemented[ {$action} ]
63 * Those that don't exist
64 * and that will never exist (eg an obsoleted Entity
65 * they need to be returned by the function toBeSkipped_{$action} (because it has to be a static method and therefore couldn't access a this->toBeSkipped)
67 public function setUp() {
69 $this->enableCiviCampaign();
70 $this->toBeImplemented
['get'] = [
71 // CxnApp.get exists but relies on remote data outside our control; QA w/UtilsTest::testBasicArrayGet
84 $this->toBeImplemented
['create'] = [
102 $this->toBeImplemented
['delete'] = [
115 $this->onlyIDNonZeroCount
['get'] = [
122 $this->deprecatedAPI
= ['Location', 'ActivityType', 'SurveyRespondant'];
123 $this->deletableTestObjects
= [];
126 public function tearDown() {
127 foreach ($this->deletableTestObjects
as $entityName => $entities) {
128 foreach ($entities as $entityID) {
129 CRM_Core_DAO
::deleteTestObjects($entityName, ['id' => $entityID]);
135 * Generate list of all entities.
142 public static function entities($skip = []) {
143 // The order of operations in here is screwy. In the case where SYNTAX_CONFORMANCE_ENTITIES is
144 // defined, we should be able to parse+return it immediately. However, some weird dependency
145 // crept into the system where civicrm_api('Entity','get') must be called as part of entities()
146 // (even if its return value is ignored).
148 $tmp = civicrm_api('Entity', 'Get', ['version' => 3]);
149 if (getenv('SYNTAX_CONFORMANCE_ENTITIES')) {
151 'values' => explode(' ', getenv('SYNTAX_CONFORMANCE_ENTITIES')),
155 if (!is_array($skip)) {
158 $tmp = array_diff($tmp['values'], $skip);
160 foreach ($tmp as $e) {
167 * Get list of entities for get test.
171 public static function entities_get() {
172 // all the entities, beside the ones flagged
173 return static::entities(static::toBeSkipped_get(TRUE));
177 * Get entities for create tests.
181 public static function entities_create() {
182 return static::entities(static::toBeSkipped_create(TRUE));
188 public static function entities_updatesingle() {
189 return static::entities(static::toBeSkipped_updatesingle(TRUE));
195 public static function entities_getlimit() {
196 return static::entities(static::toBeSkipped_getlimit());
200 * Generate list of entities that can be retrieved using SQL operator syntax.
204 public static function entities_getSqlOperators() {
205 return static::entities(static::toBeSkipped_getSqlOperators());
211 public static function entities_delete() {
212 return static::entities(static::toBeSkipped_delete(TRUE));
218 public static function entities_getfields() {
219 return static::entities(static::toBeSkipped_getfields(TRUE));
225 public static function custom_data_entities_get() {
226 return static::custom_data_entities();
232 public static function custom_data_entities() {
233 $entities = CRM_Core_BAO_CustomQuery
::$extendsMap;
234 $enabledComponents = Civi
::settings()->get('enable_components');
235 $customDataEntities = [];
236 $invalidEntities = ['Individual', 'Organization', 'Household'];
237 $entitiesToFix = ['Case', 'Relationship'];
238 foreach ($entities as $entityName => $entity) {
239 if (!in_array($entityName, $invalidEntities)
240 && !in_array($entityName, $entitiesToFix)
242 if (!empty(self
::$componentMap[$entityName]) && empty($enabledComponents[self
::$componentMap[$entityName]])) {
243 CRM_Core_BAO_ConfigSetting
::enableComponent(self
::$componentMap[$entityName]);
245 $customDataEntities[] = [$entityName];
248 return $customDataEntities;
252 * Add a smattering of entities that don't normally have custom data.
256 public static function custom_data_incl_non_std_entities_get() {
257 return static::entities(static::toBeSkipped_custom_data_creatable(TRUE));
261 * Get entities to be skipped on get tests.
263 * @param bool $sequential
267 public static function toBeSkipped_get($sequential = FALSE) {
268 $entitiesWithoutGet = [
269 'MailingEventSubscribe',
270 'MailingEventConfirm',
271 'MailingEventResubscribe',
272 'MailingEventUnsubscribe',
275 if ($sequential === TRUE) {
276 return $entitiesWithoutGet;
279 foreach ($entitiesWithoutGet as $e) {
286 * Get entities to be skipped for get call.
288 * Mailing Contact Just doesn't support id. We have always insisted on finding a way to
289 * support id in API but in this case the underlying tables are crying out for a restructure
290 * & it just doesn't make sense.
292 * User doesn't support get By ID because the user id is actually the CMS user ID & is not part of
293 * CiviCRM - so can only be tested through UserTest - not SyntaxConformanceTest.
295 * Entity doesn't support get By ID because it simply gives the result of string Entites in CiviCRM
297 * @param bool $sequential
300 * Entities that cannot be retrieved by ID
302 public static function toBeSkipped_getByID($sequential = FALSE) {
303 return ['MailingContact', 'User', 'Attachment', 'Entity'];
307 * @param bool $sequential
311 public static function toBeSkipped_create($sequential = FALSE) {
312 $entitiesWithoutCreate = ['Constant', 'Entity', 'Location', 'Profile', 'MailingRecipients'];
313 if ($sequential === TRUE) {
314 return $entitiesWithoutCreate;
317 foreach ($entitiesWithoutCreate as $e) {
324 * @param bool $sequential
328 public static function toBeSkipped_delete($sequential = FALSE) {
331 'MailingEventConfirm',
332 'MailingEventResubscribe',
333 'MailingEventSubscribe',
334 'MailingEventUnsubscribe',
346 if ($sequential === TRUE) {
347 return $entitiesWithout;
350 foreach ($entitiesWithout as $e) {
357 * @param bool $sequential
361 public static function toBeSkipped_custom_data_creatable($sequential = FALSE) {
372 'MailingEventConfirm',
373 'MailingEventResubscribe',
374 'MailingEventSubscribe',
375 'MailingEventUnsubscribe',
386 // ones that are not real entities hence not extendable.
410 if ($sequential === TRUE) {
411 return $entitiesWithout;
414 foreach ($entitiesWithout as $e) {
421 * @param bool $sequential
424 * @todo add metadata for ALL these entities
426 public static function toBeSkipped_getfields($sequential = FALSE) {
427 $entitiesWithMetadataNotYetFixed = ['ReportTemplate', 'CustomSearch'];
428 if ($sequential === TRUE) {
429 return $entitiesWithMetadataNotYetFixed;
432 foreach ($entitiesWithMetadataNotYetFixed as $e) {
439 * Generate list of entities to test for get by id functions.
440 * @param bool $sequential
442 * Entities to be skipped
444 public static function toBeSkipped_automock($sequential = FALSE) {
445 $entitiesWithoutGet = [
459 if ($sequential === TRUE) {
460 return $entitiesWithoutGet;
463 foreach ($entitiesWithoutGet as $e) {
470 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
471 * @param bool $sequential
474 public static function toBeSkipped_updatesingle($sequential = FALSE) {
477 // pseudo-entity; testUpdateSingleValueAlter doesn't introspect properly on it. Multiple magic fields
479 'MailingEventUnsubscribe',
480 'MailingEventSubscribe',
498 'MailingEventConfirm',
503 'MailingEventResubscribe',
517 //skip this because it doesn't make sense to update logs,
520 if ($sequential === TRUE) {
521 return $entitiesWithout;
524 foreach ($entitiesWithout as $e) {
534 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
536 public static function toBeSkipped_getlimit() {
539 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
541 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
543 // failed 'check that a 5 limit returns 5' - probably is_template field is wrong or something, or could be limit doesn't work right
545 // can't handle creating 25
547 // fails on 5 limit - probably a set up problem
549 //a bit of a pseudoapi - keys by domain
551 // pseudoapi - problems with creating required sub entities.
553 return $entitiesWithout;
557 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
559 public static function toBeSkipped_getSqlOperators() {
561 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
565 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
567 // can't handle creating 25
569 // note has a default get that isn't implemented in createTestObject -meaning you don't 'get' them
571 //a bit of a pseudoapi - keys by domain
575 // The testSqlOperators fails sporadically on MySQL 5.5, which is deprecated anyway.
576 // Test data providers should be able to run in pre-boot environment, so we connect directly to SQL server.
577 require_once 'DB.php';
578 $db = DB
::connect(CIVICRM_DSN
);
579 if ($db->connection
instanceof mysqli
&& $db->connection
->server_version
< 50600) {
580 $entitiesWithout[] = 'Dedupe';
583 return $entitiesWithout;
592 public function getKnownUnworkablesUpdateSingle($entity, $key) {
593 // can't update values are values for which updates don't result in the value being changed
595 'ActionSchedule' => [
600 'ActivityContact' => [
603 //we have an FK on activity_id + contact_id + record id so if we don't leave this one distinct we get an FK constraint error
608 //issues with country id - need to ensure same country
611 //creates relationship
614 'cant_return' => ['street_parsing', 'skip_geocode', 'fix_address'],
618 // believe this field is defined in error
630 'Domain' => ['cant_update' => ['domain_version']],
631 'MembershipBlock' => [
633 // The fake/auto-generated values leave us unable to properly cleanup fake data
638 'MailingJob' => ['cant_update' => ['parent_id']],
639 'ContributionSoft' => [
641 // can't be changed through api
647 // This is being legitimately manipulated to always have a valid primary - skip.
653 // Altering fee amount will also cause net_amount to be recalculated.
659 // Weight is deliberately altered when this is changed - skip.
665 // I'm on the fence about whether the test should skip or the behaviour is wrong.
666 // display_name is set to match name if display_name is not provided. It would be more 'normal'
667 // to only calculate a default IF id is not set - but perhaps the current behaviour is kind
668 // of what someone updating the name expects..
674 'pledge_original_installment_amount',
676 'original_installment_amount',
678 // can't be changed through API,
681 // if these are passed in they are retrieved from the wrong table
685 'contribution_page_id',
686 'financial_account_id',
690 // can't be retrieved from api
692 //due to uniquename missing
701 'initial_reminder_day',
702 'additional_reminder_day',
704 'pledge_contribution_page_id',
706 'pledge_campaign_id',
707 'pledge_financial_type_id',
710 'PaymentProcessorType' => [
714 'break_return' => [],
717 'PriceFieldValue' => [
719 //won't update as there is no 1 in the same price set
723 'ReportInstance' => [
724 // View mode is part of the navigation which is not retrieved by the api.
725 'cant_return' => ['view_mode'],
728 // I think the fields below are generated based on form_values.
736 'StatusPreference' => [
743 // These fields get auto-adjusted by the BAO prior to saving
752 // These fields get auto-adjusted by the BAO prior to saving
763 // For better or worse triggers override.
764 'break_return' => ['run_time'],
765 'cant_update' => ['run_time'],
768 if (empty($knownFailures[$entity]) ||
empty($knownFailures[$entity][$key])) {
771 return $knownFailures[$entity][$key];
774 /* ----- testing the _get ----- */
777 * @dataProvider toBeSkipped_get
778 * Entities that don't need a get action
781 public function testNotImplemented_get($Entity) {
782 $result = civicrm_api($Entity, 'Get', ['version' => 3]);
783 $this->assertEquals(1, $result['is_error']);
784 // $this->assertContains("API ($Entity, Get) does not exist", $result['error_message']);
785 $this->assertRegExp('/API (.*) does not exist/', $result['error_message']);
789 * @dataProvider entities
792 public function testGetFields($Entity) {
793 if (in_array($Entity, $this->deprecatedAPI
) ||
$Entity == 'Entity' ||
$Entity == 'CustomValue') {
797 $result = civicrm_api($Entity, 'getfields', ['version' => 3]);
798 $this->assertTrue(is_array($result['values']), "$Entity ::get fields doesn't return values array in line " . __LINE__
);
799 foreach ($result['values'] as $key => $value) {
800 $this->assertTrue(is_array($value), $Entity . "::" . $key . " is not an array in line " . __LINE__
);
805 * @dataProvider entities_get
808 public function testEmptyParam_get($Entity) {
810 if (in_array($Entity, $this->toBeImplemented
['get'])) {
811 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
814 $result = civicrm_api($Entity, 'Get', []);
815 $this->assertEquals(1, $result['is_error']);
816 $this->assertContains("Unknown api version", $result['error_message']);
820 * @dataProvider entities_get
821 * @Xdepends testEmptyParam_get // no need to test the simple if the empty doesn't work/is skipped. doesn't seem to work
824 public function testSimple_get($Entity) {
825 // $this->markTestSkipped("test gives core error on test server (but not on our locals). Skip until we can get server to pass");
826 if (in_array($Entity, $this->toBeImplemented
['get'])) {
829 $result = civicrm_api($Entity, 'Get', ['version' => 3]);
830 // @TODO: list the get that have mandatory params
831 if ($result['is_error']) {
832 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
833 // either id or contact_id or entity_id is one of the field missing
834 $this->assertContains("id", $result['error_message']);
837 $this->assertEquals(3, $result['version']);
838 $this->assertArrayHasKey('count', $result);
839 $this->assertArrayHasKey('values', $result);
844 * @dataProvider custom_data_incl_non_std_entities_get
847 public function testCustomDataGet($entityName) {
848 if ($entityName === 'Note') {
849 $this->markTestIncomplete('Note can not be processed here because of a vagary in the note api, it adds entity_table=contact to the get params when id is not present - which makes sense almost always but kills this test');
851 $this->quickCleanup(['civicrm_uf_match']);
852 // so subsidiary activities are created
853 $this->createLoggedInUser();
855 $entitiesWithNamingIssues = [
856 'SmsProvider' => 'Provider',
857 'AclRole' => 'EntityRole',
858 'MailingEventQueue' => 'Queue',
859 'Dedupe' => 'PrevNextCache',
862 $usableName = !empty($entitiesWithNamingIssues[$entityName]) ?
$entitiesWithNamingIssues[$entityName] : $entityName;
863 $optionName = CRM_Core_DAO_AllCoreTables
::getTableForClass(CRM_Core_DAO_AllCoreTables
::getFullName($usableName));
865 if (!isset(CRM_Core_BAO_CustomQuery
::$extendsMap[$entityName])) {
866 $createdValue = $this->callAPISuccess('OptionValue', 'create', [
867 'option_group_id' => 'cg_extend_objects',
868 'label' => $usableName,
869 'value' => $usableName,
870 'name' => $optionName,
873 // We are not passing 'check_permissions' so the the more limited permissions *should* be
874 // ignored but per CRM-17700 there is a history of custom data applying permissions when it shouldn't.
875 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= ['access CiviCRM', 'view my contact'];
876 $objects = $this->getMockableBAOObjects($entityName, 1);
878 // simple custom field
879 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $usableName . 'Test.php');
880 $customFieldName = 'custom_' . $ids['custom_field_id'];
881 $params = ['id' => $objects[0]->id
, 'custom_' . $ids['custom_field_id'] => "custom string"];
882 $result = $this->callAPISuccess($entityName, 'create', $params);
883 $this->assertTrue(isset($result['id']), 'no id on ' . $entityName);
884 $getParams = ['id' => $result['id'], 'return' => [$customFieldName]];
885 $check = $this->callAPISuccess($entityName, 'get', $getParams);
886 $this->assertTrue(!empty($check['values'][$check['id']][$customFieldName]), 'Custom data not present for ' . $entityName);
887 $this->assertEquals("custom string", $check['values'][$check['id']][$customFieldName], 'Custom data not present for ' . $entityName);
888 $this->customFieldDelete($ids['custom_field_id']);
889 $this->customGroupDelete($ids['custom_group_id']);
891 $ids2 = $this->entityCustomGroupWithSingleStringMultiSelectFieldCreate(__FUNCTION__
, $usableName . 'Test.php');
892 $customFieldNameMultiSelect = 'custom_' . $ids2['custom_field_id'];
893 // String custom field, Multi-Select html type
894 foreach ($ids2['custom_field_group_options'] as $option_value => $option_label) {
895 $params = ['id' => $objects[0]->id
, 'custom_' . $ids2['custom_field_id'] => $option_value];
896 $result = $this->callAPISuccess($entityName, 'create', $params);
897 $getParams = [$customFieldNameMultiSelect => $option_value, 'return' => [$customFieldNameMultiSelect]];
898 $this->callAPISuccessGetCount($entityName, $getParams, 1);
902 $this->customFieldDelete($ids2['custom_field_id']);
903 $this->customGroupDelete($ids2['custom_group_id']);
905 $this->callAPISuccess($entityName, 'delete', ['id' => $result['id']]);
906 $this->quickCleanup(['civicrm_uf_match']);
907 if (!empty($createdValue)) {
908 $this->callAPISuccess('OptionValue', 'delete', ['id' => $createdValue['id']]);
913 * @dataProvider entities_get
916 public function testAcceptsOnlyID_get($Entity) {
917 // big random number. fun fact: if you multiply it by pi^e, the result is another random number, but bigger ;)
918 $nonExistantID = 30867307034;
919 if (in_array($Entity, $this->toBeImplemented
['get'])
920 ||
in_array($Entity, $this->toBeSkipped_getByID())
926 // the below function returns different values and hence an early return
927 // we'll fix this once beta1 is released
930 $result = civicrm_api($Entity, 'Get', ['version' => 3, 'id' => $nonExistantID]);
932 if ($result['is_error']) {
933 // just to get a clearer message in the log
934 $this->assertEquals("only id should be enough", $result['error_message']);
936 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
937 $this->assertEquals(0, $result['count']);
943 * @dataProvider entities_get
946 public function testGetList($Entity) {
947 if (in_array($Entity, $this->toBeImplemented
['get'])
948 ||
in_array($Entity, $this->toBeSkipped_getByID())
952 if (in_array($Entity, ['ActivityType', 'SurveyRespondant'])) {
953 $this->markTestSkipped();
955 $this->callAPISuccess($Entity, 'getlist', ['label_field' => 'id']);
959 * Test getlist works when entity is lowercase
960 * @dataProvider entities_get
963 public function testGetListLowerCaseEntity($Entity) {
964 if (in_array($Entity, $this->toBeImplemented
['get'])
965 ||
in_array($Entity, $this->toBeSkipped_getByID())
969 if (in_array($Entity, ['ActivityType', 'SurveyRespondant'])) {
970 $this->markTestSkipped();
972 if ($Entity == 'UFGroup') {
975 $this->callAPISuccess($Entity, 'getlist', ['label_field' => 'id']);
979 * Create two entities and make sure we can fetch them individually by ID.
981 * @dataProvider entities_get
983 * limitations include the problem with avoiding loops when creating test objects -
984 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
985 * Currency - only seems to support US
988 public function testByID_get($entityName) {
989 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
990 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
994 $baos = $this->getMockableBAOObjects($entityName);
995 list($baoObj1, $baoObj2) = $baos;
998 $result = $this->callAPISuccess($entityName, 'get', [
999 'id' => $baoObj1->id
,
1002 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
1003 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
1004 $this->assertEquals(1, count($result['values']));
1006 // fetch second by ID
1007 $result = $this->callAPISuccess($entityName, 'get', [
1008 'id' => $baoObj2->id
,
1010 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
1011 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
1012 $this->assertEquals(1, count($result['values']));
1016 * Ensure that the "get" operation accepts limiting the #result records.
1018 * TODO Consider making a separate entity list ("entities_getlimit")
1019 * For the moment, the "entities_updatesingle" list should give a good
1020 * sense for which entities support createTestObject
1022 * @dataProvider entities_getlimit
1024 * @param string $entityName
1026 public function testLimit($entityName) {
1027 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
1030 ['options' => ['limit' => NULL]],
1032 'check that a NULL limit returns unlimited',
1035 ['options' => ['limit' => FALSE]],
1037 'check that a FALSE limit returns unlimited',
1040 ['options' => ['limit' => 0]],
1042 'check that a 0 limit returns unlimited',
1045 ['options' => ['limit' => 5]],
1047 'check that a 5 limit returns 5',
1052 'check that no limit returns 25',
1055 $baoString = _civicrm_api3_get_BAO($entityName);
1056 if (empty($baoString)) {
1057 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1061 // make 30 test items -- 30 > 25 (the default limit)
1063 for ($i = 0; $i < 30; $i++
) {
1064 $baoObj = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1065 $ids[] = $baoObj->id
;
1068 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
1069 foreach ($cases as $case) {
1070 $this->checkLimitAgainstExpected($entityName, $case[0], $case[1], $case[2]);
1072 //non preferred / legacy syntax
1073 if (isset($case[0]['options']['limit'])) {
1074 $this->checkLimitAgainstExpected($entityName, ['rowCount' => $case[0]['options']['limit']], $case[1], $case[2]);
1075 $this->checkLimitAgainstExpected($entityName, ['option_limit' => $case[0]['options']['limit']], $case[1], $case[2]);
1076 $this->checkLimitAgainstExpected($entityName, ['option.limit' => $case[0]['options']['limit']], $case[1], $case[2]);
1079 foreach ($ids as $id) {
1080 CRM_Core_DAO
::deleteTestObjects($baoString, ['id' => $id]);
1085 * Ensure that the "get" operation accepts limiting the #result records.
1087 * @dataProvider entities_getSqlOperators
1089 * @param string $entityName
1091 public function testSqlOperators($entityName) {
1092 $toBeIgnored = array_merge($this->toBeImplemented
['get'],
1093 $this->deprecatedAPI
,
1094 $this->toBeSkipped_get(TRUE),
1095 $this->toBeSkipped_getByID()
1097 if (in_array($entityName, $toBeIgnored)) {
1101 $baoString = _civicrm_api3_get_BAO($entityName);
1103 $entities = $this->callAPISuccess($entityName, 'get', ['options' => ['limit' => 0], 'return' => 'id']);
1104 $entities = array_keys($entities['values']);
1105 $totalEntities = count($entities);
1106 if ($totalEntities < 3) {
1108 for ($i = 0; $i < 3 - $totalEntities; $i++
) {
1109 $baoObj = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1110 $ids[] = $baoObj->id
;
1114 $entities = $this->callAPISuccess($entityName, 'get', ['options' => ['limit' => 0]]);
1115 $entities = array_keys($entities['values']);
1116 $this->assertGreaterThan(2, $totalEntities);
1117 $this->callAPISuccess($entityName, 'getsingle', ['id' => ['IN' => [$entities[0]]]]);
1118 $this->callAPISuccessGetCount($entityName, ['id' => ['NOT IN' => [$entities[0]]]], $totalEntities - 1);
1119 $this->callAPISuccessGetCount($entityName, ['id' => ['>' => $entities[0]]], $totalEntities - 1);
1123 * Check that get fetches an appropriate number of results.
1125 * @param string $entityName
1126 * Name of entity to test.
1127 * @param array $params
1129 * @param string $message
1131 public function checkLimitAgainstExpected($entityName, $params, $limit, $message) {
1132 $result = $this->callAPISuccess($entityName, 'get', $params);
1134 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
1135 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
1138 $this->assertEquals($limit, $result['count'], $message);
1139 $this->assertEquals($limit, count($result['values']), $message);
1144 * Create two entities and make sure we can fetch them individually by ID (e.g. using "contact_id=>2"
1147 * @dataProvider entities_get
1149 * limitations include the problem with avoiding loops when creating test objects -
1150 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1151 * Currency - only seems to support US
1152 * @param $entityName
1153 * @throws \PHPUnit\Framework\IncompleteTestError
1155 public function testByIDAlias_get($entityName) {
1156 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1157 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1161 $baoString = _civicrm_api3_get_BAO($entityName);
1162 if (empty($baoString)) {
1163 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1167 $idFieldName = _civicrm_api_get_entity_name_from_camel($entityName) . '_id';
1170 $baoObj1 = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1171 $this->assertTrue(is_int($baoObj1->id
), 'check first id');
1172 $this->deletableTestObjects
[$baoString][] = $baoObj1->id
;
1173 $baoObj2 = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1174 $this->assertTrue(is_int($baoObj2->id
), 'check second id');
1175 $this->deletableTestObjects
[$baoString][] = $baoObj2->id
;
1177 // fetch first by ID
1178 $result = civicrm_api($entityName, 'get', [
1180 $idFieldName => $baoObj1->id
,
1182 $this->assertAPISuccess($result);
1183 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
1184 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
1185 $this->assertEquals(1, count($result['values']));
1187 // fetch second by ID
1188 $result = civicrm_api($entityName, 'get', [
1190 $idFieldName => $baoObj2->id
,
1192 $this->assertAPISuccess($result);
1193 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
1194 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
1195 $this->assertEquals(1, count($result['values']));
1199 * @dataProvider entities_get
1202 public function testNonExistantID_get($Entity) {
1203 // cf testAcceptsOnlyID_get
1204 $nonExistantID = 30867307034;
1205 if (in_array($Entity, $this->toBeImplemented
['get'])) {
1209 $result = civicrm_api($Entity, 'Get', ['version' => 3, 'id' => $nonExistantID]);
1211 // redundant with testAcceptsOnlyID_get
1212 if ($result['is_error']) {
1216 $this->assertArrayHasKey('version', $result);
1217 $this->assertEquals(3, $result['version']);
1218 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
1219 $this->assertEquals(0, $result['count']);
1223 /* ---- testing the _create ---- */
1226 * @dataProvider toBeSkipped_create
1227 * entities that don't need a create action
1230 public function testNotImplemented_create($Entity) {
1231 $result = civicrm_api($Entity, 'Create', ['version' => 3]);
1232 $this->assertEquals(1, $result['is_error']);
1233 $this->assertContains(strtolower("API ($Entity, Create) does not exist"), strtolower($result['error_message']));
1237 * @dataProvider entities
1238 * @expectedException CiviCRM_API3_Exception
1241 public function testWithoutParam_create($Entity) {
1242 if ($Entity === 'Setting') {
1243 $this->markTestSkipped('It seems OK for setting to skip here as it silently sips invalid params');
1245 elseif ($Entity === 'Mailing') {
1246 $this->markTestSkipped('It seems OK for "Mailing" to skip here because you can create empty drafts');
1248 // should create php complaining that a param is missing
1249 civicrm_api3($Entity, 'Create');
1253 * @dataProvider entities_create
1255 * Check that create doesn't work with an invalid
1257 * @throws \PHPUnit\Framework\IncompleteTestError
1259 public function testInvalidSort_get($Entity) {
1260 $invalidEntitys = ['ActivityType', 'Setting', 'System'];
1261 if (in_array($Entity, $invalidEntitys)) {
1262 $this->markTestSkipped('It seems OK for ' . $Entity . ' to skip here as it silently sips invalid params');
1264 $result = $this->callAPIFailure($Entity, 'get', ['options' => ['sort' => 'sleep(1)']]);
1268 * @dataProvider entities_create
1270 * Check that create doesn't work with an invalid
1272 * @throws \PHPUnit\Framework\IncompleteTestError
1274 public function testValidSortSingleArrayById_get($Entity) {
1275 $invalidEntitys = ['ActivityType', 'Setting', 'System'];
1278 'id desc' => '_id desc',
1279 'id DESC' => '_id DESC',
1280 'id ASC' => '_id ASC',
1281 'id asc' => '_id asc',
1283 foreach ($tests as $test => $expected) {
1284 if (in_array($Entity, $invalidEntitys)) {
1285 $this->markTestSkipped('It seems OK for ' . $Entity . ' to skip here as it silently ignores passed in params');
1287 $params = ['sort' => [$test]];
1288 $result = _civicrm_api3_get_options_from_params($params, FALSE, $Entity, 'get');
1289 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($Entity);
1290 $this->assertEquals($lowercase_entity . $expected, $result['sort']);
1295 * @dataProvider entities_create
1297 * Check that create doesn't work with an invalid
1299 * @throws \PHPUnit\Framework\IncompleteTestError
1301 public function testInvalidID_create($Entity) {
1302 // turn test off for noew
1303 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1305 if (in_array($Entity, $this->toBeImplemented
['create'])) {
1306 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1309 $result = $this->callAPIFailure($Entity, 'Create', ['id' => 999]);
1313 * @dataProvider entities_updatesingle
1315 * limitations include the problem with avoiding loops when creating test objects -
1316 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1317 * Currency - only seems to support US
1318 * @param $entityName
1320 public function testCreateSingleValueAlter($entityName) {
1321 if (in_array($entityName, $this->toBeImplemented
['create'])) {
1322 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1326 $baoString = _civicrm_api3_get_BAO($entityName);
1327 $this->assertNotEmpty($baoString, $entityName);
1328 $this->assertNotEmpty($entityName, $entityName);
1329 $fieldsGet = $fields = $this->callAPISuccess($entityName, 'getfields', ['action' => 'get', 'options' => ['get_options' => 'all']]);
1330 if ($entityName != 'Pledge') {
1331 $fields = $this->callAPISuccess($entityName, 'getfields', ['action' => 'create', 'options' => ['get_options' => 'all']]);
1333 $fields = $fields['values'];
1334 $return = array_keys($fieldsGet['values']);
1335 $valuesNotToReturn = $this->getKnownUnworkablesUpdateSingle($entityName, 'break_return');
1336 // these can't be requested as return values
1337 $entityValuesThatDoNotWork = array_merge(
1338 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_update'),
1339 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_return'),
1343 $return = array_diff($return, $valuesNotToReturn);
1344 $baoObj = new CRM_Core_DAO();
1345 $baoObj->createTestObject($baoString, ['currency' => 'USD'], 2, 0);
1347 $getEntities = $this->callAPISuccess($entityName, 'get', [
1349 'return' => $return,
1351 'sort' => 'id DESC',
1356 // lets use first rather than assume only one exists
1357 $entity = $getEntities['values'][0];
1358 $entity2 = $getEntities['values'][1];
1359 $this->deletableTestObjects
[$baoString][] = $entity['id'];
1360 $this->deletableTestObjects
[$baoString][] = $entity2['id'];
1361 // Skip these fields that we never really expect to update well.
1362 $genericFieldsToSkip = ['currency', 'id', strtolower($entityName) . '_id', 'is_primary'];
1363 foreach ($fields as $field => $specs) {
1365 $fieldName = $field;
1367 if (in_array($field, $genericFieldsToSkip)
1368 ||
in_array($field, $entityValuesThatDoNotWork)
1370 //@todo id & entity_id are correct but we should fix currency & frequency_day
1373 $this->assertArrayHasKey('type', $specs, "the _spec function for $entityName field $field does not specify the type");
1374 switch ($specs['type']) {
1375 case CRM_Utils_Type
::T_DATE
:
1376 $entity[$fieldName] = '2012-05-20';
1379 case CRM_Utils_Type
::T_TIMESTAMP
:
1381 $entity[$fieldName] = '2012-05-20 03:05:20';
1384 case CRM_Utils_Type
::T_STRING
:
1385 case CRM_Utils_Type
::T_BLOB
:
1386 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1387 case CRM_Utils_Type
::T_TEXT
:
1388 case CRM_Utils_Type
::T_LONGTEXT
:
1389 case CRM_Utils_Type
::T_EMAIL
:
1390 if ($fieldName == 'form_values' && $entityName == 'SavedSearch') {
1391 // This is a hack for the SavedSearch API.
1392 // It expects form_values to be an array.
1393 // If you want to fix this, you should definitely read this forum
1395 // http://forum.civicrm.org/index.php/topic,33990.0.html
1396 // See also my question on the CiviCRM Stack Exchange:
1397 // https://civicrm.stackexchange.com/questions/3437
1398 $entity[$fieldName] = ['sort_name' => "SortName2"];
1401 $entity[$fieldName] = substr('New String', 0, CRM_Utils_Array
::Value('maxlength', $specs, 100));
1402 if ($fieldName == 'email') {
1403 $entity[$fieldName] = strtolower($entity[$fieldName]);
1405 // typecast with array to satisfy changes made in CRM-13160
1406 if ($entityName == 'MembershipType' && in_array($fieldName, [
1407 'relationship_type_id',
1408 'relationship_direction',
1410 $entity[$fieldName] = (array) $entity[$fieldName];
1415 case CRM_Utils_Type
::T_INT
:
1416 // probably created with a 1
1417 if ($fieldName == 'weight') {
1418 $entity[$fieldName] = 2;
1420 elseif (!empty($specs['FKClassName'])) {
1421 if ($specs['FKClassName'] == $baoString) {
1422 $entity[$fieldName] = (string) $entity2['id'];
1425 if (!empty($entity[$fieldName])) {
1426 $resetFKTo = [$fieldName => $entity[$fieldName]];
1428 $entity[$fieldName] = (string) empty($entity2[$field]) ?
'' : $entity2[$field];
1429 //todo - there isn't always something set here - & our checking on unset values is limited
1430 if (empty($entity[$field])) {
1431 unset($entity[$field]);
1436 $entity[$fieldName] = '6';
1440 case CRM_Utils_Type
::T_BOOLEAN
:
1441 // probably created with a 1
1442 $entity[$fieldName] = '0';
1445 case CRM_Utils_Type
::T_FLOAT
:
1446 case CRM_Utils_Type
::T_MONEY
:
1447 $entity[$field] = '22.75';
1450 case CRM_Utils_Type
::T_URL
:
1451 $entity[$field] = 'warm.beer.com';
1453 if (empty($specs['FKClassName']) && (!empty($specs['pseudoconstant']) ||
!empty($specs['options']))) {
1454 $options = CRM_Utils_Array
::value('options', $specs, []);
1456 //eg. pdf_format id doesn't ship with any
1457 if (isset($specs['pseudoconstant']['optionGroupName'])) {
1458 $optionValue = $this->callAPISuccess('option_value', 'create', [
1459 'option_group_id' => $specs['pseudoconstant']['optionGroupName'],
1460 'label' => 'new option value',
1463 $optionValue = $optionValue['values'];
1464 $keyColumn = CRM_Utils_Array
::value('keyColumn', $specs['pseudoconstant'], 'value');
1465 $options[$optionValue[0][$keyColumn]] = 'new option value';
1468 $entity[$field] = array_rand($options);
1470 if (!empty($specs['FKClassName']) && !empty($specs['pseudoconstant'])) {
1471 // in the weird situation where a field has both an fk and pseudoconstant defined,
1472 // e.g. campaign_id field, need to flush caches.
1473 // FIXME: Why doesn't creating a campaign clear caches?
1474 civicrm_api3($entityName, 'getfields', ['cache_clear' => 1]);
1477 'id' => $entity['id'],
1478 $field => isset($entity[$field]) ?
$entity[$field] : NULL,
1480 if (isset($updateParams['financial_type_id']) && in_array($entityName, ['Grant'])) {
1481 //api has special handling on these 2 fields for backward compatibility reasons
1482 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1484 if (isset($updateParams['next_sched_contribution_date']) && in_array($entityName, ['ContributionRecur'])) {
1485 //api has special handling on these 2 fields for backward compatibility reasons
1486 $entity['next_sched_contribution'] = $updateParams['next_sched_contribution_date'];
1488 if (isset($updateParams['image'])) {
1489 // Image field is passed through simplifyURL function so may be different, do the same here for comparison
1490 $entity['image'] = CRM_Utils_String
::simplifyURL($updateParams['image'], TRUE);
1492 if (isset($updateParams['thumbnail'])) {
1493 // Thumbnail field is passed through simplifyURL function so may be different, do the same here for comparison
1494 $entity['thumbnail'] = CRM_Utils_String
::simplifyURL($updateParams['thumbnail'], TRUE);
1497 $update = $this->callAPISuccess($entityName, 'create', $updateParams);
1499 'id' => $entity['id'],
1501 'return' => $return,
1503 'sort' => 'id DESC',
1508 $checkEntity = $this->callAPISuccess($entityName, 'getsingle', $checkParams);
1509 if (!empty($specs['serialize']) && !is_array($checkEntity[$field])) {
1510 // Put into serialized format for comparison if 'get' has not returned serialized.
1511 $entity[$field] = CRM_Core_DAO
::serializeField($checkEntity[$field], $specs['serialize']);
1514 $this->assertAPIArrayComparison($entity, $checkEntity, [], "checking if $fieldName was correctly updated\n" . print_r([
1515 'update-params' => $updateParams,
1516 'update-result' => $update,
1517 'getsingle-params' => $checkParams,
1518 'getsingle-result' => $checkEntity,
1519 'expected entity' => $entity,
1522 //reset the foreign key fields because otherwise our cleanup routine fails & some other unexpected stuff can kick in
1523 $entity = array_merge($entity, $resetFKTo);
1524 $updateParams = array_merge($updateParams, $resetFKTo);
1525 $this->callAPISuccess($entityName, 'create', $updateParams);
1526 if (isset($updateParams['financial_type_id']) && in_array($entityName, ['Grant'])) {
1527 //api has special handling on these 2 fields for backward compatibility reasons
1528 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1530 if (isset($updateParams['next_sched_contribution_date']) && in_array($entityName, ['ContributionRecur'])) {
1531 //api has special handling on these 2 fields for backward compatibility reasons
1532 $entity['next_sched_contribution'] = $updateParams['next_sched_contribution_date'];
1538 /* ---- testing the _getFields ---- */
1540 /* ---- testing the _delete ---- */
1543 * @dataProvider toBeSkipped_delete
1544 * entities that don't need a delete action
1547 public function testNotImplemented_delete($Entity) {
1548 $nonExistantID = 151416349;
1549 $result = civicrm_api($Entity, 'Delete', ['version' => 3, 'id' => $nonExistantID]);
1550 $this->assertEquals(1, $result['is_error']);
1551 $this->assertContains(strtolower("API ($Entity, Delete) does not exist"), strtolower($result['error_message']));
1555 * @dataProvider entities_delete
1558 public function testEmptyParam_delete($Entity) {
1559 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1560 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1563 $result = civicrm_api($Entity, 'Delete', []);
1564 $this->assertEquals(1, $result['is_error']);
1565 $this->assertContains("Unknown api version", $result['error_message']);
1569 * @dataProvider entities_delete
1571 * @throws \PHPUnit\Framework\IncompleteTestError
1573 public function testInvalidID_delete($Entity) {
1574 $result = $this->callAPIFailure($Entity, 'Delete', ['id' => 999999]);
1578 * Create two entities and make sure delete action only deletes one!
1580 * @dataProvider entities_delete
1582 * limitations include the problem with avoiding loops when creating test objects -
1583 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1584 * Currency - only seems to support US
1585 * @param $entityName
1586 * @throws \PHPUnit\Framework\IncompleteTestError
1588 public function testByID_delete($entityName) {
1589 // turn test off for noew
1590 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1593 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1594 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1597 $startCount = $this->callAPISuccess($entityName, 'getcount', []);
1599 $baos = $this->getMockableBAOObjects($entityName, $createcount);
1600 list($baoObj1, $baoObj2) = $baos;
1602 // make sure exactly 2 exist
1603 $result = $this->callAPISuccess($entityName, 'getcount', [],
1604 $createcount +
$startCount
1607 $this->callAPISuccess($entityName, 'delete', ['id' => $baoObj2->id
]);
1608 //make sure 1 less exists now
1609 $result = $this->callAPISuccess($entityName, 'getcount', [],
1610 ($createcount +
$startCount) - 1
1613 //make sure id #1 exists
1614 $result = $this->callAPISuccess($entityName, 'getcount', ['id' => $baoObj1->id
],
1617 //make sure id #2 desn't exist
1618 $result = $this->callAPISuccess($entityName, 'getcount', ['id' => $baoObj2->id
],
1624 * Create two entities and make sure delete action only deletes one!
1626 * @dataProvider entities_getfields
1629 public function testGetfieldsHasTitle($entity) {
1630 $entities = $this->getEntitiesSupportingCustomFields();
1631 if (in_array($entity, $entities)) {
1632 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entity . 'Test.php');
1634 $actions = $this->callAPISuccess($entity, 'getactions', []);
1635 foreach ($actions['values'] as $action) {
1636 if (substr($action, -7) == '_create' ||
substr($action, -4) == '_get' ||
substr($action, -7) == '_delete') {
1637 //getactions can't distinguish between contribution_page.create & contribution_page.create
1640 $fields = $this->callAPISuccess($entity, 'getfields', ['action' => $action]);
1641 if (!empty($ids) && in_array($action, ['create', 'get'])) {
1642 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $fields['values']);
1645 foreach ($fields['values'] as $fieldName => $fieldSpec) {
1646 $this->assertArrayHasKey('title', $fieldSpec, "no title for $entity - $fieldName on action $action");
1647 $this->assertNotEmpty($fieldSpec['title'], "empty title for $entity - $fieldName");
1651 $this->customFieldDelete($ids['custom_field_id']);
1652 $this->customGroupDelete($ids['custom_group_id']);
1659 public function getEntitiesSupportingCustomFields() {
1660 $entities = self
::custom_data_entities_get();
1661 $returnEntities = [];
1662 foreach ($entities as $entityArray) {
1663 $returnEntities[] = $entityArray[0];
1665 return $returnEntities;
1669 * @param string $entityName
1674 private function getMockableBAOObjects($entityName, $count = 2) {
1675 $baoString = _civicrm_api3_get_BAO($entityName);
1676 if (empty($baoString)) {
1677 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1682 while ($i < $count) {
1684 $baoObj = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1685 $this->assertTrue(is_int($baoObj->id
), 'check first id');
1686 $this->deletableTestObjects
[$baoString][] = $baoObj->id
;
1694 * Verify that HTML metacharacters provided as inputs appear consistently.
1697 * At time of writing, the encoding scheme requires (for example) that an
1698 * event title be partially-HTML-escaped before writing to DB. To provide
1699 * consistency, the API must perform extra encoding and decoding on some
1702 * In this example, the event 'title' is subject to encoding, but the
1703 * event 'description' is not.
1705 public function testEncodeDecodeConsistency() {
1707 $createResult = civicrm_api('Event', 'Create', [
1709 'title' => 'CiviCRM <> TheRest',
1710 'description' => 'TheRest <> CiviCRM',
1711 'event_type_id' => 1,
1713 'start_date' => 20081021,
1715 $this->assertAPISuccess($createResult);
1716 $eventId = $createResult['id'];
1717 $this->assertEquals('CiviCRM <> TheRest', $createResult['values'][$eventId]['title']);
1718 $this->assertEquals('TheRest <> CiviCRM', $createResult['values'][$eventId]['description']);
1720 // Verify "get" handles decoding in result value
1721 $getByIdResult = civicrm_api('Event', 'Get', [
1725 $this->assertAPISuccess($getByIdResult);
1726 $this->assertEquals('CiviCRM <> TheRest', $getByIdResult['values'][$eventId]['title']);
1727 $this->assertEquals('TheRest <> CiviCRM', $getByIdResult['values'][$eventId]['description']);
1729 // Verify "get" handles encoding in search value
1730 $getByTitleResult = civicrm_api('Event', 'Get', [
1732 'title' => 'CiviCRM <> TheRest',
1734 $this->assertAPISuccess($getByTitleResult);
1735 $this->assertEquals('CiviCRM <> TheRest', $getByTitleResult['values'][$eventId]['title']);
1736 $this->assertEquals('TheRest <> CiviCRM', $getByTitleResult['values'][$eventId]['description']);
1738 // Verify that "getSingle" handles decoding
1739 $getSingleResult = $this->callAPISuccess('Event', 'GetSingle', [
1743 $this->assertEquals('CiviCRM <> TheRest', $getSingleResult['title']);
1744 $this->assertEquals('TheRest <> CiviCRM', $getSingleResult['description']);
1746 // Verify that chaining handles decoding
1747 $chainResult = $this->callAPISuccess('Event', 'Get', [
1749 'api.event.get' => [],
1751 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['title']);
1752 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['description']);
1753 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['api.event.get']['values'][0]['title']);
1754 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['api.event.get']['values'][0]['description']);
1756 // Verify that "setvalue" handles encoding for updates
1757 $setValueTitleResult = civicrm_api('Event', 'setvalue', [
1761 'value' => 'setValueTitle: CiviCRM <> TheRest',
1763 $this->assertAPISuccess($setValueTitleResult);
1764 $this->assertEquals('setValueTitle: CiviCRM <> TheRest', $setValueTitleResult['values']['title']);
1765 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', [
1768 'field' => 'description',
1769 'value' => 'setValueDescription: TheRest <> CiviCRM',
1771 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1772 $this->assertEquals('setValueDescription: TheRest <> CiviCRM', $setValueDescriptionResult['values']['description']);
1776 * Verify that write operations (create/update) use partial HTML-encoding
1778 * In this example, the event 'title' is subject to encoding, but the
1779 * event 'description' is not.
1781 public function testEncodeWrite() {
1783 $createResult = civicrm_api('Event', 'Create', [
1785 'title' => 'createNew: CiviCRM <> TheRest',
1786 'description' => 'createNew: TheRest <> CiviCRM',
1787 'event_type_id' => 1,
1789 'start_date' => 20081021,
1791 $this->assertAPISuccess($createResult);
1792 $eventId = $createResult['id'];
1793 $this->assertDBQuery('createNew: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1794 1 => [$eventId, 'Integer'],
1796 $this->assertDBQuery('createNew: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1797 1 => [$eventId, 'Integer'],
1800 // Verify that "create" handles encoding for updates
1801 $createWithIdResult = civicrm_api('Event', 'Create', [
1804 'title' => 'createWithId: CiviCRM <> TheRest',
1805 'description' => 'createWithId: TheRest <> CiviCRM',
1807 $this->assertAPISuccess($createWithIdResult);
1808 $this->assertDBQuery('createWithId: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1809 1 => [$eventId, 'Integer'],
1811 $this->assertDBQuery('createWithId: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1812 1 => [$eventId, 'Integer'],
1815 // Verify that "setvalue" handles encoding for updates
1816 $setValueTitleResult = civicrm_api('Event', 'setvalue', [
1820 'value' => 'setValueTitle: CiviCRM <> TheRest',
1822 $this->assertAPISuccess($setValueTitleResult);
1823 $this->assertDBQuery('setValueTitle: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1824 1 => [$eventId, 'Integer'],
1826 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', [
1829 'field' => 'description',
1830 'value' => 'setValueDescription: TheRest <> CiviCRM',
1832 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1833 $this->assertAPISuccess($setValueDescriptionResult);
1834 $this->assertDBQuery('setValueDescription: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1835 1 => [$eventId, 'Integer'],