1
1
mirror of https://github.com/ariya/phantomjs.git synced 2024-10-26 14:29:13 +03:00

Convert non-webpage tests to the new format.

This covers fs-spec-*.js, require/require_spec.js, module_spec.js,
webkit-spec.js, and webserver-spec.js.  Also, incorporate
set/690-ttf-crash/ as a regression test (it wasn't being run
automatically).

Part of issue #13478 (test suite overhaul).
This commit is contained in:
Zack Weinberg 2015-08-13 09:47:14 -04:00
parent 2121b56d5b
commit 5a266e48dc
44 changed files with 752 additions and 966 deletions

27
test/basics/module.js Normal file
View File

@ -0,0 +1,27 @@
// Test the properties of the 'module' object.
// Assumes the 'dummy_exposed' module is to be found in a directory
// named 'node_modules'.
// Module load might fail, so do it in a setup function.
var module;
setup(function () {
module = require("dummy_exposed");
});
test(function() {
assert_regexp_match(module.filename, /\/node_modules\/dummy_exposed\.js$/);
}, "module.filename is the absolute pathname of the module .js file");
test(function() {
assert_regexp_match(module.dirname, /\/node_modules$/);
}, "module.dirname is the absolute pathname of the directory containing "+
"the module");
test(function() {
assert_equals(module.id, module.filename);
}, "module.id equals module.filename");
test(function() {
var dummy_file = module.require('./dummy_file');
assert_equals(dummy_file, 'spec/node_modules/dummy_file');
}, "module.require is callable and resolves relative to the module");

10
test/basics/require.js Normal file
View File

@ -0,0 +1,10 @@
/* The require tests need to run inside a module to work correctly; that
module is require/require_spec.js. (That directory also contains a
bunch of other files used by this test.) The module exports an array
of test functions in the form expected by generate_tests(). */
var rtests = require("require/require_spec.js").tests;
for (var i = 0; i < rtests.length; i++) {
test.apply(null, rtests[i]);
}

View File

@ -0,0 +1,131 @@
var fs = require('fs');
var tests = [];
exports.tests = tests;
tests.push([function () {
assert_no_property(window, 'CoffeeScript');
assert_own_property(window, 'require');
assert_own_property(require('webpage'), 'create');
assert_own_property(require('webserver'), 'create');
assert_own_property(require('cookiejar'), 'create');
assert_own_property(require('fs'), 'separator');
assert_equals(require('system').platform, 'phantomjs');
}, "native modules"]);
tests.push([function () {
assert_equals(require('./json_dummy').message, 'hello');
assert_equals(require('./dummy.js'), 'require/dummy');
}, "JS and JSON modules"]);
tests.push([function () {
require('./empty').hello = 'hola';
assert_equals(require('./empty').hello, 'hola');
// assert_own_property rejects Functions
assert_equals(require.hasOwnProperty('cache'), true);
var exposed = require('dummy_exposed');
assert_equals(require.cache[exposed.filename], exposed);
}, "module caching"]);
tests.push([function () {
var a = require('./a');
var b = require('./b');
assert_equals(a.b, b);
assert_equals(b.a, a);
}, "circular dependencies"]);
tests.push([function () {
assert_throws("Cannot find module 'dummy_missing'",
function () { require('dummy_missing'); });
try {
require('./not_found').requireNonExistent();
} catch (e) {
assert_regexp_match(e.stack, /\n\s+at require/);
}
}, "error handling 1"]);
tests.push([function error_handling_2 () {
try {
require('./thrower').fn();
} catch (e) {
assert_regexp_match(e.toString() + "\n" + e.stack,
/^Error: fn\n\s+at thrower\n\s+at error_handling_2\n/);
}
}, "error handling 2", { expected_fail: true }]);
tests.push([function () {
assert_equals(require('./stubber').stubbed, 'stubbed module');
assert_equals(require('./stubber').child.stubbed, 'stubbed module');
assert_throws("Cannot find module 'stubbed'",
function () { require('stubbed'); });
var count = 0;
require.stub('lazily_stubbed', function() {
++count;
return 'lazily stubbed module';
});
assert_equals(require('lazily_stubbed'), 'lazily stubbed module');
require('lazily_stubbed');
assert_equals(count, 1);
}, "stub modules"]);
tests.push([function () {
assert_equals(require('./dummy'), 'require/dummy');
assert_equals(require('../dummy'), 'spec/dummy');
assert_equals(require('./dir/dummy'), 'dir/dummy');
assert_equals(require('./dir/subdir/dummy'), 'subdir/dummy');
assert_equals(require('./dir/../dummy'), 'require/dummy');
assert_equals(require('./dir/./dummy'), 'dir/dummy');
assert_equals(require(
fs.absolute(module.dirname + '/dummy.js')), 'require/dummy');
}, "relative and absolute paths"]);
tests.push([function () {
assert_equals(require('dummy_file'), 'require/node_modules/dummy_file');
assert_equals(require('dummy_file2'), 'spec/node_modules/dummy_file2');
assert_equals(require('./dir/subdir/loader').dummyFile2,
'spec/node_modules/dummy_file2');
assert_equals(require('dummy_module'),
'require/node_modules/dummy_module');
assert_equals(require('dummy_module2'),
'require/node_modules/dummy_module2');
}, "loading from node_modules"]);
function require_paths_tests_1 () {
assert_equals(require('loader').dummyFile2,
'spec/node_modules/dummy_file2');
assert_equals(require('../subdir2/loader'),
'require/subdir2/loader');
assert_equals(require('../dummy'), 'spec/dummy');
}
function require_paths_tests_2 () {
assert_throws("Cannot find module 'loader'",
function () { require('loader'); });
}
tests.push([function () {
require.paths.push('dir/subdir');
this.add_cleanup(function () { require.paths.pop(); });
require_paths_tests_1();
}, "relative paths in require.paths"]);
tests.push([
require_paths_tests_2, "relative paths in require paths (after removal)"]);
tests.push([function () {
require.paths.push(fs.absolute(module.dirname + '/dir/subdir'));
this.add_cleanup(function () { require.paths.pop(); });
require_paths_tests_1();
}, "absolute paths in require.paths"]);
tests.push([
require_paths_tests_2, "relative paths in require paths (after removal)"]);

View File

@ -0,0 +1,3 @@
exports.fn = function thrower() {
throw new Error('fn');
};

View File

