-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathFilesController.spec.js
316 lines (272 loc) · 11.8 KB
/
FilesController.spec.js
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
const LoggerController = require('../lib/Controllers/LoggerController').LoggerController;
const WinstonLoggerAdapter = require('../lib/Adapters/Logger/WinstonLoggerAdapter')
.WinstonLoggerAdapter;
const GridFSBucketAdapter = require('../lib/Adapters/Files/GridFSBucketAdapter')
.GridFSBucketAdapter;
const Config = require('../lib/Config');
const FilesController = require('../lib/Controllers/FilesController').default;
const databaseURI = 'mongodb://localhost:27017/parse';
const mockAdapter = {
createFile: () => {
return Promise.reject(new Error('it failed with xyz'));
},
deleteFile: () => {},
getFileData: () => {},
getFileLocation: () => 'xyz',
validateFilename: () => {
return null;
},
};
// Small additional tests to improve overall coverage
describe('FilesController', () => {
it('should properly expand objects with sync getFileLocation', async () => {
const config = Config.get(Parse.applicationId);
const gridFSAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse');
gridFSAdapter.getFileLocation = (config, filename) => {
return config.mount + '/files/' + config.applicationId + '/' + encodeURIComponent(filename);
}
const filesController = new FilesController(gridFSAdapter);
const result = await filesController.expandFilesInObject(config, function () { });
expect(result).toBeUndefined();
const fullFile = {
type: '__type',
url: 'http://an.url',
};
const anObject = {
aFile: fullFile,
};
await filesController.expandFilesInObject(config, anObject);
expect(anObject.aFile.url).toEqual('http://an.url');
});
it('should properly expand objects with async getFileLocation', async () => {
const config = Config.get(Parse.applicationId);
const gridFSAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse');
gridFSAdapter.getFileLocation = async (config, filename) => {
await Promise.resolve();
return config.mount + '/files/' + config.applicationId + '/' + encodeURIComponent(filename);
}
const filesController = new FilesController(gridFSAdapter);
const result = await filesController.expandFilesInObject(config, function () { });
expect(result).toBeUndefined();
const fullFile = {
type: '__type',
url: 'http://an.url',
};
const anObject = {
aFile: fullFile,
};
await filesController.expandFilesInObject(config, anObject);
expect(anObject.aFile.url).toEqual('http://an.url');
});
it('should call getFileLocation when config.fileKey is undefined', async () => {
const config = {};
const gridFSAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse');
const fullFile = {
name: 'mock-name',
__type: 'File',
};
gridFSAdapter.getFileLocation = jasmine.createSpy('getFileLocation').and.returnValue(Promise.resolve('mock-url'));
const filesController = new FilesController(gridFSAdapter);
const anObject = { aFile: fullFile };
await filesController.expandFilesInObject(config, anObject);
expect(gridFSAdapter.getFileLocation).toHaveBeenCalledWith(config, fullFile.name);
expect(anObject.aFile.url).toEqual('mock-url');
});
it('should call getFileLocation when config.fileKey is defined', async () => {
const config = { fileKey: 'mock-key' };
const gridFSAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse');
const fullFile = {
name: 'mock-name',
__type: 'File',
};
gridFSAdapter.getFileLocation = jasmine.createSpy('getFileLocation').and.returnValue(Promise.resolve('mock-url'));
const filesController = new FilesController(gridFSAdapter);
const anObject = { aFile: fullFile };
await filesController.expandFilesInObject(config, anObject);
expect(gridFSAdapter.getFileLocation).toHaveBeenCalledWith(config, fullFile.name);
expect(anObject.aFile.url).toEqual('mock-url');
});
it_only_db('mongo')('should pass databaseOptions to GridFSBucketAdapter', async () => {
await reconfigureServer({
databaseURI: 'mongodb://localhost:27017/parse',
filesAdapter: null,
databaseAdapter: null,
databaseOptions: {
retryWrites: true,
},
});
const config = Config.get(Parse.applicationId);
expect(config.database.adapter._mongoOptions.retryWrites).toBeTrue();
expect(config.filesController.adapter._mongoOptions.retryWrites).toBeTrue();
expect(config.filesController.adapter._mongoOptions.enableSchemaHooks).toBeUndefined();
expect(config.filesController.adapter._mongoOptions.schemaCacheTtl).toBeUndefined();
});
it('should create a server log on failure', done => {
const logController = new LoggerController(new WinstonLoggerAdapter());
reconfigureServer({ filesAdapter: mockAdapter })
.then(() => new Parse.File('yolo.txt', [1, 2, 3], 'text/plain').save())
.then(
() => done.fail('should not succeed'),
() => setImmediate(() => Promise.resolve('done'))
)
.then(() => new Promise(resolve => setTimeout(resolve, 200)))
.then(() => logController.getLogs({ from: Date.now() - 1000, size: 1000 }))
.then(logs => {
// we get two logs here: 1. the source of the failure to save the file
// and 2 the message that will be sent back to the client.
const log1 = logs.find(x => x.message === 'Error creating a file: it failed with xyz');
expect(log1.level).toBe('error');
const log2 = logs.find(x => x.message === 'it failed with xyz');
expect(log2.level).toBe('error');
expect(log2.code).toBe(130);
done();
});
});
it('should create a parse error when a string is returned', done => {
const mock2 = mockAdapter;
mock2.validateFilename = () => {
return 'Bad file! No biscuit!';
};
const filesController = new FilesController(mockAdapter);
const error = filesController.validateFilename();
expect(typeof error).toBe('object');
expect(error.message.indexOf('biscuit')).toBe(13);
expect(error.code).toBe(Parse.Error.INVALID_FILE_NAME);
mockAdapter.validateFilename = () => {
return null;
};
done();
});
it('should add a unique hash to the file name when the preserveFileName option is false', async () => {
const config = Config.get(Parse.applicationId);
const gridFSAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse');
spyOn(gridFSAdapter, 'createFile');
gridFSAdapter.createFile.and.returnValue(Promise.resolve());
const fileName = 'randomFileName.pdf';
const regexEscapedFileName = fileName.replace(/\./g, '\\$&');
const filesController = new FilesController(gridFSAdapter, null, {
preserveFileName: false,
});
await filesController.createFile(config, fileName);
expect(gridFSAdapter.createFile).toHaveBeenCalledTimes(1);
expect(gridFSAdapter.createFile.calls.mostRecent().args[0]).toMatch(
`^.{32}_${regexEscapedFileName}$`
);
});
it('should not add a unique hash to the file name when the preserveFileName option is true', async () => {
const config = Config.get(Parse.applicationId);
const gridFSAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse');
spyOn(gridFSAdapter, 'createFile');
gridFSAdapter.createFile.and.returnValue(Promise.resolve());
const fileName = 'randomFileName.pdf';
const filesController = new FilesController(gridFSAdapter, null, {
preserveFileName: true,
});
await filesController.createFile(config, fileName);
expect(gridFSAdapter.createFile).toHaveBeenCalledTimes(1);
expect(gridFSAdapter.createFile.calls.mostRecent().args[0]).toEqual(fileName);
});
it('should handle adapter without getMetadata', async () => {
const gridFSAdapter = new GridFSBucketAdapter(databaseURI);
gridFSAdapter.getMetadata = null;
const filesController = new FilesController(gridFSAdapter);
const result = await filesController.getMetadata();
expect(result).toEqual({});
});
it('should reject slashes in file names', done => {
const gridFSAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse');
const fileName = 'foo/randomFileName.pdf';
expect(gridFSAdapter.validateFilename(fileName)).not.toBe(null);
done();
});
it('should also reject slashes in file names', done => {
const gridFSAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse');
const fileName = 'foo/randomFileName.pdf';
expect(gridFSAdapter.validateFilename(fileName)).not.toBe(null);
done();
});
it('should return valid filename or url from createFile response when provided', async () => {
const config = Config.get(Parse.applicationId);
// Test case 1: adapter returns new filename and url
const adapterWithReturn = { ...mockAdapter };
adapterWithReturn.createFile = () => {
return Promise.resolve({
name: 'newFilename.txt',
url: 'http://new.url/newFilename.txt'
});
};
adapterWithReturn.getFileLocation = () => {
return Promise.resolve('http://default.url/file.txt');
};
const controllerWithReturn = new FilesController(adapterWithReturn, null, { preserveFileName: true });
// preserveFileName is true to make filename behaviors predictable
const result1 = await controllerWithReturn.createFile(
config,
'originalFile.txt',
'data',
'text/plain'
);
expect(result1.name).toBe('newFilename.txt');
expect(result1.url).toBe('http://new.url/newFilename.txt');
// Test case 2: adapter returns nothing, falling back to default behavior
const adapterWithoutReturn = { ...mockAdapter };
adapterWithoutReturn.createFile = () => {
return Promise.resolve();
};
adapterWithoutReturn.getFileLocation = (config, filename) => {
return Promise.resolve(`http://default.url/${filename}`);
};
const controllerWithoutReturn = new FilesController(adapterWithoutReturn, null, { preserveFileName: true });
const result2 = await controllerWithoutReturn.createFile(
config,
'originalFile.txt',
'data',
'text/plain',
{}
);
expect(result2.name).toBe('originalFile.txt');
expect(result2.url).toBe('http://default.url/originalFile.txt');
// Test case 3: adapter returns partial info (only url)
// This is a valid scenario, as the adapter may return a modified filename
// but may result in a mismatch between the filename and the resource URL
const adapterWithOnlyURL = { ...mockAdapter };
adapterWithOnlyURL.createFile = () => {
return Promise.resolve({
url: 'http://new.url/partialFile.txt'
});
};
adapterWithOnlyURL.getFileLocation = () => {
return Promise.resolve('http://default.url/file.txt');
};
const controllerWithPartial = new FilesController(adapterWithOnlyURL, null, { preserveFileName: true });
const result3 = await controllerWithPartial.createFile(
config,
'originalFile.txt',
'data',
'text/plain',
{}
);
expect(result3.name).toBe('originalFile.txt');
expect(result3.url).toBe('http://new.url/partialFile.txt'); // Technically, the resource does not need to match the filename
// Test case 4: adapter returns only filename
const adapterWithOnlyFilename = { ...mockAdapter };
adapterWithOnlyFilename.createFile = () => {
return Promise.resolve({
name: 'newname.txt'
});
};
adapterWithOnlyFilename.getFileLocation = (config, filename) => {
return Promise.resolve(`http://default.url/${filename}`);
};
const controllerWithOnlyFilename = new FilesController(adapterWithOnlyFilename, null, { preserveFileName: true });
const result4 = await controllerWithOnlyFilename.createFile(
config,
'originalFile.txt',
'data',
'text/plain',
{}
);
expect(result4.name).toBe('newname.txt');
expect(result4.url).toBe('http://default.url/newname.txt');
});
});