CRM-17860 - CiviTester - Split into separate class files
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
old mode 100755 (executable)
new mode 100644 (file)
index e62a051..c92568a
 
 use Civi\Payment\System;
 
-/**
- *  Include configuration
- */
-define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
-define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
-
-if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
-  require_once CIVICRM_SETTINGS_LOCAL_PATH;
-}
-require_once CIVICRM_SETTINGS_PATH;
 /**
  *  Include class definitions
  */
-require_once 'tests/phpunit/Utils.php';
 require_once 'api/api.php';
 require_once 'CRM/Financial/BAO/FinancialType.php';
 define('API_LATEST_VERSION', 3);
@@ -100,11 +89,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    */
   protected $tempDirs;
 
-  /**
-   * @var Utils instance
-   */
-  public static $utils;
-
   /**
    * @var boolean populateOnce allows to skip db resets in setUp
    *
@@ -118,11 +102,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    */
   public static $populateOnce = FALSE;
 
-  /**
-   * Allow classes to state E-notice compliance
-   */
-  public $_eNoticeCompliant = TRUE;
-
   /**
    * @var boolean DBResetRequired allows skipping DB reset
    *               in specific test case. If you still need
@@ -174,19 +153,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     // we need full error reporting
     error_reporting(E_ALL & ~E_NOTICE);
 
-    if (!empty($GLOBALS['mysql_db'])) {
-      self::$_dbName = $GLOBALS['mysql_db'];
-    }
-    else {
-      self::$_dbName = 'civicrm_tests_dev';
-    }
-
-    //  create test database
-    self::$utils = new Utils($GLOBALS['mysql_host'],
-      $GLOBALS['mysql_port'],
-      $GLOBALS['mysql_user'],
-      $GLOBALS['mysql_pass']
-    );
+    self::$_dbName = self::getDBName();
 
     // also load the class loader
     require_once 'CRM/Core/ClassLoader.php';
@@ -225,7 +192,12 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * @return string
    */
   public static function getDBName() {
-    $dbName = !empty($GLOBALS['mysql_db']) ? $GLOBALS['mysql_db'] : 'civicrm_tests_dev';
+    static $dbName = NULL;
+    if ($dbName === NULL) {
+      require_once "DB.php";
+      $dsninfo = DB::parseDSN(CIVICRM_DSN);
+      $dbName = $dsninfo['database'];
+    }
     return $dbName;
   }
 
@@ -248,7 +220,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
 
       self::$dbInit = TRUE;
     }