@ -1,219 +0,0 @@
describe("Basic Files API (read, write, remove, ...)", function() {
var FILENAME = "temp-01.test",
FILENAME_COPY = FILENAME + ".copy",
FILENAME_MOVED = FILENAME + ".moved",
FILENAME_EMPTY = FILENAME + ".empty",
FILENAME_ENC = FILENAME + ".enc",
FILENAME_BIN = FILENAME + ".bin",
ABSENT = "absent-01.test";
it("should be able to create and write a file", function() {
try{
var f = fs.open(FILENAME, "w");
f.write("hello");
f.writeLine("");
f.writeLine("world");
f.close();
} catch (e) { }
expect(fs.exists(FILENAME)).toBeTruthy();
});
it("should be able to create (touch) an empty file", function() {
expect(fs.exists(FILENAME_EMPTY)).toBeFalsy();
fs.touch(FILENAME_EMPTY);
expect(fs.exists(FILENAME_EMPTY)).toBeTruthy();
expect(fs.size(FILENAME_EMPTY)).toEqual(0);
});
it("should be able to read content from a file", function() {
var content = "";
try{
var f = fs.open(FILENAME, "r");
content = f.read();
f.close();
} catch (e) { }
expect(content).toEqual("hello\nworld\n");
});
it("should be able to read specific number of bytes from a specific position in a file", function() {
var content = "";
try{
var f = fs.open(FILENAME, "r");
f.seek(3);
content = f.read(5);
f.close();
} catch (e) { }
expect(content).toEqual("lo\nwo");
});
it("should be able to read/write/append content from a file", function() {
var content = "";
try{
var f = fs.open(FILENAME, "rw+");
f.writeLine("asdf");
content = f.read();
f.close();
} catch (e) { }
expect(content).toEqual("hello\nworld\nasdf\n");
});
it("should be able to get the encoding (default: UTF-8)", function() {
var encoding = "";
try {
var f = fs.open(FILENAME, "r");
encoding = f.getEncoding();
f.close();
} catch (e) {
console.log(e);
}
expect(encoding).toEqual("UTF-8");
});
it("should be able to set the encoding via options", function() {
var encoding = "";
try {
var f = fs.open(FILENAME, {
charset: "UTF-8"
, mode: "r"
});
encoding = f.getEncoding();
f.close();
} catch (e) {
console.log(e);
}
expect(encoding).toEqual("UTF-8");
try {
var f = fs.open(FILENAME, {
charset: "SJIS"
, mode: "r"
});
encoding = f.getEncoding();
f.close();
} catch (e) {
console.log(e);
}
expect(encoding).toEqual("Shift_JIS");
});
it("should be able to change the encoding", function() {
var encoding = "";
try {
var f = fs.open(FILENAME, {
charset: "UTF-8"
, mode: "r"
});
f.setEncoding("utf8");
encoding = f.getEncoding();
f.close();
} catch (e) {
console.log(e);
}
expect(encoding).toEqual("UTF-8");
try {
var f = fs.open(FILENAME, {
charset: "SJIS"
, mode: "r"
});
f.setEncoding("eucjp");
encoding = f.getEncoding();
f.close();
} catch (e) {
console.log(e);
}
expect(encoding).toEqual("EUC-JP");
});
it("should be able to copy a file", function() {
expect(fs.exists(FILENAME_COPY)).toBeFalsy();
fs.copy(FILENAME, FILENAME_COPY);
expect(fs.exists(FILENAME_COPY)).toBeTruthy();
expect(fs.read(FILENAME)).toEqual(fs.read(FILENAME_COPY));
});
it("should be able to move a file", function() {
expect(fs.exists(FILENAME)).toBeTruthy();
var contentBeforeMove = fs.read(FILENAME);
fs.move(FILENAME, FILENAME_MOVED);
expect(fs.exists(FILENAME)).toBeFalsy();
expect(fs.exists(FILENAME_MOVED)).toBeTruthy();
expect(fs.read(FILENAME_MOVED)).toEqual(contentBeforeMove);
});
it("should be able to remove a (moved) file", function() {
expect(fs.exists(FILENAME_MOVED)).toBeTruthy();
fs.remove(FILENAME_MOVED);
expect(fs.exists(FILENAME_MOVED)).toBeFalsy();
});
it("should be able to remove a (copied) file", function() {
expect(fs.exists(FILENAME_COPY)).toBeTruthy();
fs.remove(FILENAME_COPY);
expect(fs.exists(FILENAME_COPY)).toBeFalsy();
});
it("should be able to remove an empty file", function() {
expect(fs.exists(FILENAME_EMPTY)).toBeTruthy();
fs.remove(FILENAME_EMPTY);
expect(fs.exists(FILENAME_EMPTY)).toBeFalsy();
});
it("should throw an exception when trying to open for read a non existing file", function(){
expect(function(){
fs.open(ABSENT, "r");
}).toThrow("Unable to open file '"+ ABSENT +"'");
});
it("should throw an exception when trying to copy a non existing file", function() {
expect(function(){
fs.copy(ABSENT, FILENAME_COPY);
}).toThrow("Unable to copy file '" + ABSENT + "' at '" + FILENAME_COPY + "'");
});
it("should be read/write utf8 text by default", function() {
var content, output = "ÄABCÖ";
try {
var f = fs.open(FILENAME_ENC, "w");
f.write(output);
f.close();
f = fs.open(FILENAME_ENC, "r");
content = f.read();
f.close();
fs.remove(FILENAME_ENC);
} catch (e) { }
expect(content).toEqual(output);
});
it("should be read/write binary data", function() {
var content, output = String.fromCharCode(0, 1, 2, 3, 4, 5);
try {
var f = fs.open(FILENAME_BIN, "wb");
f.write(output);
f.close();
f = fs.open(FILENAME_BIN, "rb");
content = f.read();
f.close();
fs.remove(FILENAME_BIN);
} catch (e) { }
expect(content).toEqual(output);
});
it("should be read/write binary data (shortcuts)", function() {
var content, output = String.fromCharCode(0, 1, 2, 3, 4, 5);
try {
fs.write(FILENAME_BIN, output, "b");
content = fs.read(FILENAME_BIN, "b");
fs.remove(FILENAME_BIN);
} catch (e) { }
expect(content).toEqual(output);
});
});

View File

@ -1,46 +0,0 @@
describe("Attributes Files API", function() {
var FILENAME = "temp-02.test",
CONTENT = "This is a test for PhantomJS, an awesome headless browser to do all sort of stuff :) ",
CONTENT_MULTIPLIER = 1024,
ABSENT = "absent-02.test";
it("should throw an exception when trying to read the size of a non existing file", function(){
expect(function(){
fs.size(ABSENT);
}).toThrow("Unable to read file '"+ ABSENT +"' size");
});
it("should return a null Date object when trying to read the last modified date of a non existing file", function(){
expect(fs.lastModified(ABSENT)).toBeNull();
});
it("should create temporary file '"+ FILENAME +"' and writes some content in it", function(){
try{
var f = fs.open(FILENAME, "w");
expect(f).toBeDefined();
for (var i = 1; i <= CONTENT_MULTIPLIER; ++i) {
f.write(CONTENT);
}
f.close();
} catch (e) { }
});
it("should be able to read the size of a temporary file '"+ FILENAME +"'", function() {
expect(fs.size(FILENAME)).toEqual(CONTENT.length * CONTENT_MULTIPLIER);
});
it("should be able to read the Date on which a temporary file '"+ FILENAME +"' was last modified", function() {
var flm = fs.lastModified(FILENAME),
now = new Date();
expect(now.getDay()).toEqual(flm.getDay());
expect(now.getMonth()).toEqual(flm.getMonth());
expect(now.getFullYear()).toEqual(flm.getFullYear());
expect(now.getMilliseconds()).toNotEqual(flm.getMilliseconds());
});
it("should remove temporary file '"+ FILENAME +"'", function(){
fs.remove(FILENAME);
});
});

