]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - tests/service/RESTAPI4Test.php
Release 6.2.0
[Github/sugarcrm.git] / tests / service / RESTAPI4Test.php
1 <?php
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5  * 
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of the GNU Affero General Public License version 3 as published by the
8  * Free Software Foundation with the addition of the following permission added
9  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12  * 
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
16  * details.
17  * 
18  * You should have received a copy of the GNU Affero General Public License along with
19  * this program; if not, see http://www.gnu.org/licenses or write to the Free
20  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  * 02110-1301 USA.
22  * 
23  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25  * 
26  * The interactive user interfaces in modified source and object code versions
27  * of this program must display Appropriate Legal Notices, as required under
28  * Section 5 of the GNU Affero General Public License version 3.
29  * 
30  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31  * these Appropriate Legal Notices must retain the display of the "Powered by
32  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33  * technical reasons, the Appropriate Legal Notices must display the words
34  * "Powered by SugarCRM".
35  ********************************************************************************/
36
37  
38 require_once('service/v3/SugarWebServiceUtilv3.php');
39 require_once('tests/service/APIv3Helper.php');
40
41
42 class RESTAPI4Test extends Sugar_PHPUnit_Framework_TestCase
43 {
44     protected $_user;
45     protected $_admin_user;
46     protected $_lastRawResponse;
47
48     private static $helperObject;
49     
50     protected $aclRole;
51     protected $aclField;
52     
53     public function setUp()
54     {
55         $beanList = array();
56                 $beanFiles = array();
57                 require('include/modules.php');
58                 $GLOBALS['beanList'] = $beanList;
59                 $GLOBALS['beanFiles'] = $beanFiles;
60                 
61         //Reload langauge strings
62         $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
63         $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
64         $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], 'Accounts');
65         //Create an anonymous user for login purposes/
66         $this->_user = SugarTestUserUtilities::createAnonymousUser();
67         
68         $this->_admin_user = SugarTestUserUtilities::createAnonymousUser();
69         $this->_admin_user->status = 'Active';
70         $this->_admin_user->is_admin = 1;
71         $this->_admin_user->save();
72         $GLOBALS['current_user'] = $this->_user;
73
74         self::$helperObject = new APIv3Helper();
75         
76         //Disable access to the website field.
77         $this->aclRole = new ACLRole();
78         $this->aclRole->name = "Unit Test";
79         $this->aclRole->save();
80         $this->aclRole->set_relationship('acl_roles_users', array('role_id'=>$this->aclRole->id ,'user_id'=> $this->_user->id), false);
81     }
82
83     public function tearDown()
84         {
85             $GLOBALS['db']->query("DELETE FROM acl_roles WHERE id IN ( SELECT role_id FROM acl_user_roles WHERE user_id = '{$GLOBALS['current_user']->id}' )");
86             $GLOBALS['db']->query("DELETE FROM acl_user_roles WHERE user_id = '{$GLOBALS['current_user']->id}'");
87             
88             if(isset($GLOBALS['listViewDefs'])) unset($GLOBALS['listViewDefs']);
89             if(isset($GLOBALS['viewdefs'])) unset($GLOBALS['viewdefs']);
90             unset($GLOBALS['beanList']);
91                 unset($GLOBALS['beanFiles']);
92                 unset($GLOBALS['app_list_strings']);
93             unset($GLOBALS['app_strings']);
94             unset($GLOBALS['mod_strings']);
95             unset($GLOBALS['current_user']);
96         SugarTestUserUtilities::removeAllCreatedAnonymousUsers();
97         }
98
99     protected function _makeRESTCall($method,$parameters)
100     {
101         // specify the REST web service to interact with
102         $url = $GLOBALS['sugar_config']['site_url'].'/service/v4/rest.php';
103         // Open a curl session for making the call
104         $curl = curl_init($url);
105         // set URL and other appropriate options
106         curl_setopt($curl, CURLOPT_URL, $url);
107         curl_setopt($curl, CURLOPT_POST, 1);
108         curl_setopt($curl, CURLOPT_HEADER, 0);
109         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
110         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
111         curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
112         curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
113         // build the request URL
114         $json = json_encode($parameters);
115         $postArgs = "method=$method&input_type=JSON&response_type=JSON&rest_data=$json";
116         curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
117         // Make the REST call, returning the result
118         $response = curl_exec($curl);
119         // Close the connection
120         curl_close($curl);
121
122         $this->_lastRawResponse = $response;
123
124         // Convert the result from JSON format to a PHP array
125         return json_decode($response,true);
126     }
127
128     protected function _returnLastRawResponse()
129     {
130         return "Error in web services call. Response was: {$this->_lastRawResponse}";
131     }
132
133     protected function _login($user = null)
134     {
135         if($user == null)
136             $user = $this->_user;
137         return $this->_makeRESTCall('login',
138             array(
139                 'user_auth' =>
140                     array(
141                         'user_name' => $user->user_name,
142                         'password' => $user->user_hash,
143                         'version' => '.01',
144                         ),
145                 'application_name' => 'mobile',
146                 'name_value_list' => array(),
147                 )
148             );
149     }
150     /**
151      * Ensure the ability to retrieve a module list of recrods that are favorites.
152      *
153      */
154     public function testGetModuleFavoriteList()
155     {
156         $result = $this->_login($this->_admin_user);
157         $session = $result['id'];
158
159         $account = new Account();
160         $account->id = uniqid();
161         $account->new_with_id = TRUE;
162         $account->name = "Test " . $account->id;
163         $account->save();
164
165         $this->_markBeanAsFavorite($session, "Accounts", $account->id);
166         
167         $whereClause = "accounts.name='{$account->name}'";
168         $module = 'Accounts';
169         $orderBy = 'name';
170         $offset = 0;
171         $returnFields = array('name');
172         $linkNameFields = "";
173         $maxResults = 50;
174         $deleted = FALSE;
175         $favorites = TRUE;
176         $result = $this->_makeRESTCall('get_entry_list', array($session, $module, $whereClause, $orderBy,$offset, $returnFields,$linkNameFields, $maxResults, $deleted, $favorites));
177
178         $this->assertEquals($account->id, $result['entry_list'][0]['id'],'Unable to retrieve account favorite list.');
179
180         $GLOBALS['db']->query("DELETE FROM accounts WHERE id = '{$account->id}'");
181         $GLOBALS['db']->query("DELETE FROM sugarfavorites WHERE record_id = '{$account->id}'");
182     }
183     
184     /**
185      * Test set entries call with name value list format key=>value.
186      *
187      */
188     public function testSetEntriesCall()
189     {
190         $result = $this->_login();
191         $session = $result['id'];
192         $module = 'Contacts';
193         $c1_uuid = uniqid();
194         $c2_uuid = uniqid();
195         $contacts = array( 
196             array('first_name' => 'Unit Test', 'last_name' => $c1_uuid), 
197             array('first_name' => 'Unit Test', 'last_name' => $c2_uuid)
198         );
199         $results = $this->_makeRESTCall('set_entries',
200         array(
201             'session' => $session,
202             'module' => $module,
203             'name_value_lists' => $contacts,
204         ));
205         $this->assertTrue(isset($results['ids']) && count($results['ids']) == 2);
206         
207         $actual_results = $this->_makeRESTCall('get_entries',
208         array(
209             'session' => $session,
210             'module' => $module,
211             'ids' => $results['ids'],
212             'select_fields' => array('first_name','last_name')
213         ));
214         
215         $this->assertTrue(isset($actual_results['entry_list']) && count($actual_results['entry_list']) == 2);
216         $this->assertEquals($actual_results['entry_list'][0]['name_value_list']['last_name']['value'], $c1_uuid);
217         $this->assertEquals($actual_results['entry_list'][1]['name_value_list']['last_name']['value'], $c2_uuid);
218     }
219     
220     
221     /**
222      * Test search by module with favorites flag enabled.
223      *
224      */
225     public function testSearchByModuleWithFavorites()
226     {
227         $result = $this->_login($this->_admin_user);
228         $session = $result['id'];
229
230         $account = new Account();
231         $account->id = uniqid();
232         $account->assigned_user_id = $this->_user->id;
233         $account->team_id = 1;
234         $account->new_with_id = TRUE;
235         $account->name = "Unit Test Fav " . $account->id;
236         $account->save();
237         $this->_markBeanAsFavorite($session, "Accounts", $account->id);
238         
239         //Negative test.
240         $account2 = new Account();
241         $account2->id = uniqid();
242         $account2->new_with_id = TRUE;
243         $account2->name = "Unit Test Fav " . $account->id;
244         $account->assigned_user_id = $this->_user->id;
245         $account2->save();
246         
247         $searchModules = array('Accounts');
248         $searchString = "Unit Test Fav ";
249         $offSet = 0;
250         $maxResults = 10;
251
252         $results = $this->_makeRESTCall('search_by_module',
253                         array(
254                             'session' => $session,
255                             'search_string'  => $searchString,
256                             'modules' => $searchModules,
257                             'offset'  => $offSet,
258                             'max_results'     => $maxResults,
259                             'assigned_user_id'    => $this->_user->id,
260                             'select_fields' => array(),
261                             'unified_search_only' => true,
262                             'favorites' => true,                            
263                             )
264                         );
265         
266         $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'Unit Test %' ");
267         $GLOBALS['db']->query("DELETE FROM sugarfavorites WHERE record_id = '{$account->id}'");
268         $GLOBALS['db']->query("DELETE FROM sugarfavorites WHERE record_id = '{$account2->id}'");
269         
270         $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$account->id,'Accounts'), "Unable to find {$account->id} id in favorites search.");
271         $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$account2->id,'Accounts'), "Account {$account2->id} id in favorites search should not be there.");
272     }    
273     /**
274      * Private helper function to mark a bean as a favorite item.
275      *
276      * @param string $session
277      * @param string $moduleName
278      * @param string $recordID
279      */
280     private function _markBeanAsFavorite($session, $moduleName, $recordID)
281     {
282         $result = $this->_makeRESTCall('set_entry',
283             array(
284                 'session' => $session,
285                 'module' => 'SugarFavorites',
286                 'name_value_list' => array(
287                     array('name' => 'record_id', 'value' => $recordID),
288                     array('name' => 'module', 'value' => $moduleName),
289                     ),
290                 )
291             );
292     }
293 }