model.spec.ts 14 KB

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