model.spec.ts 15 KB

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