Improve CustomGroupTest
authorEileen McNaughton <emcnaughton@wikimedia.org>
Wed, 16 Jun 2021 03:00:06 +0000 (15:00 +1200)
committerEileen McNaughton <emcnaughton@wikimedia.org>
Thu, 17 Jun 2021 02:25:58 +0000 (14:25 +1200)
Use api, various cleanups

tests/phpunit/CRM/Core/BAO/CustomFieldTest.php
tests/phpunit/CRM/Core/BAO/CustomGroupTest.php
tests/phpunit/CRM/Dedupe/MergerTest.php
tests/phpunit/CiviTest/CiviUnitTestCase.php
tests/phpunit/api/v3/CustomFieldTest.php
tests/phpunit/api/v3/JobTest.php

index 721f168edcda779b614294a1f02d3d0ff58fa37f..f554aa905895c1f0b6ae61e0c5042f44f3a06a9d 100644 (file)
@@ -607,7 +607,7 @@ class CRM_Core_BAO_CustomFieldTest extends CiviUnitTestCase {
         'label' => 'Enter text here',
         'groupTitle' => 'Custom Group',
         'default_value' => 'xyz',
-        'custom_group_id' => '1',
+        'custom_group_id' => $customGroupID,
         'extends' => 'Contact',
         'extends_entity_column_value' => NULL,
         'extends_entity_column_id' => NULL,
index 6fe01558763d6fad1799b202e4721877e23a1325..568f8e3ea5d32edc97aee2a4f757f43dacd4bc8b 100644 (file)
@@ -9,12 +9,26 @@
  +--------------------------------------------------------------------+
  */
 
+use Civi\Api4\CustomGroup;
+
 /**
  * Class CRM_Core_BAO_CustomGroupTest
  * @group headless
  */
 class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
 
+  /**
+   * Clean up after test.
+   *
+   * @throws \API_Exception
+   * @throws \CRM_Core_Exception
+   * @throws \CiviCRM_API3_Exception
+   */
+  public function tearDown(): void {
+    $this->quickCleanup(['civicrm_contact'], TRUE);
+    parent::tearDown();
+  }
+
   /**
    * Test getTree().
    */
@@ -23,7 +37,6 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
     $customField = $this->customFieldCreate(['custom_group_id' => $customGroup['id']]);
     $result = CRM_Core_BAO_CustomGroup::getTree('Individual', NULL, $customGroup['id']);
     $this->assertEquals('Custom Field', $result[$customGroup['id']]['fields'][$customField['id']]['label']);
-    $this->customGroupDelete($customGroup['id']);
   }
 
   /**
@@ -137,13 +150,12 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
     $customField = $this->customFieldCreate(['custom_group_id' => $customGroup['id']]);
     $result = CRM_Core_BAO_CustomGroup::getTree('Activity', NULL, NULL, NULL, 1);
     $this->assertEquals('Custom Field', $result[$customGroup['id']]['fields'][$customField['id']]['label']);
-    $this->customGroupDelete($customGroup['id']);
   }
 
   /**
    * Test retrieve() with Empty Params.
    */
