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');
86 * @param string $entity
87 * @param string $action
88 * @param array $params
90 * Whether we should pass any exceptions for authorization failures.
92 * @throws API_Exception
95 * TRUE or FALSE depending on the outcome of the authorization check
97 public function runPermissionCheck($entity, $action, $params, $throws = FALSE) {
98 $params['version'] = 3;
99 $dispatcher = new \Symfony\Component\EventDispatcher\
EventDispatcher();
100 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
101 $kernel = new \Civi\API\
Kernel($dispatcher);
102 $apiRequest = \Civi\API\Request
::create($entity, $action, $params);
104 $kernel->authorize(NULL, $apiRequest);
107 catch (\API_Exception
$e) {
108 $extra = $e->getExtraParams();
109 if (!$throws && $extra['error_code'] == API_Exception
::UNAUTHORIZED
) {
119 * Test verify mandatory - includes DAO & passed as well as empty & NULL fields
121 public function testVerifyMandatory() {
122 _civicrm_api3_initialize(TRUE);
124 'entity_table' => 'civicrm_contact',
126 'contact_id' => $this->_contactID
,
127 'modified_date' => '2011-01-31',
129 'version' => $this->_apiversion
,
132 civicrm_api3_verify_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
134 catch (Exception
$expected) {
135 $this->assertEquals('Mandatory key(s) missing from params array: note, subject', $expected->getMessage());
139 $this->fail('An expected exception has not been raised.');
143 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
145 public function testVerifyOneMandatory() {
146 _civicrm_api3_initialize(TRUE);
148 'entity_table' => 'civicrm_contact',
150 'contact_id' => $this->_contactID
,
151 'modified_date' => '2011-01-31',
153 'version' => $this->_apiversion
,
157 civicrm_api3_verify_one_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
159 catch (Exception
$expected) {
160 $this->assertEquals('Mandatory key(s) missing from params array: one of (note, subject)', $expected->getMessage());
164 $this->fail('An expected exception has not been raised.');
168 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
170 public function testVerifyOneMandatoryOneSet() {
171 _civicrm_api3_initialize(TRUE);
174 'entity_table' => 'civicrm_contact',
176 'contact_id' => $this->_contactID
,
177 'modified_date' => '2011-01-31',
182 civicrm_api3_verify_one_mandatory($params, NULL, ['note', 'subject']);
184 catch (Exception
$expected) {
185 $this->fail('Exception raised when it shouldn\'t have been in line ' . __LINE__
);
190 * Test GET DAO function returns DAO.
192 public function testGetDAO() {
194 'civicrm_api3_custom_group_get' => 'CRM_Core_DAO_CustomGroup',
195 'custom_group' => 'CRM_Core_DAO_CustomGroup',
196 'CustomGroup' => 'CRM_Core_DAO_CustomGroup',
197 'civicrm_api3_custom_field_get' => 'CRM_Core_DAO_CustomField',
198 'civicrm_api3_survey_get' => 'CRM_Campaign_DAO_Survey',
199 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_DAO_PledgePayment',
200 'civicrm_api3_website_get' => 'CRM_Core_DAO_Website',
201 'Membership' => 'CRM_Member_DAO_Membership',
203 foreach ($params as $input => $expected) {
204 $result = _civicrm_api3_get_DAO($input);
205 $this->assertEquals($expected, $result);
210 * Test GET BAO function returns BAO when it exists.
212 public function testGetBAO() {
214 'civicrm_api3_website_get' => 'CRM_Core_BAO_Website',
215 'civicrm_api3_survey_get' => 'CRM_Campaign_BAO_Survey',
216 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_BAO_PledgePayment',
217 'Household' => 'CRM_Contact_BAO_Contact',
218 // Note this one DOES NOT have a BAO so we expect to fall back on returning the DAO
219 'mailing_group' => 'CRM_Mailing_DAO_MailingGroup',
220 // Make sure we get null back with nonexistant entities
221 'civicrm_this_does_not_exist' => NULL,
223 foreach ($params as $input => $expected) {
224 $result = _civicrm_api3_get_BAO($input);
225 $this->assertEquals($expected, $result);
230 * Test the validate function transforms dates.
232 * @throws \CiviCRM_API3_Exception
235 public function test_civicrm_api3_validate_fields() {
236 $params = ['relationship_start_date' => '2010-12-20', 'relationship_end_date' => ''];
237 $fields = civicrm_api3('relationship', 'getfields', ['action' => 'get']);
238 _civicrm_api3_validate_fields('relationship', 'get', $params, $fields['values']);
239 $this->assertEquals('20101220000000', $params['relationship_start_date']);
240 $this->assertEquals('', $params['relationship_end_date']);
243 public function test_civicrm_api3_validate_fields_membership() {
245 'start_date' => '2010-12-20',
247 'membership_end_date' => '0',
248 'membership_join_date' => '2010-12-20',
249 'membership_start_date' => '2010-12-20',
251 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
252 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
253 $this->assertEquals('2010-12-20', $params['start_date']);
254 $this->assertEquals('20101220000000', $params['membership_start_date']);
255 $this->assertEquals('', $params['end_date']);
256 $this->assertEquals('20101220000000', $params['membership_join_date'], 'join_date not set in line ' . __LINE__
);
259 public function test_civicrm_api3_validate_fields_event() {
262 'registration_start_date' => 20080601,
263 'registration_end_date' => '2008-10-15',
264 'start_date' => '2010-12-20',
267 $fields = civicrm_api3('Event', 'getfields', ['action' => 'create']);
268 _civicrm_api3_validate_fields('event', 'create', $params, $fields['values']);
269 $this->assertEquals('20101220000000', $params['start_date']);
270 $this->assertEquals('20081015000000', $params['registration_end_date']);
271 $this->assertEquals('', $params['end_date']);
272 $this->assertEquals('20080601000000', $params['registration_start_date']);
275 public function test_civicrm_api3_validate_fields_exception() {
277 'membership_join_date' => 'abc',
280 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
281 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
283 catch (Exception
$expected) {
284 $this->assertEquals('membership_join_date is not a valid date: abc', $expected->getMessage());
288 public function testGetFields() {
289 $result = $this->callAPISuccess('membership', 'getfields', []);
290 $this->assertArrayHasKey('values', $result);
291 $result = $this->callAPISuccess('relationship', 'getfields', []);
292 $this->assertArrayHasKey('values', $result);
293 $result = $this->callAPISuccess('event', 'getfields', []);
294 $this->assertArrayHasKey('values', $result);
297 public function testGetFields_AllOptions() {
298 $result = $this->callAPISuccess('contact', 'getfields', [
300 'get_options' => 'all',
303 $this->assertEquals('Household', $result['values']['contact_type']['options']['Household']);
304 $this->assertEquals('HTML', $result['values']['preferred_mail_format']['options']['HTML']);
307 public function basicArrayCases() {
309 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
310 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
311 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
312 ['snack_id' => 'd', 'fruit' => 'apple', 'cheese' => 'gouda'],
313 ['snack_id' => 'e', 'fruit' => 'apple', 'cheese' => 'provolone'],
321 ['a', 'b', 'c', 'd', 'e'],
327 ['version' => 3, 'fruit' => 'apple'],
329 ['a', 'c', 'd', 'e'],
334 ['version' => 3, 'cheese' => 'cheddar'],
340 ['version' => 3, 'id' => 'd'],
348 * Make a basic API (Widget.get) which allows getting data out of a simple in-memory
352 * The list of all records.
354 * The filter criteria
355 * @param array $resultIds
356 * The records which are expected to match.
357 * @dataProvider basicArrayCases
359 public function testBasicArrayGet($records, $params, $resultIds) {
360 $params['version'] = 3;
362 $kernel = new \Civi\API\
Kernel(new \Symfony\Component\EventDispatcher\
EventDispatcher());
364 $provider = new \Civi\API\Provider\
AdhocProvider($params['version'], 'Widget');
365 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
366 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
368 $kernel->registerApiProvider($provider);
370 $r1 = $kernel->runSafe('Widget', 'get', $params);
371 $this->assertEquals(count($resultIds), $r1['count']);
372 $this->assertEquals($resultIds, array_keys($r1['values']));
373 $this->assertEquals($resultIds, array_values(CRM_Utils_Array
::collect('snack_id', $r1['values'])));
374 $this->assertEquals($resultIds, array_values(CRM_Utils_Array
::collect('id', $r1['values'])));
376 $r2 = $kernel->runSafe('Widget', 'get', $params +
['sequential' => 1]);
377 $this->assertEquals(count($resultIds), $r2['count']);
378 $this->assertEquals($resultIds, array_values(CRM_Utils_Array
::collect('snack_id', $r2['values'])));
379 $this->assertEquals($resultIds, array_values(CRM_Utils_Array
::collect('id', $r2['values'])));
381 $r3 = $kernel->runSafe('Widget', 'get', $params +
['options' => ['offset' => 1, 'limit' => 2]]);
382 $slice = array_slice($resultIds, 1, 2);
383 $this->assertEquals(count($slice), $r3['count']);
384 $this->assertEquals($slice, array_values(CRM_Utils_Array
::collect('snack_id', $r3['values'])));
385 $this->assertEquals($slice, array_values(CRM_Utils_Array
::collect('id', $r3['values'])));
388 public function testBasicArrayGetReturn() {
390 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
391 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
392 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
395 $kernel = new \Civi\API\
Kernel(new \Symfony\Component\EventDispatcher\
EventDispatcher());
396 $provider = new \Civi\API\Provider\
AdhocProvider(3, 'Widget');
397 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
398 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
400 $kernel->registerApiProvider($provider);
402 $r1 = $kernel->runSafe('Widget', 'get', [
407 $this->assertAPISuccess($r1);
408 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape']], $r1['values']);
410 $r2 = $kernel->runSafe('Widget', 'get', [
413 'return' => ['fruit', 'cheese'],
415 $this->assertAPISuccess($r2);
416 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar']], $r2['values']);
418 $r3 = $kernel->runSafe('Widget', 'get', [
420 'cheese' => 'cheddar',
421 'return' => ['fruit'],
423 $this->assertAPISuccess($r3);
424 $this->assertEquals([
425 'b' => ['id' => 'b', 'fruit' => 'grape'],
426 'c' => ['id' => 'c', 'fruit' => 'apple'],
431 * CRM-20892 Add Tests of new timestamp checking function
433 * @throws \CRM_Core_Exception
435 public function testTimeStampChecking() {
436 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_mailing (id, modified_date) VALUES (25, '2016-06-30 12:52:52')");
437 $this->assertTrue(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
438 $this->callAPISuccess('Mailing', 'create', ['id' => 25, 'subject' => 'Test Subject']);
439 $this->assertFalse(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
440 $this->callAPISuccess('Mailing', 'delete', ['id' => 25]);
444 * Test that the foreign key constraint test correctly interprets pseudoconstants.
446 * @throws \CRM_Core_Exception
447 * @throws \API_Exception
449 public function testKeyConstraintCheck() {
450 $fieldInfo = $this->callAPISuccess('Contribution', 'getfields', [])['values']['financial_type_id'];
451 _civicrm_api3_validate_constraint(1, 'financial_type_id', $fieldInfo, 'Contribution');
452 _civicrm_api3_validate_constraint('Donation', 'financial_type_id', $fieldInfo, 'Contribution');
454 _civicrm_api3_validate_constraint('Blah', 'financial_type_id', $fieldInfo, 'Contribution');
456 catch (API_Exception
$e) {
457 $this->assertEquals("'Blah' is not a valid option for field financial_type_id", $e->getMessage());
460 $this->fail('Last function call should have thrown an exception');