-    return $this->createDefaultDBConnection(self::$utils->pdo, $dbName);
+
+    return $this->createDefaultDBConnection(Civi\Test::pdo(), $dbName);
   }
 
   /**
@@ -264,6 +237,9 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *   TRUE if the populate logic runs; FALSE if it is skipped
    */
   protected static function _populateDB($perClass = FALSE, &$object = NULL) {
+    if (CIVICRM_UF !== 'UnitTests') {
+      throw new \RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
+    }
 
     if ($perClass || $object == NULL) {
       $dbreset = TRUE;
@@ -277,95 +253,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     }
     self::$populateOnce = NULL;
 
-    $dbName = self::getDBName();
-    $pdo = self::$utils->pdo;
-    // only consider real tables and not views
-    $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
-    WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
-
-    $truncates = array();
-    $drops = array();
-    foreach ($tables as $table) {
-      // skip log tables
-      if (substr($table['table_name'], 0, 4) == 'log_') {
-        continue;
-      }
-
-      // don't change list of installed extensions
-      if ($table['table_name'] == 'civicrm_extension') {
-        continue;
-      }
-
-      if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
-        $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
-      }
-      else {
-        $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
-      }
-    }
-
-    $queries = array(
-      "USE {$dbName};",
-      "SET foreign_key_checks = 0",
-      // SQL mode needs to be strict, that's our standard
-      "SET SQL_MODE='STRICT_ALL_TABLES';",
-      "SET global innodb_flush_log_at_trx_commit = 2;",
-    );
-    $queries = array_merge($queries, $truncates);
-    $queries = array_merge($queries, $drops);
-    foreach ($queries as $query) {
-      if (self::$utils->do_query($query) === FALSE) {
-        //  failed to create test database
-        echo "failed to create test db.";
-        exit;
-      }
-    }
-
-    //  initialize test database
-    $sql_file2 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/civicrm_data.mysql";
-    $sql_file3 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data.mysql";
-    $sql_file4 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data_second_domain.mysql";
-
-    $query2 = file_get_contents($sql_file2);
-    $query3 = file_get_contents($sql_file3);
-    $query4 = file_get_contents($sql_file4);
-    if (self::$utils->do_query($query2) === FALSE) {
-      echo "Cannot load civicrm_data.mysql. Aborting.";
-      exit;
-    }
-    if (self::$utils->do_query($query3) === FALSE) {
-      echo "Cannot load test_data.mysql. Aborting.";
-      exit;
-    }
-    if (self::$utils->do_query($query4) === FALSE) {
-      echo "Cannot load test_data.mysql. Aborting.";
-      exit;
-    }
-
-    // done with all the loading, get transactions back
-    if (self::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
-      echo "Cannot set global? Huh?";
-      exit;
-    }
-
-    if (self::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
-      echo "Cannot get foreign keys back? Huh?";
-      exit;
-    }
-
-    unset($query, $query2, $query3);
-
-    // Rebuild triggers
-    civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
-
-    CRM_Core_BAO_ConfigSetting::setEnabledComponents(array(
-      'CiviEvent',
-      'CiviContribute',
-      'CiviMember',
-      'CiviMail',
-      'CiviReport',
-      'CiviPledge',
-    ));
+    Civi\Test::data()->populate();
 
     return TRUE;
   }
@@ -401,19 +289,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     // "initialize" CiviCRM to avoid problems when running single tests
     // FIXME: look at it closer in second stage
 
-    // initialize the object once db is loaded
-    CRM_Core_Config::$_mail = NULL;
-    $config = CRM_Core_Config::singleton();
-
-    // when running unit tests, use mockup user framework
-    $config->setUserFramework('UnitTests');
-    $this->hookClass = CRM_Utils_Hook::singleton(TRUE);
-    // also fix the fatal error handler to throw exceptions,
-    // rather than exit
-    $config->fatalErrorHandler = 'CiviUnitTestCase_fatalErrorHandler';
-
-    // enable backtrace to get meaningful errors
-    $config->backtrace = 1;
+    $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
+    $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
 
     // disable any left-over test extensions
     CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
@@ -421,24 +298,26 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     // reset all the caches
     CRM_Utils_System::flushCache();
 
+    // initialize the object once db is loaded
+    \Civi::reset();
+    $config = CRM_Core_Config::singleton(TRUE, TRUE); // ugh, performance
+
+    // when running unit tests, use mockup user framework
+    $this->hookClass = CRM_Utils_Hook::singleton();
+
     // Make sure the DB connection is setup properly
     $config->userSystem->setMySQLTimeZone();
-    $env = new CRM_Utils_Check_Env();
+    $env = new CRM_Utils_Check_Component_Env();
     CRM_Utils_Check::singleton()->assertValid($env->checkMysqlTime());
 
     // clear permissions stub to not check permissions
-    $config = CRM_Core_Config::singleton();
     $config->userPermissionClass->permissions = NULL;
 
     //flush component settings
     CRM_Core_Component::getEnabledComponents(TRUE);
 
-    if ($this->_eNoticeCompliant) {
-      error_reporting(E_ALL);
-    }
-    else {
-      error_reporting(E_ALL & ~E_NOTICE);
-    }
+    error_reporting(E_ALL);
+
     $this->_sethtmlGlobals();
   }
 
@@ -495,15 +374,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     return $contactID;
   }
 