-  public function testRetrieveEmptyParams() {
+  public function testRetrieveEmptyParams(): void {
     $params = [];
     $customGroup = CRM_Core_BAO_CustomGroup::retrieve($params, $dafaults);
     $this->assertNull($customGroup, 'Check that no custom Group is retreived');
@@ -342,8 +354,10 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
 
   /**
    * Test createTable()
+   *
+   * @throws \Exception
    */
-  public function testCreateTable() {
+  public function testCreateTable(): void {
     $groupParams = [
       'title' => 'My Custom Group',
       'name' => 'my_custom_group',
@@ -363,7 +377,7 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
     $customGroupId = $customGroup->id;
 
     //check db for custom group.
-    $dbCustomGroupTitle = $this->assertDBNotNull('CRM_Core_DAO_CustomGroup', $customGroupId, 'title', 'id',
+    $this->assertDBNotNull('CRM_Core_DAO_CustomGroup', $customGroupId, 'title', 'id',
       'Database check for custom group record.'
     );
     //check for custom group table name
@@ -376,6 +390,8 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
 
   /**
    * Test checkCustomField()
+   *
+   * @throws \CRM_Core_Exception
    */
   public function testCheckCustomField() {
     $groupParams = [
@@ -429,8 +445,10 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
 
   /**
    * Test getActiveGroups() with Invalid Params()
+   *
+   * @throws \CiviCRM_API3_Exception
    */
-  public function testGetActiveGroupsWithInvalidParams() {
+  public function testGetActiveGroupsWithInvalidParams(): void {
     $contactId = $this->individualCreate();
     $activeGroups = CRM_Core_BAO_CustomGroup::getActiveGroups('ABC', 'civicrm/contact/view/cd', $contactId);
     $this->assertEquals(empty($activeGroups), TRUE, 'Check that Emprt params are retreived');
@@ -452,7 +470,7 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
     $activeGroup = CRM_Core_BAO_CustomGroup::getActiveGroups('Individual', 'civicrm/contact/view/cd', $contactId);
     foreach ($activeGroup as $key => $value) {
       if ($value['id'] == $customGroup['id']) {
-        $this->assertEquals($value['path'], 'civicrm/contact/view/cd');
+        $this->assertEquals('civicrm/contact/view/cd', $value['path']);
         $this->assertEquals($value['title'], $customGroupTitle);
         $query = 'reset=1&gid=' . $customGroup['id'] . '&cid=' . $contactId;
         $this->assertEquals($value['query'], $query);
@@ -465,8 +483,10 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
 
   /**
    * Test create()
+   *
+   * @throws \CRM_Core_Exception
    */
-  public function testCreate() {
+  public function testCreate(): void {
     $params = [
       'title' => 'Test_Group_1',
       'name' => 'test_group_1',
@@ -479,26 +499,27 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
       'is_active' => 1,
       'version' => 3,
     ];
-    $customGroup = CRM_Core_BAO_CustomGroup::create($params);
+    $customGroupID = $this->callAPISuccess('CustomGroup', 'create', $params)['id'];
 
-    $dbCustomGroupTitle = $this->assertDBNotNull('CRM_Core_DAO_CustomGroup', $customGroup->id, 'title', 'id',
+    $dbCustomGroupTitle = $this->assertDBNotNull('CRM_Core_DAO_CustomGroup', $customGroupID, 'title', 'id',
       'Database check for custom group record.'
     );
     $this->assertEquals($params['title'], $dbCustomGroupTitle);
 
-    $dbCustomGroupTableName = $this->assertDBNotNull('CRM_Core_DAO_CustomGroup', $customGroup->id, 'table_name', 'id',
+    $dbCustomGroupTableName = $this->assertDBNotNull('CRM_Core_DAO_CustomGroup', $customGroupID, 'table_name', 'id',
       'Database check for custom group record.'
     );
-    $this->assertEquals(strtolower("civicrm_value_{$params['name']}_{$customGroup->id}"), $dbCustomGroupTableName,
+    $this->assertEquals(strtolower("civicrm_value_{$params['name']}_$customGroupID"), $dbCustomGroupTableName,
       "The table name should be suffixed with '_ID' unless specified.");
-
-    $this->customGroupDelete($customGroup->id);
   }
 
   /**
    * Test create() given a table_name
+   *
+   * @throws \CRM_Core_Exception
+   * @throws \API_Exception
    */
-  public function testCreateTableName() {
+  public function testCreateTableName(): void {
     $params = [
       'title' => 'Test_Group_2',
       'name' => 'test_group_2',
@@ -511,19 +532,13 @@ class CRM_Core_BAO_CustomGroupTest extends CiviUnitTestCase {
       'help_post' => 'This is Post Help For Test Group 1',
       'is_active' => 1,
     ];
-    $customGroup = CRM_Core_BAO_CustomGroup::create($params);
-
-    $dbCustomGroupTitle = $this->assertDBNotNull('CRM_Core_DAO_CustomGroup', $customGroup->id, 'title', 'id',
-      'Database check for custom group record.'
-    );
-    $this->assertEquals($params['title'], $dbCustomGroupTitle);
-
-    $dbCustomGroupTableName = $this->assertDBNotNull('CRM_Core_DAO_CustomGroup', $customGroup->id, 'table_name', 'id',
-      'Database check for custom group record.'
-    );
-    $this->assertEquals($params['table_name'], $dbCustomGroupTableName);
-
-    $this->customGroupDelete($customGroup->id);
+    $customGroupID = $this->callAPISuccess('CustomGroup', 'create', $params)['id'];
+    $group = CustomGroup::get()
+      ->addWhere('id', '=', $customGroupID)
+      ->addSelect('title', 'table_name')
+      ->execute()->first();
+    $this->assertEquals('Test_Group_2', $group['title']);
+    $this->assertEquals('test_otherTableName', $group['table_name']);
   }
 
   /**
index 80168f2ae2fda36d3935dadeaac0be9adfa5de35..b7415be6cf5f4711568882d02641ca4d1f2d3564 100644 (file)
@@ -300,11 +300,6 @@ class CRM_Dedupe_MergerTest extends CiviUnitTestCase {
     $unsetRefs = array_fill_keys(['civicrm_group_contact_cache', 'civicrm_acl_cache', 'civicrm_acl_contact_cache'], 1);
     $this->assertEquals($sortRefs(array_diff_key($this->getStaticCIDRefs(), $unsetRefs)), $sortRefs(CRM_Dedupe_Merger::cidRefs()));
     $this->assertEquals($sortRefs(array_diff_key($this->getCalculatedCIDRefs(), $unsetRefs)), $sortRefs(CRM_Dedupe_Merger::cidRefs()));
-
-    // These are deliberately unset.
-    // $unsetRefs = array_fill_keys(['civicrm_group_contact_cache', 'civicrm_acl_cache', 'civicrm_acl_contact_cache', 'civicrm_relationship_cache'], 1);
-    // $this->assertEquals(array_diff_key($this->getStaticCIDRefs(), $unsetRefs), CRM_Dedupe_Merger::cidRefs());
-    // $this->assertEquals(array_diff_key($this->getCalculatedCIDRefs(), $unsetRefs), CRM_Dedupe_Merger::cidRefs());
   }
 
   /**
@@ -314,6 +309,7 @@ class CRM_Dedupe_MergerTest extends CiviUnitTestCase {
    * focus is on ensuring they match.
    *
    * @throws \CRM_Core_Exception
+   * @throws \CiviCRM_API3_Exception
    */
   public function testGetMatches(): void {
     $this->setupMatchData();
index 50c94f7a1f3c8658290af32a99208ff7848065fe..9a31a35ea7394477860689de834fffb2d9a8157a 100644 (file)
@@ -26,6 +26,8 @@
  *   <http://www.gnu.org/licenses/>.
  */
 
+use Civi\Api4\CustomField;
+use Civi\Api4\CustomGroup;
 use Civi\Api4\OptionGroup;
 use Civi\Api4\RelationshipType;
 use Civi\Payment\System;
@@ -1844,22 +1846,24 @@ class CiviUnitTestCase extends PHPUnit\Framework\TestCase {
    * @param bool $dropCustomValueTables
    *
    * @throws \CRM_Core_Exception
+   * @throws \API_Exception
    */
   public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
     if ($this->tx) {
       throw new \CRM_Core_Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
     }
     if ($dropCustomValueTables) {
-      $optionGroupResult = CRM_Core_DAO::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
-      while ($optionGroupResult->fetch()) {
-        // We have a test that sets the option_group_id for a custom group to that of 'activity_type'.
-        // Then test tearDown deletes it. This is all mildly terrifying but for the context here we can be pretty
-        // sure the low-numbered (50 is arbitrary) option groups are not ones to 'just delete' in a
-        // generic cleanup routine.
-        if (!empty($optionGroupResult->option_group_id) && $optionGroupResult->option_group_id > 50) {
-          CRM_Core_DAO::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id);
-        }
-      }
+
+      CustomField::get(FALSE)->setSelect(['option_group_id', 'custom_group_id'])
+        ->addChain('delete_options', OptionGroup::delete()
+          ->addWhere('id', '=', '$option_group_id')
+        )
+        ->addChain('delete_fields', CustomField::delete()
+          ->addWhere('id', '=', '$id')
+        )->execute();
+
+      CustomGroup::delete(FALSE)->addWhere('id', '>', 0)->execute();
+      // Reset autoincrement too.
       $tablesToTruncate[] = 'civicrm_custom_group';
       $tablesToTruncate[] = 'civicrm_custom_field';
     }
@@ -1872,22 +1876,6 @@ class CiviUnitTestCase extends PHPUnit\Framework\TestCase {
       CRM_Core_DAO::executeQuery($sql);
     }
     CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
-
-    if ($dropCustomValueTables) {
-      $dbName = self::getDBName();
-      $query = "
-SELECT TABLE_NAME as tableName
-FROM   INFORMATION_SCHEMA.TABLES
-WHERE  TABLE_SCHEMA = '{$dbName}'
-AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
-";
-
-      $tableDAO = CRM_Core_DAO::executeQuery($query);
-      while ($tableDAO->fetch()) {
-        $sql = "DROP TABLE {$tableDAO->tableName}";
-        CRM_Core_DAO::executeQuery($sql);
-      }
-    }
   }
 
   /**
index 303a91d7c8d122935b751fcebf81b8677fe18201..87acb78cba0b8bc541271302dfc86a7fd5dfa31b 100644 (file)
@@ -9,6 +9,8 @@
  +--------------------------------------------------------------------+
  */
 
+use Civi\Api4\OptionGroup;
+
 /**
  *  Test APIv3 civicrm_create_custom_group
  *
@@ -573,17 +575,22 @@ class api_v3_CustomFieldTest extends CiviUnitTestCase {
     $this->customGroupDelete($customGroup['id']);
   }
 
-  public function testCustomFieldCreateWithOptionGroupName() {
+  /**
+   * @throws \API_Exception
+   * @throws \CRM_Core_Exception
+   */
+  public function testCustomFieldCreateWithOptionGroupName(): void {
     $customGroup = $this->customGroupCreate(['extends' => 'Individual', 'title' => 'test_custom_group']);
+    OptionGroup::create()->setValues(['name' => 'abc'])->execute();
     $params = [
       'custom_group_id' => $customGroup['id'],
       'name' => 'Activity type',
       'label' => 'Activity type',
       'data_type' => 'String',
       'html_type' => 'Select',
-      'option_group_id' => 'activity_type',
+      'option_group_id' => 'abc',
     ];
-    $result = $this->callAPISuccess('CustomField', 'create', $params);
+    $this->callAPISuccess('CustomField', 'create', $params);
   }
 
   /**
@@ -593,15 +600,18 @@ class api_v3_CustomFieldTest extends CiviUnitTestCase {
    */
   public function getCustomFieldKeys($getFieldsResult) {
     $isCustom = function ($key) {
-      return preg_match('/^custom_/', $key);
+      return 0 === strpos($key, 'custom_');
     };
     $r = array_values(array_filter(array_keys($getFieldsResult['values']), $isCustom));
     sort($r);
     return $r;
   }
 
+  /**
+   * @throws \CRM_Core_Exception
+   */
   public function testMakeSearchableContactReferenceFieldUnsearchable() {
-    $customGroup = $this->customGroupCreate([
+    $this->customGroupCreate([
       'name' => 'testCustomGroup',
       'title' => 'testCustomGroup',
       'extends' => 'Individual',
index ef77a10a569f8fddbb26985b1aa11f81c11e8d9f..f4802f46f53387639a5aea9ca828ae7ff211d22c 100644 (file)
@@ -1146,9 +1146,6 @@ class api_v3_JobTest extends CiviUnitTestCase {
     $mouseParams['return'] = 'custom_' . $customField['id'];
     $mouse = $this->callAPISuccess('Contact', 'getsingle', $mouseParams);
     $this->assertEquals('blah', $mouse['custom_' . $customField['id']]);
-
-    $this->customFieldDelete($customField['id']);
-    $this->customGroupDelete($customGroup['id']);
   }
 
   /**
@@ -1180,9 +1177,6 @@ class api_v3_JobTest extends CiviUnitTestCase {
     $mouseParams['return'] = 'custom_' . $customField['id'];
     $mouse = $this->callAPISuccess('Contact', 'getsingle', $mouseParams);
     $this->assertEquals(0, $mouse['custom_' . $customField['id']]);
-
-    $this->customFieldDelete($customField['id']);
-    $this->customGroupDelete($customGroup['id']);
   }
 
   /**
@@ -1207,9 +1201,6 @@ class api_v3_JobTest extends CiviUnitTestCase {
     $this->individualCreate(array_merge($mouseParams, ['id' => $mouse2, 'custom_' . $customField['id'] => 0]));
     $result = $this->callAPISuccess('Job', 'process_batch_merge', ['check_permissions' => 0, 'mode' => 'safe']);
     $this->assertCount(0, $result['values']['merged']);
-
-    $this->customFieldDelete($customField['id']);
-    $this->customGroupDelete($customGroup['id']);
   }
 
   /**