AvatarControllerTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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\Files\File;
  34. use OCP\Files\IRootFolder;
  35. use OCP\Files\NotFoundException;
  36. use OCP\Files\NotPermittedException;
  37. use OCP\IAvatar;
  38. use OCP\IAvatarManager;
  39. use OCP\ICache;
  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 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(): void {
  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')->willReturnArgument(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. protected function tearDown(): void {
  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->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders());
  138. $this->assertEquals('1', $response->getHeaders()['X-NC-IsCustomAvatar']);
  139. $this->assertEquals('my etag', $response->getETag());
  140. }
  141. /**
  142. * Fetch the user's avatar
  143. */
  144. public function testGetGeneratedAvatar() {
  145. $this->avatarMock->method('getFile')->willReturn($this->avatarFile);
  146. $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
  147. $response = $this->avatarController->getAvatar('userId', 32);
  148. $this->assertEquals(Http::STATUS_OK, $response->getStatus());
  149. $this->assertArrayHasKey('Content-Type', $response->getHeaders());
  150. $this->assertEquals('image type', $response->getHeaders()['Content-Type']);
  151. $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders());
  152. $this->assertEquals('0', $response->getHeaders()['X-NC-IsCustomAvatar']);
  153. $this->assertEquals('my etag', $response->getETag());
  154. }
  155. /**
  156. * Fetch the avatar of a non-existing user
  157. */
  158. public function testGetAvatarNoUser() {
  159. $this->avatarManager
  160. ->method('getAvatar')
  161. ->with('userDoesNotExist')
  162. ->will($this->throwException(new \Exception('user does not exist')));
  163. $response = $this->avatarController->getAvatar('userDoesNotExist', 32);
  164. //Comment out until JS is fixed
  165. $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
  166. }
  167. /**
  168. * Make sure we get the correct size
  169. */
  170. public function testGetAvatarSize() {
  171. $this->avatarMock->expects($this->once())
  172. ->method('getFile')
  173. ->with($this->equalTo(32))
  174. ->willReturn($this->avatarFile);
  175. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  176. $this->avatarController->getAvatar('userId', 32);
  177. }
  178. /**
  179. * We cannot get avatars that are 0 or negative
  180. */
  181. public function testGetAvatarSizeMin() {
  182. $this->avatarMock->expects($this->once())
  183. ->method('getFile')
  184. ->with($this->equalTo(64))
  185. ->willReturn($this->avatarFile);
  186. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  187. $this->avatarController->getAvatar('userId', 0);
  188. }
  189. /**
  190. * We do not support avatars larger than 2048*2048
  191. */
  192. public function testGetAvatarSizeMax() {
  193. $this->avatarMock->expects($this->once())
  194. ->method('getFile')
  195. ->with($this->equalTo(2048))
  196. ->willReturn($this->avatarFile);
  197. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  198. $this->avatarController->getAvatar('userId', 2049);
  199. }
  200. /**
  201. * Remove an avatar
  202. */
  203. public function testDeleteAvatar() {
  204. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  205. $response = $this->avatarController->deleteAvatar();
  206. $this->assertEquals(Http::STATUS_OK, $response->getStatus());
  207. }
  208. /**
  209. * Test what happens if the removing of the avatar fails
  210. */
  211. public function testDeleteAvatarException() {
  212. $this->avatarMock->method('remove')->will($this->throwException(new \Exception("foo")));
  213. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  214. $this->logger->expects($this->once())
  215. ->method('logException')
  216. ->with(new \Exception("foo"));
  217. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
  218. $this->assertEquals($expectedResponse, $this->avatarController->deleteAvatar());
  219. }
  220. /**
  221. * Trying to get a tmp avatar when it is not available. 404
  222. */
  223. public function testTmpAvatarNoTmp() {
  224. $response = $this->avatarController->getTmpAvatar();
  225. $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
  226. }
  227. /**
  228. * Fetch tmp avatar
  229. */
  230. public function testTmpAvatarValid() {
  231. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  232. $response = $this->avatarController->getTmpAvatar();
  233. $this->assertEquals(Http::STATUS_OK, $response->getStatus());
  234. }
  235. /**
  236. * When trying to post a new avatar a path or image should be posted.
  237. */
  238. public function testPostAvatarNoPathOrImage() {
  239. $response = $this->avatarController->postAvatar(null);
  240. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  241. }
  242. /**
  243. * Test a correct post of an avatar using POST
  244. */
  245. public function testPostAvatarFile() {
  246. //Create temp file
  247. $fileName = tempnam(null, "avatarTest");
  248. $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.jpg', $fileName);
  249. $this->assertTrue($copyRes);
  250. //Create file in cache
  251. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  252. //Create request return
  253. $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.jpg')]];
  254. $this->request->method('getUploadedFile')->willReturn($reqRet);
  255. $response = $this->avatarController->postAvatar(null);
  256. //On correct upload always respond with the notsquare message
  257. $this->assertEquals('notsquare', $response->getData()['data']);
  258. //File should be deleted
  259. $this->assertFalse(file_exists($fileName));
  260. }
  261. /**
  262. * Test invalid post os an avatar using POST
  263. */
  264. public function testPostAvatarInvalidFile() {
  265. //Create request return
  266. $reqRet = ['error' => [1], 'tmp_name' => ['foo']];
  267. $this->request->method('getUploadedFile')->willReturn($reqRet);
  268. $response = $this->avatarController->postAvatar(null);
  269. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  270. }
  271. /**
  272. * Check what happens when we upload a GIF
  273. */
  274. public function testPostAvatarFileGif() {
  275. //Create temp file
  276. $fileName = tempnam(null, "avatarTest");
  277. $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.gif', $fileName);
  278. $this->assertTrue($copyRes);
  279. //Create file in cache
  280. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.gif'));
  281. //Create request return
  282. $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.gif')]];
  283. $this->request->method('getUploadedFile')->willReturn($reqRet);
  284. $response = $this->avatarController->postAvatar(null);
  285. $this->assertEquals('Unknown filetype', $response->getData()['data']['message']);
  286. //File should be deleted
  287. $this->assertFalse(file_exists($fileName));
  288. }
  289. /**
  290. * Test posting avatar from existing file
  291. */
  292. public function testPostAvatarFromFile() {
  293. //Mock node API call
  294. $file = $this->getMockBuilder('OCP\Files\File')
  295. ->disableOriginalConstructor()->getMock();
  296. $file->expects($this->once())
  297. ->method('getContent')
  298. ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  299. $file->expects($this->once())
  300. ->method('getMimeType')
  301. ->willReturn('image/jpeg');
  302. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  303. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  304. $userFolder->method('get')->willReturn($file);
  305. //Create request return
  306. $response = $this->avatarController->postAvatar('avatar.jpg');
  307. //On correct upload always respond with the notsquare message
  308. $this->assertEquals('notsquare', $response->getData()['data']);
  309. }
  310. /**
  311. * Test posting avatar from existing folder
  312. */
  313. public function testPostAvatarFromNoFile() {
  314. $file = $this->getMockBuilder('OCP\Files\Node')->getMock();
  315. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  316. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  317. $userFolder
  318. ->method('get')
  319. ->with('folder')
  320. ->willReturn($file);
  321. //Create request return
  322. $response = $this->avatarController->postAvatar('folder');
  323. //On correct upload always respond with the notsquare message
  324. $this->assertEquals(['data' => ['message' => 'Please select a file.']], $response->getData());
  325. }
  326. public function testPostAvatarInvalidType() {
  327. $file = $this->getMockBuilder('OCP\Files\File')
  328. ->disableOriginalConstructor()->getMock();
  329. $file->expects($this->never())
  330. ->method('getContent');
  331. $file->expects($this->exactly(2))
  332. ->method('getMimeType')
  333. ->willReturn('text/plain');
  334. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  335. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  336. $userFolder->method('get')->willReturn($file);
  337. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file is not an image.']], Http::STATUS_BAD_REQUEST);
  338. $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
  339. }
  340. public function testPostAvatarNotPermittedException() {
  341. $file = $this->getMockBuilder('OCP\Files\File')
  342. ->disableOriginalConstructor()->getMock();
  343. $file->expects($this->once())
  344. ->method('getContent')
  345. ->willThrowException(new NotPermittedException());
  346. $file->expects($this->once())
  347. ->method('getMimeType')
  348. ->willReturn('image/jpeg');
  349. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  350. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  351. $userFolder->method('get')->willReturn($file);
  352. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file cannot be read.']], Http::STATUS_BAD_REQUEST);
  353. $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
  354. }
  355. /**
  356. * Test what happens if the upload of the avatar fails
  357. */
  358. public function testPostAvatarException() {
  359. $this->cache->expects($this->once())
  360. ->method('set')
  361. ->will($this->throwException(new \Exception("foo")));
  362. $file = $this->getMockBuilder('OCP\Files\File')
  363. ->disableOriginalConstructor()->getMock();
  364. $file->expects($this->once())
  365. ->method('getContent')
  366. ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  367. $file->expects($this->once())
  368. ->method('getMimeType')
  369. ->willReturn('image/jpeg');
  370. $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
  371. $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
  372. $userFolder->method('get')->willReturn($file);
  373. $this->logger->expects($this->once())
  374. ->method('logException')
  375. ->with(new \Exception("foo"));
  376. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK);
  377. $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
  378. }
  379. /**
  380. * Test invalid crop argument
  381. */
  382. public function testPostCroppedAvatarInvalidCrop() {
  383. $response = $this->avatarController->postCroppedAvatar([]);
  384. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  385. }
  386. /**
  387. * Test no tmp avatar to crop
  388. */
  389. public function testPostCroppedAvatarNoTmpAvatar() {
  390. $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
  391. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  392. }
  393. /**
  394. * Test with non square crop
  395. */
  396. public function testPostCroppedAvatarNoSquareCrop() {
  397. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  398. $this->avatarMock->method('set')->will($this->throwException(new \OC\NotSquareException));
  399. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  400. $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]);
  401. $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
  402. }
  403. /**
  404. * Check for proper reply on proper crop argument
  405. */
  406. public function testPostCroppedAvatarValidCrop() {
  407. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  408. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  409. $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
  410. $this->assertEquals(Http::STATUS_OK, $response->getStatus());
  411. $this->assertEquals('success', $response->getData()['status']);
  412. }
  413. /**
  414. * Test what happens if the cropping of the avatar fails
  415. */
  416. public function testPostCroppedAvatarException() {
  417. $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
  418. $this->avatarMock->method('set')->will($this->throwException(new \Exception('foo')));
  419. $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
  420. $this->logger->expects($this->once())
  421. ->method('logException')
  422. ->with(new \Exception('foo'));
  423. $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
  424. $this->assertEquals($expectedResponse, $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]));
  425. }
  426. /**
  427. * Check for proper reply on proper crop argument
  428. */
  429. public function testFileTooBig() {
  430. $fileName = \OC::$SERVERROOT.'/tests/data/testimage.jpg';
  431. //Create request return
  432. $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21 * 1024 * 1024]];
  433. $this->request->method('getUploadedFile')->willReturn($reqRet);
  434. $response = $this->avatarController->postAvatar(null);
  435. $this->assertEquals('File is too big', $response->getData()['data']['message']);
  436. }
  437. }