3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Test that the core actions for APIv3 entities comply with standard syntax+behavior.
31 * By default, this tests all API entities. To only test specific entities, call phpunit with
32 * environment variable SYNTAX_CONFORMANCE_ENTITIES, e.g.
34 * env SYNTAX_CONFORMANCE_ENTITIES="Contact Event" ./scripts/phpunit api_v3_SyntaxConformanceTest
36 * @package CiviCRM_APIv3
37 * @subpackage API_Core
40 class api_v3_SyntaxConformanceTest
extends CiviUnitTestCase
{
41 protected $_apiversion = 3;
44 * @var array e.g. $this->deletes['CRM_Contact_DAO_Contact'][] = $contactID;
46 protected $deletableTestObjects;
49 * This test case doesn't require DB reset.
51 public $DBResetRequired = FALSE;
56 * Map custom group entities to civicrm components.
58 static $componentMap = array(
59 'Contribution' => 'CiviContribute',
60 'Membership' => 'CiviMember',
61 'Participant' => 'CiviEvent',
62 'Event' => 'CiviEvent',
64 'Pledge' => 'CiviPledge',
65 'Grant' => 'CiviGrant',
66 'Campaign' => 'CiviCampaign',
67 'Survey' => 'CiviCampaign',
73 * There are two types of missing APIs:
74 * Those that are to be implemented
75 * (in some future version when someone steps in -hint hint-). List the entities in toBeImplemented[ {$action} ]
76 * Those that don't exist
77 * and that will never exist (eg an obsoleted Entity
78 * 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)
80 public function setUp() {
82 $this->enableCiviCampaign();
83 $this->toBeImplemented
['get'] = array(
84 'CxnApp', // CxnApp.get exists but relies on remote data outside our control; QA w/UtilsTest::testBasicArrayGet
96 $this->toBeImplemented
['create'] = array(
110 'SavedSearch', //work fine in local
113 $this->toBeImplemented
['delete'] = array(
126 $this->onlyIDNonZeroCount
['get'] = array(
133 $this->deprecatedAPI
= array('Location', 'ActivityType', 'SurveyRespondant');
134 $this->deletableTestObjects
= array();
137 public function tearDown() {
138 foreach ($this->deletableTestObjects
as $entityName => $entities) {
139 foreach ($entities as $entityID) {
140 CRM_Core_DAO
::deleteTestObjects($entityName, array('id' => $entityID));
146 * Generate list of all entities.
153 public static function entities($skip = array()) {
154 // The order of operations in here is screwy. In the case where SYNTAX_CONFORMANCE_ENTITIES is
155 // defined, we should be able to parse+return it immediately. However, some weird dependency
156 // crept into the system where civicrm_api('Entity','get') must be called as part of entities()
157 // (even if its return value is ignored).
159 $tmp = civicrm_api('Entity', 'Get', array('version' => 3));
160 if (getenv('SYNTAX_CONFORMANCE_ENTITIES')) {
162 'values' => explode(' ', getenv('SYNTAX_CONFORMANCE_ENTITIES')),
166 if (!is_array($skip)) {
169 $tmp = array_diff($tmp['values'], $skip);
171 foreach ($tmp as $e) {
172 $entities[] = array($e);
178 * Get list of entities for get test.
182 public static function entities_get() {
183 // all the entities, beside the ones flagged
184 return static::entities(static::toBeSkipped_get(TRUE));
188 * Get entities for create tests.
192 public static function entities_create() {
193 return static::entities(static::toBeSkipped_create(TRUE));
199 public static function entities_updatesingle() {
200 return static::entities(static::toBeSkipped_updatesingle(TRUE));
206 public static function entities_getlimit() {
207 return static::entities(static::toBeSkipped_getlimit());
211 * Generate list of entities that can be retrieved using SQL operator syntax.
215 public static function entities_getSqlOperators() {
216 return static::entities(static::toBeSkipped_getSqlOperators());
222 public static function entities_delete() {
223 return static::entities(static::toBeSkipped_delete(TRUE));
229 public static function entities_getfields() {
230 return static::entities(static::toBeSkipped_getfields(TRUE));
236 public static function custom_data_entities_get() {
237 return static::custom_data_entities();
243 public static function custom_data_entities() {
244 $entities = CRM_Core_BAO_CustomQuery
::$extendsMap;
245 $enabledComponents = Civi
::settings()->get('enable_components');
246 $customDataEntities = array();
247 $invalidEntities = array('Individual', 'Organization', 'Household');
248 $entitiesToFix = array('Case', 'Relationship');
249 foreach ($entities as $entityName => $entity) {
250 if (!in_array($entityName, $invalidEntities)
251 && !in_array($entityName, $entitiesToFix)
253 if (!empty(self
::$componentMap[$entityName]) && empty($enabledComponents[self
::$componentMap[$entityName]])) {
254 CRM_Core_BAO_ConfigSetting
::enableComponent(self
::$componentMap[$entityName]);
256 $customDataEntities[] = array($entityName);
259 return $customDataEntities;
263 * Add a smattering of entities that don't normally have custom data.
267 public static function custom_data_incl_non_std_entities_get() {
268 return static::entities(static::toBeSkipped_custom_data_creatable(TRUE));
272 * Get entities to be skipped on get tests.
274 * @param bool $sequential
278 public static function toBeSkipped_get($sequential = FALSE) {
279 $entitiesWithoutGet = array(
280 'MailingEventSubscribe',
281 'MailingEventConfirm',
282 'MailingEventResubscribe',
283 'MailingEventUnsubscribe',
286 if ($sequential === TRUE) {
287 return $entitiesWithoutGet;
290 foreach ($entitiesWithoutGet as $e) {
291 $entities[] = array($e);
297 * Get entities to be skipped for get call.
299 * Mailing Contact Just doesn't support id. We have always insisted on finding a way to
300 * support id in API but in this case the underlying tables are crying out for a restructure
301 * & it just doesn't make sense.
303 * User doesn't support get By ID because the user id is actually the CMS user ID & is not part of
304 * CiviCRM - so can only be tested through UserTest - not SyntaxConformanceTest.
306 * Entity doesn't support get By ID because it simply gives the result of string Entites in CiviCRM
308 * @param bool $sequential
311 * Entities that cannot be retrieved by ID
313 public static function toBeSkipped_getByID($sequential = FALSE) {
314 return array('MailingContact', 'User', 'Attachment', 'Entity');
318 * @param bool $sequential
322 public static function toBeSkipped_create($sequential = FALSE) {
323 $entitiesWithoutCreate = array('Constant', 'Entity', 'Location', 'Profile', 'MailingRecipients');
324 if ($sequential === TRUE) {
325 return $entitiesWithoutCreate;
328 foreach ($entitiesWithoutCreate as $e) {
329 $entities[] = array($e);
335 * @param bool $sequential
339 public static function toBeSkipped_delete($sequential = FALSE) {
340 $entitiesWithout = array(
342 'MailingEventConfirm',
343 'MailingEventResubscribe',
344 'MailingEventSubscribe',
345 'MailingEventUnsubscribe',
357 if ($sequential === TRUE) {
358 return $entitiesWithout;
361 foreach ($entitiesWithout as $e) {
362 $entities[] = array($e);
368 * @param bool $sequential
372 public static function toBeSkipped_custom_data_creatable($sequential = FALSE) {
373 $entitiesWithout = array(
383 'MailingEventConfirm',
384 'MailingEventResubscribe',
385 'MailingEventSubscribe',
386 'MailingEventUnsubscribe',
397 // ones that are not real entities hence not extendable.
421 if ($sequential === TRUE) {
422 return $entitiesWithout;
425 foreach ($entitiesWithout as $e) {
426 $entities[] = array($e);
432 * @param bool $sequential
435 * @todo add metadata for ALL these entities
437 public static function toBeSkipped_getfields($sequential = FALSE) {
438 $entitiesWithMetadataNotYetFixed = array('ReportTemplate', 'CustomSearch');
439 if ($sequential === TRUE) {
440 return $entitiesWithMetadataNotYetFixed;
443 foreach ($entitiesWithMetadataNotYetFixed as $e) {
444 $entities[] = array($e);
450 * Generate list of entities to test for get by id functions.
451 * @param bool $sequential
453 * Entities to be skipped
455 public static function toBeSkipped_automock($sequential = FALSE) {
456 $entitiesWithoutGet = array(
469 if ($sequential === TRUE) {
470 return $entitiesWithoutGet;
473 foreach ($entitiesWithoutGet as $e) {
474 $entities[] = array($e);
480 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
481 * @param bool $sequential
484 public static function toBeSkipped_updatesingle($sequential = FALSE) {
485 $entitiesWithout = array(
487 // pseudo-entity; testUpdateSingleValueAlter doesn't introspect properly on it. Multiple magic fields
489 'MailingEventUnsubscribe',
490 'MailingEventSubscribe',
509 'MailingEventConfirm',
514 'MailingEventResubscribe',
528 //skip this because it doesn't make sense to update logs,
531 if ($sequential === TRUE) {
532 return $entitiesWithout;
535 foreach ($entitiesWithout as $e) {
540 return array('pledge');
545 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
547 public static function toBeSkipped_getlimit() {
548 $entitiesWithout = array(
550 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
552 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
554 // failed 'check that a 5 limit returns 5' - probably is_template field is wrong or something, or could be limit doesn't work right
556 // can't handle creating 25
558 // fails on 5 limit - probably a set up problem
560 //a bit of a pseudoapi - keys by domain
562 return $entitiesWithout;
566 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
568 public static function toBeSkipped_getSqlOperators() {
569 $entitiesWithout = array(
570 'Case', //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
571 'Contact', // on the todo list!
572 'EntityTag', // non-standard api - has inappropriate mandatory fields & doesn't implement limit
573 'Extension', // can't handle creating 25
574 'Note', // note has a default get that isn't implemented in createTestObject -meaning you don't 'get' them
575 'Setting', //a bit of a pseudoapi - keys by domain
577 return $entitiesWithout;
586 public function getKnownUnworkablesUpdateSingle($entity, $key) {
587 // can't update values are values for which updates don't result in the value being changed
588 $knownFailures = array(
589 'ActionSchedule' => array(
590 'cant_update' => array(
594 'ActivityContact' => array(
595 'cant_update' => array(
597 //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
601 'cant_update' => array(
602 'state_province_id', //issues with country id - need to ensure same country
604 'master_id', //creates relationship
606 'cant_return' => ['street_parsing', 'skip_geocode', 'fix_address'],
609 'cant_update' => array(
610 'entity_table', // believe this field is defined in error
612 'cant_return' => array(
617 'cant_update' => array(
621 'Domain' => ['cant_update' => ['domain_version']],
622 'MembershipBlock' => array(
623 'cant_update' => array(
624 // The fake/auto-generated values leave us unable to properly cleanup fake data
629 'MailingJob' => ['cant_update' => ['parent_id']],
630 'ContributionSoft' => array(
631 'cant_update' => array(
632 // can't be changed through api
637 'cant_update' => array(
638 // This is being legitimately manipulated to always have a valid primary - skip.
642 'Navigation' => array(
643 'cant_update' => array(
644 // Weight is deliberately altered when this is changed - skip.
648 'LocationType' => array(
649 'cant_update' => array(
650 // I'm on the fence about whether the test should skip or the behaviour is wrong.
651 // display_name is set to match name if display_name is not provided. It would be more 'normal'
652 // to only calculate a default IF id is not set - but perhaps the current behaviour is kind
653 // of what someone updating the name expects..
658 'cant_update' => array(
659 'pledge_original_installment_amount',
661 'original_installment_amount',
663 'amount', // can't be changed through API,
665 'break_return' => array(// if these are passed in they are retrieved from the wrong table
668 'contribution_page_id',
669 'financial_account_id',
673 'cant_return' => array(// can't be retrieved from api
674 'honor_type_id', //due to uniquename missing
682 'initial_reminder_day',
683 'additional_reminder_day',
685 'pledge_contribution_page_id',
687 'pledge_campaign_id',
688 'pledge_financial_type_id',
691 'PaymentProcessorType' => array(
692 'cant_update' => array(
695 'break_return' => array(),
696 'cant_return' => array(),
698 'PriceFieldValue' => array(
699 'cant_update' => array(
700 'weight', //won't update as there is no 1 in the same price set
703 'ReportInstance' => array(
704 // View mode is part of the navigation which is not retrieved by the api.
705 'cant_return' => array('view_mode'),
707 'SavedSearch' => array(
708 // I think the fields below are generated based on form_values.
709 'cant_update' => array(
716 'StatusPreference' => array(
717 'break_return' => array(
722 // For better or worse triggers override.
723 'break_return' => ['run_time'],
724 'cant_update' => ['run_time'],
727 if (empty($knownFailures[$entity]) ||
empty($knownFailures[$entity][$key])) {
730 return $knownFailures[$entity][$key];
733 /* ----- testing the _get ----- */
736 * @dataProvider toBeSkipped_get
737 * Entities that don't need a get action
740 public function testNotImplemented_get($Entity) {
741 $result = civicrm_api($Entity, 'Get', array('version' => 3));
742 $this->assertEquals(1, $result['is_error']);
743 // $this->assertContains("API ($Entity, Get) does not exist", $result['error_message']);
744 $this->assertRegExp('/API (.*) does not exist/', $result['error_message']);
748 * @dataProvider entities
751 public function testWithoutParam_get($Entity) {
752 // should get php complaining that a param is missing
754 $result = civicrm_api($Entity, 'Get');
755 $this->fail('Expected an exception. No exception was thrown.');
757 // As of php7.1 a new Exception is thrown by PHP ArgumentCountError when not enough params are passed.
758 catch (ArgumentCountError
$e) {
761 catch (PHPUnit_Framework_Error
$e) {
767 * @dataProvider entities
770 public function testGetFields($Entity) {
771 if (in_array($Entity, $this->deprecatedAPI
) ||
$Entity == 'Entity' ||
$Entity == 'CustomValue') {
775 $result = civicrm_api($Entity, 'getfields', array('version' => 3));
776 $this->assertTrue(is_array($result['values']), "$Entity ::get fields doesn't return values array in line " . __LINE__
);
777 foreach ($result['values'] as $key => $value) {
778 $this->assertTrue(is_array($value), $Entity . "::" . $key . " is not an array in line " . __LINE__
);
783 * @dataProvider entities_get
786 public function testEmptyParam_get($Entity) {
788 if (in_array($Entity, $this->toBeImplemented
['get'])) {
789 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
792 $result = civicrm_api($Entity, 'Get', array());
793 $this->assertEquals(1, $result['is_error']);
794 $this->assertContains("Unknown api version", $result['error_message']);
798 * @dataProvider entities_get
801 public function testEmptyParam_getString($Entity) {
803 if (in_array($Entity, $this->toBeImplemented
['get'])) {
804 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
807 $result = $this->callAPIFailure($Entity, 'Get', 'string');
808 $this->assertEquals(2000, $result['error_code']);
809 $this->assertEquals('Input variable `params` is not an array', $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', array('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 $this->quickCleanup(array('civicrm_uf_match'));
842 $this->createLoggedInUser();// so subsidiary activities are created
844 $entitiesWithNamingIssues = [
845 'MailingComponent' => 'Component',
846 'SmsProvider' => 'Provider',
847 'AclRole' => 'EntityRole',
848 'MailingEventQueue' => 'Queue',
851 $usableName = !empty($entitiesWithNamingIssues[$entityName]) ?
$entitiesWithNamingIssues[$entityName] : $entityName;
852 $optionName = CRM_Core_DAO_AllCoreTables
::getTableForClass(CRM_Core_DAO_AllCoreTables
::getFullName($usableName));
854 if (!isset(CRM_Core_BAO_CustomQuery
::$extendsMap[$entityName])) {
855 $createdValue = $this->callAPISuccess('OptionValue', 'create', [
856 'option_group_id' => 'cg_extend_objects',
857 'label' => $usableName,
858 'value' => $usableName,
859 'name' => $optionName,
862 // We are not passing 'check_permissions' so the the more limited permissions *should* be
863 // ignored but per CRM-17700 there is a history of custom data applying permissions when it shouldn't.
864 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM', 'view my contact');
865 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $usableName . 'Test.php');
866 $customFieldName = 'custom_' . $ids['custom_field_id'];
867 $objects = $this->getMockableBAOObjects($entityName, 1);
868 $params = array('id' => $objects[0]->id
, 'custom_' . $ids['custom_field_id'] => "custom string");
869 $result = $this->callAPISuccess($entityName, 'create', $params);
871 $this->assertTrue(isset($result['id']), 'no id on ' . $entityName);
872 $getParams = array('id' => $result['id'], 'return' => array($customFieldName));
873 $check = $this->callAPISuccess($entityName, 'get', $getParams);
874 $this->assertTrue(!empty($check['values'][$check['id']][$customFieldName]), 'Custom data not present for ' . $entityName);
875 $this->assertEquals("custom string", $check['values'][$check['id']][$customFieldName], 'Custom data not present for ' . $entityName);
877 $this->customFieldDelete($ids['custom_field_id']);
878 $this->customGroupDelete($ids['custom_group_id']);
879 $this->callAPISuccess($entityName, 'delete', array('id' => $result['id']));
880 $this->quickCleanup(array('civicrm_uf_match'));
881 if (!empty($createdValue)) {
882 $this->callAPISuccess('OptionValue', 'delete', ['id' => $createdValue['id']]);
887 * @dataProvider entities_get
890 public function testAcceptsOnlyID_get($Entity) {
891 // big random number. fun fact: if you multiply it by pi^e, the result is another random number, but bigger ;)
892 $nonExistantID = 30867307034;
893 if (in_array($Entity, $this->toBeImplemented
['get'])
894 ||
in_array($Entity, $this->toBeSkipped_getByID())
900 // the below function returns different values and hence an early return
901 // we'll fix this once beta1 is released
904 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
906 if ($result['is_error']) {
907 // just to get a clearer message in the log
908 $this->assertEquals("only id should be enough", $result['error_message']);
910 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
911 $this->assertEquals(0, $result['count']);
916 * Create two entities and make sure we can fetch them individually by ID.
918 * @dataProvider entities_get
920 * limitations include the problem with avoiding loops when creating test objects -
921 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
922 * Currency - only seems to support US
925 public function testByID_get($entityName) {
926 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
927 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
931 $baos = $this->getMockableBAOObjects($entityName);
932 list($baoObj1, $baoObj2) = $baos;
935 $result = $this->callAPISuccess($entityName, 'get', array(
936 'id' => $baoObj1->id
,
939 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
940 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
941 $this->assertEquals(1, count($result['values']));
943 // fetch second by ID
944 $result = $this->callAPISuccess($entityName, 'get', array(
945 'id' => $baoObj2->id
,
947 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
948 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
949 $this->assertEquals(1, count($result['values']));
953 * Ensure that the "get" operation accepts limiting the #result records.
955 * TODO Consider making a separate entity list ("entities_getlimit")
956 * For the moment, the "entities_updatesingle" list should give a good
957 * sense for which entities support createTestObject
959 * @dataProvider entities_getlimit
961 * @param string $entityName
963 public function testLimit($entityName) {
964 $cases = array(); // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
966 array('options' => array('limit' => NULL)),
968 'check that a NULL limit returns unlimited',
971 array('options' => array('limit' => FALSE)),
973 'check that a FALSE limit returns unlimited',
976 array('options' => array('limit' => 0)),
978 'check that a 0 limit returns unlimited',
981 array('options' => array('limit' => 5)),
983 'check that a 5 limit returns 5',
988 'check that no limit returns 25',
991 $baoString = _civicrm_api3_get_BAO($entityName);
992 if (empty($baoString)) {
993 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
997 // make 30 test items -- 30 > 25 (the default limit)
999 for ($i = 0; $i < 30; $i++
) {
1000 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1001 $ids[] = $baoObj->id
;
1005 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
1006 foreach ($cases as $case) {
1007 $this->checkLimitAgainstExpected($entityName, $case[0], $case[1], $case[2]);
1009 //non preferred / legacy syntax
1010 if (isset($case[0]['options']['limit'])) {
1011 $this->checkLimitAgainstExpected($entityName, array('rowCount' => $case[0]['options']['limit']), $case[1], $case[2]);
1012 $this->checkLimitAgainstExpected($entityName, array('option_limit' => $case[0]['options']['limit']), $case[1], $case[2]);
1013 $this->checkLimitAgainstExpected($entityName, array('option.limit' => $case[0]['options']['limit']), $case[1], $case[2]);
1016 foreach ($ids as $id) {
1017 CRM_Core_DAO
::deleteTestObjects($baoString, array('id' => $id));
1023 * Ensure that the "get" operation accepts limiting the #result records.
1025 * @dataProvider entities_getSqlOperators
1027 * @param string $entityName
1029 public function testSqlOperators($entityName) {
1030 $toBeIgnored = array_merge($this->toBeImplemented
['get'],
1031 $this->deprecatedAPI
,
1032 $this->toBeSkipped_get(TRUE),
1033 $this->toBeSkipped_getByID()
1035 if (in_array($entityName, $toBeIgnored)) {
1039 $baoString = _civicrm_api3_get_BAO($entityName);
1041 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0), 'return' => 'id'));
1042 $entities = array_keys($entities['values']);
1043 $totalEntities = count($entities);
1044 if ($totalEntities < 3) {
1046 for ($i = 0; $i < 3 - $totalEntities; $i++
) {
1047 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1048 $ids[] = $baoObj->id
;
1053 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0)));
1054 $entities = array_keys($entities['values']);
1055 $this->assertGreaterThan(2, $totalEntities);
1056 $this->callAPISuccess($entityName, 'getsingle', array('id' => array('IN' => array($entities[0]))));
1057 $this->callAPISuccessGetCount($entityName, array('id' => array('NOT IN' => array($entities[0]))), $totalEntities - 1);
1058 $this->callAPISuccessGetCount($entityName, array('id' => array('>' => $entities[0])), $totalEntities - 1);
1062 * Check that get fetches an appropriate number of results.
1064 * @param string $entityName
1065 * Name of entity to test.
1066 * @param array $params
1068 * @param string $message
1070 public function checkLimitAgainstExpected($entityName, $params, $limit, $message) {
1071 $result = $this->callAPISuccess($entityName, 'get', $params);
1073 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
1074 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
1077 $this->assertEquals($limit, $result['count'], $message);
1078 $this->assertEquals($limit, count($result['values']), $message);
1083 * Create two entities and make sure we can fetch them individually by ID (e.g. using "contact_id=>2"
1086 * @dataProvider entities_get
1088 * limitations include the problem with avoiding loops when creating test objects -
1089 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1090 * Currency - only seems to support US
1091 * @param $entityName
1092 * @throws \PHPUnit_Framework_IncompleteTestError
1094 public function testByIDAlias_get($entityName) {
1095 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1096 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1100 $baoString = _civicrm_api3_get_BAO($entityName);
1101 if (empty($baoString)) {
1102 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1106 $idFieldName = _civicrm_api_get_entity_name_from_camel($entityName) . '_id';
1109 $baoObj1 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1110 $this->assertTrue(is_int($baoObj1->id
), 'check first id');
1111 $this->deletableTestObjects
[$baoString][] = $baoObj1->id
;
1112 $baoObj2 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1113 $this->assertTrue(is_int($baoObj2->id
), 'check second id');
1114 $this->deletableTestObjects
[$baoString][] = $baoObj2->id
;
1116 // fetch first by ID
1117 $result = civicrm_api($entityName, 'get', array(
1119 $idFieldName => $baoObj1->id
,
1121 $this->assertAPISuccess($result);
1122 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
1123 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
1124 $this->assertEquals(1, count($result['values']));
1126 // fetch second by ID
1127 $result = civicrm_api($entityName, 'get', array(
1129 $idFieldName => $baoObj2->id
,
1131 $this->assertAPISuccess($result);
1132 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
1133 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
1134 $this->assertEquals(1, count($result['values']));
1138 * @dataProvider entities_get
1141 public function testNonExistantID_get($Entity) {
1142 // cf testAcceptsOnlyID_get
1143 $nonExistantID = 30867307034;
1144 if (in_array($Entity, $this->toBeImplemented
['get'])) {
1148 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
1150 // redundant with testAcceptsOnlyID_get
1151 if ($result['is_error']) {
1155 $this->assertArrayHasKey('version', $result);
1156 $this->assertEquals(3, $result['version']);
1157 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
1158 $this->assertEquals(0, $result['count']);
1162 /* ---- testing the _create ---- */
1165 * @dataProvider toBeSkipped_create
1166 entities that don't need a create action
1169 public function testNotImplemented_create($Entity) {
1170 $result = civicrm_api($Entity, 'Create', array('version' => 3));
1171 $this->assertEquals(1, $result['is_error']);
1172 $this->assertContains(strtolower("API ($Entity, Create) does not exist"), strtolower($result['error_message']));
1176 * @dataProvider entities
1177 * @expectedException CiviCRM_API3_Exception
1180 public function testWithoutParam_create($Entity) {
1181 if ($Entity === 'Setting') {
1182 $this->markTestSkipped('It seems OK for setting to skip here as it silently sips invalid params');
1184 elseif ($Entity === 'Mailing') {
1185 $this->markTestSkipped('It seems OK for "Mailing" to skip here because you can create empty drafts');
1187 // should create php complaining that a param is missing
1188 civicrm_api3($Entity, 'Create');
1192 * @dataProvider entities_create
1194 * Check that create doesn't work with an invalid
1196 * @throws \PHPUnit_Framework_IncompleteTestError
1198 public function testInvalidSort_get($Entity) {
1199 $invalidEntitys = array('ActivityType', 'Setting', 'System');
1200 if (in_array($Entity, $invalidEntitys)) {
1201 $this->markTestSkipped('It seems OK for ' . $Entity . ' to skip here as it silently sips invalid params');
1203 $result = $this->callAPIFailure($Entity, 'get', array('options' => array('sort' => 'sleep(1)')));
1207 * @dataProvider entities_create
1209 * Check that create doesn't work with an invalid
1211 * @throws \PHPUnit_Framework_IncompleteTestError
1213 public function testValidSortSingleArrayById_get($Entity) {
1214 $invalidEntitys = array('ActivityType', 'Setting', 'System');
1217 'id desc' => '_id desc',
1218 'id DESC' => '_id DESC',
1219 'id ASC' => '_id ASC',
1220 'id asc' => '_id asc');
1221 foreach ($tests as $test => $expected) {
1222 if (in_array($Entity, $invalidEntitys)) {
1223 $this->markTestSkipped('It seems OK for ' . $Entity . ' to skip here as it silently ignores passed in params');
1225 $params = array('sort' => array($test));
1226 $result = _civicrm_api3_get_options_from_params($params, FALSE, $Entity, 'get');
1227 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($Entity);
1228 $this->assertEquals($lowercase_entity . $expected, $result['sort']);
1233 * @dataProvider entities_create
1235 * Check that create doesn't work with an invalid
1237 * @throws \PHPUnit_Framework_IncompleteTestError
1239 public function testInvalidID_create($Entity) {
1240 // turn test off for noew
1241 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1243 if (in_array($Entity, $this->toBeImplemented
['create'])) {
1244 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1247 $result = $this->callAPIFailure($Entity, 'Create', array('id' => 999));
1251 * @dataProvider entities
1253 public function testCreateWrongTypeParamTag_create() {
1254 $result = civicrm_api("Tag", 'Create', 'this is not a string');
1255 $this->assertEquals(1, $result['is_error']);
1256 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1260 * @dataProvider entities_updatesingle
1262 * limitations include the problem with avoiding loops when creating test objects -
1263 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1264 * Currency - only seems to support US
1265 * @param $entityName
1267 public function testCreateSingleValueAlter($entityName) {
1268 if (in_array($entityName, $this->toBeImplemented
['create'])) {
1269 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1273 $baoString = _civicrm_api3_get_BAO($entityName);
1274 $this->assertNotEmpty($baoString, $entityName);
1275 $this->assertNotEmpty($entityName, $entityName);
1276 $fieldsGet = $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'get', 'options' => array('get_options' => 'all')));
1277 if ($entityName != 'Pledge') {
1278 $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'create', 'options' => array('get_options' => 'all')));
1280 $fields = $fields['values'];
1281 $return = array_keys($fieldsGet['values']);
1282 $valuesNotToReturn = $this->getKnownUnworkablesUpdateSingle($entityName, 'break_return');
1283 // these can't be requested as return values
1284 $entityValuesThatDoNotWork = array_merge(
1285 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_update'),
1286 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_return'),
1290 $return = array_diff($return, $valuesNotToReturn);
1291 $baoObj = new CRM_Core_DAO();
1292 $baoObj->createTestObject($baoString, array('currency' => 'USD'), 2, 0);
1294 $getEntities = $this->callAPISuccess($entityName, 'get', array(
1296 'return' => $return,
1298 'sort' => 'id DESC',
1303 // lets use first rather than assume only one exists
1304 $entity = $getEntities['values'][0];
1305 $entity2 = $getEntities['values'][1];
1306 $this->deletableTestObjects
[$baoString][] = $entity['id'];
1307 $this->deletableTestObjects
[$baoString][] = $entity2['id'];
1308 // Skip these fields that we never really expect to update well.
1309 $genericFieldsToSkip = ['currency', 'id', strtolower($entityName) . '_id', 'is_primary'];
1310 foreach ($fields as $field => $specs) {
1312 $fieldName = $field;
1314 if (in_array($field, $genericFieldsToSkip)
1315 ||
in_array($field, $entityValuesThatDoNotWork)
1317 //@todo id & entity_id are correct but we should fix currency & frequency_day
1320 $this->assertArrayHasKey('type', $specs, "the _spec function for $entityName field $field does not specify the type");
1321 switch ($specs['type']) {
1322 case CRM_Utils_Type
::T_DATE
:
1323 $entity[$fieldName] = '2012-05-20';
1326 case CRM_Utils_Type
::T_TIMESTAMP
:
1328 $entity[$fieldName] = '2012-05-20 03:05:20';
1331 case CRM_Utils_Type
::T_STRING
:
1332 case CRM_Utils_Type
::T_BLOB
:
1333 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1334 case CRM_Utils_Type
::T_TEXT
:
1335 case CRM_Utils_Type
::T_LONGTEXT
:
1336 case CRM_Utils_Type
::T_EMAIL
:
1337 if ($fieldName == 'form_values' && $entityName == 'SavedSearch') {
1338 // This is a hack for the SavedSearch API.
1339 // It expects form_values to be an array.
1340 // If you want to fix this, you should definitely read this forum
1342 // http://forum.civicrm.org/index.php/topic,33990.0.html
1343 // See also my question on the CiviCRM Stack Exchange:
1344 // https://civicrm.stackexchange.com/questions/3437
1345 $entity[$fieldName] = array('sort_name' => "SortName2");
1348 $entity[$fieldName] = substr('New String', 0, CRM_Utils_Array
::Value('maxlength', $specs, 100));
1349 if ($fieldName == 'email') {
1350 $entity[$fieldName] = strtolower($entity[$fieldName]);
1352 // typecast with array to satisfy changes made in CRM-13160
1353 if ($entityName == 'MembershipType' && in_array($fieldName, array(
1354 'relationship_type_id',
1355 'relationship_direction',
1358 $entity[$fieldName] = (array) $entity[$fieldName];
1363 case CRM_Utils_Type
::T_INT
:
1364 // probably created with a 1
1365 if ($fieldName == 'weight') {
1366 $entity[$fieldName] = 2;
1368 elseif (!empty($specs['FKClassName'])) {
1369 if ($specs['FKClassName'] == $baoString) {
1370 $entity[$fieldName] = (string) $entity2['id'];
1373 if (!empty($entity[$fieldName])) {
1374 $resetFKTo = array($fieldName => $entity[$fieldName]);
1376 $entity[$fieldName] = (string) empty($entity2[$field]) ?
'' : $entity2[$field];
1377 //todo - there isn't always something set here - & our checking on unset values is limited
1378 if (empty($entity[$field])) {
1379 unset($entity[$field]);
1384 $entity[$fieldName] = '6';
1388 case CRM_Utils_Type
::T_BOOLEAN
:
1389 // probably created with a 1
1390 $entity[$fieldName] = '0';
1393 case CRM_Utils_Type
::T_FLOAT
:
1394 case CRM_Utils_Type
::T_MONEY
:
1395 $entity[$field] = '22.75';
1398 case CRM_Utils_Type
::T_URL
:
1399 $entity[$field] = 'warm.beer.com';
1401 if (empty($specs['FKClassName']) && (!empty($specs['pseudoconstant']) ||
!empty($specs['options']))) {
1402 $options = CRM_Utils_Array
::value('options', $specs, array());
1404 //eg. pdf_format id doesn't ship with any
1405 if (isset($specs['pseudoconstant']['optionGroupName'])) {
1406 $optionValue = $this->callAPISuccess('option_value', 'create', array(
1407 'option_group_id' => $specs['pseudoconstant']['optionGroupName'],
1408 'label' => 'new option value',
1411 $optionValue = $optionValue['values'];
1412 $keyColumn = CRM_Utils_Array
::value('keyColumn', $specs['pseudoconstant'], 'value');
1413 $options[$optionValue[0][$keyColumn]] = 'new option value';
1416 $entity[$field] = array_rand($options);
1418 if (!empty($specs['FKClassName']) && !empty($specs['pseudoconstant'])) {
1419 // in the weird situation where a field has both an fk and pseudoconstant defined,
1420 // e.g. campaign_id field, need to flush caches.
1421 // FIXME: Why doesn't creating a campaign clear caches?
1422 civicrm_api3($entityName, 'getfields', array('cache_clear' => 1));
1424 $updateParams = array(
1425 'id' => $entity['id'],
1426 $field => isset($entity[$field]) ?
$entity[$field] : NULL,
1428 if (!empty($specs['serialize'])) {
1429 $updateParams[$field] = $entity[$field] = (array) $specs['serialize'];
1431 if (isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1432 //api has special handling on these 2 fields for backward compatibility reasons
1433 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1435 if (isset($updateParams['next_sched_contribution_date']) && in_array($entityName, array('ContributionRecur'))) {
1436 //api has special handling on these 2 fields for backward compatibility reasons
1437 $entity['next_sched_contribution'] = $updateParams['next_sched_contribution_date'];
1439 if (isset($updateParams['image'])) {
1440 // Image field is passed through simplifyURL function so may be different, do the same here for comparison
1441 $entity['image'] = CRM_Utils_String
::simplifyURL($updateParams['image'], TRUE);
1443 if (isset($updateParams['thumbnail'])) {
1444 // Thumbnail field is passed through simplifyURL function so may be different, do the same here for comparison
1445 $entity['thumbnail'] = CRM_Utils_String
::simplifyURL($updateParams['thumbnail'], TRUE);
1448 $update = $this->callAPISuccess($entityName, 'create', $updateParams);
1449 $checkParams = array(
1450 'id' => $entity['id'],
1452 'return' => $return,
1454 'sort' => 'id DESC',
1459 $checkEntity = $this->callAPISuccess($entityName, 'getsingle', $checkParams);
1460 if (!empty($specs['serialize']) && !is_array($checkEntity[$field])) {
1461 // Put into serialized format for comparison if 'get' has not returned serialized.
1462 $entity[$field] = CRM_Core_DAO
::serializeField($checkEntity[$field], $specs['serialize']);
1465 $this->assertAPIArrayComparison($entity, $checkEntity, array(), "checking if $fieldName was correctly updated\n" . print_r(array(
1466 'update-params' => $updateParams,
1467 'update-result' => $update,
1468 'getsingle-params' => $checkParams,
1469 'getsingle-result' => $checkEntity,
1470 'expected entity' => $entity,
1473 //reset the foreign key fields because otherwise our cleanup routine fails & some other unexpected stuff can kick in
1474 $entity = array_merge($entity, $resetFKTo);
1475 $updateParams = array_merge($updateParams, $resetFKTo);
1476 $this->callAPISuccess($entityName, 'create', $updateParams);
1477 if (isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1478 //api has special handling on these 2 fields for backward compatibility reasons
1479 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1481 if (isset($updateParams['next_sched_contribution_date']) && in_array($entityName, array('ContributionRecur'))) {
1482 //api has special handling on these 2 fields for backward compatibility reasons
1483 $entity['next_sched_contribution'] = $updateParams['next_sched_contribution_date'];
1490 /* ---- testing the _getFields ---- */
1492 /* ---- testing the _delete ---- */
1495 * @dataProvider toBeSkipped_delete
1496 entities that don't need a delete action
1499 public function testNotImplemented_delete($Entity) {
1500 $nonExistantID = 151416349;
1501 $result = civicrm_api($Entity, 'Delete', array('version' => 3, 'id' => $nonExistantID));
1502 $this->assertEquals(1, $result['is_error']);
1503 $this->assertContains(strtolower("API ($Entity, Delete) does not exist"), strtolower($result['error_message']));
1507 * @dataProvider entities
1510 public function testWithoutParam_delete($Entity) {
1511 // should delete php complaining that a param is missing
1513 $result = civicrm_api($Entity, 'Delete');
1514 $this->fail('Expected an exception. No exception was thrown.');
1516 // As of php7.1 a new Exception is thrown by PHP ArgumentCountError when not enough params are passed.
1517 catch (ArgumentCountError
$e) {
1520 catch (PHPUnit_Framework_Error
$e) {
1526 * @dataProvider entities_delete
1529 public function testEmptyParam_delete($Entity) {
1530 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1531 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1534 $result = civicrm_api($Entity, 'Delete', array());
1535 $this->assertEquals(1, $result['is_error']);
1536 $this->assertContains("Unknown api version", $result['error_message']);
1540 * @dataProvider entities_delete
1542 * @throws \PHPUnit_Framework_IncompleteTestError
1544 public function testInvalidID_delete($Entity) {
1545 $result = $this->callAPIFailure($Entity, 'Delete', array('id' => 999999));
1549 * @dataProvider entities
1551 public function testDeleteWrongTypeParamTag_delete() {
1552 $result = civicrm_api("Tag", 'Delete', 'this is not a string');
1553 $this->assertEquals(1, $result['is_error']);
1554 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1558 * Create two entities and make sure delete action only deletes one!
1560 * @dataProvider entities_delete
1562 * limitations include the problem with avoiding loops when creating test objects -
1563 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1564 * Currency - only seems to support US
1565 * @param $entityName
1566 * @throws \PHPUnit_Framework_IncompleteTestError
1568 public function testByID_delete($entityName) {
1569 // turn test off for noew
1570 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1573 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1574 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1577 $startCount = $this->callAPISuccess($entityName, 'getcount', array());
1579 $baos = $this->getMockableBAOObjects($entityName, $createcount);
1580 list($baoObj1, $baoObj2) = $baos;
1582 // make sure exactly 2 exist
1583 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1584 $createcount +
$startCount
1587 $this->callAPISuccess($entityName, 'delete', array('id' => $baoObj2->id
));
1588 //make sure 1 less exists now
1589 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1590 ($createcount +
$startCount) - 1
1593 //make sure id #1 exists
1594 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj1->id
),
1597 //make sure id #2 desn't exist
1598 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj2->id
),
1604 * Create two entities and make sure delete action only deletes one!
1606 * @dataProvider entities_getfields
1609 public function testGetfieldsHasTitle($entity) {
1610 $entities = $this->getEntitiesSupportingCustomFields();
1611 if (in_array($entity, $entities)) {
1612 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entity . 'Test.php');
1614 $actions = $this->callAPISuccess($entity, 'getactions', array());
1615 foreach ($actions['values'] as $action) {
1616 if (substr($action, -7) == '_create' ||
substr($action, -4) == '_get' ||
substr($action, -7) == '_delete') {
1617 //getactions can't distinguish between contribution_page.create & contribution_page.create
1620 $fields = $this->callAPISuccess($entity, 'getfields', array('action' => $action));
1621 if (!empty($ids) && in_array($action, array('create', 'get'))) {
1622 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $fields['values']);
1625 foreach ($fields['values'] as $fieldName => $fieldSpec) {
1626 $this->assertArrayHasKey('title', $fieldSpec, "no title for $entity - $fieldName on action $action");
1627 $this->assertNotEmpty($fieldSpec['title'], "empty title for $entity - $fieldName");
1631 $this->customFieldDelete($ids['custom_field_id']);
1632 $this->customGroupDelete($ids['custom_group_id']);
1639 public function getEntitiesSupportingCustomFields() {
1640 $entities = self
::custom_data_entities_get();
1641 $returnEntities = array();
1642 foreach ($entities as $entityArray) {
1643 $returnEntities[] = $entityArray[0];
1645 return $returnEntities;
1649 * @param string $entityName
1654 private function getMockableBAOObjects($entityName, $count = 2) {
1655 $baoString = _civicrm_api3_get_BAO($entityName);
1656 if (empty($baoString)) {
1657 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1662 while ($i < $count) {
1664 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1665 $this->assertTrue(is_int($baoObj->id
), 'check first id');
1666 $this->deletableTestObjects
[$baoString][] = $baoObj->id
;
1674 * Verify that HTML metacharacters provided as inputs appear consistently.
1677 * At time of writing, the encoding scheme requires (for example) that an
1678 * event title be partially-HTML-escaped before writing to DB. To provide
1679 * consistency, the API must perform extra encoding and decoding on some
1682 * In this example, the event 'title' is subject to encoding, but the
1683 * event 'description' is not.
1685 public function testEncodeDecodeConsistency() {
1687 $createResult = civicrm_api('Event', 'Create', array(
1689 'title' => 'CiviCRM <> TheRest',
1690 'description' => 'TheRest <> CiviCRM',
1691 'event_type_id' => 1,
1693 'start_date' => 20081021,
1695 $this->assertAPISuccess($createResult);
1696 $eventId = $createResult['id'];
1697 $this->assertEquals('CiviCRM <> TheRest', $createResult['values'][$eventId]['title']);
1698 $this->assertEquals('TheRest <> CiviCRM', $createResult['values'][$eventId]['description']);
1700 // Verify "get" handles decoding in result value
1701 $getByIdResult = civicrm_api('Event', 'Get', array(
1705 $this->assertAPISuccess($getByIdResult);
1706 $this->assertEquals('CiviCRM <> TheRest', $getByIdResult['values'][$eventId]['title']);
1707 $this->assertEquals('TheRest <> CiviCRM', $getByIdResult['values'][$eventId]['description']);
1709 // Verify "get" handles encoding in search value
1710 $getByTitleResult = civicrm_api('Event', 'Get', array(
1712 'title' => 'CiviCRM <> TheRest',
1714 $this->assertAPISuccess($getByTitleResult);
1715 $this->assertEquals('CiviCRM <> TheRest', $getByTitleResult['values'][$eventId]['title']);
1716 $this->assertEquals('TheRest <> CiviCRM', $getByTitleResult['values'][$eventId]['description']);
1718 // Verify that "getSingle" handles decoding
1719 $getSingleResult = $this->callAPISuccess('Event', 'GetSingle', array(
1723 $this->assertEquals('CiviCRM <> TheRest', $getSingleResult['title']);
1724 $this->assertEquals('TheRest <> CiviCRM', $getSingleResult['description']);
1726 // Verify that chaining handles decoding
1727 $chainResult = $this->callAPISuccess('Event', 'Get', array(
1729 'api.event.get' => array(),
1731 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['title']);
1732 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['description']);
1733 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['api.event.get']['values'][0]['title']);
1734 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['api.event.get']['values'][0]['description']);
1736 // Verify that "setvalue" handles encoding for updates
1737 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1741 'value' => 'setValueTitle: CiviCRM <> TheRest',
1743 $this->assertAPISuccess($setValueTitleResult);
1744 $this->assertEquals('setValueTitle: CiviCRM <> TheRest', $setValueTitleResult['values']['title']);
1745 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1748 'field' => 'description',
1749 'value' => 'setValueDescription: TheRest <> CiviCRM',
1751 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1752 $this->assertEquals('setValueDescription: TheRest <> CiviCRM', $setValueDescriptionResult['values']['description']);
1756 * Verify that write operations (create/update) use partial HTML-encoding
1758 * In this example, the event 'title' is subject to encoding, but the
1759 * event 'description' is not.
1761 public function testEncodeWrite() {
1763 $createResult = civicrm_api('Event', 'Create', array(
1765 'title' => 'createNew: CiviCRM <> TheRest',
1766 'description' => 'createNew: TheRest <> CiviCRM',
1767 'event_type_id' => 1,
1769 'start_date' => 20081021,
1771 $this->assertAPISuccess($createResult);
1772 $eventId = $createResult['id'];
1773 $this->assertDBQuery('createNew: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1774 1 => array($eventId, 'Integer'),
1776 $this->assertDBQuery('createNew: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1777 1 => array($eventId, 'Integer'),
1780 // Verify that "create" handles encoding for updates
1781 $createWithIdResult = civicrm_api('Event', 'Create', array(
1784 'title' => 'createWithId: CiviCRM <> TheRest',
1785 'description' => 'createWithId: TheRest <> CiviCRM',
1787 $this->assertAPISuccess($createWithIdResult);
1788 $this->assertDBQuery('createWithId: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1789 1 => array($eventId, 'Integer'),
1791 $this->assertDBQuery('createWithId: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1792 1 => array($eventId, 'Integer'),
1795 // Verify that "setvalue" handles encoding for updates
1796 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1800 'value' => 'setValueTitle: CiviCRM <> TheRest',
1802 $this->assertAPISuccess($setValueTitleResult);
1803 $this->assertDBQuery('setValueTitle: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1804 1 => array($eventId, 'Integer'),
1806 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1809 'field' => 'description',
1810 'value' => 'setValueDescription: TheRest <> CiviCRM',
1812 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1813 $this->assertAPISuccess($setValueDescriptionResult);
1814 $this->assertDBQuery('setValueDescription: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1815 1 => array($eventId, 'Integer'),