From 3097a0d61a37450044aa68fab9f0b9faf2115649 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Sun, 25 Aug 2013 23:27:21 -0700 Subject: [PATCH] CRM-13261 - Add unit test for hook_civicrm_apiWrappers ---------------------------------------- * CRM-13261: add hooks to extend the API from extension http://issues.civicrm.org/jira/browse/CRM-13261 --- tests/phpunit/api/v3/APIWrapperTest.php | 112 ++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 tests/phpunit/api/v3/APIWrapperTest.php diff --git a/tests/phpunit/api/v3/APIWrapperTest.php b/tests/phpunit/api/v3/APIWrapperTest.php new file mode 100644 index 0000000000..7c7a4aae11 --- /dev/null +++ b/tests/phpunit/api/v3/APIWrapperTest.php @@ -0,0 +1,112 @@ +setHook('civicrm_apiWrappers', array($this, 'onApiWrappers')); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + * + * @access protected + */ + protected function tearDown() { + parent::tearDown(); + } + + function onApiWrappers(&$apiWrappers, $apiRequest) { + $this->assertTrue(is_string($apiRequest['entity']) && !empty($apiRequest['entity'])); + $this->assertTrue(is_string($apiRequest['action']) && !empty($apiRequest['action'])); + $this->assertTrue(is_array($apiRequest['params']) && !empty($apiRequest['params'])); + + $apiWrappers[] = new api_v3_APIWrapperTest_Impl(); + } + + function testWrapperHook() { + // Note: this API call would fail due to missing contact_type, but + // the wrapper intervenes (fromApiInput) + // Note: The output would define "display_name", but the wrapper + // intervenes (toApiOutput) and replaces with "display_name_munged". + $result = $this->callAPISuccess('contact', 'create', array( + 'contact_type' => 'Invalid', + 'first_name' => 'First', + 'last_name' => 'Last', + )); + $this->assertEquals('First', $result['values'][$result['id']]['first_name']); + $this->assertEquals('MUNGE! First Last', $result['values'][$result['id']]['display_name_munged']); + } +} + +class api_v3_APIWrapperTest_Impl implements API_Wrapper { + /** + * {@inheritDoc} + */ + public function fromApiInput($apiRequest) { + if ($apiRequest['entity'] == 'contact' && $apiRequest['action'] == 'create') { + if ('Invalid' == CRM_Utils_Array::value('contact_type', $apiRequest['params'])) { + $apiRequest['params']['contact_type'] = 'Individual'; + } + } + return $apiRequest; + } + + /** + * {@inheritDoc} + */ + public function toApiOutput($apiRequest, $result) { + if ($apiRequest['entity'] == 'contact' && $apiRequest['action'] == 'create') { + if (isset($result['id'], $result['values'][$result['id']]['display_name'])) { + $result['values'][$result['id']]['display_name_munged'] = 'MUNGE! ' . $result['values'][$result['id']]['display_name']; + unset($result['values'][$result['id']]['display_name']); + } + } + return $result; + } +} -- 2.25.1