View File

@ -1,147 +0,0 @@
describe("Files and Directories API", function() {
var TEST_DIR = "testdir",
TEST_FILE = "testfile",
START_CWD = fs.workingDirectory,
system = require('system');
it("should create a new temporary directory and change the Current Working Directory to it", function() {
expect(fs.makeDirectory(TEST_DIR)).toBeTruthy();
expect(fs.changeWorkingDirectory(TEST_DIR)).toBeTruthy();
});
it("should create a file in the Current Working Directory and check it's absolute path", function() {
fs.write(TEST_FILE, TEST_FILE, "w");
var suffix = fs.join("", TEST_DIR, TEST_FILE),
abs = fs.absolute(".." + suffix),
lastIndex = abs.lastIndexOf(suffix);
expect(lastIndex).toNotEqual(-1);
expect(lastIndex + suffix.length === abs.length);
});
it("should return to previous Current Working Directory and remove temporary directory", function() {
expect(fs.changeWorkingDirectory(START_CWD)).toBeTruthy();
fs.removeTree(TEST_DIR);
});
it("should copy Content of the '/test/' Directory in a temporary directory, compare with the original and then remove", function() {
var phantomLibraryPathListingLength = fs.list(phantom.libraryPath).length;
var targetDirectory = '/tmp/';
if (system.os.name === 'windows') {
targetDirectory = system.env['TMP'];
if (targetDirectory.indexOf('\\', targetDirectory.length - '\\'.length) === -1) {
targetDirectory += '\\';
}
}
fs.copyTree(phantom.libraryPath, targetDirectory + TEST_DIR);
expect(phantomLibraryPathListingLength === fs.list(targetDirectory + TEST_DIR).length);
fs.removeTree(targetDirectory + TEST_DIR);
});
// TODO: test the actual functionality once we can create symlink.
it("should have readLink function", function() {
expect(typeof fs.readLink).toEqual('function');
});
fs.removeTree(TEST_DIR);
describe("fs.join(...)", function() {
var parts, expected, actual;
it("empty parts", function() {
parts = [];
expected = ".";
actual = fs.join.apply(null, parts);
expect(actual).toEqual(expected);
});
it("one part (empty string)", function() {
parts = [""];
expected = ".";
actual = fs.join.apply(null, parts);
expect(actual).toEqual(expected);
});
it("one part (array)", function() {
parts = [[], null];
expected = ".";
actual = fs.join.apply(null, parts);
expect(actual).toEqual(expected);
});
it("empty string and one part", function() {
parts = ["", "a"];
expected = "/a";
actual = fs.join.apply(null, parts);
expect(actual).toEqual(expected);
});
it("empty string and multiple parts", function() {
parts = ["", "a", "b", "c"];
expected = "/a/b/c";
actual = fs.join.apply(null, parts);
expect(actual).toEqual(expected);
});
it("empty string and multiple parts with empty strings", function() {
parts = ["", "a", "", "b", "", "c"];
expected = "/a/b/c";
actual = fs.join.apply(null, parts);
expect(actual).toEqual(expected);
});
it("multiple parts", function() {
parts = ["a", "b", "c"];
expected = "a/b/c";
actual = fs.join.apply(null, parts);
expect(actual).toEqual(expected);
});
it("multiple parts with empty strings", function() {
parts = ["a", "", "b", "", "c"];
expected = "a/b/c";
actual = fs.join.apply(null, parts);
expect(actual).toEqual(expected);
});
});
describe("fs.split(path)", function() {
var path, expected, actual;
it("should split absolute path with trailing separator", function() {
path = fs.separator + "a" + fs.separator + "b" + fs.separator + "c" + fs.separator + "d" + fs.separator;
actual = fs.split(path);
expected = ["", "a", "b", "c", "d"];
expect(actual).toEqual(expected);
});
it("should split absolute path without trailing separator", function() {
path = fs.separator + "a" + fs.separator + "b" + fs.separator + "c" + fs.separator + "d";
actual = fs.split(path);
expected = ["", "a", "b", "c", "d"];
expect(actual).toEqual(expected);
});
it("should split non-absolute path with trailing separator", function() {
path = "a" + fs.separator + "b" + fs.separator + "c" + fs.separator + "d" + fs.separator;
actual = fs.split(path);
expected = ["a", "b", "c", "d"];
expect(actual).toEqual(expected);
});
it("should split non-absolute path without trailing separator", function() {
path = "a" + fs.separator + "b" + fs.separator + "c" + fs.separator + "d";
actual = fs.split(path);
expected = ["a", "b", "c", "d"];
expect(actual).toEqual(expected);
});
it("should split path with consecutive separators", function() {
path = "a" + fs.separator + fs.separator + fs.separator + "b" + fs.separator + "c" + fs.separator + fs.separator + "d" + fs.separator + fs.separator + fs.separator;
expected = ["a", "b", "c", "d"];
actual = fs.split(path);
expect(actual).toEqual(expected);
});
});
});

View File

@ -1,70 +0,0 @@
describe("Tests Files API", function() {
var ABSENT_DIR = "absentdir04",
ABSENT_FILE = "absentfile04",
TEST_DIR = "testdir04",
TEST_FILE = "testfile04",
TEST_FILE_PATH = fs.join(TEST_DIR, TEST_FILE),
TEST_CONTENT = "test content",
START_CWD = null;
it("should create some temporary file and directory", function(){
fs.makeDirectory(TEST_DIR);
fs.write(TEST_FILE_PATH, TEST_CONTENT, "w");
});
it("should confirm that test file and test dir exist, while the absent ones don't", function(){
expect(fs.exists(TEST_FILE_PATH)).toBeTruthy();
expect(fs.exists(TEST_DIR)).toBeTruthy();
expect(fs.exists(ABSENT_FILE)).toBeFalsy();
expect(fs.exists(ABSENT_DIR)).toBeFalsy();
});
it("should confirm that the temporary directory is infact a directory, while the absent one doesn't", function(){
expect(fs.isDirectory(TEST_DIR)).toBeTruthy();
expect(fs.isDirectory(ABSENT_DIR)).toBeFalsy();
});
it("should confirm that the temporary file is infact a file, while the absent one doesn't", function(){
expect(fs.isFile(TEST_FILE_PATH)).toBeTruthy();
expect(fs.isFile(ABSENT_FILE)).toBeFalsy();
});
it("should confirm that a relative path is not absolute, while an absolute one is", function(){
var absPath = fs.absolute(TEST_FILE_PATH);
expect(fs.isAbsolute(TEST_FILE_PATH)).toBeFalsy();
expect(fs.isAbsolute(absPath)).toBeTruthy();
});
it("should confirm that temporary file is readable, writable and non-executable, while absent file is none of those", function(){
expect(fs.isReadable(TEST_FILE_PATH)).toBeTruthy();
expect(fs.isWritable(TEST_FILE_PATH)).toBeTruthy();
expect(fs.isExecutable(TEST_FILE_PATH)).toBeFalsy();
expect(fs.isReadable(ABSENT_FILE)).toBeFalsy();
expect(fs.isWritable(ABSENT_FILE)).toBeFalsy();
expect(fs.isExecutable(ABSENT_FILE)).toBeFalsy();
});
it("should confirm that temporary directory is readable, writable and executable, while absent dir is none of those", function(){
expect(fs.isReadable(TEST_DIR)).toBeTruthy();
expect(fs.isWritable(TEST_DIR)).toBeTruthy();
expect(fs.isExecutable(TEST_DIR)).toBeTruthy();
expect(fs.isReadable(ABSENT_DIR)).toBeFalsy();
expect(fs.isWritable(ABSENT_DIR)).toBeFalsy();
expect(fs.isExecutable(ABSENT_DIR)).toBeFalsy();
});
it("should confirm that neither temporary file/dir or absent file/dir are links", function(){
expect(fs.isLink(TEST_DIR)).toBeFalsy();
expect(fs.isLink(TEST_FILE_PATH)).toBeFalsy();
expect(fs.isLink(ABSENT_DIR)).toBeFalsy();
expect(fs.isLink(ABSENT_FILE)).toBeFalsy();
});
it("should delete the temporary directory and file", function(){
fs.removeTree(TEST_DIR);
});
});

