tests.js 72 KB

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