Merge pull request #14516 from eileenmcnaughton/except
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
index 4ece15ebce7a33e2e6e093f7256247fcf593dd09..1c11b5e095ab4eebf54f96c5961ce25585274420 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
@@ -371,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');
   }
 
   /**
@@ -405,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) {
@@ -1326,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'];
@@ -2467,6 +2520,19 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
     ));
   }
 
+  /**
+   * Assert 2 sql strings are the same, ignoring double spaces.
+   *
+   * @param string $expectedSQL
+   * @param string $actualSQL
+   * @param string $message
+   */
+  protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
+    $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
+    $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
+    $this->assertEquals($expected, $actual, $message);
+  }
+
   /**
    * Create a price set for an event.
    *