3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
42 class api_v3_SyntaxConformanceTest
extends CiviUnitTestCase
{
43 protected $_apiversion = 3;
46 * @var array e.g. $this->deletes['CRM_Contact_DAO_Contact'][] = $contactID;
48 protected $deletableTestObjects;
50 /** This test case doesn't require DB reset */
51 public $DBResetRequired = FALSE;
55 /** Map custom group entities to civicrm components */
56 static $componentMap = array(
57 'Contribution' => 'CiviContribute',
58 'Membership' => 'CiviMember',
59 'Participant' => 'CiviEvent',
60 'Event' => 'CiviEvent',
62 'Pledge' => 'CiviPledge',
63 'Grant' => 'CiviGrant',
64 'Campaign' => 'CiviCampaign',
65 'Survey' => 'CiviCampaign',
68 /* they are two types of missing APIs:
69 - Those that are to be implemented
70 (in some future version when someone steps in -hint hint-). List the entities in toBeImplemented[ {$action} ]
71 Those that don't exist
72 and that will never exist (eg an obsoleted Entity
73 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)
75 public function setUp() {
77 $this->enableCiviCampaign();
78 $this->toBeImplemented
['get'] = array(
88 $this->toBeImplemented
['create'] = array(
99 $this->toBeImplemented
['delete'] = array(
109 $this->onlyIDNonZeroCount
['get'] = array('ActivityType', 'Entity', 'Domain', 'Setting');
110 $this->deprecatedAPI
= array('Location', 'ActivityType', 'SurveyRespondant');
111 $this->deletableTestObjects
= array();
114 public function tearDown() {
115 foreach ($this->deletableTestObjects
as $entityName => $entities) {
116 foreach ($entities as $entityID) {
117 CRM_Core_DAO
::deleteTestObjects($entityName, array('id' => $entityID));
127 public static function entities($skip = NULL) {
128 // The order of operations in here is screwy. In the case where SYNTAX_CONFORMANCE_ENTITIES is
129 // defined, we should be able to parse+return it immediately. However, some weird dependency
130 // crept into the system where civicrm_api('Entity','get') must be called as part of entities()
131 // (even if its return value is ignored).
133 $tmp = civicrm_api('Entity', 'Get', array('version' => 3));
134 if (getenv('SYNTAX_CONFORMANCE_ENTITIES')) {
136 'values' => explode(' ', getenv('SYNTAX_CONFORMANCE_ENTITIES')),
140 if (!is_array($skip)) {
143 $tmp = array_diff($tmp['values'], $skip);
145 foreach ($tmp as $e) {
146 $entities[] = array($e);
154 public static function entities_get() {
155 // all the entities, beside the ones flagged
156 return static::entities(static::toBeSkipped_get(TRUE));
162 public static function entities_create() {
163 return static::entities(static::toBeSkipped_create(TRUE));
169 public static function entities_updatesingle() {
170 return static::entities(static::toBeSkipped_updatesingle(TRUE));
176 public static function entities_getlimit() {
177 return static::entities(static::toBeSkipped_getlimit());
180 public static function entities_getSqlOperators() {
181 return static::entities(static::toBeSkipped_getSqlOperators());
187 public static function entities_delete() {
188 return static::entities(static::toBeSkipped_delete(TRUE));
194 public static function entities_getfields() {
195 return static::entities(static::toBeSkipped_getfields(TRUE));
201 public static function custom_data_entities_get() {
202 return static::custom_data_entities();
208 public static function custom_data_entities() {
209 $entities = CRM_Core_BAO_CustomQuery
::$extendsMap;
210 $enabledComponents = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'enable_components', NULL, array());
211 $customDataEntities = array();
212 $invalidEntities = array('Individual', 'Organization', 'Household');
213 $entitiesToFix = array('Case', 'Relationship');
214 foreach ($entities as $entityName => $entity) {
215 if (!in_array($entityName, $invalidEntities)
216 && !in_array($entityName, $entitiesToFix)
218 if (!empty(self
::$componentMap[$entityName]) && empty($enabledComponents[self
::$componentMap[$entityName]])) {
219 CRM_Core_BAO_ConfigSetting
::enableComponent(self
::$componentMap[$entityName]);
221 $customDataEntities[] = array($entityName);
224 return $customDataEntities;
228 * @param bool $sequential
232 public static function toBeSkipped_get($sequential = FALSE) {
233 $entitiesWithoutGet = array(
234 'MailingEventSubscribe',
235 'MailingEventConfirm',
236 'MailingEventResubscribe',
237 'MailingEventUnsubscribe',
240 if ($sequential === TRUE) {
241 return $entitiesWithoutGet;
244 foreach ($entitiesWithoutGet as $e) {
245 $entities[] = array($e);
251 * Mailing Contact Just doesn't support id. We have always insisted on finding a way to
252 * support id in API but in this case the underlying tables are crying out for a restructure
253 * & it just doesn't make sense
255 * @param bool $sequential
258 * Entities that cannot be retrieved by ID
260 public static function toBeSkipped_getByID($sequential = FALSE) {
261 return array('MailingContact');
265 * @param bool $sequential
269 public static function toBeSkipped_create($sequential = FALSE) {
270 $entitiesWithoutCreate = array('Constant', 'Entity', 'Location', 'Profile', 'MailingRecipients');
271 if ($sequential === TRUE) {
272 return $entitiesWithoutCreate;
275 foreach ($entitiesWithoutCreate as $e) {
276 $entities[] = array($e);
282 * @param bool $sequential
286 public static function toBeSkipped_delete($sequential = FALSE) {
287 $entitiesWithout = array(
289 'MailingEventConfirm',
290 'MailingEventResubscribe',
291 'MailingEventSubscribe',
292 'MailingEventUnsubscribe',
302 if ($sequential === TRUE) {
303 return $entitiesWithout;
306 foreach ($entitiesWithout as $e) {
307 $entities[] = array($e);
313 * @param bool $sequential
316 * @todo add metadata for ALL these entities
318 public static function toBeSkipped_getfields($sequential = FALSE) {
319 $entitiesWithMetadataNotYetFixed = array('ReportTemplate', 'CustomSearch');
320 if ($sequential === TRUE) {
321 return $entitiesWithMetadataNotYetFixed;
324 foreach ($entitiesWithMetadataNotYetFixed as $e) {
325 $entities[] = array($e);
331 * Generate list of entities to test for get by id functions
332 * @param bool $sequential
334 * Entities to be skipped
336 public static function toBeSkipped_automock($sequential = FALSE) {
337 $entitiesWithoutGet = array(
341 'ParticipantPayment',
350 if ($sequential === TRUE) {
351 return $entitiesWithoutGet;
354 foreach ($entitiesWithoutGet as $e) {
355 $entities[] = array($e);
362 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
364 public static function toBeSkipped_updatesingle($sequential = FALSE) {
365 $entitiesWithout = array(
367 // pseudo-entity; testUpdateSingleValueAlter doesn't introspect properly on it. Multiple magic fields
372 'MailingEventUnsubscribe',
373 'MailingEventSubscribe',
400 'MailingEventConfirm',
404 'MailingEventResubscribe',
412 'ParticipantPayment',
421 //skip this because it doesn't make sense to update logs,
423 if ($sequential === TRUE) {
424 return $entitiesWithout;
427 foreach ($entitiesWithout as $e) {
432 return array('pledge');
437 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
439 public static function toBeSkipped_getlimit() {
440 $entitiesWithout = array(
442 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
444 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
446 // failed 'check that a 5 limit returns 5' - probably is_template field is wrong or something, or could be limit doesn't work right
448 // can't handle creating 25
450 // fails on 5 limit - probably a set up problem
452 //a bit of a pseudoapi - keys by domain
454 return $entitiesWithout;
458 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
460 public static function toBeSkipped_getSqlOperators() {
461 $entitiesWithout = array(
462 'Case', //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
463 'Contact', // on the todo list!
464 'EntityTag', // non-standard api - has inappropriate mandatory fields & doesn't implement limit
465 'Extension', // can't handle creating 25
466 'Note', // note has a default get that isn't implemented in createTestObject -meaning you don't 'get' them
467 'Setting', //a bit of a pseudoapi - keys by domain
469 return $entitiesWithout;
478 public function getKnownUnworkablesUpdateSingle($entity, $key) {
479 // can't update values are values for which updates don't result in the value being changed
480 $knownFailures = array(
481 'ActionSchedule' => array(
482 'cant_update' => array(
486 'ActivityContact' => array(
487 'cant_update' => array(
489 //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
493 'cant_update' => array(
494 'state_province_id', //issues with country id - need to ensure same country
495 'master_id', //creates relationship
497 'cant_return' => array(),
500 'cant_update' => array(
501 'entity_table', // believe this field is defined in error
503 'cant_return' => array(
508 'cant_update' => array(
512 'MembershipBlock' => array(
513 'cant_update' => array(
514 // The fake/auto-generated values leave us unable to properly cleanup fake data
520 'cant_update' => array(
521 'pledge_original_installment_amount',
523 'original_installment_amount',
525 'amount' // can't be changed through API,
527 'break_return' => array(// if these are passed in they are retrieved from the wrong table
530 'contribution_page_id',
531 'financial_account_id',
535 'cant_return' => array(// can't be retrieved from api
536 'honor_type_id', //due to uniquename missing
544 'initial_reminder_day',
545 'additional_reminder_day',
547 'pledge_contribution_page_id',
549 'pledge_campaign_id',
550 'pledge_financial_type_id',
553 'PaymentProcessorType' => array(
554 'cant_update' => array(
557 'break_return' => array(),
558 'cant_return' => array(),
560 'PriceFieldValue' => array(
561 'cant_update' => array(
562 'weight', //won't update as there is no 1 in the same price set
566 if (empty($knownFailures[$entity]) ||
empty($knownFailures[$entity][$key])) {
569 return $knownFailures[$entity][$key];
572 /** testing the _get **/
575 * @dataProvider toBeSkipped_get
576 entities that don't need a get action
578 public function testNotImplemented_get($Entity) {
579 $result = civicrm_api($Entity, 'Get', array('version' => 3));
580 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
581 // $this->assertContains("API ($Entity, Get) does not exist", $result['error_message']);
582 $this->assertRegExp('/API (.*) does not exist/', $result['error_message']);
586 * @dataProvider entities
587 * @expectedException PHPUnit_Framework_Error
589 public function testWithoutParam_get($Entity) {
590 // should get php complaining that a param is missing
591 $result = civicrm_api($Entity, 'Get');
595 * @dataProvider entities
597 public function testGetFields($Entity) {
598 if (in_array($Entity, $this->deprecatedAPI
) ||
$Entity == 'Entity' ||
$Entity == 'CustomValue') {
602 $result = civicrm_api($Entity, 'getfields', array('version' => 3));
603 $this->assertTrue(is_array($result['values']), "$Entity ::get fields doesn't return values array in line " . __LINE__
);
604 foreach ($result['values'] as $key => $value) {
605 $this->assertTrue(is_array($value), $Entity . "::" . $key . " is not an array in line " . __LINE__
);
610 * @dataProvider entities_get
612 public function testEmptyParam_get($Entity) {
614 if (in_array($Entity, $this->toBeImplemented
['get'])) {
615 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
618 $result = civicrm_api($Entity, 'Get', array());
619 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
620 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
624 * @dataProvider entities_get
626 public function testEmptyParam_getString($Entity) {
628 if (in_array($Entity, $this->toBeImplemented
['get'])) {
629 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
632 $result = $this->callAPIFailure($Entity, 'Get', 'string');
633 $this->assertEquals(2000, $result['error_code']);
634 $this->assertEquals('Input variable `params` is not an array', $result['error_message']);
638 * @dataProvider entities_get
639 * @Xdepends testEmptyParam_get // no need to test the simple if the empty doesn't work/is skipped. doesn't seem to work
641 public function testSimple_get($Entity) {
642 // $this->markTestSkipped("test gives core error on test server (but not on our locals). Skip until we can get server to pass");
643 if (in_array($Entity, $this->toBeImplemented
['get'])) {
646 $result = civicrm_api($Entity, 'Get', array('version' => 3));
647 // @TODO: list the get that have mandatory params
648 if ($result['is_error']) {
649 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
650 // either id or contact_id or entity_id is one of the field missing
651 $this->assertContains("id", $result['error_message']);
654 $this->assertEquals(3, $result['version']);
655 $this->assertArrayHasKey('count', $result);
656 $this->assertArrayHasKey('values', $result);
661 * @dataProvider custom_data_entities_get
663 public function testCustomDataGet($entityName) {
664 $this->createLoggedInUser();// so subsidiary activities are created
665 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entityName . 'Test.php');
666 $customFieldName = 'custom_' . $ids['custom_field_id'];
667 $objects = $this->getMockableBAOObjects($entityName, 1);
668 $params = array('id' => $objects[0]->id
, 'custom_' . $ids['custom_field_id'] => "custom string");
669 $result = $this->callAPISuccess($entityName, 'create', $params);
671 $getParams = array('id' => $result['id'], 'return' => array($customFieldName));
672 $check = $this->callAPISuccess($entityName, 'get', $getParams);
673 $this->assertEquals("custom string", $check['values'][$check['id']][$customFieldName]);
675 $this->customFieldDelete($ids['custom_field_id']);
676 $this->customGroupDelete($ids['custom_group_id']);
677 $this->callAPISuccess($entityName, 'delete', array('id' => $result['id']));
681 * @dataProvider entities_get
683 public function testAcceptsOnlyID_get($Entity) {
684 // big random number. fun fact: if you multiply it by pi^e, the result is another random number, but bigger ;)
685 $nonExistantID = 30867307034;
686 if (in_array($Entity, $this->toBeImplemented
['get'])
687 ||
in_array($Entity, $this->toBeSkipped_getByID())
693 // the below function returns different values and hence an early return
694 // we'll fix this once beta1 is released
697 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
699 if ($result['is_error']) {
700 // just to get a clearer message in the log
701 $this->assertEquals("only id should be enough", $result['error_message']);
703 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
704 $this->assertEquals(0, $result['count']);
709 * Create two entities and make sure we can fetch them individually by ID
711 * @dataProvider entities_get
713 * limitations include the problem with avoiding loops when creating test objects -
714 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
715 * Currency - only seems to support US
717 public function testByID_get($entityName) {
718 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
719 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
723 $baos = $this->getMockableBAOObjects($entityName);
724 list($baoObj1, $baoObj2) = $baos;
727 $result = $this->callAPISuccess($entityName, 'get', array(
728 'id' => $baoObj1->id
,
731 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
732 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
733 $this->assertEquals(1, count($result['values']));
735 // fetch second by ID
736 $result = $this->callAPISuccess($entityName, 'get', array(
737 'id' => $baoObj2->id
,
739 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
740 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
741 $this->assertEquals(1, count($result['values']));
745 * Ensure that the "get" operation accepts limiting the #result records.
747 * TODO Consider making a separate entity list ("entities_getlimit")
748 * For the moment, the "entities_updatesingle" list should give a good
749 * sense for which entities support createTestObject
751 * @dataProvider entities_getlimit
753 * @param string $entityName
755 public function testLimit($entityName) {
756 $cases = array(); // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
758 array('options' => array('limit' => NULL)),
760 'check that a NULL limit returns unlimited',
763 array('options' => array('limit' => FALSE)),
765 'check that a FALSE limit returns unlimited',
768 array('options' => array('limit' => 0)),
770 'check that a 0 limit returns unlimited',
773 array('options' => array('limit' => 5)),
775 'check that a 5 limit returns 5',
780 'check that no limit returns 25',
783 $baoString = _civicrm_api3_get_BAO($entityName);
784 if (empty($baoString)) {
785 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
789 // make 30 test items -- 30 > 25 (the default limit)
791 for ($i = 0; $i < 30; $i++
) {
792 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
793 $ids[] = $baoObj->id
;
796 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
797 foreach ($cases as $case) {
798 $this->checkLimitAgainstExpected($entityName, $case[0], $case[1], $case[2]);
800 //non preferred / legacy syntax
801 if (isset($case[0]['options']['limit'])) {
802 $this->checkLimitAgainstExpected($entityName, array('rowCount' => $case[0]['options']['limit']), $case[1], $case[2]);
803 $this->checkLimitAgainstExpected($entityName, array('option_limit' => $case[0]['options']['limit']), $case[1], $case[2]);
804 $this->checkLimitAgainstExpected($entityName, array('option.limit' => $case[0]['options']['limit']), $case[1], $case[2]);
807 foreach ($ids as $id) {
808 CRM_Core_DAO
::deleteTestObjects($baoString, array('id' => $id));
814 * Ensure that the "get" operation accepts limiting the #result records.
816 * @dataProvider entities_getSqlOperators
818 * @param string $entityName
820 public function testSqlOperators($entityName) {
821 $baoString = _civicrm_api3_get_BAO($entityName);
822 if (empty($baoString)) {
823 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
826 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0), 'return' => 'id'));
827 $entities = array_keys($entities['values']);
828 $totalEntities = count($entities);
829 if ($totalEntities < 3) {
831 for ($i = 0; $i < 3 - $totalEntities; $i++
) {
832 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
833 $ids[] = $baoObj->id
;
837 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0)));
838 $entities = array_keys($entities['values']);
839 $this->assertGreaterThan(2, $totalEntities);
840 $this->callAPISuccess($entityName, 'getsingle', array('id' => array('IN' => array($entities[0]))));
841 $this->callAPISuccessGetCount($entityName, array('id' => array('NOT IN' => array($entities[0]))), $totalEntities - 1);
842 $this->callAPISuccessGetCount($entityName, array('id' => array('>' => $entities[0])), $totalEntities - 1);
846 * Check that get fetches an appropriate number of results
848 * @param string $entityName
849 * Name of entity to test.
850 * @param array $params
852 * @param string $message
854 public function checkLimitAgainstExpected($entityName, $params, $limit, $message) {
855 $result = $this->callAPISuccess($entityName, 'get', $params);
857 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
858 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
861 $this->assertEquals($limit, $result['count'], $message);
862 $this->assertEquals($limit, count($result['values']), $message);
867 * Create two entities and make sure we can fetch them individually by ID (e.g. using "contact_id=>2"
870 * @dataProvider entities_get
872 * limitations include the problem with avoiding loops when creating test objects -
873 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
874 * Currency - only seems to support US
876 public function testByIDAlias_get($entityName) {
877 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
878 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
882 $baoString = _civicrm_api3_get_BAO($entityName);
883 if (empty($baoString)) {
884 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
888 $idFieldName = _civicrm_api_get_entity_name_from_camel($entityName) . '_id';
891 $baoObj1 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
892 $this->assertTrue(is_integer($baoObj1->id
), 'check first id');
893 $this->deletableTestObjects
[$baoString][] = $baoObj1->id
;
894 $baoObj2 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
895 $this->assertTrue(is_integer($baoObj2->id
), 'check second id');
896 $this->deletableTestObjects
[$baoString][] = $baoObj2->id
;
899 $result = civicrm_api($entityName, 'get', array(
901 $idFieldName => $baoObj1->id
,
903 $this->assertAPISuccess($result);
904 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
905 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
906 $this->assertEquals(1, count($result['values']));
908 // fetch second by ID
909 $result = civicrm_api($entityName, 'get', array(
911 $idFieldName => $baoObj2->id
,
913 $this->assertAPISuccess($result);
914 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
915 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
916 $this->assertEquals(1, count($result['values']));
920 * @dataProvider entities_get
922 public function testNonExistantID_get($Entity) {
923 // cf testAcceptsOnlyID_get
924 $nonExistantID = 30867307034;
925 if (in_array($Entity, $this->toBeImplemented
['get'])) {
929 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
931 // redundant with testAcceptsOnlyID_get
932 if ($result['is_error']) {
936 $this->assertArrayHasKey('version', $result);
937 $this->assertEquals(3, $result['version']);
938 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
939 $this->assertEquals(0, $result['count']);
943 /** testing the _create **/
946 * @dataProvider toBeSkipped_create
947 entities that don't need a create action
949 public function testNotImplemented_create($Entity) {
950 $result = civicrm_api($Entity, 'Create', array('version' => 3));
951 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
952 $this->assertContains(strtolower("API ($Entity, Create) does not exist"), strtolower($result['error_message']));
956 * @dataProvider entities
957 * @expectedException PHPUnit_Framework_Error
959 public function testWithoutParam_create($Entity) {
960 // should create php complaining that a param is missing
961 $result = civicrm_api($Entity, 'Create');
965 * @dataProvider entities_create
967 public function testEmptyParam_create($Entity) {
968 $this->markTestIncomplete("fixing this test to test the api functions fails on numberous tests
969 which will either create a completely blank entity (batch, participant status) or
970 have a damn good crack at it (e.g mailing job). Marking this as incomplete beats false success");
972 if (in_array($Entity, $this->toBeImplemented
['create'])) {
973 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
976 $result = $this->callAPIFailure($Entity, 'Create', array());
977 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
981 * @dataProvider entities_create
983 * Check that create doesn't work with an invalid
985 public function testInvalidID_create($Entity) {
986 // turn test off for noew
987 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
989 if (in_array($Entity, $this->toBeImplemented
['create'])) {
990 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
993 $result = $this->callAPIFailure($Entity, 'Create', array('id' => 999));
997 * @dataProvider entities
999 public function testCreateWrongTypeParamTag_create() {
1000 $result = civicrm_api("Tag", 'Create', 'this is not a string');
1001 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1002 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1006 * @dataProvider entities_updatesingle
1008 * limitations include the problem with avoiding loops when creating test objects -
1009 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1010 * Currency - only seems to support US
1012 public function testCreateSingleValueAlter($entityName) {
1013 if (in_array($entityName, $this->toBeImplemented
['create'])) {
1014 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1018 $baoString = _civicrm_api3_get_BAO($entityName);
1019 $this->assertNotEmpty($baoString, $entityName);
1020 $this->assertNotEmpty($entityName, $entityName);
1021 $fieldsGet = $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'get'));
1022 if ($entityName != 'Pledge') {
1023 $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'create'));
1025 $fields = $fields['values'];
1026 $return = array_keys($fieldsGet['values']);
1027 $valuesNotToReturn = $this->getKnownUnworkablesUpdateSingle($entityName, 'break_return');
1028 // these can't be requested as return values
1029 $entityValuesThatDoNotWork = array_merge(
1030 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_update'),
1031 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_return'),
1035 $return = array_diff($return, $valuesNotToReturn);
1036 $baoObj = new CRM_Core_DAO();
1037 $baoObj->createTestObject($baoString, array('currency' => 'USD'), 2, 0);
1039 $getEntities = $this->callAPISuccess($entityName, 'get', array(
1041 'return' => $return,
1043 'sort' => 'id DESC',
1048 // lets use first rather than assume only one exists
1049 $entity = $getEntities['values'][0];
1050 $entity2 = $getEntities['values'][1];
1051 $this->deletableTestObjects
[$baoString][] = $entity['id'];
1052 $this->deletableTestObjects
[$baoString][] = $entity2['id'];
1053 foreach ($fields as $field => $specs) {
1055 $fieldName = $field;
1056 if (!empty($specs['uniquename'])) {
1057 $fieldName = $specs['uniquename'];
1059 if ($field == 'currency' ||
$field == 'id' ||
$field == strtolower($entityName) . '_id'
1060 ||
in_array($field, $entityValuesThatDoNotWork)
1062 //@todo id & entity_id are correct but we should fix currency & frequency_day
1065 $this->assertArrayHasKey('type', $specs, "the _spec function for $entityName field $field does not specify the type");
1066 switch ($specs['type']) {
1067 case CRM_Utils_Type
::T_DATE
:
1068 case CRM_Utils_Type
::T_TIMESTAMP
:
1069 $entity[$fieldName] = '2012-05-20';
1072 //case CRM_Utils_Type::T_DATETIME:
1075 $entity[$fieldName] = '2012-05-20 03:05:20';
1078 case CRM_Utils_Type
::T_STRING
:
1079 case CRM_Utils_Type
::T_BLOB
:
1080 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1081 case CRM_Utils_Type
::T_TEXT
:
1082 case CRM_Utils_Type
::T_LONGTEXT
:
1083 case CRM_Utils_Type
::T_EMAIL
:
1084 $entity[$fieldName] = substr('New String', 0, CRM_Utils_Array
::Value('maxlength', $specs, 100));
1087 case CRM_Utils_Type
::T_INT
:
1088 // probably created with a 1
1089 if ($fieldName == 'weight') {
1090 $entity[$fieldName] = 2;
1092 elseif (!empty($specs['FKClassName'])) {
1093 if ($specs['FKClassName'] == $baoString) {
1094 $entity[$fieldName] = (string) $entity2['id'];
1097 $uniqueName = CRM_Utils_Array
::value('uniqueName', $specs);
1098 if (!empty($entity[$fieldName])) {
1099 $resetFKTo = array($fieldName => $entity[$fieldName]);
1101 $entity[$fieldName] = (string) empty($entity2[$field]) ? CRM_Utils_Array
::value($uniqueName, $entity2) : $entity2[$field];
1102 //todo - there isn't always something set here - & our checking on unset values is limited
1103 if (empty($entity[$field])) {
1104 unset($entity[$field]);
1109 $entity[$fieldName] = '6';
1113 case CRM_Utils_Type
::T_BOOLEAN
:
1114 // probably created with a 1
1115 $entity[$fieldName] = '0';
1118 case CRM_Utils_Type
::T_FLOAT
:
1119 case CRM_Utils_Type
::T_MONEY
:
1120 $entity[$field] = '22.75';
1123 case CRM_Utils_Type
::T_URL
:
1124 $entity[$field] = 'warm.beer.com';
1126 if (!empty($specs['pseudoconstant'])) {
1127 $options = $this->callAPISuccess($entityName, 'getoptions', array('context' => 'create', 'field' => $field));
1128 if (empty($options['values'])) {
1129 //eg. pdf_format id doesn't ship with any
1130 if (isset($specs['pseudoconstant']['optionGroupName'])) {
1131 $optionGroupID = $this->callAPISuccess('option_group', 'getvalue', array(
1132 'name' => 'pdf_format',
1135 $optionValue = $this->callAPISuccess('option_value', 'create', array(
1136 'option_group_id' => $optionGroupID,
1137 'label' => 'new option value'
1139 $options['values'][] = $optionValue['id'];
1142 $entity[$field] = array_rand($options['values']);
1144 $updateParams = array(
1145 'id' => $entity['id'],
1146 $field => isset($entity[$field]) ?
$entity[$field] : NULL,
1148 if (isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1149 //api has special handling on these 2 fields for backward compatibility reasons
1150 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1153 $update = $this->callAPISuccess($entityName, 'create', $updateParams);
1154 $checkParams = array(
1155 'id' => $entity['id'],
1157 'return' => $return,
1159 'sort' => 'id DESC',
1164 $checkEntity = $this->callAPISuccess($entityName, 'getsingle', $checkParams);
1165 $this->assertAPIArrayComparison($entity, $checkEntity, array(), "checking if $fieldName was correctly updated\n" . print_r(array(
1166 'update-params' => $updateParams,
1167 'update-result' => $update,
1168 'getsingle-params' => $checkParams,
1169 'getsingle-result' => $checkEntity,
1170 'expected entity' => $entity
1173 //reset the foreign key fields because otherwise our cleanup routine fails & some other unexpected stuff can kick in
1174 $entity = array_merge($entity, $resetFKTo);
1175 $updateParams = array_merge($updateParams, $resetFKTo);
1176 $this->callAPISuccess($entityName, 'create', $updateParams);
1177 if (isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1178 //api has special handling on these 2 fields for backward compatibility reasons
1179 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1186 /** testing the _getFields **/
1188 /** testing the _delete **/
1191 * @dataProvider toBeSkipped_delete
1192 entities that don't need a delete action
1194 public function testNotImplemented_delete($Entity) {
1195 $nonExistantID = 151416349;
1196 $result = civicrm_api($Entity, 'Delete', array('version' => 3, 'id' => $nonExistantID));
1197 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1198 $this->assertContains(strtolower("API ($Entity, Delete) does not exist"), strtolower($result['error_message']));
1202 * @dataProvider entities
1203 * @expectedException PHPUnit_Framework_Error
1205 public function testWithoutParam_delete($Entity) {
1206 // should delete php complaining that a param is missing
1207 $result = civicrm_api($Entity, 'Delete');
1211 * @dataProvider entities_delete
1213 public function testEmptyParam_delete($Entity) {
1214 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1215 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1218 $result = civicrm_api($Entity, 'Delete', array());
1219 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1220 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
1224 * @dataProvider entities_delete
1226 public function testInvalidID_delete($Entity) {
1227 // turn test off for now
1228 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1230 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1231 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1234 $result = $this->callAPIFailure($Entity, 'Delete', array('id' => 999));
1238 * @dataProvider entities
1240 public function testDeleteWrongTypeParamTag_delete() {
1241 $result = civicrm_api("Tag", 'Delete', 'this is not a string');
1242 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1243 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1247 * Create two entities and make sure delete action only deletes one!
1249 * @dataProvider entities_delete
1251 * limitations include the problem with avoiding loops when creating test objects -
1252 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1253 * Currency - only seems to support US
1255 public function testByID_delete($entityName) {
1256 // turn test off for noew
1257 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1260 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1261 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1264 $startCount = $this->callAPISuccess($entityName, 'getcount', array());
1266 $baos = $this->getMockableBAOObjects($entityName, $createcount);
1267 list($baoObj1, $baoObj2) = $baos;
1269 // make sure exactly 2 exist
1270 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1271 $createcount +
$startCount
1274 $this->callAPISuccess($entityName, 'delete', array('id' => $baoObj2->id
));
1275 //make sure 1 less exists now
1276 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1277 ($createcount +
$startCount) - 1
1280 //make sure id #1 exists
1281 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj1->id
),
1284 //make sure id #2 desn't exist
1285 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj2->id
),
1291 * Create two entities and make sure delete action only deletes one!
1293 * @dataProvider entities_getfields
1295 public function testGetfieldsHasTitle($entity) {
1296 $entities = $this->getEntitiesSupportingCustomFields();
1297 if (in_array($entity, $entities)) {
1298 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entity . 'Test.php');
1300 $actions = $this->callAPISuccess($entity, 'getactions', array());
1301 foreach ($actions['values'] as $action) {
1302 if (substr($action, -7) == '_create' ||
substr($action, -4) == '_get' ||
substr($action, -7) == '_delete') {
1303 //getactions can't distinguish between contribution_page.create & contribution_page.create
1306 $fields = $this->callAPISuccess($entity, 'getfields', array('action' => $action));
1307 if (!empty($ids) && in_array($action, array('create', 'get'))) {
1308 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $fields['values']);
1311 foreach ($fields['values'] as $fieldName => $fieldSpec) {
1312 $this->assertArrayHasKey('title', $fieldSpec, "no title for $entity - $fieldName on action $action");
1313 $this->assertNotEmpty($fieldSpec['title'], "empty title for $entity - $fieldName");
1317 $this->customFieldDelete($ids['custom_field_id']);
1318 $this->customGroupDelete($ids['custom_group_id']);
1325 public function getEntitiesSupportingCustomFields() {
1326 $entities = self
::custom_data_entities_get();
1327 $returnEntities = array();
1328 foreach ($entities as $entityArray) {
1329 $returnEntities[] = $entityArray[0];
1331 return $returnEntities;
1335 * @param string $entityName
1340 private function getMockableBAOObjects($entityName, $count = 2) {
1341 $baoString = _civicrm_api3_get_BAO($entityName);
1342 if (empty($baoString)) {
1343 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1348 while ($i < $count) {
1350 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1351 $this->assertTrue(is_integer($baoObj->id
), 'check first id');
1352 $this->deletableTestObjects
[$baoString][] = $baoObj->id
;
1361 * Verify that HTML metacharacters provided as inputs appear consistently
1364 * At time of writing, the encoding scheme requires (for example) that an
1365 * event title be partially-HTML-escaped before writing to DB. To provide
1366 * consistency, the API must perform extra encoding and decoding on some
1369 * In this example, the event 'title' is subject to encoding, but the
1370 * event 'description' is not.
1372 public function testEncodeDecodeConsistency() {
1374 $createResult = civicrm_api('Event', 'Create', array(
1376 'title' => 'CiviCRM <> TheRest',
1377 'description' => 'TheRest <> CiviCRM',
1378 'event_type_id' => 1,
1380 'start_date' => 20081021,
1382 $this->assertAPISuccess($createResult);
1383 $eventId = $createResult['id'];
1384 $this->assertEquals('CiviCRM <> TheRest', $createResult['values'][$eventId]['title']);
1385 $this->assertEquals('TheRest <> CiviCRM', $createResult['values'][$eventId]['description']);
1387 // Verify "get" handles decoding in result value
1388 $getByIdResult = civicrm_api('Event', 'Get', array(
1392 $this->assertAPISuccess($getByIdResult);
1393 $this->assertEquals('CiviCRM <> TheRest', $getByIdResult['values'][$eventId]['title']);
1394 $this->assertEquals('TheRest <> CiviCRM', $getByIdResult['values'][$eventId]['description']);
1396 // Verify "get" handles encoding in search value
1397 $getByTitleResult = civicrm_api('Event', 'Get', array(
1399 'title' => 'CiviCRM <> TheRest',
1401 $this->assertAPISuccess($getByTitleResult);
1402 $this->assertEquals('CiviCRM <> TheRest', $getByTitleResult['values'][$eventId]['title']);
1403 $this->assertEquals('TheRest <> CiviCRM', $getByTitleResult['values'][$eventId]['description']);
1405 // Verify that "getSingle" handles decoding
1406 $getSingleResult = $this->callAPISuccess('Event', 'GetSingle', array(
1410 $this->assertEquals('CiviCRM <> TheRest', $getSingleResult['title']);
1411 $this->assertEquals('TheRest <> CiviCRM', $getSingleResult['description']);
1413 // Verify that chaining handles decoding
1414 $chainResult = $this->callAPISuccess('Event', 'Get', array(
1416 'api.event.get' => array(),
1418 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['title']);
1419 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['description']);
1420 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['api.event.get']['values'][0]['title']);
1421 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['api.event.get']['values'][0]['description']);
1423 // Verify that "setvalue" handles encoding for updates
1424 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1428 'value' => 'setValueTitle: CiviCRM <> TheRest',
1430 $this->assertAPISuccess($setValueTitleResult);
1431 $this->assertEquals('setValueTitle: CiviCRM <> TheRest', $setValueTitleResult['values']['title']);
1432 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1435 'field' => 'description',
1436 'value' => 'setValueDescription: TheRest <> CiviCRM',
1438 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1439 $this->assertEquals('setValueDescription: TheRest <> CiviCRM', $setValueDescriptionResult['values']['description']);
1443 * Verify that write operations (create/update) use partial HTML-encoding
1445 * In this example, the event 'title' is subject to encoding, but the
1446 * event 'description' is not.
1448 public function testEncodeWrite() {
1450 $createResult = civicrm_api('Event', 'Create', array(
1452 'title' => 'createNew: CiviCRM <> TheRest',
1453 'description' => 'createNew: TheRest <> CiviCRM',
1454 'event_type_id' => 1,
1456 'start_date' => 20081021,
1458 $this->assertAPISuccess($createResult);
1459 $eventId = $createResult['id'];
1460 $this->assertDBQuery('createNew: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1461 1 => array($eventId, 'Integer'),
1463 $this->assertDBQuery('createNew: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1464 1 => array($eventId, 'Integer'),
1467 // Verify that "create" handles encoding for updates
1468 $createWithIdResult = civicrm_api('Event', 'Create', array(
1471 'title' => 'createWithId: CiviCRM <> TheRest',
1472 'description' => 'createWithId: TheRest <> CiviCRM',
1474 $this->assertAPISuccess($createWithIdResult);
1475 $this->assertDBQuery('createWithId: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1476 1 => array($eventId, 'Integer'),
1478 $this->assertDBQuery('createWithId: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1479 1 => array($eventId, 'Integer'),
1482 // Verify that "setvalue" handles encoding for updates
1483 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1487 'value' => 'setValueTitle: CiviCRM <> TheRest',
1489 $this->assertAPISuccess($setValueTitleResult);
1490 $this->assertDBQuery('setValueTitle: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1491 1 => array($eventId, 'Integer'),
1493 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1496 'field' => 'description',
1497 'value' => 'setValueDescription: TheRest <> CiviCRM',
1499 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1500 $this->assertAPISuccess($setValueDescriptionResult);
1501 $this->assertDBQuery('setValueDescription: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1502 1 => array($eventId, 'Integer'),