file.test 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846
  1. <?php
  2. /**
  3. * @file
  4. * This provides SimpleTests for the core file handling functionality.
  5. * These include FileValidateTest and FileSaveTest.
  6. */
  7. /**
  8. * Helper validator that returns the $errors parameter.
  9. */
  10. function file_test_validator($file, $errors) {
  11. return $errors;
  12. }
  13. /**
  14. * Helper function for testing file_scan_directory().
  15. *
  16. * Each time the function is called the file is stored in a static variable.
  17. * When the function is called with no $filepath parameter, the results are
  18. * returned.
  19. *
  20. * @param $filepath
  21. * File path
  22. * @return
  23. * If $filepath is NULL, an array of all previous $filepath parameters
  24. */
  25. function file_test_file_scan_callback($filepath = NULL) {
  26. $files = &drupal_static(__FUNCTION__, array());
  27. if (isset($filepath)) {
  28. $files[] = $filepath;
  29. }
  30. else {
  31. return $files;
  32. }
  33. }
  34. /**
  35. * Reset static variables used by file_test_file_scan_callback().
  36. */
  37. function file_test_file_scan_callback_reset() {
  38. drupal_static_reset('file_test_file_scan_callback');
  39. }
  40. /**
  41. * Base class for file tests that adds some additional file specific
  42. * assertions and helper functions.
  43. */
  44. class FileTestCase extends DrupalWebTestCase {
  45. /**
  46. * Check that two files have the same values for all fields other than the
  47. * timestamp.
  48. *
  49. * @param $before
  50. * File object to compare.
  51. * @param $after
  52. * File object to compare.
  53. */
  54. function assertFileUnchanged($before, $after) {
  55. $this->assertEqual($before->fid, $after->fid, format_string('File id is the same: %file1 == %file2.', array('%file1' => $before->fid, '%file2' => $after->fid)), 'File unchanged');
  56. $this->assertEqual($before->uid, $after->uid, format_string('File owner is the same: %file1 == %file2.', array('%file1' => $before->uid, '%file2' => $after->uid)), 'File unchanged');
  57. $this->assertEqual($before->filename, $after->filename, format_string('File name is the same: %file1 == %file2.', array('%file1' => $before->filename, '%file2' => $after->filename)), 'File unchanged');
  58. $this->assertEqual($before->uri, $after->uri, format_string('File path is the same: %file1 == %file2.', array('%file1' => $before->uri, '%file2' => $after->uri)), 'File unchanged');
  59. $this->assertEqual($before->filemime, $after->filemime, format_string('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->filemime, '%file2' => $after->filemime)), 'File unchanged');
  60. $this->assertEqual($before->filesize, $after->filesize, format_string('File size is the same: %file1 == %file2.', array('%file1' => $before->filesize, '%file2' => $after->filesize)), 'File unchanged');
  61. $this->assertEqual($before->status, $after->status, format_string('File status is the same: %file1 == %file2.', array('%file1' => $before->status, '%file2' => $after->status)), 'File unchanged');
  62. }
  63. /**
  64. * Check that two files are not the same by comparing the fid and filepath.
  65. *
  66. * @param $file1
  67. * File object to compare.
  68. * @param $file2
  69. * File object to compare.
  70. */
  71. function assertDifferentFile($file1, $file2) {
  72. $this->assertNotEqual($file1->fid, $file2->fid, format_string('Files have different ids: %file1 != %file2.', array('%file1' => $file1->fid, '%file2' => $file2->fid)), 'Different file');
  73. $this->assertNotEqual($file1->uri, $file2->uri, format_string('Files have different paths: %file1 != %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Different file');
  74. }
  75. /**
  76. * Check that two files are the same by comparing the fid and filepath.
  77. *
  78. * @param $file1
  79. * File object to compare.
  80. * @param $file2
  81. * File object to compare.
  82. */
  83. function assertSameFile($file1, $file2) {
  84. $this->assertEqual($file1->fid, $file2->fid, format_string('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->fid, '%file2-fid' => $file2->fid)), 'Same file');
  85. $this->assertEqual($file1->uri, $file2->uri, format_string('Files have the same path: %file1 == %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Same file');
  86. }
  87. /**
  88. * Helper function to test the permissions of a file.
  89. *
  90. * @param $filepath
  91. * String file path.
  92. * @param $expected_mode
  93. * Octal integer like 0664 or 0777.
  94. * @param $message
  95. * Optional message.
  96. */
  97. function assertFilePermissions($filepath, $expected_mode, $message = NULL) {
  98. // Clear out PHP's file stat cache to be sure we see the current value.
  99. clearstatcache();
  100. // Mask out all but the last three octets.
  101. $actual_mode = fileperms($filepath) & 0777;
  102. // PHP on Windows has limited support for file permissions. Usually each of
  103. // "user", "group" and "other" use one octal digit (3 bits) to represent the
  104. // read/write/execute bits. On Windows, chmod() ignores the "group" and
  105. // "other" bits, and fileperms() returns the "user" bits in all three
  106. // positions. $expected_mode is updated to reflect this.
  107. if (substr(PHP_OS, 0, 3) == 'WIN') {
  108. // Reset the "group" and "other" bits.
  109. $expected_mode = $expected_mode & 0700;
  110. // Shift the "user" bits to the "group" and "other" positions also.
  111. $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
  112. }
  113. if (!isset($message)) {
  114. $message = t('Expected file permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
  115. }
  116. $this->assertEqual($actual_mode, $expected_mode, $message);
  117. }
  118. /**
  119. * Helper function to test the permissions of a directory.
  120. *
  121. * @param $directory
  122. * String directory path.
  123. * @param $expected_mode
  124. * Octal integer like 0664 or 0777.
  125. * @param $message
  126. * Optional message.
  127. */
  128. function assertDirectoryPermissions($directory, $expected_mode, $message = NULL) {
  129. // Clear out PHP's file stat cache to be sure we see the current value.
  130. clearstatcache();
  131. // Mask out all but the last three octets.
  132. $actual_mode = fileperms($directory) & 0777;
  133. // PHP on Windows has limited support for file permissions. Usually each of
  134. // "user", "group" and "other" use one octal digit (3 bits) to represent the
  135. // read/write/execute bits. On Windows, chmod() ignores the "group" and
  136. // "other" bits, and fileperms() returns the "user" bits in all three
  137. // positions. $expected_mode is updated to reflect this.
  138. if (substr(PHP_OS, 0, 3) == 'WIN') {
  139. // Reset the "group" and "other" bits.
  140. $expected_mode = $expected_mode & 0700;
  141. // Shift the "user" bits to the "group" and "other" positions also.
  142. $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
  143. }
  144. if (!isset($message)) {
  145. $message = t('Expected directory permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
  146. }
  147. $this->assertEqual($actual_mode, $expected_mode, $message);
  148. }
  149. /**
  150. * Create a directory and assert it exists.
  151. *
  152. * @param $path
  153. * Optional string with a directory path. If none is provided, a random
  154. * name in the site's files directory will be used.
  155. * @return
  156. * The path to the directory.
  157. */
  158. function createDirectory($path = NULL) {
  159. // A directory to operate on.
  160. if (!isset($path)) {
  161. $path = file_default_scheme() . '://' . $this->randomName();
  162. }
  163. $this->assertTrue(drupal_mkdir($path) && is_dir($path), 'Directory was created successfully.');
  164. return $path;
  165. }
  166. /**
  167. * Create a file and save it to the files table and assert that it occurs
  168. * correctly.
  169. *
  170. * @param $filepath
  171. * Optional string specifying the file path. If none is provided then a
  172. * randomly named file will be created in the site's files directory.
  173. * @param $contents
  174. * Optional contents to save into the file. If a NULL value is provided an
  175. * arbitrary string will be used.
  176. * @param $scheme
  177. * Optional string indicating the stream scheme to use. Drupal core includes
  178. * public, private, and temporary. The public wrapper is the default.
  179. * @return
  180. * File object.
  181. */
  182. function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
  183. if (!isset($filepath)) {
  184. // Prefix with non-latin characters to ensure that all file-related
  185. // tests work with international filenames.
  186. $filepath = 'Файл для тестирования ' . $this->randomName();
  187. }
  188. if (!isset($scheme)) {
  189. $scheme = file_default_scheme();
  190. }
  191. $filepath = $scheme . '://' . $filepath;
  192. if (!isset($contents)) {
  193. $contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
  194. }
  195. file_put_contents($filepath, $contents);
  196. $this->assertTrue(is_file($filepath), 'The test file exists on the disk.', 'Create test file');
  197. $file = new stdClass();
  198. $file->uri = $filepath;
  199. $file->filename = drupal_basename($file->uri);
  200. $file->filemime = 'text/plain';
  201. $file->uid = 1;
  202. $file->timestamp = REQUEST_TIME;
  203. $file->filesize = filesize($file->uri);
  204. $file->status = 0;
  205. // Write the record directly rather than calling file_save() so we don't
  206. // invoke the hooks.
  207. $this->assertNotIdentical(drupal_write_record('file_managed', $file), FALSE, 'The file was added to the database.', 'Create test file');
  208. return $file;
  209. }
  210. }
  211. /**
  212. * Base class for file tests that use the file_test module to test uploads and
  213. * hooks.
  214. */
  215. class FileHookTestCase extends FileTestCase {
  216. function setUp() {
  217. // Install file_test module
  218. parent::setUp('file_test');
  219. // Clear out any hook calls.
  220. file_test_reset();
  221. }
  222. /**
  223. * Assert that all of the specified hook_file_* hooks were called once, other
  224. * values result in failure.
  225. *
  226. * @param $expected
  227. * Array with string containing with the hook name, e.g. 'load', 'save',
  228. * 'insert', etc.
  229. */
  230. function assertFileHooksCalled($expected) {
  231. // Determine which hooks were called.
  232. $actual = array_keys(array_filter(file_test_get_all_calls()));
  233. // Determine if there were any expected that were not called.
  234. $uncalled = array_diff($expected, $actual);
  235. if (count($uncalled)) {
  236. $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
  237. }
  238. else {
  239. $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? t('(none)') : implode(', ', $expected))));
  240. }
  241. // Determine if there were any unexpected calls.
  242. $unexpected = array_diff($actual, $expected);
  243. if (count($unexpected)) {
  244. $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? t('(none)') : implode(', ', $unexpected))));
  245. }
  246. else {
  247. $this->assertTrue(TRUE, 'No unexpected hooks were called.');
  248. }
  249. }
  250. /**
  251. * Assert that a hook_file_* hook was called a certain number of times.
  252. *
  253. * @param $hook
  254. * String with the hook name, e.g. 'load', 'save', 'insert', etc.
  255. * @param $expected_count
  256. * Optional integer count.
  257. * @param $message
  258. * Optional translated string message.
  259. */
  260. function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
  261. $actual_count = count(file_test_get_calls($hook));
  262. if (!isset($message)) {
  263. if ($actual_count == $expected_count) {
  264. $message = format_string('hook_file_@name was called correctly.', array('@name' => $hook));
  265. }
  266. elseif ($expected_count == 0) {
  267. $message = format_plural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count));
  268. }
  269. else {
  270. $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count));
  271. }
  272. }
  273. $this->assertEqual($actual_count, $expected_count, $message);
  274. }
  275. }
  276. /**
  277. * This will run tests against the file_space_used() function.
  278. */
  279. class FileSpaceUsedTest extends FileTestCase {
  280. public static function getInfo() {
  281. return array(
  282. 'name' => 'File space used tests',
  283. 'description' => 'Tests the file_space_used() function.',
  284. 'group' => 'File API',
  285. );
  286. }
  287. function setUp() {
  288. parent::setUp();
  289. // Create records for a couple of users with different sizes.
  290. $file = array('uid' => 2, 'uri' => 'public://example1.txt', 'filesize' => 50, 'status' => FILE_STATUS_PERMANENT);
  291. drupal_write_record('file_managed', $file);
  292. $file = array('uid' => 2, 'uri' => 'public://example2.txt', 'filesize' => 20, 'status' => FILE_STATUS_PERMANENT);
  293. drupal_write_record('file_managed', $file);
  294. $file = array('uid' => 3, 'uri' => 'public://example3.txt', 'filesize' => 100, 'status' => FILE_STATUS_PERMANENT);
  295. drupal_write_record('file_managed', $file);
  296. $file = array('uid' => 3, 'uri' => 'public://example4.txt', 'filesize' => 200, 'status' => FILE_STATUS_PERMANENT);
  297. drupal_write_record('file_managed', $file);
  298. // Now create some non-permanent files.
  299. $file = array('uid' => 2, 'uri' => 'public://example5.txt', 'filesize' => 1, 'status' => 0);
  300. drupal_write_record('file_managed', $file);
  301. $file = array('uid' => 3, 'uri' => 'public://example6.txt', 'filesize' => 3, 'status' => 0);
  302. drupal_write_record('file_managed', $file);
  303. }
  304. /**
  305. * Test different users with the default status.
  306. */
  307. function testFileSpaceUsed() {
  308. // Test different users with default status.
  309. $this->assertEqual(file_space_used(2), 70);
  310. $this->assertEqual(file_space_used(3), 300);
  311. $this->assertEqual(file_space_used(), 370);
  312. // Test the status fields
  313. $this->assertEqual(file_space_used(NULL, 0), 4);
  314. $this->assertEqual(file_space_used(NULL, FILE_STATUS_PERMANENT), 370);
  315. // Test both the user and status.
  316. $this->assertEqual(file_space_used(1, 0), 0);
  317. $this->assertEqual(file_space_used(1, FILE_STATUS_PERMANENT), 0);
  318. $this->assertEqual(file_space_used(2, 0), 1);
  319. $this->assertEqual(file_space_used(2, FILE_STATUS_PERMANENT), 70);
  320. $this->assertEqual(file_space_used(3, 0), 3);
  321. $this->assertEqual(file_space_used(3, FILE_STATUS_PERMANENT), 300);
  322. }
  323. }
  324. /**
  325. * This will run tests against the file validation functions (file_validate_*).
  326. */
  327. class FileValidatorTest extends DrupalWebTestCase {
  328. public static function getInfo() {
  329. return array(
  330. 'name' => 'File validator tests',
  331. 'description' => 'Tests the functions used to validate uploaded files.',
  332. 'group' => 'File API',
  333. );
  334. }
  335. function setUp() {
  336. parent::setUp();
  337. $this->image = new stdClass();
  338. $this->image->uri = 'misc/druplicon.png';
  339. $this->image->filename = drupal_basename($this->image->uri);
  340. $this->non_image = new stdClass();
  341. $this->non_image->uri = 'misc/jquery.js';
  342. $this->non_image->filename = drupal_basename($this->non_image->uri);
  343. }
  344. /**
  345. * Test the file_validate_extensions() function.
  346. */
  347. function testFileValidateExtensions() {
  348. $file = new stdClass();
  349. $file->filename = 'asdf.txt';
  350. $errors = file_validate_extensions($file, 'asdf txt pork');
  351. $this->assertEqual(count($errors), 0, 'Valid extension accepted.', 'File');
  352. $file->filename = 'asdf.txt';
  353. $errors = file_validate_extensions($file, 'exe png');
  354. $this->assertEqual(count($errors), 1, 'Invalid extension blocked.', 'File');
  355. }
  356. /**
  357. * This ensures a specific file is actually an image.
  358. */
  359. function testFileValidateIsImage() {
  360. $this->assertTrue(file_exists($this->image->uri), 'The image being tested exists.', 'File');
  361. $errors = file_validate_is_image($this->image);
  362. $this->assertEqual(count($errors), 0, 'No error reported for our image file.', 'File');
  363. $this->assertTrue(file_exists($this->non_image->uri), 'The non-image being tested exists.', 'File');
  364. $errors = file_validate_is_image($this->non_image);
  365. $this->assertEqual(count($errors), 1, 'An error reported for our non-image file.', 'File');
  366. }
  367. /**
  368. * This ensures the resolution of a specific file is within bounds.
  369. * The image will be resized if it's too large.
  370. */
  371. function testFileValidateImageResolution() {
  372. // Non-images.
  373. $errors = file_validate_image_resolution($this->non_image);
  374. $this->assertEqual(count($errors), 0, 'Should not get any errors for a non-image file.', 'File');
  375. $errors = file_validate_image_resolution($this->non_image, '50x50', '100x100');
  376. $this->assertEqual(count($errors), 0, 'Do not check the resolution on non files.', 'File');
  377. // Minimum size.
  378. $errors = file_validate_image_resolution($this->image);
  379. $this->assertEqual(count($errors), 0, 'No errors for an image when there is no minimum or maximum resolution.', 'File');
  380. $errors = file_validate_image_resolution($this->image, 0, '200x1');
  381. $this->assertEqual(count($errors), 1, 'Got an error for an image that was not wide enough.', 'File');
  382. $errors = file_validate_image_resolution($this->image, 0, '1x200');
  383. $this->assertEqual(count($errors), 1, 'Got an error for an image that was not tall enough.', 'File');
  384. $errors = file_validate_image_resolution($this->image, 0, '200x200');
  385. $this->assertEqual(count($errors), 1, 'Small images report an error.', 'File');
  386. // Maximum size.
  387. if (image_get_toolkit()) {
  388. // Copy the image so that the original doesn't get resized.
  389. copy('misc/druplicon.png', 'temporary://druplicon.png');
  390. $this->image->uri = 'temporary://druplicon.png';
  391. $errors = file_validate_image_resolution($this->image, '10x5');
  392. $this->assertEqual(count($errors), 0, 'No errors should be reported when an oversized image can be scaled down.', 'File');
  393. $info = image_get_info($this->image->uri);
  394. $this->assertTrue($info['width'] <= 10, 'Image scaled to correct width.', 'File');
  395. $this->assertTrue($info['height'] <= 5, 'Image scaled to correct height.', 'File');
  396. drupal_unlink('temporary://druplicon.png');
  397. }
  398. else {
  399. // TODO: should check that the error is returned if no toolkit is available.
  400. $errors = file_validate_image_resolution($this->image, '5x10');
  401. $this->assertEqual(count($errors), 1, 'Oversize images that cannot be scaled get an error.', 'File');
  402. }
  403. }
  404. /**
  405. * This will ensure the filename length is valid.
  406. */
  407. function testFileValidateNameLength() {
  408. // Create a new file object.
  409. $file = new stdClass();
  410. // Add a filename with an allowed length and test it.
  411. $file->filename = str_repeat('x', 240);
  412. $this->assertEqual(strlen($file->filename), 240);
  413. $errors = file_validate_name_length($file);
  414. $this->assertEqual(count($errors), 0, 'No errors reported for 240 length filename.', 'File');
  415. // Add a filename with a length too long and test it.
  416. $file->filename = str_repeat('x', 241);
  417. $errors = file_validate_name_length($file);
  418. $this->assertEqual(count($errors), 1, 'An error reported for 241 length filename.', 'File');
  419. // Add a filename with an empty string and test it.
  420. $file->filename = '';
  421. $errors = file_validate_name_length($file);
  422. $this->assertEqual(count($errors), 1, 'An error reported for 0 length filename.', 'File');
  423. }
  424. /**
  425. * Test file_validate_size().
  426. */
  427. function testFileValidateSize() {
  428. // Create a file with a size of 1000 bytes, and quotas of only 1 byte.
  429. $file = new stdClass();
  430. $file->filesize = 1000;
  431. $errors = file_validate_size($file, 0, 0);
  432. $this->assertEqual(count($errors), 0, 'No limits means no errors.', 'File');
  433. $errors = file_validate_size($file, 1, 0);
  434. $this->assertEqual(count($errors), 1, 'Error for the file being over the limit.', 'File');
  435. $errors = file_validate_size($file, 0, 1);
  436. $this->assertEqual(count($errors), 1, 'Error for the user being over their limit.', 'File');
  437. $errors = file_validate_size($file, 1, 1);
  438. $this->assertEqual(count($errors), 2, 'Errors for both the file and their limit.', 'File');
  439. }
  440. }
  441. /**
  442. * Tests the file_unmanaged_save_data() function.
  443. */
  444. class FileUnmanagedSaveDataTest extends FileTestCase {
  445. public static function getInfo() {
  446. return array(
  447. 'name' => 'Unmanaged file save data',
  448. 'description' => 'Tests the unmanaged file save data function.',
  449. 'group' => 'File API',
  450. );
  451. }
  452. /**
  453. * Test the file_unmanaged_save_data() function.
  454. */
  455. function testFileSaveData() {
  456. $contents = $this->randomName(8);
  457. // No filename.
  458. $filepath = file_unmanaged_save_data($contents);
  459. $this->assertTrue($filepath, 'Unnamed file saved correctly.');
  460. $this->assertEqual(file_uri_scheme($filepath), file_default_scheme(), "File was placed in Drupal's files directory.");
  461. $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
  462. // Provide a filename.
  463. $filepath = file_unmanaged_save_data($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
  464. $this->assertTrue($filepath, 'Unnamed file saved correctly.');
  465. $this->assertEqual('asdf.txt', drupal_basename($filepath), 'File was named correctly.');
  466. $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
  467. $this->assertFilePermissions($filepath, variable_get('file_chmod_file', 0664));
  468. }
  469. }
  470. /**
  471. * Tests the file_unmanaged_save_data() function on remote filesystems.
  472. */
  473. class RemoteFileUnmanagedSaveDataTest extends FileUnmanagedSaveDataTest {
  474. public static function getInfo() {
  475. $info = parent::getInfo();
  476. $info['group'] = 'File API (remote)';
  477. return $info;
  478. }
  479. function setUp() {
  480. parent::setUp('file_test');
  481. variable_set('file_default_scheme', 'dummy-remote');
  482. }
  483. }
  484. /**
  485. * Test the file_save_upload() function.
  486. */
  487. class FileSaveUploadTest extends FileHookTestCase {
  488. /**
  489. * An image file path for uploading.
  490. */
  491. protected $image;
  492. /**
  493. * A PHP file path for upload security testing.
  494. */
  495. protected $phpfile;
  496. /**
  497. * The largest file id when the test starts.
  498. */
  499. protected $maxFidBefore;
  500. public static function getInfo() {
  501. return array(
  502. 'name' => 'File uploading',
  503. 'description' => 'Tests the file uploading functions.',
  504. 'group' => 'File API',
  505. );
  506. }
  507. function setUp() {
  508. parent::setUp();
  509. $account = $this->drupalCreateUser(array('access content'));
  510. $this->drupalLogin($account);
  511. $image_files = $this->drupalGetTestFiles('image');
  512. $this->image = current($image_files);
  513. list(, $this->image_extension) = explode('.', $this->image->filename);
  514. $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");
  515. $this->phpfile = current($this->drupalGetTestFiles('php'));
  516. $this->assertTrue(is_file($this->phpfile->uri), "The PHP file we're going to upload exists.");
  517. $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  518. // Upload with replace to guarantee there's something there.
  519. $edit = array(
  520. 'file_test_replace' => FILE_EXISTS_REPLACE,
  521. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  522. );
  523. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  524. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  525. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  526. // Check that the correct hooks were called then clean out the hook
  527. // counters.
  528. $this->assertFileHooksCalled(array('validate', 'insert'));
  529. file_test_reset();
  530. }
  531. /**
  532. * Test the file_save_upload() function.
  533. */
  534. function testNormal() {
  535. $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  536. $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
  537. $file1 = file_load($max_fid_after);
  538. $this->assertTrue($file1, 'Loaded the file.');
  539. // MIME type of the uploaded image may be either image/jpeg or image/png.
  540. $this->assertEqual(substr($file1->filemime, 0, 5), 'image', 'A MIME type was set.');
  541. // Reset the hook counters to get rid of the 'load' we just called.
  542. file_test_reset();
  543. // Upload a second file.
  544. $max_fid_before = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  545. $image2 = current($this->drupalGetTestFiles('image'));
  546. $edit = array('files[file_test_upload]' => drupal_realpath($image2->uri));
  547. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  548. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  549. $this->assertRaw(t('You WIN!'));
  550. $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  551. // Check that the correct hooks were called.
  552. $this->assertFileHooksCalled(array('validate', 'insert'));
  553. $file2 = file_load($max_fid_after);
  554. $this->assertTrue($file2);
  555. // MIME type of the uploaded image may be either image/jpeg or image/png.
  556. $this->assertEqual(substr($file2->filemime, 0, 5), 'image', 'A MIME type was set.');
  557. // Load both files using file_load_multiple().
  558. $files = file_load_multiple(array($file1->fid, $file2->fid));
  559. $this->assertTrue(isset($files[$file1->fid]), 'File was loaded successfully');
  560. $this->assertTrue(isset($files[$file2->fid]), 'File was loaded successfully');
  561. // Upload a third file to a subdirectory.
  562. $image3 = current($this->drupalGetTestFiles('image'));
  563. $image3_realpath = drupal_realpath($image3->uri);
  564. $dir = $this->randomName();
  565. $edit = array(
  566. 'files[file_test_upload]' => $image3_realpath,
  567. 'file_subdir' => $dir,
  568. );
  569. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  570. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  571. $this->assertRaw(t('You WIN!'));
  572. $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
  573. // Check that file_load_multiple() with no arguments returns FALSE.
  574. $this->assertFalse(file_load_multiple(), 'No files were loaded.');
  575. }
  576. /**
  577. * Test extension handling.
  578. */
  579. function testHandleExtension() {
  580. // The file being tested is a .gif which is in the default safe list
  581. // of extensions to allow when the extension validator isn't used. This is
  582. // implicitly tested at the testNormal() test. Here we tell
  583. // file_save_upload() to only allow ".foo".
  584. $extensions = 'foo';
  585. $edit = array(
  586. 'file_test_replace' => FILE_EXISTS_REPLACE,
  587. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  588. 'extensions' => $extensions,
  589. );
  590. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  591. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  592. $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
  593. $this->assertRaw($message, 'Cannot upload a disallowed extension');
  594. $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
  595. // Check that the correct hooks were called.
  596. $this->assertFileHooksCalled(array('validate'));
  597. // Reset the hook counters.
  598. file_test_reset();
  599. $extensions = 'foo ' . $this->image_extension;
  600. // Now tell file_save_upload() to allow the extension of our test image.
  601. $edit = array(
  602. 'file_test_replace' => FILE_EXISTS_REPLACE,
  603. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  604. 'extensions' => $extensions,
  605. );
  606. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  607. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  608. $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload an allowed extension.');
  609. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  610. // Check that the correct hooks were called.
  611. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  612. // Reset the hook counters.
  613. file_test_reset();
  614. // Now tell file_save_upload() to allow any extension.
  615. $edit = array(
  616. 'file_test_replace' => FILE_EXISTS_REPLACE,
  617. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  618. 'allow_all_extensions' => TRUE,
  619. );
  620. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  621. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  622. $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
  623. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  624. // Check that the correct hooks were called.
  625. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  626. }
  627. /**
  628. * Test dangerous file handling.
  629. */
  630. function testHandleDangerousFile() {
  631. // Allow the .php extension and make sure it gets renamed to .txt for
  632. // safety. Also check to make sure its MIME type was changed.
  633. $edit = array(
  634. 'file_test_replace' => FILE_EXISTS_REPLACE,
  635. 'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
  636. 'is_image_file' => FALSE,
  637. 'extensions' => 'php',
  638. );
  639. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  640. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  641. $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '.txt' . '</em>';
  642. $this->assertRaw($message, 'Dangerous file was renamed.');
  643. $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
  644. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  645. // Check that the correct hooks were called.
  646. $this->assertFileHooksCalled(array('validate', 'insert'));
  647. // Ensure dangerous files are not renamed when insecure uploads is TRUE.
  648. // Turn on insecure uploads.
  649. variable_set('allow_insecure_uploads', 1);
  650. // Reset the hook counters.
  651. file_test_reset();
  652. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  653. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  654. $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
  655. $this->assertRaw(t('File name is !filename', array('!filename' => $this->phpfile->filename)), 'Dangerous file was not renamed when insecure uploads is TRUE.');
  656. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  657. // Check that the correct hooks were called.
  658. $this->assertFileHooksCalled(array('validate', 'insert'));
  659. // Turn off insecure uploads.
  660. variable_set('allow_insecure_uploads', 0);
  661. }
  662. /**
  663. * Test file munge handling.
  664. */
  665. function testHandleFileMunge() {
  666. // Ensure insecure uploads are disabled for this test.
  667. variable_set('allow_insecure_uploads', 0);
  668. $this->image = file_move($this->image, $this->image->uri . '.foo.' . $this->image_extension);
  669. // Reset the hook counters to get rid of the 'move' we just called.
  670. file_test_reset();
  671. $extensions = $this->image_extension;
  672. $edit = array(
  673. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  674. 'extensions' => $extensions,
  675. );
  676. $munged_filename = $this->image->filename;
  677. $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
  678. $munged_filename .= '_.' . $this->image_extension;
  679. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  680. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  681. $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
  682. $this->assertRaw(t('File name is !filename', array('!filename' => $munged_filename)), 'File was successfully munged.');
  683. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  684. // Check that the correct hooks were called.
  685. $this->assertFileHooksCalled(array('validate', 'insert'));
  686. // Ensure we don't munge files if we're allowing any extension.
  687. // Reset the hook counters.
  688. file_test_reset();
  689. $edit = array(
  690. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  691. 'allow_all_extensions' => TRUE,
  692. );
  693. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  694. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  695. $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
  696. $this->assertRaw(t('File name is !filename', array('!filename' => $this->image->filename)), 'File was not munged when allowing any extension.');
  697. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  698. // Check that the correct hooks were called.
  699. $this->assertFileHooksCalled(array('validate', 'insert'));
  700. }
  701. /**
  702. * Test renaming when uploading over a file that already exists.
  703. */
  704. function testExistingRename() {
  705. $edit = array(
  706. 'file_test_replace' => FILE_EXISTS_RENAME,
  707. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  708. );
  709. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  710. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  711. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  712. // Check that the correct hooks were called.
  713. $this->assertFileHooksCalled(array('validate', 'insert'));
  714. }
  715. /**
  716. * Test replacement when uploading over a file that already exists.
  717. */
  718. function testExistingReplace() {
  719. $edit = array(
  720. 'file_test_replace' => FILE_EXISTS_REPLACE,
  721. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  722. );
  723. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  724. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  725. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  726. // Check that the correct hooks were called.
  727. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  728. }
  729. /**
  730. * Test for failure when uploading over a file that already exists.
  731. */
  732. function testExistingError() {
  733. $edit = array(
  734. 'file_test_replace' => FILE_EXISTS_ERROR,
  735. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  736. );
  737. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  738. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  739. $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
  740. // Check that the no hooks were called while failing.
  741. $this->assertFileHooksCalled(array());
  742. }
  743. /**
  744. * Test for no failures when not uploading a file.
  745. */
  746. function testNoUpload() {
  747. $this->drupalPost('file-test/upload', array(), t('Submit'));
  748. $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
  749. }
  750. }
  751. /**
  752. * Test the file_save_upload() function on remote filesystems.
  753. */
  754. class RemoteFileSaveUploadTest extends FileSaveUploadTest {
  755. public static function getInfo() {
  756. $info = parent::getInfo();
  757. $info['group'] = 'File API (remote)';
  758. return $info;
  759. }
  760. function setUp() {
  761. parent::setUp('file_test');
  762. variable_set('file_default_scheme', 'dummy-remote');
  763. }
  764. }
  765. /**
  766. * Directory related tests.
  767. */
  768. class FileDirectoryTest extends FileTestCase {
  769. public static function getInfo() {
  770. return array(
  771. 'name' => 'File paths and directories',
  772. 'description' => 'Tests operations dealing with directories.',
  773. 'group' => 'File API',
  774. );
  775. }
  776. /**
  777. * Test directory handling functions.
  778. */
  779. function testFileCheckDirectoryHandling() {
  780. // A directory to operate on.
  781. $directory = file_default_scheme() . '://' . $this->randomName() . '/' . $this->randomName();
  782. $this->assertFalse(is_dir($directory), 'Directory does not exist prior to testing.');
  783. // Non-existent directory.
  784. $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for non-existing directory.', 'File');
  785. // Make a directory.
  786. $this->assertTrue(file_prepare_directory($directory, FILE_CREATE_DIRECTORY), 'No error reported when creating a new directory.', 'File');
  787. // Make sure directory actually exists.
  788. $this->assertTrue(is_dir($directory), 'Directory actually exists.', 'File');
  789. if (substr(PHP_OS, 0, 3) != 'WIN') {
  790. // PHP on Windows doesn't support any kind of useful read-only mode for
  791. // directories. When executing a chmod() on a directory, PHP only sets the
  792. // read-only flag, which doesn't prevent files to actually be written
  793. // in the directory on any recent version of Windows.
  794. // Make directory read only.
  795. @drupal_chmod($directory, 0444);
  796. $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for a non-writeable directory.', 'File');
  797. // Test directory permission modification.
  798. $this->assertTrue(file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS), 'No error reported when making directory writeable.', 'File');
  799. }
  800. // Test that the directory has the correct permissions.
  801. $this->assertDirectoryPermissions($directory, variable_get('file_chmod_directory', 0775));
  802. // Remove .htaccess file to then test that it gets re-created.
  803. @drupal_unlink(file_default_scheme() . '://.htaccess');
  804. $this->assertFalse(is_file(file_default_scheme() . '://.htaccess'), 'Successfully removed the .htaccess file in the files directory.', 'File');
  805. file_ensure_htaccess();
  806. $this->assertTrue(is_file(file_default_scheme() . '://.htaccess'), 'Successfully re-created the .htaccess file in the files directory.', 'File');
  807. // Verify contents of .htaccess file.
  808. $file = file_get_contents(file_default_scheme() . '://.htaccess');
  809. $this->assertEqual($file, file_htaccess_lines(FALSE), 'The .htaccess file contains the proper content.', 'File');
  810. }
  811. /**
  812. * This will take a directory and path, and find a valid filepath that is not
  813. * taken by another file.
  814. */
  815. function testFileCreateNewFilepath() {
  816. // First we test against an imaginary file that does not exist in a
  817. // directory.
  818. $basename = 'xyz.txt';
  819. $directory = 'misc';
  820. $original = $directory . '/' . $basename;
  821. $path = file_create_filename($basename, $directory);
  822. $this->assertEqual($path, $original, format_string('New filepath %new equals %original.', array('%new' => $path, '%original' => $original)), 'File');
  823. // Then we test against a file that already exists within that directory.
  824. $basename = 'druplicon.png';
  825. $original = $directory . '/' . $basename;
  826. $expected = $directory . '/druplicon_0.png';
  827. $path = file_create_filename($basename, $directory);
  828. $this->assertEqual($path, $expected, format_string('Creating a new filepath from %original equals %new.', array('%new' => $path, '%original' => $original)), 'File');
  829. try {
  830. $filename = "a\xFFtest\x80€.txt";
  831. file_create_filename($filename, $directory);
  832. $this->fail('Expected exception not thrown');
  833. }
  834. catch (RuntimeException $e) {
  835. $this->assertEqual("Invalid filename '$filename'", $e->getMessage(), 'The invalid filename has been detected and RuntimeException has been thrown.');
  836. }
  837. // @TODO: Finally we copy a file into a directory several times, to ensure a properly iterating filename suffix.
  838. }
  839. /**
  840. * This will test the filepath for a destination based on passed flags and
  841. * whether or not the file exists.
  842. *
  843. * If a file exists, file_destination($destination, $replace) will either
  844. * return:
  845. * - the existing filepath, if $replace is FILE_EXISTS_REPLACE
  846. * - a new filepath if FILE_EXISTS_RENAME
  847. * - an error (returning FALSE) if FILE_EXISTS_ERROR.
  848. * If the file doesn't currently exist, then it will simply return the
  849. * filepath.
  850. */
  851. function testFileDestination() {
  852. // First test for non-existent file.
  853. $destination = 'misc/xyz.txt';
  854. $path = file_destination($destination, FILE_EXISTS_REPLACE);
  855. $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_REPLACE.', 'File');
  856. $path = file_destination($destination, FILE_EXISTS_RENAME);
  857. $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_RENAME.', 'File');
  858. $path = file_destination($destination, FILE_EXISTS_ERROR);
  859. $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_ERROR.', 'File');
  860. $destination = 'misc/druplicon.png';
  861. $path = file_destination($destination, FILE_EXISTS_REPLACE);
  862. $this->assertEqual($path, $destination, 'Existing filepath destination remains the same with FILE_EXISTS_REPLACE.', 'File');
  863. $path = file_destination($destination, FILE_EXISTS_RENAME);
  864. $this->assertNotEqual($path, $destination, 'A new filepath destination is created when filepath destination already exists with FILE_EXISTS_RENAME.', 'File');
  865. $path = file_destination($destination, FILE_EXISTS_ERROR);
  866. $this->assertEqual($path, FALSE, 'An error is returned when filepath destination already exists with FILE_EXISTS_ERROR.', 'File');
  867. try {
  868. file_destination("core/misc/a\xFFtest\x80€.txt", FILE_EXISTS_REPLACE);
  869. $this->fail('Expected exception not thrown');
  870. }
  871. catch (RuntimeException $e) {
  872. $this->assertEqual("Invalid filename 'a\xFFtest\x80€.txt'", $e->getMessage(), 'The invalid destination has been detected and RuntimeException has been thrown.');
  873. }
  874. }
  875. /**
  876. * Ensure that the file_directory_temp() function always returns a value.
  877. */
  878. function testFileDirectoryTemp() {
  879. // Start with an empty variable to ensure we have a clean slate.
  880. variable_set('file_temporary_path', '');
  881. $tmp_directory = file_directory_temp();
  882. $this->assertEqual(empty($tmp_directory), FALSE, 'file_directory_temp() returned a non-empty value.');
  883. $setting = variable_get('file_temporary_path', '');
  884. $this->assertEqual($setting, $tmp_directory, "The 'file_temporary_path' variable has the same value that file_directory_temp() returned.");
  885. }
  886. }
  887. /**
  888. * Directory related tests.
  889. */
  890. class RemoteFileDirectoryTest extends FileDirectoryTest {
  891. public static function getInfo() {
  892. $info = parent::getInfo();
  893. $info['group'] = 'File API (remote)';
  894. return $info;
  895. }
  896. function setUp() {
  897. parent::setUp('file_test');
  898. variable_set('file_default_scheme', 'dummy-remote');
  899. }
  900. }
  901. /**
  902. * Tests the file_scan_directory() function.
  903. */
  904. class FileScanDirectoryTest extends FileTestCase {
  905. public static function getInfo() {
  906. return array(
  907. 'name' => 'File scan directory',
  908. 'description' => 'Tests the file_scan_directory() function.',
  909. 'group' => 'File API',
  910. );
  911. }
  912. function setUp() {
  913. parent::setUp();
  914. $this->path = drupal_get_path('module', 'simpletest') . '/files';
  915. }
  916. /**
  917. * Check the format of the returned values.
  918. */
  919. function testReturn() {
  920. // Grab a listing of all the JavaSscript files and check that they're
  921. // passed to the callback.
  922. $all_files = file_scan_directory($this->path, '/^javascript-/');
  923. ksort($all_files);
  924. $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
  925. // Check the first file.
  926. $file = reset($all_files);
  927. $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the first returned file.');
  928. $this->assertEqual($file->uri, $this->path . '/javascript-1.txt', 'First file name was set correctly.');
  929. $this->assertEqual($file->filename, 'javascript-1.txt', 'First basename was set correctly');
  930. $this->assertEqual($file->name, 'javascript-1', 'First name was set correctly.');
  931. // Check the second file.
  932. $file = next($all_files);
  933. $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the second returned file.');
  934. $this->assertEqual($file->uri, $this->path . '/javascript-2.script', 'Second file name was set correctly.');
  935. $this->assertEqual($file->filename, 'javascript-2.script', 'Second basename was set correctly');
  936. $this->assertEqual($file->name, 'javascript-2', 'Second name was set correctly.');
  937. }
  938. /**
  939. * Check that the callback function is called correctly.
  940. */
  941. function testOptionCallback() {
  942. // When nothing is matched nothing should be passed to the callback.
  943. $all_files = file_scan_directory($this->path, '/^NONEXISTINGFILENAME/', array('callback' => 'file_test_file_scan_callback'));
  944. $this->assertEqual(0, count($all_files), 'No files were found.');
  945. $results = file_test_file_scan_callback();
  946. file_test_file_scan_callback_reset();
  947. $this->assertEqual(0, count($results), 'No files were passed to the callback.');
  948. // Grab a listing of all the JavaSscript files and check that they're
  949. // passed to the callback.
  950. $all_files = file_scan_directory($this->path, '/^javascript-/', array('callback' => 'file_test_file_scan_callback'));
  951. $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
  952. $results = file_test_file_scan_callback();
  953. file_test_file_scan_callback_reset();
  954. $this->assertEqual(2, count($results), 'Files were passed to the callback.');
  955. }
  956. /**
  957. * Check that the no-mask parameter is honored.
  958. */
  959. function testOptionNoMask() {
  960. // Grab a listing of all the JavaSscript files.
  961. $all_files = file_scan_directory($this->path, '/^javascript-/');
  962. $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
  963. // Now use the nomast parameter to filter out the .script file.
  964. $filtered_files = file_scan_directory($this->path, '/^javascript-/', array('nomask' => '/.script$/'));
  965. $this->assertEqual(1, count($filtered_files), 'Filtered correctly.');
  966. }
  967. /**
  968. * Check that key parameter sets the return value's key.
  969. */
  970. function testOptionKey() {
  971. // "filename", for the path starting with $dir.
  972. $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
  973. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filepath')));
  974. sort($actual);
  975. $this->assertEqual($expected, $actual, 'Returned the correct values for the filename key.');
  976. // "basename", for the basename of the file.
  977. $expected = array('javascript-1.txt', 'javascript-2.script');
  978. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filename')));
  979. sort($actual);
  980. $this->assertEqual($expected, $actual, 'Returned the correct values for the basename key.');
  981. // "name" for the name of the file without an extension.
  982. $expected = array('javascript-1', 'javascript-2');
  983. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'name')));
  984. sort($actual);
  985. $this->assertEqual($expected, $actual, 'Returned the correct values for the name key.');
  986. // Invalid option that should default back to "filename".
  987. $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
  988. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'INVALID')));
  989. sort($actual);
  990. $this->assertEqual($expected, $actual, 'An invalid key defaulted back to the default.');
  991. }
  992. /**
  993. * Check that the recurse option decends into subdirectories.
  994. */
  995. function testOptionRecurse() {
  996. $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => FALSE));
  997. $this->assertTrue(empty($files), "Without recursion couldn't find javascript files.");
  998. $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => TRUE));
  999. $this->assertEqual(2, count($files), 'With recursion we found the expected javascript files.');
  1000. }
  1001. /**
  1002. * Check that the min_depth options lets us ignore files in the starting
  1003. * directory.
  1004. */
  1005. function testOptionMinDepth() {
  1006. $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 0));
  1007. $this->assertEqual(2, count($files), 'No minimum-depth gets files in current directory.');
  1008. $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 1));
  1009. $this->assertTrue(empty($files), "Minimum-depth of 1 successfully excludes files from current directory.");
  1010. }
  1011. }
  1012. /**
  1013. * Tests the file_scan_directory() function on remote filesystems.
  1014. */
  1015. class RemoteFileScanDirectoryTest extends FileScanDirectoryTest {
  1016. public static function getInfo() {
  1017. $info = parent::getInfo();
  1018. $info['group'] = 'File API (remote)';
  1019. return $info;
  1020. }
  1021. function setUp() {
  1022. parent::setUp('file_test');
  1023. variable_set('file_default_scheme', 'dummy-remote');
  1024. }
  1025. }
  1026. /**
  1027. * Deletion related tests.
  1028. */
  1029. class FileUnmanagedDeleteTest extends FileTestCase {
  1030. public static function getInfo() {
  1031. return array(
  1032. 'name' => 'Unmanaged file delete',
  1033. 'description' => 'Tests the unmanaged file delete function.',
  1034. 'group' => 'File API',
  1035. );
  1036. }
  1037. /**
  1038. * Delete a normal file.
  1039. */
  1040. function testNormal() {
  1041. // Create a file for testing
  1042. $file = $this->createFile();
  1043. // Delete a regular file
  1044. $this->assertTrue(file_unmanaged_delete($file->uri), 'Deleted worked.');
  1045. $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
  1046. }
  1047. /**
  1048. * Try deleting a missing file.
  1049. */
  1050. function testMissing() {
  1051. // Try to delete a non-existing file
  1052. $this->assertTrue(file_unmanaged_delete(file_default_scheme() . '/' . $this->randomName()), 'Returns true when deleting a non-existent file.');
  1053. }
  1054. /**
  1055. * Try deleting a directory.
  1056. */
  1057. function testDirectory() {
  1058. // A directory to operate on.
  1059. $directory = $this->createDirectory();
  1060. // Try to delete a directory
  1061. $this->assertFalse(file_unmanaged_delete($directory), 'Could not delete the delete directory.');
  1062. $this->assertTrue(file_exists($directory), 'Directory has not been deleted.');
  1063. }
  1064. }
  1065. /**
  1066. * Deletion related tests on remote filesystems.
  1067. */
  1068. class RemoteFileUnmanagedDeleteTest extends FileUnmanagedDeleteTest {
  1069. public static function getInfo() {
  1070. $info = parent::getInfo();
  1071. $info['group'] = 'File API (remote)';
  1072. return $info;
  1073. }
  1074. function setUp() {
  1075. parent::setUp('file_test');
  1076. variable_set('file_default_scheme', 'dummy-remote');
  1077. }
  1078. }
  1079. /**
  1080. * Deletion related tests.
  1081. */
  1082. class FileUnmanagedDeleteRecursiveTest extends FileTestCase {
  1083. public static function getInfo() {
  1084. return array(
  1085. 'name' => 'Unmanaged recursive file delete',
  1086. 'description' => 'Tests the unmanaged file delete recursive function.',
  1087. 'group' => 'File API',
  1088. );
  1089. }
  1090. /**
  1091. * Delete a normal file.
  1092. */
  1093. function testSingleFile() {
  1094. // Create a file for testing
  1095. $filepath = file_default_scheme() . '://' . $this->randomName();
  1096. file_put_contents($filepath, '');
  1097. // Delete the file.
  1098. $this->assertTrue(file_unmanaged_delete_recursive($filepath), 'Function reported success.');
  1099. $this->assertFalse(file_exists($filepath), 'Test file has been deleted.');
  1100. }
  1101. /**
  1102. * Try deleting an empty directory.
  1103. */
  1104. function testEmptyDirectory() {
  1105. // A directory to operate on.
  1106. $directory = $this->createDirectory();
  1107. // Delete the directory.
  1108. $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
  1109. $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
  1110. }
  1111. /**
  1112. * Try deleting a directory with some files.
  1113. */
  1114. function testDirectory() {
  1115. // A directory to operate on.
  1116. $directory = $this->createDirectory();
  1117. $filepathA = $directory . '/A';
  1118. $filepathB = $directory . '/B';
  1119. file_put_contents($filepathA, '');
  1120. file_put_contents($filepathB, '');
  1121. // Delete the directory.
  1122. $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
  1123. $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
  1124. $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
  1125. $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
  1126. }
  1127. /**
  1128. * Try deleting subdirectories with some files.
  1129. */
  1130. function testSubDirectory() {
  1131. // A directory to operate on.
  1132. $directory = $this->createDirectory();
  1133. $subdirectory = $this->createDirectory($directory . '/sub');
  1134. $filepathA = $directory . '/A';
  1135. $filepathB = $subdirectory . '/B';
  1136. file_put_contents($filepathA, '');
  1137. file_put_contents($filepathB, '');
  1138. // Delete the directory.
  1139. $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
  1140. $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
  1141. $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
  1142. $this->assertFalse(file_exists($subdirectory), 'Subdirectory has been deleted.');
  1143. $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
  1144. }
  1145. }
  1146. /**
  1147. * Deletion related tests on remote filesystems.
  1148. */
  1149. class RemoteFileUnmanagedDeleteRecursiveTest extends FileUnmanagedDeleteRecursiveTest {
  1150. public static function getInfo() {
  1151. $info = parent::getInfo();
  1152. $info['group'] = 'File API (remote)';
  1153. return $info;
  1154. }
  1155. function setUp() {
  1156. parent::setUp('file_test');
  1157. variable_set('file_default_scheme', 'dummy-remote');
  1158. }
  1159. }
  1160. /**
  1161. * Unmanaged move related tests.
  1162. */
  1163. class FileUnmanagedMoveTest extends FileTestCase {
  1164. public static function getInfo() {
  1165. return array(
  1166. 'name' => 'Unmanaged file moving',
  1167. 'description' => 'Tests the unmanaged file move function.',
  1168. 'group' => 'File API',
  1169. );
  1170. }
  1171. /**
  1172. * Move a normal file.
  1173. */
  1174. function testNormal() {
  1175. // Create a file for testing
  1176. $file = $this->createFile();
  1177. // Moving to a new name.
  1178. $desired_filepath = 'public://' . $this->randomName();
  1179. $new_filepath = file_unmanaged_move($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
  1180. $this->assertTrue($new_filepath, 'Move was successful.');
  1181. $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
  1182. $this->assertTrue(file_exists($new_filepath), 'File exists at the new location.');
  1183. $this->assertFalse(file_exists($file->uri), 'No file remains at the old location.');
  1184. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1185. // Moving with rename.
  1186. $desired_filepath = 'public://' . $this->randomName();
  1187. $this->assertTrue(file_exists($new_filepath), 'File exists before moving.');
  1188. $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
  1189. $newer_filepath = file_unmanaged_move($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
  1190. $this->assertTrue($newer_filepath, 'Move was successful.');
  1191. $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
  1192. $this->assertTrue(file_exists($newer_filepath), 'File exists at the new location.');
  1193. $this->assertFalse(file_exists($new_filepath), 'No file remains at the old location.');
  1194. $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
  1195. // TODO: test moving to a directory (rather than full directory/file path)
  1196. // TODO: test creating and moving normal files (rather than streams)
  1197. }
  1198. /**
  1199. * Try to move a missing file.
  1200. */
  1201. function testMissing() {
  1202. // Move non-existent file.
  1203. $new_filepath = file_unmanaged_move($this->randomName(), $this->randomName());
  1204. $this->assertFalse($new_filepath, 'Moving a missing file fails.');
  1205. }
  1206. /**
  1207. * Try to move a file onto itself.
  1208. */
  1209. function testOverwriteSelf() {
  1210. // Create a file for testing.
  1211. $file = $this->createFile();
  1212. // Move the file onto itself without renaming shouldn't make changes.
  1213. $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_REPLACE);
  1214. $this->assertFalse($new_filepath, 'Moving onto itself without renaming fails.');
  1215. $this->assertTrue(file_exists($file->uri), 'File exists after moving onto itself.');
  1216. // Move the file onto itself with renaming will result in a new filename.
  1217. $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_RENAME);
  1218. $this->assertTrue($new_filepath, 'Moving onto itself with renaming works.');
  1219. $this->assertFalse(file_exists($file->uri), 'Original file has been removed.');
  1220. $this->assertTrue(file_exists($new_filepath), 'File exists after moving onto itself.');
  1221. }
  1222. }
  1223. /**
  1224. * Unmanaged move related tests on remote filesystems.
  1225. */
  1226. class RemoteFileUnmanagedMoveTest extends FileUnmanagedMoveTest {
  1227. public static function getInfo() {
  1228. $info = parent::getInfo();
  1229. $info['group'] = 'File API (remote)';
  1230. return $info;
  1231. }
  1232. function setUp() {
  1233. parent::setUp('file_test');
  1234. variable_set('file_default_scheme', 'dummy-remote');
  1235. }
  1236. }
  1237. /**
  1238. * Unmanaged copy related tests.
  1239. */
  1240. class FileUnmanagedCopyTest extends FileTestCase {
  1241. public static function getInfo() {
  1242. return array(
  1243. 'name' => 'Unmanaged file copying',
  1244. 'description' => 'Tests the unmanaged file copy function.',
  1245. 'group' => 'File API',
  1246. );
  1247. }
  1248. /**
  1249. * Copy a normal file.
  1250. */
  1251. function testNormal() {
  1252. // Create a file for testing
  1253. $file = $this->createFile();
  1254. // Copying to a new name.
  1255. $desired_filepath = 'public://' . $this->randomName();
  1256. $new_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
  1257. $this->assertTrue($new_filepath, 'Copy was successful.');
  1258. $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
  1259. $this->assertTrue(file_exists($file->uri), 'Original file remains.');
  1260. $this->assertTrue(file_exists($new_filepath), 'New file exists.');
  1261. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1262. // Copying with rename.
  1263. $desired_filepath = 'public://' . $this->randomName();
  1264. $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
  1265. $newer_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_RENAME);
  1266. $this->assertTrue($newer_filepath, 'Copy was successful.');
  1267. $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
  1268. $this->assertTrue(file_exists($file->uri), 'Original file remains.');
  1269. $this->assertTrue(file_exists($newer_filepath), 'New file exists.');
  1270. $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
  1271. // TODO: test copying to a directory (rather than full directory/file path)
  1272. // TODO: test copying normal files using normal paths (rather than only streams)
  1273. }
  1274. /**
  1275. * Copy a non-existent file.
  1276. */
  1277. function testNonExistent() {
  1278. // Copy non-existent file
  1279. $desired_filepath = $this->randomName();
  1280. $this->assertFalse(file_exists($desired_filepath), "Randomly named file doesn't exists.");
  1281. $new_filepath = file_unmanaged_copy($desired_filepath, $this->randomName());
  1282. $this->assertFalse($new_filepath, 'Copying a missing file fails.');
  1283. }
  1284. /**
  1285. * Copy a file onto itself.
  1286. */
  1287. function testOverwriteSelf() {
  1288. // Create a file for testing
  1289. $file = $this->createFile();
  1290. // Copy the file onto itself with renaming works.
  1291. $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_RENAME);
  1292. $this->assertTrue($new_filepath, 'Copying onto itself with renaming works.');
  1293. $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
  1294. $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
  1295. $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
  1296. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1297. // Copy the file onto itself without renaming fails.
  1298. $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_ERROR);
  1299. $this->assertFalse($new_filepath, 'Copying onto itself without renaming fails.');
  1300. $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
  1301. // Copy the file into same directory without renaming fails.
  1302. $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_ERROR);
  1303. $this->assertFalse($new_filepath, 'Copying onto itself fails.');
  1304. $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
  1305. // Copy the file into same directory with renaming works.
  1306. $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_RENAME);
  1307. $this->assertTrue($new_filepath, 'Copying into same directory works.');
  1308. $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
  1309. $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
  1310. $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
  1311. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1312. }
  1313. }
  1314. /**
  1315. * Unmanaged copy related tests on remote filesystems.
  1316. */
  1317. class RemoteFileUnmanagedCopyTest extends FileUnmanagedCopyTest {
  1318. public static function getInfo() {
  1319. $info = parent::getInfo();
  1320. $info['group'] = 'File API (remote)';
  1321. return $info;
  1322. }
  1323. function setUp() {
  1324. parent::setUp('file_test');
  1325. variable_set('file_default_scheme', 'dummy-remote');
  1326. }
  1327. }
  1328. /**
  1329. * Deletion related tests.
  1330. */
  1331. class FileDeleteTest extends FileHookTestCase {
  1332. public static function getInfo() {
  1333. return array(
  1334. 'name' => 'File delete',
  1335. 'description' => 'Tests the file delete function.',
  1336. 'group' => 'File API',
  1337. );
  1338. }
  1339. /**
  1340. * Tries deleting a normal file (as opposed to a directory, symlink, etc).
  1341. */
  1342. function testUnused() {
  1343. $file = $this->createFile();
  1344. // Check that deletion removes the file and database record.
  1345. $this->assertTrue(is_file($file->uri), 'File exists.');
  1346. $this->assertIdentical(file_delete($file), TRUE, 'Delete worked.');
  1347. $this->assertFileHooksCalled(array('delete'));
  1348. $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
  1349. $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
  1350. }
  1351. /**
  1352. * Tries deleting a file that is in use.
  1353. */
  1354. function testInUse() {
  1355. $file = $this->createFile();
  1356. file_usage_add($file, 'testing', 'test', 1);
  1357. file_usage_add($file, 'testing', 'test', 1);
  1358. file_usage_delete($file, 'testing', 'test', 1);
  1359. file_delete($file);
  1360. $usage = file_usage_list($file);
  1361. $this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.');
  1362. $this->assertTrue(file_exists($file->uri), 'File still exists on the disk.');
  1363. $this->assertTrue(file_load($file->fid), 'File still exists in the database.');
  1364. // Clear out the call to hook_file_load().
  1365. file_test_reset();
  1366. file_usage_delete($file, 'testing', 'test', 1);
  1367. file_delete($file);
  1368. $usage = file_usage_list($file);
  1369. $this->assertFileHooksCalled(array('delete'));
  1370. $this->assertTrue(empty($usage), 'File usage data was removed.');
  1371. $this->assertFalse(file_exists($file->uri), 'File has been deleted after its last usage was removed.');
  1372. $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
  1373. }
  1374. }
  1375. /**
  1376. * Move related tests
  1377. */
  1378. class FileMoveTest extends FileHookTestCase {
  1379. public static function getInfo() {
  1380. return array(
  1381. 'name' => 'File moving',
  1382. 'description' => 'Tests the file move function.',
  1383. 'group' => 'File API',
  1384. );
  1385. }
  1386. /**
  1387. * Move a normal file.
  1388. */
  1389. function testNormal() {
  1390. $contents = $this->randomName(10);
  1391. $source = $this->createFile(NULL, $contents);
  1392. $desired_filepath = 'public://' . $this->randomName();
  1393. // Clone the object so we don't have to worry about the function changing
  1394. // our reference copy.
  1395. $result = file_move(clone $source, $desired_filepath, FILE_EXISTS_ERROR);
  1396. // Check the return status and that the contents changed.
  1397. $this->assertTrue($result, 'File moved successfully.');
  1398. $this->assertFalse(file_exists($source->uri));
  1399. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
  1400. // Check that the correct hooks were called.
  1401. $this->assertFileHooksCalled(array('move', 'load', 'update'));
  1402. // Make sure we got the same file back.
  1403. $this->assertEqual($source->fid, $result->fid, format_string("Source file id's' %fid is unchanged after move.", array('%fid' => $source->fid)));
  1404. // Reload the file from the database and check that the changes were
  1405. // actually saved.
  1406. $loaded_file = file_load($result->fid, TRUE);
  1407. $this->assertTrue($loaded_file, 'File can be loaded from the database.');
  1408. $this->assertFileUnchanged($result, $loaded_file);
  1409. }
  1410. /**
  1411. * Test renaming when moving onto a file that already exists.
  1412. */
  1413. function testExistingRename() {
  1414. // Setup a file to overwrite.
  1415. $contents = $this->randomName(10);
  1416. $source = $this->createFile(NULL, $contents);
  1417. $target = $this->createFile();
  1418. $this->assertDifferentFile($source, $target);
  1419. // Clone the object so we don't have to worry about the function changing
  1420. // our reference copy.
  1421. $result = file_move(clone $source, $target->uri, FILE_EXISTS_RENAME);
  1422. // Check the return status and that the contents changed.
  1423. $this->assertTrue($result, 'File moved successfully.');
  1424. $this->assertFalse(file_exists($source->uri));
  1425. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
  1426. // Check that the correct hooks were called.
  1427. $this->assertFileHooksCalled(array('move', 'load', 'update'));
  1428. // Compare the returned value to what made it into the database.
  1429. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1430. // The target file should not have been altered.
  1431. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1432. // Make sure we end up with two distinct files afterwards.
  1433. $this->assertDifferentFile($target, $result);
  1434. // Compare the source and results.
  1435. $loaded_source = file_load($source->fid, TRUE);
  1436. $this->assertEqual($loaded_source->fid, $result->fid, "Returned file's id matches the source.");
  1437. $this->assertNotEqual($loaded_source->uri, $source->uri, 'Returned file path has changed from the original.');
  1438. }
  1439. /**
  1440. * Test replacement when moving onto a file that already exists.
  1441. */
  1442. function testExistingReplace() {
  1443. // Setup a file to overwrite.
  1444. $contents = $this->randomName(10);
  1445. $source = $this->createFile(NULL, $contents);
  1446. $target = $this->createFile();
  1447. $this->assertDifferentFile($source, $target);
  1448. // Clone the object so we don't have to worry about the function changing
  1449. // our reference copy.
  1450. $result = file_move(clone $source, $target->uri, FILE_EXISTS_REPLACE);
  1451. // Look at the results.
  1452. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
  1453. $this->assertFalse(file_exists($source->uri));
  1454. $this->assertTrue($result, 'File moved successfully.');
  1455. // Check that the correct hooks were called.
  1456. $this->assertFileHooksCalled(array('move', 'update', 'delete', 'load'));
  1457. // Reload the file from the database and check that the changes were
  1458. // actually saved.
  1459. $loaded_result = file_load($result->fid, TRUE);
  1460. $this->assertFileUnchanged($result, $loaded_result);
  1461. // Check that target was re-used.
  1462. $this->assertSameFile($target, $loaded_result);
  1463. // Source and result should be totally different.
  1464. $this->assertDifferentFile($source, $loaded_result);
  1465. }
  1466. /**
  1467. * Test replacement when moving onto itself.
  1468. */
  1469. function testExistingReplaceSelf() {
  1470. // Setup a file to overwrite.
  1471. $contents = $this->randomName(10);
  1472. $source = $this->createFile(NULL, $contents);
  1473. // Copy the file over itself. Clone the object so we don't have to worry
  1474. // about the function changing our reference copy.
  1475. $result = file_move(clone $source, $source->uri, FILE_EXISTS_REPLACE);
  1476. $this->assertFalse($result, 'File move failed.');
  1477. $this->assertEqual($contents, file_get_contents($source->uri), 'Contents of file were not altered.');
  1478. // Check that no hooks were called while failing.
  1479. $this->assertFileHooksCalled(array());
  1480. // Load the file from the database and make sure it is identical to what
  1481. // was returned.
  1482. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1483. }
  1484. /**
  1485. * Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
  1486. * specified.
  1487. */
  1488. function testExistingError() {
  1489. $contents = $this->randomName(10);
  1490. $source = $this->createFile();
  1491. $target = $this->createFile(NULL, $contents);
  1492. $this->assertDifferentFile($source, $target);
  1493. // Clone the object so we don't have to worry about the function changing
  1494. // our reference copy.
  1495. $result = file_move(clone $source, $target->uri, FILE_EXISTS_ERROR);
  1496. // Check the return status and that the contents did not change.
  1497. $this->assertFalse($result, 'File move failed.');
  1498. $this->assertTrue(file_exists($source->uri));
  1499. $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
  1500. // Check that no hooks were called while failing.
  1501. $this->assertFileHooksCalled(array());
  1502. // Load the file from the database and make sure it is identical to what
  1503. // was returned.
  1504. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1505. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1506. }
  1507. }
  1508. /**
  1509. * Copy related tests.
  1510. */
  1511. class FileCopyTest extends FileHookTestCase {
  1512. public static function getInfo() {
  1513. return array(
  1514. 'name' => 'File copying',
  1515. 'description' => 'Tests the file copy function.',
  1516. 'group' => 'File API',
  1517. );
  1518. }
  1519. /**
  1520. * Test file copying in the normal, base case.
  1521. */
  1522. function testNormal() {
  1523. $contents = $this->randomName(10);
  1524. $source = $this->createFile(NULL, $contents);
  1525. $desired_uri = 'public://' . $this->randomName();
  1526. // Clone the object so we don't have to worry about the function changing
  1527. // our reference copy.
  1528. $result = file_copy(clone $source, $desired_uri, FILE_EXISTS_ERROR);
  1529. // Check the return status and that the contents changed.
  1530. $this->assertTrue($result, 'File copied successfully.');
  1531. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
  1532. // Check that the correct hooks were called.
  1533. $this->assertFileHooksCalled(array('copy', 'insert'));
  1534. $this->assertDifferentFile($source, $result);
  1535. $this->assertEqual($result->uri, $desired_uri, 'The copied file object has the desired filepath.');
  1536. $this->assertTrue(file_exists($source->uri), 'The original file still exists.');
  1537. $this->assertTrue(file_exists($result->uri), 'The copied file exists.');
  1538. // Reload the file from the database and check that the changes were
  1539. // actually saved.
  1540. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1541. }
  1542. /**
  1543. * Test renaming when copying over a file that already exists.
  1544. */
  1545. function testExistingRename() {
  1546. // Setup a file to overwrite.
  1547. $contents = $this->randomName(10);
  1548. $source = $this->createFile(NULL, $contents);
  1549. $target = $this->createFile();
  1550. $this->assertDifferentFile($source, $target);
  1551. // Clone the object so we don't have to worry about the function changing
  1552. // our reference copy.
  1553. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_RENAME);
  1554. // Check the return status and that the contents changed.
  1555. $this->assertTrue($result, 'File copied successfully.');
  1556. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
  1557. $this->assertNotEqual($result->uri, $source->uri, 'Returned file path has changed from the original.');
  1558. // Check that the correct hooks were called.
  1559. $this->assertFileHooksCalled(array('copy', 'insert'));
  1560. // Load all the affected files to check the changes that actually made it
  1561. // to the database.
  1562. $loaded_source = file_load($source->fid, TRUE);
  1563. $loaded_target = file_load($target->fid, TRUE);
  1564. $loaded_result = file_load($result->fid, TRUE);
  1565. // Verify that the source file wasn't changed.
  1566. $this->assertFileUnchanged($source, $loaded_source);
  1567. // Verify that what was returned is what's in the database.
  1568. $this->assertFileUnchanged($result, $loaded_result);
  1569. // Make sure we end up with three distinct files afterwards.
  1570. $this->assertDifferentFile($loaded_source, $loaded_target);
  1571. $this->assertDifferentFile($loaded_target, $loaded_result);
  1572. $this->assertDifferentFile($loaded_source, $loaded_result);
  1573. }
  1574. /**
  1575. * Test replacement when copying over a file that already exists.
  1576. */
  1577. function testExistingReplace() {
  1578. // Setup a file to overwrite.
  1579. $contents = $this->randomName(10);
  1580. $source = $this->createFile(NULL, $contents);
  1581. $target = $this->createFile();
  1582. $this->assertDifferentFile($source, $target);
  1583. // Clone the object so we don't have to worry about the function changing
  1584. // our reference copy.
  1585. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_REPLACE);
  1586. // Check the return status and that the contents changed.
  1587. $this->assertTrue($result, 'File copied successfully.');
  1588. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
  1589. $this->assertDifferentFile($source, $result);
  1590. // Check that the correct hooks were called.
  1591. $this->assertFileHooksCalled(array('load', 'copy', 'update'));
  1592. // Load all the affected files to check the changes that actually made it
  1593. // to the database.
  1594. $loaded_source = file_load($source->fid, TRUE);
  1595. $loaded_target = file_load($target->fid, TRUE);
  1596. $loaded_result = file_load($result->fid, TRUE);
  1597. // Verify that the source file wasn't changed.
  1598. $this->assertFileUnchanged($source, $loaded_source);
  1599. // Verify that what was returned is what's in the database.
  1600. $this->assertFileUnchanged($result, $loaded_result);
  1601. // Target file was reused for the result.
  1602. $this->assertFileUnchanged($loaded_target, $loaded_result);
  1603. }
  1604. /**
  1605. * Test that copying over an existing file fails when FILE_EXISTS_ERROR is
  1606. * specified.
  1607. */
  1608. function testExistingError() {
  1609. $contents = $this->randomName(10);
  1610. $source = $this->createFile();
  1611. $target = $this->createFile(NULL, $contents);
  1612. $this->assertDifferentFile($source, $target);
  1613. // Clone the object so we don't have to worry about the function changing
  1614. // our reference copy.
  1615. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_ERROR);
  1616. // Check the return status and that the contents were not changed.
  1617. $this->assertFalse($result, 'File copy failed.');
  1618. $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
  1619. // Check that the correct hooks were called.
  1620. $this->assertFileHooksCalled(array());
  1621. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1622. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1623. }
  1624. }
  1625. /**
  1626. * Tests the file_load() function.
  1627. */
  1628. class FileLoadTest extends FileHookTestCase {
  1629. public static function getInfo() {
  1630. return array(
  1631. 'name' => 'File loading',
  1632. 'description' => 'Tests the file_load() function.',
  1633. 'group' => 'File API',
  1634. );
  1635. }
  1636. /**
  1637. * Try to load a non-existent file by fid.
  1638. */
  1639. function testLoadMissingFid() {
  1640. $this->assertFalse(file_load(-1), "Try to load an invalid fid fails.");
  1641. $this->assertFileHooksCalled(array());
  1642. }
  1643. /**
  1644. * Try to load a non-existent file by URI.
  1645. */
  1646. function testLoadMissingFilepath() {
  1647. $files = file_load_multiple(array(), array('uri' => 'foobar://misc/druplicon.png'));
  1648. $this->assertFalse(reset($files), "Try to load a file that doesn't exist in the database fails.");
  1649. $this->assertFileHooksCalled(array());
  1650. }
  1651. /**
  1652. * Try to load a non-existent file by status.
  1653. */
  1654. function testLoadInvalidStatus() {
  1655. $files = file_load_multiple(array(), array('status' => -99));
  1656. $this->assertFalse(reset($files), "Trying to load a file with an invalid status fails.");
  1657. $this->assertFileHooksCalled(array());
  1658. }
  1659. /**
  1660. * Load a single file and ensure that the correct values are returned.
  1661. */
  1662. function testSingleValues() {
  1663. // Create a new file object from scratch so we know the values.
  1664. $file = $this->createFile('druplicon.txt', NULL, 'public');
  1665. $by_fid_file = file_load($file->fid);
  1666. $this->assertFileHookCalled('load');
  1667. $this->assertTrue(is_object($by_fid_file), 'file_load() returned an object.');
  1668. $this->assertEqual($by_fid_file->fid, $file->fid, 'Loading by fid got the same fid.', 'File');
  1669. $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
  1670. $this->assertEqual($by_fid_file->filename, $file->filename, 'Loading by fid got the correct filename.', 'File');
  1671. $this->assertEqual($by_fid_file->filemime, $file->filemime, 'Loading by fid got the correct MIME type.', 'File');
  1672. $this->assertEqual($by_fid_file->status, $file->status, 'Loading by fid got the correct status.', 'File');
  1673. $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
  1674. }
  1675. /**
  1676. * This will test loading file data from the database.
  1677. */
  1678. function testMultiple() {
  1679. // Create a new file object.
  1680. $file = $this->createFile('druplicon.txt', NULL, 'public');
  1681. // Load by path.
  1682. file_test_reset();
  1683. $by_path_files = file_load_multiple(array(), array('uri' => $file->uri));
  1684. $this->assertFileHookCalled('load');
  1685. $this->assertEqual(1, count($by_path_files), 'file_load_multiple() returned an array of the correct size.');
  1686. $by_path_file = reset($by_path_files);
  1687. $this->assertTrue($by_path_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
  1688. $this->assertEqual($by_path_file->fid, $file->fid, 'Loading by filepath got the correct fid.', 'File');
  1689. // Load by fid.
  1690. file_test_reset();
  1691. $by_fid_files = file_load_multiple(array($file->fid), array());
  1692. $this->assertFileHookCalled('load');
  1693. $this->assertEqual(1, count($by_fid_files), 'file_load_multiple() returned an array of the correct size.');
  1694. $by_fid_file = reset($by_fid_files);
  1695. $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
  1696. $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
  1697. }
  1698. }
  1699. /**
  1700. * Tests the file_save() function.
  1701. */
  1702. class FileSaveTest extends FileHookTestCase {
  1703. public static function getInfo() {
  1704. return array(
  1705. 'name' => 'File saving',
  1706. 'description' => 'Tests the file_save() function.',
  1707. 'group' => 'File API',
  1708. );
  1709. }
  1710. function testFileSave() {
  1711. // Create a new file object.
  1712. $file = array(
  1713. 'uid' => 1,
  1714. 'filename' => 'druplicon.txt',
  1715. 'uri' => 'public://druplicon.txt',
  1716. 'filemime' => 'text/plain',
  1717. 'timestamp' => 1,
  1718. 'status' => FILE_STATUS_PERMANENT,
  1719. );
  1720. $file = (object) $file;
  1721. file_put_contents($file->uri, 'hello world');
  1722. // Save it, inserting a new record.
  1723. $saved_file = file_save($file);
  1724. // Check that the correct hooks were called.
  1725. $this->assertFileHooksCalled(array('insert'));
  1726. $this->assertNotNull($saved_file, 'Saving the file should give us back a file object.', 'File');
  1727. $this->assertTrue($saved_file->fid > 0, 'A new file ID is set when saving a new file to the database.', 'File');
  1728. $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
  1729. $this->assertNotNull($loaded_file, 'Record exists in the database.');
  1730. $this->assertEqual($loaded_file->status, $file->status, 'Status was saved correctly.');
  1731. $this->assertEqual($saved_file->filesize, filesize($file->uri), 'File size was set correctly.', 'File');
  1732. $this->assertTrue($saved_file->timestamp > 1, 'File size was set correctly.', 'File');
  1733. // Resave the file, updating the existing record.
  1734. file_test_reset();
  1735. $saved_file->status = 7;
  1736. $resaved_file = file_save($saved_file);
  1737. // Check that the correct hooks were called.
  1738. $this->assertFileHooksCalled(array('load', 'update'));
  1739. $this->assertEqual($resaved_file->fid, $saved_file->fid, 'The file ID of an existing file is not changed when updating the database.', 'File');
  1740. $this->assertTrue($resaved_file->timestamp >= $saved_file->timestamp, "Timestamp didn't go backwards.", 'File');
  1741. $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
  1742. $this->assertNotNull($loaded_file, 'Record still exists in the database.', 'File');
  1743. $this->assertEqual($loaded_file->status, $saved_file->status, 'Status was saved correctly.');
  1744. // Try to insert a second file with the same name apart from case insensitivity
  1745. // to ensure the 'uri' index allows for filenames with different cases.
  1746. $file = (object) array(
  1747. 'uid' => 1,
  1748. 'filename' => 'DRUPLICON.txt',
  1749. 'uri' => 'public://DRUPLICON.txt',
  1750. 'filemime' => 'text/plain',
  1751. 'timestamp' => 1,
  1752. 'status' => FILE_STATUS_PERMANENT,
  1753. );
  1754. file_put_contents($file->uri, 'hello world');
  1755. file_save($file);
  1756. }
  1757. }
  1758. /**
  1759. * Tests file usage functions.
  1760. */
  1761. class FileUsageTest extends FileTestCase {
  1762. public static function getInfo() {
  1763. return array(
  1764. 'name' => 'File usage',
  1765. 'description' => 'Tests the file usage functions.',
  1766. 'group' => 'File',
  1767. );
  1768. }
  1769. /**
  1770. * Tests file_usage_list().
  1771. */
  1772. function testGetUsage() {
  1773. $file = $this->createFile();
  1774. db_insert('file_usage')
  1775. ->fields(array(
  1776. 'fid' => $file->fid,
  1777. 'module' => 'testing',
  1778. 'type' => 'foo',
  1779. 'id' => 1,
  1780. 'count' => 1
  1781. ))
  1782. ->execute();
  1783. db_insert('file_usage')
  1784. ->fields(array(
  1785. 'fid' => $file->fid,
  1786. 'module' => 'testing',
  1787. 'type' => 'bar',
  1788. 'id' => 2,
  1789. 'count' => 2
  1790. ))
  1791. ->execute();
  1792. $usage = file_usage_list($file);
  1793. $this->assertEqual(count($usage['testing']), 2, 'Returned the correct number of items.');
  1794. $this->assertTrue(isset($usage['testing']['foo'][1]), 'Returned the correct id.');
  1795. $this->assertTrue(isset($usage['testing']['bar'][2]), 'Returned the correct id.');
  1796. $this->assertEqual($usage['testing']['foo'][1], 1, 'Returned the correct count.');
  1797. $this->assertEqual($usage['testing']['bar'][2], 2, 'Returned the correct count.');
  1798. }
  1799. /**
  1800. * Tests file_usage_add().
  1801. */
  1802. function testAddUsage() {
  1803. $file = $this->createFile();
  1804. file_usage_add($file, 'testing', 'foo', 1);
  1805. // Add the file twice to ensure that the count is incremented rather than
  1806. // creating additional records.
  1807. file_usage_add($file, 'testing', 'bar', 2);
  1808. file_usage_add($file, 'testing', 'bar', 2);
  1809. $usage = db_select('file_usage', 'f')
  1810. ->fields('f')
  1811. ->condition('f.fid', $file->fid)
  1812. ->execute()
  1813. ->fetchAllAssoc('id');
  1814. $this->assertEqual(count($usage), 2, 'Created two records');
  1815. $this->assertEqual($usage[1]->module, 'testing', 'Correct module');
  1816. $this->assertEqual($usage[2]->module, 'testing', 'Correct module');
  1817. $this->assertEqual($usage[1]->type, 'foo', 'Correct type');
  1818. $this->assertEqual($usage[2]->type, 'bar', 'Correct type');
  1819. $this->assertEqual($usage[1]->count, 1, 'Correct count');
  1820. $this->assertEqual($usage[2]->count, 2, 'Correct count');
  1821. }
  1822. /**
  1823. * Tests file_usage_delete().
  1824. */
  1825. function testRemoveUsage() {
  1826. $file = $this->createFile();
  1827. db_insert('file_usage')
  1828. ->fields(array(
  1829. 'fid' => $file->fid,
  1830. 'module' => 'testing',
  1831. 'type' => 'bar',
  1832. 'id' => 2,
  1833. 'count' => 3,
  1834. ))
  1835. ->execute();
  1836. // Normal decrement.
  1837. file_usage_delete($file, 'testing', 'bar', 2);
  1838. $count = db_select('file_usage', 'f')
  1839. ->fields('f', array('count'))
  1840. ->condition('f.fid', $file->fid)
  1841. ->execute()
  1842. ->fetchField();
  1843. $this->assertEqual(2, $count, 'The count was decremented correctly.');
  1844. // Multiple decrement and removal.
  1845. file_usage_delete($file, 'testing', 'bar', 2, 2);
  1846. $count = db_select('file_usage', 'f')
  1847. ->fields('f', array('count'))
  1848. ->condition('f.fid', $file->fid)
  1849. ->execute()
  1850. ->fetchField();
  1851. $this->assertIdentical(FALSE, $count, 'The count was removed entirely when empty.');
  1852. // Non-existent decrement.
  1853. file_usage_delete($file, 'testing', 'bar', 2);
  1854. $count = db_select('file_usage', 'f')
  1855. ->fields('f', array('count'))
  1856. ->condition('f.fid', $file->fid)
  1857. ->execute()
  1858. ->fetchField();
  1859. $this->assertIdentical(FALSE, $count, 'Decrementing non-exist record complete.');
  1860. }
  1861. }
  1862. /**
  1863. * Tests the file_validate() function..
  1864. */
  1865. class FileValidateTest extends FileHookTestCase {
  1866. public static function getInfo() {
  1867. return array(
  1868. 'name' => 'File validate',
  1869. 'description' => 'Tests the file_validate() function.',
  1870. 'group' => 'File API',
  1871. );
  1872. }
  1873. /**
  1874. * Test that the validators passed into are checked.
  1875. */
  1876. function testCallerValidation() {
  1877. $file = $this->createFile();
  1878. // Empty validators.
  1879. $this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.');
  1880. $this->assertFileHooksCalled(array('validate'));
  1881. // Use the file_test.module's test validator to ensure that passing tests
  1882. // return correctly.
  1883. file_test_reset();
  1884. file_test_set_return('validate', array());
  1885. $passing = array('file_test_validator' => array(array()));
  1886. $this->assertEqual(file_validate($file, $passing), array(), 'Validating passes.');
  1887. $this->assertFileHooksCalled(array('validate'));
  1888. // Now test for failures in validators passed in and by hook_validate.
  1889. file_test_reset();
  1890. file_test_set_return('validate', array('Epic fail'));
  1891. $failing = array('file_test_validator' => array(array('Failed', 'Badly')));
  1892. $this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), 'Validating returns errors.');
  1893. $this->assertFileHooksCalled(array('validate'));
  1894. }
  1895. }
  1896. /**
  1897. * Tests the file_save_data() function.
  1898. */
  1899. class FileSaveDataTest extends FileHookTestCase {
  1900. public static function getInfo() {
  1901. return array(
  1902. 'name' => 'File save data',
  1903. 'description' => 'Tests the file save data function.',
  1904. 'group' => 'File API',
  1905. );
  1906. }
  1907. /**
  1908. * Test the file_save_data() function when no filename is provided.
  1909. */
  1910. function testWithoutFilename() {
  1911. $contents = $this->randomName(8);
  1912. $result = file_save_data($contents);
  1913. $this->assertTrue($result, 'Unnamed file saved correctly.');
  1914. $this->assertEqual(file_default_scheme(), file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
  1915. $this->assertEqual($result->filename, drupal_basename($result->uri), "Filename was set to the file's basename.");
  1916. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
  1917. $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
  1918. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
  1919. // Check that the correct hooks were called.
  1920. $this->assertFileHooksCalled(array('insert'));
  1921. // Verify that what was returned is what's in the database.
  1922. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1923. }
  1924. /**
  1925. * Test the file_save_data() function when a filename is provided.
  1926. */
  1927. function testWithFilename() {
  1928. $contents = $this->randomName(8);
  1929. // Using filename with non-latin characters.
  1930. $filename = 'Текстовый файл.txt';
  1931. $result = file_save_data($contents, 'public://' . $filename);
  1932. $this->assertTrue($result, 'Unnamed file saved correctly.');
  1933. $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
  1934. $this->assertEqual($filename, drupal_basename($result->uri), 'File was named correctly.');
  1935. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
  1936. $this->assertEqual($result->filemime, 'text/plain', 'A MIME type was set.');
  1937. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
  1938. // Check that the correct hooks were called.
  1939. $this->assertFileHooksCalled(array('insert'));
  1940. // Verify that what was returned is what's in the database.
  1941. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1942. }
  1943. /**
  1944. * Test file_save_data() when renaming around an existing file.
  1945. */
  1946. function testExistingRename() {
  1947. // Setup a file to overwrite.
  1948. $existing = $this->createFile();
  1949. $contents = $this->randomName(8);
  1950. $result = file_save_data($contents, $existing->uri, FILE_EXISTS_RENAME);
  1951. $this->assertTrue($result, 'File saved successfully.');
  1952. $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
  1953. $this->assertEqual($result->filename, $existing->filename, 'Filename was set to the basename of the source, rather than that of the renamed file.');
  1954. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
  1955. $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
  1956. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
  1957. // Check that the correct hooks were called.
  1958. $this->assertFileHooksCalled(array('insert'));
  1959. // Ensure that the existing file wasn't overwritten.
  1960. $this->assertDifferentFile($existing, $result);
  1961. $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
  1962. // Verify that was returned is what's in the database.
  1963. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1964. }
  1965. /**
  1966. * Test file_save_data() when replacing an existing file.
  1967. */
  1968. function testExistingReplace() {
  1969. // Setup a file to overwrite.
  1970. $existing = $this->createFile();
  1971. $contents = $this->randomName(8);
  1972. $result = file_save_data($contents, $existing->uri, FILE_EXISTS_REPLACE);
  1973. $this->assertTrue($result, 'File saved successfully.');
  1974. $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
  1975. $this->assertEqual($result->filename, $existing->filename, 'Filename was set to the basename of the existing file, rather than preserving the original name.');
  1976. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
  1977. $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
  1978. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
  1979. // Check that the correct hooks were called.
  1980. $this->assertFileHooksCalled(array('load', 'update'));
  1981. // Verify that the existing file was re-used.
  1982. $this->assertSameFile($existing, $result);
  1983. // Verify that what was returned is what's in the database.
  1984. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1985. }
  1986. /**
  1987. * Test that file_save_data() fails overwriting an existing file.
  1988. */
  1989. function testExistingError() {
  1990. $contents = $this->randomName(8);
  1991. $existing = $this->createFile(NULL, $contents);
  1992. // Check the overwrite error.
  1993. $result = file_save_data('asdf', $existing->uri, FILE_EXISTS_ERROR);
  1994. $this->assertFalse($result, 'Overwriting a file fails when FILE_EXISTS_ERROR is specified.');
  1995. $this->assertEqual($contents, file_get_contents($existing->uri), 'Contents of existing file were unchanged.');
  1996. // Check that no hooks were called while failing.
  1997. $this->assertFileHooksCalled(array());
  1998. // Ensure that the existing file wasn't overwritten.
  1999. $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
  2000. }
  2001. }
  2002. /**
  2003. * Tests for download/file transfer functions.
  2004. */
  2005. class FileDownloadTest extends FileTestCase {
  2006. public static function getInfo() {
  2007. return array(
  2008. 'name' => 'File download',
  2009. 'description' => 'Tests for file download/transfer functions.',
  2010. 'group' => 'File API',
  2011. );
  2012. }
  2013. function setUp() {
  2014. parent::setUp('file_test');
  2015. // Clear out any hook calls.
  2016. file_test_reset();
  2017. }
  2018. /**
  2019. * Test the public file transfer system.
  2020. */
  2021. function testPublicFileTransfer() {
  2022. // Test generating an URL to a created file.
  2023. $file = $this->createFile();
  2024. $url = file_create_url($file->uri);
  2025. // URLs can't contain characters outside the ASCII set so $filename has to be
  2026. // encoded.
  2027. $filename = $GLOBALS['base_url'] . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . rawurlencode($file->filename);
  2028. $this->assertEqual($filename, $url, 'Correctly generated a URL for a created file.');
  2029. $this->drupalHead($url);
  2030. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the created file.');
  2031. // Test generating an URL to a shipped file (i.e. a file that is part of
  2032. // Drupal core, a module or a theme, for example a JavaScript file).
  2033. $filepath = 'misc/jquery.js';
  2034. $url = file_create_url($filepath);
  2035. $this->assertEqual($GLOBALS['base_url'] . '/' . $filepath, $url, 'Correctly generated a URL for a shipped file.');
  2036. $this->drupalHead($url);
  2037. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  2038. }
  2039. /**
  2040. * Test the private file transfer system.
  2041. */
  2042. function testPrivateFileTransfer() {
  2043. // Set file downloads to private so handler functions get called.
  2044. // Create a file.
  2045. $contents = $this->randomName(8);
  2046. $file = $this->createFile(NULL, $contents, 'private');
  2047. $url = file_create_url($file->uri);
  2048. // Set file_test access header to allow the download.
  2049. file_test_set_return('download', array('x-foo' => 'Bar'));
  2050. $this->drupalGet($url);
  2051. $headers = $this->drupalGetHeaders();
  2052. $this->assertEqual($headers['x-foo'], 'Bar', 'Found header set by file_test module on private download.');
  2053. $this->assertResponse(200, 'Correctly allowed access to a file when file_test provides headers.');
  2054. // Test that the file transferred correctly.
  2055. $this->assertEqual($contents, $this->content, 'Contents of the file are correct.');
  2056. // Deny access to all downloads via a -1 header.
  2057. file_test_set_return('download', -1);
  2058. $this->drupalHead($url);
  2059. $this->assertResponse(403, 'Correctly denied access to a file when file_test sets the header to -1.');
  2060. // Try non-existent file.
  2061. $url = file_create_url('private://' . $this->randomName());
  2062. $this->drupalHead($url);
  2063. $this->assertResponse(404, 'Correctly returned 404 response for a non-existent file.');
  2064. }
  2065. /**
  2066. * Test file_create_url().
  2067. */
  2068. function testFileCreateUrl() {
  2069. global $base_url;
  2070. // Tilde (~) is excluded from this test because it is encoded by
  2071. // rawurlencode() in PHP 5.2 but not in PHP 5.3, as per RFC 3986.
  2072. // @see http://www.php.net/manual/en/function.rawurlencode.php#86506
  2073. $basename = " -._!$'\"()*@[]?&+%#,;=:\n\x00" . // "Special" ASCII characters.
  2074. "%23%25%26%2B%2F%3F" . // Characters that look like a percent-escaped string.
  2075. "éøïвβ中國書۞"; // Characters from various non-ASCII alphabets.
  2076. $basename_encoded = '%20-._%21%24%27%22%28%29%2A%40%5B%5D%3F%26%2B%25%23%2C%3B%3D%3A__' .
  2077. '%2523%2525%2526%252B%252F%253F' .
  2078. '%C3%A9%C3%B8%C3%AF%D0%B2%CE%B2%E4%B8%AD%E5%9C%8B%E6%9B%B8%DB%9E';
  2079. $this->checkUrl('public', '', $basename, $base_url . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . $basename_encoded);
  2080. $this->checkUrl('private', '', $basename, $base_url . '/system/files/' . $basename_encoded);
  2081. $this->checkUrl('private', '', $basename, $base_url . '/?q=system/files/' . $basename_encoded, '0');
  2082. }
  2083. /**
  2084. * Download a file from the URL generated by file_create_url().
  2085. *
  2086. * Create a file with the specified scheme, directory and filename; check that
  2087. * the URL generated by file_create_url() for the specified file equals the
  2088. * specified URL; fetch the URL and then compare the contents to the file.
  2089. *
  2090. * @param $scheme
  2091. * A scheme, e.g. "public"
  2092. * @param $directory
  2093. * A directory, possibly ""
  2094. * @param $filename
  2095. * A filename
  2096. * @param $expected_url
  2097. * The expected URL
  2098. * @param $clean_url
  2099. * The value of the clean_url setting
  2100. */
  2101. private function checkUrl($scheme, $directory, $filename, $expected_url, $clean_url = '1') {
  2102. variable_set('clean_url', $clean_url);
  2103. // Convert $filename to a valid filename, i.e. strip characters not
  2104. // supported by the filesystem, and create the file in the specified
  2105. // directory.
  2106. $filepath = file_create_filename($filename, $directory);
  2107. $directory_uri = $scheme . '://' . dirname($filepath);
  2108. file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
  2109. $file = $this->createFile($filepath, NULL, $scheme);
  2110. $url = file_create_url($file->uri);
  2111. $this->assertEqual($url, $expected_url, 'Generated URL matches expected URL.');
  2112. if ($scheme == 'private') {
  2113. // Tell the implementation of hook_file_download() in file_test.module
  2114. // that this file may be downloaded.
  2115. file_test_set_return('download', array('x-foo' => 'Bar'));
  2116. }
  2117. $this->drupalGet($url);
  2118. if ($this->assertResponse(200) == 'pass') {
  2119. $this->assertRaw(file_get_contents($file->uri), 'Contents of the file are correct.');
  2120. }
  2121. file_delete($file);
  2122. }
  2123. }
  2124. /**
  2125. * Tests for file URL rewriting.
  2126. */
  2127. class FileURLRewritingTest extends FileTestCase {
  2128. public static function getInfo() {
  2129. return array(
  2130. 'name' => 'File URL rewriting',
  2131. 'description' => 'Tests for file URL rewriting.',
  2132. 'group' => 'File',
  2133. );
  2134. }
  2135. function setUp() {
  2136. parent::setUp('file_test');
  2137. }
  2138. /**
  2139. * Test the generating of rewritten shipped file URLs.
  2140. */
  2141. function testShippedFileURL() {
  2142. // Test generating an URL to a shipped file (i.e. a file that is part of
  2143. // Drupal core, a module or a theme, for example a JavaScript file).
  2144. // Test alteration of file URLs to use a CDN.
  2145. variable_set('file_test_hook_file_url_alter', 'cdn');
  2146. $filepath = 'misc/jquery.js';
  2147. $url = file_create_url($filepath);
  2148. $this->assertEqual(FILE_URL_TEST_CDN_1 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
  2149. $filepath = 'misc/favicon.ico';
  2150. $url = file_create_url($filepath);
  2151. $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
  2152. // Test alteration of file URLs to use root-relative URLs.
  2153. variable_set('file_test_hook_file_url_alter', 'root-relative');
  2154. $filepath = 'misc/jquery.js';
  2155. $url = file_create_url($filepath);
  2156. $this->assertEqual(base_path() . '/' . $filepath, $url, 'Correctly generated a root-relative URL for a shipped file.');
  2157. $filepath = 'misc/favicon.ico';
  2158. $url = file_create_url($filepath);
  2159. $this->assertEqual(base_path() . '/' . $filepath, $url, 'Correctly generated a root-relative URL for a shipped file.');
  2160. // Test alteration of file URLs to use protocol-relative URLs.
  2161. variable_set('file_test_hook_file_url_alter', 'protocol-relative');
  2162. $filepath = 'misc/jquery.js';
  2163. $url = file_create_url($filepath);
  2164. $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
  2165. $filepath = 'misc/favicon.ico';
  2166. $url = file_create_url($filepath);
  2167. $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
  2168. }
  2169. /**
  2170. * Test the generating of rewritten public created file URLs.
  2171. */
  2172. function testPublicCreatedFileURL() {
  2173. // Test generating an URL to a created file.
  2174. // Test alteration of file URLs to use a CDN.
  2175. variable_set('file_test_hook_file_url_alter', 'cdn');
  2176. $file = $this->createFile();
  2177. $url = file_create_url($file->uri);
  2178. $public_directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  2179. $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a CDN URL for a created file.');
  2180. // Test alteration of file URLs to use root-relative URLs.
  2181. variable_set('file_test_hook_file_url_alter', 'root-relative');
  2182. $file = $this->createFile();
  2183. $url = file_create_url($file->uri);
  2184. $this->assertEqual(base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a root-relative URL for a created file.');
  2185. // Test alteration of file URLs to use a protocol-relative URLs.
  2186. variable_set('file_test_hook_file_url_alter', 'protocol-relative');
  2187. $file = $this->createFile();
  2188. $url = file_create_url($file->uri);
  2189. $this->assertEqual('/' . base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a protocol-relative URL for a created file.');
  2190. }
  2191. }
  2192. /**
  2193. * Tests for file_munge_filename() and file_unmunge_filename().
  2194. */
  2195. class FileNameMungingTest extends FileTestCase {
  2196. public static function getInfo() {
  2197. return array(
  2198. 'name' => 'File naming',
  2199. 'description' => 'Test filename munging and unmunging.',
  2200. 'group' => 'File API',
  2201. );
  2202. }
  2203. function setUp() {
  2204. parent::setUp();
  2205. $this->bad_extension = 'php';
  2206. $this->name = $this->randomName() . '.' . $this->bad_extension . '.txt';
  2207. $this->name_with_uc_ext = $this->randomName() . '.' . strtoupper($this->bad_extension) . '.txt';
  2208. }
  2209. /**
  2210. * Create a file and munge/unmunge the name.
  2211. */
  2212. function testMunging() {
  2213. // Disable insecure uploads.
  2214. variable_set('allow_insecure_uploads', 0);
  2215. $munged_name = file_munge_filename($this->name, '', TRUE);
  2216. $messages = drupal_get_messages();
  2217. $this->assertTrue(in_array(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $munged_name)), $messages['status']), 'Alert properly set when a file is renamed.');
  2218. $this->assertNotEqual($munged_name, $this->name, format_string('The new filename (%munged) has been modified from the original (%original)', array('%munged' => $munged_name, '%original' => $this->name)));
  2219. }
  2220. /**
  2221. * Tests munging with a null byte in the filename.
  2222. */
  2223. function testMungeNullByte() {
  2224. $prefix = $this->randomName();
  2225. $filename = $prefix . '.' . $this->bad_extension . "\0.txt";
  2226. $this->assertEqual(file_munge_filename($filename, ''), $prefix . '.' . $this->bad_extension . '_.txt', 'A filename with a null byte is correctly munged to remove the null byte.');
  2227. }
  2228. /**
  2229. * If the allow_insecure_uploads variable evaluates to true, the file should
  2230. * come out untouched, no matter how evil the filename.
  2231. */
  2232. function testMungeIgnoreInsecure() {
  2233. variable_set('allow_insecure_uploads', 1);
  2234. $munged_name = file_munge_filename($this->name, '');
  2235. $this->assertIdentical($munged_name, $this->name, format_string('The original filename (%original) matches the munged filename (%munged) when insecure uploads are enabled.', array('%munged' => $munged_name, '%original' => $this->name)));
  2236. }
  2237. /**
  2238. * White listed extensions are ignored by file_munge_filename().
  2239. */
  2240. function testMungeIgnoreWhitelisted() {
  2241. // Declare our extension as whitelisted. The declared extensions should
  2242. // be case insensitive so test using one with a different case.
  2243. $munged_name = file_munge_filename($this->name_with_uc_ext, $this->bad_extension);
  2244. $this->assertIdentical($munged_name, $this->name_with_uc_ext, format_string('The new filename (%munged) matches the original (%original) once the extension has been whitelisted.', array('%munged' => $munged_name, '%original' => $this->name_with_uc_ext)));
  2245. // The allowed extensions should also be normalized.
  2246. $munged_name = file_munge_filename($this->name, strtoupper($this->bad_extension));
  2247. $this->assertIdentical($munged_name, $this->name, format_string('The new filename (%munged) matches the original (%original) also when the whitelisted extension is in uppercase.', array('%munged' => $munged_name, '%original' => $this->name)));
  2248. }
  2249. /**
  2250. * Ensure that unmunge gets your name back.
  2251. */
  2252. function testUnMunge() {
  2253. $munged_name = file_munge_filename($this->name, '', FALSE);
  2254. $unmunged_name = file_unmunge_filename($munged_name);
  2255. $this->assertIdentical($unmunged_name, $this->name, format_string('The unmunged (%unmunged) filename matches the original (%original)', array('%unmunged' => $unmunged_name, '%original' => $this->name)));
  2256. }
  2257. }
  2258. /**
  2259. * Tests for file_get_mimetype().
  2260. */
  2261. class FileMimeTypeTest extends DrupalWebTestCase {
  2262. function setUp() {
  2263. parent::setUp('file_test');
  2264. }
  2265. public static function getInfo() {
  2266. return array(
  2267. 'name' => 'File mimetypes',
  2268. 'description' => 'Test filename mimetype detection.',
  2269. 'group' => 'File API',
  2270. );
  2271. }
  2272. /**
  2273. * Test mapping of mimetypes from filenames.
  2274. */
  2275. public function testFileMimeTypeDetection() {
  2276. $prefix = 'public://';
  2277. $test_case = array(
  2278. 'test.jar' => 'application/java-archive',
  2279. 'test.jpeg' => 'image/jpeg',
  2280. 'test.JPEG' => 'image/jpeg',
  2281. 'test.jpg' => 'image/jpeg',
  2282. 'test.jar.jpg' => 'image/jpeg',
  2283. 'test.jpg.jar' => 'application/java-archive',
  2284. 'test.pcf.Z' => 'application/x-font',
  2285. 'pcf.z' => 'application/octet-stream',
  2286. 'jar' => 'application/octet-stream',
  2287. 'some.junk' => 'application/octet-stream',
  2288. 'foo.file_test_1' => 'madeup/file_test_1',
  2289. 'foo.file_test_2' => 'madeup/file_test_2',
  2290. 'foo.doc' => 'madeup/doc',
  2291. 'test.ogg' => 'audio/ogg',
  2292. );
  2293. // Test using default mappings.
  2294. foreach ($test_case as $input => $expected) {
  2295. // Test stream [URI].
  2296. $output = file_get_mimetype($prefix . $input);
  2297. $this->assertIdentical($output, $expected, format_string('Mimetype for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2298. // Test normal path equivalent
  2299. $output = file_get_mimetype($input);
  2300. $this->assertIdentical($output, $expected, format_string('Mimetype (using default mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2301. }
  2302. // Now test passing in the map.
  2303. $mapping = array(
  2304. 'mimetypes' => array(
  2305. 0 => 'application/java-archive',
  2306. 1 => 'image/jpeg',
  2307. ),
  2308. 'extensions' => array(
  2309. 'jar' => 0,
  2310. 'jpg' => 1,
  2311. )
  2312. );
  2313. $test_case = array(
  2314. 'test.jar' => 'application/java-archive',
  2315. 'test.jpeg' => 'application/octet-stream',
  2316. 'test.jpg' => 'image/jpeg',
  2317. 'test.jar.jpg' => 'image/jpeg',
  2318. 'test.jpg.jar' => 'application/java-archive',
  2319. 'test.pcf.z' => 'application/octet-stream',
  2320. 'pcf.z' => 'application/octet-stream',
  2321. 'jar' => 'application/octet-stream',
  2322. 'some.junk' => 'application/octet-stream',
  2323. 'foo.file_test_1' => 'application/octet-stream',
  2324. 'foo.file_test_2' => 'application/octet-stream',
  2325. 'foo.doc' => 'application/octet-stream',
  2326. 'test.ogg' => 'application/octet-stream',
  2327. );
  2328. foreach ($test_case as $input => $expected) {
  2329. $output = file_get_mimetype($input, $mapping);
  2330. $this->assertIdentical($output, $expected, format_string('Mimetype (using passed-in mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2331. }
  2332. }
  2333. }
  2334. /**
  2335. * Tests stream wrapper functions.
  2336. */
  2337. class StreamWrapperTest extends DrupalWebTestCase {
  2338. protected $scheme = 'dummy';
  2339. protected $classname = 'DrupalDummyStreamWrapper';
  2340. public static function getInfo() {
  2341. return array(
  2342. 'name' => 'Stream wrappers',
  2343. 'description' => 'Tests stream wrapper functions.',
  2344. 'group' => 'File API',
  2345. );
  2346. }
  2347. function setUp() {
  2348. parent::setUp('file_test');
  2349. drupal_static_reset('file_get_stream_wrappers');
  2350. }
  2351. function tearDown() {
  2352. parent::tearDown();
  2353. stream_wrapper_unregister($this->scheme);
  2354. }
  2355. /**
  2356. * Test the getClassName() function.
  2357. */
  2358. function testGetClassName() {
  2359. // Check the dummy scheme.
  2360. $this->assertEqual($this->classname, file_stream_wrapper_get_class($this->scheme), 'Got correct class name for dummy scheme.');
  2361. // Check core's scheme.
  2362. $this->assertEqual('DrupalPublicStreamWrapper', file_stream_wrapper_get_class('public'), 'Got correct class name for public scheme.');
  2363. }
  2364. /**
  2365. * Test the file_stream_wrapper_get_instance_by_scheme() function.
  2366. */
  2367. function testGetInstanceByScheme() {
  2368. $instance = file_stream_wrapper_get_instance_by_scheme($this->scheme);
  2369. $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy scheme.');
  2370. $instance = file_stream_wrapper_get_instance_by_scheme('public');
  2371. $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public scheme.');
  2372. }
  2373. /**
  2374. * Test the URI and target functions.
  2375. */
  2376. function testUriFunctions() {
  2377. $instance = file_stream_wrapper_get_instance_by_uri($this->scheme . '://foo');
  2378. $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy URI.');
  2379. $instance = file_stream_wrapper_get_instance_by_uri('public://foo');
  2380. $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public URI.');
  2381. // Test file_uri_target().
  2382. $this->assertEqual(file_uri_target('public://foo/bar.txt'), 'foo/bar.txt', 'Got a valid stream target from public://foo/bar.txt.');
  2383. $this->assertFalse(file_uri_target('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
  2384. // Test file_build_uri() and DrupalLocalStreamWrapper::getDirectoryPath().
  2385. $this->assertEqual(file_build_uri('foo/bar.txt'), 'public://foo/bar.txt', 'Expected scheme was added.');
  2386. $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath(), variable_get('file_public_path'), 'Expected default directory path was returned.');
  2387. $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath(), variable_get('file_temporary_path'), 'Expected temporary directory path was returned.');
  2388. variable_set('file_default_scheme', 'private');
  2389. $this->assertEqual(file_build_uri('foo/bar.txt'), 'private://foo/bar.txt', 'Got a valid URI from foo/bar.txt.');
  2390. }
  2391. /**
  2392. * Test the scheme functions.
  2393. */
  2394. function testGetValidStreamScheme() {
  2395. $this->assertEqual('foo', file_uri_scheme('foo://pork//chops'), 'Got the correct scheme from foo://asdf');
  2396. $this->assertTrue(file_stream_wrapper_valid_scheme(file_uri_scheme('public://asdf')), 'Got a valid stream scheme from public://asdf');
  2397. $this->assertFalse(file_stream_wrapper_valid_scheme(file_uri_scheme('foo://asdf')), 'Did not get a valid stream scheme from foo://asdf');
  2398. }
  2399. /**
  2400. * Tests that phar stream wrapper is registered as expected.
  2401. *
  2402. * @see file_get_stream_wrappers()
  2403. */
  2404. public function testPharStreamWrapperRegistration() {
  2405. if (!class_exists('Phar', FALSE)) {
  2406. $this->assertFalse(in_array('phar', stream_get_wrappers(), TRUE), 'PHP is compiled without phar support. Therefore, no phar stream wrapper is registered.');
  2407. }
  2408. elseif (version_compare(PHP_VERSION, '5.3.3', '<')) {
  2409. $this->assertFalse(in_array('phar', stream_get_wrappers(), TRUE), 'The PHP version is <5.3.3. The built-in phar stream wrapper has been unregistered and not replaced.');
  2410. }
  2411. else {
  2412. $this->assertTrue(in_array('phar', stream_get_wrappers(), TRUE), 'A phar stream wrapper is registered.');
  2413. $this->assertFalse(file_stream_wrapper_valid_scheme('phar'), 'The phar scheme is not a valid scheme for Drupal File API usage.');
  2414. }
  2415. // Ensure that calling file_get_stream_wrappers() multiple times, both
  2416. // without and with a drupal_static_reset() in between, does not create
  2417. // errors due to the PharStreamWrapperManager singleton.
  2418. file_get_stream_wrappers();
  2419. file_get_stream_wrappers();
  2420. drupal_static_reset('file_get_stream_wrappers');
  2421. file_get_stream_wrappers();
  2422. }
  2423. /**
  2424. * Tests that only valid phar files can be used.
  2425. */
  2426. public function testPharFile() {
  2427. if (!in_array('phar', stream_get_wrappers(), TRUE)) {
  2428. $this->pass('There is no phar stream wrapper registered.');
  2429. // Nothing else in this test is relevant when there's no phar stream
  2430. // wrapper. testPharStreamWrapperRegistration() is sufficient for testing
  2431. // the conditions of when the stream wrapper should or should not be
  2432. // registered.
  2433. return;
  2434. }
  2435. $base = dirname(dirname(__FILE__)) . '/files';
  2436. // Ensure that file operations via the phar:// stream wrapper work for phar
  2437. // files with the .phar extension.
  2438. $this->assertFalse(file_exists("phar://$base/phar-1.phar/no-such-file.php"));
  2439. $this->assertTrue(file_exists("phar://$base/phar-1.phar/index.php"));
  2440. $file_contents = file_get_contents("phar://$base/phar-1.phar/index.php");
  2441. $expected_hash = 'c7e7904ea573c5ebea3ef00bb08c1f86af1a45961fbfbeb1892ff4a98fd73ad5';
  2442. $this->assertIdentical($expected_hash, hash('sha256', $file_contents));
  2443. // Ensure that file operations via the phar:// stream wrapper throw an
  2444. // exception for files without the .phar extension.
  2445. try {
  2446. file_exists("phar://$base/image-2.jpg/index.php");
  2447. $this->fail('Expected exception failed to be thrown when accessing an invalid phar file.');
  2448. }
  2449. catch (Exception $e) {
  2450. $this->assertEqual(get_class($e), 'TYPO3\PharStreamWrapper\Exception', 'Expected exception thrown when accessing an invalid phar file.');
  2451. }
  2452. }
  2453. }