UNPKG

2.58 kBJavaScriptView Raw
1'use strict';
2
3var realFs = require('fs');
4var path = require('path');
5
6var rewire = require('rewire');
7var semver = require('semver');
8
9var Binding = require('./binding');
10var FileSystem = require('./filesystem');
11
12var versions = {
13 '0.8.x': 'fs-0.8.26.js',
14 '0.9.x': 'fs-0.9.12.js',
15 '0.10.x': 'fs-0.10.28.js',
16 '0.11 - 0.11.14': 'fs-0.11.13.js',
17 '0.11.15 - 0.12.x': 'fs-0.12.0.js',
18 '1.x.x': 'fs-1.1.0.js'
19};
20var nodeVersion = process.versions.node;
21var fsName;
22
23Object.keys(versions).forEach(function (version) {
24 if (semver.satisfies(nodeVersion, version)) {
25 fsName = versions[version];
26 return false;
27 }
28});
29
30if (!fsName) {
31 throw new Error('Unsupported Node version: ' + nodeVersion);
32}
33
34
35/**
36 * Hijack the real fs module immediately so the binding can be swapped at will.
37 * This works as expected in cases where mock-fs is required before any other
38 * module that wraps fs exports.
39 */
40var mockFs = rewire(path.join(__dirname, '..', 'node', fsName));
41var originalBinding = mockFs.__get__('binding');
42var originalStats = mockFs.Stats;
43for (var name in mockFs) {
44 var descriptor = Object.getOwnPropertyDescriptor(realFs, name);
45
46 if (!descriptor || descriptor && descriptor.writable) {
47 realFs[name] = mockFs[name];
48 }
49}
50
51function setBinding(binding, Stats) {
52 mockFs.__set__('binding', binding);
53 mockFs.Stats = realFs.Stats = Stats;
54}
55
56
57/**
58 * Swap out the fs bindings for a mock file system.
59 * @param {Object} config Mock file system configuration.
60 */
61var exports = module.exports = function mock(config) {
62 var system = FileSystem.create(config);
63 var binding = new Binding(system);
64 setBinding(binding, binding.Stats);
65};
66
67
68/**
69 * Restore the fs bindings for the real file system.
70 */
71exports.restore = function() {
72 setBinding(originalBinding, originalStats);
73};
74
75
76/**
77 * Create a mock fs module based on the given file system configuration.
78 * @param {Object} config File system configuration.
79 * @return {Object} A fs module with a mock file system.
80 */
81exports.fs = function(config) {
82 var system = FileSystem.create(config);
83 var binding = new Binding(system);
84
85 // inject the mock binding
86 var mockFs = rewire(path.join(__dirname, '..', 'node', fsName));
87 mockFs.__set__('binding', binding);
88
89 // overwrite fs.Stats from original binding
90 mockFs.Stats = binding.Stats;
91
92 return mockFs;
93};
94
95
96/**
97 * Create a file factory.
98 */
99exports.file = FileSystem.file;
100
101
102/**
103 * Create a directory factory.
104 */
105exports.directory = FileSystem.directory;
106
107
108/**
109 * Create a symbolic link factory.
110 */
111exports.symlink = FileSystem.symlink;