]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - tests/service/RESTAPI3Test.php
Release 6.4.0beta3
[Github/sugarcrm.git] / tests / service / RESTAPI3Test.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 RESTAPI3Test extends Sugar_PHPUnit_Framework_TestCase
43 {
44     protected $_user;
45
46     protected $_lastRawResponse;
47
48     private static $helperObject;
49
50     private $_unified_search_modules_content;
51
52     public function setUp()
53     {
54         global $beanList, $beanFiles;
55         include('include/modules.php');
56
57         //Reload langauge strings
58         $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
59         $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
60         $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], 'Accounts');
61         //Create an anonymous user for login purposes/
62         $this->_user = new User();
63         $this->_user->retrieve('1');
64         $GLOBALS['current_user'] = $this->_user;
65
66         self::$helperObject = new APIv3Helper();
67
68
69         if(file_exists(sugar_cached('modules/unified_search_modules.php')))
70         {
71             $this->unified_search_modules_content = file_get_contents(sugar_cached('modules/unified_search_modules.php'));
72             unlink(sugar_cached('modules/unified_search_modules.php'));
73         }
74
75         require_once('modules/Home/UnifiedSearchAdvanced.php');
76         $unifiedSearchAdvanced = new UnifiedSearchAdvanced();
77         $_REQUEST['enabled_modules'] = 'Accounts,Contacts,Opportunities';
78         $unifiedSearchAdvanced->saveGlobalSearchSettings();
79
80         $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'UNIT TEST%' ");
81         $GLOBALS['db']->query("DELETE FROM opportunities WHERE name like 'UNIT TEST%' ");
82         $GLOBALS['db']->query("DELETE FROM contacts WHERE first_name like 'UNIT TEST%' ");
83
84         //$this->useOutputBuffering = false;
85     }
86
87     public function tearDown()
88         {
89             if(isset($GLOBALS['listViewDefs'])) unset($GLOBALS['listViewDefs']);
90             if(isset($GLOBALS['viewdefs'])) unset($GLOBALS['viewdefs']);
91             unset($GLOBALS['app_list_strings']);
92             unset($GLOBALS['app_strings']);
93             unset($GLOBALS['mod_strings']);
94
95         if(!empty($this->unified_search_modules_content))
96         {
97             file_put_contents(sugar_cached('modules/unified_search_modules.php'), $this->unified_search_modules_content);
98         }
99
100         $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'UNIT TEST%' ");
101         $GLOBALS['db']->query("DELETE FROM opportunities WHERE name like 'UNIT TEST%' ");
102         $GLOBALS['db']->query("DELETE FROM contacts WHERE first_name like 'UNIT TEST%' ");
103         }
104
105     protected function _makeRESTCall($method,$parameters)
106     {
107         // specify the REST web service to interact with
108         $url = $GLOBALS['sugar_config']['site_url'].'/service/v3/rest.php';
109         // Open a curl session for making the call
110         $curl = curl_init($url);
111         // set URL and other appropriate options
112         curl_setopt($curl, CURLOPT_URL, $url);
113         curl_setopt($curl, CURLOPT_POST, 1);
114         curl_setopt($curl, CURLOPT_HEADER, 0);
115         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
116         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
117         curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
118         curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
119         // build the request URL
120         $json = json_encode($parameters);
121         $postArgs = "method=$method&input_type=JSON&response_type=JSON&rest_data=$json";
122         curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
123         // Make the REST call, returning the result
124         $response = curl_exec($curl);
125         // Close the connection
126         curl_close($curl);
127
128         $this->_lastRawResponse = $response;
129
130         // Convert the result from JSON format to a PHP array
131         return json_decode($response,true);
132     }
133
134     protected function _returnLastRawResponse()
135     {
136         return "Error in web services call. Response was: {$this->_lastRawResponse}";
137     }
138
139     protected function _login()
140     {
141         $GLOBALS['db']->commit(); // Making sure we commit any changes before logging in
142
143         return $this->_makeRESTCall('login',
144             array(
145                 'user_auth' =>
146                     array(
147                         'user_name' => $this->_user->user_name,
148                         'password' => $this->_user->user_hash,
149                         'version' => '.01',
150                         ),
151                 'application_name' => 'SugarTestRunner',
152                 'name_value_list' => array(),
153                 )
154             );
155     }
156
157     public function testSearchByModule()
158     {
159         $seedData = self::$helperObject->populateSeedDataForSearchTest($this->_user->id);
160
161         $searchModules = array('Accounts','Contacts','Opportunities');
162         $searchString = "UNIT TEST";
163         $offSet = 0;
164         $maxResults = 10;
165
166         $result = $this->_login(); // Logging in just before the REST call as this will also commit any pending DB changes
167         $session = $result['id'];
168         $results = $this->_makeRESTCall('search_by_module',
169                         array(
170                             'session' => $session,
171                             'search'  => $searchString,
172                             'modules' => $searchModules,
173                             'offset'  => $offSet,
174                             'max'     => $maxResults,
175                             'user'    => $this->_user->id)
176                         );
177
178         $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[0]['id'],'Accounts') );
179         $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[1]['id'],'Accounts') );
180         $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[2]['id'],'Contacts') );
181         $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[3]['id'],'Opportunities') );
182         $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[4]['id'],'Opportunities') );
183     }
184
185     public function testSearchByModuleWithReturnFields()
186     {
187         $seedData = self::$helperObject->populateSeedDataForSearchTest($this->_user->id);
188
189         $returnFields = array('name','id','deleted');
190         $searchModules = array('Accounts','Contacts','Opportunities');
191         $searchString = "UNIT TEST";
192         $offSet = 0;
193         $maxResults = 10;
194
195         $result = $this->_login(); // Logging in just before the REST call as this will also commit any pending DB changes
196         $session = $result['id'];
197         $results = $this->_makeRESTCall('search_by_module',
198                         array(
199                             'session' => $session,
200                             'search'  => $searchString,
201                             'modules' => $searchModules,
202                             'offset'  => $offSet,
203                             'max'     => $maxResults,
204                             'user'    => $this->_user->id,
205                             'selectFields' => $returnFields)
206                         );
207
208
209         $this->assertEquals($seedData[0]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[0]['id'],'Accounts', $seedData[0]['fieldName']));
210         $this->assertFalse(self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[1]['id'],'Accounts', $seedData[1]['fieldName']));
211         $this->assertEquals($seedData[2]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[2]['id'],'Contacts', $seedData[2]['fieldName']));
212         $this->assertEquals($seedData[3]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[3]['id'],'Opportunities', $seedData[3]['fieldName']));
213         $this->assertFalse(self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[4]['id'],'Opportunities', $seedData[4]['fieldName']));
214     }
215
216     public function testGetServerInformation()
217     {
218         require('sugar_version.php');
219
220         $result = $this->_login();
221         $session = $result['id'];
222
223         $result = $this->_makeRESTCall('get_server_info',array());
224
225         $this->assertEquals($sugar_version, $result['version'],'Unable to get server information');
226         $this->assertEquals($sugar_flavor, $result['flavor'],'Unable to get server information');
227     }
228
229     public function testGetModuleList()
230     {
231         $account = new Account();
232         $account->id = uniqid();
233         $account->new_with_id = TRUE;
234         $account->name = "Test " . $account->id;
235         $account->save();
236
237         $whereClause = "accounts.name='{$account->name}'";
238         $module = 'Accounts';
239         $orderBy = 'name';
240         $offset = 0;
241         $returnFields = array('name');
242
243         $result = $this->_login(); // Logging in just before the REST call as this will also commit any pending DB changes
244         $session = $result['id'];
245         $result = $this->_makeRESTCall('get_entry_list', array($session, $module, $whereClause, $orderBy,$offset, $returnFields));
246
247         $this->assertEquals($account->id, $result['entry_list'][0]['id'],'Unable to retrieve account list during search.');
248
249         $GLOBALS['db']->query("DELETE FROM accounts WHERE id = '{$account->id}'");
250
251     }
252
253     public function testLogin()
254     {
255         $result = $this->_login();
256         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
257     }
258
259     public static function _multipleModuleLayoutProvider()
260     {
261         return array(
262                         array(
263                             'module' => array('Accounts','Contacts'),
264                             'type' => array('default'),
265                             'view' => array('list'),
266                             'expected_file' => array(
267                                 'Accounts' => array( 'default' => array('list' => 'modules/Accounts/metadata/listviewdefs.php')),
268                                 'Contacts' => array( 'default' => array('list' => 'modules/Contacts/metadata/listviewdefs.php')))
269                         ),
270                         array(
271                             'module' => array('Accounts','Contacts'),
272                             'type' => array('default'),
273                             'view' => array('list','detail'),
274                             'expected_file' => array(
275                                 'Accounts' => array(
276                                     'default' => array(
277                                                 'list' => 'modules/Accounts/metadata/listviewdefs.php',
278                                                 'detail' => 'modules/Accounts/metadata/detailviewdefs.php')),
279                                 'Contacts' => array(
280                                     'default' => array(
281                                                 'list' => 'modules/Contacts/metadata/listviewdefs.php',
282                                                 'detail' => 'modules/Contacts/metadata/detailviewdefs.php'))
283                         ))
284         );
285     }
286
287     /**
288      * @dataProvider _multipleModuleLayoutProvider
289      */
290     public function testGetMultipleModuleLayout($a_module, $a_type, $a_view, $a_expected_file)
291     {
292         $result = $this->_login();
293         $session = $result['id'];
294
295         $results = $this->_makeRESTCall('get_module_layout',
296                         array(
297                             'session' => $session,
298                             'module' => $a_module,
299                             'type' => $a_type,
300                             'view' => $a_view)
301                         );
302
303         foreach ($results as $module => $moduleResults )
304         {
305             foreach ($moduleResults as $type => $viewResults)
306             {
307                 foreach ($viewResults as $view => $result)
308                 {
309                     $expected_file = $a_expected_file[$module][$type][$view];
310                     if ( is_file('custom'  . DIRECTORY_SEPARATOR . $expected_file) )
311                         require('custom'  . DIRECTORY_SEPARATOR . $expected_file);
312                     else
313                         require($expected_file);
314
315                     if($view == 'list')
316                         $expectedResults = $listViewDefs[$module];
317                     else
318                         $expectedResults = $viewdefs[$module][ucfirst($view) .'View' ];
319
320                     $this->assertEquals(md5(serialize($expectedResults)), md5(serialize($result)), "Unable to retrieve module layout: module {$module}, type $type, view $view");
321                 }
322                 }
323         }
324    }
325
326     public static function _moduleLayoutProvider()
327     {
328         return array(
329                     array('module' => 'Accounts','type' => 'default', 'view' => 'list','expected_file' => 'modules/Accounts/metadata/listviewdefs.php' ),
330                     array('module' => 'Accounts','type' => 'default', 'view' => 'edit','expected_file' => 'modules/Accounts/metadata/editviewdefs.php' ),
331                     array('module' => 'Accounts','type' => 'default', 'view' => 'detail','expected_file' => 'modules/Accounts/metadata/detailviewdefs.php' ),
332         );
333     }
334
335     /**
336      * @dataProvider _moduleLayoutProvider
337      */
338     public function testGetModuleLayout($module, $type, $view, $expected_file)
339     {
340         $result = $this->_login();
341         $session = $result['id'];
342
343         $result = $this->_makeRESTCall('get_module_layout',
344                         array(
345                             'session' => $session,
346                             'module' => array($module),
347                             'type' => array($type),
348                             'view' => array($view))
349                         );
350
351         if ( is_file('custom'  . DIRECTORY_SEPARATOR . $expected_file) )
352                 require('custom'  . DIRECTORY_SEPARATOR . $expected_file);
353         else
354             require($expected_file);
355
356         if($view == 'list')
357             $expectedResults = $listViewDefs[$module];
358         else
359             $expectedResults = $viewdefs[$module][ucfirst($view) .'View' ];
360
361         $a_expectedResults = array();
362         $a_expectedResults[$module][$type][$view] = $expectedResults;
363
364         $this->assertEquals(md5(serialize($a_expectedResults)), md5(serialize($result)), "Unable to retrieve module layout: module {$module}, type $type, view $view");
365     }
366
367      /**
368      * @dataProvider _moduleLayoutProvider
369      */
370     public function testGetModuleLayoutMD5($module, $type, $view, $expected_file)
371     {
372         $result = $this->_login();
373         $session = $result['id'];
374
375         $fullResult = $this->_makeRESTCall('get_module_layout_md5',
376                         array(
377                             'session' => $session,
378                             'module' => array($module),
379                             'type' => array($type),
380                             'view' => array($view) )
381                         );
382         $result = $fullResult['md5'];
383         if ( is_file('custom'  . DIRECTORY_SEPARATOR . $expected_file) )
384                 require('custom'  . DIRECTORY_SEPARATOR . $expected_file);
385         else
386             require($expected_file);
387
388         if($view == 'list')
389             $expectedResults = $listViewDefs[$module];
390         else
391             $expectedResults = $viewdefs[$module][ucfirst($view) .'View' ];
392
393         $a_expectedResults = array();
394         $a_expectedResults[$module][$type][$view] = $expectedResults;
395
396         $this->assertEquals(md5(serialize($expectedResults)), $result[$module][$type][$view], "Unable to retrieve module layout md5: module {$module}, type $type, view $view");
397
398     }
399
400     public function testGetAvailableModules()
401     {
402         $this->markTestSkipped('Will be updated week of June 21, 2010');
403
404         $result = $this->_login();
405         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
406         $session = $result['id'];
407
408         $fullResult = $this->_makeRESTCall('get_available_modules', array('session' => $session, 'filter' => 'all' ));
409         $this->assertTrue(in_array('ACLFields', $fullResult['modules']), "Unable to get all available modules");
410         $this->assertTrue(in_array('Schedulers', $fullResult['modules']), "Unable to get all available modules");
411         $this->assertTrue(in_array('Roles', $fullResult['modules']), "Unable to get all available modules");
412
413         $sh = new SugarWebServiceUtilv3();
414
415         $mobileResult = $this->_makeRESTCall('get_available_modules', array('session' => $session, 'filter' => 'mobile' ));
416         $mobileResultExpected = $sh->get_visible_mobile_modules($fullResult['modules']);
417         $mobileResultExpected = md5(serialize(array('modules' => $mobileResultExpected)));
418         $mobileResult = md5(serialize($mobileResult));
419         $this->assertEquals($mobileResultExpected, $mobileResult, "Unable to get all visible mobile modules");
420
421         $defaultResult = $this->_makeRESTCall('get_available_modules', array('session' => $session, 'filter' => 'default' ));
422         $defaultResult = md5(serialize($defaultResult['modules']));
423         $defaultResultExpected = $sh->get_visible_modules($fullResult['modules']);
424         $defaultResultExpected = md5(serialize($defaultResultExpected));
425         $this->assertEquals($defaultResultExpected, $defaultResult, "Unable to get all visible default modules");
426
427     }
428
429     public function testGetVardefsMD5()
430     {
431         $GLOBALS['reload_vardefs'] = TRUE;
432         $result = $this->_login();
433         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
434         $session = $result['id'];
435
436         //Test a regular module
437         $fullResult = $this->_makeRESTCall('get_module_fields_md5', array('session' => $session, 'module' => 'Accounts' ));
438         $result = $fullResult['Accounts'];
439         $a = new Account();
440         $soapHelper = new SugarWebServiceUtilv3();
441         $actualVardef = $soapHelper->get_return_module_fields($a,'Accounts','');
442         $actualMD5 = md5(serialize($actualVardef));
443         $this->assertEquals($actualMD5, $result, "Unable to retrieve vardef md5.");
444
445         //Test a fake module
446         $result = $this->_makeRESTCall('get_module_fields_md5', array('session' => $session, 'module' => 'BadModule' ));
447         $this->assertTrue($result['name'] == 'Module Does Not Exist');
448         unset($GLOBALS['reload_vardefs']);
449     }
450
451     public function testAddNewAccountAndThenDeleteIt()
452     {
453         $result = $this->_login();
454         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
455         $session = $result['id'];
456
457         $result = $this->_makeRESTCall('set_entry',
458             array(
459                 'session' => $session,
460                 'module' => 'Accounts',
461                 'name_value_list' => array(
462                     array('name' => 'name', 'value' => 'New Account'),
463                     array('name' => 'description', 'value' => 'This is an account created from a REST web services call'),
464                     ),
465                 )
466             );
467
468         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
469
470         $accountId = $result['id'];
471
472         // verify record was created
473         $result = $this->_makeRESTCall('get_entry',
474             array(
475                 'session' => $session,
476                 'module' => 'Accounts',
477                 'id' => $accountId,
478                 )
479             );
480
481         $this->assertEquals($result['entry_list'][0]['id'],$accountId,$this->_returnLastRawResponse());
482
483         // delete the record
484         $result = $this->_makeRESTCall('set_entry',
485             array(
486                 'session' => $session,
487                 'module' => 'Accounts',
488                 'name_value_list' => array(
489                     array('name' => 'id', 'value' => $accountId),
490                     array('name' => 'deleted', 'value' => '1'),
491                     ),
492                 )
493             );
494
495         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
496
497         // try to retrieve again to validate it is deleted
498         $result = $this->_makeRESTCall('get_entry',
499             array(
500                 'session' => $session,
501                 'module' => 'Accounts',
502                 'id' => $accountId,
503                 )
504             );
505
506         $GLOBALS['db']->query("DELETE FROM accounts WHERE id= '{$accountId}'");
507         
508         $this->assertTrue(!empty($result['entry_list'][0]['id']) && $result['entry_list'][0]['id'] != -1,$this->_returnLastRawResponse());
509         $this->assertEquals($result['entry_list'][0]['name_value_list'][0]['name'],'warning',$this->_returnLastRawResponse());
510         $this->assertEquals($result['entry_list'][0]['name_value_list'][0]['value'],"Access to this object is denied since it has been deleted or does not exist",$this->_returnLastRawResponse());
511         $this->assertEquals($result['entry_list'][0]['name_value_list'][1]['name'],'deleted',$this->_returnLastRawResponse());
512         $this->assertEquals($result['entry_list'][0]['name_value_list'][1]['value'],1,$this->_returnLastRawResponse());
513     }
514
515     public function testRelateAccountToTwoContacts()
516     {
517         $result = $this->_login();
518         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
519         $session = $result['id'];
520
521         $result = $this->_makeRESTCall('set_entry',
522             array(
523                 'session' => $session,
524                 'module' => 'Accounts',
525                 'name_value_list' => array(
526                     array('name' => 'name', 'value' => 'New Account'),
527                     array('name' => 'description', 'value' => 'This is an account created from a REST web services call'),
528                     ),
529                 )
530             );
531
532         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
533
534         $accountId = $result['id'];
535
536         $result = $this->_makeRESTCall('set_entry',
537             array(
538                 'session' => $session,
539                 'module' => 'Contacts',
540                 'name_value_list' => array(
541                     array('name' => 'last_name', 'value' => 'New Contact 1'),
542                     array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'),
543                     ),
544                 )
545             );
546
547         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
548
549         $contactId1 = $result['id'];
550
551         $result = $this->_makeRESTCall('set_entry',
552             array(
553                 'session' => $session,
554                 'module' => 'Contacts',
555                 'name_value_list' => array(
556                     array('name' => 'last_name', 'value' => 'New Contact 2'),
557                     array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'),
558                     ),
559                 )
560             );
561
562         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
563
564         $contactId2 = $result['id'];
565
566         // now relate them together
567         $result = $this->_makeRESTCall('set_relationship',
568             array(
569                 'session' => $session,
570                 'module' => 'Accounts',
571                 'module_id' => $accountId,
572                 'link_field_name' => 'contacts',
573                 'related_ids' => array($contactId1,$contactId2),
574                 )
575             );
576
577         $this->assertEquals($result['created'],1,$this->_returnLastRawResponse());
578
579         // check the relationship
580         $result = $this->_makeRESTCall('get_relationships',
581             array(
582                 'session' => $session,
583                 'module' => 'Accounts',
584                 'module_id' => $accountId,
585                 'link_field_name' => 'contacts',
586                 'related_module_query' => '',
587                 'related_fields' => array('last_name','description'),
588                 'related_module_link_name_to_fields_array' => array(),
589                 'deleted' => false,
590                 )
591             );
592
593         $returnedValues = array();
594         $returnedValues[] = $result['entry_list'][0]['name_value_list']['last_name']['value'];
595         $returnedValues[] = $result['entry_list'][1]['name_value_list']['last_name']['value'];
596
597         $GLOBALS['db']->query("DELETE FROM accounts WHERE id= '{$accountId}'");
598         $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$contactId1}'");
599         $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$contactId2}'");
600         $GLOBALS['db']->query("DELETE FROM accounts_contacts WHERE account_id= '{$accountId}'");
601
602         $this->assertContains('New Contact 1',$returnedValues,$this->_returnLastRawResponse());
603         $this->assertContains('New Contact 2',$returnedValues,$this->_returnLastRawResponse());
604     }
605
606     /**
607      * @ticket 36658
608      */
609     public function testOrderByClauseOfGetRelationship()
610     {
611         $result = $this->_login();
612         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
613         $session = $result['id'];
614
615         $result = $this->_makeRESTCall('set_entry',
616             array(
617                 'session' => $session,
618                 'module' => 'Accounts',
619                 'name_value_list' => array(
620                     array('name' => 'name', 'value' => 'New Account'),
621                     array('name' => 'description', 'value' => 'This is an account created from a REST web services call'),
622                     ),
623                 )
624             );
625
626         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
627
628         $accountId = $result['id'];
629
630         $result = $this->_makeRESTCall('set_entry',
631             array(
632                 'session' => $session,
633                 'module' => 'Contacts',
634                 'name_value_list' => array(
635                     array('name' => 'last_name', 'value' => 'New Contact 1'),
636                     array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'),
637                     ),
638                 )
639             );
640
641         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
642
643         $contactId1 = $result['id'];
644
645         $result = $this->_makeRESTCall('set_entry',
646             array(
647                 'session' => $session,
648                 'module' => 'Contacts',
649                 'name_value_list' => array(
650                     array('name' => 'last_name', 'value' => 'New Contact 3'),
651                     array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'),
652                     ),
653                 )
654             );
655
656         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
657         $contactId3 = $result['id'];
658
659         $result = $this->_makeRESTCall('set_entry',
660             array(
661                 'session' => $session,
662                 'module' => 'Contacts',
663                 'name_value_list' => array(
664                     array('name' => 'last_name', 'value' => 'New Contact 2'),
665                     array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'),
666                     ),
667                 )
668             );
669
670         $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
671
672         $contactId2 = $result['id'];
673
674         // now relate them together
675         $result = $this->_makeRESTCall('set_relationship',
676             array(
677                 'session' => $session,
678                 'module' => 'Accounts',
679                 'module_id' => $accountId,
680                 'link_field_name' => 'contacts',
681                 'related_ids' => array($contactId1,$contactId3,$contactId2),
682                 )
683             );
684
685         $this->assertEquals($result['created'],1,$this->_returnLastRawResponse());
686
687         // check the relationship
688         $result = $this->_makeRESTCall('get_relationships',
689             array(
690                 'session' => $session,
691                 'module' => 'Accounts',
692                 'module_id' => $accountId,
693                 'link_field_name' => 'contacts',
694                 'related_module_query' => '',
695                 'related_fields' => array('last_name','description'),
696                 'related_module_link_name_to_fields_array' => array(),
697                 'deleted' => false,
698                 'order_by' => 'last_name',
699                 )
700             );
701
702         $GLOBALS['db']->query("DELETE FROM accounts WHERE id= '{$accountId}'");
703         $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$contactId1}'");
704         $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$contactId2}'");
705         $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$contactId3}'");
706         $GLOBALS['db']->query("DELETE FROM accounts_contacts WHERE account_id= '{$accountId}'");
707
708         $this->assertEquals($result['entry_list'][0]['name_value_list']['last_name']['value'],'New Contact 1',$this->_returnLastRawResponse());
709         $this->assertEquals($result['entry_list'][1]['name_value_list']['last_name']['value'],'New Contact 2',$this->_returnLastRawResponse());
710         $this->assertEquals($result['entry_list'][2]['name_value_list']['last_name']['value'],'New Contact 3',$this->_returnLastRawResponse());
711     }
712
713     public static function _subpanelLayoutProvider()
714     {
715         return array(
716             array(
717                 'module' => 'Contacts',
718                 'type' => 'default',
719                 'view' => 'subpanel',
720             ),
721             array(
722                 'module' => 'Leads',
723                 'type' => 'wireless',
724                 'view' => 'subpanel',
725             ),
726         );
727     }
728
729     /**
730      * @dataProvider _subpanelLayoutProvider
731      */
732     public function testGetSubpanelLayout($module, $type, $view)
733     {
734         $result = $this->_login();
735         $session = $result['id'];
736
737         $results = $this->_makeRESTCall('get_module_layout',
738             array(
739                 'session' => $session,
740                 'module' => array($module),
741                 'type' => array($type),
742                 'view' => array($view))
743         );
744
745         $this->assertTrue(isset($results[$module][$type][$view]), "Unable to get subpanel defs");
746     }
747      public function testGetUpcomingActivities()
748      {
749          $expected = $this->_createUpcomingActivities(); //Seed the data.
750
751          $result = $this->_login(); // Logging in just before the REST call as this will also commit any pending DB changes
752          $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse());
753          $session = $result['id'];
754          $results = $this->_makeRESTCall('get_upcoming_activities',
755                              array(
756                              'session' => $session,
757                              )
758          );
759
760          $this->assertEquals($expected[0] ,$results[0]['id'] , "Unable to get upcoming activities");
761          $this->assertEquals($expected[1] ,$results[1]['id'] , "Unable to get upcoming activities");
762
763          $this->_removeUpcomingActivities();
764      }
765
766      private function _removeUpcomingActivities()
767      {
768          $GLOBALS['db']->query("DELETE FROM calls where name = 'UNIT TEST'");
769          $GLOBALS['db']->query("DELETE FROM tasks where name = 'UNIT TEST'");
770      }
771
772      private function _createUpcomingActivities()
773      {
774          $GLOBALS['current_user']->setPreference('datef','Y-m-d') ;
775          $GLOBALS['current_user']->setPreference('timef','H:i') ;
776
777          $date1 = $GLOBALS['timedate']->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() + (3600 * 24 * 2) ) ),true,true, $GLOBALS['current_user']) ; //Two days from today
778          $date2 = $GLOBALS['timedate']->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() + (3600 * 24 * 4) ) ),true,true, $GLOBALS['current_user']) ; //Two days from today
779
780          $callID = uniqid();
781          $c = new Call();
782          $c->id = $callID;
783          $c->new_with_id = TRUE;
784          $c->status = 'Not Planned';
785          $c->date_start = $date1;
786          $c->name = "UNIT TEST";
787          $c->assigned_user_id = $this->_user->id;
788          $c->save(FALSE);
789
790          $callID = uniqid();
791          $c = new Call();
792          $c->id = $callID;
793          $c->new_with_id = TRUE;
794          $c->status = 'Planned';
795          $c->date_start = $date1;
796          $c->name = "UNIT TEST";
797          $c->assigned_user_id = $this->_user->id;
798          $c->save(FALSE);
799
800          $taskID = uniqid();
801          $t = new Task();
802          $t->id = $taskID;
803          $t->new_with_id = TRUE;
804          $t->status = 'Not Started';
805          $t->date_due = $date2;
806          $t->name = "UNIT TEST";
807          $t->assigned_user_id = $this->_user->id;
808          $t->save(FALSE);
809
810          return array($callID, $taskID);
811      }
812 }