220
test/module/fs/basics.js Normal file
View File

@ -0,0 +1,220 @@
// Basic Files API (read, write, remove, ...)
var FILENAME = "temp-01.test",
FILENAME_COPY = FILENAME + ".copy",
FILENAME_MOVED = FILENAME + ".moved",
FILENAME_EMPTY = FILENAME + ".empty",
FILENAME_ENC = FILENAME + ".enc",
FILENAME_BIN = FILENAME + ".bin",
ABSENT = "absent-01.test";
var fs;
setup(function () {
fs = require('fs');
var f = fs.open(FILENAME, "w");
f.write("hello");
f.writeLine("");
f.writeLine("world");
f.close();
});
test(function () {
assert_is_true(fs.exists(FILENAME));
// we might've gotten DOS line endings
assert_greater_than_equal(fs.size(FILENAME), "hello\nworld\n".length);
}, "create a file with contents");
test(function () {
assert_is_false(fs.exists(FILENAME_EMPTY));
fs.touch(FILENAME_EMPTY);
assert_is_true(fs.exists(FILENAME_EMPTY));
assert_equals(fs.size(FILENAME_EMPTY), 0);
}, "create (touch) an empty file");
test(function () {
var content = "";
var f = fs.open(FILENAME, "r");
this.add_cleanup(function () { f.close(); });
content = f.read();
assert_equals(content, "hello\nworld\n");
}, "read content from a file");
test(function () {
var content = "";
var f = fs.open(FILENAME, "r");
this.add_cleanup(function () { f.close(); });
f.seek(3);
content = f.read(5);
assert_equals(content, "lo\nwo");
}, "read specific number of bytes from a specific position in a file");
test(function () {
var content = "";
var f = fs.open(FILENAME, "rw+");
this.add_cleanup(function () { f.close(); });
f.writeLine("asdf");
content = f.read();
assert_equals(content, "hello\nworld\nasdf\n");
}, "append content to a file");
test(function () {
var f = fs.open(FILENAME, "r");
this.add_cleanup(function () { f.close(); });
assert_equals(f.getEncoding(), "UTF-8");
}, "get the file encoding (default: UTF-8)");
test(function () {
var f = fs.open(FILENAME, { charset: "UTF-8", mode: "r" });
this.add_cleanup(function () { f.close(); });
assert_equals(f.getEncoding(), "UTF-8");
var g = fs.open(FILENAME, { charset: "SJIS", mode: "r" });
this.add_cleanup(function () { g.close(); });
assert_equals(g.getEncoding(), "Shift_JIS");
}, "set the encoding on open");
test(function () {
var f = fs.open(FILENAME, { charset: "UTF-8", mode: "r" });
this.add_cleanup(function () { f.close(); });
assert_equals(f.getEncoding(), "UTF-8");
f.setEncoding("utf8");
assert_equals(f.getEncoding(), "UTF-8");
var g = fs.open(FILENAME, { charset: "SJIS", mode: "r" });
this.add_cleanup(function () { g.close(); });
assert_equals(g.getEncoding(), "Shift_JIS");
g.setEncoding("eucjp");
assert_equals(g.getEncoding(), "EUC-JP");
}, "change the encoding using setEncoding");
test(function () {
assert_is_false(fs.exists(FILENAME_COPY));
fs.copy(FILENAME, FILENAME_COPY);
assert_is_true(fs.exists(FILENAME_COPY));
assert_equals(fs.read(FILENAME), fs.read(FILENAME_COPY));
}, "copy a file");
test(function () {
assert_is_true(fs.exists(FILENAME));
var contentBeforeMove = fs.read(FILENAME);
fs.move(FILENAME, FILENAME_MOVED);
assert_is_false(fs.exists(FILENAME));
assert_is_true(fs.exists(FILENAME_MOVED));
assert_equals(fs.read(FILENAME_MOVED), contentBeforeMove);
}, "move a file");
test(function () {
assert_is_true(fs.exists(FILENAME_MOVED));
assert_is_true(fs.exists(FILENAME_COPY));
assert_is_true(fs.exists(FILENAME_EMPTY));
fs.remove(FILENAME_MOVED);
fs.remove(FILENAME_COPY);
fs.remove(FILENAME_EMPTY);
assert_is_false(fs.exists(FILENAME_MOVED));
assert_is_false(fs.exists(FILENAME_COPY));
assert_is_false(fs.exists(FILENAME_EMPTY));
}, "remove a file");
test(function () {
assert_throws("Unable to open file '"+ ABSENT +"'",
function () { fs.open(ABSENT, "r"); });
assert_throws("Unable to copy file '" + ABSENT +
"' at '" + FILENAME_COPY + "'",
function () { fs.copy(ABSENT, FILENAME_COPY); });
}, "operations on nonexistent files throw an exception");
test(function () {
var data = "ÄABCÖ";
var data_b = String.fromCharCode(
0xC3, 0x84, 0x41, 0x42, 0x43, 0xC3, 0x96);
var f = fs.open(FILENAME_ENC, "w");
this.add_cleanup(function () {
f.close();
fs.remove(FILENAME_ENC);
});
f.write(data);
f.close();
f = fs.open(FILENAME_ENC, "r");
assert_equals(f.read(), data);
var g = fs.open(FILENAME_ENC, "rb");
this.add_cleanup(function () { g.close(); });
assert_equals(g.read(), data_b);
}, "read/write UTF-8 text by default");
test(function () {
var data = "ピタゴラスイッチ";
var data_b = String.fromCharCode(
0x83, 0x73, 0x83, 0x5e, 0x83, 0x53, 0x83, 0x89,
0x83, 0x58, 0x83, 0x43, 0x83, 0x62, 0x83, 0x60);
var f = fs.open(FILENAME_ENC, { mode: "w", charset: "Shift_JIS" });
this.add_cleanup(function () {
f.close();
fs.remove(FILENAME_ENC);
});
f.write(data);
f.close();
f = fs.open(FILENAME_ENC, { mode: "r", charset: "Shift_JIS" });
assert_equals(f.read(), data);
var g = fs.open(FILENAME_ENC, "rb");
this.add_cleanup(function () { g.close(); });
assert_equals(g.read(), data_b);
}, "read/write Shift-JIS text with options");
test(function () {
var data = String.fromCharCode(0, 1, 2, 3, 4, 5);
var f = fs.open(FILENAME_BIN, "wb");
this.add_cleanup(function () {
f.close();
fs.remove(FILENAME_BIN);
});
f.write(data);
f.close();
f = fs.open(FILENAME_BIN, "rb");
assert_equals(f.read(), data);
}, "read/write binary data");
test(function () {
var data = String.fromCharCode(0, 1, 2, 3, 4, 5);
fs.write(FILENAME_BIN, data, "b");
this.add_cleanup(function () {
fs.remove(FILENAME_BIN);
});
assert_equals(fs.read(FILENAME_BIN, "b"), data);
}, "read/write binary data (shortcuts)");

