RestAPIContactTest.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. /* Copyright (C) 2010 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2023 Alexandre Janniaux <alexandre.janniaux@gmail.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. * or see https://www.gnu.org/
  18. */
  19. /**
  20. * \file test/phpunit/RestAPIUserTest.php
  21. * \ingroup test
  22. * \brief PHPUnit test
  23. * \remarks To run this script as CLI: phpunit filename.php
  24. */
  25. global $conf,$user,$langs,$db;
  26. //define('TEST_DB_FORCE_TYPE','mysql'); // This is to force using mysql driver
  27. //require_once 'PHPUnit/Autoload.php';
  28. require_once dirname(__FILE__).'/../../htdocs/master.inc.php';
  29. require_once dirname(__FILE__).'/../../htdocs/core/lib/date.lib.php';
  30. require_once dirname(__FILE__).'/../../htdocs/core/lib/geturl.lib.php';
  31. if (empty($user->id)) {
  32. print "Load permissions for admin user nb 1\n";
  33. $user->fetch(1);
  34. $user->getrights();
  35. }
  36. $conf->global->MAIN_DISABLE_ALL_MAILS=1;
  37. $conf->global->MAIN_UMASK='0666';
  38. /**
  39. * Class for PHPUnit tests
  40. *
  41. * @backupGlobals disabled
  42. * @backupStaticAttributes enabled
  43. * @remarks backupGlobals must be disabled to have db,conf,user and lang not erased.
  44. */
  45. class RestAPIContactTest extends PHPUnit\Framework\TestCase
  46. {
  47. protected $savconf;
  48. protected $savuser;
  49. protected $savlangs;
  50. protected $savdb;
  51. protected $api_url;
  52. protected $api_key;
  53. /**
  54. * Constructor
  55. * We save global variables into local variables
  56. *
  57. * @param string $name Name
  58. * @return RestAPIContactTest
  59. */
  60. public function __construct($name = '')
  61. {
  62. parent::__construct($name);
  63. //$this->sharedFixture
  64. global $conf,$user,$langs,$db;
  65. $this->savconf=$conf;
  66. $this->savuser=$user;
  67. $this->savlangs=$langs;
  68. $this->savdb=$db;
  69. if (!isModEnabled('api')) {
  70. print __METHOD__." module api must be enabled.\n";
  71. die(1);
  72. }
  73. print __METHOD__." db->type=".$db->type." user->id=".$user->id;
  74. //print " - db ".$db->db;
  75. print "\n";
  76. }
  77. /**
  78. * setUpBeforeClass
  79. *
  80. * @return void
  81. */
  82. public static function setUpBeforeClass(): void
  83. {
  84. global $conf,$user,$langs,$db;
  85. $db->begin(); // This is to have all actions inside a transaction even if test launched without suite.
  86. print __METHOD__."\n";
  87. }
  88. /**
  89. * tearDownAfterClass
  90. *
  91. * @return void
  92. */
  93. public static function tearDownAfterClass(): void
  94. {
  95. global $conf,$user,$langs,$db;
  96. $db->rollback();
  97. print __METHOD__."\n";
  98. }
  99. /**
  100. * Init phpunit tests
  101. *
  102. * @return void
  103. */
  104. protected function setUp(): void
  105. {
  106. global $conf,$user,$langs,$db;
  107. $conf=$this->savconf;
  108. $user=$this->savuser;
  109. $langs=$this->savlangs;
  110. $db=$this->savdb;
  111. $this->api_url = DOL_MAIN_URL_ROOT.'/api/index.php';
  112. $login='admin';
  113. $password='admin';
  114. $url=$this->api_url.'/login?login='.$login.'&password='.$password;
  115. // Call the API login method to save api_key for this test class.
  116. // At first call, if token is not defined a random value is generated and returned.
  117. $result=getURLContent($url, 'GET', '', 1, array(), array('http', 'https'), 2);
  118. print __METHOD__." result = ".var_export($result, true)."\n";
  119. print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n";
  120. $this->assertEquals($result['curl_error_no'], '');
  121. $object = json_decode($result['content'], true); // If success content is just an id, if not an array
  122. $this->assertNotNull($object, "Parsing of json result must not be null");
  123. $this->assertNotEquals(500, (empty($object['error']['code']) ? 0 : $object['error']['code']), 'Error'.(empty($object['error']['message']) ? '' : ' '.$object['error']['message']));
  124. $this->assertEquals('200', $object['success']['code']);
  125. $this->api_key = $object['success']['token'];
  126. print __METHOD__." api_key: $this->api_key \n";
  127. }
  128. /**
  129. * End phpunit tests
  130. *
  131. * @return void
  132. */
  133. protected function tearDown(): void
  134. {
  135. print __METHOD__."\n";
  136. }
  137. /**
  138. * testRestGetContact
  139. *
  140. * @return int
  141. */
  142. public function testRestGetContact()
  143. {
  144. global $conf,$user,$langs,$db;
  145. //fetch Non-Existent contact
  146. $url = $this->api_url.'/contacts/123456789?api_key='.$this->api_key;
  147. //$addheaders=array('Content-Type: application/json');
  148. print __METHOD__." Request GET url=".$url."\n";
  149. $result = getURLContent($url, 'GET', '', 1, array(), array('http', 'https'), 2);
  150. print __METHOD__." result for get on unexisting contact: ".var_export($result, true)."\n";
  151. print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n";
  152. $this->assertEquals($result['curl_error_no'], '');
  153. $object=json_decode($result['content'], true);
  154. $this->assertNotNull($object, "Parsing of json result must not be null");
  155. $this->assertEquals(404, $object['error']['code'], 'Error code is not 404');
  156. //fetch an existent contact
  157. $url = $this->api_url.'/contacts/1?api_key='.$this->api_key;
  158. print __METHOD__." Request GET url=".$url."\n";
  159. $result=getURLContent($url, 'GET', '', 1, array(), array('http', 'https'), 2);
  160. print __METHOD__." result for get on an existing contact: ".var_export($result, true)."\n";
  161. print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n";
  162. $this->assertEquals($result['curl_error_no'], '');
  163. $object=json_decode($result['content'], true);
  164. $this->assertNotNull($object, "Parsing of json result must not be null");
  165. $this->assertEquals(1, $object['statut']);
  166. }
  167. /**
  168. * testRestCreateContact
  169. *
  170. * @return int
  171. *
  172. * @depends testRestGetContact
  173. * The depends says test is run only if previous is ok
  174. */
  175. public function testRestCreateContact()
  176. {
  177. global $conf,$user,$langs,$db;
  178. // attempt to create without mandatory fields
  179. $url = $this->api_url.'/contacts?api_key='.$this->api_key;
  180. $addheaders=array('Content-Type: application/json');
  181. $bodyobj= array(
  182. "firstname" => "firstname"
  183. );
  184. $body = json_encode($bodyobj);
  185. //print __METHOD__." Request POST url=".$url."\n";
  186. $result=getURLContent($url, 'POST', $body, 1, $addheaders, array('http', 'https'), 2);
  187. //print __METHOD__." Result for creating incomplete contact".var_export($result, true)."\n";
  188. //print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n";
  189. $this->assertEquals($result['curl_error_no'], '');
  190. $object = json_decode($result['content'], true); // If success content is just an id, if not an array
  191. $this->assertNotNull($object, "Parsing of json result must no be null");
  192. $this->assertEquals(400, (empty($object['error']['code']) ? 0 : $object['error']['code']), 'Error'.(empty($object['error']['message']) ? '' : ' '.$object['error']['message']));
  193. $idofcontactcreated = (int) $object;
  194. // create regular contact
  195. unset($result);
  196. // Creating a Contact
  197. $bodyobj = array(
  198. "firstname" => "testRestContact" . mt_rand(),
  199. "lastname" => "testRestContact",
  200. );
  201. $body = json_encode($bodyobj);
  202. $result = getURLContent($url, 'POST', $body, 1, $addheaders, array('http', 'https'), 2);
  203. $this->assertEquals($result['curl_error_no'], '');
  204. $object = json_decode($result['content'], true); // If success content is just an id, if not an array
  205. $this->assertNotNull($object, "Parsing of json result must not be null");
  206. $this->assertNotEquals(500, (empty($object['error']['code']) ? 0 : $object['error']['code']), 'Error'.(empty($object['error']['message']) ? '' : ' '.$object['error']['message']));
  207. $this->assertGreaterThan(0, $object, 'ID return is no > 0');
  208. return $idofcontactcreated;
  209. }
  210. /**
  211. * testRestUpdateContact
  212. *
  213. * @param int $objid Id of object created at previous test
  214. * @return int
  215. *
  216. * @depends testRestCreateContact
  217. * The depends says test is run only if previous is ok
  218. */
  219. public function testRestUpdateContact($objid)
  220. {
  221. global $conf,$user,$langs,$db;
  222. // attempt to create without mandatory fields
  223. $url = $this->api_url.'/contacts?api_key='.$this->api_key;
  224. $addheaders=array('Content-Type: application/json');
  225. //update the contact
  226. // Update the firstname of the contact
  227. $updateBody = array(
  228. "firstname" => "UpdatedFirstName",
  229. );
  230. $updateRequestBody = json_encode($updateBody);
  231. $updateUrl = $this->api_url . '/contacts/' . $objid. '?api_key=' . $this->api_key;
  232. $updateResult = getURLContent($updateUrl, 'PUTALREADYFORMATED', $updateRequestBody, 1, $addheaders, array('http', 'https'), 2);
  233. $this->assertEquals($updateResult['curl_error_no'], '');
  234. $updateResponse = json_decode($updateResult['content'], true);
  235. $this->assertNotNull($updateResponse, "Parsing of JSON result must not be null");
  236. print_r($updateResponse);
  237. // Check if the updated fields match the changes you made
  238. $this->assertTrue($updateResponse['firstname'] === $updateBody['firstname'], 'Update might have failed');
  239. // Deleting the Contact
  240. /*
  241. $deleteUrl = $this->api_url . '/contacts/' . $objid . '?api_key=' . $this->api_key;
  242. $deleteResult = getURLContent($deleteUrl, 'DELETE', '', 1, $addheaders, array('http', 'https'), 2);
  243. $this->assertEquals($deleteResult['curl_error_no'], '');
  244. $deleteResponse = json_decode($deleteResult['content'], true);
  245. $this->assertNotNull($deleteResponse, "Parsing of json result must not be null");
  246. //$this->assertEquals(1, $deleteResponse, "Deletion should return a 200 status");
  247. // Update Non-Existent Contact
  248. // Delete Non-Existent Contact
  249. */
  250. return 0;
  251. }
  252. }