UNPKG

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