]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - tests/service/SOAPAPI3Test.php
Added unit tests.
[Github/sugarcrm.git] / tests / service / SOAPAPI3Test.php
1 <?php
2 require_once('include/nusoap/nusoap.php');
3 require_once('include/TimeDate.php');
4 require_once('service/v3/SugarWebServiceUtilv3.php');
5 require_once('tests/service/APIv3Helper.php');
6
7 /**
8  * This class is meant to test everything SOAP
9  *
10  */
11 class SOAPAPI3Test extends Sugar_PHPUnit_Framework_TestCase
12 {
13         public $_user = null;
14         public $_soapClient = null;
15         public $_session = null;
16         public $_sessionId = '';
17     public $_contactId = '';
18     private static $helperObject;
19         
20     /**
21      * Create test user
22      *
23      */
24         public function setUp() 
25     {
26         $this->_soapClient = new nusoapclient($GLOBALS['sugar_config']['site_url'].'/service/v3/soap.php',false,false,false,false,false,600,600);
27         $this->_setupTestUser();
28         $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
29         $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
30         
31         self::$helperObject = new APIv3Helper();
32     }
33
34     /**
35      * Remove anything that was used during this test
36      *
37      */
38     public function tearDown() {
39         global $soap_version_test_accountId, $soap_version_test_opportunityId, $soap_version_test_contactId;
40         $this->_tearDownTestUser();
41         $this->_user = null;
42         $this->_sessionId = '';
43         unset($soap_version_test_accountId);
44         unset($soap_version_test_opportunityId);
45         unset($soap_version_test_contactId);
46     }
47
48         /**
49          * Ensure we can create a session on the server.
50          *
51          */
52     public function testCanLogin(){
53                 $result = $this->_login();
54         $this->assertTrue(!empty($result['id']) && $result['id'] != -1, 
55             'SOAP Session not created. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail);
56     }
57
58     public function testSearchByModule()
59     {
60         $this->_login();
61
62         $seedData = self::$helperObject->populateSeedDataForSearchTest($this->_user->id);
63         
64         $searchModules = array('Accounts','Contacts','Opportunities');
65         $searchString = "UNIT TEST";
66         $offSet = 0;
67         $maxResults = 10;
68
69         $results = $this->_soapClient->call('search_by_module',
70                         array(
71                             'session' => $this->_sessionId,
72                             'search'  => $searchString,
73                             'modules' => $searchModules,
74                             'offset'  => $offSet,
75                             'max'     => $maxResults,
76                             'user'    => $this->_user->id)
77                         );
78             
79         $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[0]['id'],'Accounts') );  
80         $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[1]['id'],'Accounts') ); 
81         $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[2]['id'],'Contacts') ); 
82         $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[3]['id'],'Opportunities') ); 
83         $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[4]['id'],'Opportunities') );  
84         $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'UNIT TEST%' ");
85         $GLOBALS['db']->query("DELETE FROM opportunities WHERE name like 'UNIT TEST%' ");
86         $GLOBALS['db']->query("DELETE FROM contacts WHERE first_name like 'UNIT TEST%' ");
87     }
88     
89     public function testSearchByModuleWithReturnFields()
90     {
91         $this->_login();
92
93         $seedData = self::$helperObject->populateSeedDataForSearchTest($this->_user->id);
94         
95         $returnFields = array('name','id','deleted');
96         $searchModules = array('Accounts','Contacts','Opportunities');
97         $searchString = "UNIT TEST";
98         $offSet = 0;
99         $maxResults = 10;
100
101         $results = $this->_soapClient->call('search_by_module',
102                         array(
103                             'session' => $this->_sessionId,
104                             'search'  => $searchString,
105                             'modules' => $searchModules,
106                             'offset'  => $offSet,
107                             'max'     => $maxResults,
108                             'user'    => $this->_user->id,
109                             'fields'  => $returnFields)
110                         );
111             
112         $this->assertEquals($seedData[0]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[0]['id'],'Accounts', $seedData[0]['fieldName']));
113         $this->assertFalse(self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[1]['id'],'Accounts', $seedData[1]['fieldName']));
114         $this->assertEquals($seedData[2]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[2]['id'],'Contacts', $seedData[2]['fieldName']));
115         $this->assertEquals($seedData[3]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[3]['id'],'Opportunities', $seedData[3]['fieldName']));
116         $this->assertFalse(self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[4]['id'],'Opportunities', $seedData[4]['fieldName']));
117         
118         $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'UNIT TEST%' ");
119         $GLOBALS['db']->query("DELETE FROM opportunities WHERE name like 'UNIT TEST%' ");
120         $GLOBALS['db']->query("DELETE FROM contacts WHERE first_name like 'UNIT TEST%' ");
121     }
122     
123     public function testGetVardefsMD5()
124     {   
125         $GLOBALS['reload_vardefs'] = TRUE;
126         //Test a regular module
127         $result = $this->_getVardefsMD5('Accounts');
128         $a = new Account();
129         $soapHelper = new SugarWebServiceUtilv3();
130         $actualVardef = $soapHelper->get_return_module_fields($a,'Accounts','');
131         $actualMD5 = md5(serialize($actualVardef));
132         $this->assertEquals($actualMD5, $result, "Unable to retrieve vardef md5.");
133         
134         //Test a fake module
135         $result = $this->_getVardefsMD5('BadModule');
136         $this->assertTrue($result['faultstring'] == 'Module Does Not Exist');
137         unset($GLOBALS['reload_vardefs']);
138     }     
139
140     public function testGetUpcomingActivities()
141     {
142          $this->_login();
143          $expected = $this->_createUpcomingActivities(); //Seed the data.
144          $results = $this->_soapClient->call('get_upcoming_activities',array('session'=>$this->_sessionId));
145          
146          $this->assertEquals($expected[0] ,$results[0]['id'] , 'Unable to get upcoming activities Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail);
147          $this->assertEquals($expected[1] ,$results[1]['id'] , 'Unable to get upcoming activities Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail);
148          
149          $this->_removeUpcomingActivities();
150     }
151
152     public function testGetLastViewed()
153     {
154          $testModule = 'Accounts';
155          $testModuleID = uniqid();
156
157          $this->_createTrackerEntry($testModule,$testModuleID);
158
159          $this->_login();
160                  $results = $this->_soapClient->call('get_last_viewed',array('session'=>$this->_sessionId,'module_names'=> array($testModule) ));
161          
162                  $found = FALSE;
163          foreach ($results as $entry)
164          {
165              if($entry['item_id'] == $testModuleID)
166              {
167                  $found = TRUE;
168                  break;
169              }
170          }
171
172          $this->assertTrue($found, "Unable to get last viewed modules");
173      }
174
175      private function _createTrackerEntry($module, $id,$summaryText = "UNIT TEST SUMMARY")
176      {
177         $trackerManager = TrackerManager::getInstance();
178         $timeStamp = gmdate($GLOBALS['timedate']->get_db_date_time_format());
179         $monitor = $trackerManager->getMonitor('tracker');
180         $monitor->setValue('action', 'detail');
181         $monitor->setValue('user_id', $this->_user->id);
182         $monitor->setValue('module_name', $module);
183         $monitor->setValue('date_modified', $timeStamp);
184         $monitor->setValue('visible', true);
185         $monitor->setValue('item_id', $id);
186         $monitor->setValue('item_summary', $summaryText);
187         $trackerManager->saveMonitor($monitor, true, true);
188      }
189     
190    
191     /**
192      * Get Module Layout functions not exposed to soap service, make sure they are not available.
193      *
194      */
195     public function testGetModuleLayoutMD5()
196     {
197         $result = $this->_getModuleLayoutMD5();
198         $this->assertContains('Client',$result['faultcode']);
199         
200     }
201     
202     public function testSetEntriesForAccount() {
203         $result = $this->_setEntriesForAccount();
204         $this->assertTrue(!empty($result['ids']) && $result['ids'][0] != -1, 
205             'Can not create new account using testSetEntriesForAccount. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail);
206     } // fn
207     
208     /**********************************
209      * HELPER PUBLIC FUNCTIONS
210      **********************************/
211     private function _removeUpcomingActivities()
212     {
213         $GLOBALS['db']->query("DELETE FROM calls where name = 'UNIT TEST'");
214         $GLOBALS['db']->query("DELETE FROM tasks where name = 'UNIT TEST'");
215     }
216
217     private function _createUpcomingActivities()
218     {
219         $GLOBALS['current_user']->setPreference('datef','Y-m-d') ;
220         $GLOBALS['current_user']->setPreference('timef','H:i') ;
221
222         $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
223         $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
224
225         $callID = uniqid();
226         $c = new Call();
227         $c->id = $callID;
228         $c->new_with_id = TRUE;
229         $c->status = 'Not Planned';
230         $c->date_start = $date1;
231         $c->name = "UNIT TEST";
232         $c->assigned_user_id = $this->_user->id;
233         $c->save(FALSE);
234         
235         $callID = uniqid();
236         $c = new Call();
237         $c->id = $callID;
238         $c->new_with_id = TRUE;
239         $c->status = 'Planned';
240         $c->date_start = $date1;
241         $c->name = "UNIT TEST";
242         $c->assigned_user_id = $this->_user->id;
243         $c->save(FALSE);
244
245         $taskID = uniqid();
246         $t = new Task();
247         $t->id = $taskID;
248         $t->new_with_id = TRUE;
249         $t->status = 'Not Started';
250         $t->date_due = $date2;
251         $t->name = "UNIT TEST";
252         $t->assigned_user_id = $this->_user->id;
253         $t->save(FALSE);
254
255         return array($callID, $taskID);
256     }
257      
258     /**
259      * Attempt to login to the soap server
260      *
261      * @return $set_entry_result - this should contain an id and error.  The id corresponds
262      * to the session_id.
263      */
264     public function _login(){
265                 global $current_user;   
266         $result = $this->_soapClient->call('login',
267             array('user_auth' => 
268                 array('user_name' => $current_user->user_name,
269                     'password' => $current_user->user_hash, 
270                     'version' => '.01'), 
271                 'application_name' => 'SoapTest')
272             );
273            
274         $this->_sessionId = $result['id'];
275                 return $result;
276     }
277     
278     public function _getVardefsMD5($module)
279     {
280         $this->_login();
281                 $result = $this->_soapClient->call('get_module_fields_md5',array('session'=>$this->_sessionId,'module'=> array($module) ));
282                 if(isset($result[0]))
283                   return $result[0]; 
284                 else 
285                   return $result;
286     }
287     
288     public function _getModuleLayoutMD5()
289     {
290         $this->_login();
291                 $result = $this->_soapClient->call('get_module_layout_md5',
292                               array('session'=>$this->_sessionId,'module_names'=> array('Accounts'),'types' => array('default'),'views' => array('list')));
293                 if(isset($result['md5']))
294                   return $result['md5']; 
295                 else 
296                   return $result; 
297     }
298     
299     public function _setEntryForContact() {
300                 $this->_login();
301                 global $timedate;
302                 $current_date = $timedate->convert_to_gmt_datetime('now');
303         $time = mt_rand();
304         $first_name = 'SugarContactFirst' . $time;
305         $last_name = 'SugarContactLast';
306         $email1 = 'contact@sugar.com';
307                 $result = $this->_soapClient->call('set_entry',array('session'=>$this->_sessionId,'module_name'=>'Contacts', 'name_value_list'=>array(array('name'=>'last_name' , 'value'=>"$last_name"), array('name'=>'first_name' , 'value'=>"$first_name"), array('name'=>'do_not_call' , 'value'=>"1"), array('name'=>'birthdate' , 'value'=>"$current_date"), array('name'=>'lead_source' , 'value'=>"Cold Call"), array('name'=>'email1' , 'value'=>"$email1"))));
308                 SugarTestContactUtilities::setCreatedContact(array($this->_contactId));
309                 return $result;
310     } // fn
311     
312     public function _getEntryForContact() {
313         global $soap_version_test_contactId;
314                 $this->_login();
315                 $result = $this->_soapClient->call('get_entry',array('session'=>$this->_sessionId,'module_name'=>'Contacts','id'=>$soap_version_test_contactId,'select_fields'=>array('last_name', 'first_name', 'do_not_call', 'lead_source'), 'link_name_to_fields_array' => array(array('name' =>  'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address')))));
316                 $GLOBALS['log']->fatal("_getEntryForContact" . " " . $soap_version_test_contactId);
317                 return $result;
318     }
319         
320     public function _setEntriesForAccount() {
321         global $soap_version_test_accountId;
322                 $this->_login();
323                 global $timedate;
324                 $current_date = $timedate->convert_to_gmt_datetime('now');
325         $time = mt_rand();
326         $name = 'SugarAccount' . $time;
327         $email1 = 'account@'. $time. 'sugar.com';
328                 $result = $this->_soapClient->call('set_entries',array('session'=>$this->_sessionId,'module_name'=>'Accounts', 'name_value_lists'=>array(array(array('name'=>'name' , 'value'=>"$name"), array('name'=>'email1' , 'value'=>"$email1")))));
329                 $soap_version_test_accountId = $result['ids'][0];
330                 $GLOBALS['log']->fatal("_setEntriesForAccount id = " . $soap_version_test_accountId);
331                 SugarTestAccountUtilities::setCreatedAccount(array($soap_version_test_accountId));
332                 return $result;
333     } // fn
334
335     public function _setEntryForOpportunity() {
336         global $soap_version_test_accountId, $soap_version_test_opportunityId;
337                 $this->_login();
338                 global $timedate;
339                 $date_closed = $timedate->convert_to_gmt_datetime(strtotime('+1 week'));
340         $time = mt_rand();
341         $name = 'SugarOpportunity' . $time;
342         $account_id = $soap_version_test_accountId;
343         $sales_stage = 'Prospecting';
344         $probability = 10;
345         $amount = 1000;
346                 $GLOBALS['log']->fatal("_setEntryForOpportunity id = " . $soap_version_test_accountId);
347                 $result = $this->_soapClient->call('set_entry',array('session'=>$this->_sessionId,'module_name'=>'Opportunities', 'name_value_lists'=>array(array('name'=>'name' , 'value'=>"$name"), array('name'=>'amount' , 'value'=>"$amount"), array('name'=>'probability' , 'value'=>"$probability"), array('name'=>'sales_stage' , 'value'=>"$sales_stage"), array('name'=>'account_id' , 'value'=>"$account_id"))));
348                 $soap_version_test_opportunityId = $result['id'];
349                 return $result;
350     } // fn
351     
352     public function _setRelationshipForOpportunity() {
353         global $soap_version_test_contactId, $soap_version_test_opportunityId;
354                 $this->_login();
355                 $result = $this->_soapClient->call('set_relationship',array('session'=>$this->_sessionId,'module_name' => 'Opportunities','module_id' => "$soap_version_test_opportunityId", 'link_field_name' => 'contacts','related_ids' =>array("$soap_version_test_contactId"), 'name_value_list' => array(array('name' => 'contact_role', 'value' => 'testrole'))));
356                 return $result;         
357     } // fn
358     
359     public function _getRelationshipForOpportunity() {
360         global $soap_version_test_opportunityId;
361                 $this->_login();
362                 $result = $this->_soapClient->call('get_relationships',
363                                 array(
364                 'session' => $this->_sessionId,
365                 'module_name' => 'Opportunities',
366                 'module_id' => "$soap_version_test_opportunityId",
367                 'link_field_name' => 'contacts',
368                 'related_module_query' => '',
369                 'related_fields' => array('id'),
370                 'related_module_link_name_to_fields_array' => array(array('name' =>  'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address'))))
371             );
372                 return $result;         
373     } // fn
374     
375     public function _searchByModule() {
376                 $this->_login();
377                 $result = $this->_soapClient->call('search_by_module',
378                                 array(
379                 'session' => $this->_sessionId,
380                 'search_string' => 'Sugar',
381                                 'modules' => array('Accounts', 'Contacts', 'Opportunities'),
382                 'offset' => '0',
383                 'max_results' => '10')
384             );
385             
386                 return $result;         
387     } // fn
388     
389     /**
390      * Create a test user
391      *
392      */
393         public function _setupTestUser() {
394         $this->_user = SugarTestUserUtilities::createAnonymousUser();
395         $this->_user->status = 'Active';
396         $this->_user->is_admin = 1;
397         $this->_user->save();
398         $GLOBALS['current_user'] = $this->_user;
399     }
400         
401     /**
402      * Remove user created for test
403      *
404      */
405         public function _tearDownTestUser() {
406        SugarTestUserUtilities::removeAllCreatedAnonymousUsers();
407        unset($GLOBALS['current_user']);
408     }
409 }
410 ?>