View File

@ -0,0 +1,91 @@
var fs = require('fs');
var ABSENT_DIR = "absentdir02",
ABSENT_FILE = "absentfile02",
TEST_DIR = "testdir02",
TEST_FILE = "temp-02.test",
TEST_FILE_PATH = fs.join(TEST_DIR, TEST_FILE),
TEST_CONTENT = "test content",
CONTENT_MULTIPLIER = 1024;
test(function () {
assert_throws("Unable to read file '"+ ABSENT_FILE +"' size",
function () { fs.size(ABSENT_FILE); });
assert_equals(fs.lastModified(ABSENT_FILE), null);
}, "size/date queries on nonexistent files");
test(function () {
// Round down to the nearest multiple of two seconds, because
// file timestamps might only have that much precision.
var before_creation = Math.floor(Date.now() / 2000) * 2000;
var f = fs.open(TEST_FILE, "w");
this.add_cleanup(function () {
if (f !== null) f.close();
fs.remove(TEST_FILE);
});
for (var i = 0; i < CONTENT_MULTIPLIER; i++) {
f.write(TEST_CONTENT);
}
f.close(); f = null;
// Similarly, but round _up_.
var after_creation = Math.ceil(Date.now() / 2000) * 2000;
assert_equals(fs.size(TEST_FILE),
TEST_CONTENT.length * CONTENT_MULTIPLIER);
var flm = fs.lastModified(TEST_FILE).getTime();
assert_greater_than_equal(flm, before_creation);
assert_less_than_equal(flm, after_creation);
}, "size/date queries on existing files");
test(function () {
fs.makeDirectory(TEST_DIR);
this.add_cleanup(function () { fs.removeTree(TEST_DIR); });
fs.write(TEST_FILE_PATH, TEST_CONTENT, "w");
assert_is_true(fs.exists(TEST_FILE_PATH));
assert_is_true(fs.exists(TEST_DIR));
assert_is_false(fs.exists(ABSENT_FILE));
assert_is_false(fs.exists(ABSENT_DIR));
assert_is_true(fs.isDirectory(TEST_DIR));
assert_is_false(fs.isDirectory(ABSENT_DIR));
assert_is_true(fs.isFile(TEST_FILE_PATH));
assert_is_false(fs.isFile(ABSENT_FILE));
var absPath = fs.absolute(TEST_FILE_PATH);
assert_is_false(fs.isAbsolute(TEST_FILE_PATH));
assert_is_true(fs.isAbsolute(absPath));
assert_is_true(fs.isReadable(TEST_FILE_PATH));
assert_is_true(fs.isWritable(TEST_FILE_PATH));
assert_is_false(fs.isExecutable(TEST_FILE_PATH));
assert_is_false(fs.isReadable(ABSENT_FILE));
assert_is_false(fs.isWritable(ABSENT_FILE));
assert_is_false(fs.isExecutable(ABSENT_FILE));
assert_is_true(fs.isReadable(TEST_DIR));
assert_is_true(fs.isWritable(TEST_DIR));
assert_is_true(fs.isExecutable(TEST_DIR));
assert_is_false(fs.isReadable(ABSENT_DIR));
assert_is_false(fs.isWritable(ABSENT_DIR));
assert_is_false(fs.isExecutable(ABSENT_DIR));
assert_is_false(fs.isLink(TEST_DIR));
assert_is_false(fs.isLink(TEST_FILE_PATH));
assert_is_false(fs.isLink(ABSENT_DIR));
assert_is_false(fs.isLink(ABSENT_FILE));
}, "file types and access modes");

72
test/module/fs/paths.js Normal file
View File

@ -0,0 +1,72 @@
var fs = require('fs');
var system = require('system');
var TEST_DIR = "testdir",
TEST_FILE = "testfile",
START_CWD = fs.workingDirectory;
test(function () {
assert_is_true(fs.makeDirectory(TEST_DIR));
this.add_cleanup(function () { fs.removeTree(TEST_DIR); });
assert_is_true(fs.changeWorkingDirectory(TEST_DIR));
this.add_cleanup(function () { fs.changeWorkingDirectory(START_CWD); });
fs.write(TEST_FILE, TEST_FILE, "w");
var suffix = fs.join("", TEST_DIR, TEST_FILE),
abs = fs.absolute(".." + suffix),
lastIndex = abs.lastIndexOf(suffix);
assert_not_equals(lastIndex, -1);
assert_equals(lastIndex + suffix.length, abs.length);
}, "manipulation of current working directory");
test(function () {
fs.copyTree(phantom.libraryPath, TEST_DIR);
this.add_cleanup(function () { fs.removeTree(TEST_DIR); });
assert_deep_equals(fs.list(phantom.libraryPath), fs.list(TEST_DIR));
}, "copying a directory tree");
test(function () {
assert_type_of(fs.readLink, 'function');
// TODO: test the actual functionality once we can create symlinks.
}, "fs.readLink exists");
generate_tests(function fs_join_test (parts, expected) {
var actual = fs.join.apply(null, parts);
assert_equals(actual, expected);
}, [
[ "fs.join: []", [], "." ],
[ "fs.join: nonsense", [[], null], "." ],
[ "fs.join: 1 element", [""], "." ],
[ "fs.join: 2 elements", ["", "a"], "/a" ],
[ "fs.join: 3 elements", ["a", "b", "c"], "a/b/c" ],
[ "fs.join: 4 elements", ["", "a", "b", "c"], "/a/b/c" ],
[ "fs.join: empty elements", ["", "a", "", "b", "", "c"], "/a/b/c" ],
[ "fs.join: empty elements 2", ["a", "", "b", "", "c"], "a/b/c" ]
]);
generate_tests(function fs_split_test (input, expected) {
var path = input.join(fs.separator);
var actual = fs.split(path);
assert_deep_equals(actual, expected);
}, [
[ "fs.split: absolute",
["", "a", "b", "c", "d"], ["", "a", "b", "c", "d"] ],
[ "fs.split: absolute, trailing",
["", "a", "b", "c", "d", ""], ["", "a", "b", "c", "d"] ],
[ "fs.split: non-absolute",
["a", "b", "c", "d"], ["a", "b", "c", "d"] ],
[ "fs.split: non-absolute, trailing",
["a", "b", "c", "d", ""], ["a", "b", "c", "d"] ],
[ "fs.split: repeated separators",
["a", "", "", "",
"b", "",
"c", "", "",
"d", "", "", ""], ["a", "b", "c", "d"] ]
]);

