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;
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(
106 $this->toBeImplemented
['delete'] = array(
116 $this->onlyIDNonZeroCount
['get'] = array(
122 $this->deprecatedAPI
= array('Location', 'ActivityType', 'SurveyRespondant');
123 $this->deletableTestObjects
= array();
126 public function tearDown() {
127 foreach ($this->deletableTestObjects
as $entityName => $entities) {
128 foreach ($entities as $entityID) {
129 CRM_Core_DAO
::deleteTestObjects($entityName, array('id' => $entityID));
135 * Generate list of all entities.
142 public static function entities($skip = array()) {
143 // The order of operations in here is screwy. In the case where SYNTAX_CONFORMANCE_ENTITIES is
144 // defined, we should be able to parse+return it immediately. However, some weird dependency
145 // crept into the system where civicrm_api('Entity','get') must be called as part of entities()
146 // (even if its return value is ignored).
148 $tmp = civicrm_api('Entity', 'Get', array('version' => 3));
149 if (getenv('SYNTAX_CONFORMANCE_ENTITIES')) {
151 'values' => explode(' ', getenv('SYNTAX_CONFORMANCE_ENTITIES')),
155 if (!is_array($skip)) {
158 $tmp = array_diff($tmp['values'], $skip);
160 foreach ($tmp as $e) {
161 $entities[] = array($e);
167 * Get list of entities for get test.
171 public static function entities_get() {
172 // all the entities, beside the ones flagged
173 return static::entities(static::toBeSkipped_get(TRUE));
177 * Get entities for create tests.
181 public static function entities_create() {
182 return static::entities(static::toBeSkipped_create(TRUE));
188 public static function entities_updatesingle() {
189 return static::entities(static::toBeSkipped_updatesingle(TRUE));
195 public static function entities_getlimit() {
196 return static::entities(static::toBeSkipped_getlimit());
200 * Generate list of entities that can be retrieved using SQL operator syntax.
204 public static function entities_getSqlOperators() {
205 return static::entities(static::toBeSkipped_getSqlOperators());
211 public static function entities_delete() {
212 return static::entities(static::toBeSkipped_delete(TRUE));
218 public static function entities_getfields() {
219 return static::entities(static::toBeSkipped_getfields(TRUE));
225 public static function custom_data_entities_get() {
226 return static::custom_data_entities();
232 public static function custom_data_entities() {
233 $entities = CRM_Core_BAO_CustomQuery
::$extendsMap;
234 $enabledComponents = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'enable_components', NULL, array());
235 $customDataEntities = array();
236 $invalidEntities = array('Individual', 'Organization', 'Household');
237 $entitiesToFix = array('Case', 'Relationship');
238 foreach ($entities as $entityName => $entity) {
239 if (!in_array($entityName, $invalidEntities)
240 && !in_array($entityName, $entitiesToFix)
242 if (!empty(self
::$componentMap[$entityName]) && empty($enabledComponents[self
::$componentMap[$entityName]])) {
243 CRM_Core_BAO_ConfigSetting
::enableComponent(self
::$componentMap[$entityName]);
245 $customDataEntities[] = array($entityName);
248 return $customDataEntities;
252 * Get entities to be skipped on get tests.
254 * @param bool $sequential
258 public static function toBeSkipped_get($sequential = FALSE) {
259 $entitiesWithoutGet = array(
260 'MailingEventSubscribe',
261 'MailingEventConfirm',
262 'MailingEventResubscribe',
263 'MailingEventUnsubscribe',
266 if ($sequential === TRUE) {
267 return $entitiesWithoutGet;
270 foreach ($entitiesWithoutGet as $e) {
271 $entities[] = array($e);
277 * Get entities to be skipped for get call.
279 * Mailing Contact Just doesn't support id. We have always insisted on finding a way to
280 * support id in API but in this case the underlying tables are crying out for a restructure
281 * & it just doesn't make sense, on the otherhand Event need id to be existant as pseudo property
282 * is been associated with it, so we need to bypass for get api otherwise it will through pseudo_match validation
284 * @param bool $sequential
287 * Entities that cannot be retrieved by ID
289 public static function toBeSkipped_getByID($sequential = FALSE) {
290 return array('MailingContact', 'Event');
294 * @param bool $sequential
298 public static function toBeSkipped_create($sequential = FALSE) {
299 $entitiesWithoutCreate = array('Constant', 'Entity', 'Location', 'Profile', 'MailingRecipients');
300 if ($sequential === TRUE) {
301 return $entitiesWithoutCreate;
304 foreach ($entitiesWithoutCreate as $e) {
305 $entities[] = array($e);
311 * @param bool $sequential
315 public static function toBeSkipped_delete($sequential = FALSE) {
316 $entitiesWithout = array(
318 'MailingEventConfirm',
319 'MailingEventResubscribe',
320 'MailingEventSubscribe',
321 'MailingEventUnsubscribe',
331 if ($sequential === TRUE) {
332 return $entitiesWithout;
335 foreach ($entitiesWithout as $e) {
336 $entities[] = array($e);
342 * @param bool $sequential
345 * @todo add metadata for ALL these entities
347 public static function toBeSkipped_getfields($sequential = FALSE) {
348 $entitiesWithMetadataNotYetFixed = array('ReportTemplate', 'CustomSearch');
349 if ($sequential === TRUE) {
350 return $entitiesWithMetadataNotYetFixed;
353 foreach ($entitiesWithMetadataNotYetFixed as $e) {
354 $entities[] = array($e);
360 * Generate list of entities to test for get by id functions
361 * @param bool $sequential
363 * Entities to be skipped
365 public static function toBeSkipped_automock($sequential = FALSE) {
366 $entitiesWithoutGet = array(
370 'ParticipantPayment',
379 if ($sequential === TRUE) {
380 return $entitiesWithoutGet;
383 foreach ($entitiesWithoutGet as $e) {
384 $entities[] = array($e);
391 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
392 * @param bool $sequential
395 public static function toBeSkipped_updatesingle($sequential = FALSE) {
396 $entitiesWithout = array(
398 // pseudo-entity; testUpdateSingleValueAlter doesn't introspect properly on it. Multiple magic fields
403 'MailingEventUnsubscribe',
404 'MailingEventSubscribe',
431 'MailingEventConfirm',
435 'MailingEventResubscribe',
443 'ParticipantPayment',
452 //skip this because it doesn't make sense to update logs,
454 if ($sequential === TRUE) {
455 return $entitiesWithout;
458 foreach ($entitiesWithout as $e) {
463 return array('pledge');
468 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
470 public static function toBeSkipped_getlimit() {
471 $entitiesWithout = array(
473 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
475 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
477 // failed 'check that a 5 limit returns 5' - probably is_template field is wrong or something, or could be limit doesn't work right
479 // can't handle creating 25
481 // fails on 5 limit - probably a set up problem
483 //a bit of a pseudoapi - keys by domain
485 return $entitiesWithout;
489 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
491 public static function toBeSkipped_getSqlOperators() {
492 $entitiesWithout = array(
493 'Case', //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
494 'Contact', // on the todo list!
495 'EntityTag', // non-standard api - has inappropriate mandatory fields & doesn't implement limit
496 'Extension', // can't handle creating 25
497 'Note', // note has a default get that isn't implemented in createTestObject -meaning you don't 'get' them
498 'Setting', //a bit of a pseudoapi - keys by domain
500 return $entitiesWithout;
509 public function getKnownUnworkablesUpdateSingle($entity, $key) {
510 // can't update values are values for which updates don't result in the value being changed
511 $knownFailures = array(
512 'ActionSchedule' => array(
513 'cant_update' => array(
517 'ActivityContact' => array(
518 'cant_update' => array(
520 //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
524 'cant_update' => array(
525 'state_province_id', //issues with country id - need to ensure same country
526 'master_id', //creates relationship
528 'cant_return' => array(),
531 'cant_update' => array(
532 'entity_table', // believe this field is defined in error
534 'cant_return' => array(
539 'cant_update' => array(
543 'MembershipBlock' => array(
544 'cant_update' => array(
545 // The fake/auto-generated values leave us unable to properly cleanup fake data
550 'ContributionSoft' => array(
551 'cant_update' => array(
552 // can't be changed through api
557 'cant_update' => array(
558 'pledge_original_installment_amount',
560 'original_installment_amount',
562 'amount', // can't be changed through API,
564 'break_return' => array(// if these are passed in they are retrieved from the wrong table
567 'contribution_page_id',
568 'financial_account_id',
572 'cant_return' => array(// can't be retrieved from api
573 'honor_type_id', //due to uniquename missing
581 'initial_reminder_day',
582 'additional_reminder_day',
584 'pledge_contribution_page_id',
586 'pledge_campaign_id',
587 'pledge_financial_type_id',
590 'PaymentProcessorType' => array(
591 'cant_update' => array(
594 'break_return' => array(),
595 'cant_return' => array(),
597 'PriceFieldValue' => array(
598 'cant_update' => array(
599 'weight', //won't update as there is no 1 in the same price set
603 if (empty($knownFailures[$entity]) ||
empty($knownFailures[$entity][$key])) {
606 return $knownFailures[$entity][$key];
609 /* ----- testing the _get ----- */
612 * @dataProvider toBeSkipped_get
613 * Entities that don't need a get action
616 public function testNotImplemented_get($Entity) {
617 $result = civicrm_api($Entity, 'Get', array('version' => 3));
618 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
619 // $this->assertContains("API ($Entity, Get) does not exist", $result['error_message']);
620 $this->assertRegExp('/API (.*) does not exist/', $result['error_message']);
624 * @dataProvider entities
625 * @expectedException PHPUnit_Framework_Error
628 public function testWithoutParam_get($Entity) {
629 // should get php complaining that a param is missing
630 $result = civicrm_api($Entity, 'Get');
634 * @dataProvider entities
637 public function testGetFields($Entity) {
638 if (in_array($Entity, $this->deprecatedAPI
) ||
$Entity == 'Entity' ||
$Entity == 'CustomValue') {
642 $result = civicrm_api($Entity, 'getfields', array('version' => 3));
643 $this->assertTrue(is_array($result['values']), "$Entity ::get fields doesn't return values array in line " . __LINE__
);
644 foreach ($result['values'] as $key => $value) {
645 $this->assertTrue(is_array($value), $Entity . "::" . $key . " is not an array in line " . __LINE__
);
650 * @dataProvider entities_get
653 public function testEmptyParam_get($Entity) {
655 if (in_array($Entity, $this->toBeImplemented
['get'])) {
656 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
659 $result = civicrm_api($Entity, 'Get', array());
660 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
661 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
665 * @dataProvider entities_get
668 public function testEmptyParam_getString($Entity) {
670 if (in_array($Entity, $this->toBeImplemented
['get'])) {
671 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
674 $result = $this->callAPIFailure($Entity, 'Get', 'string');
675 $this->assertEquals(2000, $result['error_code']);
676 $this->assertEquals('Input variable `params` is not an array', $result['error_message']);
680 * @dataProvider entities_get
681 * @Xdepends testEmptyParam_get // no need to test the simple if the empty doesn't work/is skipped. doesn't seem to work
684 public function testSimple_get($Entity) {
685 // $this->markTestSkipped("test gives core error on test server (but not on our locals). Skip until we can get server to pass");
686 if (in_array($Entity, $this->toBeImplemented
['get'])) {
689 $result = civicrm_api($Entity, 'Get', array('version' => 3));
690 // @TODO: list the get that have mandatory params
691 if ($result['is_error']) {
692 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
693 // either id or contact_id or entity_id is one of the field missing
694 $this->assertContains("id", $result['error_message']);
697 $this->assertEquals(3, $result['version']);
698 $this->assertArrayHasKey('count', $result);
699 $this->assertArrayHasKey('values', $result);
704 * @dataProvider custom_data_entities_get
707 public function testCustomDataGet($entityName) {
708 $this->createLoggedInUser();// so subsidiary activities are created
709 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entityName . 'Test.php');
710 $customFieldName = 'custom_' . $ids['custom_field_id'];
711 $objects = $this->getMockableBAOObjects($entityName, 1);
712 $params = array('id' => $objects[0]->id
, 'custom_' . $ids['custom_field_id'] => "custom string");
713 $result = $this->callAPISuccess($entityName, 'create', $params);
715 $getParams = array('id' => $result['id'], 'return' => array($customFieldName));
716 $check = $this->callAPISuccess($entityName, 'get', $getParams);
717 $this->assertEquals("custom string", $check['values'][$check['id']][$customFieldName]);
719 $this->customFieldDelete($ids['custom_field_id']);
720 $this->customGroupDelete($ids['custom_group_id']);
721 $this->callAPISuccess($entityName, 'delete', array('id' => $result['id']));
725 * @dataProvider entities_get
728 public function testAcceptsOnlyID_get($Entity) {
729 // big random number. fun fact: if you multiply it by pi^e, the result is another random number, but bigger ;)
730 $nonExistantID = 30867307034;
731 if (in_array($Entity, $this->toBeImplemented
['get'])
732 ||
in_array($Entity, $this->toBeSkipped_getByID())
738 // the below function returns different values and hence an early return
739 // we'll fix this once beta1 is released
742 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
744 if ($result['is_error']) {
745 // just to get a clearer message in the log
746 $this->assertEquals("only id should be enough", $result['error_message']);
748 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
749 $this->assertEquals(0, $result['count']);
754 * Create two entities and make sure we can fetch them individually by ID
756 * @dataProvider entities_get
758 * limitations include the problem with avoiding loops when creating test objects -
759 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
760 * Currency - only seems to support US
763 public function testByID_get($entityName) {
764 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
765 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
769 $baos = $this->getMockableBAOObjects($entityName);
770 list($baoObj1, $baoObj2) = $baos;
773 $result = $this->callAPISuccess($entityName, 'get', array(
774 'id' => $baoObj1->id
,
777 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
778 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
779 $this->assertEquals(1, count($result['values']));
781 // fetch second by ID
782 $result = $this->callAPISuccess($entityName, 'get', array(
783 'id' => $baoObj2->id
,
785 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
786 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
787 $this->assertEquals(1, count($result['values']));
791 * Ensure that the "get" operation accepts limiting the #result records.
793 * TODO Consider making a separate entity list ("entities_getlimit")
794 * For the moment, the "entities_updatesingle" list should give a good
795 * sense for which entities support createTestObject
797 * @dataProvider entities_getlimit
799 * @param string $entityName
801 public function testLimit($entityName) {
802 $cases = array(); // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
804 array('options' => array('limit' => NULL)),
806 'check that a NULL limit returns unlimited',
809 array('options' => array('limit' => FALSE)),
811 'check that a FALSE limit returns unlimited',
814 array('options' => array('limit' => 0)),
816 'check that a 0 limit returns unlimited',
819 array('options' => array('limit' => 5)),
821 'check that a 5 limit returns 5',
826 'check that no limit returns 25',
829 $baoString = _civicrm_api3_get_BAO($entityName);
830 if (empty($baoString)) {
831 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
835 // make 30 test items -- 30 > 25 (the default limit)
837 for ($i = 0; $i < 30; $i++
) {
838 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
839 $ids[] = $baoObj->id
;
842 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
843 foreach ($cases as $case) {
844 $this->checkLimitAgainstExpected($entityName, $case[0], $case[1], $case[2]);
846 //non preferred / legacy syntax
847 if (isset($case[0]['options']['limit'])) {
848 $this->checkLimitAgainstExpected($entityName, array('rowCount' => $case[0]['options']['limit']), $case[1], $case[2]);
849 $this->checkLimitAgainstExpected($entityName, array('option_limit' => $case[0]['options']['limit']), $case[1], $case[2]);
850 $this->checkLimitAgainstExpected($entityName, array('option.limit' => $case[0]['options']['limit']), $case[1], $case[2]);
853 foreach ($ids as $id) {
854 CRM_Core_DAO
::deleteTestObjects($baoString, array('id' => $id));
860 * Ensure that the "get" operation accepts limiting the #result records.
862 * @dataProvider entities_getSqlOperators
864 * @param string $entityName
866 public function testSqlOperators($entityName) {
867 $baoString = _civicrm_api3_get_BAO($entityName);
868 if (empty($baoString)) {
869 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
872 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0), 'return' => 'id'));
873 $entities = array_keys($entities['values']);
874 $totalEntities = count($entities);
875 if ($totalEntities < 3) {
877 for ($i = 0; $i < 3 - $totalEntities; $i++
) {
878 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
879 $ids[] = $baoObj->id
;
883 $entities = $this->callAPISuccess($entityName, 'get', array('options' => array('limit' => 0)));
884 $entities = array_keys($entities['values']);
885 $this->assertGreaterThan(2, $totalEntities);
886 $this->callAPISuccess($entityName, 'getsingle', array('id' => array('IN' => array($entities[0]))));
887 $this->callAPISuccessGetCount($entityName, array('id' => array('NOT IN' => array($entities[0]))), $totalEntities - 1);
888 $this->callAPISuccessGetCount($entityName, array('id' => array('>' => $entities[0])), $totalEntities - 1);
892 * Check that get fetches an appropriate number of results
894 * @param string $entityName
895 * Name of entity to test.
896 * @param array $params
898 * @param string $message
900 public function checkLimitAgainstExpected($entityName, $params, $limit, $message) {
901 $result = $this->callAPISuccess($entityName, 'get', $params);
903 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
904 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
907 $this->assertEquals($limit, $result['count'], $message);
908 $this->assertEquals($limit, count($result['values']), $message);
913 * Create two entities and make sure we can fetch them individually by ID (e.g. using "contact_id=>2"
916 * @dataProvider entities_get
918 * limitations include the problem with avoiding loops when creating test objects -
919 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
920 * Currency - only seems to support US
922 * @throws \PHPUnit_Framework_IncompleteTestError
924 public function testByIDAlias_get($entityName) {
925 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
926 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
930 $baoString = _civicrm_api3_get_BAO($entityName);
931 if (empty($baoString)) {
932 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
936 $idFieldName = _civicrm_api_get_entity_name_from_camel($entityName) . '_id';
939 $baoObj1 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
940 $this->assertTrue(is_int($baoObj1->id
), 'check first id');
941 $this->deletableTestObjects
[$baoString][] = $baoObj1->id
;
942 $baoObj2 = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
943 $this->assertTrue(is_int($baoObj2->id
), 'check second id');
944 $this->deletableTestObjects
[$baoString][] = $baoObj2->id
;
947 $result = civicrm_api($entityName, 'get', array(
949 $idFieldName => $baoObj1->id
,
951 $this->assertAPISuccess($result);
952 $this->assertTrue(!empty($result['values'][$baoObj1->id
]), 'Should find first object by id');
953 $this->assertEquals($baoObj1->id
, $result['values'][$baoObj1->id
]['id'], 'Should find id on first object');
954 $this->assertEquals(1, count($result['values']));
956 // fetch second by ID
957 $result = civicrm_api($entityName, 'get', array(
959 $idFieldName => $baoObj2->id
,
961 $this->assertAPISuccess($result);
962 $this->assertTrue(!empty($result['values'][$baoObj2->id
]), 'Should find second object by id');
963 $this->assertEquals($baoObj2->id
, $result['values'][$baoObj2->id
]['id'], 'Should find id on second object');
964 $this->assertEquals(1, count($result['values']));
968 * @dataProvider entities_get
971 public function testNonExistantID_get($Entity) {
972 // cf testAcceptsOnlyID_get
973 $nonExistantID = 30867307034;
974 if (in_array($Entity, $this->toBeImplemented
['get'])) {
978 $result = civicrm_api($Entity, 'Get', array('version' => 3, 'id' => $nonExistantID));
980 // redundant with testAcceptsOnlyID_get
981 if ($result['is_error']) {
985 $this->assertArrayHasKey('version', $result);
986 $this->assertEquals(3, $result['version']);
987 if (!in_array($Entity, $this->onlyIDNonZeroCount
['get'])) {
988 $this->assertEquals(0, $result['count']);
992 /* ---- testing the _create ---- */
995 * @dataProvider toBeSkipped_create
996 entities that don't need a create action
999 public function testNotImplemented_create($Entity) {
1000 $result = civicrm_api($Entity, 'Create', array('version' => 3));
1001 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1002 $this->assertContains(strtolower("API ($Entity, Create) does not exist"), strtolower($result['error_message']));
1006 * @dataProvider entities
1007 * @expectedException PHPUnit_Framework_Error
1010 public function testWithoutParam_create($Entity) {
1011 // should create php complaining that a param is missing
1012 $result = civicrm_api($Entity, 'Create');
1016 * @dataProvider entities_create
1018 * @throws \PHPUnit_Framework_IncompleteTestError
1020 public function testEmptyParam_create($Entity) {
1021 $this->markTestIncomplete("fixing this test to test the api functions fails on numberous tests
1022 which will either create a completely blank entity (batch, participant status) or
1023 have a damn good crack at it (e.g mailing job). Marking this as incomplete beats false success");
1025 if (in_array($Entity, $this->toBeImplemented
['create'])) {
1026 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1029 $result = $this->callAPIFailure($Entity, 'Create', array());
1030 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
1034 * @dataProvider entities_create
1036 * Check that create doesn't work with an invalid
1038 * @throws \PHPUnit_Framework_IncompleteTestError
1040 public function testInvalidID_create($Entity) {
1041 // turn test off for noew
1042 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1044 if (in_array($Entity, $this->toBeImplemented
['create'])) {
1045 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1048 $result = $this->callAPIFailure($Entity, 'Create', array('id' => 999));
1052 * @dataProvider entities
1054 public function testCreateWrongTypeParamTag_create() {
1055 $result = civicrm_api("Tag", 'Create', 'this is not a string');
1056 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1057 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1061 * @dataProvider entities_updatesingle
1063 * limitations include the problem with avoiding loops when creating test objects -
1064 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1065 * Currency - only seems to support US
1066 * @param $entityName
1068 public function testCreateSingleValueAlter($entityName) {
1069 if (in_array($entityName, $this->toBeImplemented
['create'])) {
1070 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1074 $baoString = _civicrm_api3_get_BAO($entityName);
1075 $this->assertNotEmpty($baoString, $entityName);
1076 $this->assertNotEmpty($entityName, $entityName);
1077 $fieldsGet = $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'get'));
1078 if ($entityName != 'Pledge') {
1079 $fields = $this->callAPISuccess($entityName, 'getfields', array('action' => 'create'));
1081 $fields = $fields['values'];
1082 $return = array_keys($fieldsGet['values']);
1083 $valuesNotToReturn = $this->getKnownUnworkablesUpdateSingle($entityName, 'break_return');
1084 // these can't be requested as return values
1085 $entityValuesThatDoNotWork = array_merge(
1086 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_update'),
1087 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_return'),
1091 $return = array_diff($return, $valuesNotToReturn);
1092 $baoObj = new CRM_Core_DAO();
1093 $baoObj->createTestObject($baoString, array('currency' => 'USD'), 2, 0);
1095 $getEntities = $this->callAPISuccess($entityName, 'get', array(
1097 'return' => $return,
1099 'sort' => 'id DESC',
1104 // lets use first rather than assume only one exists
1105 $entity = $getEntities['values'][0];
1106 $entity2 = $getEntities['values'][1];
1107 $this->deletableTestObjects
[$baoString][] = $entity['id'];
1108 $this->deletableTestObjects
[$baoString][] = $entity2['id'];
1109 foreach ($fields as $field => $specs) {
1111 $fieldName = $field;
1112 if (!empty($specs['uniquename'])) {
1113 $fieldName = $specs['uniquename'];
1115 if ($field == 'currency' ||
$field == 'id' ||
$field == strtolower($entityName) . '_id'
1116 ||
in_array($field, $entityValuesThatDoNotWork)
1118 //@todo id & entity_id are correct but we should fix currency & frequency_day
1121 $this->assertArrayHasKey('type', $specs, "the _spec function for $entityName field $field does not specify the type");
1122 switch ($specs['type']) {
1123 case CRM_Utils_Type
::T_DATE
:
1124 case CRM_Utils_Type
::T_TIMESTAMP
:
1125 $entity[$fieldName] = '2012-05-20';
1128 //case CRM_Utils_Type::T_DATETIME:
1131 $entity[$fieldName] = '2012-05-20 03:05:20';
1134 case CRM_Utils_Type
::T_STRING
:
1135 case CRM_Utils_Type
::T_BLOB
:
1136 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1137 case CRM_Utils_Type
::T_TEXT
:
1138 case CRM_Utils_Type
::T_LONGTEXT
:
1139 case CRM_Utils_Type
::T_EMAIL
:
1140 $entity[$fieldName] = substr('New String', 0, CRM_Utils_Array
::Value('maxlength', $specs, 100));
1143 case CRM_Utils_Type
::T_INT
:
1144 // probably created with a 1
1145 if ($fieldName == 'weight') {
1146 $entity[$fieldName] = 2;
1148 elseif (!empty($specs['FKClassName'])) {
1149 if ($specs['FKClassName'] == $baoString) {
1150 $entity[$fieldName] = (string) $entity2['id'];
1153 $uniqueName = CRM_Utils_Array
::value('uniqueName', $specs);
1154 if (!empty($entity[$fieldName])) {
1155 $resetFKTo = array($fieldName => $entity[$fieldName]);
1157 $entity[$fieldName] = (string) empty($entity2[$field]) ? CRM_Utils_Array
::value($uniqueName, $entity2) : $entity2[$field];
1158 //todo - there isn't always something set here - & our checking on unset values is limited
1159 if (empty($entity[$field])) {
1160 unset($entity[$field]);
1165 $entity[$fieldName] = '6';
1169 case CRM_Utils_Type
::T_BOOLEAN
:
1170 // probably created with a 1
1171 $entity[$fieldName] = '0';
1174 case CRM_Utils_Type
::T_FLOAT
:
1175 case CRM_Utils_Type
::T_MONEY
:
1176 $entity[$field] = '22.75';
1179 case CRM_Utils_Type
::T_URL
:
1180 $entity[$field] = 'warm.beer.com';
1182 if (!empty($specs['pseudoconstant'])) {
1183 $options = $this->callAPISuccess($entityName, 'getoptions', array('context' => 'create', 'field' => $field));
1184 if (empty($options['values'])) {
1185 //eg. pdf_format id doesn't ship with any
1186 if (isset($specs['pseudoconstant']['optionGroupName'])) {
1187 $optionGroupID = $this->callAPISuccess('option_group', 'getvalue', array(
1188 'name' => 'pdf_format',
1191 $optionValue = $this->callAPISuccess('option_value', 'create', array(
1192 'option_group_id' => $optionGroupID,
1193 'label' => 'new option value',
1195 $options['values'][] = $optionValue['id'];
1198 $entity[$field] = array_rand($options['values']);
1200 $updateParams = array(
1201 'id' => $entity['id'],
1202 $field => isset($entity[$field]) ?
$entity[$field] : NULL,
1204 if (isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1205 //api has special handling on these 2 fields for backward compatibility reasons
1206 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1209 $update = $this->callAPISuccess($entityName, 'create', $updateParams);
1210 $checkParams = array(
1211 'id' => $entity['id'],
1213 'return' => $return,
1215 'sort' => 'id DESC',
1220 $checkEntity = $this->callAPISuccess($entityName, 'getsingle', $checkParams);
1221 $this->assertAPIArrayComparison($entity, $checkEntity, array(), "checking if $fieldName was correctly updated\n" . print_r(array(
1222 'update-params' => $updateParams,
1223 'update-result' => $update,
1224 'getsingle-params' => $checkParams,
1225 'getsingle-result' => $checkEntity,
1226 'expected entity' => $entity,
1229 //reset the foreign key fields because otherwise our cleanup routine fails & some other unexpected stuff can kick in
1230 $entity = array_merge($entity, $resetFKTo);
1231 $updateParams = array_merge($updateParams, $resetFKTo);
1232 $this->callAPISuccess($entityName, 'create', $updateParams);
1233 if (isset($updateParams['financial_type_id']) && in_array($entityName, array('Grant'))) {
1234 //api has special handling on these 2 fields for backward compatibility reasons
1235 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1242 /* ---- testing the _getFields ---- */
1244 /* ---- testing the _delete ---- */
1247 * @dataProvider toBeSkipped_delete
1248 entities that don't need a delete action
1251 public function testNotImplemented_delete($Entity) {
1252 $nonExistantID = 151416349;
1253 $result = civicrm_api($Entity, 'Delete', array('version' => 3, 'id' => $nonExistantID));
1254 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1255 $this->assertContains(strtolower("API ($Entity, Delete) does not exist"), strtolower($result['error_message']));
1259 * @dataProvider entities
1260 * @expectedException PHPUnit_Framework_Error
1263 public function testWithoutParam_delete($Entity) {
1264 // should delete php complaining that a param is missing
1265 $result = civicrm_api($Entity, 'Delete');
1269 * @dataProvider entities_delete
1272 public function testEmptyParam_delete($Entity) {
1273 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1274 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1277 $result = civicrm_api($Entity, 'Delete', array());
1278 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1279 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
1283 * @dataProvider entities_delete
1285 * @throws \PHPUnit_Framework_IncompleteTestError
1287 public function testInvalidID_delete($Entity) {
1288 // turn test off for now
1289 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1291 if (in_array($Entity, $this->toBeImplemented
['delete'])) {
1292 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1295 $result = $this->callAPIFailure($Entity, 'Delete', array('id' => 999));
1299 * @dataProvider entities
1301 public function testDeleteWrongTypeParamTag_delete() {
1302 $result = civicrm_api("Tag", 'Delete', 'this is not a string');
1303 $this->assertEquals(1, $result['is_error'], 'In line ' . __LINE__
);
1304 $this->assertEquals("Input variable `params` is not an array", $result['error_message']);
1308 * Create two entities and make sure delete action only deletes one!
1310 * @dataProvider entities_delete
1312 * limitations include the problem with avoiding loops when creating test objects -
1313 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1314 * Currency - only seems to support US
1315 * @param $entityName
1316 * @throws \PHPUnit_Framework_IncompleteTestError
1318 public function testByID_delete($entityName) {
1319 // turn test off for noew
1320 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1323 if (in_array($entityName, self
::toBeSkipped_automock(TRUE))) {
1324 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1327 $startCount = $this->callAPISuccess($entityName, 'getcount', array());
1329 $baos = $this->getMockableBAOObjects($entityName, $createcount);
1330 list($baoObj1, $baoObj2) = $baos;
1332 // make sure exactly 2 exist
1333 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1334 $createcount +
$startCount
1337 $this->callAPISuccess($entityName, 'delete', array('id' => $baoObj2->id
));
1338 //make sure 1 less exists now
1339 $result = $this->callAPISuccess($entityName, 'getcount', array(),
1340 ($createcount +
$startCount) - 1
1343 //make sure id #1 exists
1344 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj1->id
),
1347 //make sure id #2 desn't exist
1348 $result = $this->callAPISuccess($entityName, 'getcount', array('id' => $baoObj2->id
),
1354 * Create two entities and make sure delete action only deletes one!
1356 * @dataProvider entities_getfields
1359 public function testGetfieldsHasTitle($entity) {
1360 $entities = $this->getEntitiesSupportingCustomFields();
1361 if (in_array($entity, $entities)) {
1362 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, $entity . 'Test.php');
1364 $actions = $this->callAPISuccess($entity, 'getactions', array());
1365 foreach ($actions['values'] as $action) {
1366 if (substr($action, -7) == '_create' ||
substr($action, -4) == '_get' ||
substr($action, -7) == '_delete') {
1367 //getactions can't distinguish between contribution_page.create & contribution_page.create
1370 $fields = $this->callAPISuccess($entity, 'getfields', array('action' => $action));
1371 if (!empty($ids) && in_array($action, array('create', 'get'))) {
1372 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $fields['values']);
1375 foreach ($fields['values'] as $fieldName => $fieldSpec) {
1376 $this->assertArrayHasKey('title', $fieldSpec, "no title for $entity - $fieldName on action $action");
1377 $this->assertNotEmpty($fieldSpec['title'], "empty title for $entity - $fieldName");
1381 $this->customFieldDelete($ids['custom_field_id']);
1382 $this->customGroupDelete($ids['custom_group_id']);
1389 public function getEntitiesSupportingCustomFields() {
1390 $entities = self
::custom_data_entities_get();
1391 $returnEntities = array();
1392 foreach ($entities as $entityArray) {
1393 $returnEntities[] = $entityArray[0];
1395 return $returnEntities;
1399 * @param string $entityName
1404 private function getMockableBAOObjects($entityName, $count = 2) {
1405 $baoString = _civicrm_api3_get_BAO($entityName);
1406 if (empty($baoString)) {
1407 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1412 while ($i < $count) {
1414 $baoObj = CRM_Core_DAO
::createTestObject($baoString, array('currency' => 'USD'));
1415 $this->assertTrue(is_int($baoObj->id
), 'check first id');
1416 $this->deletableTestObjects
[$baoString][] = $baoObj->id
;
1425 * Verify that HTML metacharacters provided as inputs appear consistently
1428 * At time of writing, the encoding scheme requires (for example) that an
1429 * event title be partially-HTML-escaped before writing to DB. To provide
1430 * consistency, the API must perform extra encoding and decoding on some
1433 * In this example, the event 'title' is subject to encoding, but the
1434 * event 'description' is not.
1436 public function testEncodeDecodeConsistency() {
1438 $createResult = civicrm_api('Event', 'Create', array(
1440 'title' => 'CiviCRM <> TheRest',
1441 'description' => 'TheRest <> CiviCRM',
1442 'event_type_id' => 1,
1444 'start_date' => 20081021,
1446 $this->assertAPISuccess($createResult);
1447 $eventId = $createResult['id'];
1448 $this->assertEquals('CiviCRM <> TheRest', $createResult['values'][$eventId]['title']);
1449 $this->assertEquals('TheRest <> CiviCRM', $createResult['values'][$eventId]['description']);
1451 // Verify "get" handles decoding in result value
1452 $getByIdResult = civicrm_api('Event', 'Get', array(
1456 $this->assertAPISuccess($getByIdResult);
1457 $this->assertEquals('CiviCRM <> TheRest', $getByIdResult['values'][$eventId]['title']);
1458 $this->assertEquals('TheRest <> CiviCRM', $getByIdResult['values'][$eventId]['description']);
1460 // Verify "get" handles encoding in search value
1461 $getByTitleResult = civicrm_api('Event', 'Get', array(
1463 'title' => 'CiviCRM <> TheRest',
1465 $this->assertAPISuccess($getByTitleResult);
1466 $this->assertEquals('CiviCRM <> TheRest', $getByTitleResult['values'][$eventId]['title']);
1467 $this->assertEquals('TheRest <> CiviCRM', $getByTitleResult['values'][$eventId]['description']);
1469 // Verify that "getSingle" handles decoding
1470 $getSingleResult = $this->callAPISuccess('Event', 'GetSingle', array(
1474 $this->assertEquals('CiviCRM <> TheRest', $getSingleResult['title']);
1475 $this->assertEquals('TheRest <> CiviCRM', $getSingleResult['description']);
1477 // Verify that chaining handles decoding
1478 $chainResult = $this->callAPISuccess('Event', 'Get', array(
1480 'api.event.get' => array(),
1482 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['title']);
1483 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['description']);
1484 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['api.event.get']['values'][0]['title']);
1485 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['api.event.get']['values'][0]['description']);
1487 // Verify that "setvalue" handles encoding for updates
1488 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1492 'value' => 'setValueTitle: CiviCRM <> TheRest',
1494 $this->assertAPISuccess($setValueTitleResult);
1495 $this->assertEquals('setValueTitle: CiviCRM <> TheRest', $setValueTitleResult['values']['title']);
1496 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1499 'field' => 'description',
1500 'value' => 'setValueDescription: TheRest <> CiviCRM',
1502 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1503 $this->assertEquals('setValueDescription: TheRest <> CiviCRM', $setValueDescriptionResult['values']['description']);
1507 * Verify that write operations (create/update) use partial HTML-encoding
1509 * In this example, the event 'title' is subject to encoding, but the
1510 * event 'description' is not.
1512 public function testEncodeWrite() {
1514 $createResult = civicrm_api('Event', 'Create', array(
1516 'title' => 'createNew: CiviCRM <> TheRest',
1517 'description' => 'createNew: TheRest <> CiviCRM',
1518 'event_type_id' => 1,
1520 'start_date' => 20081021,
1522 $this->assertAPISuccess($createResult);
1523 $eventId = $createResult['id'];
1524 $this->assertDBQuery('createNew: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1525 1 => array($eventId, 'Integer'),
1527 $this->assertDBQuery('createNew: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1528 1 => array($eventId, 'Integer'),
1531 // Verify that "create" handles encoding for updates
1532 $createWithIdResult = civicrm_api('Event', 'Create', array(
1535 'title' => 'createWithId: CiviCRM <> TheRest',
1536 'description' => 'createWithId: TheRest <> CiviCRM',
1538 $this->assertAPISuccess($createWithIdResult);
1539 $this->assertDBQuery('createWithId: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1540 1 => array($eventId, 'Integer'),
1542 $this->assertDBQuery('createWithId: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1543 1 => array($eventId, 'Integer'),
1546 // Verify that "setvalue" handles encoding for updates
1547 $setValueTitleResult = civicrm_api('Event', 'setvalue', array(
1551 'value' => 'setValueTitle: CiviCRM <> TheRest',
1553 $this->assertAPISuccess($setValueTitleResult);
1554 $this->assertDBQuery('setValueTitle: CiviCRM <> TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', array(
1555 1 => array($eventId, 'Integer'),
1557 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', array(
1560 'field' => 'description',
1561 'value' => 'setValueDescription: TheRest <> CiviCRM',
1563 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1564 $this->assertAPISuccess($setValueDescriptionResult);
1565 $this->assertDBQuery('setValueDescription: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', array(
1566 1 => array($eventId, 'Integer'),