-  public function cleanDB() {
-    self::$populateOnce = NULL;
-    $this->DBResetRequired = TRUE;
-
-    $this->_dbconn = $this->getConnection();
-    static::_populateDB();
-    $this->tempDirs = array();
-  }
-
   /**
    * Create default domain contacts for the two domains added during test class.
    * database population.
@@ -541,30 +411,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
 
     $this->cleanTempDirs();
     $this->unsetExtensionSystem();
-    $this->clearOutputBuffer();
-  }
-
-  /**
-   *  FIXME: Maybe a better way to do it
-   */
-  public function foreignKeyChecksOff() {
-    self::$utils = new Utils($GLOBALS['mysql_host'],
-      $GLOBALS['mysql_port'],
-      $GLOBALS['mysql_user'],
-      $GLOBALS['mysql_pass']
-    );
-    $dbName = self::getDBName();
-    $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
-    if (self::$utils->do_query($query) === FALSE) {
-      // fail happens
-      echo 'Cannot set foreign_key_checks = 0';
-      exit(1);
-    }
-    return TRUE;
-  }
-
-  public function foreignKeyChecksOn() {
-    // FIXME: might not be needed if previous fixme implemented
   }
 
   /**
@@ -789,7 +635,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
         $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . "  value 2 is " . print_r($actualValues[$paramName], TRUE));
       }
       else {
-        $this->fail("Attribute '$paramName' not present in actual array.");
+        $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
       }
     }
   }
@@ -941,7 +787,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     );
 
     $calls = new \Civi\API\ExternalBatch($defaultParams);
-    $calls->setSettingsPath("$civicrm_root/tests/phpunit/CiviTest/civicrm.settings.cli.php");
 
     if (!$calls->isSupported()) {
       $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
@@ -1502,26 +1347,27 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Create Payment Processor.
    *
-   * @return CRM_Financial_DAO_PaymentProcessor
-   *   instance of Payment Processor
+   * @return int
+   *   Id Payment Processor
    */
   public function processorCreate() {
     $processorParams = array(
       'domain_id' => 1,
       'name' => 'Dummy',
-      'payment_processor_type_id' => 10,
+      'payment_processor_type_id' => 'Dummy',
       'financial_account_id' => 12,
+      'is_test' => TRUE,
       'is_active' => 1,
       'user_name' => '',
       'url_site' => 'http://dummy.com',
       'url_recur' => 'http://dummy.com',
       'billing_mode' => 1,
+      'sequential' => 1,
     );
-    $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
-    return $paymentProcessor;
+    $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
+    return $processor['id'];
   }
 
-
   /**
    * Create Payment Processor.
    *
@@ -1532,7 +1378,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    */
   public function dummyProcessorCreate($processorParams = array()) {
     $paymentProcessorID = $this->processorCreate($processorParams);
-    return Civi\Payment\System::singleton()->getById($paymentProcessorID);
+    return System::singleton()->getById($paymentProcessorID);
   }
 
   /**
@@ -1662,17 +1508,11 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *
    * @param array $params
    *   Array of parameters.
-   * @param int $cTypeID
-   *   Id of financial type.
-   * @param int $invoiceID
-   * @param int $trxnID
-   * @param int $paymentInstrumentID
    *
    * @return int
    *   id of created contribution
    */
