3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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;
51 * This test case doesn't require DB reset.
53 public $DBResetRequired = FALSE;
58 * Map custom group entities to civicrm components.
60 static $componentMap = array(
61 'Contribution' => 'CiviContribute',
62 'Membership' => 'CiviMember',
63 'Participant' => 'CiviEvent',
64 'Event' => 'CiviEvent',
66 'Pledge' => 'CiviPledge',
67 'Grant' => 'CiviGrant',
68 'Campaign' => 'CiviCampaign',
69 'Survey' => 'CiviCampaign',
75 * There 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)
82 public function setUp() {
84 $this->enableCiviCampaign();
85 $this->toBeImplemented
['get'] = array(
95 $this->toBeImplemented
['create'] = array(
107 $this->toBeImplemented
['delete'] = array(
117 $this->onlyIDNonZeroCount
['get'] = array(
124 $this->deprecatedAPI
= array('Location', 'ActivityType', 'SurveyRespondant');
125 $this->deletableTestObjects
= array();
128 public function tearDown() {
129 foreach ($this->deletableTestObjects
as $entityName => $entities) {
130 foreach ($entities as $entityID) {
131 CRM_Core_DAO
::deleteTestObjects($entityName, array('id' => $entityID));
137 * Generate list of all entities.
144 public static function entities($skip = array()) {
145 // The order of operations in here is screwy. In the case where SYNTAX_CONFORMANCE_ENTITIES is
146 // defined, we should be able to parse+return it immediately. However, some weird dependency
147 // crept into the system where civicrm_api('Entity','get') must be called as part of entities()
148 // (even if its return value is ignored).
150 $tmp = civicrm_api('Entity', 'Get', array('version' => 3));
151 if (getenv('SYNTAX_CONFORMANCE_ENTITIES')) {
153 'values' => explode(' ', getenv('SYNTAX_CONFORMANCE_ENTITIES')),
157 if (!is_array($skip)) {
160 $tmp = array_diff($tmp['values'], $skip);
162 foreach ($tmp as $e) {
163 $entities[] = array($e);
169 * Get list of entities for get test.
173 public static function entities_get() {
174 // all the entities, beside the ones flagged
175 return static::entities(static::toBeSkipped_get(TRUE));
179 * Get entities for create tests.
183 public static function entities_create() {
184 return static::entities(static::toBeSkipped_create(TRUE));
190 public static function entities_updatesingle() {
191 return static::entities(static::toBeSkipped_updatesingle(TRUE));
197 public static function entities_getlimit() {
198 return static::entities(static::toBeSkipped_getlimit());
202 * Generate list of entities that can be retrieved using SQL operator syntax.
206 public static function entities_getSqlOperators() {
207 return static::entities(static::toBeSkipped_getSqlOperators());
213 public static function entities_delete() {
214 return static::entities(static::toBeSkipped_delete(TRUE));
220 public static function entities_getfields() {
221 return static::entities(static::toBeSkipped_getfields(TRUE));
227 public static function custom_data_entities_get() {
228 return static::custom_data_entities();
234 public static function custom_data_entities() {
235 $entities = CRM_Core_BAO_CustomQuery
::$extendsMap;
236 $enabledComponents = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'enable_components', NULL, array());
237 $customDataEntities = array();
238 $invalidEntities = array('Individual', 'Organization', 'Household');
239 $entitiesToFix = array('Case', 'Relationship');
240 foreach ($entities as $entityName => $entity) {
241 if (!in_array($entityName, $invalidEntities)
242 && !in_array($entityName, $entitiesToFix)
244 if (!empty(self
::$componentMap[$entityName]) && empty($enabledComponents[self
::$componentMap[$entityName]])) {
245 CRM_Core_BAO_ConfigSetting
::enableComponent(self
::$componentMap[$entityName]);
247 $customDataEntities[] = array($entityName);
250 return $customDataEntities;
254 * Get entities to be skipped on get tests.
256 * @param bool $sequential
260 public static function toBeSkipped_get($sequential = FALSE) {
261 $entitiesWithoutGet = array(
262 'MailingEventSubscribe',
263 'MailingEventConfirm',
264 'MailingEventResubscribe',
265 'MailingEventUnsubscribe',
268 if ($sequential === TRUE) {
269 return $entitiesWithoutGet;
272 foreach ($entitiesWithoutGet as $e) {
273 $entities[] = array($e);
279 * Get entities to be skipped for get call.
281 * Mailing Contact Just doesn't support id. We have always insisted on finding a way to
282 * support id in API but in this case the underlying tables are crying out for a restructure
283 * & it just doesn't make sense.
285 * User doesn't support get By ID because the user id is actually the CMS user ID & is not part of
286 * CiviCRM - so can only be tested through UserTest - not SyntaxConformanceTest.
288 * @param bool $sequential
291 * Entities that cannot be retrieved by ID
293 public static function toBeSkipped_getByID($sequential = FALSE) {
294 return array('MailingContact', 'User');
298 * @param bool $sequential
302 public static function toBeSkipped_create($sequential = FALSE) {
303 $entitiesWithoutCreate = array('Constant', 'Entity', 'Location', 'Profile', 'MailingRecipients');
304 if ($sequential === TRUE) {
305 return $entitiesWithoutCreate;
308 foreach ($entitiesWithoutCreate as $e) {
309 $entities[] = array($e);
315 * @param bool $sequential
319 public static function toBeSkipped_delete($sequential = FALSE) {
320 $entitiesWithout = array(
322 'MailingEventConfirm',
323 'MailingEventResubscribe',
324 'MailingEventSubscribe',
325 'MailingEventUnsubscribe',
336 if ($sequential === TRUE) {
337 return $entitiesWithout;
340 foreach ($entitiesWithout as $e) {
341 $entities[] = array($e);
347 * @param bool $sequential
350 * @todo add metadata for ALL these entities
352 public static function toBeSkipped_getfields($sequential = FALSE) {
353 $entitiesWithMetadataNotYetFixed = array('ReportTemplate', 'CustomSearch');
354 if ($sequential === TRUE) {
355 return $entitiesWithMetadataNotYetFixed;
358 foreach ($entitiesWithMetadataNotYetFixed as $e) {
359 $entities[] = array($e);
365 * Generate list of entities to test for get by id functions.
366 * @param bool $sequential
368 * Entities to be skipped
370 public static function toBeSkipped_automock($sequential = FALSE) {
371 $entitiesWithoutGet = array(
375 'ParticipantPayment',
384 if ($sequential === TRUE) {
385 return $entitiesWithoutGet;
388 foreach ($entitiesWithoutGet as $e) {
389 $entities[] = array($e);
396 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
397 * @param bool $sequential
400 public static function toBeSkipped_updatesingle($sequential = FALSE) {
401 $entitiesWithout = array(
403 // pseudo-entity; testUpdateSingleValueAlter doesn't introspect properly on it. Multiple magic fields
408 'MailingEventUnsubscribe',
409 'MailingEventSubscribe',
436 'MailingEventConfirm',
440 'MailingEventResubscribe',
448 'ParticipantPayment',
457 //skip this because it doesn't make sense to update logs,
459 if ($sequential === TRUE) {
460 return $entitiesWithout;
463 foreach ($entitiesWithout as $e) {
468 return array('pledge');
473 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
475 public static function toBeSkipped_getlimit() {
476 $entitiesWithout = array(
478 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
480 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
482 // failed 'check that a 5 limit returns 5' - probably is_template field is wrong or something, or could be limit doesn't work right
484 // can't handle creating 25
486 // fails on 5 limit - probably a set up problem
488 //a bit of a pseudoapi - keys by domain
490 return $entitiesWithout;
494 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
496 public static function toBeSkipped_getSqlOperators() {
497 $entitiesWithout = array(
498 'Case', //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
499 'Contact', // on the todo list!
500 'EntityTag', // non-standard api - has inappropriate mandatory fields & doesn't implement limit
501 'Extension', // can't handle creating 25
502 'Note', // note has a default get that isn't implemented in createTestObject -meaning you don't 'get' them
503 'Setting', //a bit of a pseudoapi - keys by domain
505 return $entitiesWithout;
514 public function getKnownUnworkablesUpdateSingle($entity, $key) {
515 // can't update values are values for which updates don't result in the value being changed
516 $knownFailures = array(
517 'ActionSchedule' => array(
518 'cant_update' => array(
522 'ActivityContact' => array(
523 'cant_update' => array(
525 //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
529 'cant_update' => array(
530 'state_province_id', //issues with country id - need to ensure same country
531 'master_id', //creates relationship
533 'cant_return' => array(),
536 'cant_update' => array(
537 'entity_table', // believe this field is defined in error
539 'cant_return' => array(
544 'cant_update' => array(
548 'MembershipBlock' => array(
549 'cant_update' => array(
550 // The fake/auto-generated values leave us unable to properly cleanup fake data
555 'ContributionSoft' => array(
556 'cant_update' => array(
557 // can't be changed through api
562 'cant_update' => array(
563 'pledge_original_installment_amount',
565 'original_installment_amount',
567 'amount', // can't be changed through API,
569 'break_return' => array(// if these are passed in they are retrieved from the wrong table
572 'contribution_page_id',
573 'financial_account_id',
577 'cant_return' => array(// can't be retrieved from api
578 'honor_type_id', //due to uniquename missing
586 'initial_reminder_day',
587 'additional_reminder_day',
589 'pledge_contribution_page_id',
591 'pledge_campaign_id',
592 'pledge_financial_type_id',
595 'PaymentProcessorType' => array(
596 'cant_update' => array(
599 'break_return' => array(),
600 'cant_return' => array(),
602 'PriceFieldValue' => array(
603 'cant_update' => array(
604 'weight', //won't update as there is no 1 in the same price set
608 if (empty($knownFailures[$entity]) ||
empty($knownFailures[$entity][$key])) {
611 return $knownFailures[$entity][$key];
614 /* ----- testing the _get ----- */
617 * @dataProvider toBeSkipped_get
618 * Entities that don't need a get action
621 public function testNotImplemented_get($Entity) {
622 $result = civicrm_api($Entity, 'Get', array('version' => 3));
623 $this->assertEquals(1, $result['is_error']);
624 // $this->assertContains("API ($Entity, Get) does not exist", $result['error_message']);
625 $this->assertRegExp('/API (.*) does not exist/', $result['error_message']);
629 * @dataProvider entities
630 * @expectedException PHPUnit_Framework_Error
633 public function testWithoutParam_get($Entity) {
634 // should get php complaining that a param is missing
635 $result = civicrm_api($Entity, 'Get');
639 * @dataProvider entities
642 public function testGetFields($Entity) {
643 if (in_array($Entity, $this->deprecatedAPI
) ||
$Entity == 'Entity' ||
$Entity == 'CustomValue') {
647 $result = civicrm_api($Entity, 'getfields', array('version' => 3));
648 $this->assertTrue(is_array($result['values']), "$Entity ::get fields doesn't return values array in line " . __LINE__
);
649 foreach ($result['values'] as $key => $value) {
650 $this->assertTrue(is_array($value), $Entity . "::" . $key . " is not an array in line " . __LINE__
);
655 * @dataProvider entities_get
658 public function testEmptyParam_get($Entity) {
660 if (in_array($Entity, $this->toBeImplemented
['get'])) {
661 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
664 $result = civicrm_api($Entity, 'Get', array());
665 $this->assertEquals(1, $result['is_error']);
666 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
670 * @dataProvider entities_get
673 public function testEmptyParam_getString($Entity) {
675 if (in_array($Entity, $this->toBeImplemented
['get'])) {
676 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
679 $result = $this->callAPIFailure($Entity, 'Get', 'string');
680 $this->assertEquals(2000, $result['error_code']);
681 $this->assertEquals('Input variable `params` is not an array', $result['error_message']);
685 * @dataProvider entities_get
686 * @Xdepends testEmptyParam_get // no need to test the simple if the empty doesn't work/is skipped. doesn't seem to work
689 public function testSimple_get($Entity) {
690 // $this->markTestSkipped("test gives core error on test server (but not on our locals). Skip until we can get server to pass");
691 if (in_array($Entity, $this->toBeImplemented
['get'])) {
694 $result = civicrm_api($Entity, 'Get', array('version' => 3));
695 // @TODO: list the get that have mandatory params
696 if ($result['is_error']) {
697 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
698 // either id or contact_id or entity_id is one of the field missing
699 $this->assertContains("id", $result['error_message']);
702 $this->assertEquals(3, $result['version']);
703 $this->assertArrayHasKey('count', $result);
704 $this->assertArrayHasKey('values', $result);
709 * @dataProvider custom_data_entities_get
712 public function testCustomDataGet($entityName) {
713 $this->createLoggedInUser();// so subsidiary activities are created
714 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entityName . 'Test.php');
715 $customFieldName = 'custom_' . $ids['custom_field_id'];
716 $objects = $this->getMockableBAOObjects($entityName, 1);
717 $params = array('id' => $objects[0]->id
, 'custom_' . $ids['custom_field_id'] => "custom string");
718 $result = $this->callAPISuccess($entityName, 'create', $params);
720 $getParams = array('id' => $result['id'], 'return' => array($customFieldName));
721 $check = $this->callAPISuccess($entityName, 'get', $getParams);
722 $this->assertEquals("custom string", $check['values'][$check['id']][$customFieldName]);
724 $this->customFieldDelete($ids['custom_field_id']);
725 $this->customGroupDelete($ids['custom_group_id']);
726 $this->callAPISuccess($entityName, 'delete', array('id' => $result['id']));
727 $this->quickCleanup(array('civicrm_uf_match'));
731 * @dataProvider entities_get
734 public function testAcceptsOnlyID_get($Entity) {
735 // big random number. fun fact: if you multiply it by pi^e, the result is another random number, but bigger ;)
736 $nonExistantID = 30867307034;
737 if (in_array($Entity, $this->toBeImplemented
['get'])
738 ||
in_array($Entity, $this->toBeSkipped_getByID())
744 // the below function returns different values and hence an early return
745 // we'll fix this once beta1 is released
748 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
750 if ($result['is_error']) {
751 // just to get a clearer message in the log
752 $this->assertEquals("only id should be enough", $result['error_message']);
754 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
755 $this->assertEquals(0, $result['count']);
760 * Create two entities and make sure we can fetch them individually by ID.
762 * @dataProvider entities_get
764 * limitations include the problem with avoiding loops when creating test objects -
765 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
766 * Currency - only seems to support US
769 public function testByID_get($entityName) {
770 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
771 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
775 $baos = $this->getMockableBAOObjects($entityName);
776 list($baoObj1, $baoObj2) = $baos;
779 $result = $this->callAPISuccess($entityName, 'get', array(
780 'id' => $baoObj1->id
,
783 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
784 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
785 $this->assertEquals(1, count($result['values']));
787 // fetch second by ID
788 $result = $this->callAPISuccess($entityName, 'get', array(
789 'id' => $baoObj2->id
,
791 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
792 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
793 $this->assertEquals(1, count($result['values']));
797 * Ensure that the "get" operation accepts limiting the #result records.
799 * TODO Consider making a separate entity list ("entities_getlimit")
800 * For the moment, the "entities_updatesingle" list should give a good
801 * sense for which entities support createTestObject
803 * @dataProvider entities_getlimit
805 * @param string $entityName
807 public function testLimit($entityName) {
808 $cases = array(); // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
810 array('options' => array('limit' => NULL)),
812 'check that a NULL limit returns unlimited',
815 array('options' => array('limit' => FALSE)),
817 'check that a FALSE limit returns unlimited',
820 array('options' => array('limit' => 0)),
822 'check that a 0 limit returns unlimited',
825 array('options' => array('limit' => 5)),
827 'check that a 5 limit returns 5',
832 'check that no limit returns 25',
835 $baoString = _civicrm_api3_get_BAO($entityName);
836 if (empty($baoString)) {
837 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
841 // make 30 test items -- 30 > 25 (the default limit)
843 for ($i = 0; $i < 30; $i++
) {
844 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
845 $ids[] = $baoObj->id
;
848 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
849 foreach ($cases as $case) {
850 $this->checkLimitAgainstExpected($entityName, $case[0], $case[1], $case[2]);
852 //non preferred / legacy syntax
853 if (isset($case[0]['options']['limit'])) {
854 $this->checkLimitAgainstExpected($entityName, array('rowCount' => $case[0]['options']['limit']), $case[1], $case[2]);
855 $this->checkLimitAgainstExpected($entityName, array('option_limit' => $case[0]['options']['limit']), $case[1], $case[2]);
856 $this->checkLimitAgainstExpected($entityName, array('option.limit' => $case[0]['options']['limit']), $case[1], $case[2]);
859 foreach ($ids as $id) {
860 CRM_Core_DAO
::deleteTestObjects($baoString, array('id' => $id));
866 * Ensure that the "get" operation accepts limiting the #result records.
868 * @dataProvider entities_getSqlOperators
870 * @param string $entityName
872 public function testSqlOperators($entityName) {
873 $baoString = _civicrm_api3_get_BAO($entityName);
874 if (empty($baoString)) {
875 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
878 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0), 'return' => 'id'));
879 $entities = array_keys($entities['values']);
880 $totalEntities = count($entities);
881 if ($totalEntities < 3) {
883 for ($i = 0; $i < 3 - $totalEntities; $i++
) {
884 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
885 $ids[] = $baoObj->id
;
889 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0)));
890 $entities = array_keys($entities['values']);
891 $this->assertGreaterThan(2, $totalEntities);
892 $this->callAPISuccess($entityName, 'getsingle', array('id' => array('IN' => array($entities[0]))));
893 $this->callAPISuccessGetCount($entityName, array('id' => array('NOT IN' => array($entities[0]))), $totalEntities - 1);
894 $this->callAPISuccessGetCount($entityName, array('id' => array('>' => $entities[0])), $totalEntities - 1);
898 * Check that get fetches an appropriate number of results.
900 * @param string $entityName
901 * Name of entity to test.
902 * @param array $params
904 * @param string $message
906 public function checkLimitAgainstExpected($entityName, $params, $limit, $message) {
907 $result = $this->callAPISuccess($entityName, 'get', $params);
909 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
910 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
913 $this->assertEquals($limit, $result['count'], $message);
914 $this->assertEquals($limit, count($result['values']), $message);
919 * Create two entities and make sure we can fetch them individually by ID (e.g. using "contact_id=>2"
922 * @dataProvider entities_get
924 * limitations include the problem with avoiding loops when creating test objects -
925 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
926 * Currency - only seems to support US
928 * @throws \PHPUnit_Framework_IncompleteTestError
930 public function testByIDAlias_get($entityName) {
931 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
932 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
936 $baoString = _civicrm_api3_get_BAO($entityName);
937 if (empty($baoString)) {
938 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
942 $idFieldName = _civicrm_api_get_entity_name_from_camel($entityName) . '_id';
945 $baoObj1 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
946 $this->assertTrue(is_int($baoObj1->id
), 'check first id');
947 $this->deletableTestObjects
[$baoString][] = $baoObj1->id
;
948 $baoObj2 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
949 $this->assertTrue(is_int($baoObj2->id
), 'check second id');
950 $this->deletableTestObjects
[$baoString][] = $baoObj2->id
;
953 $result = civicrm_api($entityName, 'get', array(
955 $idFieldName => $baoObj1->id
,
957 $this->assertAPISuccess($result);
958 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
959 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
960 $this->assertEquals(1, count($result['values']));
962 // fetch second by ID
963 $result = civicrm_api($entityName, 'get', array(
965 $idFieldName => $baoObj2->id
,
967 $this->assertAPISuccess($result);
968 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
969 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
970 $this->assertEquals(1, count($result['values']));
974 * @dataProvider entities_get
977 public function testNonExistantID_get($Entity) {
978 // cf testAcceptsOnlyID_get
979 $nonExistantID = 30867307034;
980 if (in_array($Entity, $this->toBeImplemented
['get'])) {
984 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
986 // redundant with testAcceptsOnlyID_get
987 if ($result['is_error']) {
991 $this->assertArrayHasKey('version', $result);
992 $this->assertEquals(3, $result['version']);
993 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
994 $this->assertEquals(0, $result['count']);
998 /* ---- testing the _create ---- */
1001 * @dataProvider toBeSkipped_create
1002 entities that don't need a create action
1005 public function testNotImplemented_create($Entity) {
1006 $result = civicrm_api($Entity, 'Create', array('version' => 3));
1007 $this->assertEquals(1, $result['is_error']);
1008 $this->assertContains(strtolower("API ($Entity, Create) does not exist"), strtolower($result['error_message']));
1012 * @dataProvider entities
1013 * @expectedException PHPUnit_Framework_Error
1016 public function testWithoutParam_create($Entity) {
1017 // should create php complaining that a param is missing
1018 $result = civicrm_api($Entity, 'Create');
1022 * @dataProvider entities_create
1024 * @throws \PHPUnit_Framework_IncompleteTestError
1026 public function testEmptyParam_create($Entity) {
1027 $this->markTestIncomplete("fixing this test to test the api functions fails on numerous tests
1028 which will either create a completely blank entity (batch, participant status) or
1029 have a damn good crack at it (e.g mailing job). Marking this as incomplete beats false success");
1031 if (in_array($Entity, $this->toBeImplemented
['create'])) {
1032 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1035 $result = $this->callAPIFailure($Entity, 'Create', array());
1036 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
1040 * @dataProvider entities_create
1042 * Check that create doesn't work with an invalid
1044 * @throws \PHPUnit_Framework_IncompleteTestError
1046 public function testInvalidID_create($Entity) {
1047 // turn test off for noew
1048 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1050 if (in_array($Entity, $this->toBeImplemented
['create'])) {
1051 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1054 $result = $this->callAPIFailure($Entity, 'Create', array('id' => 999));
1058 * @dataProvider entities
1060 public function testCreateWrongTypeParamTag_create() {
1061 $result = civicrm_api("Tag", 'Create', 'this is not a string');
1062 $this->assertEquals(1, $result['is_error']);
1063 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1067 * @dataProvider entities_updatesingle
1069 * limitations include the problem with avoiding loops when creating test objects -
1070 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1071 * Currency - only seems to support US
1072 * @param $entityName
1074 public function testCreateSingleValueAlter($entityName) {
1075 if (in_array($entityName, $this->toBeImplemented
['create'])) {
1076 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1080 $baoString = _civicrm_api3_get_BAO($entityName);
1081 $this->assertNotEmpty($baoString, $entityName);
1082 $this->assertNotEmpty($entityName, $entityName);
1083 $fieldsGet = $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'get', 'options' => array('get_options' => 'all')));
1084 if ($entityName != 'Pledge') {
1085 $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'create', 'options' => array('get_options' => 'all')));
1087 $fields = $fields['values'];
1088 $return = array_keys($fieldsGet['values']);
1089 $valuesNotToReturn = $this->getKnownUnworkablesUpdateSingle($entityName, 'break_return');
1090 // these can't be requested as return values
1091 $entityValuesThatDoNotWork = array_merge(
1092 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_update'),
1093 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_return'),
1097 $return = array_diff($return, $valuesNotToReturn);
1098 $baoObj = new CRM_Core_DAO();
1099 $baoObj->createTestObject($baoString, array('currency' => 'USD'), 2, 0);
1101 $getEntities = $this->callAPISuccess($entityName, 'get', array(
1103 'return' => $return,
1105 'sort' => 'id DESC',
1110 // lets use first rather than assume only one exists
1111 $entity = $getEntities['values'][0];
1112 $entity2 = $getEntities['values'][1];
1113 $this->deletableTestObjects
[$baoString][] = $entity['id'];
1114 $this->deletableTestObjects
[$baoString][] = $entity2['id'];
1115 foreach ($fields as $field => $specs) {
1117 $fieldName = $field;
1118 if (!empty($specs['uniquename'])) {
1119 $fieldName = $specs['uniquename'];
1121 if ($field == 'currency' ||
$field == 'id' ||
$field == strtolower($entityName) . '_id'
1122 ||
in_array($field, $entityValuesThatDoNotWork)
1124 //@todo id & entity_id are correct but we should fix currency & frequency_day
1127 $this->assertArrayHasKey('type', $specs, "the _spec function for $entityName field $field does not specify the type");
1128 switch ($specs['type']) {
1129 case CRM_Utils_Type
::T_DATE
:
1130 $entity[$fieldName] = '2012-05-20';
1133 case CRM_Utils_Type
::T_TIMESTAMP
:
1135 $entity[$fieldName] = '2012-05-20 03:05:20';
1138 case CRM_Utils_Type
::T_STRING
:
1139 case CRM_Utils_Type
::T_BLOB
:
1140 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1141 case CRM_Utils_Type
::T_TEXT
:
1142 case CRM_Utils_Type
::T_LONGTEXT
:
1143 case CRM_Utils_Type
::T_EMAIL
:
1144 $entity[$fieldName] = substr('New String', 0, CRM_Utils_Array
::Value('maxlength', $specs, 100));
1147 case CRM_Utils_Type
::T_INT
:
1148 // probably created with a 1
1149 if ($fieldName == 'weight') {
1150 $entity[$fieldName] = 2;
1152 elseif (!empty($specs['FKClassName'])) {
1153 if ($specs['FKClassName'] == $baoString) {
1154 $entity[$fieldName] = (string) $entity2['id'];
1157 $uniqueName = CRM_Utils_Array
::value('uniqueName', $specs);
1158 if (!empty($entity[$fieldName])) {
1159 $resetFKTo = array($fieldName => $entity[$fieldName]);
1161 $entity[$fieldName] = (string) empty($entity2[$field]) ? CRM_Utils_Array
::value($uniqueName, $entity2) : $entity2[$field];
1162 //todo - there isn't always something set here - & our checking on unset values is limited
1163 if (empty($entity[$field])) {
1164 unset($entity[$field]);
1169 $entity[$fieldName] = '6';
1173 case CRM_Utils_Type
::T_BOOLEAN
:
1174 // probably created with a 1
1175 $entity[$fieldName] = '0';
1178 case CRM_Utils_Type
::T_FLOAT
:
1179 case CRM_Utils_Type
::T_MONEY
:
1180 $entity[$field] = '22.75';
1183 case CRM_Utils_Type
::T_URL
:
1184 $entity[$field] = 'warm.beer.com';
1186 if (empty($specs['FKClassName']) && (!empty($specs['pseudoconstant']) ||
!empty($specs['options']))) {
1187 $options = CRM_Utils_Array
::value('options', $specs, array());
1189 //eg. pdf_format id doesn't ship with any
1190 if (isset($specs['pseudoconstant']['optionGroupName'])) {
1191 $optionValue = $this->callAPISuccess('option_value', 'create', array(
1192 'option_group_id' => $specs['pseudoconstant']['optionGroupName'],
1193 'label' => 'new option value',
1196 $optionValue = $optionValue['values'];
1197 $options[$optionValue[0]['value']] = 'new option value';
1200 $entity[$field] = array_rand($options);
1202 if (!empty($specs['FKClassName']) && !empty($specs['pseudoconstant'])) {
1203 // in the weird situation where a field has both an fk and pseudoconstant defined,
1204 // e.g. campaign_id field, need to flush caches.
1205 // FIXME: Why doesn't creating a campaign clear caches?
1206 civicrm_api3($entityName, 'getfields', array('cache_clear' => 1));
1208 $updateParams = array(
1209 'id' => $entity['id'],
1210 $field => isset($entity[$field]) ?
$entity[$field] : NULL,
1212 if (isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1213 //api has special handling on these 2 fields for backward compatibility reasons
1214 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1217 $update = $this->callAPISuccess($entityName, 'create', $updateParams);
1218 $checkParams = array(
1219 'id' => $entity['id'],
1221 'return' => $return,
1223 'sort' => 'id DESC',
1228 $checkEntity = $this->callAPISuccess($entityName, 'getsingle', $checkParams);
1229 $this->assertAPIArrayComparison($entity, $checkEntity, array(), "checking if $fieldName was correctly updated\n" . print_r(array(
1230 'update-params' => $updateParams,
1231 'update-result' => $update,
1232 'getsingle-params' => $checkParams,
1233 'getsingle-result' => $checkEntity,
1234 'expected entity' => $entity,
1237 //reset the foreign key fields because otherwise our cleanup routine fails & some other unexpected stuff can kick in
1238 $entity = array_merge($entity, $resetFKTo);
1239 $updateParams = array_merge($updateParams, $resetFKTo);
1240 $this->callAPISuccess($entityName, 'create', $updateParams);
1241 if (isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1242 //api has special handling on these 2 fields for backward compatibility reasons
1243 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1250 /* ---- testing the _getFields ---- */
1252 /* ---- testing the _delete ---- */
1255 * @dataProvider toBeSkipped_delete
1256 entities that don't need a delete action
1259 public function testNotImplemented_delete($Entity) {
1260 $nonExistantID = 151416349;
1261 $result = civicrm_api($Entity, 'Delete', array('version' => 3, 'id' => $nonExistantID));
1262 $this->assertEquals(1, $result['is_error']);
1263 $this->assertContains(strtolower("API ($Entity, Delete) does not exist"), strtolower($result['error_message']));
1267 * @dataProvider entities
1268 * @expectedException PHPUnit_Framework_Error
1271 public function testWithoutParam_delete($Entity) {
1272 // should delete php complaining that a param is missing
1273 $result = civicrm_api($Entity, 'Delete');
1277 * @dataProvider entities_delete
1280 public function testEmptyParam_delete($Entity) {
1281 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1282 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1285 $result = civicrm_api($Entity, 'Delete', array());
1286 $this->assertEquals(1, $result['is_error']);
1287 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
1291 * @dataProvider entities_delete
1293 * @throws \PHPUnit_Framework_IncompleteTestError
1295 public function testInvalidID_delete($Entity) {
1296 // turn test off for now
1297 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1299 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1300 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1303 $result = $this->callAPIFailure($Entity, 'Delete', array('id' => 999));
1307 * @dataProvider entities
1309 public function testDeleteWrongTypeParamTag_delete() {
1310 $result = civicrm_api("Tag", 'Delete', 'this is not a string');
1311 $this->assertEquals(1, $result['is_error']);
1312 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1316 * Create two entities and make sure delete action only deletes one!
1318 * @dataProvider entities_delete
1320 * limitations include the problem with avoiding loops when creating test objects -
1321 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1322 * Currency - only seems to support US
1323 * @param $entityName
1324 * @throws \PHPUnit_Framework_IncompleteTestError
1326 public function testByID_delete($entityName) {
1327 // turn test off for noew
1328 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1331 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1332 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1335 $startCount = $this->callAPISuccess($entityName, 'getcount', array());
1337 $baos = $this->getMockableBAOObjects($entityName, $createcount);
1338 list($baoObj1, $baoObj2) = $baos;
1340 // make sure exactly 2 exist
1341 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1342 $createcount +
$startCount
1345 $this->callAPISuccess($entityName, 'delete', array('id' => $baoObj2->id
));
1346 //make sure 1 less exists now
1347 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1348 ($createcount +
$startCount) - 1
1351 //make sure id #1 exists
1352 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj1->id
),
1355 //make sure id #2 desn't exist
1356 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj2->id
),
1362 * Create two entities and make sure delete action only deletes one!
1364 * @dataProvider entities_getfields
1367 public function testGetfieldsHasTitle($entity) {
1368 $entities = $this->getEntitiesSupportingCustomFields();
1369 if (in_array($entity, $entities)) {
1370 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entity . 'Test.php');
1372 $actions = $this->callAPISuccess($entity, 'getactions', array());
1373 foreach ($actions['values'] as $action) {
1374 if (substr($action, -7) == '_create' ||
substr($action, -4) == '_get' ||
substr($action, -7) == '_delete') {
1375 //getactions can't distinguish between contribution_page.create & contribution_page.create
1378 $fields = $this->callAPISuccess($entity, 'getfields', array('action' => $action));
1379 if (!empty($ids) && in_array($action, array('create', 'get'))) {
1380 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $fields['values']);
1383 foreach ($fields['values'] as $fieldName => $fieldSpec) {
1384 $this->assertArrayHasKey('title', $fieldSpec, "no title for $entity - $fieldName on action $action");
1385 $this->assertNotEmpty($fieldSpec['title'], "empty title for $entity - $fieldName");
1389 $this->customFieldDelete($ids['custom_field_id']);
1390 $this->customGroupDelete($ids['custom_group_id']);
1397 public function getEntitiesSupportingCustomFields() {
1398 $entities = self
::custom_data_entities_get();
1399 $returnEntities = array();
1400 foreach ($entities as $entityArray) {
1401 $returnEntities[] = $entityArray[0];
1403 return $returnEntities;
1407 * @param string $entityName
1412 private function getMockableBAOObjects($entityName, $count = 2) {
1413 $baoString = _civicrm_api3_get_BAO($entityName);
1414 if (empty($baoString)) {
1415 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1420 while ($i < $count) {
1422 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1423 $this->assertTrue(is_int($baoObj->id
), 'check first id');
1424 $this->deletableTestObjects
[$baoString][] = $baoObj->id
;
1433 * Verify that HTML metacharacters provided as inputs appear consistently.
1436 * At time of writing, the encoding scheme requires (for example) that an
1437 * event title be partially-HTML-escaped before writing to DB. To provide
1438 * consistency, the API must perform extra encoding and decoding on some
1441 * In this example, the event 'title' is subject to encoding, but the
1442 * event 'description' is not.
1444 public function testEncodeDecodeConsistency() {
1446 $createResult = civicrm_api('Event', 'Create', array(
1448 'title' => 'CiviCRM <> TheRest',
1449 'description' => 'TheRest <> CiviCRM',
1450 'event_type_id' => 1,
1452 'start_date' => 20081021,
1454 $this->assertAPISuccess($createResult);
1455 $eventId = $createResult['id'];
1456 $this->assertEquals('CiviCRM <> TheRest', $createResult['values'][$eventId]['title']);
1457 $this->assertEquals('TheRest <> CiviCRM', $createResult['values'][$eventId]['description']);
1459 // Verify "get" handles decoding in result value
1460 $getByIdResult = civicrm_api('Event', 'Get', array(
1464 $this->assertAPISuccess($getByIdResult);
1465 $this->assertEquals('CiviCRM <> TheRest', $getByIdResult['values'][$eventId]['title']);
1466 $this->assertEquals('TheRest <> CiviCRM', $getByIdResult['values'][$eventId]['description']);
1468 // Verify "get" handles encoding in search value
1469 $getByTitleResult = civicrm_api('Event', 'Get', array(
1471 'title' => 'CiviCRM <> TheRest',
1473 $this->assertAPISuccess($getByTitleResult);
1474 $this->assertEquals('CiviCRM <> TheRest', $getByTitleResult['values'][$eventId]['title']);
1475 $this->assertEquals('TheRest <> CiviCRM', $getByTitleResult['values'][$eventId]['description']);
1477 // Verify that "getSingle" handles decoding
1478 $getSingleResult = $this->callAPISuccess('Event', 'GetSingle', array(
1482 $this->assertEquals('CiviCRM <> TheRest', $getSingleResult['title']);
1483 $this->assertEquals('TheRest <> CiviCRM', $getSingleResult['description']);
1485 // Verify that chaining handles decoding
1486 $chainResult = $this->callAPISuccess('Event', 'Get', array(
1488 'api.event.get' => array(),
1490 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['title']);
1491 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['description']);
1492 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['api.event.get']['values'][0]['title']);
1493 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['api.event.get']['values'][0]['description']);
1495 // Verify that "setvalue" handles encoding for updates
1496 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1500 'value' => 'setValueTitle: CiviCRM <> TheRest',
1502 $this->assertAPISuccess($setValueTitleResult);
1503 $this->assertEquals('setValueTitle: CiviCRM <> TheRest', $setValueTitleResult['values']['title']);
1504 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1507 'field' => 'description',
1508 'value' => 'setValueDescription: TheRest <> CiviCRM',
1510 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1511 $this->assertEquals('setValueDescription: TheRest <> CiviCRM', $setValueDescriptionResult['values']['description']);
1515 * Verify that write operations (create/update) use partial HTML-encoding
1517 * In this example, the event 'title' is subject to encoding, but the
1518 * event 'description' is not.
1520 public function testEncodeWrite() {
1522 $createResult = civicrm_api('Event', 'Create', array(
1524 'title' => 'createNew: CiviCRM <> TheRest',
1525 'description' => 'createNew: TheRest <> CiviCRM',
1526 'event_type_id' => 1,
1528 'start_date' => 20081021,
1530 $this->assertAPISuccess($createResult);
1531 $eventId = $createResult['id'];
1532 $this->assertDBQuery('createNew: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1533 1 => array($eventId, 'Integer'),
1535 $this->assertDBQuery('createNew: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1536 1 => array($eventId, 'Integer'),
1539 // Verify that "create" handles encoding for updates
1540 $createWithIdResult = civicrm_api('Event', 'Create', array(
1543 'title' => 'createWithId: CiviCRM <> TheRest',
1544 'description' => 'createWithId: TheRest <> CiviCRM',
1546 $this->assertAPISuccess($createWithIdResult);
1547 $this->assertDBQuery('createWithId: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1548 1 => array($eventId, 'Integer'),
1550 $this->assertDBQuery('createWithId: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1551 1 => array($eventId, 'Integer'),
1554 // Verify that "setvalue" handles encoding for updates
1555 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1559 'value' => 'setValueTitle: CiviCRM <> TheRest',
1561 $this->assertAPISuccess($setValueTitleResult);
1562 $this->assertDBQuery('setValueTitle: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1563 1 => array($eventId, 'Integer'),
1565 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1568 'field' => 'description',
1569 'value' => 'setValueDescription: TheRest <> CiviCRM',
1571 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1572 $this->assertAPISuccess($setValueDescriptionResult);
1573 $this->assertDBQuery('setValueDescription: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1574 1 => array($eventId, 'Integer'),