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 +--------------------------------------------------------------------+
13 * Test class for CRM_Contact_BAO_GroupContact BAO
18 class CRM_Contact_BAO_GroupContactCacheTest
extends CiviUnitTestCase
{
21 * Manually add and remove contacts from a smart group.
23 public function testManualAddRemove() {
24 list($group, $living, $deceased) = $this->setupSmartGroup();
27 $this->callAPISuccess('group_contact', 'create', [
28 'contact_id' => $living[0]->id
,
29 'group_id' => $group->id
,
32 CRM_Contact_BAO_GroupContactCache
::load($group, TRUE);
33 $this->assertCacheMatches(
34 [$deceased[0]->id
, $deceased[1]->id
, $deceased[2]->id
, $living[0]->id
],
39 $this->callAPISuccess('group_contact', 'create', [
40 'contact_id' => $deceased[0]->id
,
41 'group_id' => $group->id
,
42 'status' => 'Removed',
45 CRM_Contact_BAO_GroupContactCache
::load($group, TRUE);
46 $this->assertCacheMatches(
57 * Allow removing contact from a parent group even if contact is in a child group. (CRM-8858).
59 public function testRemoveFromParentSmartGroup() {
60 // Create smart group $parent
62 'name' => 'Deceased Contacts',
63 'title' => 'Deceased Contacts',
65 'formValues' => ['is_deceased' => 1],
67 $parent = CRM_Contact_BAO_Group
::createSmartGroup($params);
68 $this->registerTestObjects([$parent]);
70 // Create group $child in $parent
72 'name' => 'Child Group',
73 'title' => 'Child Group',
75 'parents' => [$parent->id
=> 1],
77 $child = CRM_Contact_BAO_Group
::create($params);
78 $this->registerTestObjects([$child]);
80 // Create $c1, $c2, $c3
81 $deceased = $this->createTestObject('CRM_Contact_DAO_Contact', ['is_deceased' => 1], 3);
83 // Add $c1, $c2, $c3 to $child
84 foreach ($deceased as $contact) {
85 $this->callAPISuccess('group_contact', 'create', [
86 'contact_id' => $contact->id
,
87 'group_id' => $child->id
,
91 CRM_Contact_BAO_GroupContactCache
::load($parent, TRUE);
92 $this->assertCacheMatches(
93 [$deceased[0]->id
, $deceased[1]->id
, $deceased[2]->id
],
97 // Remove $c1 from $parent
98 $this->callAPISuccess('group_contact', 'create', [
99 'contact_id' => $deceased[0]->id
,
100 'group_id' => $parent->id
,
101 'status' => 'Removed',
104 // Assert $c1 not in $parent
105 CRM_Contact_BAO_GroupContactCache
::load($parent, TRUE);
106 $this->assertCacheMatches(
114 // Assert $c1 still in $child
115 $this->assertDBQuery(1,
116 'select count(*) from civicrm_group_contact where group_id=%1 and contact_id=%2 and status=%3',
118 1 => [$child->id
, 'Integer'],
119 2 => [$deceased[0]->id
, 'Integer'],
120 3 => ['Added', 'String'],
126 * Assert that the cache for a group contains exactly the listed contacts.
128 * @param array $expectedContactIds
130 * @param int $groupId
132 public function assertCacheMatches($expectedContactIds, $groupId) {
133 $sql = 'SELECT contact_id FROM civicrm_group_contact_cache WHERE group_id = %1';
134 $params = [1 => [$groupId, 'Integer']];
135 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
136 $actualContactIds = [];
137 while ($dao->fetch()) {
138 $actualContactIds[] = $dao->contact_id
;
141 sort($expectedContactIds);
142 sort($actualContactIds);
143 $this->assertEquals($expectedContactIds, $actualContactIds);
147 * Test the opportunistic refresh cache function does not touch non-expired entries.
149 public function testOpportunisticRefreshCacheNoChangeIfNotExpired() {
150 list($group, $living, $deceased) = $this->setupSmartGroup();
151 $this->callAPISuccess('Contact', 'create', ['id' => $deceased[0]->id
, 'is_deceased' => 0]);
152 $this->assertCacheMatches(
153 [$deceased[0]->id
, $deceased[1]->id
, $deceased[2]->id
],
156 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
158 $this->assertCacheNotRefreshed($deceased, $group);
162 * Test the opportunistic refresh cache function does refresh stale entries.
164 public function testOpportunisticRefreshChangeIfCacheDateFieldStale() {
165 list($group, $living, $deceased) = $this->setupSmartGroup();
166 $this->callAPISuccess('Contact', 'create', ['id' => $deceased[0]->id
, 'is_deceased' => 0]);
167 CRM_Core_DAO
::executeQuery('UPDATE civicrm_group SET cache_date = DATE_SUB(NOW(), INTERVAL 7 MINUTE) WHERE id = ' . $group->id
);
169 Civi
::$statics['CRM_Contact_BAO_GroupContactCache']['is_refresh_init'] = FALSE;
171 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
173 $this->assertCacheRefreshed($group);
177 * Test the opportunistic refresh cache function does refresh expired entries if mode is deterministic.
179 public function testOpportunisticRefreshNoChangeWithDeterministicSetting() {
180 list($group, $living, $deceased) = $this->setupSmartGroup();
181 $this->callAPISuccess('Setting', 'create', ['smart_group_cache_refresh_mode' => 'deterministic']);
182 $this->callAPISuccess('Contact', 'create', ['id' => $deceased[0]->id
, 'is_deceased' => 0]);
183 $this->makeCacheStale($group);
184 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
185 $this->assertCacheNotRefreshed($deceased, $group);
186 $this->callAPISuccess('Setting', 'create', ['smart_group_cache_refresh_mode' => 'opportunistic']);
190 * Test the deterministic cache function refreshes with the deterministic setting.
192 public function testDeterministicRefreshChangeWithDeterministicSetting() {
193 list($group, $living, $deceased) = $this->setupSmartGroup();
194 $this->callAPISuccess('Setting', 'create', ['smart_group_cache_refresh_mode' => 'deterministic']);
195 $this->callAPISuccess('Contact', 'create', ['id' => $deceased[0]->id
, 'is_deceased' => 0]);
196 $this->makeCacheStale($group);
197 CRM_Contact_BAO_GroupContactCache
::deterministicCacheFlush();
198 $this->assertCacheRefreshed($group);
199 $this->callAPISuccess('Setting', 'create', ['smart_group_cache_refresh_mode' => 'opportunistic']);
203 * Test the deterministic cache function refresh doesn't mess up non-expired.
205 public function testDeterministicRefreshChangeDoesNotTouchNonExpired() {
206 list($group, $living, $deceased) = $this->setupSmartGroup();
207 $this->callAPISuccess('Setting', 'create', ['smart_group_cache_refresh_mode' => 'deterministic']);
208 $this->callAPISuccess('Contact', 'create', ['id' => $deceased[0]->id
, 'is_deceased' => 0]);
209 CRM_Contact_BAO_GroupContactCache
::deterministicCacheFlush();
210 $this->assertCacheNotRefreshed($deceased, $group);
211 $this->callAPISuccess('Setting', 'create', ['smart_group_cache_refresh_mode' => 'opportunistic']);
215 * Test the deterministic cache function refreshes with the opportunistic setting.
217 * (hey it's an opportunity!).
219 public function testDeterministicRefreshChangeWithOpportunisticSetting() {
220 list($group, $living, $deceased) = $this->setupSmartGroup();
221 $this->callAPISuccess('Setting', 'create', ['smart_group_cache_refresh_mode' => 'opportunistic']);
222 $this->callAPISuccess('Contact', 'create', ['id' => $deceased[0]->id
, 'is_deceased' => 0]);
223 $this->makeCacheStale($group);
224 CRM_Contact_BAO_GroupContactCache
::deterministicCacheFlush();
225 $this->assertCacheRefreshed($group);
229 * Test the api job wrapper around the deterministic refresh works.
231 public function testJobWrapper() {
232 list($group, $living, $deceased) = $this->setupSmartGroup();
233 $this->callAPISuccess('Setting', 'create', ['smart_group_cache_refresh_mode' => 'opportunistic']);
234 $this->callAPISuccess('Contact', 'create', ['id' => $deceased[0]->id
, 'is_deceased' => 0]);
235 $this->makeCacheStale($group);
236 $this->callAPISuccess('Job', 'group_cache_flush', []);
237 $this->assertCacheRefreshed($group);
240 // *** Everything below this should be moved to parent class ****
244 * (DAO_Name => array(int)) List of items to garbage-collect during tearDown
246 private $_testObjects;
249 * Sets up the fixture, for example, opens a network connection.
251 * This method is called before a test is executed.
253 protected function setUp() {
254 $this->_testObjects
= [];
259 * Tears down the fixture, for example, closes a network connection.
261 * This method is called after a test is executed.
263 protected function tearDown() {
265 $this->deleteTestObjects();
269 * This is a wrapper for CRM_Core_DAO::createTestObject which tracks created entities.
271 * @see CRM_Core_DAO::createTestObject
273 * @param string $daoName
274 * @param array $params
275 * @param int $numObjects
276 * @param bool $createOnly
278 * @return array|NULL|object
280 public function createTestObject($daoName, $params = [], $numObjects = 1, $createOnly = FALSE) {
281 $objects = CRM_Core_DAO
::createTestObject($daoName, $params, $numObjects, $createOnly);
282 if (is_array($objects)) {
283 $this->registerTestObjects($objects);
286 $this->registerTestObjects([$objects]);
292 * Register test objects.
294 * @param array $objects
295 * DAO or BAO objects.
297 public function registerTestObjects($objects) {
298 foreach ($objects as $object) {
299 $daoName = preg_replace('/_BAO_/', '_DAO_', get_class($object));
300 $this->_testObjects
[$daoName][] = $object->id
;
305 * Delete test objects.
307 * Note: You might argue that the FK relations between test
308 * objects could make this problematic; however, it should
309 * behave intuitively as long as we mentally split our
310 * test-objects between the "manual/primary records"
311 * and the "automatic/secondary records"
313 public function deleteTestObjects() {
314 foreach ($this->_testObjects
as $daoName => $daoIds) {
315 foreach ($daoIds as $daoId) {
316 CRM_Core_DAO
::deleteTestObjects($daoName, ['id' => $daoId]);
319 $this->_testObjects
= [];
323 * Set up a smart group testing scenario.
327 protected function setupSmartGroup() {
329 'name' => 'Deceased Contacts',
330 'title' => 'Deceased Contacts',
332 'formValues' => ['is_deceased' => 1],
334 $group = CRM_Contact_BAO_Group
::createSmartGroup($params);
335 $this->registerTestObjects([$group]);
337 // Create contacts $y1, $y2, $y3 which do match $g; create $n1, $n2, $n3 which do not match $g
338 $living = $this->createTestObject('CRM_Contact_DAO_Contact', ['is_deceased' => 0], 3);
339 $deceased = $this->createTestObject('CRM_Contact_DAO_Contact', ['is_deceased' => 1], 3);
340 $this->assertEquals(3, count($deceased));
341 $this->assertEquals(3, count($living));
343 // Assert: $g cache has exactly $y1, $y2, $y3
344 CRM_Contact_BAO_GroupContactCache
::load($group, TRUE);
346 $this->assertCacheMatches(
347 [$deceased[0]->id
, $deceased[1]->id
, $deceased[2]->id
],
350 // Reload the group so we have the cache_date & refresh_date.
351 return [$group, $living, $deceased];
360 protected function assertCacheNotRefreshed($deceased, $group) {
361 $this->assertCacheMatches(
362 [$deceased[0]->id
, $deceased[1]->id
, $deceased[2]->id
],
365 $afterGroup = $this->callAPISuccessGetSingle('Group', ['id' => $group->id
]);
366 $this->assertEquals($group->cache_date
, $afterGroup['cache_date']);
370 * Make the cache for the group stale, resetting it to before the timeout period.
372 * @param CRM_Contact_BAO_Group $group
374 protected function makeCacheStale(&$group) {
375 CRM_Core_DAO
::executeQuery('UPDATE civicrm_group SET cache_date = DATE_SUB(NOW(), INTERVAL 7 MINUTE) WHERE id = ' . $group->id
);
376 unset($group->cache_date
);
378 Civi
::$statics['CRM_Contact_BAO_GroupContactCache']['is_refresh_init'] = FALSE;
386 protected function assertCacheRefreshed($group) {
387 $this->assertCacheMatches(
392 $afterGroup = $this->callAPISuccessGetSingle('Group', ['id' => $group->id
]);
393 $this->assertTrue(empty($afterGroup['cache_date']), 'cache date should not be set as the cache is not built');
397 * Test Smart group search
399 public function testSmartGroupSearchBuilder() {
400 $returnProperties = [
402 'contact_sub_type' => 1,
406 list($group, $living, $deceased) = $this->setupSmartGroup();
409 'name' => 'Living Contacts',
410 'title' => 'Living Contacts',
412 'formValues' => ['is_deceased' => 0],
414 $group2 = CRM_Contact_BAO_Group
::createSmartGroup($params);
416 //Filter on smart group with =, !=, IN and NOT IN operator.
417 $params = [['group', '=', $group2->id
, 1, 0]];
418 $query = new CRM_Contact_BAO_Query(
419 $params, $returnProperties,
420 NULL, FALSE, FALSE, CRM_Contact_BAO_Query
::MODE_CONTACTS
,
424 $ids = $query->searchQuery(0, 0, NULL,
428 $key = $query->getGroupCacheTableKeys()[0];
429 $expectedWhere = "civicrm_group_contact_cache_{$key}.group_id IN (\"{$group2->id}\")";
430 $this->assertContains($expectedWhere, $query->_whereClause
);
431 $this->_assertContactIds($query, "group_id = {$group2->id}");
433 $params = [['group', '!=', $group->id
, 1, 0]];
434 $query = new CRM_Contact_BAO_Query(
435 $params, $returnProperties,
436 NULL, FALSE, FALSE, CRM_Contact_BAO_Query
::MODE_CONTACTS
,
440 $key = $query->getGroupCacheTableKeys()[0];
441 //Assert if proper where clause is present.
442 $expectedWhere = "civicrm_group_contact_{$key}.group_id != {$group->id} AND civicrm_group_contact_cache_{$key}.group_id IS NULL OR ( civicrm_group_contact_cache_{$key}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( {$group->id} ) ) )";
443 $this->assertContains($expectedWhere, $query->_whereClause
);
444 $this->_assertContactIds($query, "group_id != {$group->id}");
446 $params = [['group', 'IN', [$group->id
, $group2->id
], 1, 0]];
447 $query = new CRM_Contact_BAO_Query(
448 $params, $returnProperties,
449 NULL, FALSE, FALSE, CRM_Contact_BAO_Query
::MODE_CONTACTS
,
453 $key = $query->getGroupCacheTableKeys()[0];
454 $expectedWhere = "civicrm_group_contact_cache_{$key}.group_id IN (\"{$group->id}\", \"{$group2->id}\")";
455 $this->assertContains($expectedWhere, $query->_whereClause
);
456 $this->_assertContactIds($query, "group_id IN ({$group->id}, {$group2->id})");
458 $params = [['group', 'NOT IN', [$group->id
], 1, 0]];
459 $query = new CRM_Contact_BAO_Query(
460 $params, $returnProperties,
461 NULL, FALSE, FALSE, CRM_Contact_BAO_Query
::MODE_CONTACTS
,
465 $key = $query->getGroupCacheTableKeys()[0];
466 $expectedWhere = "civicrm_group_contact_{$key}.group_id NOT IN ( {$group->id} ) AND civicrm_group_contact_cache_{$key}.group_id IS NULL OR ( civicrm_group_contact_cache_{$key}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( {$group->id} ) ) )";
467 $this->assertContains($expectedWhere, $query->_whereClause
);
468 $this->_assertContactIds($query, "group_id NOT IN ({$group->id})");
469 $this->callAPISuccess('group', 'delete', ['id' => $group->id
]);
470 $this->callAPISuccess('group', 'delete', ['id' => $group2->id
]);
473 public function testMultipleGroupWhereClause() {
474 $returnProperties = [
476 'contact_sub_type' => 1,
480 list($group, $living, $deceased) = $this->setupSmartGroup();
483 'name' => 'Living Contacts',
484 'title' => 'Living Contacts',
486 'formValues' => ['is_deceased' => 0],
488 $group2 = CRM_Contact_BAO_Group
::createSmartGroup($params);
490 //Filter on smart group with =, !=, IN and NOT IN operator.
491 $params = [['group', '=', $group2->id
, 1, 0], ['group', '=', $group->id
, 1, 0]];
492 $query = new CRM_Contact_BAO_Query(
493 $params, $returnProperties,
494 NULL, FALSE, FALSE, CRM_Contact_BAO_Query
::MODE_CONTACTS
,
498 $ids = $query->searchQuery(0, 0, NULL,
502 $key1 = $query->getGroupCacheTableKeys()[0];
503 $key2 = $query->getGroupCacheTableKeys()[1];
504 $expectedWhere = 'civicrm_group_contact_cache_' . $key1 . '.group_id IN ("' . $group2->id
. '") ) ) AND ( ( civicrm_group_contact_cache_' . $key2 . '.group_id IN ("' . $group->id
. '")';
505 $this->assertContains($expectedWhere, $query->_whereClause
);
506 // Check that we have 3 joins to the group contact cache 1 for each of the group where clauses and 1 for the fact we are returning groups in the select.
507 $expectedFrom1 = 'LEFT JOIN civicrm_group_contact_cache civicrm_group_contact_cache_' . $key1 . ' ON contact_a.id = civicrm_group_contact_cache_' . $key1 . '.contact_id';
508 $this->assertContains($expectedFrom1, $query->_fromClause
);
509 $expectedFrom2 = 'LEFT JOIN civicrm_group_contact_cache civicrm_group_contact_cache_' . $key2 . ' ON contact_a.id = civicrm_group_contact_cache_' . $key2 . '.contact_id';
510 $this->assertContains($expectedFrom2, $query->_fromClause
);
511 $expectedFrom3 = 'LEFT JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id';
512 $this->assertContains($expectedFrom3, $query->_fromClause
);
516 * Check if contact ids are fetched correctly.
518 * @param object $query
519 * @param string $groupWhereClause
521 public function _assertContactIds($query, $groupWhereClause) {
522 $contactIds = explode(',', $query->searchQuery(0, 0, NULL,
526 $expectedContactIds = [];
527 $groupDAO = CRM_Core_DAO
::executeQuery("SELECT contact_id FROM civicrm_group_contact_cache WHERE {$groupWhereClause}");
528 while ($groupDAO->fetch()) {
529 $expectedContactIds[] = $groupDAO->contact_id
;
531 $this->assertEquals(sort($expectedContactIds), sort($contactIds));