View File

@ -0,0 +1,25 @@
test(function () {
assert_no_property(window, "WebServer",
"WebServer constructor should not be global");
var WebServer = require("webserver").create;
assert_type_of(WebServer, "function");
}, "WebServer constructor");
test(function () {
var server = require("webserver").create();
assert_not_equals(server, null);
assert_type_of(server, "object");
assert_equals(server.objectName, "WebServer");
assert_own_property(server, "port");
assert_type_of(server.port, "string");
assert_equals(server.port, "");
assert_type_of(server.listenOnPort, "function");
assert_type_of(server.newRequest, "function");
assert_type_of(server.close, "function");
}, "WebServer object properties");

View File

@ -0,0 +1,145 @@
var server, port, request_cb;
setup(function () {
server = require("webserver").create();
// Should be unable to listen on port 1 (FIXME: this might succeed if
// the test suite is being run with root privileges).
assert_is_false(server.listen(1, function () {}));
assert_equals(server.port, "");
// Find an unused port in the 1024--32767 range on which to run the
// rest of the tests. The function in "request_cb" will be called
// for each request; it is set appropriately by each test case.
for (var i = 1024; i < 32768; i++) {
if (server.listen(i, function(rq,rs){return request_cb(rq,rs);})) {
assert_equals(server.port, i.toString());
port = server.port;
return;
}
}
assert_unreached("unable to find a free TCP port for server tests");
},
{ "test_timeout": 1000 });
function arm_check_request (test, expected_postdata, expected_bindata,
expected_mimetype) {
request_cb = test.step_func(function check_request (request, response) {
try {
assert_type_of(request, "object");
assert_own_property(request, "url");
assert_own_property(request, "method");
assert_own_property(request, "httpVersion");
assert_own_property(request, "headers");
assert_type_of(request.headers, "object");
assert_type_of(response, "object");
assert_own_property(response, "statusCode");
assert_own_property(response, "headers");
assert_type_of(response.setHeaders, "function");
assert_type_of(response.setHeader, "function");
assert_type_of(response.header, "function");
assert_type_of(response.write, "function");
assert_type_of(response.writeHead, "function");
if (expected_postdata !== false) {
assert_equals(request.method, "POST");
assert_own_property(request, "post");
if (request.headers["Content-Type"] ===
"application/x-www-form-urlencoded") {
assert_own_property(request, "postRaw");
assert_type_of(request.postRaw, "string");
assert_type_of(request.post, "object");
assert_deep_equals(request.post, expected_postdata);
} else {
assert_no_property(request, "postRaw");
assert_type_of(request.post, "string");
assert_not_equals(request.post, expected_postdata);
}
}
if (expected_bindata !== false) {
response.setEncoding("binary");
response.setHeader("Content-Type", expected_mimetype);
response.write(expected_bindata);
} else {
response.write("request handled");
}
} finally {
response.close();
request_cb = test.unreached_func();
}
});
}
async_test(function () {
var page = require("webpage").create();
var url = "http://localhost:"+port+"/foo/bar.php?asdf=true";
arm_check_request(this, false, false);
page.open(url, this.step_func_done(function (status) {
assert_equals(status, "success");
assert_equals(page.plainText, "request handled");
}));
}, "basic request handling");
async_test(function () {
var page = require("webpage").create();
var url = "http://localhost:"+port+"/foo/bar.txt?asdf=true";
arm_check_request(this,
{"answer" : "42", "universe" : "expanding"}, false);
page.open(url, "post", "universe=expanding&answer=42",
{ "Content-Type" : "application/x-www-form-urlencoded" },
this.step_func_done(function (status) {
assert_equals(status, "success");
assert_equals(page.plainText, "request handled");
}));
}, "handling POST with application/x-www-form-urlencoded data");
async_test(function () {
var page = require("webpage").create();
var url = "http://localhost:"+port+"/foo/bar.txt?asdf=true";
arm_check_request(this,
{"answer" : "42", "universe" : "expanding"}, false);
page.open(url, "post", "universe=expanding&answer=42",
{ "Content-Type" : "application/json;charset=UTF-8" },
this.step_func_done(function (status) {
assert_equals(status, "success");
assert_equals(page.plainText, "request handled");
}));
}, "handling POST with ill-formed application/json data");
async_test(function () {
var page = require("webpage").create();
var url = "http://localhost:"+port+"/";
var fs = require("fs");
var png = fs.read(fs.join(phantom.libraryPath, "../../phantomjs.png"), "b");
arm_check_request(this, false, png, "image/png");
page.open(url, "get", this.step_func_done(function (status) {
assert_equals(status, "success");
function checkImg() {
var img = document.querySelector("img");
if (img) {
return { w: img.width, h: img.height };
} else {
return {};
}
}
// XFAIL: image doesn't load properly and we receive the dimensions of
// the ?-in-a-box placeholder
assert_object_equals(page.evaluate(checkImg), { w: 200, h: 200 });
}));
}, "handling binary data", {
skip: true, // crash: https://github.com/ariya/phantomjs/issues/13461
expected_fail: true // received image is corrupt:
// https://github.com/ariya/phantomjs/issues/13026
// and perhaps others
});

View File

@ -1,18 +0,0 @@
describe("Module", function() {
it("has filename property containing its absolute path", function() {
module.filename.should.match(/\/.*test\/module_spec.js/);
});
it("has id property equal to filename", function() {
module.id.should.equal(module.filename);
});
it("has dirname property containing absolute path to its directory", function() {
module.dirname.should.match(/\/.*test/);
});
it("its require() can be used externally", function() {
var exposed = require('dummy_exposed');
exposed.require('./dummy_file').should.equal('spec/node_modules/dummy_file');
});
});

View File

@ -0,0 +1,14 @@
// Issue 10690: the second page load used to crash on OSX.
var url = 'http://localhost:9180/regression/pjs-10690/index.html';
function do_test() {
var page = require('webpage').create();
page.open(url, this.step_func_done (function (status) {
assert_equals(status, "success");
page.release();
}));
}
async_test(do_test, "load a page with a downloadable font, once");
async_test(do_test, "load a page with a downloadable font, again");

View File

@ -0,0 +1,13 @@
var url =
"http://localhost:9180/regression/webkit-60448.html";
async_test(function () {
var p = require("webpage").create();
p.open(url, this.step_func_done(function (status) {
assert_equals(status, "success");
assert_is_true(p.evaluate(function () {
return document.getElementById("test") === null;
}));
}));
},
"remove an inline HTML element from the document");

View File

