3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 require_once 'CRM/Utils/DeprecatedUtils.php';
15 * Test class for API utils
20 class api_v3_UtilsTest
extends CiviUnitTestCase
{
21 protected $_apiversion = 3;
22 public $DBResetRequired = FALSE;
24 public $_contactID = 1;
27 * Sets up the fixture, for example, opens a network connection.
29 * This method is called before a test is executed.
31 protected function setUp() {
33 $this->useTransaction(TRUE);
36 public function testAddFormattedParam() {
37 $values = ['contact_type' => 'Individual'];
38 $params = ['something' => 1];
39 $result = _civicrm_api3_deprecated_add_formatted_param($values, $params);
40 $this->assertTrue($result);
43 public function testCheckPermissionReturn() {
44 $check = ['check_permissions' => TRUE];
45 $config = CRM_Core_Config
::singleton();
46 $config->userPermissionClass
->permissions
= [];
47 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'empty permissions should not be enough');
48 $config->userPermissionClass
->permissions
= ['access CiviCRM'];
49 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'lacking permissions should not be enough');
50 $config->userPermissionClass
->permissions
= ['add contacts'];
51 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'lacking permissions should not be enough');
53 $config->userPermissionClass
->permissions
= ['access CiviCRM', 'add contacts'];
54 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'exact permissions should be enough');
56 $config->userPermissionClass
->permissions
= ['access CiviCRM', 'add contacts', 'import contacts'];
57 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'overfluous permissions should be enough');
60 public function testCheckPermissionThrow() {
61 $check = ['check_permissions' => TRUE];
62 $config = CRM_Core_Config
::singleton();
64 $config->userPermissionClass
->permissions
= ['access CiviCRM'];
65 $this->runPermissionCheck('contact', 'create', $check, TRUE);
67 catch (Exception
$e) {
68 $message = $e->getMessage();
70 $this->assertEquals($message, 'API permission check failed for Contact/create call; insufficient permission: require access CiviCRM and add contacts', 'lacking permissions should throw an exception');
72 $config->userPermissionClass
->permissions
= ['access CiviCRM', 'add contacts', 'import contacts'];
73 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'overfluous permissions should return true');
76 public function testCheckPermissionSkip() {
77 $config = CRM_Core_Config
::singleton();
78 $config->userPermissionClass
->permissions
= ['access CiviCRM'];
79 $params = ['check_permissions' => TRUE];
80 $this->assertFalse($this->runPermissionCheck('contact', 'create', $params), 'lacking permissions should not be enough');
81 $params = ['check_permissions' => FALSE];
82 $this->assertTrue($this->runPermissionCheck('contact', 'create', $params), 'permission check should be skippable');
85 public function getCamelCaseFuncs() {
86 // There have been two slightly different functions for normalizing names;
87 // _civicrm_api_get_camel_name() and \Civi\API\Request::normalizeEntityName().
89 // These are the typical cases - where the two have always agreed.
93 ['foo_bar', 'FooBar'],
99 // These are some atypical cases - where the two have always agreed.
100 ['foo__bar', 'FooBar'],
101 ['Foo_Bar', 'FooBar'],
102 ['one_two_three', 'OneTwoThree'],
103 ['oneTwo_three', 'OneTwoThree'],
105 ['got2_BGood', 'Got2BGood'],
107 // These are some atypical cases - where they have traditionally disagreed.
108 // _civicrm_api_get_camel_name() has now changed to match normalizeEntityName()
109 // because the latter is more defensive.
110 ['Foo-Bar', 'FooBar'],
111 ['Foo+Bar', 'FooBar'],
112 ['Foo.Bar', 'FooBar'],
113 ['Foo/../Bar/', 'FooBar'],
119 * @param string $inputValue
120 * The user-supplied/untrusted entity name.
121 * @param string $expectValue
122 * The normalized/UpperCamelCase entity name.
123 * @dataProvider getCamelCaseFuncs
125 public function testCamelName($inputValue, $expectValue) {
126 $actualValue = _civicrm_api_get_camel_name($inputValue);
127 $this->assertEquals($expectValue, $actualValue);
131 * @param string $entity
132 * @param string $action
133 * @param array $params
134 * @param bool $throws
135 * Whether we should pass any exceptions for authorization failures.
137 * @throws API_Exception
140 * TRUE or FALSE depending on the outcome of the authorization check
142 public function runPermissionCheck($entity, $action, $params, $throws = FALSE) {
143 $params['version'] = 3;
144 $dispatcher = new \Symfony\Component\EventDispatcher\
EventDispatcher();
145 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
146 $kernel = new \Civi\API\
Kernel($dispatcher);
147 $apiRequest = \Civi\API\Request
::create($entity, $action, $params);
149 $kernel->authorize(NULL, $apiRequest);
152 catch (\API_Exception
$e) {
153 $extra = $e->getExtraParams();
154 if (!$throws && $extra['error_code'] == API_Exception
::UNAUTHORIZED
) {
164 * Test verify mandatory - includes DAO & passed as well as empty & NULL fields
166 public function testVerifyMandatory() {
167 _civicrm_api3_initialize(TRUE);
169 'entity_table' => 'civicrm_contact',
171 'contact_id' => $this->_contactID
,
172 'modified_date' => '2011-01-31',
174 'version' => $this->_apiversion
,
177 civicrm_api3_verify_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
179 catch (Exception
$expected) {
180 $this->assertEquals('Mandatory key(s) missing from params array: note, subject', $expected->getMessage());
184 $this->fail('An expected exception has not been raised.');
188 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
190 public function testVerifyOneMandatory() {
191 _civicrm_api3_initialize(TRUE);
193 'entity_table' => 'civicrm_contact',
195 'contact_id' => $this->_contactID
,
196 'modified_date' => '2011-01-31',
198 'version' => $this->_apiversion
,
202 civicrm_api3_verify_one_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
204 catch (Exception
$expected) {
205 $this->assertEquals('Mandatory key(s) missing from params array: one of (note, subject)', $expected->getMessage());
209 $this->fail('An expected exception has not been raised.');
213 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
215 public function testVerifyOneMandatoryOneSet() {
216 _civicrm_api3_initialize(TRUE);
219 'entity_table' => 'civicrm_contact',
221 'contact_id' => $this->_contactID
,
222 'modified_date' => '2011-01-31',
227 civicrm_api3_verify_one_mandatory($params, NULL, ['note', 'subject']);
229 catch (Exception
$expected) {
230 $this->fail('Exception raised when it shouldn\'t have been in line ' . __LINE__
);
235 * Test GET DAO function returns DAO.
237 public function testGetDAO() {
239 'civicrm_api3_custom_group_get' => 'CRM_Core_DAO_CustomGroup',
240 'custom_group' => 'CRM_Core_DAO_CustomGroup',
241 'CustomGroup' => 'CRM_Core_DAO_CustomGroup',
242 'civicrm_api3_custom_field_get' => 'CRM_Core_DAO_CustomField',
243 'civicrm_api3_survey_get' => 'CRM_Campaign_DAO_Survey',
244 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_DAO_PledgePayment',
245 'civicrm_api3_website_get' => 'CRM_Core_DAO_Website',
246 'Membership' => 'CRM_Member_DAO_Membership',
248 foreach ($params as $input => $expected) {
249 $result = _civicrm_api3_get_DAO($input);
250 $this->assertEquals($expected, $result);
255 * Test GET BAO function returns BAO when it exists.
257 public function testGetBAO() {
259 'civicrm_api3_website_get' => 'CRM_Core_BAO_Website',
260 'civicrm_api3_survey_get' => 'CRM_Campaign_BAO_Survey',
261 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_BAO_PledgePayment',
262 'Household' => 'CRM_Contact_BAO_Contact',
263 // Note this one DOES NOT have a BAO so we expect to fall back on returning the DAO
264 'mailing_group' => 'CRM_Mailing_DAO_MailingGroup',
265 // Make sure we get null back with nonexistant entities
266 'civicrm_this_does_not_exist' => NULL,
268 foreach ($params as $input => $expected) {
269 $result = _civicrm_api3_get_BAO($input);
270 $this->assertEquals($expected, $result);
275 * Test the validate function transforms dates.
277 * @throws \CiviCRM_API3_Exception
280 public function test_civicrm_api3_validate_fields() {
281 $params = ['relationship_start_date' => '2010-12-20', 'relationship_end_date' => ''];
282 $fields = civicrm_api3('relationship', 'getfields', ['action' => 'get']);
283 _civicrm_api3_validate_fields('relationship', 'get', $params, $fields['values']);
284 $this->assertEquals('20101220000000', $params['relationship_start_date']);
285 $this->assertEquals('', $params['relationship_end_date']);
288 public function test_civicrm_api3_validate_fields_membership() {
290 'start_date' => '2010-12-20',
292 'membership_end_date' => '0',
293 'membership_join_date' => '2010-12-20',
294 'membership_start_date' => '2010-12-20',
296 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
297 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
298 $this->assertEquals('2010-12-20', $params['start_date']);
299 $this->assertEquals('20101220000000', $params['membership_start_date']);
300 $this->assertEquals('', $params['end_date']);
301 $this->assertEquals('20101220000000', $params['membership_join_date'], 'join_date not set in line ' . __LINE__
);
304 public function test_civicrm_api3_validate_fields_event() {
307 'registration_start_date' => 20080601,
308 'registration_end_date' => '2008-10-15',
309 'start_date' => '2010-12-20',
312 $fields = civicrm_api3('Event', 'getfields', ['action' => 'create']);
313 _civicrm_api3_validate_fields('event', 'create', $params, $fields['values']);
314 $this->assertEquals('20101220000000', $params['start_date']);
315 $this->assertEquals('20081015000000', $params['registration_end_date']);
316 $this->assertEquals('', $params['end_date']);
317 $this->assertEquals('20080601000000', $params['registration_start_date']);
320 public function test_civicrm_api3_validate_fields_exception() {
322 'membership_join_date' => 'abc',
325 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
326 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
328 catch (Exception
$expected) {
329 $this->assertEquals('membership_join_date is not a valid date: abc', $expected->getMessage());
333 public function testGetFields() {
334 $result = $this->callAPISuccess('membership', 'getfields', []);
335 $this->assertArrayHasKey('values', $result);
336 $result = $this->callAPISuccess('relationship', 'getfields', []);
337 $this->assertArrayHasKey('values', $result);
338 $result = $this->callAPISuccess('event', 'getfields', []);
339 $this->assertArrayHasKey('values', $result);
342 public function testGetFields_AllOptions() {
343 $result = $this->callAPISuccess('contact', 'getfields', [
345 'get_options' => 'all',
348 $this->assertEquals('Household', $result['values']['contact_type']['options']['Household']);
349 $this->assertEquals('HTML', $result['values']['preferred_mail_format']['options']['HTML']);
352 public function basicArrayCases() {
354 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
355 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
356 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
357 ['snack_id' => 'd', 'fruit' => 'apple', 'cheese' => 'gouda'],
358 ['snack_id' => 'e', 'fruit' => 'apple', 'cheese' => 'provolone'],
366 ['a', 'b', 'c', 'd', 'e'],
372 ['version' => 3, 'fruit' => 'apple'],
374 ['a', 'c', 'd', 'e'],
379 ['version' => 3, 'cheese' => 'cheddar'],
385 ['version' => 3, 'id' => 'd'],
393 * Make a basic API (Widget.get) which allows getting data out of a simple in-memory
397 * The list of all records.
399 * The filter criteria
400 * @param array $resultIds
401 * The records which are expected to match.
402 * @dataProvider basicArrayCases
404 public function testBasicArrayGet($records, $params, $resultIds) {
405 $params['version'] = 3;
407 $kernel = new \Civi\API\
Kernel(new \Symfony\Component\EventDispatcher\
EventDispatcher());
409 $provider = new \Civi\API\Provider\
AdhocProvider($params['version'], 'Widget');
410 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
411 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
413 $kernel->registerApiProvider($provider);
415 $r1 = $kernel->runSafe('Widget', 'get', $params);
416 $this->assertEquals(count($resultIds), $r1['count']);
417 $this->assertEquals($resultIds, array_keys($r1['values']));
418 $this->assertEquals($resultIds, array_values(CRM_Utils_Array
::collect('snack_id', $r1['values'])));
419 $this->assertEquals($resultIds, array_values(CRM_Utils_Array
::collect('id', $r1['values'])));
421 $r2 = $kernel->runSafe('Widget', 'get', $params +
['sequential' => 1]);
422 $this->assertEquals(count($resultIds), $r2['count']);
423 $this->assertEquals($resultIds, array_values(CRM_Utils_Array
::collect('snack_id', $r2['values'])));
424 $this->assertEquals($resultIds, array_values(CRM_Utils_Array
::collect('id', $r2['values'])));
426 $r3 = $kernel->runSafe('Widget', 'get', $params +
['options' => ['offset' => 1, 'limit' => 2]]);
427 $slice = array_slice($resultIds, 1, 2);
428 $this->assertEquals(count($slice), $r3['count']);
429 $this->assertEquals($slice, array_values(CRM_Utils_Array
::collect('snack_id', $r3['values'])));
430 $this->assertEquals($slice, array_values(CRM_Utils_Array
::collect('id', $r3['values'])));
433 public function testBasicArrayGetReturn() {
435 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
436 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
437 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
440 $kernel = new \Civi\API\
Kernel(new \Symfony\Component\EventDispatcher\
EventDispatcher());
441 $provider = new \Civi\API\Provider\
AdhocProvider(3, 'Widget');
442 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
443 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
445 $kernel->registerApiProvider($provider);
447 $r1 = $kernel->runSafe('Widget', 'get', [
452 $this->assertAPISuccess($r1);
453 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape']], $r1['values']);
455 $r2 = $kernel->runSafe('Widget', 'get', [
458 'return' => ['fruit', 'cheese'],
460 $this->assertAPISuccess($r2);
461 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar']], $r2['values']);
463 $r3 = $kernel->runSafe('Widget', 'get', [
465 'cheese' => 'cheddar',
466 'return' => ['fruit'],
468 $this->assertAPISuccess($r3);
469 $this->assertEquals([
470 'b' => ['id' => 'b', 'fruit' => 'grape'],
471 'c' => ['id' => 'c', 'fruit' => 'apple'],
476 * CRM-20892 Add Tests of new timestamp checking function
478 * @throws \CRM_Core_Exception
480 public function testTimeStampChecking() {
481 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_mailing (id, modified_date) VALUES (25, '2016-06-30 12:52:52')");
482 $this->assertTrue(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
483 $this->callAPISuccess('Mailing', 'create', ['id' => 25, 'subject' => 'Test Subject']);
484 $this->assertFalse(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
485 $this->callAPISuccess('Mailing', 'delete', ['id' => 25]);
489 * Test that the foreign key constraint test correctly interprets pseudoconstants.
491 * @throws \CRM_Core_Exception
492 * @throws \API_Exception
494 public function testKeyConstraintCheck() {
495 $fieldInfo = $this->callAPISuccess('Contribution', 'getfields', [])['values']['financial_type_id'];
496 _civicrm_api3_validate_constraint(1, 'financial_type_id', $fieldInfo, 'Contribution');
497 _civicrm_api3_validate_constraint('Donation', 'financial_type_id', $fieldInfo, 'Contribution');
499 _civicrm_api3_validate_constraint('Blah', 'financial_type_id', $fieldInfo, 'Contribution');
501 catch (API_Exception
$e) {
502 $this->assertEquals("'Blah' is not a valid option for field financial_type_id", $e->getMessage());
505 $this->fail('Last function call should have thrown an exception');