model.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import 'jest';
  4. import expect from 'expect';
  5. import { PageConfig } from '@jupyterlab/coreutils';
  6. import { UUID } from '@lumino/coreutils';
  7. import { DocumentManager, IDocumentManager } from '@jupyterlab/docmanager';
  8. import { DocumentRegistry, TextModelFactory } from '@jupyterlab/docregistry';
  9. import { StateDB } from '@jupyterlab/statedb';
  10. import { FileBrowserModel, CHUNK_SIZE, LARGE_FILE_SIZE } from '../src';
  11. import { Contents, ServiceManager } from '@jupyterlab/services';
  12. import {
  13. acceptDialog,
  14. dismissDialog,
  15. signalToPromises,
  16. sleep
  17. } from '@jupyterlab/testutils';
  18. import * as Mock from '@jupyterlab/testutils/lib/mock';
  19. import { toArray } from '@lumino/algorithm';
  20. /**
  21. * A contents manager that delays requests by less each time it is called
  22. * in order to simulate out-of-order responses from the server.
  23. */
  24. class DelayedContentsManager extends Mock.ContentsManagerMock {
  25. get(
  26. path: string,
  27. options?: Contents.IFetchOptions
  28. ): Promise<Contents.IModel> {
  29. return new Promise<Contents.IModel>(resolve => {
  30. const delay = this._delay;
  31. this._delay -= 500;
  32. void super.get(path, options).then(contents => {
  33. setTimeout(() => {
  34. resolve(contents);
  35. }, Math.max(delay, 0));
  36. });
  37. });
  38. }
  39. private _delay = 1000;
  40. }
  41. describe('filebrowser/model', () => {
  42. let manager: IDocumentManager;
  43. let serviceManager: ServiceManager.IManager;
  44. let registry: DocumentRegistry;
  45. let model: FileBrowserModel;
  46. let name: string;
  47. let subDir: string;
  48. let state: StateDB;
  49. const opener: DocumentManager.IWidgetOpener = {
  50. open: widget => {
  51. /* no op */
  52. }
  53. };
  54. beforeAll(() => {
  55. registry = new DocumentRegistry({
  56. textModelFactory: new TextModelFactory()
  57. });
  58. serviceManager = new Mock.ServiceManagerMock();
  59. manager = new DocumentManager({
  60. registry,
  61. opener,
  62. manager: serviceManager
  63. });
  64. state = new StateDB();
  65. });
  66. beforeEach(async () => {
  67. await state.clear();
  68. model = new FileBrowserModel({ manager, state });
  69. let contents = await manager.newUntitled({ type: 'file' });
  70. name = contents.name;
  71. contents = await manager.newUntitled({ type: 'directory' });
  72. subDir = contents.path;
  73. return model.cd();
  74. });
  75. afterEach(() => {
  76. model.dispose();
  77. });
  78. describe('FileBrowserModel', () => {
  79. describe('#constructor()', () => {
  80. it('should construct a new file browser model', () => {
  81. model = new FileBrowserModel({ manager });
  82. expect(model).toBeInstanceOf(FileBrowserModel);
  83. });
  84. });
  85. describe('#pathChanged', () => {
  86. it('should be emitted when the path changes', async () => {
  87. let called = false;
  88. model.pathChanged.connect((sender, args) => {
  89. expect(sender).toBe(model);
  90. expect(args.name).toBe('path');
  91. expect(args.oldValue).toBe('');
  92. expect(args.newValue).toBe(subDir);
  93. called = true;
  94. });
  95. await model.cd(subDir);
  96. expect(called).toBe(true);
  97. });
  98. });
  99. describe('#refreshed', () => {
  100. it('should be emitted after a refresh', async () => {
  101. let called = false;
  102. model.refreshed.connect((sender, arg) => {
  103. expect(sender).toBe(model);
  104. expect(arg).toBeUndefined();
  105. called = true;
  106. });
  107. await model.cd();
  108. expect(called).toBe(true);
  109. });
  110. it('should be emitted when the path changes', async () => {
  111. let called = false;
  112. model.refreshed.connect((sender, arg) => {
  113. expect(sender).toBe(model);
  114. expect(arg).toBeUndefined();
  115. called = true;
  116. });
  117. await model.cd(subDir);
  118. expect(called).toBe(true);
  119. });
  120. });
  121. describe('#fileChanged', () => {
  122. it('should be emitted when a file is created', async () => {
  123. let called = false;
  124. model.fileChanged.connect((sender, args) => {
  125. expect(sender).toBe(model);
  126. expect(args.type).toBe('new');
  127. expect(args.oldValue).toBeNull();
  128. expect(args.newValue!.type).toBe('file');
  129. called = true;
  130. });
  131. await manager.newUntitled({ type: 'file' });
  132. expect(called).toBe(true);
  133. });
  134. it('should be emitted when a file is renamed', async () => {
  135. let called = false;
  136. model.fileChanged.connect((sender, args) => {
  137. expect(sender).toBe(model);
  138. expect(args.type).toBe('rename');
  139. expect(args.oldValue!.path).toBe(name);
  140. expect(args.newValue!.path).toBe(name + '.bak');
  141. called = true;
  142. });
  143. await manager.rename(name, name + '.bak');
  144. expect(called).toBe(true);
  145. });
  146. it('should be emitted when a file is deleted', async () => {
  147. let called = false;
  148. model.fileChanged.connect((sender, args) => {
  149. expect(sender).toBe(model);
  150. expect(args.type).toBe('delete');
  151. expect(args.oldValue!.path).toBe(name);
  152. expect(args.newValue).toBeNull();
  153. called = true;
  154. });
  155. await manager.deleteFile(name);
  156. expect(called).toBe(true);
  157. });
  158. });
  159. describe('#path', () => {
  160. it('should be the current path of the model', async () => {
  161. expect(model.path).toBe('');
  162. await model.cd(subDir);
  163. expect(model.path).toBe(subDir);
  164. });
  165. });
  166. describe('#items()', () => {
  167. it('should get an iterator of items in the current path', () => {
  168. const items = model.items();
  169. expect(items.next()).toBeTruthy();
  170. });
  171. });
  172. describe('#isDisposed', () => {
  173. it('should test whether the model is disposed', () => {
  174. expect(model.isDisposed).toBe(false);
  175. model.dispose();
  176. expect(model.isDisposed).toBe(true);
  177. });
  178. });
  179. describe('#sessions()', () => {
  180. it('should be the session models for the active notebooks', async () => {
  181. const contents = await manager.newUntitled({ type: 'notebook' });
  182. const session = await serviceManager.sessions.startNew({
  183. name: '',
  184. path: contents.path,
  185. type: 'test'
  186. });
  187. await model.cd();
  188. expect(model.sessions().next()).toBeTruthy();
  189. await session.shutdown();
  190. });
  191. });
  192. describe('#dispose()', () => {
  193. it('should dispose of the resources held by the model', () => {
  194. model.dispose();
  195. expect(model.isDisposed).toBe(true);
  196. });
  197. it('should be safe to call more than once', () => {
  198. model.dispose();
  199. model.dispose();
  200. expect(model.isDisposed).toBe(true);
  201. });
  202. });
  203. describe('#refresh()', () => {
  204. it('should refresh the contents', () => {
  205. return model.refresh();
  206. });
  207. });
  208. describe('#cd()', () => {
  209. it('should change directory', async () => {
  210. await model.cd(subDir);
  211. expect(model.path).toBe(subDir);
  212. });
  213. it('should accept a relative path', async () => {
  214. await model.cd(subDir);
  215. expect(model.path).toBe(subDir);
  216. });
  217. it('should accept a parent directory', async () => {
  218. await model.cd(subDir);
  219. await model.cd('..');
  220. expect(model.path).toBe('');
  221. });
  222. it('should be resilient to a slow initial fetch', async () => {
  223. const delayedServiceManager = new Mock.ServiceManagerMock();
  224. (delayedServiceManager as any).contents = new DelayedContentsManager();
  225. const contents = await delayedServiceManager.contents.newUntitled({
  226. type: 'directory'
  227. });
  228. subDir = contents.path;
  229. const manager = new DocumentManager({
  230. registry,
  231. opener,
  232. manager: delayedServiceManager
  233. });
  234. model = new FileBrowserModel({ manager, state }); // Should delay 1000ms
  235. // An initial refresh is called in the constructor.
  236. // If it is too slow, it can come in after the directory change,
  237. // causing a directory set by, e.g., the tree handler to be wrong.
  238. // This checks to make sure we are handling that case correctly.
  239. await model.cd(subDir); // should delay 500ms
  240. await sleep(2000);
  241. expect(model.path).toBe(subDir);
  242. manager.dispose();
  243. delayedServiceManager.contents.dispose();
  244. delayedServiceManager.dispose();
  245. model.dispose();
  246. });
  247. });
  248. describe('#restore()', () => {
  249. it('should restore based on ID', async () => {
  250. const id = 'foo';
  251. const model2 = new FileBrowserModel({ manager, state });
  252. await model.restore(id);
  253. await model.cd(subDir);
  254. expect(model.path).toBe(subDir);
  255. expect(model2.path).toBe('');
  256. await model2.restore(id);
  257. expect(model2.path).toBe(subDir);
  258. model2.dispose();
  259. });
  260. it('should be safe to call multiple times', async () => {
  261. const id = 'bar';
  262. const model2 = new FileBrowserModel({ manager, state });
  263. await model.restore(id);
  264. await model.cd(subDir);
  265. expect(model.path).toBe(subDir);
  266. expect(model2.path).toBe('');
  267. await model2.restore(id);
  268. await model2.restore(id);
  269. expect(model2.path).toBe(subDir);
  270. model2.dispose();
  271. });
  272. });
  273. describe('#download()', () => {
  274. it('should download the file without error', () => {
  275. // TODO: how to test this?
  276. });
  277. });
  278. describe('#upload()', () => {
  279. it('should upload a file object', async () => {
  280. const fname = UUID.uuid4() + '.html';
  281. const file = new File(['<p>Hello world!</p>'], fname, {
  282. type: 'text/html'
  283. });
  284. const contents = await model.upload(file);
  285. expect(contents.name).toBe(fname);
  286. });
  287. it('should overwrite', async () => {
  288. const fname = UUID.uuid4() + '.html';
  289. const file = new File(['<p>Hello world!</p>'], fname, {
  290. type: 'text/html'
  291. });
  292. const contents = await model.upload(file);
  293. expect(contents.name).toBe(fname);
  294. const promise = model.upload(file);
  295. await acceptDialog();
  296. await promise;
  297. expect(contents.name).toBe(fname);
  298. });
  299. it('should not overwrite', async () => {
  300. const fname = UUID.uuid4() + '.html';
  301. const file = new File(['<p>Hello world!</p>'], fname, {
  302. type: 'text/html'
  303. });
  304. const contents = await model.upload(file);
  305. expect(contents.name).toBe(fname);
  306. const promise = model.upload(file);
  307. await dismissDialog();
  308. await expect(promise).rejects.toThrow('File not uploaded');
  309. });
  310. it('should emit the fileChanged signal', async () => {
  311. const fname = UUID.uuid4() + '.html';
  312. let called = false;
  313. model.fileChanged.connect((sender, args) => {
  314. expect(sender).toBe(model);
  315. expect(args.type).toBe('save');
  316. expect(args.oldValue).toBeNull();
  317. expect(args.newValue!.path).toBe(fname);
  318. called = true;
  319. });
  320. const file = new File(['<p>Hello world!</p>'], fname, {
  321. type: 'text/html'
  322. });
  323. await model.upload(file);
  324. expect(called).toBe(true);
  325. });
  326. describe('older notebook version', () => {
  327. let prevNotebookVersion: string;
  328. beforeAll(() => {
  329. prevNotebookVersion = PageConfig.setOption(
  330. 'notebookVersion',
  331. JSON.stringify([5, 0, 0])
  332. );
  333. });
  334. it('should not upload large file', async () => {
  335. const fname = UUID.uuid4() + '.html';
  336. const file = new File([new ArrayBuffer(LARGE_FILE_SIZE + 1)], fname);
  337. await expect(model.upload(file)).rejects.toThrow(
  338. `Cannot upload file (>15 MB). ${fname}`
  339. );
  340. });
  341. afterAll(() => {
  342. PageConfig.setOption('notebookVersion', prevNotebookVersion);
  343. });
  344. });
  345. describe('newer notebook version', () => {
  346. let prevNotebookVersion: string;
  347. beforeAll(() => {
  348. prevNotebookVersion = PageConfig.setOption(
  349. 'notebookVersion',
  350. JSON.stringify([5, 1, 0])
  351. );
  352. });
  353. for (const ending of ['.txt', '.ipynb']) {
  354. for (const size of [
  355. CHUNK_SIZE - 1,
  356. CHUNK_SIZE,
  357. CHUNK_SIZE + 1,
  358. 2 * CHUNK_SIZE
  359. ]) {
  360. it(`should upload a large ${ending} file of size ${size}`, async () => {
  361. const fname = UUID.uuid4() + ending;
  362. // minimal valid (according to server) notebook
  363. let content =
  364. '{"nbformat": 4, "metadata": {"_": ""}, "nbformat_minor": 2, "cells": []}';
  365. // make metadata longer so that total document is `size` long
  366. content = content.replace(
  367. '"_": ""',
  368. `"_": "${' '.repeat(size - content.length)}"`
  369. );
  370. const file = new File([content], fname, { type: 'text/plain' });
  371. await model.upload(file);
  372. // Ensure we get the file back.
  373. const contentModel = await model.manager.services.contents.get(
  374. fname
  375. );
  376. expect(contentModel.content.length).toBeGreaterThan(0);
  377. });
  378. }
  379. }
  380. it(`should produce progress as a large file uploads`, async () => {
  381. const fname = UUID.uuid4() + '.txt';
  382. const file = new File([new ArrayBuffer(2 * CHUNK_SIZE)], fname);
  383. const [start, first, second, finished] = signalToPromises(
  384. model.uploadChanged,
  385. 4
  386. );
  387. const uploaded = model.upload(file);
  388. expect(toArray(model.uploads())).toEqual([]);
  389. expect(await start).toEqual([
  390. model,
  391. {
  392. name: 'start',
  393. oldValue: null,
  394. newValue: { path: fname, progress: 0 }
  395. }
  396. ]);
  397. expect(toArray(model.uploads())).toEqual([
  398. { path: fname, progress: 0 }
  399. ]);
  400. expect(await first).toEqual([
  401. model,
  402. {
  403. name: 'update',
  404. oldValue: { path: fname, progress: 0 },
  405. newValue: { path: fname, progress: 0 }
  406. }
  407. ]);
  408. expect(toArray(model.uploads())).toEqual([
  409. { path: fname, progress: 0 }
  410. ]);
  411. expect(await second).toEqual([
  412. model,
  413. {
  414. name: 'update',
  415. oldValue: { path: fname, progress: 0 },
  416. newValue: { path: fname, progress: 1 / 2 }
  417. }
  418. ]);
  419. expect(toArray(model.uploads())).toEqual([
  420. { path: fname, progress: 1 / 2 }
  421. ]);
  422. expect(await finished).toEqual([
  423. model,
  424. {
  425. name: 'finish',
  426. oldValue: { path: fname, progress: 1 / 2 },
  427. newValue: null
  428. }
  429. ]);
  430. expect(toArray(model.uploads())).toEqual([]);
  431. await uploaded;
  432. });
  433. afterAll(() => {
  434. PageConfig.setOption('notebookVersion', prevNotebookVersion);
  435. });
  436. });
  437. });
  438. });
  439. });