Repository navigation
Expand file tree
/
Copy pathdocs.js
More file actions
279 lines (241 loc) · 6.97 KB
/
Copy pathdocs.js
File metadata and controls
279 lines (241 loc) · 6.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed 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.
*/
'use strict';
var createErrorClass = require('create-error-class');
var format = require('string-format-obj');
var fs = require('fs');
var glob = require('glob');
var jshint = require('jshint').JSHINT;
var mitm = require('mitm');
var multiline = require('multiline');
var overviews = require('../scripts/docs/config').OVERVIEW;
var path = require('path');
var prop = require('propprop');
var vm = require('vm');
var rootFile = 'index.json';
var noop = function() {};
var DocsError = createErrorClass('DocsError', function(err, code) {
var lineCol = err.stack.match('assert-code\.vm:(.+)');
lineCol.line = lineCol[1];
var lines = code
.split('\n')
.filter(function(line, index) {
return index < lineCol.line && line;
})
.join('\n');
this.message = format('\n{lines}\n\n{message}', {
lines: lines,
message: err.message
});
});
var JSHintError = createErrorClass('JSHintError', function(err) {
this.message = format('"{evidence}" - {reason}', {
evidence: err.evidence.trim(),
reason: err.reason
});
this.code = err.code;
});
var FakeConsole = Object.keys(console)
.reduce(function(console, method) {
console[method] = noop;
return console;
}, {});
// For {module:datastore} docs.
var FakeExpress = function() {
return {
get: function(route, callback) {
callback({ query: {} }, {});
}
};
};
// For {module:vision} docs.
var FakeLevel = function() {
return {
get: function(key, options, callback) {
callback(null, 'image.jpg');
}
};
};
// For {module:speech} docs.
var FakeFs = function() {
return {
writeFile: function(name, contents, callback) {
callback(null);
},
readFile: function(filename, callback) {
callback(null, new Buffer(''));
},
readFileSync: function() {
return new Buffer('');
},
createWriteStream: function() {
return require('through2')();
},
createReadStream: function() {
return require('through2')();
}
};
};
// For {module:google-cloud} docs.
var FakeBluebird = function() {
return Promise;
};
// For {module:logging-winston} docs.
var fakeWinston = '{ add: function() {}, emerg: function() {} }';
var modules;
if (process.env.TEST_MODULE) {
modules = [process.env.TEST_MODULE];
} else {
modules = fs.readdirSync('docs/json');
}
modules.forEach(function(mod) {
describe(mod + ' documentation', function() {
var MITM;
var docFiles = getDocs(mod);
var moduleInstantationCode = createInstantiationCode(mod);
var sandbox = {
require: require,
process: process,
console: FakeConsole,
Buffer: Buffer,
Date: Date,
Array: Array,
global: global
};
before(function() {
// Set a global to indicate to any interested function inside of gcloud
// that this is a sandbox environment.
global.GCLOUD_SANDBOX_ENV = true;
// Turn off the network so that API calls aren't actually made.
MITM = mitm();
});
after(function() {
delete global.GCLOUD_SANDBOX_ENV;
// Re-enable the network.
MITM.disable();
});
docFiles.forEach(function(docFile) {
docFile.methods
.filter(function(method) {
return method.examples && method.examples.length;
})
.forEach(function(method) {
var name = [docFile.name, method.name].join('#');
var snippet = createSnippet(mod, moduleInstantationCode, method);
it('should run ' + name + ' examples without errors', function() {
jshint(snippet, {
// in several snippets we give an example as to how to access
// a property (like metadata) without doing anything with it
// e.g. `list[0].metadata`
expr: true,
// this allows us to redefine variables, generally it's bad, buuut
// for copy/paste purposes this is desirable within the docs
shadow: true
});
if (jshint.errors.length) {
throw new JSHintError(jshint.errors[0]);
}
runCodeInSandbox(snippet, sandbox);
});
});
});
});
});
function getDocs(mod) {
return glob
.sync('docs/json/' + mod + '/*/*.json', {
ignore: [
'**/toc.json',
'**/types.json'
]
})
.sort(function(a, b) {
if (a.indexOf(rootFile) > -1) {
return -1;
}
if (b.indexOf('index.json') > -1) {
return 1;
}
})
.map(function(filename) {
return require(path.resolve(filename));
});
}
function createInstantiationCode(mod) {
var config = overviews[mod] || {};
if (config.skip) {
return;
}
return format(multiline.stripIndent(function() {/*
var {instanceName} = require('{path}')({config});
var api = {instanceName}.api;
if (api) {
Object.keys(api).forEach(function(apiName) {
Object.keys(api[apiName]).forEach(function(method) {
api[apiName][method] = function() {};
});
});
}
*/}), {
instanceName: config.instanceName || mod,
path: '../packages/' + mod,
config: JSON.stringify({
// All of the minimum required options our APIs expect.
projectId: 'grape-spaceship-123',
key: 'apiKey'
})
});
}
function createSnippet(mod, instantiation, method) {
var examples = method.examples.map(prop('code'));
examples.unshift(instantiation);
return examples
.join('\n')
.replace(
/require\('google-cloud'\)/g,
'require(\'../packages/google-cloud\')'
)
.replace(
'require(\'@google-cloud/logging-winston\')',
'{}'
)
.replace(
/require\('(@google-cloud\/[^']*)/g,
'require(\'../packages/' + mod + '/node_modules/$1'
)
.replace(
'keyFilename: \'/path/to/keyfile.json\'',
'keyFilename: \'\''
)
.replace('require(\'express\')', FakeExpress.toString())
.replace('require(\'level\')', FakeLevel.toString())
.replace('require(\'bluebird\')', FakeBluebird.toString())
.replace('require(\'winston\')', fakeWinston)
.replace('require(\'fs\')', '(' + FakeFs.toString() + '())');
}
function runCodeInSandbox(code, sandbox) {
vm.createContext(sandbox);
try {
vm.runInNewContext(code, sandbox, {
filename: 'assert-code.vm',
timeout: 5000
});
} catch (err) {
var docsErr = new DocsError(err, code);
docsErr.stack = err.stack;
throw docsErr;
}
}