model.spec.ts 15 KB

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