utils.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. // Utils from: https://github.com/jupyterlab/jupyterlab/blob/b1e2b83047421bf7196bec5f2a94d0616dcb2329/packages/services/test/utils.ts
  4. import { ServerConnection } from '@jupyterlab/services';
  5. import { JSONObject } from '@lumino/coreutils';
  6. export const KERNELSPECS: JSONObject = {
  7. default: 'xpython',
  8. kernelspecs: {
  9. python3: {
  10. name: 'Python',
  11. spec: {
  12. language: 'python',
  13. argv: [],
  14. display_name: 'Python 3',
  15. env: {}
  16. },
  17. resources: {}
  18. },
  19. xpython: {
  20. name: 'xpython',
  21. spec: {
  22. language: 'python',
  23. argv: [],
  24. display_name: 'xpython',
  25. env: {},
  26. metadata: { debugger: true }
  27. },
  28. resources: {}
  29. }
  30. }
  31. };
  32. /**
  33. * Create new server connection settings.
  34. *
  35. * @param settings The server connection settings.
  36. */
  37. export function makeSettings(
  38. settings?: Partial<ServerConnection.ISettings>
  39. ): ServerConnection.ISettings {
  40. return ServerConnection.makeSettings(settings);
  41. }
  42. /**
  43. * An interface for a service that has server settings.
  44. */
  45. export interface IService {
  46. readonly serverSettings: ServerConnection.ISettings;
  47. }
  48. /**
  49. * Handle a single request with a mock response.
  50. *
  51. * @param item The service.
  52. * @param status The status code for the response.
  53. * @param body The body for the response.
  54. */
  55. export function handleRequest(item: IService, status: number, body: any): void {
  56. // Store the existing fetch function.
  57. const oldFetch = item.serverSettings.fetch;
  58. // A single use callback.
  59. const temp = (info: RequestInfo, init: RequestInit): Promise<void> => {
  60. // Restore fetch.
  61. (item.serverSettings as any).fetch = oldFetch;
  62. // Normalize the body.
  63. if (typeof body !== 'string') {
  64. body = JSON.stringify(body);
  65. }
  66. // Create the response and return it as a promise.
  67. const response = new Response(body, { status });
  68. return Promise.resolve(response as any);
  69. };
  70. // Override the fetch function.
  71. (item.serverSettings as any).fetch = temp;
  72. }