@ -1,215 +0,0 @@
describe("require()", function() {
it("loads 'webpage' native module", function() {
should.exist(require('webpage').create);
});
it("loads 'fs' native module", function() {
should.exist(require('fs').separator);
});
it("loads 'webserver' native module", function() {
should.exist(require('webserver').create);
});
it("loads 'cookiejar' native module", function() {
should.exist(require('cookiejar').create);
});
it("loads 'system' native module", function() {
require('system').platform.should.equal('phantomjs');
});
it("doesn't expose CoffeeScript", function() {
should.not.exist(window.CoffeeScript);
});
it("loads JSON modules", function() {
require('./json_dummy').message.should.equal('hello');
});
it("loads modules with specified extension", function() {
require('./dummy.js').should.equal('require/dummy');
});
it("caches modules", function() {
require('./empty').hello = 'hola';
require('./empty').hello.should.equal('hola');
});
it("supports cycles (circular dependencies)", function() {
var a = require('./a');
var b = require('./b');
a.b.should.equal(b);
b.a.should.equal(a);
});
it("has cache object attached containing cached modules", function() {
var exposed = require('dummy_exposed');
should.exist(require.cache);
require.cache[module.filename].should.equal(module);
require.cache[exposed.filename].should.equal(exposed);
});
it("throws an error with appropriate message when module not found", function() {
(function() {
require('dummy_missing');
}).should.Throw("Cannot find module 'dummy_missing'");
});
xit("maintains proper .stack when module not found", function() {
try {
require('./not_found').requireNonExistent();
} catch (e) {
e.stack.should.match(/\n *at .*not_found\.js:2\n/);
}
});
xit("maintains proper .stack when an error is thrown in module's exports", function() {
try {
require('./thrower').fn();
} catch (e) {
e.stack.should.match(/^Error: fn\n *at .*thrower\.js:2/);
}
});
describe("stub()", function() {
it("stubs modules in given context", function() {
require('./stubber').stubbed.should.equal('stubbed module');
});
it("stubs modules in child context", function() {
require('./stubber').child.stubbed.should.equal('stubbed module');
});
it("doesn't stub in parent context", function() {
(function() {
require('stubbed');
}).should.Throw("Cannot find module 'stubbed'");
});
describe("when invoked with a factory function", function() {
var count = 0;
require.stub('lazily_stubbed', function() {
++count;
return 'lazily stubbed module';
});
it("initializes the module lazily", function() {
require('lazily_stubbed').should.equal('lazily stubbed module');
});
it("doesn't reinitialize the module each time it's required", function() {
require('lazily_stubbed');
count.should.equal(1);
});
});
});
describe("when the path is relative", function() {
it("loads modules from the same directory", function() {
require('./dummy').should.equal('require/dummy');
});
it("loads modules from the parent directory", function() {
require('../dummy').should.equal('spec/dummy');
});
it("loads modules from a child directory", function() {
require('./dir/dummy').should.equal('dir/dummy');
});
it("loads modules from a deeper directory", function() {
require('./dir/subdir/dummy').should.equal('subdir/dummy');
});
it("loads modules when path has intertwined '..'", function() {
require('./dir/../dummy').should.equal('require/dummy');
});
it("loads modules when path has intertwined '.'", function() {
require('./dir/./dummy').should.equal('dir/dummy');
});
});
describe("when loading from node_modules", function() {
it("first tries to load from ./node_modules", function() {
require('dummy_file').should.equal('require/node_modules/dummy_file');
});
it("loads from ../node_modules", function() {
require('dummy_file2').should.equal('spec/node_modules/dummy_file2');
});
it("loads from further up the directory tree", function() {
require('./dir/subdir/loader').dummyFile2.should.equal('spec/node_modules/dummy_file2');
});
describe("when module is a directory", function() {
it("first tries to load the path from package.json", function() {
require('dummy_module').should.equal('require/node_modules/dummy_module');
});
it("loads index.js if package.json not found", function() {
require('dummy_module2').should.equal('require/node_modules/dummy_module2');
});
});
});
describe("when path is absolute", function() {
it("loads modules from the absolute path", function() {
require(fs.absolute('dummy')).should.equal('spec/dummy');
});
});
describe("with require.paths", function() {
describe("when require.paths.push(relative)", function() {
it("add relative path to paths", function() {
require.paths.push('./dir/subdir');
});
it("loads 'loader' module in dir/subdir", function() {
require('loader').dummyFile2.should.equal('spec/node_modules/dummy_file2');
});
it("loads 'loader' module in dir/subdir2 relative to require.paths", function() {
require('../subdir2/loader').should.equal('require/subdir2/loader');
});
it("loads 'dummy' module from the path that takes precedence", function() {
require('../dummy').should.equal('spec/dummy');
});
it("doesn't load 'loader' module in dir/subdir after require.paths.pop()", function() {
(function() {
require.paths.pop();
require('loader');
}).should.Throw("Cannot find module 'loader'");
});
});
describe("when require.paths.push(absolute)", function() {
it("adds absolute path to paths", function() {
require.paths.push(fs.absolute('require/dir/subdir'));
});
it("loads 'loader' module in dir/subdir", function() {
require('loader').dummyFile2.should.equal('spec/node_modules/dummy_file2');
});
it("loads 'loader' module in dir/subdir2 relative to require.paths", function() {
require('../subdir2/loader').should.equal('require/subdir2/loader');
});
it("loads 'dummy' module from the path that takes precedence", function() {
require('../dummy').should.equal('spec/dummy');
});
it("doesn't load 'loader' module in dir/subdir after require.paths.pop()", function() {
(function() {
require.paths.pop();
require('loader');
}).should.Throw("Cannot find module 'loader'");
});
});
});
});

View File

@ -1,3 +0,0 @@
exports.fn = function() {
throw new Error('fn');
};

View File

@ -64,16 +64,7 @@ function expectHasPropertyString(o, name) {
}
// Load specs
phantom.injectJs("./phantom-spec.js");
phantom.injectJs("./webserver-spec.js");
phantom.injectJs("./fs-spec-01.js"); //< Filesystem Specs 01 (Basic)
phantom.injectJs("./fs-spec-02.js"); //< Filesystem Specs 02 (Attributes)
phantom.injectJs("./fs-spec-03.js"); //< Filesystem Specs 03 (Paths)
phantom.injectJs("./fs-spec-04.js"); //< Filesystem Specs 04 (Tests)
phantom.injectJs("./webkit-spec.js");
phantom.injectJs("./webpage-spec.js");
require("./module_spec.js");
require("./require/require_spec.js");
// Environment configuration
var jasmineEnv = jasmine.getEnv();

View File

@ -1,12 +0,0 @@
var page = require('webpage').create();
var url = 'http://localhost:5000';
page.open(url, function (status) {
console.log('Page loaded once', status);
page.release();
page = require('webpage').create();
page.open(url, function (status) {
console.log('Page loaded twice', status);
phantom.exit();
});
});

View File

