foreign.spec.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import 'jest';
  4. import { UUID } from '@lumino/coreutils';
  5. import { KernelMessage } from '@jupyterlab/services';
  6. import { Signal } from '@lumino/signaling';
  7. import { Panel } from '@lumino/widgets';
  8. import { CodeCellModel, CodeCell } from '@jupyterlab/cells';
  9. import { defaultRenderMime, NBTestUtils } from '@jupyterlab/testutils';
  10. import * as Mock from '@jupyterlab/testutils/lib/mock';
  11. import { ISessionContext } from '@jupyterlab/apputils';
  12. import { ForeignHandler } from '../src';
  13. class TestParent extends Panel implements ForeignHandler.IReceiver {
  14. addCell(cell: CodeCell, msgId?: string): void {
  15. this.addWidget(cell);
  16. if (msgId) {
  17. this._cells.set(msgId, cell);
  18. }
  19. }
  20. createCodeCell(): CodeCell {
  21. const contentFactory = NBTestUtils.createCodeCellFactory();
  22. const model = new CodeCellModel({});
  23. const cell = new CodeCell({
  24. model,
  25. rendermime,
  26. contentFactory
  27. }).initializeState();
  28. return cell;
  29. }
  30. getCell(msgId: string) {
  31. return this._cells.get(msgId);
  32. }
  33. private _cells = new Map<string, CodeCell>();
  34. }
  35. class TestHandler extends ForeignHandler {
  36. injected = new Signal<this, KernelMessage.IIOPubMessage>(this);
  37. received = new Signal<this, KernelMessage.IIOPubMessage>(this);
  38. rejected = new Signal<this, KernelMessage.IIOPubMessage>(this);
  39. methods: string[] = [];
  40. protected onIOPubMessage(
  41. sender: ISessionContext,
  42. msg: KernelMessage.IIOPubMessage
  43. ): boolean {
  44. const injected = super.onIOPubMessage(sender, msg);
  45. if (injected) {
  46. this.injected.emit(msg);
  47. } else {
  48. // If the message was not injected but otherwise would have been, emit
  49. // a rejected signal. This should only happen if `enabled` is `false`.
  50. const session = (msg.parent_header as KernelMessage.IHeader).session;
  51. const msgType = msg.header.msg_type;
  52. if (
  53. session !== this.sessionContext.session!.kernel!.clientId &&
  54. relevantTypes.has(msgType)
  55. ) {
  56. this.rejected.emit(msg);
  57. } else {
  58. console.debug(session, this.sessionContext.session?.kernel?.clientId);
  59. }
  60. }
  61. this.received.emit(msg);
  62. return injected;
  63. }
  64. }
  65. const rendermime = defaultRenderMime();
  66. const relevantTypes = [
  67. 'execute_input',
  68. 'execute_result',
  69. 'display_data',
  70. 'stream',
  71. 'error',
  72. 'clear_output'
  73. ].reduce((acc, val) => {
  74. acc.add(val);
  75. return acc;
  76. }, new Set<string>());
  77. describe('@jupyterlab/console', () => {
  78. describe('ForeignHandler', () => {
  79. let foreign: ISessionContext;
  80. let handler: TestHandler;
  81. let sessionContext: ISessionContext;
  82. const streamMsg = KernelMessage.createMessage({
  83. session: 'foo',
  84. channel: 'iopub',
  85. msgType: 'stream',
  86. content: { name: 'stderr', text: 'foo' }
  87. });
  88. const clearMsg = KernelMessage.createMessage({
  89. session: 'foo',
  90. channel: 'iopub',
  91. msgType: 'clear_output',
  92. content: { wait: false }
  93. });
  94. beforeAll(async function() {
  95. const path = UUID.uuid4();
  96. const kernel0 = new Mock.KernelMock({});
  97. const kernel1 = Mock.cloneKernel(kernel0);
  98. const connection0 = new Mock.SessionConnectionMock(
  99. { model: { path, type: 'test' } },
  100. kernel0
  101. );
  102. sessionContext = new Mock.SessionContextMock({}, connection0);
  103. const connection1 = new Mock.SessionConnectionMock(
  104. { model: { path, type: 'test2' } },
  105. kernel1
  106. );
  107. foreign = new Mock.SessionContextMock({}, connection1);
  108. await sessionContext.initialize();
  109. await sessionContext.session!.kernel!.info;
  110. });
  111. beforeEach(() => {
  112. const parent = new TestParent();
  113. handler = new TestHandler({ sessionContext, parent });
  114. });
  115. afterEach(() => {
  116. handler.dispose();
  117. });
  118. afterAll(async () => {
  119. foreign.dispose();
  120. await sessionContext.shutdown();
  121. sessionContext.dispose();
  122. });
  123. describe('#constructor()', () => {
  124. it('should create a new foreign handler', () => {
  125. expect(handler).toBeInstanceOf(ForeignHandler);
  126. });
  127. });
  128. describe('#enabled', () => {
  129. it('should default to `false`', () => {
  130. expect(handler.enabled).toBe(false);
  131. });
  132. it('should allow foreign cells to be injected if `true`', async () => {
  133. handler.enabled = true;
  134. let called = false;
  135. handler.injected.connect(() => {
  136. called = true;
  137. });
  138. await foreign.session!.kernel!.requestExecute({ code: 'foo' }).done;
  139. Mock.emitIopubMessage(foreign, streamMsg);
  140. expect(called).toBe(true);
  141. });
  142. it('should reject foreign cells if `false`', async () => {
  143. handler.enabled = false;
  144. let called = false;
  145. handler.rejected.connect(() => {
  146. called = true;
  147. });
  148. await foreign.session!.kernel!.requestExecute({ code: 'foo' }).done;
  149. Mock.emitIopubMessage(foreign, streamMsg);
  150. expect(called).toBe(true);
  151. });
  152. });
  153. describe('#isDisposed', () => {
  154. it('should indicate whether the handler is disposed', () => {
  155. expect(handler.isDisposed).toBe(false);
  156. handler.dispose();
  157. expect(handler.isDisposed).toBe(true);
  158. });
  159. });
  160. describe('#session', () => {
  161. it('should be a client session object', () => {
  162. expect(handler.sessionContext.session!.path).toBeTruthy();
  163. });
  164. });
  165. describe('#parent', () => {
  166. it('should be set upon instantiation', () => {
  167. const parent = new TestParent();
  168. handler = new TestHandler({
  169. sessionContext: handler.sessionContext,
  170. parent
  171. });
  172. expect(handler.parent).toBe(parent);
  173. });
  174. });
  175. describe('#dispose()', () => {
  176. it('should dispose the resources held by the handler', () => {
  177. expect(handler.isDisposed).toBe(false);
  178. handler.dispose();
  179. expect(handler.isDisposed).toBe(true);
  180. });
  181. it('should be safe to call multiple times', () => {
  182. expect(handler.isDisposed).toBe(false);
  183. handler.dispose();
  184. handler.dispose();
  185. expect(handler.isDisposed).toBe(true);
  186. });
  187. });
  188. describe('#onIOPubMessage()', () => {
  189. it('should be called when messages come through', async () => {
  190. handler.enabled = false;
  191. let called = false;
  192. handler.received.connect(() => {
  193. called = true;
  194. });
  195. await foreign.session!.kernel!.requestExecute({ code: 'foo' }).done;
  196. Mock.emitIopubMessage(foreign, streamMsg);
  197. expect(called).toBe(true);
  198. });
  199. it('should inject relevant cells into the parent', async () => {
  200. handler.enabled = true;
  201. const parent = handler.parent as TestParent;
  202. expect(parent.widgets.length).toBe(0);
  203. let called = false;
  204. handler.injected.connect(() => {
  205. expect(parent.widgets.length).toBeGreaterThan(0);
  206. called = true;
  207. });
  208. await foreign.session!.kernel!.requestExecute({ code: 'foo' }).done;
  209. Mock.emitIopubMessage(foreign, streamMsg);
  210. expect(called).toBe(true);
  211. });
  212. it('should not reject relevant iopub messages', async () => {
  213. let called = false;
  214. let errored = false;
  215. handler.enabled = true;
  216. handler.rejected.connect(() => {
  217. errored = true;
  218. });
  219. handler.received.connect((sender, msg) => {
  220. if (KernelMessage.isClearOutputMsg(msg)) {
  221. called = true;
  222. }
  223. });
  224. await foreign.session!.kernel!.requestExecute({ code: 'foo' }).done;
  225. Mock.emitIopubMessage(foreign, clearMsg);
  226. expect(called).toBe(true);
  227. expect(errored).toBe(false);
  228. });
  229. });
  230. });
  231. });