tests.js 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  1. /*
  2. *
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. *
  20. */
  21. /* global exports, cordova, FileTransfer, FileTransferError, FileUploadOptions, LocalFileSystem */
  22. /* jshint jasmine: true */
  23. exports.defineAutoTests = function () {
  24. "use strict";
  25. // constants
  26. var ONE_SECOND = 1000; // in milliseconds
  27. var GRACE_TIME_DELTA = 600; // in milliseconds
  28. var DEFAULT_FILESYSTEM_SIZE = 1024 * 50; // filesystem size in bytes
  29. var UNKNOWN_HOST = "http://foobar.apache.org";
  30. var HEADERS_ECHO = "http://whatheaders.com"; // NOTE: this site is very useful!
  31. var DOWNLOAD_TIMEOUT = 7 * ONE_SECOND;
  32. var WINDOWS_UNKNOWN_HOST_TIMEOUT = 35 * ONE_SECOND;
  33. var UPLOAD_TIMEOUT = 7 * ONE_SECOND;
  34. var ABORT_DELAY = 100; // for abort() tests
  35. var LATIN1_SYMBOLS = '¥§©ÆÖÑøøø¼';
  36. var DATA_URI_PREFIX = "data:image/png;base64,";
  37. var DATA_URI_CONTENT = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
  38. var DATA_URI_CONTENT_LENGTH = 85; // bytes. (This is the raw file size: used https://en.wikipedia.org/wiki/File:Red-dot-5px.png from https://en.wikipedia.org/wiki/Data_URI_scheme)
  39. // config for upload test server
  40. // NOTE:
  41. // more info at https://github.com/apache/cordova-labs/tree/cordova-filetransfer
  42. var SERVER = "http://cordova-vm.apache.org:5000";
  43. var SERVER_WITH_CREDENTIALS = "http://cordova_user:cordova_password@cordova-vm.apache.org:5000";
  44. // flags
  45. var isWindows = cordova.platformId === "windows8" || cordova.platformId === "windows";
  46. var isWP8 = cordova.platformId === "windowsphone";
  47. var isBrowser = cordova.platformId === "browser";
  48. var isIE = isBrowser && navigator.userAgent.indexOf("Trident") >= 0;
  49. var isIos = cordova.platformId === "ios";
  50. // tests
  51. describe("FileTransferError", function () {
  52. it("should exist", function () {
  53. expect(FileTransferError).toBeDefined();
  54. });
  55. it("should be constructable", function () {
  56. var transferError = new FileTransferError();
  57. expect(transferError).toBeDefined();
  58. });
  59. it("filetransfer.spec.3 should expose proper constants", function () {
  60. expect(FileTransferError.FILE_NOT_FOUND_ERR).toBeDefined();
  61. expect(FileTransferError.INVALID_URL_ERR).toBeDefined();
  62. expect(FileTransferError.CONNECTION_ERR).toBeDefined();
  63. expect(FileTransferError.ABORT_ERR).toBeDefined();
  64. expect(FileTransferError.NOT_MODIFIED_ERR).toBeDefined();
  65. expect(FileTransferError.FILE_NOT_FOUND_ERR).toBe(1);
  66. expect(FileTransferError.INVALID_URL_ERR).toBe(2);
  67. expect(FileTransferError.CONNECTION_ERR).toBe(3);
  68. expect(FileTransferError.ABORT_ERR).toBe(4);
  69. expect(FileTransferError.NOT_MODIFIED_ERR).toBe(5);
  70. });
  71. });
  72. describe("FileUploadOptions", function () {
  73. it("should exist", function () {
  74. expect(FileUploadOptions).toBeDefined();
  75. });
  76. it("should be constructable", function () {
  77. var transferOptions = new FileUploadOptions();
  78. expect(transferOptions).toBeDefined();
  79. });
  80. });
  81. describe("FileTransfer", function () {
  82. this.persistentRoot = null;
  83. this.tempRoot = null;
  84. // named callbacks
  85. var unexpectedCallbacks = {
  86. httpFail: function () {},
  87. httpWin: function () {},
  88. fileSystemFail: function () {},
  89. fileSystemWin: function () {},
  90. fileOperationFail: function () {},
  91. fileOperationWin: function () {},
  92. };
  93. var expectedCallbacks = {
  94. unsupportedOperation: function (response) {
  95. console.log("spec called unsupported functionality; response:", response);
  96. },
  97. };
  98. // helpers
  99. var deleteFile = function (fileSystem, name, done) {
  100. fileSystem.getFile(name, null,
  101. function (fileEntry) {
  102. fileEntry.remove(
  103. function () {
  104. done();
  105. },
  106. function () {
  107. throw new Error("failed to delete: '" + name + "'");
  108. }
  109. );
  110. },
  111. function () {
  112. done();
  113. }
  114. );
  115. };
  116. var writeFile = function (fileSystem, name, content, success, done) {
  117. var fileOperationFail = function() {
  118. unexpectedCallbacks.fileOperationFail();
  119. done();
  120. };
  121. fileSystem.getFile(name, { create: true },
  122. function (fileEntry) {
  123. fileEntry.createWriter(function (writer) {
  124. writer.onwrite = function () {
  125. success(fileEntry);
  126. };
  127. writer.onabort = function (evt) {
  128. throw new Error("aborted creating test file '" + name + "': " + evt);
  129. };
  130. writer.error = function (evt) {
  131. throw new Error("aborted creating test file '" + name + "': " + evt);
  132. };
  133. if (cordova.platformId === "browser") {
  134. var blob = new Blob([content + "\n"], { type: "text/plain" });
  135. writer.write(blob);
  136. } else {
  137. writer.write(content + "\n");
  138. }
  139. }, fileOperationFail);
  140. },
  141. function () {
  142. throw new Error("could not create test file '" + name + "'");
  143. }
  144. );
  145. };
  146. // according to documentation, wp8 does not support onProgress:
  147. // https://github.com/apache/cordova-plugin-file-transfer/blob/master/doc/index.md#supported-platforms
  148. var wp8OnProgressHandler = function () {};
  149. var defaultOnProgressHandler = function (event) {
  150. if (event.lengthComputable) {
  151. expect(event.loaded).toBeGreaterThan(1);
  152. expect(event.total).toBeGreaterThan(0);
  153. expect(event.total).not.toBeLessThan(event.loaded);
  154. expect(event.lengthComputable).toBe(true, "lengthComputable");
  155. } else {
  156. // In IE, when lengthComputable === false, event.total somehow is equal to 2^64
  157. if (isIE) {
  158. expect(event.total).toBe(Math.pow(2, 64));
  159. } else {
  160. // iOS returns -1, and other platforms return 0
  161. expect(event.total).toBeLessThan(1);
  162. }
  163. }
  164. };
  165. var getMalformedUrl = function () {
  166. if (cordova.platformId === "android" || cordova.platformId === "amazon-fireos") {
  167. // bad protocol causes a MalformedUrlException on Android
  168. return "httpssss://example.com";
  169. } else {
  170. // iOS doesn't care about protocol, space in hostname causes error
  171. return "httpssss://exa mple.com";
  172. }
  173. };
  174. // NOTE:
  175. // there are several beforeEach calls, one per async call; since calling done()
  176. // signifies a completed async call, each async call needs its own done(), and
  177. // therefore its own beforeEach
  178. beforeEach(function (done) {
  179. var specContext = this;
  180. window.requestFileSystem(LocalFileSystem.PERSISTENT, DEFAULT_FILESYSTEM_SIZE,
  181. function (fileSystem) {
  182. specContext.persistentRoot = fileSystem.root;
  183. done();
  184. },
  185. function () {
  186. throw new Error("Failed to initialize persistent file system.");
  187. }
  188. );
  189. });
  190. beforeEach(function (done) {
  191. var specContext = this;
  192. window.requestFileSystem(LocalFileSystem.TEMPORARY, DEFAULT_FILESYSTEM_SIZE,
  193. function (fileSystem) {
  194. specContext.tempRoot = fileSystem.root;
  195. done();
  196. },
  197. function () {
  198. throw new Error("Failed to initialize temporary file system.");
  199. }
  200. );
  201. });
  202. // spy on all named callbacks
  203. beforeEach(function() {
  204. // ignore the actual implementations of the unexpected callbacks
  205. for (var callback in unexpectedCallbacks) {
  206. if (unexpectedCallbacks.hasOwnProperty(callback)) {
  207. spyOn(unexpectedCallbacks, callback);
  208. }
  209. }
  210. // but run the implementations of the expected callbacks
  211. for (callback in expectedCallbacks) { // jshint ignore: line
  212. if (expectedCallbacks.hasOwnProperty(callback)) {
  213. spyOn(expectedCallbacks, callback).and.callThrough();
  214. }
  215. }
  216. });
  217. // at the end, check that none of the unexpected callbacks got called,
  218. // and act on the expected callbacks
  219. afterEach(function() {
  220. for (var callback in unexpectedCallbacks) {
  221. if (unexpectedCallbacks.hasOwnProperty(callback)) {
  222. expect(unexpectedCallbacks[callback]).not.toHaveBeenCalled();
  223. }
  224. }
  225. if (expectedCallbacks.unsupportedOperation.calls.any()) {
  226. pending();
  227. }
  228. });
  229. it("should initialise correctly", function() {
  230. expect(this.persistentRoot).toBeDefined();
  231. expect(this.tempRoot).toBeDefined();
  232. });
  233. it("should exist", function () {
  234. expect(FileTransfer).toBeDefined();
  235. });
  236. it("filetransfer.spec.1 should be constructable", function () {
  237. var transfer = new FileTransfer();
  238. expect(transfer).toBeDefined();
  239. });
  240. it("filetransfer.spec.2 should expose proper functions", function () {
  241. var transfer = new FileTransfer();
  242. expect(transfer.upload).toBeDefined();
  243. expect(transfer.download).toBeDefined();
  244. expect(transfer.upload).toEqual(jasmine.any(Function));
  245. expect(transfer.download).toEqual(jasmine.any(Function));
  246. });
  247. describe("methods", function() {
  248. this.transfer = null;
  249. this.root = null;
  250. this.fileName = null;
  251. this.localFilePath = null;
  252. beforeEach(function() {
  253. this.transfer = new FileTransfer();
  254. // assign onprogress handler
  255. this.transfer.onprogress = isWP8 ? wp8OnProgressHandler : defaultOnProgressHandler;
  256. // spy on the onprogress handler, but still call through to it
  257. spyOn(this.transfer, "onprogress").and.callThrough();
  258. this.root = this.persistentRoot;
  259. this.fileName = "testFile.txt";
  260. this.localFilePath = this.root.toURL() + this.fileName;
  261. });
  262. // NOTE:
  263. // if download tests are failing, check the
  264. // URL white list for the following URLs:
  265. // - 'httpssss://example.com'
  266. // - 'apache.org', with subdomains="true"
  267. // - 'cordova-filetransfer.jitsu.com'
  268. describe("download", function () {
  269. // helpers
  270. var verifyDownload = function (fileEntry, specContext) {
  271. expect(fileEntry.name).toBe(specContext.fileName);
  272. };
  273. // delete the downloaded file
  274. afterEach(function (done) {
  275. deleteFile(this.root, this.fileName, done);
  276. });
  277. it("ensures that test file does not exist", function (done) {
  278. deleteFile(this.root, this.fileName, done);
  279. });
  280. it("filetransfer.spec.4 should download a file", function (done) {
  281. var fileURL = SERVER + "/robots.txt";
  282. var specContext = this;
  283. var fileWin = function (blob) {
  284. if (specContext.transfer.onprogress.calls.any()) {
  285. var lastProgressEvent = specContext.transfer.onprogress.calls.mostRecent().args[0];
  286. expect(lastProgressEvent.loaded).not.toBeGreaterThan(blob.size);
  287. } else {
  288. console.log("no progress events were emitted");
  289. }
  290. done();
  291. };
  292. var fileSystemFail = function() {
  293. unexpectedCallbacks.fileSystemFail();
  294. done();
  295. };
  296. var downloadFail = function() {
  297. unexpectedCallbacks.httpFail();
  298. done();
  299. };
  300. var downloadWin = function (entry) {
  301. verifyDownload(entry, specContext);
  302. // verify the FileEntry representing this file
  303. entry.file(fileWin, fileSystemFail);
  304. };
  305. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
  306. }, DOWNLOAD_TIMEOUT);
  307. it("filetransfer.spec.5 should download a file using http basic auth", function (done) {
  308. var fileURL = SERVER_WITH_CREDENTIALS + "/download_basic_auth";
  309. var specContext = this;
  310. var downloadWin = function (entry) {
  311. verifyDownload(entry, specContext);
  312. done();
  313. };
  314. var downloadFail = function() {
  315. unexpectedCallbacks.httpFail();
  316. done();
  317. };
  318. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
  319. }, DOWNLOAD_TIMEOUT);
  320. it("filetransfer.spec.6 should get 401 status on http basic auth failure", function (done) {
  321. // NOTE:
  322. // using server without credentials
  323. var fileURL = SERVER + "/download_basic_auth";
  324. var downloadFail = function (error) {
  325. expect(error.http_status).toBe(401);
  326. expect(error.http_status).not.toBe(404, "Ensure " + fileURL + " is in the white list");
  327. done();
  328. };
  329. var downloadWin = function() {
  330. unexpectedCallbacks.httpWin();
  331. done();
  332. };
  333. this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail, null,
  334. {
  335. headers: {
  336. "If-Modified-Since": "Thu, 19 Mar 2015 00:00:00 GMT"
  337. }
  338. });
  339. }, DOWNLOAD_TIMEOUT);
  340. it("filetransfer.spec.7 should download a file using file:// (when hosted from file://)", function (done) {
  341. // for Windows platform it's ms-appdata:/// by default, not file://
  342. if (isWindows) {
  343. pending();
  344. return;
  345. }
  346. var fileURL = window.location.protocol + "//" + window.location.pathname.replace(/ /g, "%20");
  347. var specContext = this;
  348. if (!/^file:/.exec(fileURL) && cordova.platformId !== "blackberry10") {
  349. if (cordova.platformId === "windowsphone") {
  350. expect(fileURL).toMatch(/^x-wmapp0:/);
  351. }
  352. done();
  353. return;
  354. }
  355. var downloadWin = function (entry) {
  356. verifyDownload(entry, specContext);
  357. done();
  358. };
  359. var downloadFail = function() {
  360. unexpectedCallbacks.httpFail();
  361. done();
  362. };
  363. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
  364. }, DOWNLOAD_TIMEOUT);
  365. it("filetransfer.spec.8 should download a file using https://", function (done) {
  366. var fileURL = "https://www.apache.org/licenses/";
  367. var specContext = this;
  368. var downloadFail = function() {
  369. unexpectedCallbacks.httpFail();
  370. done();
  371. };
  372. var fileOperationFail = function() {
  373. unexpectedCallbacks.fileOperationFail();
  374. done();
  375. };
  376. var fileSystemFail = function() {
  377. unexpectedCallbacks.fileSystemFail();
  378. done();
  379. };
  380. var fileWin = function (file) {
  381. var reader = new FileReader();
  382. reader.onerror = fileOperationFail;
  383. reader.onload = function () {
  384. expect(reader.result).toMatch(/The Apache Software Foundation/);
  385. done();
  386. };
  387. reader.readAsText(file);
  388. };
  389. var downloadWin = function (entry) {
  390. verifyDownload(entry, specContext);
  391. entry.file(fileWin, fileSystemFail);
  392. };
  393. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
  394. }, DOWNLOAD_TIMEOUT);
  395. it("filetransfer.spec.11 should call the error callback on abort()", function (done) {
  396. var fileURL = "http://cordova.apache.org/downloads/BlueZedEx.mp3";
  397. fileURL = fileURL + "?q=" + (new Date()).getTime();
  398. var specContext = this;
  399. var downloadWin = function () {
  400. unexpectedCallbacks.httpWin();
  401. done();
  402. };
  403. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, done);
  404. setTimeout(function() {
  405. specContext.transfer.abort();
  406. }, ABORT_DELAY);
  407. }, DOWNLOAD_TIMEOUT);
  408. it("filetransfer.spec.9 should not leave partial file due to abort", function (done) {
  409. var fileURL = "http://cordova.apache.org/downloads/logos_2.zip";
  410. var specContext = this;
  411. var fileSystemWin = function() {
  412. unexpectedCallbacks.fileSystemWin();
  413. done();
  414. };
  415. var downloadWin = function() {
  416. unexpectedCallbacks.httpWin();
  417. done();
  418. };
  419. var downloadFail = function (error) {
  420. var result = (error.code === FileTransferError.ABORT_ERR || error.code === FileTransferError.CONNECTION_ERR)? true: false;
  421. if (!result) {
  422. fail("Expected " + error.code + " to be " + FileTransferError.ABORT_ERR + " or " + FileTransferError.CONNECTION_ERR);
  423. }
  424. expect(specContext.transfer.onprogress).toHaveBeenCalled();
  425. // check that there is no file
  426. specContext.root.getFile(specContext.fileName, null, fileSystemWin, done);
  427. };
  428. // abort at the first onprogress event
  429. specContext.transfer.onprogress = function (event) {
  430. if (event.loaded > 0) {
  431. specContext.transfer.abort();
  432. }
  433. };
  434. spyOn(specContext.transfer, "onprogress").and.callThrough();
  435. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
  436. }, DOWNLOAD_TIMEOUT);
  437. it("filetransfer.spec.10 should be stopped by abort()", function (done) {
  438. var fileURL = "http://cordova.apache.org/downloads/BlueZedEx.mp3";
  439. fileURL = fileURL + "?q=" + (new Date()).getTime();
  440. var specContext = this;
  441. expect(specContext.transfer.abort).not.toThrow(); // should be a no-op.
  442. var downloadWin = function() {
  443. unexpectedCallbacks.httpWin();
  444. done();
  445. };
  446. var downloadFail = function (error) {
  447. expect(error.code).toBe(FileTransferError.ABORT_ERR);
  448. // delay calling done() to wait for the bogus abort()
  449. setTimeout(done, GRACE_TIME_DELTA * 2);
  450. };
  451. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
  452. setTimeout(function() {
  453. specContext.transfer.abort();
  454. }, ABORT_DELAY);
  455. // call abort() again, after a time greater than the grace period
  456. setTimeout(function () {
  457. expect(specContext.transfer.abort).not.toThrow();
  458. }, GRACE_TIME_DELTA);
  459. }, DOWNLOAD_TIMEOUT);
  460. it("filetransfer.spec.12 should get http status on failure", function (done) {
  461. var fileURL = SERVER + "/404";
  462. var downloadFail = function (error) {
  463. expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
  464. expect(error.http_status).toBe(404);
  465. // wp8 does not make difference between 404 and unknown host
  466. if (isWP8) {
  467. expect(error.code).toBe(FileTransferError.CONNECTION_ERR);
  468. } else {
  469. expect(error.code).toBe(FileTransferError.FILE_NOT_FOUND_ERR);
  470. }
  471. done();
  472. };
  473. var downloadWin = function() {
  474. unexpectedCallbacks.httpWin();
  475. done();
  476. };
  477. this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail);
  478. }, DOWNLOAD_TIMEOUT);
  479. it("filetransfer.spec.13 should get http body on failure", function (done) {
  480. var fileURL = SERVER + "/404";
  481. var downloadFail = function (error) {
  482. expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
  483. expect(error.http_status).toBe(404);
  484. expect(error.body).toBeDefined();
  485. expect(error.body).toMatch("You requested a 404");
  486. done();
  487. };
  488. var downloadWin = function() {
  489. unexpectedCallbacks.httpWin();
  490. done();
  491. };
  492. this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail);
  493. }, DOWNLOAD_TIMEOUT);
  494. it("filetransfer.spec.14 should handle malformed urls", function (done) {
  495. var fileURL = getMalformedUrl();
  496. var downloadFail = function (error) {
  497. // Note: Android needs the bad protocol to be added to the access list
  498. // <access origin=".*"/> won't match because ^https?:// is prepended to the regex
  499. // The bad protocol must begin with http to avoid automatic prefix
  500. expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
  501. expect(error.code).toBe(FileTransferError.INVALID_URL_ERR);
  502. done();
  503. };
  504. var downloadWin = function() {
  505. unexpectedCallbacks.httpWin();
  506. done();
  507. };
  508. this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail);
  509. });
  510. it("filetransfer.spec.15 should handle unknown host", function (done) {
  511. var fileURL = UNKNOWN_HOST;
  512. var downloadFail = function (error) {
  513. expect(error.code).toBe(FileTransferError.CONNECTION_ERR);
  514. done();
  515. };
  516. var downloadWin = function() {
  517. unexpectedCallbacks.httpWin();
  518. done();
  519. };
  520. // turn off the onprogress handler
  521. this.transfer.onprogress = function () {};
  522. this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail);
  523. }, isWindows ? WINDOWS_UNKNOWN_HOST_TIMEOUT : DOWNLOAD_TIMEOUT);
  524. it("filetransfer.spec.16 should handle bad file path", function (done) {
  525. var fileURL = SERVER;
  526. var downloadWin = function() {
  527. unexpectedCallbacks.httpWin();
  528. done();
  529. };
  530. this.transfer.download(fileURL, "c:\\54321", downloadWin, done);
  531. });
  532. it("filetransfer.spec.17 progress should work with gzip encoding", function (done) {
  533. // lengthComputable false on bb10 when downloading gzip
  534. if (cordova.platformId === "blackberry10") {
  535. pending();
  536. return;
  537. }
  538. var fileURL = "http://www.apache.org/";
  539. var specContext = this;
  540. var downloadWin = function (entry) {
  541. verifyDownload(entry, specContext);
  542. done();
  543. };
  544. var downloadFail = function () {
  545. unexpectedCallbacks.httpFail();
  546. done();
  547. };
  548. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin,downloadFail);
  549. }, DOWNLOAD_TIMEOUT);
  550. it("filetransfer.spec.30 downloaded file entries should have a toNativeURL method", function (done) {
  551. if (cordova.platformId === "browser") {
  552. pending();
  553. return;
  554. }
  555. var fileURL = SERVER + "/robots.txt";
  556. var downloadWin = function (entry) {
  557. expect(entry.toNativeURL).toBeDefined();
  558. expect(entry.toNativeURL).toEqual(jasmine.any(Function));
  559. var nativeURL = entry.toNativeURL();
  560. expect(nativeURL).toBeTruthy();
  561. expect(nativeURL).toEqual(jasmine.any(String));
  562. if (isWindows) {
  563. expect(nativeURL.substring(0, 14)).toBe("ms-appdata:///");
  564. } else if (isWP8) {
  565. expect(nativeURL.substring(0, 1)).toBe("/");
  566. } else {
  567. expect(nativeURL.substring(0, 7)).toBe("file://");
  568. }
  569. done();
  570. };
  571. var downloadFail = function() {
  572. unexpectedCallbacks.httpFail();
  573. done();
  574. };
  575. this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail);
  576. }, DOWNLOAD_TIMEOUT);
  577. it("filetransfer.spec.28 (compatibility) should be able to download a file using local paths", function (done) {
  578. var fileURL = SERVER + "/robots.txt";
  579. var specContext = this;
  580. var unsupported = function (response) {
  581. expectedCallbacks.unsupportedOperation(response);
  582. done();
  583. };
  584. var downloadWin = function (entry) {
  585. verifyDownload(entry, specContext);
  586. done();
  587. };
  588. var internalFilePath;
  589. if (specContext.root.toInternalURL) {
  590. internalFilePath = specContext.root.toInternalURL() + specContext.fileName;
  591. } else {
  592. internalFilePath = specContext.localFilePath;
  593. }
  594. var downloadFail = function() {
  595. unexpectedCallbacks.httpFail();
  596. done();
  597. };
  598. // This is an undocumented interface to File which exists only for testing
  599. // backwards compatibilty. By obtaining the raw filesystem path of the download
  600. // location, we can pass that to transfer.download() to make sure that previously-stored
  601. // paths are still valid.
  602. cordova.exec(function (localPath) {
  603. specContext.transfer.download(fileURL, localPath, downloadWin, downloadFail);
  604. }, unsupported, "File", "_getLocalFilesystemPath", [internalFilePath]);
  605. });
  606. it("filetransfer.spec.33 should properly handle 304", function (done) {
  607. if (isWP8) {
  608. pending();
  609. return;
  610. }
  611. var imageURL = "http://apache.org/images/feather-small.gif";
  612. var lastModified = new Date();
  613. var downloadFail = function (error) {
  614. expect(error.http_status).toBe(304);
  615. expect(error.code).toBe(FileTransferError.NOT_MODIFIED_ERR);
  616. done();
  617. };
  618. var downloadWin = function() {
  619. unexpectedCallbacks.httpWin();
  620. done();
  621. };
  622. this.transfer.download(imageURL + "?q=" + lastModified.getTime(), this.localFilePath, downloadWin, downloadFail, null,
  623. {
  624. headers: {
  625. "If-Modified-Since": lastModified.toUTCString()
  626. }
  627. });
  628. }, DOWNLOAD_TIMEOUT);
  629. it("filetransfer.spec.35 304 should not result in the deletion of a cached file", function (done) {
  630. if (isWP8) {
  631. pending();
  632. return;
  633. }
  634. var imageURL = "http://apache.org/images/feather-small.gif";
  635. var lastModified = new Date();
  636. var specContext = this;
  637. var fileOperationFail = function() {
  638. unexpectedCallbacks.fileOperationFail();
  639. done();
  640. };
  641. var fileSystemFail = function() {
  642. unexpectedCallbacks.fileSystemFail();
  643. done();
  644. };
  645. var httpWin = function() {
  646. unexpectedCallbacks.httpWin();
  647. done();
  648. };
  649. var httpFail = function() {
  650. unexpectedCallbacks.httpFail();
  651. done();
  652. };
  653. var downloadFail = function (error) {
  654. expect(error.http_status).toBe(304);
  655. expect(error.code).toBe(FileTransferError.NOT_MODIFIED_ERR);
  656. specContext.persistentRoot.getFile(specContext.fileName, { create: false },
  657. function (entry) {
  658. var fileWin = function (file) {
  659. var reader = new FileReader();
  660. reader.onerror = fileOperationFail;
  661. reader.onloadend = function () {
  662. expect(reader.result).toBeTruthy();
  663. if (reader.result !== null) {
  664. expect(reader.result.length).toBeGreaterThan(0);
  665. }
  666. done();
  667. };
  668. reader.readAsBinaryString(file);
  669. };
  670. entry.file(fileWin, fileSystemFail);
  671. },
  672. function (err) {
  673. expect("Could not open test file '" + specContext.fileName + "': " + JSON.stringify(err)).not.toBeDefined();
  674. done();
  675. }
  676. );
  677. };
  678. // Adding parameters to the requests to avoid caching on iOS, which leads to 200
  679. // instead of 304 in result of the second request. (a similar issue is described in CB-8606, CB-10088)
  680. specContext.transfer.download(imageURL + "?q=" + lastModified.getTime(), specContext.localFilePath, function () {
  681. specContext.transfer.download(imageURL + "?q=" + (lastModified.getTime() + 1), specContext.localFilePath, httpWin, downloadFail, null,
  682. {
  683. headers: {
  684. "If-Modified-Since": lastModified.toUTCString()
  685. }
  686. });
  687. }, httpFail);
  688. }, DOWNLOAD_TIMEOUT * 2);
  689. it("filetransfer.spec.36 should handle non-UTF8 encoded download response", function (done) {
  690. // Only iOS is supported: https://issues.apache.org/jira/browse/CB-9840
  691. if (!isIos) {
  692. pending();
  693. }
  694. var fileURL = SERVER + '/download_non_utf';
  695. var specContext = this;
  696. var fileOperationFail = function() {
  697. unexpectedCallbacks.fileOperationFail();
  698. done();
  699. };
  700. var fileSystemFail = function() {
  701. unexpectedCallbacks.fileSystemFail();
  702. done();
  703. };
  704. var httpFail = function() {
  705. unexpectedCallbacks.httpFail();
  706. done();
  707. };
  708. var fileWin = function (blob) {
  709. if (specContext.transfer.onprogress.calls.any()) {
  710. var lastProgressEvent = specContext.transfer.onprogress.calls.mostRecent().args[0];
  711. expect(lastProgressEvent.loaded).not.toBeGreaterThan(blob.size);
  712. } else {
  713. console.log("no progress events were emitted");
  714. }
  715. expect(blob.size).toBeGreaterThan(0);
  716. var reader = new FileReader();
  717. reader.onerror = fileOperationFail;
  718. reader.onloadend = function () {
  719. expect(reader.result.indexOf(LATIN1_SYMBOLS)).not.toBe(-1);
  720. done();
  721. };
  722. reader.readAsBinaryString(blob);
  723. };
  724. var downloadWin = function (entry) {
  725. verifyDownload(entry, specContext);
  726. // verify the FileEntry representing this file
  727. entry.file(fileWin, fileSystemFail);
  728. };
  729. specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, httpFail);
  730. }, UPLOAD_TIMEOUT);
  731. });
  732. describe("upload", function() {
  733. this.uploadParams = null;
  734. this.uploadOptions = null;
  735. this.fileName = null;
  736. this.fileContents = null;
  737. this.localFilePath = null;
  738. // helpers
  739. var verifyUpload = function (uploadResult, specContext) {
  740. expect(uploadResult.bytesSent).toBeGreaterThan(0);
  741. expect(uploadResult.responseCode).toBe(200);
  742. var obj = null;
  743. try {
  744. obj = JSON.parse(uploadResult.response);
  745. expect(obj.fields).toBeDefined();
  746. expect(obj.fields.value1).toBe("test");
  747. expect(obj.fields.value2).toBe("param");
  748. } catch (e) {
  749. expect(obj).not.toBeNull("returned data from server should be valid json");
  750. }
  751. expect(specContext.transfer.onprogress).toHaveBeenCalled();
  752. };
  753. beforeEach(function(done) {
  754. var specContext = this;
  755. specContext.fileName = "fileToUpload.txt";
  756. specContext.fileContents = "upload test file";
  757. specContext.uploadParams = {};
  758. specContext.uploadParams.value1 = "test";
  759. specContext.uploadParams.value2 = "param";
  760. specContext.uploadOptions = new FileUploadOptions();
  761. specContext.uploadOptions.fileKey = "file";
  762. specContext.uploadOptions.fileName = specContext.fileName;
  763. specContext.uploadOptions.mimeType = "text/plain";
  764. specContext.uploadOptions.params = specContext.uploadParams;
  765. var fileWin = function (entry) {
  766. specContext.localFilePath = entry.toURL();
  767. done();
  768. };
  769. // create a file to upload
  770. writeFile(specContext.root, specContext.fileName, specContext.fileContents, fileWin, done);
  771. });
  772. // delete the uploaded file
  773. afterEach(function (done) {
  774. deleteFile(this.root, this.fileName, done);
  775. });
  776. it("filetransfer.spec.18 should be able to upload a file", function (done) {
  777. var fileURL = SERVER + "/upload";
  778. var specContext = this;
  779. var uploadWin = function (uploadResult) {
  780. verifyUpload(uploadResult, specContext);
  781. if (cordova.platformId === "ios") {
  782. expect(uploadResult.headers).toBeDefined("Expected headers to be defined.");
  783. expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined.");
  784. }
  785. done();
  786. };
  787. var uploadFail = function() {
  788. unexpectedCallbacks.httpFail();
  789. done();
  790. };
  791. // NOTE: removing uploadOptions cause Android to timeout
  792. specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions);
  793. }, UPLOAD_TIMEOUT);
  794. it("filetransfer.spec.19 should be able to upload a file with http basic auth", function (done) {
  795. var fileURL = SERVER_WITH_CREDENTIALS + "/upload_basic_auth";
  796. var specContext = this;
  797. var uploadWin = function (uploadResult) {
  798. verifyUpload(uploadResult, specContext);
  799. done();
  800. };
  801. var uploadFail = function() {
  802. unexpectedCallbacks.httpFail();
  803. done();
  804. };
  805. // NOTE: removing uploadOptions cause Android to timeout
  806. specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions);
  807. }, UPLOAD_TIMEOUT);
  808. it("filetransfer.spec.21 should be stopped by abort()", function (done) {
  809. var fileURL = SERVER + "/upload";
  810. var specContext = this;
  811. var uploadFail = function (e) {
  812. expect(e.code).toBe(FileTransferError.ABORT_ERR);
  813. // delay calling done() to wait for the bogus abort()
  814. setTimeout(done, GRACE_TIME_DELTA * 2);
  815. };
  816. var uploadWin = function() {
  817. unexpectedCallbacks.httpWin();
  818. done();
  819. };
  820. var fileWin = function () {
  821. expect(specContext.transfer.abort).not.toThrow();
  822. // NOTE: removing uploadOptions cause Android to timeout
  823. specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions);
  824. setTimeout(function() {
  825. specContext.transfer.abort();
  826. }, ABORT_DELAY);
  827. setTimeout(function () {
  828. expect(specContext.transfer.abort).not.toThrow();
  829. }, GRACE_TIME_DELTA);
  830. };
  831. writeFile(specContext.root, specContext.fileName, new Array(200000).join("aborttest!"), fileWin, done);
  832. }, UPLOAD_TIMEOUT);
  833. it("filetransfer.spec.22 should get http status and body on failure", function (done) {
  834. var fileURL = SERVER + "/403";
  835. var uploadFail = function (error) {
  836. expect(error.http_status).toBe(403);
  837. expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
  838. done();
  839. };
  840. var uploadWin = function() {
  841. unexpectedCallbacks.httpWin();
  842. done();
  843. };
  844. this.transfer.upload(this.localFilePath, fileURL, uploadWin, uploadFail, this.uploadOptions);
  845. }, UPLOAD_TIMEOUT);
  846. it("filetransfer.spec.24 should handle malformed urls", function (done) {
  847. var fileURL = getMalformedUrl();
  848. var uploadFail = function (error) {
  849. expect(error.code).toBe(FileTransferError.INVALID_URL_ERR);
  850. expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
  851. done();
  852. };
  853. var uploadWin = function() {
  854. unexpectedCallbacks.httpWin();
  855. done();
  856. };
  857. this.transfer.upload(this.localFilePath, fileURL, uploadWin, uploadFail, {});
  858. });
  859. it("filetransfer.spec.25 should handle unknown host", function (done) {
  860. var fileURL = UNKNOWN_HOST;
  861. var uploadFail = function (error) {
  862. expect(error.code).toBe(FileTransferError.CONNECTION_ERR);
  863. expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
  864. done();
  865. };
  866. var uploadWin = function() {
  867. unexpectedCallbacks.httpWin();
  868. done();
  869. };
  870. this.transfer.upload(this.localFilePath, fileURL, uploadWin, uploadFail, {});
  871. }, UPLOAD_TIMEOUT);
  872. it("filetransfer.spec.25 should handle missing file", function (done) {
  873. var fileURL = SERVER + "/upload";
  874. var uploadFail = function (error) {
  875. expect(error.code).toBe(FileTransferError.FILE_NOT_FOUND_ERR);
  876. expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
  877. done();
  878. };
  879. var uploadWin = function() {
  880. unexpectedCallbacks.httpWin();
  881. done();
  882. };
  883. this.transfer.upload("does_not_exist.txt", fileURL, uploadWin, uploadFail);
  884. }, UPLOAD_TIMEOUT);
  885. it("filetransfer.spec.26 should handle bad file path", function (done) {
  886. var fileURL = SERVER + "/upload";
  887. var uploadFail = function (error) {
  888. expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
  889. done();
  890. };
  891. var uploadWin = function() {
  892. unexpectedCallbacks.httpWin();
  893. done();
  894. };
  895. this.transfer.upload("c:\\54321", fileURL, uploadWin, uploadFail);
  896. });
  897. it("filetransfer.spec.27 should be able to set custom headers", function (done) {
  898. var fileURL = HEADERS_ECHO;
  899. var uploadWin = function (uploadResult) {
  900. expect(uploadResult.bytesSent).toBeGreaterThan(0);
  901. expect(uploadResult.responseCode).toBe(200);
  902. expect(uploadResult.response).toBeDefined();
  903. var responseHtml = decodeURIComponent(uploadResult.response);
  904. expect(responseHtml).toMatch(/CustomHeader1[\s\S]*CustomValue1/i);
  905. expect(responseHtml).toMatch(/CustomHeader2[\s\S]*CustomValue2[\s\S]*CustomValue3/i, "Should allow array values");
  906. done();
  907. };
  908. var uploadFail = function() {
  909. unexpectedCallbacks.httpFail();
  910. done();
  911. };
  912. this.uploadOptions.headers = {
  913. "CustomHeader1": "CustomValue1",
  914. "CustomHeader2": ["CustomValue2", "CustomValue3"],
  915. };
  916. // NOTE: removing uploadOptions cause Android to timeout
  917. this.transfer.upload(this.localFilePath, fileURL, uploadWin, uploadFail, this.uploadOptions);
  918. }, UPLOAD_TIMEOUT);
  919. it("filetransfer.spec.29 (compatibility) should be able to upload a file using local paths", function (done) {
  920. var fileURL = SERVER + "/upload";
  921. var specContext = this;
  922. var unsupported = function (response) {
  923. expectedCallbacks.unsupportedOperation(response);
  924. done();
  925. };
  926. var uploadWin = function (uploadResult) {
  927. verifyUpload(uploadResult, specContext);
  928. done();
  929. };
  930. var uploadFail = function() {
  931. unexpectedCallbacks.httpFail();
  932. done();
  933. };
  934. var internalFilePath;
  935. if (specContext.root.toInternalURL) {
  936. internalFilePath = specContext.root.toInternalURL() + specContext.fileName;
  937. } else {
  938. internalFilePath = specContext.localFilePath;
  939. }
  940. // This is an undocumented interface to File which exists only for testing
  941. // backwards compatibilty. By obtaining the raw filesystem path of the download
  942. // location, we can pass that to transfer.download() to make sure that previously-stored
  943. // paths are still valid.
  944. cordova.exec(function (localPath) {
  945. specContext.transfer.upload(localPath, fileURL, uploadWin, uploadFail, specContext.uploadOptions);
  946. }, unsupported, "File", "_getLocalFilesystemPath", [internalFilePath]);
  947. }, UPLOAD_TIMEOUT);
  948. it("filetransfer.spec.31 should be able to upload a file using PUT method", function (done) {
  949. var fileURL = SERVER + "/upload";
  950. var specContext = this;
  951. var uploadWin = function (uploadResult) {
  952. verifyUpload(uploadResult, specContext);
  953. if (cordova.platformId === "ios") {
  954. expect(uploadResult.headers).toBeDefined("Expected headers to be defined.");
  955. expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined.");
  956. }
  957. done();
  958. };
  959. var uploadFail = function() {
  960. unexpectedCallbacks.httpFail();
  961. done();
  962. };
  963. specContext.uploadOptions.httpMethod = "PUT";
  964. // NOTE: removing uploadOptions cause Android to timeout
  965. specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions);
  966. }, UPLOAD_TIMEOUT);
  967. it("filetransfer.spec.32 should be able to upload a file (non-multipart)", function (done) {
  968. var fileURL = SERVER + "/upload";
  969. var specContext = this;
  970. var uploadWin = function (uploadResult) {
  971. expect(uploadResult.bytesSent).toBeGreaterThan(0);
  972. expect(uploadResult.responseCode).toBe(200);
  973. expect(uploadResult.response).toBeDefined();
  974. if (uploadResult.response) {
  975. expect(uploadResult.response).toEqual(specContext.fileContents + "\n");
  976. }
  977. expect(specContext.transfer.onprogress).toHaveBeenCalled();
  978. if (cordova.platformId === "ios") {
  979. expect(uploadResult.headers).toBeDefined("Expected headers to be defined.");
  980. expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined.");
  981. }
  982. done();
  983. };
  984. var uploadFail = function() {
  985. unexpectedCallbacks.httpFail();
  986. done();
  987. };
  988. // Content-Type header disables multipart
  989. specContext.uploadOptions.headers = {
  990. "Content-Type": "text/plain"
  991. };
  992. // NOTE: removing uploadOptions cause Android to timeout
  993. specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions);
  994. }, UPLOAD_TIMEOUT);
  995. it("filetransfer.spec.34 should not delete a file on upload error", function (done) {
  996. var fileURL = SERVER + "/upload";
  997. var specContext = this;
  998. var uploadFail = function (e) {
  999. expect(e.code).toBe(FileTransferError.ABORT_ERR);
  1000. // check that the file is there
  1001. specContext.root.getFile(specContext.fileName, null, function(entry) {
  1002. expect(entry).toBeDefined();
  1003. // delay calling done() to wait for the bogus abort()
  1004. setTimeout(done, GRACE_TIME_DELTA * 2);
  1005. }, function(err) {
  1006. expect(err).not.toBeDefined(err && err.code);
  1007. done();
  1008. });
  1009. };
  1010. var uploadWin = function() {
  1011. unexpectedCallbacks.httpWin();
  1012. done();
  1013. };
  1014. var fileWin = function () {
  1015. expect(specContext.transfer.abort).not.toThrow();
  1016. // abort at the first onprogress event
  1017. specContext.transfer.onprogress = function (event) {
  1018. if (event.loaded > 0) {
  1019. specContext.transfer.abort();
  1020. }
  1021. };
  1022. // NOTE: removing uploadOptions cause Android to timeout
  1023. specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions);
  1024. };
  1025. writeFile(specContext.root, specContext.fileName, new Array(100000).join("aborttest!"), fileWin, done);
  1026. }, UPLOAD_TIMEOUT);
  1027. it("filetransfer.spec.37 should handle non-UTF8 encoded upload response", function (done) {
  1028. // Only iOS is supported: https://issues.apache.org/jira/browse/CB-9840
  1029. if (!isIos) {
  1030. pending();
  1031. }
  1032. var fileURL = SERVER + '/upload_non_utf';
  1033. var specContext = this;
  1034. var uploadWin = function (uploadResult) {
  1035. verifyUpload(uploadResult, specContext);
  1036. var obj = null;
  1037. try {
  1038. obj = JSON.parse(uploadResult.response);
  1039. expect(obj.latin1Symbols).toBe(LATIN1_SYMBOLS);
  1040. } catch (e) {
  1041. expect(obj).not.toBeNull("returned data from server should be valid json");
  1042. }
  1043. if (cordova.platformId === 'ios') {
  1044. expect(uploadResult.headers).toBeDefined('Expected headers to be defined.');
  1045. expect(uploadResult.headers['Content-Type']).toBeDefined('Expected content-type header to be defined.');
  1046. }
  1047. done();
  1048. };
  1049. var uploadFail = function() {
  1050. unexpectedCallbacks.httpFail();
  1051. done();
  1052. };
  1053. // NOTE: removing uploadOptions cause Android to timeout
  1054. specContext.transfer.upload(specContext.localFilePath, fileURL, uploadWin, uploadFail, specContext.uploadOptions);
  1055. }, UPLOAD_TIMEOUT);
  1056. it("filetransfer.spec.38 should be able to upload a file using data: source uri", function (done) {
  1057. var fileURL = SERVER + "/upload";
  1058. var specContext = this;
  1059. var uploadWin = function (uploadResult) {
  1060. verifyUpload(uploadResult,specContext);
  1061. var obj = null;
  1062. try {
  1063. obj = JSON.parse(uploadResult.response);
  1064. expect(obj.files.file.size).toBe(DATA_URI_CONTENT_LENGTH);
  1065. } catch (e) {
  1066. expect(obj).not.toBeNull("returned data from server should be valid json");
  1067. }
  1068. if (cordova.platformId === "ios") {
  1069. expect(uploadResult.headers).toBeDefined("Expected headers to be defined.");
  1070. expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined.");
  1071. }
  1072. done();
  1073. };
  1074. var dataUri = DATA_URI_PREFIX + DATA_URI_CONTENT;
  1075. // NOTE: removing uploadOptions cause Android to timeout
  1076. specContext.transfer.upload(dataUri, fileURL, uploadWin, function (err) {
  1077. console.error('err: ' + JSON.stringify(err));
  1078. expect(err).not.toBeDefined();
  1079. done();
  1080. }, specContext.uploadOptions);
  1081. }, UPLOAD_TIMEOUT);
  1082. it("filetransfer.spec.39 should be able to upload a file using data: source uri (non-multipart)", function (done) {
  1083. var fileURL = SERVER + "/upload";
  1084. var uploadWin = function (uploadResult) {
  1085. expect(uploadResult.responseCode).toBe(200);
  1086. expect(uploadResult.bytesSent).toBeGreaterThan(0);
  1087. if (cordova.platformId === "ios") {
  1088. expect(uploadResult.headers).toBeDefined("Expected headers to be defined.");
  1089. expect(uploadResult.headers["Content-Type"]).toBeDefined("Expected content-type header to be defined.");
  1090. }
  1091. done();
  1092. };
  1093. var uploadFail = function() {
  1094. unexpectedCallbacks.httpFail();
  1095. done();
  1096. };
  1097. // Content-Type header disables multipart
  1098. this.uploadOptions.headers = {
  1099. "Content-Type": "image/png"
  1100. };
  1101. var dataUri = DATA_URI_PREFIX + DATA_URI_CONTENT;
  1102. // NOTE: removing uploadOptions cause Android to timeout
  1103. this.transfer.upload(dataUri, fileURL, uploadWin, uploadFail, this.uploadOptions);
  1104. }, UPLOAD_TIMEOUT);
  1105. it("filetransfer.spec.40 should not fail to upload a file using data: source uri when the data is empty", function (done) {
  1106. var fileURL = SERVER + "/upload";
  1107. var dataUri = DATA_URI_PREFIX;
  1108. var uploadFail = function() {
  1109. unexpectedCallbacks.httpFail();
  1110. done();
  1111. };
  1112. // NOTE: removing uploadOptions cause Android to timeout
  1113. this.transfer.upload(dataUri, fileURL, done, uploadFail, this.uploadOptions);
  1114. }, UPLOAD_TIMEOUT);
  1115. it("filetransfer.spec.41 should not fail to upload a file using data: source uri when the data is empty (non-multipart)", function (done) {
  1116. var fileURL = SERVER + "/upload";
  1117. // Content-Type header disables multipart
  1118. this.uploadOptions.headers = {
  1119. "Content-Type": "image/png"
  1120. };
  1121. // turn off the onprogress handler
  1122. this.transfer.onprogress = function () { };
  1123. var dataUri = DATA_URI_PREFIX;
  1124. var uploadFail = function() {
  1125. unexpectedCallbacks.httpFail();
  1126. done();
  1127. };
  1128. // NOTE: removing uploadOptions cause Android to timeout
  1129. this.transfer.upload(dataUri, fileURL, done, uploadFail, this.uploadOptions);
  1130. }, UPLOAD_TIMEOUT);
  1131. });
  1132. });
  1133. });
  1134. };
  1135. /******************************************************************************/
  1136. /******************************************************************************/
  1137. /******************************************************************************/
  1138. exports.defineManualTests = function (contentEl, createActionButton) {
  1139. "use strict";
  1140. var imageURL = "http://apache.org/images/feather-small.gif";
  1141. var videoURL = "http://techslides.com/demos/sample-videos/small.mp4";
  1142. function clearResults() {
  1143. var results = document.getElementById("info");
  1144. results.innerHTML = "";
  1145. }
  1146. function downloadImg(source, urlFn, element, directory) {
  1147. var filename = source.substring(source.lastIndexOf("/") + 1);
  1148. filename = (directory || "") + filename;
  1149. function download(fileSystem) {
  1150. var ft = new FileTransfer();
  1151. console.log("Starting download");
  1152. var progress = document.getElementById("loadingStatus");
  1153. progress.value = 0;
  1154. ft.onprogress = function(progressEvent) {
  1155. if (progressEvent.lengthComputable) {
  1156. var currPercents = parseInt(100 * (progressEvent.loaded / progressEvent.total), 10);
  1157. if (currPercents > progress.value) {
  1158. progress.value = currPercents;
  1159. }
  1160. } else {
  1161. progress.value = null;
  1162. }
  1163. };
  1164. ft.download(source, fileSystem.root.toURL() + filename, function (entry) {
  1165. console.log("Download complete");
  1166. element.src = urlFn(entry);
  1167. console.log("Src URL is " + element.src);
  1168. console.log("Inserting element");
  1169. document.getElementById("info").appendChild(element);
  1170. }, function (e) { console.log("ERROR: ft.download " + e.code); });
  1171. }
  1172. console.log("Requesting filesystem");
  1173. clearResults();
  1174. window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fileSystem) {
  1175. console.log("Checking for existing file");
  1176. if (typeof directory !== "undefined") {
  1177. console.log("Checking for existing directory.");
  1178. fileSystem.root.getDirectory(directory, {}, function (dirEntry) {
  1179. dirEntry.removeRecursively(function () {
  1180. download(fileSystem);
  1181. }, function () { console.log("ERROR: dirEntry.removeRecursively"); });
  1182. }, function () {
  1183. download(fileSystem);
  1184. });
  1185. } else {
  1186. fileSystem.root.getFile(filename, { create: false }, function (entry) {
  1187. console.log("Removing existing file");
  1188. entry.remove(function () {
  1189. download(fileSystem);
  1190. }, function () { console.log("ERROR: entry.remove"); });
  1191. }, function () {
  1192. download(fileSystem);
  1193. });
  1194. }
  1195. }, function () { console.log("ERROR: requestFileSystem"); });
  1196. }
  1197. /******************************************************************************/
  1198. var progress_tag = "<progress id=\"loadingStatus\" value=\"0\" max=\"100\" style=\"width: 100%;\"></progress>";
  1199. var file_transfer_tests = "<h2>Image File Transfer Tests</h2>" +
  1200. "<h3>The following tests should display an image of the Apache feather in the status box</h3>" +
  1201. "<div id=\"cdv_image\"></div>" +
  1202. "<div id=\"native_image\"></div>" +
  1203. "<div id=\"non-existent_dir\"></div>" +
  1204. "<h2>Video File Transfer Tests</h2>" +
  1205. "<h3>The following tests should display a video in the status box. The video should play when play is pressed</h3>" +
  1206. "<div id=\"cdv_video\"></div>" +
  1207. "<div id=\"native_video\"></div>";
  1208. contentEl.innerHTML = "<div id=\"info\"></div>" + "<br>" + progress_tag +
  1209. file_transfer_tests;
  1210. createActionButton("Download and display img (cdvfile)", function () {
  1211. downloadImg(imageURL, function (entry) { return entry.toInternalURL(); }, new Image());
  1212. }, "cdv_image");
  1213. createActionButton("Download and display img (native)", function () {
  1214. downloadImg(imageURL, function (entry) { return entry.toURL(); }, new Image());
  1215. }, "native_image");
  1216. createActionButton("Download to a non-existent dir (should work)", function () {
  1217. downloadImg(imageURL, function (entry) { return entry.toURL(); }, new Image(), "/nonExistentDirTest/");
  1218. }, "non-existent_dir");
  1219. createActionButton("Download and play video (cdvfile)", function () {
  1220. var videoElement = document.createElement("video");
  1221. videoElement.controls = "controls";
  1222. downloadImg(videoURL, function (entry) { return entry.toInternalURL(); }, videoElement);
  1223. }, "cdv_video");
  1224. createActionButton("Download and play video (native)", function () {
  1225. var videoElement = document.createElement("video");
  1226. videoElement.controls = "controls";
  1227. downloadImg(videoURL, function (entry) { return entry.toURL(); }, videoElement);
  1228. }, "native_video");
  1229. };