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;
28 * @var array e.g. $this->deletes['CRM_Contact_DAO_Contact'][] = $contactID;
30 protected $deletableTestObjects;
33 * This test case doesn't require DB reset.
36 public $DBResetRequired = FALSE;
41 * Map custom group entities to civicrm components.
44 protected static $componentMap = [
45 'Contribution' => 'CiviContribute',
46 'Membership' => 'CiviMember',
47 'Participant' => 'CiviEvent',
48 'Event' => 'CiviEvent',
50 'Pledge' => 'CiviPledge',
51 'Grant' => 'CiviGrant',
52 'Campaign' => 'CiviCampaign',
53 'Survey' => 'CiviCampaign',
59 * There are two types of missing APIs:
60 * Those that are to be implemented
61 * (in some future version when someone steps in -hint hint-). List the entities in toBeImplemented[ {$action} ]
62 * Those that don't exist
63 * and that will never exist (eg an obsoleted Entity
64 * 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)
66 public function setUp() {
68 $this->enableCiviCampaign();
69 $this->toBeImplemented
['get'] = [
70 // CxnApp.get exists but relies on remote data outside our control; QA w/UtilsTest::testBasicArrayGet
83 $this->toBeImplemented
['create'] = [
101 $this->toBeImplemented
['delete'] = [
114 $this->onlyIDNonZeroCount
['get'] = [
121 $this->deprecatedAPI
= ['Location', 'ActivityType', 'SurveyRespondant'];
122 $this->deletableTestObjects
= [];
125 public function tearDown() {
126 foreach ($this->deletableTestObjects
as $entityName => $entities) {
127 foreach ($entities as $entityID) {
128 CRM_Core_DAO
::deleteTestObjects($entityName, ['id' => $entityID]);
134 * Generate list of all entities.
141 public static function entities($skip = []) {
142 // The order of operations in here is screwy. In the case where SYNTAX_CONFORMANCE_ENTITIES is
143 // defined, we should be able to parse+return it immediately. However, some weird dependency
144 // crept into the system where civicrm_api('Entity','get') must be called as part of entities()
145 // (even if its return value is ignored).
147 $tmp = civicrm_api('Entity', 'Get', ['version' => 3]);
148 if (getenv('SYNTAX_CONFORMANCE_ENTITIES')) {
150 'values' => explode(' ', getenv('SYNTAX_CONFORMANCE_ENTITIES')),
154 if (!is_array($skip)) {
157 $tmp = array_diff($tmp['values'], $skip);
159 foreach ($tmp as $e) {
166 * Get list of entities for get test.
170 public static function entities_get() {
171 // all the entities, beside the ones flagged
172 return static::entities(static::toBeSkipped_get(TRUE));
176 * Get entities for create tests.
180 public static function entities_create() {
181 return static::entities(static::toBeSkipped_create(TRUE));
187 public static function entities_updatesingle() {
188 return static::entities(static::toBeSkipped_updatesingle(TRUE));
194 public static function entities_getlimit() {
195 return static::entities(static::toBeSkipped_getlimit());
199 * Generate list of entities that can be retrieved using SQL operator syntax.
203 public static function entities_getSqlOperators() {
204 return static::entities(static::toBeSkipped_getSqlOperators());
210 public static function entities_delete() {
211 return static::entities(static::toBeSkipped_delete(TRUE));
217 public static function entities_getfields() {
218 return static::entities(static::toBeSkipped_getfields(TRUE));
224 public static function custom_data_entities_get() {
225 return static::custom_data_entities();
231 public static function custom_data_entities() {
232 $entities = CRM_Core_BAO_CustomQuery
::$extendsMap;
233 $enabledComponents = Civi
::settings()->get('enable_components');
234 $customDataEntities = [];
235 $invalidEntities = ['Individual', 'Organization', 'Household'];
236 $entitiesToFix = ['Case', 'Relationship'];
237 foreach ($entities as $entityName => $entity) {
238 if (!in_array($entityName, $invalidEntities)
239 && !in_array($entityName, $entitiesToFix)
241 if (!empty(self
::$componentMap[$entityName]) && empty($enabledComponents[self
::$componentMap[$entityName]])) {
242 CRM_Core_BAO_ConfigSetting
::enableComponent(self
::$componentMap[$entityName]);
244 $customDataEntities[] = [$entityName];
247 return $customDataEntities;
251 * Add a smattering of entities that don't normally have custom data.
255 public static function custom_data_incl_non_std_entities_get() {
256 return static::entities(static::toBeSkipped_custom_data_creatable(TRUE));
260 * Get entities to be skipped on get tests.
262 * @param bool $sequential
266 public static function toBeSkipped_get($sequential = FALSE) {
267 $entitiesWithoutGet = [
268 'MailingEventSubscribe',
269 'MailingEventConfirm',
270 'MailingEventResubscribe',
271 'MailingEventUnsubscribe',
274 if ($sequential === TRUE) {
275 return $entitiesWithoutGet;
278 foreach ($entitiesWithoutGet as $e) {
285 * Get entities to be skipped for get call.
287 * Mailing Contact Just doesn't support id. We have always insisted on finding a way to
288 * support id in API but in this case the underlying tables are crying out for a restructure
289 * & it just doesn't make sense.
291 * User doesn't support get By ID because the user id is actually the CMS user ID & is not part of
292 * CiviCRM - so can only be tested through UserTest - not SyntaxConformanceTest.
294 * Entity doesn't support get By ID because it simply gives the result of string Entites in CiviCRM
296 * @param bool $sequential
299 * Entities that cannot be retrieved by ID
301 public static function toBeSkipped_getByID($sequential = FALSE) {
302 return ['MailingContact', 'User', 'Attachment', 'Entity'];
306 * @param bool $sequential
310 public static function toBeSkipped_create($sequential = FALSE) {
311 $entitiesWithoutCreate = ['Constant', 'Entity', 'Location', 'Profile', 'MailingRecipients'];
312 if ($sequential === TRUE) {
313 return $entitiesWithoutCreate;
316 foreach ($entitiesWithoutCreate as $e) {
323 * @param bool $sequential
327 public static function toBeSkipped_delete($sequential = FALSE) {
330 'MailingEventConfirm',
331 'MailingEventResubscribe',
332 'MailingEventSubscribe',
333 'MailingEventUnsubscribe',
345 if ($sequential === TRUE) {
346 return $entitiesWithout;
349 foreach ($entitiesWithout as $e) {
356 * @param bool $sequential
360 public static function toBeSkipped_custom_data_creatable($sequential = FALSE) {
371 'MailingEventConfirm',
372 'MailingEventResubscribe',
373 'MailingEventSubscribe',
374 'MailingEventUnsubscribe',
385 // ones that are not real entities hence not extendable.
409 if ($sequential === TRUE) {
410 return $entitiesWithout;
413 foreach ($entitiesWithout as $e) {
420 * @param bool $sequential
423 * @todo add metadata for ALL these entities
425 public static function toBeSkipped_getfields($sequential = FALSE) {
426 $entitiesWithMetadataNotYetFixed = ['ReportTemplate', 'CustomSearch'];
427 if ($sequential === TRUE) {
428 return $entitiesWithMetadataNotYetFixed;
431 foreach ($entitiesWithMetadataNotYetFixed as $e) {
438 * Generate list of entities to test for get by id functions.
439 * @param bool $sequential
441 * Entities to be skipped
443 public static function toBeSkipped_automock($sequential = FALSE) {
444 $entitiesWithoutGet = [
458 if ($sequential === TRUE) {
459 return $entitiesWithoutGet;
462 foreach ($entitiesWithoutGet as $e) {
469 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
470 * @param bool $sequential
473 public static function toBeSkipped_updatesingle($sequential = FALSE) {
476 // pseudo-entity; testUpdateSingleValueAlter doesn't introspect properly on it. Multiple magic fields
478 'MailingEventUnsubscribe',
479 'MailingEventSubscribe',
497 'MailingEventConfirm',
502 'MailingEventResubscribe',
516 //skip this because it doesn't make sense to update logs,
519 if ($sequential === TRUE) {
520 return $entitiesWithout;
523 foreach ($entitiesWithout as $e) {
533 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
535 public static function toBeSkipped_getlimit() {
538 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
540 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
542 // failed 'check that a 5 limit returns 5' - probably is_template field is wrong or something, or could be limit doesn't work right
544 // can't handle creating 25
546 // fails on 5 limit - probably a set up problem
548 //a bit of a pseudoapi - keys by domain
550 // pseudoapi - problems with creating required sub entities.
552 return $entitiesWithout;
556 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
558 public static function toBeSkipped_getSqlOperators() {
560 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
564 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
566 // can't handle creating 25
568 // note has a default get that isn't implemented in createTestObject -meaning you don't 'get' them
570 //a bit of a pseudoapi - keys by domain
574 // The testSqlOperators fails sporadically on MySQL 5.5, which is deprecated anyway.
575 // Test data providers should be able to run in pre-boot environment, so we connect directly to SQL server.
576 require_once 'DB.php';
577 $db = DB
::connect(CIVICRM_DSN
);
578 if ($db->connection
instanceof mysqli
&& $db->connection
->server_version
< 50600) {
579 $entitiesWithout[] = 'Dedupe';
582 return $entitiesWithout;
591 public function getKnownUnworkablesUpdateSingle($entity, $key) {
592 // can't update values are values for which updates don't result in the value being changed
594 'ActionSchedule' => [
599 'ActivityContact' => [
602 //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
607 //issues with country id - need to ensure same country
610 //creates relationship
613 'cant_return' => ['street_parsing', 'skip_geocode', 'fix_address'],
617 // believe this field is defined in error
629 'Domain' => ['cant_update' => ['domain_version']],
630 'MembershipBlock' => [
632 // The fake/auto-generated values leave us unable to properly cleanup fake data
637 'MailingJob' => ['cant_update' => ['parent_id']],
638 'ContributionSoft' => [
640 // can't be changed through api
646 // This is being legitimately manipulated to always have a valid primary - skip.
652 // Weight is deliberately altered when this is changed - skip.
658 // I'm on the fence about whether the test should skip or the behaviour is wrong.
659 // display_name is set to match name if display_name is not provided. It would be more 'normal'
660 // to only calculate a default IF id is not set - but perhaps the current behaviour is kind
661 // of what someone updating the name expects..
667 'pledge_original_installment_amount',
669 'original_installment_amount',
671 // can't be changed through API,
674 // if these are passed in they are retrieved from the wrong table
678 'contribution_page_id',
679 'financial_account_id',
683 // can't be retrieved from api
685 //due to uniquename missing
694 'initial_reminder_day',
695 'additional_reminder_day',
697 'pledge_contribution_page_id',
699 'pledge_campaign_id',
700 'pledge_financial_type_id',
703 'PaymentProcessorType' => [
707 'break_return' => [],
710 'PriceFieldValue' => [
712 //won't update as there is no 1 in the same price set
716 'ReportInstance' => [
717 // View mode is part of the navigation which is not retrieved by the api.
718 'cant_return' => ['view_mode'],
721 // I think the fields below are generated based on form_values.
729 'StatusPreference' => [
736 // These fields get auto-adjusted by the BAO prior to saving
745 // These fields get auto-adjusted by the BAO prior to saving
756 // For better or worse triggers override.
757 'break_return' => ['run_time'],
758 'cant_update' => ['run_time'],
761 if (empty($knownFailures[$entity]) ||
empty($knownFailures[$entity][$key])) {
764 return $knownFailures[$entity][$key];
767 /* ----- testing the _get ----- */
770 * @dataProvider toBeSkipped_get
771 * Entities that don't need a get action
774 public function testNotImplemented_get($Entity) {
775 $result = civicrm_api($Entity, 'Get', ['version' => 3]);
776 $this->assertEquals(1, $result['is_error']);
777 // $this->assertContains("API ($Entity, Get) does not exist", $result['error_message']);
778 $this->assertRegExp('/API (.*) does not exist/', $result['error_message']);
782 * @dataProvider entities
785 public function testGetFields($Entity) {
786 if (in_array($Entity, $this->deprecatedAPI
) ||
$Entity == 'Entity' ||
$Entity == 'CustomValue') {
790 $result = civicrm_api($Entity, 'getfields', ['version' => 3]);
791 $this->assertTrue(is_array($result['values']), "$Entity ::get fields doesn't return values array in line " . __LINE__
);
792 foreach ($result['values'] as $key => $value) {
793 $this->assertTrue(is_array($value), $Entity . "::" . $key . " is not an array in line " . __LINE__
);
798 * @dataProvider entities_get
801 public function testEmptyParam_get($Entity) {
803 if (in_array($Entity, $this->toBeImplemented
['get'])) {
804 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
807 $result = civicrm_api($Entity, 'Get', []);
808 $this->assertEquals(1, $result['is_error']);
809 $this->assertContains("Unknown api version", $result['error_message']);
813 * @dataProvider entities_get
814 * @Xdepends testEmptyParam_get // no need to test the simple if the empty doesn't work/is skipped. doesn't seem to work
817 public function testSimple_get($Entity) {
818 // $this->markTestSkipped("test gives core error on test server (but not on our locals). Skip until we can get server to pass");
819 if (in_array($Entity, $this->toBeImplemented
['get'])) {
822 $result = civicrm_api($Entity, 'Get', ['version' => 3]);
823 // @TODO: list the get that have mandatory params
824 if ($result['is_error']) {
825 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
826 // either id or contact_id or entity_id is one of the field missing
827 $this->assertContains("id", $result['error_message']);
830 $this->assertEquals(3, $result['version']);
831 $this->assertArrayHasKey('count', $result);
832 $this->assertArrayHasKey('values', $result);
837 * @dataProvider custom_data_incl_non_std_entities_get
840 public function testCustomDataGet($entityName) {
841 if ($entityName === 'Note') {
842 $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');
844 $this->quickCleanup(['civicrm_uf_match']);
845 // so subsidiary activities are created
846 $this->createLoggedInUser();
848 $entitiesWithNamingIssues = [
849 'SmsProvider' => 'Provider',
850 'AclRole' => 'EntityRole',
851 'MailingEventQueue' => 'Queue',
852 'Dedupe' => 'PrevNextCache',
855 $usableName = !empty($entitiesWithNamingIssues[$entityName]) ?
$entitiesWithNamingIssues[$entityName] : $entityName;
856 $optionName = CRM_Core_DAO_AllCoreTables
::getTableForClass(CRM_Core_DAO_AllCoreTables
::getFullName($usableName));
858 if (!isset(CRM_Core_BAO_CustomQuery
::$extendsMap[$entityName])) {
859 $createdValue = $this->callAPISuccess('OptionValue', 'create', [
860 'option_group_id' => 'cg_extend_objects',
861 'label' => $usableName,
862 'value' => $usableName,
863 'name' => $optionName,
866 // We are not passing 'check_permissions' so the the more limited permissions *should* be
867 // ignored but per CRM-17700 there is a history of custom data applying permissions when it shouldn't.
868 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= ['access CiviCRM', 'view my contact'];
869 $objects = $this->getMockableBAOObjects($entityName, 1);
871 // simple custom field
872 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $usableName . 'Test.php');
873 $customFieldName = 'custom_' . $ids['custom_field_id'];
874 $params = ['id' => $objects[0]->id
, 'custom_' . $ids['custom_field_id'] => "custom string"];
875 $result = $this->callAPISuccess($entityName, 'create', $params);
876 $this->assertTrue(isset($result['id']), 'no id on ' . $entityName);
877 $getParams = ['id' => $result['id'], 'return' => [$customFieldName]];
878 $check = $this->callAPISuccess($entityName, 'get', $getParams);
879 $this->assertTrue(!empty($check['values'][$check['id']][$customFieldName]), 'Custom data not present for ' . $entityName);
880 $this->assertEquals("custom string", $check['values'][$check['id']][$customFieldName], 'Custom data not present for ' . $entityName);
881 $this->customFieldDelete($ids['custom_field_id']);
882 $this->customGroupDelete($ids['custom_group_id']);
884 $ids2 = $this->entityCustomGroupWithSingleStringMultiSelectFieldCreate(__FUNCTION__
, $usableName . 'Test.php');
885 $customFieldNameMultiSelect = 'custom_' . $ids2['custom_field_id'];
886 // String custom field, Multi-Select html type
887 foreach ($ids2['custom_field_group_options'] as $option_value => $option_label) {
888 $params = ['id' => $objects[0]->id
, 'custom_' . $ids2['custom_field_id'] => $option_value];
889 $result = $this->callAPISuccess($entityName, 'create', $params);
890 $getParams = [$customFieldNameMultiSelect => $option_value, 'return' => [$customFieldNameMultiSelect]];
891 $this->callAPISuccessGetCount($entityName, $getParams, 1);
895 $this->customFieldDelete($ids2['custom_field_id']);
896 $this->customGroupDelete($ids2['custom_group_id']);
898 $this->callAPISuccess($entityName, 'delete', ['id' => $result['id']]);
899 $this->quickCleanup(['civicrm_uf_match']);
900 if (!empty($createdValue)) {
901 $this->callAPISuccess('OptionValue', 'delete', ['id' => $createdValue['id']]);
906 * @dataProvider entities_get
909 public function testAcceptsOnlyID_get($Entity) {
910 // big random number. fun fact: if you multiply it by pi^e, the result is another random number, but bigger ;)
911 $nonExistantID = 30867307034;
912 if (in_array($Entity, $this->toBeImplemented
['get'])
913 ||
in_array($Entity, $this->toBeSkipped_getByID())
919 // the below function returns different values and hence an early return
920 // we'll fix this once beta1 is released
923 $result = civicrm_api($Entity, 'Get', ['version' => 3, 'id' => $nonExistantID]);
925 if ($result['is_error']) {
926 // just to get a clearer message in the log
927 $this->assertEquals("only id should be enough", $result['error_message']);
929 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
930 $this->assertEquals(0, $result['count']);
936 * @dataProvider entities_get
939 public function testGetList($Entity) {
940 if (in_array($Entity, $this->toBeImplemented
['get'])
941 ||
in_array($Entity, $this->toBeSkipped_getByID())
945 if (in_array($Entity, ['ActivityType', 'SurveyRespondant'])) {
946 $this->markTestSkipped();
948 $this->callAPISuccess($Entity, 'getlist', ['label_field' => 'id']);
952 * Test getlist works when entity is lowercase
953 * @dataProvider entities_get
956 public function testGetListLowerCaseEntity($Entity) {
957 if (in_array($Entity, $this->toBeImplemented
['get'])
958 ||
in_array($Entity, $this->toBeSkipped_getByID())
962 if (in_array($Entity, ['ActivityType', 'SurveyRespondant'])) {
963 $this->markTestSkipped();
965 if ($Entity == 'UFGroup') {
968 $this->callAPISuccess($Entity, 'getlist', ['label_field' => 'id']);
972 * Create two entities and make sure we can fetch them individually by ID.
974 * @dataProvider entities_get
976 * limitations include the problem with avoiding loops when creating test objects -
977 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
978 * Currency - only seems to support US
981 public function testByID_get($entityName) {
982 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
983 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
987 $baos = $this->getMockableBAOObjects($entityName);
988 list($baoObj1, $baoObj2) = $baos;
991 $result = $this->callAPISuccess($entityName, 'get', [
992 'id' => $baoObj1->id
,
995 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
996 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
997 $this->assertEquals(1, count($result['values']));
999 // fetch second by ID
1000 $result = $this->callAPISuccess($entityName, 'get', [
1001 'id' => $baoObj2->id
,
1003 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
1004 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
1005 $this->assertEquals(1, count($result['values']));
1009 * Ensure that the "get" operation accepts limiting the #result records.
1011 * TODO Consider making a separate entity list ("entities_getlimit")
1012 * For the moment, the "entities_updatesingle" list should give a good
1013 * sense for which entities support createTestObject
1015 * @dataProvider entities_getlimit
1017 * @param string $entityName
1019 public function testLimit($entityName) {
1020 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
1023 ['options' => ['limit' => NULL]],
1025 'check that a NULL limit returns unlimited',
1028 ['options' => ['limit' => FALSE]],
1030 'check that a FALSE limit returns unlimited',
1033 ['options' => ['limit' => 0]],
1035 'check that a 0 limit returns unlimited',
1038 ['options' => ['limit' => 5]],
1040 'check that a 5 limit returns 5',
1045 'check that no limit returns 25',
1048 $baoString = _civicrm_api3_get_BAO($entityName);
1049 if (empty($baoString)) {
1050 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1054 // make 30 test items -- 30 > 25 (the default limit)
1056 for ($i = 0; $i < 30; $i++
) {
1057 $baoObj = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1058 $ids[] = $baoObj->id
;
1061 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
1062 foreach ($cases as $case) {
1063 $this->checkLimitAgainstExpected($entityName, $case[0], $case[1], $case[2]);
1065 //non preferred / legacy syntax
1066 if (isset($case[0]['options']['limit'])) {
1067 $this->checkLimitAgainstExpected($entityName, ['rowCount' => $case[0]['options']['limit']], $case[1], $case[2]);
1068 $this->checkLimitAgainstExpected($entityName, ['option_limit' => $case[0]['options']['limit']], $case[1], $case[2]);
1069 $this->checkLimitAgainstExpected($entityName, ['option.limit' => $case[0]['options']['limit']], $case[1], $case[2]);
1072 foreach ($ids as $id) {
1073 CRM_Core_DAO
::deleteTestObjects($baoString, ['id' => $id]);
1078 * Ensure that the "get" operation accepts limiting the #result records.
1080 * @dataProvider entities_getSqlOperators
1082 * @param string $entityName
1084 public function testSqlOperators($entityName) {
1085 $toBeIgnored = array_merge($this->toBeImplemented
['get'],
1086 $this->deprecatedAPI
,
1087 $this->toBeSkipped_get(TRUE),
1088 $this->toBeSkipped_getByID()
1090 if (in_array($entityName, $toBeIgnored)) {
1094 $baoString = _civicrm_api3_get_BAO($entityName);
1096 $entities = $this->callAPISuccess($entityName, 'get', ['options' => ['limit' => 0], 'return' => 'id']);
1097 $entities = array_keys($entities['values']);
1098 $totalEntities = count($entities);
1099 if ($totalEntities < 3) {
1101 for ($i = 0; $i < 3 - $totalEntities; $i++
) {
1102 $baoObj = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1103 $ids[] = $baoObj->id
;
1107 $entities = $this->callAPISuccess($entityName, 'get', ['options' => ['limit' => 0]]);
1108 $entities = array_keys($entities['values']);
1109 $this->assertGreaterThan(2, $totalEntities);
1110 $this->callAPISuccess($entityName, 'getsingle', ['id' => ['IN' => [$entities[0]]]]);
1111 $this->callAPISuccessGetCount($entityName, ['id' => ['NOT IN' => [$entities[0]]]], $totalEntities - 1);
1112 $this->callAPISuccessGetCount($entityName, ['id' => ['>' => $entities[0]]], $totalEntities - 1);
1116 * Check that get fetches an appropriate number of results.
1118 * @param string $entityName
1119 * Name of entity to test.
1120 * @param array $params
1122 * @param string $message
1124 public function checkLimitAgainstExpected($entityName, $params, $limit, $message) {
1125 $result = $this->callAPISuccess($entityName, 'get', $params);
1127 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
1128 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
1131 $this->assertEquals($limit, $result['count'], $message);
1132 $this->assertEquals($limit, count($result['values']), $message);
1137 * Create two entities and make sure we can fetch them individually by ID (e.g. using "contact_id=>2"
1140 * @dataProvider entities_get
1142 * limitations include the problem with avoiding loops when creating test objects -
1143 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1144 * Currency - only seems to support US
1145 * @param $entityName
1146 * @throws \PHPUnit\Framework\IncompleteTestError
1148 public function testByIDAlias_get($entityName) {
1149 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1150 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1154 $baoString = _civicrm_api3_get_BAO($entityName);
1155 if (empty($baoString)) {
1156 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1160 $idFieldName = _civicrm_api_get_entity_name_from_camel($entityName) . '_id';
1163 $baoObj1 = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1164 $this->assertTrue(is_int($baoObj1->id
), 'check first id');
1165 $this->deletableTestObjects
[$baoString][] = $baoObj1->id
;
1166 $baoObj2 = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1167 $this->assertTrue(is_int($baoObj2->id
), 'check second id');
1168 $this->deletableTestObjects
[$baoString][] = $baoObj2->id
;
1170 // fetch first by ID
1171 $result = civicrm_api($entityName, 'get', [
1173 $idFieldName => $baoObj1->id
,
1175 $this->assertAPISuccess($result);
1176 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
1177 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
1178 $this->assertEquals(1, count($result['values']));
1180 // fetch second by ID
1181 $result = civicrm_api($entityName, 'get', [
1183 $idFieldName => $baoObj2->id
,
1185 $this->assertAPISuccess($result);
1186 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
1187 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
1188 $this->assertEquals(1, count($result['values']));
1192 * @dataProvider entities_get
1195 public function testNonExistantID_get($Entity) {
1196 // cf testAcceptsOnlyID_get
1197 $nonExistantID = 30867307034;
1198 if (in_array($Entity, $this->toBeImplemented
['get'])) {
1202 $result = civicrm_api($Entity, 'Get', ['version' => 3, 'id' => $nonExistantID]);
1204 // redundant with testAcceptsOnlyID_get
1205 if ($result['is_error']) {
1209 $this->assertArrayHasKey('version', $result);
1210 $this->assertEquals(3, $result['version']);
1211 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
1212 $this->assertEquals(0, $result['count']);
1216 /* ---- testing the _create ---- */
1219 * @dataProvider toBeSkipped_create
1220 * entities that don't need a create action
1223 public function testNotImplemented_create($Entity) {
1224 $result = civicrm_api($Entity, 'Create', ['version' => 3]);
1225 $this->assertEquals(1, $result['is_error']);
1226 $this->assertContains(strtolower("API ($Entity, Create) does not exist"), strtolower($result['error_message']));
1230 * @dataProvider entities
1231 * @expectedException CiviCRM_API3_Exception
1234 public function testWithoutParam_create($Entity) {
1235 if ($Entity === 'Setting') {
1236 $this->markTestSkipped('It seems OK for setting to skip here as it silently sips invalid params');
1238 elseif ($Entity === 'Mailing') {
1239 $this->markTestSkipped('It seems OK for "Mailing" to skip here because you can create empty drafts');
1241 // should create php complaining that a param is missing
1242 civicrm_api3($Entity, 'Create');
1246 * @dataProvider entities_create
1248 * Check that create doesn't work with an invalid
1250 * @throws \PHPUnit\Framework\IncompleteTestError
1252 public function testInvalidSort_get($Entity) {
1253 $invalidEntitys = ['ActivityType', 'Setting', 'System'];
1254 if (in_array($Entity, $invalidEntitys)) {
1255 $this->markTestSkipped('It seems OK for ' . $Entity . ' to skip here as it silently sips invalid params');
1257 $result = $this->callAPIFailure($Entity, 'get', ['options' => ['sort' => 'sleep(1)']]);
1261 * @dataProvider entities_create
1263 * Check that create doesn't work with an invalid
1265 * @throws \PHPUnit\Framework\IncompleteTestError
1267 public function testValidSortSingleArrayById_get($Entity) {
1268 $invalidEntitys = ['ActivityType', 'Setting', 'System'];
1271 'id desc' => '_id desc',
1272 'id DESC' => '_id DESC',
1273 'id ASC' => '_id ASC',
1274 'id asc' => '_id asc',
1276 foreach ($tests as $test => $expected) {
1277 if (in_array($Entity, $invalidEntitys)) {
1278 $this->markTestSkipped('It seems OK for ' . $Entity . ' to skip here as it silently ignores passed in params');
1280 $params = ['sort' => [$test]];
1281 $result = _civicrm_api3_get_options_from_params($params, FALSE, $Entity, 'get');
1282 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($Entity);
1283 $this->assertEquals($lowercase_entity . $expected, $result['sort']);
1288 * @dataProvider entities_create
1290 * Check that create doesn't work with an invalid
1292 * @throws \PHPUnit\Framework\IncompleteTestError
1294 public function testInvalidID_create($Entity) {
1295 // turn test off for noew
1296 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1298 if (in_array($Entity, $this->toBeImplemented
['create'])) {
1299 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1302 $result = $this->callAPIFailure($Entity, 'Create', ['id' => 999]);
1306 * @dataProvider entities_updatesingle
1308 * limitations include the problem with avoiding loops when creating test objects -
1309 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1310 * Currency - only seems to support US
1311 * @param $entityName
1313 public function testCreateSingleValueAlter($entityName) {
1314 if (in_array($entityName, $this->toBeImplemented
['create'])) {
1315 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1319 $baoString = _civicrm_api3_get_BAO($entityName);
1320 $this->assertNotEmpty($baoString, $entityName);
1321 $this->assertNotEmpty($entityName, $entityName);
1322 $fieldsGet = $fields = $this->callAPISuccess($entityName, 'getfields', ['action' => 'get', 'options' => ['get_options' => 'all']]);
1323 if ($entityName != 'Pledge') {
1324 $fields = $this->callAPISuccess($entityName, 'getfields', ['action' => 'create', 'options' => ['get_options' => 'all']]);
1326 $fields = $fields['values'];
1327 $return = array_keys($fieldsGet['values']);
1328 $valuesNotToReturn = $this->getKnownUnworkablesUpdateSingle($entityName, 'break_return');
1329 // these can't be requested as return values
1330 $entityValuesThatDoNotWork = array_merge(
1331 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_update'),
1332 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_return'),
1336 $return = array_diff($return, $valuesNotToReturn);
1337 $baoObj = new CRM_Core_DAO();
1338 $baoObj->createTestObject($baoString, ['currency' => 'USD'], 2, 0);
1340 $getEntities = $this->callAPISuccess($entityName, 'get', [
1342 'return' => $return,
1344 'sort' => 'id DESC',
1349 // lets use first rather than assume only one exists
1350 $entity = $getEntities['values'][0];
1351 $entity2 = $getEntities['values'][1];
1352 $this->deletableTestObjects
[$baoString][] = $entity['id'];
1353 $this->deletableTestObjects
[$baoString][] = $entity2['id'];
1354 // Skip these fields that we never really expect to update well.
1355 $genericFieldsToSkip = ['currency', 'id', strtolower($entityName) . '_id', 'is_primary'];
1356 foreach ($fields as $field => $specs) {
1358 $fieldName = $field;
1360 if (in_array($field, $genericFieldsToSkip)
1361 ||
in_array($field, $entityValuesThatDoNotWork)
1363 //@todo id & entity_id are correct but we should fix currency & frequency_day
1366 $this->assertArrayHasKey('type', $specs, "the _spec function for $entityName field $field does not specify the type");
1367 switch ($specs['type']) {
1368 case CRM_Utils_Type
::T_DATE
:
1369 $entity[$fieldName] = '2012-05-20';
1372 case CRM_Utils_Type
::T_TIMESTAMP
:
1374 $entity[$fieldName] = '2012-05-20 03:05:20';
1377 case CRM_Utils_Type
::T_STRING
:
1378 case CRM_Utils_Type
::T_BLOB
:
1379 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1380 case CRM_Utils_Type
::T_TEXT
:
1381 case CRM_Utils_Type
::T_LONGTEXT
:
1382 case CRM_Utils_Type
::T_EMAIL
:
1383 if ($fieldName == 'form_values' && $entityName == 'SavedSearch') {
1384 // This is a hack for the SavedSearch API.
1385 // It expects form_values to be an array.
1386 // If you want to fix this, you should definitely read this forum
1388 // http://forum.civicrm.org/index.php/topic,33990.0.html
1389 // See also my question on the CiviCRM Stack Exchange:
1390 // https://civicrm.stackexchange.com/questions/3437
1391 $entity[$fieldName] = ['sort_name' => "SortName2"];
1394 $entity[$fieldName] = substr('New String', 0, CRM_Utils_Array
::Value('maxlength', $specs, 100));
1395 if ($fieldName == 'email') {
1396 $entity[$fieldName] = strtolower($entity[$fieldName]);
1398 // typecast with array to satisfy changes made in CRM-13160
1399 if ($entityName == 'MembershipType' && in_array($fieldName, [
1400 'relationship_type_id',
1401 'relationship_direction',
1403 $entity[$fieldName] = (array) $entity[$fieldName];
1408 case CRM_Utils_Type
::T_INT
:
1409 // probably created with a 1
1410 if ($fieldName == 'weight') {
1411 $entity[$fieldName] = 2;
1413 elseif (!empty($specs['FKClassName'])) {
1414 if ($specs['FKClassName'] == $baoString) {
1415 $entity[$fieldName] = (string) $entity2['id'];
1418 if (!empty($entity[$fieldName])) {
1419 $resetFKTo = [$fieldName => $entity[$fieldName]];
1421 $entity[$fieldName] = (string) empty($entity2[$field]) ?
'' : $entity2[$field];
1422 //todo - there isn't always something set here - & our checking on unset values is limited
1423 if (empty($entity[$field])) {
1424 unset($entity[$field]);
1429 $entity[$fieldName] = '6';
1433 case CRM_Utils_Type
::T_BOOLEAN
:
1434 // probably created with a 1
1435 $entity[$fieldName] = '0';
1438 case CRM_Utils_Type
::T_FLOAT
:
1439 case CRM_Utils_Type
::T_MONEY
:
1440 $entity[$field] = '22.75';
1443 case CRM_Utils_Type
::T_URL
:
1444 $entity[$field] = 'warm.beer.com';
1446 if (empty($specs['FKClassName']) && (!empty($specs['pseudoconstant']) ||
!empty($specs['options']))) {
1447 $options = CRM_Utils_Array
::value('options', $specs, []);
1449 //eg. pdf_format id doesn't ship with any
1450 if (isset($specs['pseudoconstant']['optionGroupName'])) {
1451 $optionValue = $this->callAPISuccess('option_value', 'create', [
1452 'option_group_id' => $specs['pseudoconstant']['optionGroupName'],
1453 'label' => 'new option value',
1456 $optionValue = $optionValue['values'];
1457 $keyColumn = CRM_Utils_Array
::value('keyColumn', $specs['pseudoconstant'], 'value');
1458 $options[$optionValue[0][$keyColumn]] = 'new option value';
1461 $entity[$field] = array_rand($options);
1463 if (!empty($specs['FKClassName']) && !empty($specs['pseudoconstant'])) {
1464 // in the weird situation where a field has both an fk and pseudoconstant defined,
1465 // e.g. campaign_id field, need to flush caches.
1466 // FIXME: Why doesn't creating a campaign clear caches?
1467 civicrm_api3($entityName, 'getfields', ['cache_clear' => 1]);
1470 'id' => $entity['id'],
1471 $field => isset($entity[$field]) ?
$entity[$field] : NULL,
1473 if (isset($updateParams['financial_type_id']) && in_array($entityName, ['Grant'])) {
1474 //api has special handling on these 2 fields for backward compatibility reasons
1475 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1477 if (isset($updateParams['next_sched_contribution_date']) && in_array($entityName, ['ContributionRecur'])) {
1478 //api has special handling on these 2 fields for backward compatibility reasons
1479 $entity['next_sched_contribution'] = $updateParams['next_sched_contribution_date'];
1481 if (isset($updateParams['image'])) {
1482 // Image field is passed through simplifyURL function so may be different, do the same here for comparison
1483 $entity['image'] = CRM_Utils_String
::simplifyURL($updateParams['image'], TRUE);
1485 if (isset($updateParams['thumbnail'])) {
1486 // Thumbnail field is passed through simplifyURL function so may be different, do the same here for comparison
1487 $entity['thumbnail'] = CRM_Utils_String
::simplifyURL($updateParams['thumbnail'], TRUE);
1490 $update = $this->callAPISuccess($entityName, 'create', $updateParams);
1492 'id' => $entity['id'],
1494 'return' => $return,
1496 'sort' => 'id DESC',
1501 $checkEntity = $this->callAPISuccess($entityName, 'getsingle', $checkParams);
1502 if (!empty($specs['serialize']) && !is_array($checkEntity[$field])) {
1503 // Put into serialized format for comparison if 'get' has not returned serialized.
1504 $entity[$field] = CRM_Core_DAO
::serializeField($checkEntity[$field], $specs['serialize']);
1507 $this->assertAPIArrayComparison($entity, $checkEntity, [], "checking if $fieldName was correctly updated\n" . print_r([
1508 'update-params' => $updateParams,
1509 'update-result' => $update,
1510 'getsingle-params' => $checkParams,
1511 'getsingle-result' => $checkEntity,
1512 'expected entity' => $entity,
1515 //reset the foreign key fields because otherwise our cleanup routine fails & some other unexpected stuff can kick in
1516 $entity = array_merge($entity, $resetFKTo);
1517 $updateParams = array_merge($updateParams, $resetFKTo);
1518 $this->callAPISuccess($entityName, 'create', $updateParams);
1519 if (isset($updateParams['financial_type_id']) && in_array($entityName, ['Grant'])) {
1520 //api has special handling on these 2 fields for backward compatibility reasons
1521 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1523 if (isset($updateParams['next_sched_contribution_date']) && in_array($entityName, ['ContributionRecur'])) {
1524 //api has special handling on these 2 fields for backward compatibility reasons
1525 $entity['next_sched_contribution'] = $updateParams['next_sched_contribution_date'];
1531 /* ---- testing the _getFields ---- */
1533 /* ---- testing the _delete ---- */
1536 * @dataProvider toBeSkipped_delete
1537 * entities that don't need a delete action
1540 public function testNotImplemented_delete($Entity) {
1541 $nonExistantID = 151416349;
1542 $result = civicrm_api($Entity, 'Delete', ['version' => 3, 'id' => $nonExistantID]);
1543 $this->assertEquals(1, $result['is_error']);
1544 $this->assertContains(strtolower("API ($Entity, Delete) does not exist"), strtolower($result['error_message']));
1548 * @dataProvider entities_delete
1551 public function testEmptyParam_delete($Entity) {
1552 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1553 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1556 $result = civicrm_api($Entity, 'Delete', []);
1557 $this->assertEquals(1, $result['is_error']);
1558 $this->assertContains("Unknown api version", $result['error_message']);
1562 * @dataProvider entities_delete
1564 * @throws \PHPUnit\Framework\IncompleteTestError
1566 public function testInvalidID_delete($Entity) {
1567 $result = $this->callAPIFailure($Entity, 'Delete', ['id' => 999999]);
1571 * Create two entities and make sure delete action only deletes one!
1573 * @dataProvider entities_delete
1575 * limitations include the problem with avoiding loops when creating test objects -
1576 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1577 * Currency - only seems to support US
1578 * @param $entityName
1579 * @throws \PHPUnit\Framework\IncompleteTestError
1581 public function testByID_delete($entityName) {
1582 // turn test off for noew
1583 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1586 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1587 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1590 $startCount = $this->callAPISuccess($entityName, 'getcount', []);
1592 $baos = $this->getMockableBAOObjects($entityName, $createcount);
1593 list($baoObj1, $baoObj2) = $baos;
1595 // make sure exactly 2 exist
1596 $result = $this->callAPISuccess($entityName, 'getcount', [],
1597 $createcount +
$startCount
1600 $this->callAPISuccess($entityName, 'delete', ['id' => $baoObj2->id
]);
1601 //make sure 1 less exists now
1602 $result = $this->callAPISuccess($entityName, 'getcount', [],
1603 ($createcount +
$startCount) - 1
1606 //make sure id #1 exists
1607 $result = $this->callAPISuccess($entityName, 'getcount', ['id' => $baoObj1->id
],
1610 //make sure id #2 desn't exist
1611 $result = $this->callAPISuccess($entityName, 'getcount', ['id' => $baoObj2->id
],
1617 * Create two entities and make sure delete action only deletes one!
1619 * @dataProvider entities_getfields
1622 public function testGetfieldsHasTitle($entity) {
1623 $entities = $this->getEntitiesSupportingCustomFields();
1624 if (in_array($entity, $entities)) {
1625 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entity . 'Test.php');
1627 $actions = $this->callAPISuccess($entity, 'getactions', []);
1628 foreach ($actions['values'] as $action) {
1629 if (substr($action, -7) == '_create' ||
substr($action, -4) == '_get' ||
substr($action, -7) == '_delete') {
1630 //getactions can't distinguish between contribution_page.create & contribution_page.create
1633 $fields = $this->callAPISuccess($entity, 'getfields', ['action' => $action]);
1634 if (!empty($ids) && in_array($action, ['create', 'get'])) {
1635 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $fields['values']);
1638 foreach ($fields['values'] as $fieldName => $fieldSpec) {
1639 $this->assertArrayHasKey('title', $fieldSpec, "no title for $entity - $fieldName on action $action");
1640 $this->assertNotEmpty($fieldSpec['title'], "empty title for $entity - $fieldName");
1644 $this->customFieldDelete($ids['custom_field_id']);
1645 $this->customGroupDelete($ids['custom_group_id']);
1652 public function getEntitiesSupportingCustomFields() {
1653 $entities = self
::custom_data_entities_get();
1654 $returnEntities = [];
1655 foreach ($entities as $entityArray) {
1656 $returnEntities[] = $entityArray[0];
1658 return $returnEntities;
1662 * @param string $entityName
1667 private function getMockableBAOObjects($entityName, $count = 2) {
1668 $baoString = _civicrm_api3_get_BAO($entityName);
1669 if (empty($baoString)) {
1670 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1675 while ($i < $count) {
1677 $baoObj = CRM_Core_DAO
::createTestObject($baoString, ['currency' => 'USD']);
1678 $this->assertTrue(is_int($baoObj->id
), 'check first id');
1679 $this->deletableTestObjects
[$baoString][] = $baoObj->id
;
1687 * Verify that HTML metacharacters provided as inputs appear consistently.
1690 * At time of writing, the encoding scheme requires (for example) that an
1691 * event title be partially-HTML-escaped before writing to DB. To provide
1692 * consistency, the API must perform extra encoding and decoding on some
1695 * In this example, the event 'title' is subject to encoding, but the
1696 * event 'description' is not.
1698 public function testEncodeDecodeConsistency() {
1700 $createResult = civicrm_api('Event', 'Create', [
1702 'title' => 'CiviCRM <> TheRest',
1703 'description' => 'TheRest <> CiviCRM',
1704 'event_type_id' => 1,
1706 'start_date' => 20081021,
1708 $this->assertAPISuccess($createResult);
1709 $eventId = $createResult['id'];
1710 $this->assertEquals('CiviCRM <> TheRest', $createResult['values'][$eventId]['title']);
1711 $this->assertEquals('TheRest <> CiviCRM', $createResult['values'][$eventId]['description']);
1713 // Verify "get" handles decoding in result value
1714 $getByIdResult = civicrm_api('Event', 'Get', [
1718 $this->assertAPISuccess($getByIdResult);
1719 $this->assertEquals('CiviCRM <> TheRest', $getByIdResult['values'][$eventId]['title']);
1720 $this->assertEquals('TheRest <> CiviCRM', $getByIdResult['values'][$eventId]['description']);
1722 // Verify "get" handles encoding in search value
1723 $getByTitleResult = civicrm_api('Event', 'Get', [
1725 'title' => 'CiviCRM <> TheRest',
1727 $this->assertAPISuccess($getByTitleResult);
1728 $this->assertEquals('CiviCRM <> TheRest', $getByTitleResult['values'][$eventId]['title']);
1729 $this->assertEquals('TheRest <> CiviCRM', $getByTitleResult['values'][$eventId]['description']);
1731 // Verify that "getSingle" handles decoding
1732 $getSingleResult = $this->callAPISuccess('Event', 'GetSingle', [
1736 $this->assertEquals('CiviCRM <> TheRest', $getSingleResult['title']);
1737 $this->assertEquals('TheRest <> CiviCRM', $getSingleResult['description']);
1739 // Verify that chaining handles decoding
1740 $chainResult = $this->callAPISuccess('Event', 'Get', [
1742 'api.event.get' => [],
1744 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['title']);
1745 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['description']);
1746 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['api.event.get']['values'][0]['title']);
1747 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['api.event.get']['values'][0]['description']);
1749 // Verify that "setvalue" handles encoding for updates
1750 $setValueTitleResult = civicrm_api('Event', 'setvalue', [
1754 'value' => 'setValueTitle: CiviCRM <> TheRest',
1756 $this->assertAPISuccess($setValueTitleResult);
1757 $this->assertEquals('setValueTitle: CiviCRM <> TheRest', $setValueTitleResult['values']['title']);
1758 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', [
1761 'field' => 'description',
1762 'value' => 'setValueDescription: TheRest <> CiviCRM',
1764 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1765 $this->assertEquals('setValueDescription: TheRest <> CiviCRM', $setValueDescriptionResult['values']['description']);
1769 * Verify that write operations (create/update) use partial HTML-encoding
1771 * In this example, the event 'title' is subject to encoding, but the
1772 * event 'description' is not.
1774 public function testEncodeWrite() {
1776 $createResult = civicrm_api('Event', 'Create', [
1778 'title' => 'createNew: CiviCRM <> TheRest',
1779 'description' => 'createNew: TheRest <> CiviCRM',
1780 'event_type_id' => 1,
1782 'start_date' => 20081021,
1784 $this->assertAPISuccess($createResult);
1785 $eventId = $createResult['id'];
1786 $this->assertDBQuery('createNew: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1787 1 => [$eventId, 'Integer'],
1789 $this->assertDBQuery('createNew: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1790 1 => [$eventId, 'Integer'],
1793 // Verify that "create" handles encoding for updates
1794 $createWithIdResult = civicrm_api('Event', 'Create', [
1797 'title' => 'createWithId: CiviCRM <> TheRest',
1798 'description' => 'createWithId: TheRest <> CiviCRM',
1800 $this->assertAPISuccess($createWithIdResult);
1801 $this->assertDBQuery('createWithId: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1802 1 => [$eventId, 'Integer'],
1804 $this->assertDBQuery('createWithId: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1805 1 => [$eventId, 'Integer'],
1808 // Verify that "setvalue" handles encoding for updates
1809 $setValueTitleResult = civicrm_api('Event', 'setvalue', [
1813 'value' => 'setValueTitle: CiviCRM <> TheRest',
1815 $this->assertAPISuccess($setValueTitleResult);
1816 $this->assertDBQuery('setValueTitle: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1817 1 => [$eventId, 'Integer'],
1819 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', [
1822 'field' => 'description',
1823 'value' => 'setValueDescription: TheRest <> CiviCRM',
1825 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1826 $this->assertAPISuccess($setValueDescriptionResult);
1827 $this->assertDBQuery('setValueDescription: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1828 1 => [$eventId, 'Integer'],