-  public function contributionCreate($params, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345,
-    $paymentInstrumentID = 1) {
+  public function contributionCreate($params) {
 
     $params = array_merge(array(
       'domain_id' => 1,
@@ -1680,11 +1520,11 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       'total_amount' => 100.00,
       'fee_amount' => 5.00,
       'net_ammount' => 95.00,
-      'financial_type_id' => $cTypeID,
-      'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
+      'financial_type_id' => 1,
+      'payment_instrument_id' => 1,
       'non_deductible_amount' => 10.00,
-      'trxn_id' => $trxnID,
-      'invoice_id' => $invoiceID,
+      'trxn_id' => 12345,
+      'invoice_id' => 67890,
       'source' => 'SSF',
       'contribution_status_id' => 1,
     ), $params);
@@ -1693,35 +1533,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     return $result['id'];
   }
 
-  /**
-   * Create online contribution.
-   *
-   * @param array $params
-   * @param int $financialType
-   *   Id of financial type.
-   * @param int $invoiceID
-   * @param int $trxnID
-   *
-   * @return int
-   *   id of created contribution
-   */
-  public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
-    $contribParams = array(
-      'contact_id' => $params['contact_id'],
-      'receive_date' => date('Ymd'),
-      'total_amount' => 100.00,
-      'financial_type_id' => $financialType,
-      'contribution_page_id' => $params['contribution_page_id'],
-      'trxn_id' => 12345,
-      'invoice_id' => 67890,
-      'source' => 'SSF',
-    );
-    $contribParams = array_merge($contribParams, $params);
-    $result = $this->callAPISuccess('contribution', 'create', $contribParams);
-
-    return $result['id'];
-  }
-
   /**
    * Delete contribution.
    *
@@ -1851,7 +1662,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
         'is_primary' => 1,
         'name' => 'Saint Helier St',
         'county' => 'Marin',
-        'country' => 'United States',
+        'country' => 'UNITED STATES',
         'state_province' => 'Michigan',
         'supplemental_address_1' => 'Hallmark Ct',
         'supplemental_address_2' => 'Jersey Village',
@@ -1916,6 +1727,43 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     $locationType->delete();
   }
 
+  /**
+   * Add a Mapping.
+   *
+   * @param array $params
+   * @return CRM_Core_DAO_Mapping
+   *   Mapping id of created mapping
+   */
+  public function mappingCreate($params = NULL) {
+    if ($params === NULL) {
+      $params = array(
+        'name' => 'Mapping name',
+        'description' => 'Mapping description',
+        // 'Export Contact' mapping.
+        'mapping_type_id' => 7,
+      );
+    }
+
+    $mapping = new CRM_Core_DAO_Mapping();
+    $mapping->copyValues($params);
+    $mapping->save();
+    // clear getfields cache
+    CRM_Core_PseudoConstant::flush();
+    $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
+    return $mapping;
+  }
+
+  /**
+   * Delete a Mapping
+   *
+   * @param int $mappingId
+   */
+  public function mappingDelete($mappingId) {
+    $mapping = new CRM_Core_DAO_Mapping();
+    $mapping->id = $mappingId;
+    $mapping->delete();
+  }
+
   /**
    * Add a Group.
    *
@@ -2577,7 +2425,9 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   }
 
   /**
-   * @param $tablesToTruncate
+   * Quick clean by emptying tables created for the test.
+   *
+   * @param array $tablesToTruncate
    * @param bool $dropCustomValueTables
    * @throws \Exception
    */
@@ -2586,6 +2436,12 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       throw new 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()) {
+        if (!empty($optionGroupResult->option_group_id)) {
+          CRM_Core_DAO::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id);
+        }
+      }
       $tablesToTruncate[] = 'civicrm_custom_group';
       $tablesToTruncate[] = 'civicrm_custom_field';
     }
@@ -2651,7 +2507,7 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
     $this->restoreDefaultPriceSetConfig();
     $var = TRUE;
     CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
-    Civi\Payment\System::singleton()->flushProcessors();
+    System::singleton()->flushProcessors();
   }
 
   public function restoreDefaultPriceSetConfig() {
@@ -2793,7 +2649,6 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
    *   'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
    */
   public function customDirectories($customDirs) {
-    require_once 'CRM/Core/Config.php';
     $config = CRM_Core_Config::singleton();
 
     if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
@@ -2868,9 +2723,7 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
    * @return void
    */
   public function setMockSettingsMetaData($extras) {
-    CRM_Core_BAO_Setting::$_cache = array();
-    $this->callAPISuccess('system', 'flush', array());
-    CRM_Core_BAO_Setting::$_cache = array();
+    Civi::service('settings_manager')->flush();
 
     CRM_Utils_Hook::singleton()
       ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
@@ -3270,7 +3123,6 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
         'trxn_id' => 345,
       ));
     }
