model.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import 'jest';
  2. import expect from 'expect';
  3. // Copyright (c) Jupyter Development Team.
  4. // Distributed under the terms of the Modified BSD License.
  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 } 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. try {
  309. await promise;
  310. } catch (e) {
  311. expect(e).toBe('File not uploaded');
  312. }
  313. });
  314. it('should emit the fileChanged signal', async () => {
  315. const fname = UUID.uuid4() + '.html';
  316. let called = false;
  317. model.fileChanged.connect((sender, args) => {
  318. expect(sender).toBe(model);
  319. expect(args.type).toBe('save');
  320. expect(args.oldValue).toBeNull();
  321. expect(args.newValue!.path).toBe(fname);
  322. called = true;
  323. });
  324. const file = new File(['<p>Hello world!</p>'], fname, {
  325. type: 'text/html'
  326. });
  327. await model.upload(file);
  328. expect(called).toBe(true);
  329. });
  330. // describe('older notebook version', () => {
  331. // let prevNotebookVersion: string;
  332. // beforeAll(() => {
  333. // prevNotebookVersion = PageConfig.setOption(
  334. // 'notebookVersion',
  335. // JSON.stringify([5, 0, 0])
  336. // );
  337. // });
  338. // it('should not upload large file', async () => {
  339. // const fname = UUID.uuid4() + '.html';
  340. // const file = new File([new ArrayBuffer(LARGE_FILE_SIZE + 1)], fname);
  341. // try {
  342. // await model.upload(file);
  343. // throw new Error('Upload should have failed');
  344. // } catch (err) {
  345. // expect(err).toBe(`Cannot upload file (>15 MB). ${fname}`);
  346. // }
  347. // });
  348. // afterAll(() => {
  349. // PageConfig.setOption('notebookVersion', prevNotebookVersion);
  350. // });
  351. // });
  352. // describe('newer notebook version', () => {
  353. // let prevNotebookVersion: string;
  354. // beforeAll(() => {
  355. // prevNotebookVersion = PageConfig.setOption(
  356. // 'notebookVersion',
  357. // JSON.stringify([5, 1, 0])
  358. // );
  359. // });
  360. // for (const ending of ['.txt', '.ipynb']) {
  361. // for (const size of [
  362. // CHUNK_SIZE - 1,
  363. // CHUNK_SIZE,
  364. // CHUNK_SIZE + 1,
  365. // 2 * CHUNK_SIZE
  366. // ]) {
  367. // it(`should upload a large ${ending} file of size ${size}`, async () => {
  368. // const fname = UUID.uuid4() + ending;
  369. // // minimal valid (according to server) notebook
  370. // let content =
  371. // '{"nbformat": 4, "metadata": {"_": ""}, "nbformat_minor": 2, "cells": []}';
  372. // // make metadata longer so that total document is `size` long
  373. // content = content.replace(
  374. // '"_": ""',
  375. // `"_": "${' '.repeat(size - content.length)}"`
  376. // );
  377. // const file = new File([content], fname, { type: 'text/plain' });
  378. // await model.upload(file);
  379. // const {
  380. // content: newContent
  381. // } = await model.manager.services.contents.get(fname);
  382. // // the contents of notebooks are returned as objects instead of strings
  383. // if (ending === '.ipynb') {
  384. // expect(newContent).toEqual(JSON.parse(content));
  385. // } else {
  386. // expect(newContent).toBe(content);
  387. // }
  388. // });
  389. // }
  390. // }
  391. // it(`should produce progress as a large file uploads`, async () => {
  392. // const fname = UUID.uuid4() + '.txt';
  393. // const file = new File([new ArrayBuffer(2 * CHUNK_SIZE)], fname);
  394. // const [start, first, second, finished] = signalToPromises(
  395. // model.uploadChanged,
  396. // 4
  397. // );
  398. // const uploaded = model.upload(file);
  399. // expect(toArray(model.uploads())).toEqual([]);
  400. // expect(await start).toEqual([
  401. // model,
  402. // {
  403. // name: 'start',
  404. // oldValue: null,
  405. // newValue: { path: fname, progress: 0 }
  406. // }
  407. // ]);
  408. // expect(toArray(model.uploads())).toEqual([
  409. // { path: fname, progress: 0 }
  410. // ]);
  411. // expect(await first).toEqual([
  412. // model,
  413. // {
  414. // name: 'update',
  415. // oldValue: { path: fname, progress: 0 },
  416. // newValue: { path: fname, progress: 0 }
  417. // }
  418. // ]);
  419. // expect(toArray(model.uploads())).toEqual([
  420. // { path: fname, progress: 0 }
  421. // ]);
  422. // expect(await second).toEqual([
  423. // model,
  424. // {
  425. // name: 'update',
  426. // oldValue: { path: fname, progress: 0 },
  427. // newValue: { path: fname, progress: 1 / 2 }
  428. // }
  429. // ]);
  430. // expect(toArray(model.uploads())).toEqual([
  431. // { path: fname, progress: 1 / 2 }
  432. // ]);
  433. // expect(await finished).toEqual([
  434. // model,
  435. // {
  436. // name: 'finish',
  437. // oldValue: { path: fname, progress: 1 / 2 },
  438. // newValue: null
  439. // }
  440. // ]);
  441. // expect(toArray(model.uploads())).toEqual([]);
  442. // await uploaded;
  443. // });
  444. // afterAll(() => {
  445. // PageConfig.setOption('notebookVersion', prevNotebookVersion);
  446. // });
  447. // });
  448. });
  449. });
  450. });