Merge pull request #14422 from civicrm/5.14
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
index 4afdb9b3952d45c1304fbaa543ab0884ea1fa429..32fb9e3ea9c964de122a45adbb03711e1929854e 100644 (file)
@@ -27,6 +27,7 @@
  */
 
 use Civi\Payment\System;
+use Symfony\Component\Yaml\Yaml;
 
 /**
  *  Include class definitions
@@ -51,7 +52,7 @@ define('API_LATEST_VERSION', 3);
  *  Common functions for unit tests
  * @package CiviCRM
  */
-class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
+class CiviUnitTestCase extends PHPUnit\Framework\TestCase {
 
   use \Civi\Test\Api3DocTrait;
   use \Civi\Test\GenericAssertionsTrait;
@@ -62,7 +63,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    *  Database has been initialized.
    *
-   * @var boolean
+   * @var bool
    */
   private static $dbInit = FALSE;
 
@@ -92,7 +93,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   protected $tempDirs;
 
   /**
-   * @var boolean populateOnce allows to skip db resets in setUp
+   * @var bool populateOnce allows to skip db resets in setUp
    *
    *  WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
    *  BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
@@ -105,7 +106,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   public static $populateOnce = FALSE;
 
   /**
-   * @var boolean DBResetRequired allows skipping DB reset
+   * @var bool DBResetRequired allows skipping DB reset
    *               in specific test case. If you still need
    *               to reset single test (method) of such case, call
    *               $this->cleanDB() in the first line of this
@@ -194,7 +195,10 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       // FIXME: loosen coupling
       _civix_phpunit_setUp();
     }
-    if (version_compare(PHPUnit_Runner_Version::id(), '5', '>=')) {
+    if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version::id(), '5', '>=')) {
+      $this->mockMethod = 'createMock';
+    }
+    elseif (class_exists('PHPUnit\Runner\Version') && version_compare(PHPUnit\Runner\Version::id(), '6', '>=')) {
       $this->mockMethod = 'createMock';
     }
   }
@@ -241,10 +245,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *
    *  Initialize the test database if it hasn't been initialized
    *
-   * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
    */
   protected function getConnection() {
-    $dbName = self::$_dbName;
     if (!self::$dbInit) {
       $dbName = self::getDBName();
 
@@ -256,7 +258,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       self::$dbInit = TRUE;
     }
 
-    return $this->createDefaultDBConnection(Civi\Test::pdo(), $dbName);
   }
 
   /**
@@ -307,6 +308,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     $session = CRM_Core_Session::singleton();
     $session->set('userID', NULL);
 
+    $this->_apiversion = 3;
+
     // REVERT
     $this->errorScope = CRM_Core_TemporaryErrorScope::useException();
     //  Use a temporary file for STDIN
@@ -331,6 +334,12 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     // disable any left-over test extensions
     CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
 
+    $extensions = \CRM_Extension_System::singleton()->getManager();
+    $api4Status = $extensions->getStatus('org.civicrm.api4');
+    if ($api4Status != $extensions::STATUS_INSTALLED && $api4Status != $extensions::STATUS_UNKNOWN) {
+      $extensions->enable(['org.civicrm.api4']);
+    }
+
     // reset all the caches
     CRM_Utils_System::flushCache();
 
@@ -365,25 +374,73 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   public function loadAllFixtures() {
     $fixturesDir = __DIR__ . '/../../fixtures';
 
-    $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
-
-    $xmlFiles = glob($fixturesDir . '/*.xml');
-    foreach ($xmlFiles as $xmlFixture) {
-      $op = new PHPUnit_Extensions_Database_Operation_Insert();
-      $dataset = $this->createXMLDataSet($xmlFixture);
-      $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
-      $op->execute($this->_dbconn, $dataset);
-    }
+    CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
 
     $yamlFiles = glob($fixturesDir . '/*.yaml');
     foreach ($yamlFiles as $yamlFixture) {
-      $op = new PHPUnit_Extensions_Database_Operation_Insert();
-      $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
-      $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
-      $op->execute($this->_dbconn, $dataset);
+      $yaml = Yaml::parse(file_get_contents($yamlFixture));
+      foreach ($yaml as $tableName => $vars) {
+        if ($tableName === 'civicrm_contact') {
+          CRM_Core_DAO::executeQuery('DELETE c FROM civicrm_contact c LEFT JOIN civicrm_domain d ON d.contact_id = c.id WHERE d.id IS NULL');
+        }
+        else {
+          CRM_Core_DAO::executeQuery("TRUNCATE $tableName");
+        }
+        foreach ($vars as $entity) {
+          $keys = $values = [];
+          foreach ($entity as $key => $value) {
+            $keys[] = $key;
+            $values[] = is_numeric($value) ? $value : "'{$value}'";
+          }
+          CRM_Core_DAO::executeQuery("
+            INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
+          );
+        }
+
+      }
     }
 
-    $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
+    CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
+  }
+
+  /**
+   * Load the data that used to be handled by the discontinued dbunit class.
+   *
+   * This could do with further tidy up - the initial priority is simply to get rid of
+   * the dbunity package which is no longer supported.
+   *
+   * @param string $fileName
+   */
+  protected function loadXMLDataSet($fileName) {
+    CRM_Core_DAO::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
+    $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
+    foreach ($xml as $tableName => $element) {
+      if (!empty($element)) {
+        foreach ($element as $row) {
+          $keys = $values = [];
+          if (isset($row['@attributes'])) {
+            foreach ($row['@attributes'] as $key => $value) {
+              $keys[] = $key;
+              $values[] = is_numeric($value) ? $value : "'{$value}'";
+            }
+          }
+          elseif (!empty($row)) {
+            // cos we copied it & it is inconsistent....
+            foreach ($row as $key => $value) {
+              $keys[] = $key;
+              $values[] = is_numeric($value) ? $value : "'{$value}'";
+            }
+          }
+
+          if (!empty($values)) {
+            CRM_Core_DAO::executeQuery("
+            INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
+            );
+          }
+        }
+      }
+    }
+    CRM_Core_DAO::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
   }
 
   /**
@@ -399,6 +456,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *  Common teardown functions for all unit tests.
    */
   protected function tearDown() {
+    $this->_apiversion = 3;
+
     error_reporting(E_ALL & ~E_NOTICE);
     CRM_Utils_Hook::singleton()->reset();
     if ($this->hookClass) {
@@ -1320,7 +1379,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       $params['assignee_contact_id'] = $params['target_contact_id'];
     }
 
-    $result = $this->callAPISuccess('Activity', 'create', $params);
+    $result = civicrm_api3('Activity', 'create', $params);
 
     $result['target_contact_id'] = $params['target_contact_id'];
     $result['assignee_contact_id'] = $params['assignee_contact_id'];
@@ -3160,4 +3219,37 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
     $dbLocale = '_en_US';
   }
 
+  /**
+   * Setup or clean up SMS tests
+   * @param bool $teardown
+   *
+   * @throws \CiviCRM_API3_Exception
+   */
+  public function setupForSmsTests($teardown = FALSE) {
+    require_once 'CiviTest/CiviTestSMSProvider.php';
+
+    // Option value params for CiviTestSMSProvider
+    $groupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
+    $params = array(
+      'option_group_id' => $groupID,
+      'label' => 'unittestSMS',
+      'value' => 'unit.test.sms',
+      'name'  => 'CiviTestSMSProvider',
+      'is_default' => 1,
+      'is_active'  => 1,
+      'version'    => 3,
+    );
+
+    if ($teardown) {
+      // Test completed, delete provider
+      $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
+      civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
+      return;
+    }
+
+    // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
+    //  in CRM/Sms/Provider.php even though it is not an extension.
+    return civicrm_api3('option_value', 'create', $params);
+  }
+
 }