-
     $this->setupRecurringPaymentProcessorTransaction();
 
     $this->ids['membership'] = $this->callAPISuccess('membership', 'create', array(
@@ -3368,12 +3220,6 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
     }
   }
 
-  public function clearOutputBuffer() {
-    while (ob_get_level() > 0) {
-      ob_end_clean();
-    }
-  }
-
   /**
    * Assert the attachment exists.
    *
@@ -3453,4 +3299,107 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
     ));
   }
 
+  /**
+   * Add participant with contribution
+   *
+   * @return array
+   */
+  protected function createParticipantWithContribution() {
+    // creating price set, price field
+    $this->_contactId = Contact::createIndividual();
+    $this->_eventId = Event::create($this->_contactId);
+    $eventParams = array(
+      'id' => $this->_eventId,
+      'financial_type_id' => 4,
+      'is_monetary' => 1,
+    );
+    $this->callAPISuccess('event', 'create', $eventParams);
+    $priceFields = $this->createPriceSet('event', $this->_eventId);
+    $participantParams = array(
+      'financial_type_id' => 4,
+      'event_id' => $this->_eventId,
+      'role_id' => 1,
+      'status_id' => 14,
+      'fee_currency' => 'USD',
+      'contact_id' => $this->_contactId,
+    );
+    $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
+    $contributionParams = array(
+      'total_amount' => 150,
+      'currency' => 'USD',
+      'contact_id' => $this->_contactId,
+      'financial_type_id' => 4,
+      'contribution_status_id' => 1,
+      'partial_payment_total' => 300.00,
+      'partial_amount_pay' => 150,
+      'contribution_mode' => 'participant',
+      'participant_id' => $participant['id'],
+    );
+    foreach ($priceFields['values'] as $key => $priceField) {
+      $lineItems[1][$key] = array(
+        'price_field_id' => $priceField['price_field_id'],
+        'price_field_value_id' => $priceField['id'],
+        'label' => $priceField['label'],
+        'field_title' => $priceField['label'],
+        'qty' => 1,
+        'unit_price' => $priceField['amount'],
+        'line_total' => $priceField['amount'],
+        'financial_type_id' => $priceField['financial_type_id'],
+      );
+    }
+    $contributionParams['line_item'] = $lineItems;
+    $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
+    $paymentParticipant = array(
+      'participant_id' => $participant['id'],
+      'contribution_id' => $contribution['id'],
+    );
+    $ids = array();
+    $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
+    return array($lineItems, $contribution);
+  }
+
+  /**
+   * Create price set
+   *
+   * @param string $component
+   * @param int $componentId
+   *
+   * @return array
+   */
+  protected function createPriceSet($component = 'contribution_page', $componentId = NULL) {
+    $paramsSet['title'] = 'Price Set';
+    $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
+    $paramsSet['is_active'] = TRUE;
+    $paramsSet['financial_type_id'] = 4;
+    $paramsSet['extends'] = 1;
+    $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
+    $priceSetId = $priceSet['id'];
+    //Checking for priceset added in the table.
+    $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
+      'id', $paramsSet['title'], 'Check DB for created priceset'
+    );
+    $paramsField = array(
+      'label' => 'Price Field',
+      'name' => CRM_Utils_String::titleToVar('Price Field'),
+      'html_type' => 'CheckBox',
+      'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
+      'option_value' => array('1' => 100, '2' => 200),
+      'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
+      'option_weight' => array('1' => 1, '2' => 2),
+      'option_amount' => array('1' => 100, '2' => 200),
+      'is_display_amounts' => 1,
+      'weight' => 1,
+      'options_per_line' => 1,
+      'is_active' => array('1' => 1, '2' => 1),
+      'price_set_id' => $priceSet['id'],
+      'is_enter_qty' => 1,
+      'financial_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
+    );
+    $priceField = CRM_Price_BAO_PriceField::create($paramsField);
+    if ($componentId) {
+      CRM_Price_BAO_PriceSet::addTo('civicrm_' . $component, $componentId, $priceSetId);
+    }
+    return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id));
+  }
+
 }