Merge pull request #15826 from seamuslee001/dev_core_183_dedupe
[civicrm-core.git] / tests / phpunit / api / v3 / SyntaxConformanceTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Test that the core actions for APIv3 entities comply with standard syntax+behavior.
14 *
15 * By default, this tests all API entities. To only test specific entities, call phpunit with
16 * environment variable SYNTAX_CONFORMANCE_ENTITIES, e.g.
17 *
18 * env SYNTAX_CONFORMANCE_ENTITIES="Contact Event" ./scripts/phpunit api_v3_SyntaxConformanceTest
19 *
20 * @package CiviCRM_APIv3
21 * @subpackage API_Core
22 * @group headless
23 */
24 class api_v3_SyntaxConformanceTest extends CiviUnitTestCase {
25 protected $_apiversion = 3;
26
27 /**
28 * @var array e.g. $this->deletes['CRM_Contact_DAO_Contact'][] = $contactID;
29 */
30 protected $deletableTestObjects;
31
32 /**
33 * This test case doesn't require DB reset.
34 * @var bool
35 */
36 public $DBResetRequired = FALSE;
37
38 protected $_entity;
39
40 /**
41 * Map custom group entities to civicrm components.
42 * @var array
43 */
44 protected static $componentMap = [
45 'Contribution' => 'CiviContribute',
46 'Membership' => 'CiviMember',
47 'Participant' => 'CiviEvent',
48 'Event' => 'CiviEvent',
49 'Case' => 'CiviCase',
50 'Pledge' => 'CiviPledge',
51 'Grant' => 'CiviGrant',
52 'Campaign' => 'CiviCampaign',
53 'Survey' => 'CiviCampaign',
54 ];
55
56 /**
57 * Set up function.
58 *
59 * There are two types of missing APIs:
60 * Those that are to be implemented
61 * (in some future version when someone steps in -hint hint-). List the entities in toBeImplemented[ {$action} ]
62 * Those that don't exist
63 * and that will never exist (eg an obsoleted Entity
64 * 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)
65 */
66 public function setUp() {
67 parent::setUp();
68 $this->enableCiviCampaign();
69 $this->toBeImplemented['get'] = [
70 // CxnApp.get exists but relies on remote data outside our control; QA w/UtilsTest::testBasicArrayGet
71 'CxnApp',
72 'Profile',
73 'CustomValue',
74 'Constant',
75 'CustomSearch',
76 'Extension',
77 'ReportTemplate',
78 'System',
79 'Setting',
80 'Payment',
81 'Logging',
82 ];
83 $this->toBeImplemented['create'] = [
84 'Cxn',
85 'CxnApp',
86 'SurveyRespondant',
87 'OptionGroup',
88 'MailingRecipients',
89 'UFMatch',
90 'CustomSearch',
91 'Extension',
92 'ReportTemplate',
93 'System',
94 'User',
95 'Payment',
96 'Order',
97 //work fine in local
98 'SavedSearch',
99 'Logging',
100 ];
101 $this->toBeImplemented['delete'] = [
102 'Cxn',
103 'CxnApp',
104 'MembershipPayment',
105 'OptionGroup',
106 'SurveyRespondant',
107 'UFJoin',
108 'UFMatch',
109 'Extension',
110 'System',
111 'Payment',
112 'Order',
113 ];
114 $this->onlyIDNonZeroCount['get'] = [
115 'ActivityType',
116 'Entity',
117 'Domain',
118 'Setting',
119 'User',
120 ];
121 $this->deprecatedAPI = ['Location', 'ActivityType', 'SurveyRespondant'];
122 $this->deletableTestObjects = [];
123 }
124
125 public function tearDown() {
126 foreach ($this->deletableTestObjects as $entityName => $entities) {
127 foreach ($entities as $entityID) {
128 CRM_Core_DAO::deleteTestObjects($entityName, ['id' => $entityID]);
129 }
130 }
131 }
132
133 /**
134 * Generate list of all entities.
135 *
136 * @param array $skip
137 * Entities to skip.
138 *
139 * @return array
140 */
141 public static function entities($skip = []) {
142 // The order of operations in here is screwy. In the case where SYNTAX_CONFORMANCE_ENTITIES is
143 // defined, we should be able to parse+return it immediately. However, some weird dependency
144 // crept into the system where civicrm_api('Entity','get') must be called as part of entities()
145 // (even if its return value is ignored).
146
147 $tmp = civicrm_api('Entity', 'Get', ['version' => 3]);
148 if (getenv('SYNTAX_CONFORMANCE_ENTITIES')) {
149 $tmp = [
150 'values' => explode(' ', getenv('SYNTAX_CONFORMANCE_ENTITIES')),
151 ];
152 }
153
154 if (!is_array($skip)) {
155 $skip = [];
156 }
157 $tmp = array_diff($tmp['values'], $skip);
158 $entities = [];
159 foreach ($tmp as $e) {
160 $entities[] = [$e];
161 }
162 return $entities;
163 }
164
165 /**
166 * Get list of entities for get test.
167 *
168 * @return array
169 */
170 public static function entities_get() {
171 // all the entities, beside the ones flagged
172 return static::entities(static::toBeSkipped_get(TRUE));
173 }
174
175 /**
176 * Get entities for create tests.
177 *
178 * @return array
179 */
180 public static function entities_create() {
181 return static::entities(static::toBeSkipped_create(TRUE));
182 }
183
184 /**
185 * @return array
186 */
187 public static function entities_updatesingle() {
188 return static::entities(static::toBeSkipped_updatesingle(TRUE));
189 }
190
191 /**
192 * @return array
193 */
194 public static function entities_getlimit() {
195 return static::entities(static::toBeSkipped_getlimit());
196 }
197
198 /**
199 * Generate list of entities that can be retrieved using SQL operator syntax.
200 *
201 * @return array
202 */
203 public static function entities_getSqlOperators() {
204 return static::entities(static::toBeSkipped_getSqlOperators());
205 }
206
207 /**
208 * @return array
209 */
210 public static function entities_delete() {
211 return static::entities(static::toBeSkipped_delete(TRUE));
212 }
213
214 /**
215 * @return array
216 */
217 public static function entities_getfields() {
218 return static::entities(static::toBeSkipped_getfields(TRUE));
219 }
220
221 /**
222 * @return array
223 */
224 public static function custom_data_entities_get() {
225 return static::custom_data_entities();
226 }
227
228 /**
229 * @return array
230 */
231 public static function custom_data_entities() {
232 $entities = CRM_Core_BAO_CustomQuery::$extendsMap;
233 $enabledComponents = Civi::settings()->get('enable_components');
234 $customDataEntities = [];
235 $invalidEntities = ['Individual', 'Organization', 'Household'];
236 $entitiesToFix = ['Case', 'Relationship'];
237 foreach ($entities as $entityName => $entity) {
238 if (!in_array($entityName, $invalidEntities)
239 && !in_array($entityName, $entitiesToFix)
240 ) {
241 if (!empty(self::$componentMap[$entityName]) && empty($enabledComponents[self::$componentMap[$entityName]])) {
242 CRM_Core_BAO_ConfigSetting::enableComponent(self::$componentMap[$entityName]);
243 }
244 $customDataEntities[] = [$entityName];
245 }
246 }
247 return $customDataEntities;
248 }
249
250 /**
251 * Add a smattering of entities that don't normally have custom data.
252 *
253 * @return array
254 */
255 public static function custom_data_incl_non_std_entities_get() {
256 return static::entities(static::toBeSkipped_custom_data_creatable(TRUE));
257 }
258
259 /**
260 * Get entities to be skipped on get tests.
261 *
262 * @param bool $sequential
263 *
264 * @return array
265 */
266 public static function toBeSkipped_get($sequential = FALSE) {
267 $entitiesWithoutGet = [
268 'MailingEventSubscribe',
269 'MailingEventConfirm',
270 'MailingEventResubscribe',
271 'MailingEventUnsubscribe',
272 'Location',
273 ];
274 if ($sequential === TRUE) {
275 return $entitiesWithoutGet;
276 }
277 $entities = [];
278 foreach ($entitiesWithoutGet as $e) {
279 $entities[] = [$e];
280 }
281 return $entities;
282 }
283
284 /**
285 * Get entities to be skipped for get call.
286 *
287 * Mailing Contact Just doesn't support id. We have always insisted on finding a way to
288 * support id in API but in this case the underlying tables are crying out for a restructure
289 * & it just doesn't make sense.
290 *
291 * User doesn't support get By ID because the user id is actually the CMS user ID & is not part of
292 * CiviCRM - so can only be tested through UserTest - not SyntaxConformanceTest.
293 *
294 * Entity doesn't support get By ID because it simply gives the result of string Entites in CiviCRM
295 *
296 * @param bool $sequential
297 *
298 * @return array
299 * Entities that cannot be retrieved by ID
300 */
301 public static function toBeSkipped_getByID($sequential = FALSE) {
302 return ['MailingContact', 'User', 'Attachment', 'Entity'];
303 }
304
305 /**
306 * @param bool $sequential
307 *
308 * @return array
309 */
310 public static function toBeSkipped_create($sequential = FALSE) {
311 $entitiesWithoutCreate = ['Constant', 'Entity', 'Location', 'Profile', 'MailingRecipients'];
312 if ($sequential === TRUE) {
313 return $entitiesWithoutCreate;
314 }
315 $entities = [];
316 foreach ($entitiesWithoutCreate as $e) {
317 $entities[] = [$e];
318 }
319 return $entities;
320 }
321
322 /**
323 * @param bool $sequential
324 *
325 * @return array
326 */
327 public static function toBeSkipped_delete($sequential = FALSE) {
328 $entitiesWithout = [
329 'MailingContact',
330 'MailingEventConfirm',
331 'MailingEventResubscribe',
332 'MailingEventSubscribe',
333 'MailingEventUnsubscribe',
334 'MailingRecipients',
335 'Constant',
336 'Entity',
337 'Location',
338 'Domain',
339 'Profile',
340 'CustomValue',
341 'Setting',
342 'User',
343 'Logging',
344 ];
345 if ($sequential === TRUE) {
346 return $entitiesWithout;
347 }
348 $entities = [];
349 foreach ($entitiesWithout as $e) {
350 $entities[] = [$e];
351 }
352 return $entities;
353 }
354
355 /**
356 * @param bool $sequential
357 *
358 * @return array
359 */
360 public static function toBeSkipped_custom_data_creatable($sequential = FALSE) {
361 $entitiesWithout = [
362 // Ones to fix.
363 'CaseContact',
364 'CustomField',
365 'CustomGroup',
366 'DashboardContact',
367 'Domain',
368 'File',
369 'FinancialType',
370 'LocBlock',
371 'MailingEventConfirm',
372 'MailingEventResubscribe',
373 'MailingEventSubscribe',
374 'MailingEventUnsubscribe',
375 'MembershipPayment',
376 'SavedSearch',
377 'UFJoin',
378 'UFField',
379 'PriceFieldValue',
380 'GroupContact',
381 'EntityTag',
382 'PledgePayment',
383 'Relationship',
384
385 // ones that are not real entities hence not extendable.
386 'ActivityType',
387 'Entity',
388 'Cxn',
389 'Constant',
390 'Attachment',
391 'CustomSearch',
392 'CustomValue',
393 'CxnApp',
394 'Extension',
395 'MailingContact',
396 'User',
397 'System',
398 'Setting',
399 'SystemLog',
400 'ReportTemplate',
401 'MailingRecipients',
402 'SurveyRespondant',
403 'Profile',
404 'Payment',
405 'Order',
406 'MailingGroup',
407 'Logging',
408 ];
409 if ($sequential === TRUE) {
410 return $entitiesWithout;
411 }
412 $entities = [];
413 foreach ($entitiesWithout as $e) {
414 $entities[] = [$e];
415 }
416 return $entities;
417 }
418
419 /**
420 * @param bool $sequential
421 *
422 * @return array
423 * @todo add metadata for ALL these entities
424 */
425 public static function toBeSkipped_getfields($sequential = FALSE) {
426 $entitiesWithMetadataNotYetFixed = ['ReportTemplate', 'CustomSearch'];
427 if ($sequential === TRUE) {
428 return $entitiesWithMetadataNotYetFixed;
429 }
430 $entities = [];
431 foreach ($entitiesWithMetadataNotYetFixed as $e) {
432 $entities[] = [$e];
433 }
434 return $entities;
435 }
436
437 /**
438 * Generate list of entities to test for get by id functions.
439 * @param bool $sequential
440 * @return array
441 * Entities to be skipped
442 */
443 public static function toBeSkipped_automock($sequential = FALSE) {
444 $entitiesWithoutGet = [
445 'MailingContact',
446 'EntityTag',
447 'Participant',
448 'Setting',
449 'SurveyRespondant',
450 'MailingRecipients',
451 'CustomSearch',
452 'Extension',
453 'ReportTemplate',
454 'System',
455 'Logging',
456 'Payment',
457 ];
458 if ($sequential === TRUE) {
459 return $entitiesWithoutGet;
460 }
461 $entities = [];
462 foreach ($entitiesWithoutGet as $e) {
463 $entities[] = [$e];
464 }
465 return $entities;
466 }
467
468 /**
469 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
470 * @param bool $sequential
471 * @return array
472 */
473 public static function toBeSkipped_updatesingle($sequential = FALSE) {
474 $entitiesWithout = [
475 'Attachment',
476 // pseudo-entity; testUpdateSingleValueAlter doesn't introspect properly on it. Multiple magic fields
477 'Mailing',
478 'MailingEventUnsubscribe',
479 'MailingEventSubscribe',
480 'Constant',
481 'Entity',
482 'Location',
483 'Profile',
484 'CustomValue',
485 'UFJoin',
486 'Relationship',
487 'RelationshipType',
488 'Note',
489 'Membership',
490 'Group',
491 'File',
492 'EntityTag',
493 'CustomField',
494 'CustomGroup',
495 'Contribution',
496 'ActivityType',
497 'MailingEventConfirm',
498 'Case',
499 'CaseContact',
500 'Contact',
501 'ContactType',
502 'MailingEventResubscribe',
503 'UFGroup',
504 'Activity',
505 'Event',
506 'GroupContact',
507 'MembershipPayment',
508 'Participant',
509 'LineItem',
510 'ContributionPage',
511 'Phone',
512 'PaymentProcessor',
513 'Setting',
514 'MailingContact',
515 'SystemLog',
516 //skip this because it doesn't make sense to update logs,
517 'Logging',
518 ];
519 if ($sequential === TRUE) {
520 return $entitiesWithout;
521 }
522 $entities = [];
523 foreach ($entitiesWithout as $e) {
524 $entities[] = [
525 $e,
526 ];
527 }
528 return ['pledge'];
529 return $entities;
530 }
531
532 /**
533 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
534 */
535 public static function toBeSkipped_getlimit() {
536 $entitiesWithout = [
537 'Case',
538 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
539 'EntityTag',
540 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
541 'Event',
542 // failed 'check that a 5 limit returns 5' - probably is_template field is wrong or something, or could be limit doesn't work right
543 'Extension',
544 // can't handle creating 25
545 'Note',
546 // fails on 5 limit - probably a set up problem
547 'Setting',
548 //a bit of a pseudoapi - keys by domain
549 'Payment',
550 // pseudoapi - problems with creating required sub entities.
551 ];
552 return $entitiesWithout;
553 }
554
555 /**
556 * At this stage exclude the ones that don't pass & add them as we can troubleshoot them
557 */
558 public static function toBeSkipped_getSqlOperators() {
559 $entitiesWithout = [
560 //case api has non-std mandatory fields one of (case_id, contact_id, activity_id, contact_id)
561 'Case',
562 // on the todo list!
563 'Contact',
564 // non-standard api - has inappropriate mandatory fields & doesn't implement limit
565 'EntityTag',
566 // can't handle creating 25
567 'Extension',
568 // note has a default get that isn't implemented in createTestObject -meaning you don't 'get' them
569 'Note',
570 //a bit of a pseudoapi - keys by domain
571 'Setting',
572 ];
573
574 // The testSqlOperators fails sporadically on MySQL 5.5, which is deprecated anyway.
575 // Test data providers should be able to run in pre-boot environment, so we connect directly to SQL server.
576 require_once 'DB.php';
577 $db = DB::connect(CIVICRM_DSN);
578 if ($db->connection instanceof mysqli && $db->connection->server_version < 50600) {
579 $entitiesWithout[] = 'Dedupe';
580 }
581
582 return $entitiesWithout;
583 }
584
585 /**
586 * @param $entity
587 * @param $key
588 *
589 * @return array
590 */
591 public function getKnownUnworkablesUpdateSingle($entity, $key) {
592 // can't update values are values for which updates don't result in the value being changed
593 $knownFailures = [
594 'ActionSchedule' => [
595 'cant_update' => [
596 'group_id',
597 ],
598 ],
599 'ActivityContact' => [
600 'cant_update' => [
601 'activity_id',
602 //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
603 ],
604 ],
605 'Address' => [
606 'cant_update' => [
607 //issues with country id - need to ensure same country
608 'state_province_id',
609 'world_region',
610 //creates relationship
611 'master_id',
612 ],
613 'cant_return' => ['street_parsing', 'skip_geocode', 'fix_address'],
614 ],
615 'Batch' => [
616 'cant_update' => [
617 // believe this field is defined in error
618 'entity_table',
619 ],
620 'cant_return' => [
621 'entity_table',
622 ],
623 ],
624 'CaseType' => [
625 'cant_update' => [
626 'definition',
627 ],
628 ],
629 'Domain' => ['cant_update' => ['domain_version']],
630 'MembershipBlock' => [
631 'cant_update' => [
632 // The fake/auto-generated values leave us unable to properly cleanup fake data
633 'entity_type',
634 'entity_id',
635 ],
636 ],
637 'MailingJob' => ['cant_update' => ['parent_id']],
638 'ContributionSoft' => [
639 'cant_update' => [
640 // can't be changed through api
641 'pcp_id',
642 ],
643 ],
644 'Email' => [
645 'cant_update' => [
646 // This is being legitimately manipulated to always have a valid primary - skip.
647 'is_primary',
648 ],
649 ],
650 'Navigation' => [
651 'cant_update' => [
652 // Weight is deliberately altered when this is changed - skip.
653 'parent_id',
654 ],
655 ],
656 'LocationType' => [
657 'cant_update' => [
658 // I'm on the fence about whether the test should skip or the behaviour is wrong.
659 // display_name is set to match name if display_name is not provided. It would be more 'normal'
660 // to only calculate a default IF id is not set - but perhaps the current behaviour is kind
661 // of what someone updating the name expects..
662 'name',
663 ],
664 ],
665 'Pledge' => [
666 'cant_update' => [
667 'pledge_original_installment_amount',
668 'installments',
669 'original_installment_amount',
670 'next_pay_date',
671 // can't be changed through API,
672 'amount',
673 ],
674 // if these are passed in they are retrieved from the wrong table
675 'break_return' => [
676 'honor_contact_id',
677 'cancel_date',
678 'contribution_page_id',
679 'financial_account_id',
680 'financial_type_id',
681 'currency',
682 ],
683 // can't be retrieved from api
684 'cant_return' => [
685 //due to uniquename missing
686 'honor_type_id',
687 'end_date',
688 'modified_date',
689 'acknowledge_date',
690 'start_date',
691 'frequency_day',
692 'currency',
693 'max_reminders',
694 'initial_reminder_day',
695 'additional_reminder_day',
696 'frequency_unit',
697 'pledge_contribution_page_id',
698 'pledge_status_id',
699 'pledge_campaign_id',
700 'pledge_financial_type_id',
701 ],
702 ],
703 'PaymentProcessorType' => [
704 'cant_update' => [
705 'billing_mode',
706 ],
707 'break_return' => [],
708 'cant_return' => [],
709 ],
710 'PriceFieldValue' => [
711 'cant_update' => [
712 //won't update as there is no 1 in the same price set
713 'weight',
714 ],
715 ],
716 'ReportInstance' => [
717 // View mode is part of the navigation which is not retrieved by the api.
718 'cant_return' => ['view_mode'],
719 ],
720 'SavedSearch' => [
721 // I think the fields below are generated based on form_values.
722 'cant_update' => [
723 'search_custom_id',
724 'where_clause',
725 'select_tables',
726 'where_tables',
727 ],
728 ],
729 'StatusPreference' => [
730 'break_return' => [
731 'ignore_severity',
732 ],
733 ],
734 'UFField' => [
735 'cant_update' => [
736 // These fields get auto-adjusted by the BAO prior to saving
737 'weight',
738 'location_type_id',
739 'phone_type_id',
740 'website_type_id',
741 // Not a real field
742 'option.autoweight',
743 ],
744 'break_return' => [
745 // These fields get auto-adjusted by the BAO prior to saving
746 'weight',
747 'field_type',
748 'location_type_id',
749 'phone_type_id',
750 'website_type_id',
751 // Not a real field
752 'option.autoweight',
753 ],
754 ],
755 'JobLog' => [
756 // For better or worse triggers override.
757 'break_return' => ['run_time'],
758 'cant_update' => ['run_time'],
759 ],
760 ];
761 if (empty($knownFailures[$entity]) || empty($knownFailures[$entity][$key])) {
762 return [];
763 }
764 return $knownFailures[$entity][$key];
765 }
766
767 /* ----- testing the _get ----- */
768
769 /**
770 * @dataProvider toBeSkipped_get
771 * Entities that don't need a get action
772 * @param $Entity
773 */
774 public function testNotImplemented_get($Entity) {
775 $result = civicrm_api($Entity, 'Get', ['version' => 3]);
776 $this->assertEquals(1, $result['is_error']);
777 // $this->assertContains("API ($Entity, Get) does not exist", $result['error_message']);
778 $this->assertRegExp('/API (.*) does not exist/', $result['error_message']);
779 }
780
781 /**
782 * @dataProvider entities
783 * @param $Entity
784 */
785 public function testGetFields($Entity) {
786 if (in_array($Entity, $this->deprecatedAPI) || $Entity == 'Entity' || $Entity == 'CustomValue') {
787 return;
788 }
789
790 $result = civicrm_api($Entity, 'getfields', ['version' => 3]);
791 $this->assertTrue(is_array($result['values']), "$Entity ::get fields doesn't return values array in line " . __LINE__);
792 foreach ($result['values'] as $key => $value) {
793 $this->assertTrue(is_array($value), $Entity . "::" . $key . " is not an array in line " . __LINE__);
794 }
795 }
796
797 /**
798 * @dataProvider entities_get
799 * @param $Entity
800 */
801 public function testEmptyParam_get($Entity) {
802
803 if (in_array($Entity, $this->toBeImplemented['get'])) {
804 // $this->markTestIncomplete("civicrm_api3_{$Entity}_get to be implemented");
805 return;
806 }
807 $result = civicrm_api($Entity, 'Get', []);
808 $this->assertEquals(1, $result['is_error']);
809 $this->assertContains("Unknown api version", $result['error_message']);
810 }
811
812 /**
813 * @dataProvider entities_get
814 * @Xdepends testEmptyParam_get // no need to test the simple if the empty doesn't work/is skipped. doesn't seem to work
815 * @param $Entity
816 */
817 public function testSimple_get($Entity) {
818 // $this->markTestSkipped("test gives core error on test server (but not on our locals). Skip until we can get server to pass");
819 if (in_array($Entity, $this->toBeImplemented['get'])) {
820 return;
821 }
822 $result = civicrm_api($Entity, 'Get', ['version' => 3]);
823 // @TODO: list the get that have mandatory params
824 if ($result['is_error']) {
825 $this->assertContains("Mandatory key(s) missing from params array", $result['error_message']);
826 // either id or contact_id or entity_id is one of the field missing
827 $this->assertContains("id", $result['error_message']);
828 }
829 else {
830 $this->assertEquals(3, $result['version']);
831 $this->assertArrayHasKey('count', $result);
832 $this->assertArrayHasKey('values', $result);
833 }
834 }
835
836 /**
837 * @dataProvider custom_data_incl_non_std_entities_get
838 * @param $entityName
839 */
840 public function testCustomDataGet($entityName) {
841 if ($entityName === 'Note') {
842 $this->markTestIncomplete('Note can not be processed here because of a vagary in the note api, it adds entity_table=contact to the get params when id is not present - which makes sense almost always but kills this test');
843 }
844 $this->quickCleanup(['civicrm_uf_match']);
845 // so subsidiary activities are created
846 $this->createLoggedInUser();
847
848 $entitiesWithNamingIssues = [
849 'SmsProvider' => 'Provider',
850 'AclRole' => 'EntityRole',
851 'MailingEventQueue' => 'Queue',
852 'Dedupe' => 'PrevNextCache',
853 ];
854
855 $usableName = !empty($entitiesWithNamingIssues[$entityName]) ? $entitiesWithNamingIssues[$entityName] : $entityName;
856 $optionName = CRM_Core_DAO_AllCoreTables::getTableForClass(CRM_Core_DAO_AllCoreTables::getFullName($usableName));
857
858 if (!isset(CRM_Core_BAO_CustomQuery::$extendsMap[$entityName])) {
859 $createdValue = $this->callAPISuccess('OptionValue', 'create', [
860 'option_group_id' => 'cg_extend_objects',
861 'label' => $usableName,
862 'value' => $usableName,
863 'name' => $optionName,
864 ]);
865 }
866 // We are not passing 'check_permissions' so the the more limited permissions *should* be
867 // ignored but per CRM-17700 there is a history of custom data applying permissions when it shouldn't.
868 CRM_Core_Config::singleton()->userPermissionClass->permissions = ['access CiviCRM', 'view my contact'];
869 $objects = $this->getMockableBAOObjects($entityName, 1);
870
871 // simple custom field
872 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, $usableName . 'Test.php');
873 $customFieldName = 'custom_' . $ids['custom_field_id'];
874 $params = ['id' => $objects[0]->id, 'custom_' . $ids['custom_field_id'] => "custom string"];
875 $result = $this->callAPISuccess($entityName, 'create', $params);
876 $this->assertTrue(isset($result['id']), 'no id on ' . $entityName);
877 $getParams = ['id' => $result['id'], 'return' => [$customFieldName]];
878 $check = $this->callAPISuccess($entityName, 'get', $getParams);
879 $this->assertTrue(!empty($check['values'][$check['id']][$customFieldName]), 'Custom data not present for ' . $entityName);
880 $this->assertEquals("custom string", $check['values'][$check['id']][$customFieldName], 'Custom data not present for ' . $entityName);
881 $this->customFieldDelete($ids['custom_field_id']);
882 $this->customGroupDelete($ids['custom_group_id']);
883
884 $ids2 = $this->entityCustomGroupWithSingleStringMultiSelectFieldCreate(__FUNCTION__, $usableName . 'Test.php');
885 $customFieldNameMultiSelect = 'custom_' . $ids2['custom_field_id'];
886 // String custom field, Multi-Select html type
887 foreach ($ids2['custom_field_group_options'] as $option_value => $option_label) {
888 $params = ['id' => $objects[0]->id, 'custom_' . $ids2['custom_field_id'] => $option_value];
889 $result = $this->callAPISuccess($entityName, 'create', $params);
890 $getParams = [$customFieldNameMultiSelect => $option_value, 'return' => [$customFieldNameMultiSelect]];
891 $this->callAPISuccessGetCount($entityName, $getParams, 1);
892 }
893
894 // cleanup
895 $this->customFieldDelete($ids2['custom_field_id']);
896 $this->customGroupDelete($ids2['custom_group_id']);
897
898 $this->callAPISuccess($entityName, 'delete', ['id' => $result['id']]);
899 $this->quickCleanup(['civicrm_uf_match']);
900 if (!empty($createdValue)) {
901 $this->callAPISuccess('OptionValue', 'delete', ['id' => $createdValue['id']]);
902 }
903 }
904
905 /**
906 * @dataProvider entities_get
907 * @param $Entity
908 */
909 public function testAcceptsOnlyID_get($Entity) {
910 // big random number. fun fact: if you multiply it by pi^e, the result is another random number, but bigger ;)
911 $nonExistantID = 30867307034;
912 if (in_array($Entity, $this->toBeImplemented['get'])
913 || in_array($Entity, $this->toBeSkipped_getByID())
914 ) {
915 return;
916 }
917
918 // FIXME
919 // the below function returns different values and hence an early return
920 // we'll fix this once beta1 is released
921 // return;
922
923 $result = civicrm_api($Entity, 'Get', ['version' => 3, 'id' => $nonExistantID]);
924
925 if ($result['is_error']) {
926 // just to get a clearer message in the log
927 $this->assertEquals("only id should be enough", $result['error_message']);
928 }
929 if (!in_array($Entity, $this->onlyIDNonZeroCount['get'])) {
930 $this->assertEquals(0, $result['count']);
931 }
932 }
933
934 /**
935 * Test getlist works
936 * @dataProvider entities_get
937 * @param $Entity
938 */
939 public function testGetList($Entity) {
940 if (in_array($Entity, $this->toBeImplemented['get'])
941 || in_array($Entity, $this->toBeSkipped_getByID())
942 ) {
943 return;
944 }
945 if (in_array($Entity, ['ActivityType', 'SurveyRespondant'])) {
946 $this->markTestSkipped();
947 }
948 $this->callAPISuccess($Entity, 'getlist', ['label_field' => 'id']);
949 }
950
951 /**
952 * Test getlist works when entity is lowercase
953 * @dataProvider entities_get
954 * @param $Entity
955 */
956 public function testGetListLowerCaseEntity($Entity) {
957 if (in_array($Entity, $this->toBeImplemented['get'])
958 || in_array($Entity, $this->toBeSkipped_getByID())
959 ) {
960 return;
961 }
962 if (in_array($Entity, ['ActivityType', 'SurveyRespondant'])) {
963 $this->markTestSkipped();
964 }
965 if ($Entity == 'UFGroup') {
966 $Entity = 'ufgroup';
967 }
968 $this->callAPISuccess($Entity, 'getlist', ['label_field' => 'id']);
969 }
970
971 /**
972 * Create two entities and make sure we can fetch them individually by ID.
973 *
974 * @dataProvider entities_get
975 *
976 * limitations include the problem with avoiding loops when creating test objects -
977 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
978 * Currency - only seems to support US
979 * @param $entityName
980 */
981 public function testByID_get($entityName) {
982 if (in_array($entityName, self::toBeSkipped_automock(TRUE))) {
983 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
984 return;
985 }
986
987 $baos = $this->getMockableBAOObjects($entityName);
988 list($baoObj1, $baoObj2) = $baos;
989
990 // fetch first by ID
991 $result = $this->callAPISuccess($entityName, 'get', [
992 'id' => $baoObj1->id,
993 ]);
994
995 $this->assertTrue(!empty($result['values'][$baoObj1->id]), 'Should find first object by id');
996 $this->assertEquals($baoObj1->id, $result['values'][$baoObj1->id]['id'], 'Should find id on first object');
997 $this->assertEquals(1, count($result['values']));
998
999 // fetch second by ID
1000 $result = $this->callAPISuccess($entityName, 'get', [
1001 'id' => $baoObj2->id,
1002 ]);
1003 $this->assertTrue(!empty($result['values'][$baoObj2->id]), 'Should find second object by id');
1004 $this->assertEquals($baoObj2->id, $result['values'][$baoObj2->id]['id'], 'Should find id on second object');
1005 $this->assertEquals(1, count($result['values']));
1006 }
1007
1008 /**
1009 * Ensure that the "get" operation accepts limiting the #result records.
1010 *
1011 * TODO Consider making a separate entity list ("entities_getlimit")
1012 * For the moment, the "entities_updatesingle" list should give a good
1013 * sense for which entities support createTestObject
1014 *
1015 * @dataProvider entities_getlimit
1016 *
1017 * @param string $entityName
1018 */
1019 public function testLimit($entityName) {
1020 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
1021 $cases = [];
1022 $cases[] = [
1023 ['options' => ['limit' => NULL]],
1024 30,
1025 'check that a NULL limit returns unlimited',
1026 ];
1027 $cases[] = [
1028 ['options' => ['limit' => FALSE]],
1029 30,
1030 'check that a FALSE limit returns unlimited',
1031 ];
1032 $cases[] = [
1033 ['options' => ['limit' => 0]],
1034 30,
1035 'check that a 0 limit returns unlimited',
1036 ];
1037 $cases[] = [
1038 ['options' => ['limit' => 5]],
1039 5,
1040 'check that a 5 limit returns 5',
1041 ];
1042 $cases[] = [
1043 [],
1044 25,
1045 'check that no limit returns 25',
1046 ];
1047
1048 $baoString = _civicrm_api3_get_BAO($entityName);
1049 if (empty($baoString)) {
1050 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1051 return;
1052 }
1053
1054 // make 30 test items -- 30 > 25 (the default limit)
1055 $ids = [];
1056 for ($i = 0; $i < 30; $i++) {
1057 $baoObj = CRM_Core_DAO::createTestObject($baoString, ['currency' => 'USD']);
1058 $ids[] = $baoObj->id;
1059 }
1060
1061 // each case is array(0 => $inputtedApiOptions, 1 => $expectedResultCount)
1062 foreach ($cases as $case) {
1063 $this->checkLimitAgainstExpected($entityName, $case[0], $case[1], $case[2]);
1064
1065 //non preferred / legacy syntax
1066 if (isset($case[0]['options']['limit'])) {
1067 $this->checkLimitAgainstExpected($entityName, ['rowCount' => $case[0]['options']['limit']], $case[1], $case[2]);
1068 $this->checkLimitAgainstExpected($entityName, ['option_limit' => $case[0]['options']['limit']], $case[1], $case[2]);
1069 $this->checkLimitAgainstExpected($entityName, ['option.limit' => $case[0]['options']['limit']], $case[1], $case[2]);
1070 }
1071 }
1072 foreach ($ids as $id) {
1073 CRM_Core_DAO::deleteTestObjects($baoString, ['id' => $id]);
1074 }
1075 }
1076
1077 /**
1078 * Ensure that the "get" operation accepts limiting the #result records.
1079 *
1080 * @dataProvider entities_getSqlOperators
1081 *
1082 * @param string $entityName
1083 */
1084 public function testSqlOperators($entityName) {
1085 $toBeIgnored = array_merge($this->toBeImplemented['get'],
1086 $this->deprecatedAPI,
1087 $this->toBeSkipped_get(TRUE),
1088 $this->toBeSkipped_getByID()
1089 );
1090 if (in_array($entityName, $toBeIgnored)) {
1091 return;
1092 }
1093
1094 $baoString = _civicrm_api3_get_BAO($entityName);
1095
1096 $entities = $this->callAPISuccess($entityName, 'get', ['options' => ['limit' => 0], 'return' => 'id']);
1097 $entities = array_keys($entities['values']);
1098 $totalEntities = count($entities);
1099 if ($totalEntities < 3) {
1100 $ids = [];
1101 for ($i = 0; $i < 3 - $totalEntities; $i++) {
1102 $baoObj = CRM_Core_DAO::createTestObject($baoString, ['currency' => 'USD']);
1103 $ids[] = $baoObj->id;
1104 }
1105 $totalEntities = 3;
1106 }
1107 $entities = $this->callAPISuccess($entityName, 'get', ['options' => ['limit' => 0]]);
1108 $entities = array_keys($entities['values']);
1109 $this->assertGreaterThan(2, $totalEntities);
1110 $this->callAPISuccess($entityName, 'getsingle', ['id' => ['IN' => [$entities[0]]]]);
1111 $this->callAPISuccessGetCount($entityName, ['id' => ['NOT IN' => [$entities[0]]]], $totalEntities - 1);
1112 $this->callAPISuccessGetCount($entityName, ['id' => ['>' => $entities[0]]], $totalEntities - 1);
1113 }
1114
1115 /**
1116 * Check that get fetches an appropriate number of results.
1117 *
1118 * @param string $entityName
1119 * Name of entity to test.
1120 * @param array $params
1121 * @param int $limit
1122 * @param string $message
1123 */
1124 public function checkLimitAgainstExpected($entityName, $params, $limit, $message) {
1125 $result = $this->callAPISuccess($entityName, 'get', $params);
1126 if ($limit == 30) {
1127 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
1128 $this->assertGreaterThanOrEqual($limit, $result['count'], $message);
1129 }
1130 else {
1131 $this->assertEquals($limit, $result['count'], $message);
1132 $this->assertEquals($limit, count($result['values']), $message);
1133 }
1134 }
1135
1136 /**
1137 * Create two entities and make sure we can fetch them individually by ID (e.g. using "contact_id=>2"
1138 * or "group_id=>4")
1139 *
1140 * @dataProvider entities_get
1141 *
1142 * limitations include the problem with avoiding loops when creating test objects -
1143 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1144 * Currency - only seems to support US
1145 * @param $entityName
1146 * @throws \PHPUnit\Framework\IncompleteTestError
1147 */
1148 public function testByIDAlias_get($entityName) {
1149 if (in_array($entityName, self::toBeSkipped_automock(TRUE))) {
1150 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1151 return;
1152 }
1153
1154 $baoString = _civicrm_api3_get_BAO($entityName);
1155 if (empty($baoString)) {
1156 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1157 return;
1158 }
1159
1160 $idFieldName = _civicrm_api_get_entity_name_from_camel($entityName) . '_id';
1161
1162 // create entities
1163 $baoObj1 = CRM_Core_DAO::createTestObject($baoString, ['currency' => 'USD']);
1164 $this->assertTrue(is_int($baoObj1->id), 'check first id');
1165 $this->deletableTestObjects[$baoString][] = $baoObj1->id;
1166 $baoObj2 = CRM_Core_DAO::createTestObject($baoString, ['currency' => 'USD']);
1167 $this->assertTrue(is_int($baoObj2->id), 'check second id');
1168 $this->deletableTestObjects[$baoString][] = $baoObj2->id;
1169
1170 // fetch first by ID
1171 $result = civicrm_api($entityName, 'get', [
1172 'version' => 3,
1173 $idFieldName => $baoObj1->id,
1174 ]);
1175 $this->assertAPISuccess($result);
1176 $this->assertTrue(!empty($result['values'][$baoObj1->id]), 'Should find first object by id');
1177 $this->assertEquals($baoObj1->id, $result['values'][$baoObj1->id]['id'], 'Should find id on first object');
1178 $this->assertEquals(1, count($result['values']));
1179
1180 // fetch second by ID
1181 $result = civicrm_api($entityName, 'get', [
1182 'version' => 3,
1183 $idFieldName => $baoObj2->id,
1184 ]);
1185 $this->assertAPISuccess($result);
1186 $this->assertTrue(!empty($result['values'][$baoObj2->id]), 'Should find second object by id');
1187 $this->assertEquals($baoObj2->id, $result['values'][$baoObj2->id]['id'], 'Should find id on second object');
1188 $this->assertEquals(1, count($result['values']));
1189 }
1190
1191 /**
1192 * @dataProvider entities_get
1193 * @param $Entity
1194 */
1195 public function testNonExistantID_get($Entity) {
1196 // cf testAcceptsOnlyID_get
1197 $nonExistantID = 30867307034;
1198 if (in_array($Entity, $this->toBeImplemented['get'])) {
1199 return;
1200 }
1201
1202 $result = civicrm_api($Entity, 'Get', ['version' => 3, 'id' => $nonExistantID]);
1203
1204 // redundant with testAcceptsOnlyID_get
1205 if ($result['is_error']) {
1206 return;
1207 }
1208
1209 $this->assertArrayHasKey('version', $result);
1210 $this->assertEquals(3, $result['version']);
1211 if (!in_array($Entity, $this->onlyIDNonZeroCount['get'])) {
1212 $this->assertEquals(0, $result['count']);
1213 }
1214 }
1215
1216 /* ---- testing the _create ---- */
1217
1218 /**
1219 * @dataProvider toBeSkipped_create
1220 * entities that don't need a create action
1221 * @param $Entity
1222 */
1223 public function testNotImplemented_create($Entity) {
1224 $result = civicrm_api($Entity, 'Create', ['version' => 3]);
1225 $this->assertEquals(1, $result['is_error']);
1226 $this->assertContains(strtolower("API ($Entity, Create) does not exist"), strtolower($result['error_message']));
1227 }
1228
1229 /**
1230 * @dataProvider entities
1231 * @expectedException CiviCRM_API3_Exception
1232 * @param $Entity
1233 */
1234 public function testWithoutParam_create($Entity) {
1235 if ($Entity === 'Setting') {
1236 $this->markTestSkipped('It seems OK for setting to skip here as it silently sips invalid params');
1237 }
1238 elseif ($Entity === 'Mailing') {
1239 $this->markTestSkipped('It seems OK for "Mailing" to skip here because you can create empty drafts');
1240 }
1241 // should create php complaining that a param is missing
1242 civicrm_api3($Entity, 'Create');
1243 }
1244
1245 /**
1246 * @dataProvider entities_create
1247 *
1248 * Check that create doesn't work with an invalid
1249 * @param $Entity
1250 * @throws \PHPUnit\Framework\IncompleteTestError
1251 */
1252 public function testInvalidSort_get($Entity) {
1253 $invalidEntitys = ['ActivityType', 'Setting', 'System'];
1254 if (in_array($Entity, $invalidEntitys)) {
1255 $this->markTestSkipped('It seems OK for ' . $Entity . ' to skip here as it silently sips invalid params');
1256 }
1257 $result = $this->callAPIFailure($Entity, 'get', ['options' => ['sort' => 'sleep(1)']]);
1258 }
1259
1260 /**
1261 * @dataProvider entities_create
1262 *
1263 * Check that create doesn't work with an invalid
1264 * @param $Entity
1265 * @throws \PHPUnit\Framework\IncompleteTestError
1266 */
1267 public function testValidSortSingleArrayById_get($Entity) {
1268 $invalidEntitys = ['ActivityType', 'Setting', 'System'];
1269 $tests = [
1270 'id' => '_id',
1271 'id desc' => '_id desc',
1272 'id DESC' => '_id DESC',
1273 'id ASC' => '_id ASC',
1274 'id asc' => '_id asc',
1275 ];
1276 foreach ($tests as $test => $expected) {
1277 if (in_array($Entity, $invalidEntitys)) {
1278 $this->markTestSkipped('It seems OK for ' . $Entity . ' to skip here as it silently ignores passed in params');
1279 }
1280 $params = ['sort' => [$test]];
1281 $result = _civicrm_api3_get_options_from_params($params, FALSE, $Entity, 'get');
1282 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($Entity);
1283 $this->assertEquals($lowercase_entity . $expected, $result['sort']);
1284 }
1285 }
1286
1287 /**
1288 * @dataProvider entities_create
1289 *
1290 * Check that create doesn't work with an invalid
1291 * @param $Entity
1292 * @throws \PHPUnit\Framework\IncompleteTestError
1293 */
1294 public function testInvalidID_create($Entity) {
1295 // turn test off for noew
1296 $this->markTestIncomplete("Entity [ $Entity ] cannot be mocked - no known DAO");
1297 return;
1298 if (in_array($Entity, $this->toBeImplemented['create'])) {
1299 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1300 return;
1301 }
1302 $result = $this->callAPIFailure($Entity, 'Create', ['id' => 999]);
1303 }
1304
1305 /**
1306 * @dataProvider entities_updatesingle
1307 *
1308 * limitations include the problem with avoiding loops when creating test objects -
1309 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1310 * Currency - only seems to support US
1311 * @param $entityName
1312 */
1313 public function testCreateSingleValueAlter($entityName) {
1314 if (in_array($entityName, $this->toBeImplemented['create'])) {
1315 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1316 return;
1317 }
1318
1319 $baoString = _civicrm_api3_get_BAO($entityName);
1320 $this->assertNotEmpty($baoString, $entityName);
1321 $this->assertNotEmpty($entityName, $entityName);
1322 $fieldsGet = $fields = $this->callAPISuccess($entityName, 'getfields', ['action' => 'get', 'options' => ['get_options' => 'all']]);
1323 if ($entityName != 'Pledge') {
1324 $fields = $this->callAPISuccess($entityName, 'getfields', ['action' => 'create', 'options' => ['get_options' => 'all']]);
1325 }
1326 $fields = $fields['values'];
1327 $return = array_keys($fieldsGet['values']);
1328 $valuesNotToReturn = $this->getKnownUnworkablesUpdateSingle($entityName, 'break_return');
1329 // these can't be requested as return values
1330 $entityValuesThatDoNotWork = array_merge(
1331 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_update'),
1332 $this->getKnownUnworkablesUpdateSingle($entityName, 'cant_return'),
1333 $valuesNotToReturn
1334 );
1335
1336 $return = array_diff($return, $valuesNotToReturn);
1337 $baoObj = new CRM_Core_DAO();
1338 $baoObj->createTestObject($baoString, ['currency' => 'USD'], 2, 0);
1339
1340 $getEntities = $this->callAPISuccess($entityName, 'get', [
1341 'sequential' => 1,
1342 'return' => $return,
1343 'options' => [
1344 'sort' => 'id DESC',
1345 'limit' => 2,
1346 ],
1347 ]);
1348
1349 // lets use first rather than assume only one exists
1350 $entity = $getEntities['values'][0];
1351 $entity2 = $getEntities['values'][1];
1352 $this->deletableTestObjects[$baoString][] = $entity['id'];
1353 $this->deletableTestObjects[$baoString][] = $entity2['id'];
1354 // Skip these fields that we never really expect to update well.
1355 $genericFieldsToSkip = ['currency', 'id', strtolower($entityName) . '_id', 'is_primary'];
1356 foreach ($fields as $field => $specs) {
1357 $resetFKTo = NULL;
1358 $fieldName = $field;
1359
1360 if (in_array($field, $genericFieldsToSkip)
1361 || in_array($field, $entityValuesThatDoNotWork)
1362 ) {
1363 //@todo id & entity_id are correct but we should fix currency & frequency_day
1364 continue;
1365 }
1366 $this->assertArrayHasKey('type', $specs, "the _spec function for $entityName field $field does not specify the type");
1367 switch ($specs['type']) {
1368 case CRM_Utils_Type::T_DATE:
1369 $entity[$fieldName] = '2012-05-20';
1370 break;
1371
1372 case CRM_Utils_Type::T_TIMESTAMP:
1373 case 12:
1374 $entity[$fieldName] = '2012-05-20 03:05:20';
1375 break;
1376
1377 case CRM_Utils_Type::T_STRING:
1378 case CRM_Utils_Type::T_BLOB:
1379 case CRM_Utils_Type::T_MEDIUMBLOB:
1380 case CRM_Utils_Type::T_TEXT:
1381 case CRM_Utils_Type::T_LONGTEXT:
1382 case CRM_Utils_Type::T_EMAIL:
1383 if ($fieldName == 'form_values' && $entityName == 'SavedSearch') {
1384 // This is a hack for the SavedSearch API.
1385 // It expects form_values to be an array.
1386 // If you want to fix this, you should definitely read this forum
1387 // post.
1388 // http://forum.civicrm.org/index.php/topic,33990.0.html
1389 // See also my question on the CiviCRM Stack Exchange:
1390 // https://civicrm.stackexchange.com/questions/3437
1391 $entity[$fieldName] = ['sort_name' => "SortName2"];
1392 }
1393 else {
1394 $entity[$fieldName] = substr('New String', 0, CRM_Utils_Array::Value('maxlength', $specs, 100));
1395 if ($fieldName == 'email') {
1396 $entity[$fieldName] = strtolower($entity[$fieldName]);
1397 }
1398 // typecast with array to satisfy changes made in CRM-13160
1399 if ($entityName == 'MembershipType' && in_array($fieldName, [
1400 'relationship_type_id',
1401 'relationship_direction',
1402 ])) {
1403 $entity[$fieldName] = (array) $entity[$fieldName];
1404 }
1405 }
1406 break;
1407
1408 case CRM_Utils_Type::T_INT:
1409 // probably created with a 1
1410 if ($fieldName == 'weight') {
1411 $entity[$fieldName] = 2;
1412 }
1413 elseif (!empty($specs['FKClassName'])) {
1414 if ($specs['FKClassName'] == $baoString) {
1415 $entity[$fieldName] = (string) $entity2['id'];
1416 }
1417 else {
1418 if (!empty($entity[$fieldName])) {
1419 $resetFKTo = [$fieldName => $entity[$fieldName]];
1420 }
1421 $entity[$fieldName] = (string) empty($entity2[$field]) ? '' : $entity2[$field];
1422 //todo - there isn't always something set here - & our checking on unset values is limited
1423 if (empty($entity[$field])) {
1424 unset($entity[$field]);
1425 }
1426 }
1427 }
1428 else {
1429 $entity[$fieldName] = '6';
1430 }
1431 break;
1432
1433 case CRM_Utils_Type::T_BOOLEAN:
1434 // probably created with a 1
1435 $entity[$fieldName] = '0';
1436 break;
1437
1438 case CRM_Utils_Type::T_FLOAT:
1439 case CRM_Utils_Type::T_MONEY:
1440 $entity[$field] = '22.75';
1441 break;
1442
1443 case CRM_Utils_Type::T_URL:
1444 $entity[$field] = 'warm.beer.com';
1445 }
1446 if (empty($specs['FKClassName']) && (!empty($specs['pseudoconstant']) || !empty($specs['options']))) {
1447 $options = CRM_Utils_Array::value('options', $specs, []);
1448 if (!$options) {
1449 //eg. pdf_format id doesn't ship with any
1450 if (isset($specs['pseudoconstant']['optionGroupName'])) {
1451 $optionValue = $this->callAPISuccess('option_value', 'create', [
1452 'option_group_id' => $specs['pseudoconstant']['optionGroupName'],
1453 'label' => 'new option value',
1454 'sequential' => 1,
1455 ]);
1456 $optionValue = $optionValue['values'];
1457 $keyColumn = CRM_Utils_Array::value('keyColumn', $specs['pseudoconstant'], 'value');
1458 $options[$optionValue[0][$keyColumn]] = 'new option value';
1459 }
1460 }
1461 $entity[$field] = array_rand($options);
1462 }
1463 if (!empty($specs['FKClassName']) && !empty($specs['pseudoconstant'])) {
1464 // in the weird situation where a field has both an fk and pseudoconstant defined,
1465 // e.g. campaign_id field, need to flush caches.
1466 // FIXME: Why doesn't creating a campaign clear caches?
1467 civicrm_api3($entityName, 'getfields', ['cache_clear' => 1]);
1468 }
1469 $updateParams = [
1470 'id' => $entity['id'],
1471 $field => isset($entity[$field]) ? $entity[$field] : NULL,
1472 ];
1473 if (isset($updateParams['financial_type_id']) && in_array($entityName, ['Grant'])) {
1474 //api has special handling on these 2 fields for backward compatibility reasons
1475 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1476 }
1477 if (isset($updateParams['next_sched_contribution_date']) && in_array($entityName, ['ContributionRecur'])) {
1478 //api has special handling on these 2 fields for backward compatibility reasons
1479 $entity['next_sched_contribution'] = $updateParams['next_sched_contribution_date'];
1480 }
1481 if (isset($updateParams['image'])) {
1482 // Image field is passed through simplifyURL function so may be different, do the same here for comparison
1483 $entity['image'] = CRM_Utils_String::simplifyURL($updateParams['image'], TRUE);
1484 }
1485 if (isset($updateParams['thumbnail'])) {
1486 // Thumbnail field is passed through simplifyURL function so may be different, do the same here for comparison
1487 $entity['thumbnail'] = CRM_Utils_String::simplifyURL($updateParams['thumbnail'], TRUE);
1488 }
1489
1490 $update = $this->callAPISuccess($entityName, 'create', $updateParams);
1491 $checkParams = [
1492 'id' => $entity['id'],
1493 'sequential' => 1,
1494 'return' => $return,
1495 'options' => [
1496 'sort' => 'id DESC',
1497 'limit' => 2,
1498 ],
1499 ];
1500
1501 $checkEntity = $this->callAPISuccess($entityName, 'getsingle', $checkParams);
1502 if (!empty($specs['serialize']) && !is_array($checkEntity[$field])) {
1503 // Put into serialized format for comparison if 'get' has not returned serialized.
1504 $entity[$field] = CRM_Core_DAO::serializeField($checkEntity[$field], $specs['serialize']);
1505 }
1506
1507 $this->assertAPIArrayComparison($entity, $checkEntity, [], "checking if $fieldName was correctly updated\n" . print_r([
1508 'update-params' => $updateParams,
1509 'update-result' => $update,
1510 'getsingle-params' => $checkParams,
1511 'getsingle-result' => $checkEntity,
1512 'expected entity' => $entity,
1513 ], TRUE));
1514 if ($resetFKTo) {
1515 //reset the foreign key fields because otherwise our cleanup routine fails & some other unexpected stuff can kick in
1516 $entity = array_merge($entity, $resetFKTo);
1517 $updateParams = array_merge($updateParams, $resetFKTo);
1518 $this->callAPISuccess($entityName, 'create', $updateParams);
1519 if (isset($updateParams['financial_type_id']) && in_array($entityName, ['Grant'])) {
1520 //api has special handling on these 2 fields for backward compatibility reasons
1521 $entity['contribution_type_id'] = $updateParams['financial_type_id'];
1522 }
1523 if (isset($updateParams['next_sched_contribution_date']) && in_array($entityName, ['ContributionRecur'])) {
1524 //api has special handling on these 2 fields for backward compatibility reasons
1525 $entity['next_sched_contribution'] = $updateParams['next_sched_contribution_date'];
1526 }
1527 }
1528 }
1529 }
1530
1531 /* ---- testing the _getFields ---- */
1532
1533 /* ---- testing the _delete ---- */
1534
1535 /**
1536 * @dataProvider toBeSkipped_delete
1537 * entities that don't need a delete action
1538 * @param $Entity
1539 */
1540 public function testNotImplemented_delete($Entity) {
1541 $nonExistantID = 151416349;
1542 $result = civicrm_api($Entity, 'Delete', ['version' => 3, 'id' => $nonExistantID]);
1543 $this->assertEquals(1, $result['is_error']);
1544 $this->assertContains(strtolower("API ($Entity, Delete) does not exist"), strtolower($result['error_message']));
1545 }
1546
1547 /**
1548 * @dataProvider entities_delete
1549 * @param $Entity
1550 */
1551 public function testEmptyParam_delete($Entity) {
1552 if (in_array($Entity, $this->toBeImplemented['delete'])) {
1553 // $this->markTestIncomplete("civicrm_api3_{$Entity}_delete to be implemented");
1554 return;
1555 }
1556 $result = civicrm_api($Entity, 'Delete', []);
1557 $this->assertEquals(1, $result['is_error']);
1558 $this->assertContains("Unknown api version", $result['error_message']);
1559 }
1560
1561 /**
1562 * @dataProvider entities_delete
1563 * @param $Entity
1564 * @throws \PHPUnit\Framework\IncompleteTestError
1565 */
1566 public function testInvalidID_delete($Entity) {
1567 $result = $this->callAPIFailure($Entity, 'Delete', ['id' => 999999]);
1568 }
1569
1570 /**
1571 * Create two entities and make sure delete action only deletes one!
1572 *
1573 * @dataProvider entities_delete
1574 *
1575 * limitations include the problem with avoiding loops when creating test objects -
1576 * hence FKs only set by createTestObject when required. e.g parent_id on campaign is not being followed through
1577 * Currency - only seems to support US
1578 * @param $entityName
1579 * @throws \PHPUnit\Framework\IncompleteTestError
1580 */
1581 public function testByID_delete($entityName) {
1582 // turn test off for noew
1583 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1584 return;
1585
1586 if (in_array($entityName, self::toBeSkipped_automock(TRUE))) {
1587 // $this->markTestIncomplete("civicrm_api3_{$Entity}_create to be implemented");
1588 return;
1589 }
1590 $startCount = $this->callAPISuccess($entityName, 'getcount', []);
1591 $createcount = 2;
1592 $baos = $this->getMockableBAOObjects($entityName, $createcount);
1593 list($baoObj1, $baoObj2) = $baos;
1594
1595 // make sure exactly 2 exist
1596 $result = $this->callAPISuccess($entityName, 'getcount', [],
1597 $createcount + $startCount
1598 );
1599
1600 $this->callAPISuccess($entityName, 'delete', ['id' => $baoObj2->id]);
1601 //make sure 1 less exists now
1602 $result = $this->callAPISuccess($entityName, 'getcount', [],
1603 ($createcount + $startCount) - 1
1604 );
1605
1606 //make sure id #1 exists
1607 $result = $this->callAPISuccess($entityName, 'getcount', ['id' => $baoObj1->id],
1608 1
1609 );
1610 //make sure id #2 desn't exist
1611 $result = $this->callAPISuccess($entityName, 'getcount', ['id' => $baoObj2->id],
1612 0
1613 );
1614 }
1615
1616 /**
1617 * Create two entities and make sure delete action only deletes one!
1618 *
1619 * @dataProvider entities_getfields
1620 * @param $entity
1621 */
1622 public function testGetfieldsHasTitle($entity) {
1623 $entities = $this->getEntitiesSupportingCustomFields();
1624 if (in_array($entity, $entities)) {
1625 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, $entity . 'Test.php');
1626 }
1627 $actions = $this->callAPISuccess($entity, 'getactions', []);
1628 foreach ($actions['values'] as $action) {
1629 if (substr($action, -7) == '_create' || substr($action, -4) == '_get' || substr($action, -7) == '_delete') {
1630 //getactions can't distinguish between contribution_page.create & contribution_page.create
1631 continue;
1632 }
1633 $fields = $this->callAPISuccess($entity, 'getfields', ['action' => $action]);
1634 if (!empty($ids) && in_array($action, ['create', 'get'])) {
1635 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $fields['values']);
1636 }
1637
1638 foreach ($fields['values'] as $fieldName => $fieldSpec) {
1639 $this->assertArrayHasKey('title', $fieldSpec, "no title for $entity - $fieldName on action $action");
1640 $this->assertNotEmpty($fieldSpec['title'], "empty title for $entity - $fieldName");
1641 }
1642 }
1643 if (!empty($ids)) {
1644 $this->customFieldDelete($ids['custom_field_id']);
1645 $this->customGroupDelete($ids['custom_group_id']);
1646 }
1647 }
1648
1649 /**
1650 * @return array
1651 */
1652 public function getEntitiesSupportingCustomFields() {
1653 $entities = self::custom_data_entities_get();
1654 $returnEntities = [];
1655 foreach ($entities as $entityArray) {
1656 $returnEntities[] = $entityArray[0];
1657 }
1658 return $returnEntities;
1659 }
1660
1661 /**
1662 * @param string $entityName
1663 * @param int $count
1664 *
1665 * @return array
1666 */
1667 private function getMockableBAOObjects($entityName, $count = 2) {
1668 $baoString = _civicrm_api3_get_BAO($entityName);
1669 if (empty($baoString)) {
1670 $this->markTestIncomplete("Entity [$entityName] cannot be mocked - no known DAO");
1671 return [];
1672 }
1673 $baos = [];
1674 $i = 0;
1675 while ($i < $count) {
1676 // create entities
1677 $baoObj = CRM_Core_DAO::createTestObject($baoString, ['currency' => 'USD']);
1678 $this->assertTrue(is_int($baoObj->id), 'check first id');
1679 $this->deletableTestObjects[$baoString][] = $baoObj->id;
1680 $baos[] = $baoObj;
1681 $i++;
1682 }
1683 return $baos;
1684 }
1685
1686 /**
1687 * Verify that HTML metacharacters provided as inputs appear consistently.
1688 * as outputs.
1689 *
1690 * At time of writing, the encoding scheme requires (for example) that an
1691 * event title be partially-HTML-escaped before writing to DB. To provide
1692 * consistency, the API must perform extra encoding and decoding on some
1693 * fields.
1694 *
1695 * In this example, the event 'title' is subject to encoding, but the
1696 * event 'description' is not.
1697 */
1698 public function testEncodeDecodeConsistency() {
1699 // Create example
1700 $createResult = civicrm_api('Event', 'Create', [
1701 'version' => 3,
1702 'title' => 'CiviCRM <> TheRest',
1703 'description' => 'TheRest <> CiviCRM',
1704 'event_type_id' => 1,
1705 'is_public' => 1,
1706 'start_date' => 20081021,
1707 ]);
1708 $this->assertAPISuccess($createResult);
1709 $eventId = $createResult['id'];
1710 $this->assertEquals('CiviCRM <> TheRest', $createResult['values'][$eventId]['title']);
1711 $this->assertEquals('TheRest <> CiviCRM', $createResult['values'][$eventId]['description']);
1712
1713 // Verify "get" handles decoding in result value
1714 $getByIdResult = civicrm_api('Event', 'Get', [
1715 'version' => 3,
1716 'id' => $eventId,
1717 ]);
1718 $this->assertAPISuccess($getByIdResult);
1719 $this->assertEquals('CiviCRM <> TheRest', $getByIdResult['values'][$eventId]['title']);
1720 $this->assertEquals('TheRest <> CiviCRM', $getByIdResult['values'][$eventId]['description']);
1721
1722 // Verify "get" handles encoding in search value
1723 $getByTitleResult = civicrm_api('Event', 'Get', [
1724 'version' => 3,
1725 'title' => 'CiviCRM <> TheRest',
1726 ]);
1727 $this->assertAPISuccess($getByTitleResult);
1728 $this->assertEquals('CiviCRM <> TheRest', $getByTitleResult['values'][$eventId]['title']);
1729 $this->assertEquals('TheRest <> CiviCRM', $getByTitleResult['values'][$eventId]['description']);
1730
1731 // Verify that "getSingle" handles decoding
1732 $getSingleResult = $this->callAPISuccess('Event', 'GetSingle', [
1733 'id' => $eventId,
1734 ]);
1735
1736 $this->assertEquals('CiviCRM <> TheRest', $getSingleResult['title']);
1737 $this->assertEquals('TheRest <> CiviCRM', $getSingleResult['description']);
1738
1739 // Verify that chaining handles decoding
1740 $chainResult = $this->callAPISuccess('Event', 'Get', [
1741 'id' => $eventId,
1742 'api.event.get' => [],
1743 ]);
1744 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['title']);
1745 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['description']);
1746 $this->assertEquals('CiviCRM <> TheRest', $chainResult['values'][$eventId]['api.event.get']['values'][0]['title']);
1747 $this->assertEquals('TheRest <> CiviCRM', $chainResult['values'][$eventId]['api.event.get']['values'][0]['description']);
1748
1749 // Verify that "setvalue" handles encoding for updates
1750 $setValueTitleResult = civicrm_api('Event', 'setvalue', [
1751 'version' => 3,
1752 'id' => $eventId,
1753 'field' => 'title',
1754 'value' => 'setValueTitle: CiviCRM <> TheRest',
1755 ]);
1756 $this->assertAPISuccess($setValueTitleResult);
1757 $this->assertEquals('setValueTitle: CiviCRM <> TheRest', $setValueTitleResult['values']['title']);
1758 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', [
1759 'version' => 3,
1760 'id' => $eventId,
1761 'field' => 'description',
1762 'value' => 'setValueDescription: TheRest <> CiviCRM',
1763 ]);
1764 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1765 $this->assertEquals('setValueDescription: TheRest <> CiviCRM', $setValueDescriptionResult['values']['description']);
1766 }
1767
1768 /**
1769 * Verify that write operations (create/update) use partial HTML-encoding
1770 *
1771 * In this example, the event 'title' is subject to encoding, but the
1772 * event 'description' is not.
1773 */
1774 public function testEncodeWrite() {
1775 // Create example
1776 $createResult = civicrm_api('Event', 'Create', [
1777 'version' => 3,
1778 'title' => 'createNew: CiviCRM <> TheRest',
1779 'description' => 'createNew: TheRest <> CiviCRM',
1780 'event_type_id' => 1,
1781 'is_public' => 1,
1782 'start_date' => 20081021,
1783 ]);
1784 $this->assertAPISuccess($createResult);
1785 $eventId = $createResult['id'];
1786 $this->assertDBQuery('createNew: CiviCRM &lt;&gt; TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1787 1 => [$eventId, 'Integer'],
1788 ]);
1789 $this->assertDBQuery('createNew: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1790 1 => [$eventId, 'Integer'],
1791 ]);
1792
1793 // Verify that "create" handles encoding for updates
1794 $createWithIdResult = civicrm_api('Event', 'Create', [
1795 'version' => 3,
1796 'id' => $eventId,
1797 'title' => 'createWithId: CiviCRM <> TheRest',
1798 'description' => 'createWithId: TheRest <> CiviCRM',
1799 ]);
1800 $this->assertAPISuccess($createWithIdResult);
1801 $this->assertDBQuery('createWithId: CiviCRM &lt;&gt; TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1802 1 => [$eventId, 'Integer'],
1803 ]);
1804 $this->assertDBQuery('createWithId: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1805 1 => [$eventId, 'Integer'],
1806 ]);
1807
1808 // Verify that "setvalue" handles encoding for updates
1809 $setValueTitleResult = civicrm_api('Event', 'setvalue', [
1810 'version' => 3,
1811 'id' => $eventId,
1812 'field' => 'title',
1813 'value' => 'setValueTitle: CiviCRM <> TheRest',
1814 ]);
1815 $this->assertAPISuccess($setValueTitleResult);
1816 $this->assertDBQuery('setValueTitle: CiviCRM &lt;&gt; TheRest', 'SELECT title FROM civicrm_event WHERE id = %1', [
1817 1 => [$eventId, 'Integer'],
1818 ]);
1819 $setValueDescriptionResult = civicrm_api('Event', 'setvalue', [
1820 'version' => 3,
1821 'id' => $eventId,
1822 'field' => 'description',
1823 'value' => 'setValueDescription: TheRest <> CiviCRM',
1824 ]);
1825 //$this->assertTrue((bool)$setValueDescriptionResult['is_error']); // not supported by setValue
1826 $this->assertAPISuccess($setValueDescriptionResult);
1827 $this->assertDBQuery('setValueDescription: TheRest <> CiviCRM', 'SELECT description FROM civicrm_event WHERE id = %1', [
1828 1 => [$eventId, 'Integer'],
1829 ]);
1830 }
1831
1832 }