@ -1,25 +0,0 @@
#!/usr/bin/env ruby
# From http://chrismdp.com/2011/12/cache-busting-ruby-http-server/
require 'webrick'
class NonCachingFileHandler < WEBrick::HTTPServlet::FileHandler
def prevent_caching(res)
res['ETag'] = nil
res['Last-Modified'] = Time.now + 100**4
res['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
res['Pragma'] = 'no-cache'
res['Expires'] = Time.now - 100**4
end
def do_GET(req, res)
super
prevent_caching(res)
end
end
server = WEBrick::HTTPServer.new :Port => 5000
server.mount '/', NonCachingFileHandler , Dir.pwd
trap('INT') { server.stop }
server.start

View File

@ -1,7 +0,0 @@
describe("WebKit", function() {
it("should not crash when failing to dirty lines while removing a inline.", function () {
var p = require("webpage").create();
p.open('../test/webkit-spec/inline-destroy-dirty-lines-crash.html');
waits(50);
});
});

View File

@ -1,192 +0,0 @@
describe("WebServer constructor", function() {
it("should not exist in window", function() {
expect(window.hasOwnProperty('WebServer')).toBeFalsy();
});
it("should be a function", function() {
var WebServer = require('webserver').create;
expect(typeof WebServer).toEqual('function');
});
});
var expectedPostData = false, expectedBinaryData = false;
function checkRequest(request, response) {
expect(typeof request).toEqual('object');
expect(request.hasOwnProperty('url')).toBeTruthy();
expect(request.hasOwnProperty('method')).toBeTruthy();
expect(request.hasOwnProperty('httpVersion')).toBeTruthy();
expect(request.hasOwnProperty('headers')).toBeTruthy();
expect(typeof request.headers).toEqual('object');
expect(typeof response).toEqual('object');
expect(response.hasOwnProperty('statusCode')).toBeTruthy();
expect(response.hasOwnProperty('headers')).toBeTruthy();
expect(typeof response['setHeaders']).toEqual('function');
expect(typeof response['setHeader']).toEqual('function');
expect(typeof response['header']).toEqual('function');
expect(typeof response['write']).toEqual('function');
expect(typeof response['writeHead']).toEqual('function');
if (expectedPostData !== false) {
expect(request.method).toEqual("POST");
expect(request.hasOwnProperty('post')).toBeTruthy();
jasmine.log("request.post => " + JSON.stringify(request.post, null, 4));
jasmine.log("expectedPostData => " + JSON.stringify(expectedPostData, null, 4));
jasmine.log("request.headers => " + JSON.stringify(request.headers, null, 4));
if (request.headers["Content-Type"] && request.headers["Content-Type"] === "application/x-www-form-urlencoded") {
expect(typeof request.post).toEqual('object');
expect(request.post).toEqual(expectedPostData);
expect(request.hasOwnProperty('postRaw')).toBeTruthy();
expect(typeof request.postRaw).toEqual('string');
} else {
expect(typeof request.post).toEqual('string');
expect(request.post).toNotEqual(expectedPostData);
expect(request.hasOwnProperty('postRaw')).toBeFalsy();
}
expectedPostData = false;
}
if (expectedBinaryData !== false) {
response.setEncoding('binary');
response.write(expectedBinaryData);
expectedBinaryData = false;
} else {
response.write("request handled");
}
response.close();
}
describe("WebServer object", function() {
var server = require('webserver').create();
it("should be creatable", function() {
expect(typeof server).toEqual('object');
expect(server).toNotEqual(null);
});
it("should have objectName as 'WebServer'", function() {
expect(server.objectName).toEqual('WebServer');
});
expectHasProperty(server, 'port');
it("should have port as string", function() {
expect(typeof server.port).toEqual('string');
});
it("should not listen to any port by default", function() {
expect(server.port).toEqual("");
});
/* TODO:
expectHasProperty(page, 'settings');
it("should have non-empty settings", function() {
expect(page.settings).toNotEqual(null);
expect(page.settings).toNotEqual({});
});
*/
expectHasFunction(server, 'listenOnPort');
expectHasFunction(server, 'newRequest');
expectHasFunction(server, 'close');
it("should fail to listen to blocked ports", function() {
//NOTE: is this really blocked everywhere?
expect(server.listen(1, function(){})).toEqual(false);
expect(server.port).toEqual("");
});
it("should be able to listen to some port", function() {
//NOTE: this can fail if the port is already being listend on...
expect(server.listen("1337", checkRequest)).toEqual(true);
expect(server.port).toEqual("1337");
});
it("should handle requests", function() {
var page = require('webpage').create();
var url = "http://localhost:1337/foo/bar.php?asdf=true";
var handled = false;
runs(function() {
expect(handled).toEqual(false);
page.open(url, function (status) {
expect(status == 'success').toEqual(true);
expect(page.plainText).toEqual("request handled");
handled = true;
});
});
waits(50);
runs(function() {
expect(handled).toEqual(true);
});
});
it("should handle post requests ('Content-Type' = 'application/x-www-form-urlencoded')", function() {
var page = require('webpage').create();
var url = "http://localhost:1337/foo/bar.txt?asdf=true";
//note: sorted by key (map)
expectedPostData = {'answer' : "42", 'universe' : "expanding"};
var handled = false;
runs(function() {
expect(handled).toEqual(false);
page.open(url, 'post', "universe=expanding&answer=42", { "Content-Type" : "application/x-www-form-urlencoded" }, function (status) {
expect(status == 'success').toEqual(true);
expect(page.plainText).toEqual("request handled");
handled = true;
});
});
waits(50);
runs(function() {
expect(handled).toEqual(true);
});
});
it("should handle post requests ('Content-Type' = 'ANY')", function() {
var page = require('webpage').create();
var url = "http://localhost:1337/foo/bar.txt?asdf=true";
//note: sorted by key (map)
expectedPostData = {'answer' : "42", 'universe' : "expanding"};
var handled = false;
runs(function() {
expect(handled).toEqual(false);
page.open(url, 'post', "universe=expanding&answer=42", { "Content-Type" : "application/json;charset=UTF-8" }, function (status) {
expect(status == 'success').toEqual(true);
expect(page.plainText).toEqual("request handled");
handled = true;
});
});
waits(50);
runs(function() {
expect(handled).toEqual(true);
});
});
xit("should handle binary data", function() {
var page = require('webpage').create();
var url = "http://localhost:1337/";
var fs = require('fs');
expectedBinaryData = fs.read('phantomjs.png', 'b');
var handled = false;
runs(function() {
expect(handled).toEqual(false);
page.open(url, 'get', function(status) {
expect(status == 'success').toEqual(true);
function checkImg() {
var img = document.querySelector('img');
return (img) && (img.width == 200) && (img.height == 200);
}
expect(page.evaluate(checkImg)).toEqual(true);
handled = true;
});
});
waits(50);
runs(function() {
expect(handled).toEqual(true);
});
});
});

Binary file not shown.

View File

@ -1,9 +1,7 @@
@font-face {
font-family: 'WindsongRegular';
src: url("https://github.com/fukawi2/.fonts/raw/master/Windsong.ttf") format("truetype");
src: url("Windsong.ttf") format("truetype");
}
h1 {
font: 90px/98px "WindsongRegular", Arial, sans-serif;
}