/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* global exports, cordova, FileTransfer, FileTransferError, FileUploadOptions, LocalFileSystem */
/* jshint jasmine: true */
exports.defineAutoTests = function () {
"use strict";
// constants
var ONE_SECOND = 1000; // in milliseconds
var GRACE_TIME_DELTA = 600; // in milliseconds
var DEFAULT_FILESYSTEM_SIZE = 1024 * 50; // filesystem size in bytes
var UNKNOWN_HOST = "http://foobar.apache.org";
var HEADERS_ECHO = "http://whatheaders.com"; // NOTE: this site is very useful!
var DOWNLOAD_TIMEOUT = 7 * ONE_SECOND;
var WINDOWS_UNKNOWN_HOST_TIMEOUT = 35 * ONE_SECOND;
var UPLOAD_TIMEOUT = 7 * ONE_SECOND;
var ABORT_DELAY = 100; // for abort() tests
var LATIN1_SYMBOLS = '¥§©ÆÖÑøøø¼';
var DATA_URI_PREFIX = "data:image/png;base64,";
var DATA_URI_CONTENT = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
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)
// config for upload test server
// NOTE:
// more info at https://github.com/apache/cordova-labs/tree/cordova-filetransfer
var SERVER = "http://cordova-vm.apache.org:5000";
var SERVER_WITH_CREDENTIALS = "http://cordova_user:cordova_password@cordova-vm.apache.org:5000";
// flags
var isWindows = cordova.platformId === "windows8" || cordova.platformId === "windows";
var isWP8 = cordova.platformId === "windowsphone";
var isBrowser = cordova.platformId === "browser";
var isIE = isBrowser && navigator.userAgent.indexOf("Trident") >= 0;
var isIos = cordova.platformId === "ios";
// tests
describe("FileTransferError", function () {
it("should exist", function () {
expect(FileTransferError).toBeDefined();
});
it("should be constructable", function () {
var transferError = new FileTransferError();
expect(transferError).toBeDefined();
});
it("filetransfer.spec.3 should expose proper constants", function () {
expect(FileTransferError.FILE_NOT_FOUND_ERR).toBeDefined();
expect(FileTransferError.INVALID_URL_ERR).toBeDefined();
expect(FileTransferError.CONNECTION_ERR).toBeDefined();
expect(FileTransferError.ABORT_ERR).toBeDefined();
expect(FileTransferError.NOT_MODIFIED_ERR).toBeDefined();
expect(FileTransferError.FILE_NOT_FOUND_ERR).toBe(1);
expect(FileTransferError.INVALID_URL_ERR).toBe(2);
expect(FileTransferError.CONNECTION_ERR).toBe(3);
expect(FileTransferError.ABORT_ERR).toBe(4);
expect(FileTransferError.NOT_MODIFIED_ERR).toBe(5);
});
});
describe("FileUploadOptions", function () {
it("should exist", function () {
expect(FileUploadOptions).toBeDefined();
});
it("should be constructable", function () {
var transferOptions = new FileUploadOptions();
expect(transferOptions).toBeDefined();
});
});
describe("FileTransfer", function () {
this.persistentRoot = null;
this.tempRoot = null;
// named callbacks
var unexpectedCallbacks = {
httpFail: function () {},
httpWin: function () {},
fileSystemFail: function () {},
fileSystemWin: function () {},
fileOperationFail: function () {},
fileOperationWin: function () {},
};
var expectedCallbacks = {
unsupportedOperation: function (response) {
console.log("spec called unsupported functionality; response:", response);
},
};
// helpers
var deleteFile = function (fileSystem, name, done) {
fileSystem.getFile(name, null,
function (fileEntry) {
fileEntry.remove(
function () {
done();
},
function () {
throw new Error("failed to delete: '" + name + "'");
}
);
},
function () {
done();
}
);
};
var writeFile = function (fileSystem, name, content, success, done) {
var fileOperationFail = function() {
unexpectedCallbacks.fileOperationFail();
done();
};
fileSystem.getFile(name, { create: true },
function (fileEntry) {
fileEntry.createWriter(function (writer) {
writer.onwrite = function () {
success(fileEntry);
};
writer.onabort = function (evt) {
throw new Error("aborted creating test file '" + name + "': " + evt);
};
writer.error = function (evt) {
throw new Error("aborted creating test file '" + name + "': " + evt);
};
if (cordova.platformId === "browser") {
var blob = new Blob([content + "\n"], { type: "text/plain" });
writer.write(blob);
} else {
writer.write(content + "\n");
}
}, fileOperationFail);
},
function () {
throw new Error("could not create test file '" + name + "'");
}
);
};
// according to documentation, wp8 does not support onProgress:
// https://github.com/apache/cordova-plugin-file-transfer/blob/master/doc/index.md#supported-platforms
var wp8OnProgressHandler = function () {};
var defaultOnProgressHandler = function (event) {
if (event.lengthComputable) {
expect(event.loaded).toBeGreaterThan(1);
expect(event.total).toBeGreaterThan(0);
expect(event.total).not.toBeLessThan(event.loaded);
expect(event.lengthComputable).toBe(true, "lengthComputable");
} else {
// In IE, when lengthComputable === false, event.total somehow is equal to 2^64
if (isIE) {
expect(event.total).toBe(Math.pow(2, 64));
} else {
// iOS returns -1, and other platforms return 0
expect(event.total).toBeLessThan(1);
}
}
};
var getMalformedUrl = function () {
if (cordova.platformId === "android" || cordova.platformId === "amazon-fireos") {
// bad protocol causes a MalformedUrlException on Android
return "httpssss://example.com";
} else {
// iOS doesn't care about protocol, space in hostname causes error
return "httpssss://exa mple.com";
}
};
// NOTE:
// there are several beforeEach calls, one per async call; since calling done()
// signifies a completed async call, each async call needs its own done(), and
// therefore its own beforeEach
beforeEach(function (done) {
var specContext = this;
window.requestFileSystem(LocalFileSystem.PERSISTENT, DEFAULT_FILESYSTEM_SIZE,
function (fileSystem) {
specContext.persistentRoot = fileSystem.root;
done();
},
function () {
throw new Error("Failed to initialize persistent file system.");
}
);
});
beforeEach(function (done) {
var specContext = this;
window.requestFileSystem(LocalFileSystem.TEMPORARY, DEFAULT_FILESYSTEM_SIZE,
function (fileSystem) {
specContext.tempRoot = fileSystem.root;
done();
},
function () {
throw new Error("Failed to initialize temporary file system.");
}
);
});
// spy on all named callbacks
beforeEach(function() {
// ignore the actual implementations of the unexpected callbacks
for (var callback in unexpectedCallbacks) {
if (unexpectedCallbacks.hasOwnProperty(callback)) {
spyOn(unexpectedCallbacks, callback);
}
}
// but run the implementations of the expected callbacks
for (callback in expectedCallbacks) { // jshint ignore: line
if (expectedCallbacks.hasOwnProperty(callback)) {
spyOn(expectedCallbacks, callback).and.callThrough();
}
}
});
// at the end, check that none of the unexpected callbacks got called,
// and act on the expected callbacks
afterEach(function() {
for (var callback in unexpectedCallbacks) {
if (unexpectedCallbacks.hasOwnProperty(callback)) {
expect(unexpectedCallbacks[callback]).not.toHaveBeenCalled();
}
}
if (expectedCallbacks.unsupportedOperation.calls.any()) {
pending();
}
});
it("should initialise correctly", function() {
expect(this.persistentRoot).toBeDefined();
expect(this.tempRoot).toBeDefined();
});
it("should exist", function () {
expect(FileTransfer).toBeDefined();
});
it("filetransfer.spec.1 should be constructable", function () {
var transfer = new FileTransfer();
expect(transfer).toBeDefined();
});
it("filetransfer.spec.2 should expose proper functions", function () {
var transfer = new FileTransfer();
expect(transfer.upload).toBeDefined();
expect(transfer.download).toBeDefined();
expect(transfer.upload).toEqual(jasmine.any(Function));
expect(transfer.download).toEqual(jasmine.any(Function));
});
describe("methods", function() {
this.transfer = null;
this.root = null;
this.fileName = null;
this.localFilePath = null;
beforeEach(function() {
this.transfer = new FileTransfer();
// assign onprogress handler
this.transfer.onprogress = isWP8 ? wp8OnProgressHandler : defaultOnProgressHandler;
// spy on the onprogress handler, but still call through to it
spyOn(this.transfer, "onprogress").and.callThrough();
this.root = this.persistentRoot;
this.fileName = "testFile.txt";
this.localFilePath = this.root.toURL() + this.fileName;
});
// NOTE:
// if download tests are failing, check the
// URL white list for the following URLs:
// - 'httpssss://example.com'
// - 'apache.org', with subdomains="true"
// - 'cordova-filetransfer.jitsu.com'
describe("download", function () {
// helpers
var verifyDownload = function (fileEntry, specContext) {
expect(fileEntry.name).toBe(specContext.fileName);
};
// delete the downloaded file
afterEach(function (done) {
deleteFile(this.root, this.fileName, done);
});
it("ensures that test file does not exist", function (done) {
deleteFile(this.root, this.fileName, done);
});
it("filetransfer.spec.4 should download a file", function (done) {
var fileURL = SERVER + "/robots.txt";
var specContext = this;
var fileWin = function (blob) {
if (specContext.transfer.onprogress.calls.any()) {
var lastProgressEvent = specContext.transfer.onprogress.calls.mostRecent().args[0];
expect(lastProgressEvent.loaded).not.toBeGreaterThan(blob.size);
} else {
console.log("no progress events were emitted");
}
done();
};
var fileSystemFail = function() {
unexpectedCallbacks.fileSystemFail();
done();
};
var downloadFail = function() {
unexpectedCallbacks.httpFail();
done();
};
var downloadWin = function (entry) {
verifyDownload(entry, specContext);
// verify the FileEntry representing this file
entry.file(fileWin, fileSystemFail);
};
specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.5 should download a file using http basic auth", function (done) {
var fileURL = SERVER_WITH_CREDENTIALS + "/download_basic_auth";
var specContext = this;
var downloadWin = function (entry) {
verifyDownload(entry, specContext);
done();
};
var downloadFail = function() {
unexpectedCallbacks.httpFail();
done();
};
specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.6 should get 401 status on http basic auth failure", function (done) {
// NOTE:
// using server without credentials
var fileURL = SERVER + "/download_basic_auth";
var downloadFail = function (error) {
expect(error.http_status).toBe(401);
expect(error.http_status).not.toBe(404, "Ensure " + fileURL + " is in the white list");
done();
};
var downloadWin = function() {
unexpectedCallbacks.httpWin();
done();
};
this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail, null,
{
headers: {
"If-Modified-Since": "Thu, 19 Mar 2015 00:00:00 GMT"
}
});
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.7 should download a file using file:// (when hosted from file://)", function (done) {
// for Windows platform it's ms-appdata:/// by default, not file://
if (isWindows) {
pending();
return;
}
var fileURL = window.location.protocol + "//" + window.location.pathname.replace(/ /g, "%20");
var specContext = this;
if (!/^file:/.exec(fileURL) && cordova.platformId !== "blackberry10") {
if (cordova.platformId === "windowsphone") {
expect(fileURL).toMatch(/^x-wmapp0:/);
}
done();
return;
}
var downloadWin = function (entry) {
verifyDownload(entry, specContext);
done();
};
var downloadFail = function() {
unexpectedCallbacks.httpFail();
done();
};
specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.8 should download a file using https://", function (done) {
var fileURL = "https://www.apache.org/licenses/";
var specContext = this;
var downloadFail = function() {
unexpectedCallbacks.httpFail();
done();
};
var fileOperationFail = function() {
unexpectedCallbacks.fileOperationFail();
done();
};
var fileSystemFail = function() {
unexpectedCallbacks.fileSystemFail();
done();
};
var fileWin = function (file) {
var reader = new FileReader();
reader.onerror = fileOperationFail;
reader.onload = function () {
expect(reader.result).toMatch(/The Apache Software Foundation/);
done();
};
reader.readAsText(file);
};
var downloadWin = function (entry) {
verifyDownload(entry, specContext);
entry.file(fileWin, fileSystemFail);
};
specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.11 should call the error callback on abort()", function (done) {
var fileURL = "http://cordova.apache.org/downloads/BlueZedEx.mp3";
fileURL = fileURL + "?q=" + (new Date()).getTime();
var specContext = this;
var downloadWin = function () {
unexpectedCallbacks.httpWin();
done();
};
specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, done);
setTimeout(function() {
specContext.transfer.abort();
}, ABORT_DELAY);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.9 should not leave partial file due to abort", function (done) {
var fileURL = "http://cordova.apache.org/downloads/logos_2.zip";
var specContext = this;
var fileSystemWin = function() {
unexpectedCallbacks.fileSystemWin();
done();
};
var downloadWin = function() {
unexpectedCallbacks.httpWin();
done();
};
var downloadFail = function (error) {
var result = (error.code === FileTransferError.ABORT_ERR || error.code === FileTransferError.CONNECTION_ERR)? true: false;
if (!result) {
fail("Expected " + error.code + " to be " + FileTransferError.ABORT_ERR + " or " + FileTransferError.CONNECTION_ERR);
}
expect(specContext.transfer.onprogress).toHaveBeenCalled();
// check that there is no file
specContext.root.getFile(specContext.fileName, null, fileSystemWin, done);
};
// abort at the first onprogress event
specContext.transfer.onprogress = function (event) {
if (event.loaded > 0) {
specContext.transfer.abort();
}
};
spyOn(specContext.transfer, "onprogress").and.callThrough();
specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.10 should be stopped by abort()", function (done) {
var fileURL = "http://cordova.apache.org/downloads/BlueZedEx.mp3";
fileURL = fileURL + "?q=" + (new Date()).getTime();
var specContext = this;
expect(specContext.transfer.abort).not.toThrow(); // should be a no-op.
var downloadWin = function() {
unexpectedCallbacks.httpWin();
done();
};
var downloadFail = function (error) {
expect(error.code).toBe(FileTransferError.ABORT_ERR);
// delay calling done() to wait for the bogus abort()
setTimeout(done, GRACE_TIME_DELTA * 2);
};
specContext.transfer.download(fileURL, specContext.localFilePath, downloadWin, downloadFail);
setTimeout(function() {
specContext.transfer.abort();
}, ABORT_DELAY);
// call abort() again, after a time greater than the grace period
setTimeout(function () {
expect(specContext.transfer.abort).not.toThrow();
}, GRACE_TIME_DELTA);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.12 should get http status on failure", function (done) {
var fileURL = SERVER + "/404";
var downloadFail = function (error) {
expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
expect(error.http_status).toBe(404);
// wp8 does not make difference between 404 and unknown host
if (isWP8) {
expect(error.code).toBe(FileTransferError.CONNECTION_ERR);
} else {
expect(error.code).toBe(FileTransferError.FILE_NOT_FOUND_ERR);
}
done();
};
var downloadWin = function() {
unexpectedCallbacks.httpWin();
done();
};
this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.13 should get http body on failure", function (done) {
var fileURL = SERVER + "/404";
var downloadFail = function (error) {
expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
expect(error.http_status).toBe(404);
expect(error.body).toBeDefined();
expect(error.body).toMatch("You requested a 404");
done();
};
var downloadWin = function() {
unexpectedCallbacks.httpWin();
done();
};
this.transfer.download(fileURL, this.localFilePath, downloadWin, downloadFail);
}, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.14 should handle malformed urls", function (done) {
var fileURL = getMalformedUrl();
var downloadFail = function (error) {
// Note: Android needs the bad protocol to be added to the access list
//