3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
28 require_once 'CiviTest/CiviUnitTestCase.php';
32 * Test that the core actions for APIv3 entities comply with standard syntax+behavior.
34 * By default, this tests all API entities. To only test specific entities, call phpunit with
35 * environment variable SYNTAX_CONFORMANCE_ENTITIES, e.g.
37 * env SYNTAX_CONFORMANCE_ENTITIES="Contact Event" ./scripts/phpunit api_v3_SyntaxConformanceTest
39 * @package CiviCRM_APIv3
40 * @subpackage API_Core
43 class api_v3_SyntaxConformanceTest
extends CiviUnitTestCase
{
44 protected $_apiversion = 3;
47 * @var array e.g. $this->deletes['CRM_Contact_DAO_Contact'][] = $contactID;
49 protected $deletableTestObjects;
51 /** This test case doesn't require DB reset */
52 public $DBResetRequired = FALSE;
56 /** Map custom group entities to civicrm components */
57 static $componentMap = array(
61 'Organization' => NULL,
62 'Contribution' => 'CiviContribute',
63 'Membership' => 'CiviMember',
64 'Participant' => 'CiviEvent',
66 'Relationship' => NULL,
67 'Event' => 'CiviEvent',
70 'Pledge' => 'CiviPledge',
71 'Grant' => 'CiviGrant',
75 /* they are two types of missing APIs:
76 - Those that are to be implemented
77 (in some future version when someone steps in -hint hint-). List the entities in toBeImplemented[ {$action} ]
78 Those that don't exist
79 and that will never exist (eg an obsoleted Entity
80 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)
84 $this->enableCiviCampaign();
85 $this->toBeImplemented
['get'] = array('Profile', 'CustomValue', 'Constant', 'CustomSearch', 'Extension', 'ReportTemplate', 'System', 'Setting');
86 $this->toBeImplemented
['create'] = array('SurveyRespondant', 'OptionGroup', 'MailingRecipients', 'UFMatch', 'LocationType', 'CustomSearch', 'Extension', 'ReportTemplate', 'System');
87 $this->toBeImplemented
['delete'] = array('MembershipPayment', 'OptionGroup', 'SurveyRespondant', 'UFJoin', 'UFMatch', 'Extension', 'LocationType', 'System');
88 $this->onlyIDNonZeroCount
['get'] = array('ActivityType', 'Entity', 'Domain','Setting');
89 $this->deprecatedAPI
= array('Location', 'ActivityType', 'SurveyRespondant');
90 $this->deletableTestObjects
= array();
94 foreach ($this->deletableTestObjects
as $entityName => $entities) {
95 foreach ($entities as $entityID) {
96 CRM_Core_DAO
::deleteTestObjects($entityName, array('id' => $entityID));
106 public static function entities($skip = NULL) {
107 // The order of operations in here is screwy. In the case where SYNTAX_CONFORMANCE_ENTITIES is
108 // defined, we should be able to parse+return it immediately. However, some weird dependency
109 // crept into the system where civicrm_api('Entity','get') must be called as part of entities()
110 // (even if its return value is ignored).
112 $tmp = civicrm_api('Entity', 'Get', array('version' => 3));
113 if (getenv('SYNTAX_CONFORMANCE_ENTITIES')) {
115 'values' => explode(' ', getenv('SYNTAX_CONFORMANCE_ENTITIES'))
119 if (!is_array($skip)) {
122 $tmp = array_diff($tmp['values'], $skip);
124 foreach ($tmp as $e) {
125 $entities[] = array($e);
133 public static function entities_get() {
134 // all the entities, beside the ones flagged
135 return static::entities(static::toBeSkipped_get(TRUE));
141 public static function entities_create() {
142 return static::entities(static::toBeSkipped_create(TRUE));
148 public static function entities_updatesingle() {
149 return static::entities(static::toBeSkipped_updatesingle(TRUE));
155 public static function entities_getlimit() {
156 return static::entities(static::toBeSkipped_getlimit());
159 public static function entities_getSqlOperators() {
160 return static::entities(static::toBeSkipped_getSqlOperators());
165 public static function entities_delete() {
166 return static::entities(static::toBeSkipped_delete(TRUE));
172 public static function entities_getfields() {
173 return static::entities(static::toBeSkipped_getfields(TRUE));
178 public static function custom_data_entities_get() {
179 return static::custom_data_entities();
185 public static function custom_data_entities() {
186 $enableComponents = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'enable_components', NULL, array());
187 $entities = CRM_Core_BAO_CustomQuery
::$extendsMap;
188 $components = self
::$componentMap;
189 $customDataEntities = array();
190 $invalidEntities = array('Individual', 'Organization', 'Household');
191 $entitiesToFix = array('Case', 'Relationship');
192 foreach ($entities as $entityName => $entity ) {
193 if(!in_array($entityName, $invalidEntities)
194 && !in_array($entityName, $entitiesToFix)
195 && (!empty($components[$entityName]) && in_array($components[$entityName], $enableComponents) ||
$components[$entityName] == NULL)) {
196 $customDataEntities[] = array($entityName );
199 return $customDataEntities;
203 * @param bool $sequential
207 public static function toBeSkipped_get($sequential = FALSE) {
208 $entitiesWithoutGet = array('MailingEventSubscribe', 'MailingEventConfirm', 'MailingEventResubscribe', 'MailingEventUnsubscribe', 'Location');
209 if ($sequential === TRUE) {
210 return $entitiesWithoutGet;
213 foreach ($entitiesWithoutGet as $e) {
214 $entities[] = array($e);
220 * Mailing Contact Just doesn't support id. We have always insisted on finding a way to
221 * support id in API but in this case the underlying tables are crying out for a restructue
222 * & it just doesn't make sense
224 * @param bool|\unknown_type $sequential
226 * @return multitype:string |multitype:multitype:string
228 public static function toBeSkipped_getByID($sequential = FALSE) {
229 return array('MailingContact');
233 * @param bool $sequential
237 public static function toBeSkipped_create($sequential = FALSE) {
238 $entitiesWithoutCreate = array('Constant', 'Entity', 'Location', 'Profile', 'MailingRecipients');
239 if ($sequential === TRUE) {
240 return $entitiesWithoutCreate;
243 foreach ($entitiesWithoutCreate as $e) {
244 $entities[] = array($e);
250 * @param bool $sequential
254 public static function toBeSkipped_delete($sequential = FALSE) {
255 $entitiesWithout = array('MailingContact', 'MailingEventConfirm', 'MailingEventResubscribe', 'MailingEventSubscribe', 'MailingEventUnsubscribe', 'MailingRecipients', 'Constant', 'Entity', 'Location', 'Domain', 'Profile', 'CustomValue', 'Setting');
256 if ($sequential === TRUE) {
257 return $entitiesWithout;
260 foreach ($entitiesWithout as $e) {
261 $entities[] = array($e);
267 * @param bool $sequential
270 * @todo add metadata for ALL these entities
272 public static function toBeSkipped_getfields($sequential = FALSE) {
273 $entitiesWithMetadataNotYetFixed = array('ReportTemplate', 'CustomSearch');
274 if ($sequential === TRUE) {
275 return $entitiesWithMetadataNotYetFixed ;
278 foreach ($entitiesWithMetadataNotYetFixed as $e) {
279 $entities[] = array($e);
284 * Generate list of entities to test for get by id functions
285 * @param boolean $sequential
286 * @return multitype:string |multitype:multitype:string
288 public static function toBeSkipped_automock($sequential = FALSE) {
289 $entitiesWithoutGet = array('MailingContact', 'EntityTag', 'Participant', 'ParticipantPayment', 'Setting', 'SurveyRespondant', 'MailingRecipients', 'CustomSearch', 'Extension', 'ReportTemplate', 'System');
290 if ($sequential === TRUE) {
291 return $entitiesWithoutGet;
294 foreach ($entitiesWithoutGet as $e) {
295 $entities[] = array($e);
302 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
304 public static function toBeSkipped_updatesingle($sequential = FALSE) {
305 $entitiesWithout = array(
306 'Attachment', // pseudo-entity; testUpdateSingleValueAlter doesn't introspect properly on it. Multiple magic fields
311 'MailingEventUnsubscribe',
312 'MailingEventSubscribe',
339 'MailingEventConfirm',
343 'MailingEventResubscribe',
351 'ParticipantPayment',
359 'SystemLog' //skip this because it doesn't make sense to update logs
361 if ($sequential === TRUE) {
362 return $entitiesWithout;
365 foreach ($entitiesWithout as $e) {
370 return array('pledge');
375 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
377 public static function toBeSkipped_getlimit() {
378 $entitiesWithout = array(
379 'Case',//case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
380 'EntityTag', // non-standard api - has inappropriate mandatory fields & doesn't implement limit
381 'Event', // failed 'check that a 5 limit returns 5' - probably is_template field is wrong or something, or could be limit doesn't work right
382 'Extension', // can't handle creating 25
383 'Note', // fails on 5 limit - probably a set up problem
384 'Setting', //a bit of a pseudoapi - keys by domain
386 return $entitiesWithout;
390 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
392 public static function toBeSkipped_getSqlOperators() {
393 $entitiesWithout = array(
394 'Case',//case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
395 'Contact', // on the todo list!
396 'EntityTag', // non-standard api - has inappropriate mandatory fields & doesn't implement limit
397 'Extension', // can't handle creating 25
398 'Note', // note has a default get that isn't implemented in createTestObject -meaning you don't 'get' them
399 'Setting', //a bit of a pseudoapi - keys by domain
401 return $entitiesWithout;
410 public function getKnownUnworkablesUpdateSingle($entity, $key){
411 // can't update values are values for which updates don't result in the value being changed
412 $knownFailures = array(
413 'ActionSchedule' => array(
414 'cant_update' => array(
418 'ActivityContact' => array(
419 'cant_update' => array(
420 'activity_id', //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
424 'cant_update' => array(
425 'state_province_id', //issues with country id - need to ensure same country
426 'master_id',//creates relationship
428 'cant_return' => array(
432 'cant_update' => array(
433 'entity_table', // believe this field is defined in error
435 'cant_return' => array(
440 'cant_update' => array(
444 'MembershipBlock' => array(
445 'cant_update' => array(
446 // The fake/auto-generated values leave us unable to properly cleanup fake data
452 'cant_update' => array(
453 'pledge_original_installment_amount',
455 'original_installment_amount',
457 'amount' // can't be changed through API
459 'break_return' => array(// if these are passed in they are retrieved from the wrong table
462 'contribution_page_id',
463 'financial_account_id',
467 'cant_return' => array(// can't be retrieved from api
468 'honor_type_id', //due to uniquename missing
476 'initial_reminder_day',
477 'additional_reminder_day',
479 'pledge_contribution_page_id',
481 'pledge_campaign_id',
482 'pledge_financial_type_id',
485 'PaymentProcessorType' => array(
486 'cant_update' => array(
489 'break_return' => array(
491 'cant_return' => array(
494 'PriceFieldValue' => array(
495 'cant_update' => array(
496 'weight', //won't update as there is no 1 in the same price set
500 if(empty($knownFailures[$entity]) ||
empty($knownFailures[$entity][$key])){
503 return $knownFailures[$entity][$key];
506 /** testing the _get **/
509 * @dataProvider toBeSkipped_get
510 entities that don't need a get action
512 public function testNotImplemented_get($Entity) {
513 $result = civicrm_api($Entity, 'Get', array('version' => 3));
514 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
515 // $this->assertContains("API ($Entity, Get) does not exist", $result['error_message']);
516 $this->assertRegExp('/API (.*) does not exist/', $result['error_message']);
520 * @dataProvider entities
521 * @expectedException PHPUnit_Framework_Error
523 public function testWithoutParam_get($Entity) {
524 // should get php complaining that a param is missing
525 $result = civicrm_api($Entity, 'Get');
529 * @dataProvider entities
531 public function testGetFields($Entity) {
532 if (in_array($Entity, $this->deprecatedAPI
) ||
$Entity == 'Entity' ||
$Entity == 'CustomValue') {
536 $result = civicrm_api($Entity, 'getfields', array('version' => 3));
537 $this->assertTrue(is_array($result['values']), "$Entity ::get fields doesn't return values array in line " . __LINE__
);
538 foreach ($result['values'] as $key => $value) {
539 $this->assertTrue(is_array($value), $Entity . "::" . $key . " is not an array in line " . __LINE__
);
544 * @dataProvider entities_get
546 public function testEmptyParam_get($Entity) {
548 if (in_array($Entity, $this->toBeImplemented
['get'])) {
549 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
552 $result = civicrm_api($Entity, 'Get', array());
553 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
554 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
557 * @dataProvider entities_get
559 public function testEmptyParam_getString($Entity) {
561 if (in_array($Entity, $this->toBeImplemented
['get'])) {
562 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
565 $result = $this->callAPIFailure($Entity, 'Get', 'string');
566 $this->assertEquals(2000, $result['error_code']);
567 $this->assertEquals('Input variable `params` is not an array', $result['error_message']);
570 * @dataProvider entities_get
571 * @Xdepends testEmptyParam_get // no need to test the simple if the empty doesn't work/is skipped. doesn't seem to work
573 public function testSimple_get($Entity) {
574 // $this->markTestSkipped("test gives core error on test server (but not on our locals). Skip until we can get server to pass");
575 if (in_array($Entity, $this->toBeImplemented
['get'])) {
578 $result = civicrm_api($Entity, 'Get', array('version' => 3));
579 // @TODO: list the get that have mandatory params
580 if ($result['is_error']) {
581 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
582 // either id or contact_id or entity_id is one of the field missing
583 $this->assertContains("id", $result['error_message']);
586 $this->assertEquals(3, $result['version']);
587 $this->assertArrayHasKey('count', $result);
588 $this->assertArrayHasKey('values', $result);
593 * @dataProvider custom_data_entities_get
595 public function testCustomDataGet($entityName) {
596 $this->createLoggedInUser();// so subsidiary activities are created
597 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entityName . 'Test.php');
598 $customFieldName = 'custom_' . $ids['custom_field_id'];
599 $objects = $this->getMockableBAOObjects($entityName, 1);
600 $params = array('id' => $objects[0]->id
, 'custom_' . $ids['custom_field_id'] => "custom string");
601 $result = $this->callAPISuccess($entityName, 'create', $params);
603 $getParams = array('id' => $result['id'], 'return' => array($customFieldName));
604 $check = $this->callAPISuccess($entityName, 'get', $getParams);
605 $this->assertEquals("custom string", $check['values'][$check['id']][$customFieldName]);
607 $this->customFieldDelete($ids['custom_field_id']);
608 $this->customGroupDelete($ids['custom_group_id']);
609 $this->callAPISuccess($entityName, 'delete', array('id' => $result['id']));
613 * @dataProvider entities_get
615 public function testAcceptsOnlyID_get($Entity) {
616 // big random number. fun fact: if you multiply it by pi^e, the result is another random number, but bigger ;)
617 $nonExistantID = 30867307034;
618 if (in_array($Entity, $this->toBeImplemented
['get'])
619 ||
in_array($Entity, $this->toBeSkipped_getByID())
625 // the below function returns different values and hence an early return
626 // we'll fix this once beta1 is released
629 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
631 if ($result['is_error']) {
632 // just to get a clearer message in the log
633 $this->assertEquals("only id should be enough", $result['error_message']);
635 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
636 $this->assertEquals(0, $result['count']);
641 * Create two entities and make sure we can fetch them individually by ID
643 * @dataProvider entities_get
645 * limitations include the problem with avoiding loops when creating test objects -
646 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
647 * Currency - only seems to support US
649 public function testByID_get($entityName) {
650 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
651 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
655 $baos = $this->getMockableBAOObjects($entityName);
656 list($baoObj1, $baoObj2) = $baos;
659 $result = $this->callAPISuccess($entityName, 'get', array(
660 'id' => $baoObj1->id
,
663 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
664 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
665 $this->assertEquals(1, count($result['values']));
667 // fetch second by ID
668 $result = $this->callAPISuccess($entityName, 'get', array(
669 'id' => $baoObj2->id
,
671 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
672 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
673 $this->assertEquals(1, count($result['values']));
677 * Ensure that the "get" operation accepts limiting the #result records.
679 * TODO Consider making a separate entity list ("entities_getlimit")
680 * For the moment, the "entities_updatesingle" list should give a good
681 * sense for which entities support createTestObject
683 * @dataProvider entities_getlimit
685 * @param string $entityName
688 function testLimit($entityName) {
689 $cases = array(); // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
691 array('options' => array('limit' => NULL)),
693 'check that a NULL limit returns unlimited',
696 array('options' => array('limit' => FALSE)),
698 'check that a FALSE limit returns unlimited',
701 array('options' => array('limit' => 0)),
703 'check that a 0 limit returns unlimited',
706 array('options' => array('limit' => 5)),
708 'check that a 5 limit returns 5',
713 'check that no limit returns 25',
716 $baoString = _civicrm_api3_get_BAO($entityName);
717 if (empty($baoString)) {
718 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
722 // make 30 test items -- 30 > 25 (the default limit)
724 for ($i = 0; $i < 30; $i++
) {
725 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
726 $ids[] = $baoObj->id
;
729 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
730 foreach ($cases as $case) {
731 $this->checkLimitAgainstExpected($entityName, $case[0], $case[1], $case[2]);
733 //non preferred / legacy syntax
734 if(isset($case[0]['options']['limit'])) {
735 $this->checkLimitAgainstExpected($entityName, array('rowCount' => $case[0]['options']['limit']), $case[1], $case[2]);
736 $this->checkLimitAgainstExpected($entityName, array('option_limit' => $case[0]['options']['limit']), $case[1], $case[2]);
737 $this->checkLimitAgainstExpected($entityName, array('option.limit' => $case[0]['options']['limit']), $case[1], $case[2]);
740 foreach ($ids as $id) {
741 CRM_Core_DAO
::deleteTestObjects($baoString, array('id' => $id));
747 * Ensure that the "get" operation accepts limiting the #result records.
749 * @dataProvider entities_getSqlOperators
751 * @param string $entityName
754 function testSqlOperators($entityName) {
755 $baoString = _civicrm_api3_get_BAO($entityName);
756 if (empty($baoString)) {
757 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
760 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0), 'return' => 'id'));
761 $entities = array_keys($entities['values']);
762 $totalEntities = count($entities);
763 if ($totalEntities < 3) {
765 for ($i = 0; $i < 3 - $totalEntities; $i++
) {
766 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
767 $ids[] = $baoObj->id
;
771 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0)));
772 $entities = array_keys($entities['values']);
773 $this->assertGreaterThan(2, $totalEntities);
774 $this->callAPISuccess($entityName, 'getsingle', array('id' => array('IN' => array($entities[0]))));
775 $this->callAPISuccessGetCount($entityName, array('id' => array('NOT IN' => array($entities[0]))), $totalEntities - 1);
776 $this->callAPISuccessGetCount($entityName, array('id' => array('>' => $entities[0])), $totalEntities - 1);
780 * Check that get fetches an appropriate number of results
782 * @param string $entityName Name of entity to test
783 * @param array $params
784 * @param integer $limit
785 * @param string $message
787 function checkLimitAgainstExpected($entityName, $params, $limit, $message) {
788 $result = $this->callAPISuccess($entityName, 'get', $params);
790 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
791 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
794 $this->assertEquals($limit, $result['count'], $message);
795 $this->assertEquals($limit, count($result['values']), $message);
799 * Create two entities and make sure we can fetch them individually by ID (e.g. using "contact_id=>2"
802 * @dataProvider entities_get
804 * limitations include the problem with avoiding loops when creating test objects -
805 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
806 * Currency - only seems to support US
808 public function testByIDAlias_get($entityName) {
809 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
810 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
814 $baoString = _civicrm_api3_get_BAO($entityName);
815 if (empty($baoString)) {
816 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
820 $idFieldName = _civicrm_api_get_entity_name_from_camel($entityName) . '_id';
823 $baoObj1 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
824 $this->assertTrue(is_integer($baoObj1->id
), 'check first id');
825 $this->deletableTestObjects
[$baoString][] = $baoObj1->id
;
826 $baoObj2 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
827 $this->assertTrue(is_integer($baoObj2->id
), 'check second id');
828 $this->deletableTestObjects
[$baoString][] = $baoObj2->id
;
831 $result = civicrm_api($entityName, 'get', array(
833 $idFieldName => $baoObj1->id
,
835 $this->assertAPISuccess($result);
836 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
837 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
838 $this->assertEquals(1, count($result['values']));
840 // fetch second by ID
841 $result = civicrm_api($entityName, 'get', array(
843 $idFieldName => $baoObj2->id
,
845 $this->assertAPISuccess($result);
846 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
847 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
848 $this->assertEquals(1, count($result['values']));
852 * @dataProvider entities_get
854 public function testNonExistantID_get($Entity) {
855 // cf testAcceptsOnlyID_get
856 $nonExistantID = 30867307034;
857 if (in_array($Entity, $this->toBeImplemented
['get'])) {
861 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
863 // redundant with testAcceptsOnlyID_get
864 if ($result['is_error']) {
869 $this->assertArrayHasKey('version', $result);
870 $this->assertEquals(3, $result['version']);
871 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
872 $this->assertEquals(0, $result['count']);
876 /** testing the _create **/
879 * @dataProvider toBeSkipped_create
880 entities that don't need a create action
882 public function testNotImplemented_create($Entity) {
883 $result = civicrm_api($Entity, 'Create', array('version' => 3));
884 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
885 $this->assertContains(strtolower("API ($Entity, Create) does not exist"), strtolower($result['error_message']));
889 * @dataProvider entities
890 * @expectedException PHPUnit_Framework_Error
892 public function testWithoutParam_create($Entity) {
893 // should create php complaining that a param is missing
894 $result = civicrm_api($Entity, 'Create');
898 * @dataProvider entities_create
900 public function testEmptyParam_create($Entity) {
901 $this->markTestIncomplete("fixing this test to test the api functions fails on numberous tests
902 which will either create a completely blank entity (batch, participant status) or
903 have a damn good crack at it (e.g mailing job). Marking this as incomplete beats false success");
906 if (in_array($Entity, $this->toBeImplemented
['create'])) {
907 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
910 $result = $this->callAPIFailure($Entity, 'Create', array());
911 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
915 * @dataProvider entities_create
917 * Check that create doesn't work with an invalid
919 public function testInvalidID_create($Entity) {
920 // turn test off for noew
921 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
923 if (in_array($Entity, $this->toBeImplemented
['create'])) {
924 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
927 $result = $this->callAPIFailure($Entity, 'Create', array('id' => 999));
931 * @dataProvider entities
933 public function testCreateWrongTypeParamTag_create() {
934 $result = civicrm_api("Tag", 'Create', 'this is not a string');
935 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
936 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
940 * @dataProvider entities_updatesingle
942 * limitations include the problem with avoiding loops when creating test objects -
943 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
944 * Currency - only seems to support US
946 public function testCreateSingleValueAlter($entityName) {
947 if (in_array($entityName, $this->toBeImplemented
['create'])) {
948 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
952 $baoString = _civicrm_api3_get_BAO($entityName);
953 $this->assertNotEmpty($baoString, $entityName);
954 $this->assertNotEmpty($entityName, $entityName);
955 $fieldsGet = $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'get'));
956 if($entityName != 'Pledge'){
957 $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'create'));
959 $fields = $fields['values'];
960 $return = array_keys($fieldsGet['values']);
961 $valuesNotToReturn = $this->getKnownUnworkablesUpdateSingle($entityName, 'break_return');
962 // these can't be requested as return values
963 $entityValuesThatDoNotWork = array_merge(
964 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_update'),
965 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_return'),
969 $return = array_diff($return,$valuesNotToReturn);
970 $baoObj = new CRM_Core_DAO();
971 $baoObj->createTestObject($baoString, array('currency' => 'USD'), 2, 0);
973 $getEntities = $this->callAPISuccess($entityName, 'get', array(
982 // lets use first rather than assume only one exists
983 $entity = $getEntities['values'][0];
984 $entity2 = $getEntities['values'][1];
985 $this->deletableTestObjects
[$baoString][] = $entity['id'];
986 $this->deletableTestObjects
[$baoString][] = $entity2['id'];
987 foreach ($fields as $field => $specs) {
990 if (!empty($specs['uniquename'])) {
991 $fieldName = $specs['uniquename'];
993 if ($field == 'currency' ||
$field == 'id' ||
$field == strtolower($entityName) . '_id'
994 ||
in_array($field,$entityValuesThatDoNotWork)) {
995 //@todo id & entity_id are correct but we should fix currency & frequency_day
998 $this->assertArrayHasKey('type', $specs, "the _spec function for $entityName field $field does not specify the type");
999 switch ($specs['type']) {
1000 case CRM_Utils_Type
::T_DATE
:
1001 case CRM_Utils_Type
::T_TIMESTAMP
:
1002 $entity[$fieldName] = '2012-05-20';
1004 //case CRM_Utils_Type::T_DATETIME:
1007 $entity[$fieldName] = '2012-05-20 03:05:20';
1010 case CRM_Utils_Type
::T_STRING
:
1011 case CRM_Utils_Type
::T_BLOB
:
1012 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1013 case CRM_Utils_Type
::T_TEXT
:
1014 case CRM_Utils_Type
::T_LONGTEXT
:
1015 case CRM_Utils_Type
::T_EMAIL
:
1016 $entity[$fieldName] = substr('New String',0, CRM_Utils_Array
::Value('maxlength',$specs,100));
1019 case CRM_Utils_Type
::T_INT
:
1020 // probably created with a 1
1021 if ($fieldName == 'weight') {
1022 $entity[$fieldName] = 2;
1024 elseif (!empty($specs['FKClassName'])) {
1025 if($specs['FKClassName'] == $baoString){
1026 $entity[$fieldName] = (string) $entity2['id'];
1029 $uniqueName = CRM_Utils_Array
::value('uniqueName', $specs);
1030 if (!empty($entity[$fieldName])) {
1031 $resetFKTo = array($fieldName => $entity[$fieldName]);
1033 $entity[$fieldName] = (string) empty($entity2[$field]) ? CRM_Utils_Array
::value($uniqueName, $entity2) : $entity2[$field];
1034 //todo - there isn't always something set here - & our checking on unset values is limited
1035 if (empty($entity[$field])) {
1036 unset($entity[$field]);
1041 $entity[$fieldName] = '6';
1045 case CRM_Utils_Type
::T_BOOLEAN
:
1046 // probably created with a 1
1047 $entity[$fieldName] = '0';
1050 case CRM_Utils_Type
::T_FLOAT
:
1051 case CRM_Utils_Type
::T_MONEY
:
1052 $entity[$field] = '22.75';
1055 case CRM_Utils_Type
::T_URL
:
1056 $entity[$field] = 'warm.beer.com';
1058 if (!empty($specs['pseudoconstant'])) {
1059 $options = $this->callAPISuccess($entityName, 'getoptions', array('context' => 'create', 'field' => $field));
1060 if (empty($options['values'])) {
1061 //eg. pdf_format id doesn't ship with any
1062 if(isset($specs['pseudoconstant']['optionGroupName'])) {
1063 $optionGroupID = $this->callAPISuccess('option_group', 'getvalue', array('name' => 'pdf_format', 'return' => 'id'));
1064 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID, 'label' => 'new option value'));
1065 $options['values'][] = $optionValue['id'];
1068 $entity[$field] = array_rand($options['values']);
1070 $updateParams = array(
1071 'id' => $entity['id'],
1072 $field => isset($entity[$field]) ?
$entity[$field] : NULL,
1074 if(isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1075 //api has special handling on these 2 fields for backward compatibility reasons
1076 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1079 $update = $this->callAPISuccess($entityName, 'create', $updateParams);
1080 $checkParams = array(
1081 'id' => $entity['id'],
1083 'return' => $return,
1085 'sort' => 'id DESC',
1090 $checkEntity = $this->callAPISuccess($entityName, 'getsingle', $checkParams);
1091 $this->assertAPIArrayComparison($entity, $checkEntity, array(), "checking if $fieldName was correctly updated\n" . print_r(array('update-params' => $updateParams, 'update-result' => $update, 'getsingle-params' => $checkParams, 'getsingle-result' => $checkEntity, 'expected entity' => $entity), TRUE));
1093 //reset the foreign key fields because otherwise our cleanup routine fails & some other unexpected stuff can kick in
1094 $entity = array_merge($entity, $resetFKTo);
1095 $updateParams = array_merge($updateParams, $resetFKTo);
1096 $this->callAPISuccess($entityName, 'create', $updateParams);
1097 if(isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1098 //api has special handling on these 2 fields for backward compatibility reasons
1099 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1106 /** testing the _getFields **/
1108 /** testing the _delete **/
1111 * @dataProvider toBeSkipped_delete
1112 entities that don't need a delete action
1114 public function testNotImplemented_delete($Entity) {
1115 $nonExistantID = 151416349;
1116 $result = civicrm_api($Entity, 'Delete', array('version' => 3, 'id' => $nonExistantID));
1117 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1118 $this->assertContains(strtolower("API ($Entity, Delete) does not exist"), strtolower($result['error_message']));
1122 * @dataProvider entities
1123 * @expectedException PHPUnit_Framework_Error
1125 public function testWithoutParam_delete($Entity) {
1126 // should delete php complaining that a param is missing
1127 $result = civicrm_api($Entity, 'Delete');
1131 * @dataProvider entities_delete
1133 public function testEmptyParam_delete($Entity) {
1134 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1135 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1138 $result = civicrm_api($Entity, 'Delete', array());
1139 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1140 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
1143 * @dataProvider entities_delete
1145 public function testInvalidID_delete($Entity) {
1146 // turn test off for now
1147 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1149 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1150 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1153 $result = $this->callAPIFailure($Entity, 'Delete', array('id' => 999));
1156 * @dataProvider entities
1158 public function testDeleteWrongTypeParamTag_delete() {
1159 $result = civicrm_api("Tag", 'Delete', 'this is not a string');
1160 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1161 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1165 * Create two entities and make sure delete action only deletes one!
1167 * @dataProvider entities_delete
1169 * limitations include the problem with avoiding loops when creating test objects -
1170 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1171 * Currency - only seems to support US
1173 public function testByID_delete($entityName) {
1174 // turn test off for noew
1175 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1178 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1179 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1182 $startCount = $this->callAPISuccess($entityName, 'getcount', array());
1184 $baos = $this->getMockableBAOObjects($entityName, $createcount);
1185 list($baoObj1, $baoObj2) = $baos;
1187 // make sure exactly 2 exist
1188 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1189 $createcount +
$startCount
1192 $this->callAPISuccess($entityName, 'delete', array('id' => $baoObj2->id
));
1193 //make sure 1 less exists now
1194 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1195 ($createcount +
$startCount) -1
1198 //make sure id #1 exists
1199 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj1->id
),
1202 //make sure id #2 desn't exist
1203 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj2->id
),
1209 * Create two entities and make sure delete action only deletes one!
1211 * @dataProvider entities_getfields
1214 public function testGetfieldsHasTitle($entity) {
1215 $entities = $this->getEntitiesSupportingCustomFields();
1216 if (in_array($entity, $entities)) {
1217 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entity . 'Test.php');
1219 $actions = $this->callAPISuccess($entity, 'getactions', array());
1220 foreach ($actions['values'] as $action) {
1221 if (substr($action, -7) == '_create' ||
substr($action, -4) == '_get' ||
substr($action, -7) == '_delete') {
1222 //getactions can't distinguish between contribution_page.create & contribution_page.create
1225 $fields = $this->callAPISuccess($entity, 'getfields', array('action' => $action));
1226 if (!empty($ids) && in_array($action, array('create', 'get'))) {
1227 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $fields['values']);
1230 foreach ($fields['values'] as $fieldName => $fieldSpec) {
1231 $this->assertArrayHasKey('title', $fieldSpec, "no title for $entity - $fieldName on action $action");
1232 $this->assertNotEmpty($fieldSpec['title'], "empty title for $entity - $fieldName");
1236 $this->customFieldDelete($ids['custom_field_id']);
1237 $this->customGroupDelete($ids['custom_group_id']);
1244 public function getEntitiesSupportingCustomFields() {
1245 $entities = self
::custom_data_entities_get();
1246 $returnEntities = array();
1247 foreach ($entities as $entityArray) {
1248 $returnEntities[] = $entityArray[0];
1250 return $returnEntities;
1253 * @param string $entityName
1259 private function getMockableBAOObjects($entityName, $count = 2) {
1260 $baoString = _civicrm_api3_get_BAO($entityName);
1261 if (empty($baoString)) {
1262 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1267 while($i < $count) {
1269 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1270 $this->assertTrue(is_integer($baoObj->id
), 'check first id');
1271 $this->deletableTestObjects
[$baoString][] = $baoObj->id
;
1280 * Verify that HTML metacharacters provided as inputs appear consistently
1283 * At time of writing, the encoding scheme requires (for example) that an
1284 * event title be partially-HTML-escaped before writing to DB. To provide
1285 * consistency, the API must perform extra encoding and decoding on some
1288 * In this example, the event 'title' is subject to encoding, but the
1289 * event 'description' is not.
1291 public function testEncodeDecodeConsistency() {
1293 $createResult = civicrm_api('Event', 'Create', array(
1295 'title' => 'CiviCRM <> TheRest',
1296 'description' => 'TheRest <> CiviCRM',
1297 'event_type_id' => 1,
1299 'start_date' => 20081021,
1301 $this->assertAPISuccess($createResult);
1302 $eventId = $createResult['id'];
1303 $this->assertEquals('CiviCRM <> TheRest', $createResult['values'][$eventId]['title']);
1304 $this->assertEquals('TheRest <> CiviCRM', $createResult['values'][$eventId]['description']);
1306 // Verify "get" handles decoding in result value
1307 $getByIdResult = civicrm_api('Event', 'Get', array(
1311 $this->assertAPISuccess($getByIdResult);
1312 $this->assertEquals('CiviCRM <> TheRest', $getByIdResult['values'][$eventId]['title']);
1313 $this->assertEquals('TheRest <> CiviCRM', $getByIdResult['values'][$eventId]['description']);
1315 // Verify "get" handles encoding in search value
1316 $getByTitleResult = civicrm_api('Event', 'Get', array(
1318 'title' => 'CiviCRM <> TheRest',
1320 $this->assertAPISuccess($getByTitleResult);
1321 $this->assertEquals('CiviCRM <> TheRest', $getByTitleResult['values'][$eventId]['title']);
1322 $this->assertEquals('TheRest <> CiviCRM', $getByTitleResult['values'][$eventId]['description']);
1324 // Verify that "getSingle" handles decoding
1325 $getSingleResult = $this->callAPISuccess('Event', 'GetSingle', array(
1329 $this->assertEquals('CiviCRM <> TheRest', $getSingleResult['title']);
1330 $this->assertEquals('TheRest <> CiviCRM', $getSingleResult['description']);
1332 // Verify that chaining handles decoding
1333 $chainResult = $this->callAPISuccess('Event', 'Get', array(
1335 'api.event.get' => array(
1338 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['title']);
1339 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['description']);
1340 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['api.event.get']['values'][0]['title']);
1341 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['api.event.get']['values'][0]['description']);
1343 // Verify that "setvalue" handles encoding for updates
1344 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1348 'value' => 'setValueTitle: CiviCRM <> TheRest',
1350 $this->assertAPISuccess($setValueTitleResult);
1351 $this->assertEquals('setValueTitle: CiviCRM <> TheRest', $setValueTitleResult['values']['title']);
1352 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1355 'field' => 'description',
1356 'value' => 'setValueDescription: TheRest <> CiviCRM',
1358 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1359 $this->assertEquals('setValueDescription: TheRest <> CiviCRM', $setValueDescriptionResult['values']['description']);
1363 * Verify that write operations (create/update) use partial HTML-encoding
1365 * In this example, the event 'title' is subject to encoding, but the
1366 * event 'description' is not.
1368 public function testEncodeWrite() {
1370 $createResult = civicrm_api('Event', 'Create', array(
1372 'title' => 'createNew: CiviCRM <> TheRest',
1373 'description' => 'createNew: TheRest <> CiviCRM',
1374 'event_type_id' => 1,
1376 'start_date' => 20081021,
1378 $this->assertAPISuccess($createResult);
1379 $eventId = $createResult['id'];
1380 $this->assertDBQuery('createNew: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1381 1 => array($eventId, 'Integer')
1383 $this->assertDBQuery('createNew: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1384 1 => array($eventId, 'Integer')
1387 // Verify that "create" handles encoding for updates
1388 $createWithIdResult = civicrm_api('Event', 'Create', array(
1391 'title' => 'createWithId: CiviCRM <> TheRest',
1392 'description' => 'createWithId: TheRest <> CiviCRM',
1394 $this->assertAPISuccess($createWithIdResult);
1395 $this->assertDBQuery('createWithId: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1396 1 => array($eventId, 'Integer')
1398 $this->assertDBQuery('createWithId: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1399 1 => array($eventId, 'Integer')
1402 // Verify that "setvalue" handles encoding for updates
1403 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1407 'value' => 'setValueTitle: CiviCRM <> TheRest',
1409 $this->assertAPISuccess($setValueTitleResult);
1410 $this->assertDBQuery('setValueTitle: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1411 1 => array($eventId, 'Integer')
1413 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1416 'field' => 'description',
1417 'value' => 'setValueDescription: TheRest <> CiviCRM',
1419 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1420 $this->assertAPISuccess($setValueDescriptionResult);
1421 $this->assertDBQuery('setValueDescription: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1422 1 => array($eventId, 'Integer')