AvatarControllerTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. <?php
  2. /**
  3. * @author Roeland Jago Douma <roeland@famdouma.nl>
  4. *
  5. * @copyright Copyright (c) 2015, ownCloud, Inc.
  6. * @license AGPL-3.0
  7. *
  8. * This code is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License, version 3,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License, version 3,
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>
  19. *
  20. */
  21. namespace OC\Core\Controller;
  22. /**
  23. * Overwrite is_uploaded_file in the OC\Core\Controller namespace to allow
  24. * proper unit testing of the postAvatar call.
  25. */
  26. function is_uploaded_file($filename) {
  27. return file_exists($filename);
  28. }
  29. namespace Tests\Core\Controller;
  30. use OC\AppFramework\Utility\TimeFactory;
  31. use OC\Core\Controller\AvatarController;
  32. use OCP\AppFramework\Http;
  33. use OCP\ICache;
  34. use OCP\Files\File;
  35. use OCP\Files\IRootFolder;
  36. use OCP\Files\NotFoundException;
  37. use OCP\Files\NotPermittedException;
  38. use OCP\IAvatar;
  39. use OCP\IAvatarManager;
  40. use OCP\IL10N;
  41. use OCP\ILogger;
  42. use OCP\IRequest;
  43. use OCP\IUser;
  44. use OCP\IUserManager;
  45. /**
  46. * Class AvatarControllerTest
  47. *
  48. * @package OC\Core\Controller
  49. */
  50. class AvatarControllerTest extends \Test\TestCase {
  51. /** @var \OC\Core\Controller\AvatarController */
  52. private $avatarController;
  53. /** @var IAvatar|\PHPUnit_Framework_MockObject_MockObject */
  54. private $avatarMock;
  55. /** @var IUser|\PHPUnit_Framework_MockObject_MockObject */
  56. private $userMock;
  57. /** @var File|\PHPUnit_Framework_MockObject_MockObject */
  58. private $avatarFile;
  59. /** @var IAvatarManager|\PHPUnit_Framework_MockObject_MockObject */
  60. private $avatarManager;
  61. /** @var ICache|\PHPUnit_Framework_MockObject_MockObject */
  62. private $cache;
  63. /** @var IL10N|\PHPUnit_Framework_MockObject_MockObject */
  64. private $l;
  65. /** @var IUserManager|\PHPUnit_Framework_MockObject_MockObject */
  66. private $userManager;
  67. /** @var IRootFolder|\PHPUnit_Framework_MockObject_MockObject */
  68. private $rootFolder;
  69. /** @var ILogger|\PHPUnit_Framework_MockObject_MockObject */
  70. private $logger;
  71. /** @var IRequest|\PHPUnit_Framework_MockObject_MockObject */
  72. private $request;
  73. /** @var TimeFactory|\PHPUnit_Framework_MockObject_MockObject */
  74. private $timeFactory;
  75. protected function setUp() {
  76. parent::setUp();
  77. $this->avatarManager = $this->getMockBuilder('OCP\IAvatarManager')->getMock();
  78. $this->cache = $this->getMockBuilder('OCP\ICache')
  79. ->disableOriginalConstructor()->getMock();
  80. $this->l = $this->getMockBuilder(IL10N::class)->getMock();
  81. $this->l->method('t')->will($this->returnArgument(0));
  82. $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock();
  83. $this->request = $this->getMockBuilder(IRequest::class)->getMock();
  84. $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->getMock();
  85. $this->logger = $this->getMockBuilder(ILogger::class)->getMock();
  86. $this->timeFactory = $this->getMockBuilder('OC\AppFramework\Utility\TimeFactory')->getMock();
  87. $this->avatarMock = $this->getMockBuilder('OCP\IAvatar')->getMock();
  88. $this->userMock = $this->getMockBuilder(IUser::class)->getMock();
  89. $this->avatarController = new AvatarController(
  90. 'core',
  91. $this->request,
  92. $this->avatarManager,
  93. $this->cache,
  94. $this->l,
  95. $this->userManager,
  96. $this->rootFolder,
  97. $this->logger,
  98. 'userid',
  99. $this->timeFactory
  100. );
  101. // Configure userMock
  102. $this->userMock->method('getDisplayName')->willReturn('displayName');
  103. $this->userMock->method('getUID')->willReturn('userId');
  104. $this->userManager->method('get')
  105. ->willReturnMap([['userId', $this->userMock]]);
  106. $this->avatarFile = $this->getMockBuilder('OCP\Files\File')->getMock();
  107. $this->avatarFile->method('getContent')->willReturn('image data');
  108. $this->avatarFile->method('getMimeType')->willReturn('image type');
  109. $this->avatarFile->method('getEtag')->willReturn('my etag');
  110. }
  111. public function tearDown() {
  112. parent::tearDown();
  113. }
  114. /**
  115. * Fetch an avatar if a user has no avatar
  116. */
  117. public function testGetAvatarNoAvatar() {
  118. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  119. $this->avatarMock->method('getFile')->will($this->throwException(new NotFoundException()));
  120. $response = $this->avatarController->getAvatar('userId', 32);
  121. //Comment out until JS is fixed
  122. $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
  123. }
  124. /**
  125. * Fetch the user's avatar
  126. */
  127. public function testGetAvatar() {
  128. $this->avatarMock->method('getFile')->willReturn($this->avatarFile);
  129. $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
  130. $this->avatarMock->expects($this->once())
  131. ->method('isCustomAvatar')
  132. ->willReturn(true);
  133. $response = $this->avatarController->getAvatar('userId', 32);
  134. $this->assertEquals(Http::STATUS_OK, $response->getStatus());
  135. $this->assertArrayHasKey('Content-Type', $response->getHeaders());
  136. $this->assertEquals('image type', $response->getHeaders()['Content-Type']);
  137. $this->assertEquals('my etag', $response->getETag());
  138. }
  139. /**
  140. * Fetch the user's avatar
  141. */
  142. public function testGetGeneratedAvatar() {
  143. $this->avatarMock->method('getFile')->willReturn($this->avatarFile);
  144. $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
  145. $response = $this->avatarController->getAvatar('userId', 32);
  146. $this->assertEquals(Http::STATUS_CREATED, $response->getStatus());
  147. $this->assertArrayHasKey('Content-Type', $response->getHeaders());
  148. $this->assertEquals('image type', $response->getHeaders()['Content-Type']);
  149. $this->assertEquals('my etag', $response->getETag());
  150. }
  151. /**
  152. * Fetch the avatar of a non-existing user
  153. */
  154. public function testGetAvatarNoUser() {
  155. $this->avatarManager
  156. ->method('getAvatar')
  157. ->with('userDoesNotExist')
  158. ->will($this->throwException(new \Exception('user does not exist')));
  159. $response = $this->avatarController->getAvatar('userDoesNotExist', 32);
  160. //Comment out until JS is fixed
  161. $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
  162. }
  163. /**
  164. * Make sure we get the correct size
  165. */
  166. public function testGetAvatarSize() {
  167. $this->avatarMock->expects($this->once())
  168. ->method('getFile')
  169. ->with($this->equalTo(32))
  170. ->willReturn($this->avatarFile);
  171. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  172. $this->avatarController->getAvatar('userId', 32);
  173. }
  174. /**
  175. * We cannot get avatars that are 0 or negative
  176. */
  177. public function testGetAvatarSizeMin() {
  178. $this->avatarMock->expects($this->once())
  179. ->method('getFile')
  180. ->with($this->equalTo(64))
  181. ->willReturn($this->avatarFile);
  182. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  183. $this->avatarController->getAvatar('userId', 0);
  184. }
  185. /**
  186. * We do not support avatars larger than 2048*2048
  187. */
  188. public function testGetAvatarSizeMax() {
  189. $this->avatarMock->expects($this->once())
  190. ->method('getFile')
  191. ->with($this->equalTo(2048))
  192. ->willReturn($this->avatarFile);
  193. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  194. $this->avatarController->getAvatar('userId', 2049);
  195. }
  196. /**
  197. * Remove an avatar
  198. */
  199. public function testDeleteAvatar() {
  200. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  201. $response = $this->avatarController->deleteAvatar();
  202. $this->assertEquals(Http::STATUS_OK, $response->getStatus());
  203. }
  204. /**
  205. * Test what happens if the removing of the avatar fails
  206. */
  207. public function testDeleteAvatarException() {
  208. $this->avatarMock->method('remove')->will($this->throwException(new \Exception("foo")));
  209. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  210. $this->logger->expects($this->once())
  211. ->method('logException')
  212. ->with(new \Exception("foo"));
  213. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
  214. $this->assertEquals($expectedResponse, $this->avatarController->deleteAvatar());
  215. }
  216. /**
  217. * Trying to get a tmp avatar when it is not available. 404
  218. */
  219. public function testTmpAvatarNoTmp() {
  220. $response = $this->avatarController->getTmpAvatar();
  221. $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
  222. }
  223. /**
  224. * Fetch tmp avatar
  225. */
  226. public function testTmpAvatarValid() {
  227. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  228. $response = $this->avatarController->getTmpAvatar();
  229. $this->assertEquals(Http::STATUS_OK, $response->getStatus());
  230. }
  231. /**
  232. * When trying to post a new avatar a path or image should be posted.
  233. */
  234. public function testPostAvatarNoPathOrImage() {
  235. $response = $this->avatarController->postAvatar(null);
  236. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  237. }
  238. /**
  239. * Test a correct post of an avatar using POST
  240. */
  241. public function testPostAvatarFile() {
  242. //Create temp file
  243. $fileName = tempnam(null, "avatarTest");
  244. $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.jpg', $fileName);
  245. $this->assertTrue($copyRes);
  246. //Create file in cache
  247. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  248. //Create request return
  249. $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.jpg')]];
  250. $this->request->method('getUploadedFile')->willReturn($reqRet);
  251. $response = $this->avatarController->postAvatar(null);
  252. //On correct upload always respond with the notsquare message
  253. $this->assertEquals('notsquare', $response->getData()['data']);
  254. //File should be deleted
  255. $this->assertFalse(file_exists($fileName));
  256. }
  257. /**
  258. * Test invalid post os an avatar using POST
  259. */
  260. public function testPostAvatarInvalidFile() {
  261. //Create request return
  262. $reqRet = ['error' => [1], 'tmp_name' => ['foo']];
  263. $this->request->method('getUploadedFile')->willReturn($reqRet);
  264. $response = $this->avatarController->postAvatar(null);
  265. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  266. }
  267. /**
  268. * Check what happens when we upload a GIF
  269. */
  270. public function testPostAvatarFileGif() {
  271. //Create temp file
  272. $fileName = tempnam(null, "avatarTest");
  273. $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.gif', $fileName);
  274. $this->assertTrue($copyRes);
  275. //Create file in cache
  276. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.gif'));
  277. //Create request return
  278. $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => filesize(\OC::$SERVERROOT.'/tests/data/testimage.gif')];
  279. $this->request->method('getUploadedFile')->willReturn($reqRet);
  280. $response = $this->avatarController->postAvatar(null);
  281. $this->assertEquals('Unknown filetype', $response->getData()['data']['message']);
  282. //File should be deleted
  283. $this->assertFalse(file_exists($fileName));
  284. }
  285. /**
  286. * Test posting avatar from existing file
  287. */
  288. public function testPostAvatarFromFile() {
  289. //Mock node API call
  290. $file = $this->getMockBuilder('OCP\Files\File')
  291. ->disableOriginalConstructor()->getMock();
  292. $file->expects($this->once())
  293. ->method('getContent')
  294. ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  295. $file->expects($this->once())
  296. ->method('getMimeType')
  297. ->willReturn('image/jpeg');
  298. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  299. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  300. $userFolder->method('get')->willReturn($file);
  301. //Create request return
  302. $response = $this->avatarController->postAvatar('avatar.jpg');
  303. //On correct upload always respond with the notsquare message
  304. $this->assertEquals('notsquare', $response->getData()['data']);
  305. }
  306. /**
  307. * Test posting avatar from existing folder
  308. */
  309. public function testPostAvatarFromNoFile() {
  310. $file = $this->getMockBuilder('OCP\Files\Node')->getMock();
  311. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  312. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  313. $userFolder
  314. ->method('get')
  315. ->with('folder')
  316. ->willReturn($file);
  317. //Create request return
  318. $response = $this->avatarController->postAvatar('folder');
  319. //On correct upload always respond with the notsquare message
  320. $this->assertEquals(['data' => ['message' => 'Please select a file.']], $response->getData());
  321. }
  322. public function testPostAvatarInvalidType() {
  323. $file = $this->getMockBuilder('OCP\Files\File')
  324. ->disableOriginalConstructor()->getMock();
  325. $file->expects($this->never())
  326. ->method('getContent');
  327. $file->expects($this->exactly(2))
  328. ->method('getMimeType')
  329. ->willReturn('text/plain');
  330. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  331. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  332. $userFolder->method('get')->willReturn($file);
  333. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file is not an image.']], Http::STATUS_BAD_REQUEST);
  334. $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
  335. }
  336. public function testPostAvatarNotPermittedException() {
  337. $file = $this->getMockBuilder('OCP\Files\File')
  338. ->disableOriginalConstructor()->getMock();
  339. $file->expects($this->once())
  340. ->method('getContent')
  341. ->willThrowException(new NotPermittedException());
  342. $file->expects($this->once())
  343. ->method('getMimeType')
  344. ->willReturn('image/jpeg');
  345. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  346. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  347. $userFolder->method('get')->willReturn($file);
  348. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file cannot be read.']], Http::STATUS_BAD_REQUEST);
  349. $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
  350. }
  351. /**
  352. * Test what happens if the upload of the avatar fails
  353. */
  354. public function testPostAvatarException() {
  355. $this->cache->expects($this->once())
  356. ->method('set')
  357. ->will($this->throwException(new \Exception("foo")));
  358. $file = $this->getMockBuilder('OCP\Files\File')
  359. ->disableOriginalConstructor()->getMock();
  360. $file->expects($this->once())
  361. ->method('getContent')
  362. ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  363. $file->expects($this->once())
  364. ->method('getMimeType')
  365. ->willReturn('image/jpeg');
  366. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  367. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  368. $userFolder->method('get')->willReturn($file);
  369. $this->logger->expects($this->once())
  370. ->method('logException')
  371. ->with(new \Exception("foo"));
  372. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK);
  373. $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
  374. }
  375. /**
  376. * Test invalid crop argument
  377. */
  378. public function testPostCroppedAvatarInvalidCrop() {
  379. $response = $this->avatarController->postCroppedAvatar([]);
  380. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  381. }
  382. /**
  383. * Test no tmp avatar to crop
  384. */
  385. public function testPostCroppedAvatarNoTmpAvatar() {
  386. $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
  387. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  388. }
  389. /**
  390. * Test with non square crop
  391. */
  392. public function testPostCroppedAvatarNoSquareCrop() {
  393. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  394. $this->avatarMock->method('set')->will($this->throwException(new \OC\NotSquareException));
  395. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  396. $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]);
  397. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  398. }
  399. /**
  400. * Check for proper reply on proper crop argument
  401. */
  402. public function testPostCroppedAvatarValidCrop() {
  403. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  404. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  405. $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
  406. $this->assertEquals(Http::STATUS_OK, $response->getStatus());
  407. $this->assertEquals('success', $response->getData()['status']);
  408. }
  409. /**
  410. * Test what happens if the cropping of the avatar fails
  411. */
  412. public function testPostCroppedAvatarException() {
  413. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  414. $this->avatarMock->method('set')->will($this->throwException(new \Exception('foo')));
  415. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  416. $this->logger->expects($this->once())
  417. ->method('logException')
  418. ->with(new \Exception('foo'));
  419. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
  420. $this->assertEquals($expectedResponse, $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]));
  421. }
  422. /**
  423. * Check for proper reply on proper crop argument
  424. */
  425. public function testFileTooBig() {
  426. $fileName = \OC::$SERVERROOT.'/tests/data/testimage.jpg';
  427. //Create request return
  428. $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21*1024*1024]];
  429. $this->request->method('getUploadedFile')->willReturn($reqRet);
  430. $response = $this->avatarController->postAvatar(null);
  431. $this->assertEquals('File is too big', $response->getData()['data']['message']);
  432. }
  433. }