summaryrefslogtreecommitdiffstats
path: root/lib/fs/mock.js
diff options
context:
space:
mode:
authorSamy Pesse <samypesse@gmail.com>2016-04-26 10:23:37 +0200
committerSamy Pesse <samypesse@gmail.com>2016-04-26 10:23:37 +0200
commit374ebd6f7a77bfbde00f5d1e730403afd86e018f (patch)
tree55b8a6caca567cc76a5cf9028ec6206fa4370207 /lib/fs/mock.js
parentab2ebefe2bb6dee75e064c1ad572749e3f8104d1 (diff)
downloadgitbook-374ebd6f7a77bfbde00f5d1e730403afd86e018f.zip
gitbook-374ebd6f7a77bfbde00f5d1e730403afd86e018f.tar.gz
gitbook-374ebd6f7a77bfbde00f5d1e730403afd86e018f.tar.bz2
Add mock fs and tests for it
Diffstat (limited to 'lib/fs/mock.js')
-rw-r--r--lib/fs/mock.js101
1 files changed, 101 insertions, 0 deletions
diff --git a/lib/fs/mock.js b/lib/fs/mock.js
new file mode 100644
index 0000000..6c2670b
--- /dev/null
+++ b/lib/fs/mock.js
@@ -0,0 +1,101 @@
+var path = require('path');
+var is = require('is');
+var Buffer = require('buffer').Buffer;
+var Immutable = require('immutable');
+
+var FS = require('../models/fs');
+var error = require('../utils/error');
+
+/**
+ Create a fake filesystem for testing books
+
+ @param {Map<String:File>}
+*/
+function createMockFS(files) {
+ files = Immutable.fromJS(files);
+ var mtime = new Date();
+
+ /**
+ Get a file by resolving its path
+
+ @param {String}
+ @return {String|Map|null}
+ */
+ function getFile(filePath) {
+ var parts = path.normalize(filePath).split('/');
+ return parts.reduce(function(list, part, i) {
+ if (!list) return null;
+
+ var file;
+
+ if (!part || part === '.') file = list;
+ else file = list.get(part);
+
+ if (!file) return null;
+
+ if (is.string(file)) {
+ if (i === (parts.length - 1)) return file;
+ else return null;
+ }
+
+ return file;
+ }, files);
+ }
+
+ function fsExists(filePath) {
+ return Boolean(getFile(filePath) !== null);
+ }
+
+ function fsReadFile(filePath) {
+ var file = getFile(filePath);
+ if (!is.string(file)) {
+ throw error.FileNotFoundError({
+ filename: filePath
+ });
+ }
+
+ return new Buffer(file, 'utf8');
+ }
+
+ function fsStatFile(filePath) {
+ var file = getFile(filePath);
+ if (!file) {
+ throw error.FileNotFoundError({
+ filename: filePath
+ });
+ }
+
+ return {
+ mtime: mtime
+ };
+ }
+
+ function fsReadDir(filePath) {
+ var dir = getFile(filePath);
+ if (!dir || is.string(dir)) {
+ throw error.FileNotFoundError({
+ filename: filePath
+ });
+ }
+
+ return dir
+ .map(function(content, name) {
+ if (!is.string(content)) {
+ name = name + '/';
+ }
+
+ return name;
+ })
+ .valueSeq();
+ }
+
+ return FS.create({
+ root: '',
+ fsExists: fsExists,
+ fsReadFile: fsReadFile,
+ fsStatFile: fsStatFile,
+ fsReadDir: fsReadDir
+ });
+}
+
+module.exports = createMockFS;