utils.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. // eslint-disable-next-line @typescript-eslint/camelcase
  15. display_name: 'Python 3',
  16. env: {}
  17. },
  18. resources: {}
  19. },
  20. xpython: {
  21. name: 'xpython',
  22. spec: {
  23. language: 'python',
  24. argv: [],
  25. // eslint-disable-next-line @typescript-eslint/camelcase
  26. display_name: 'xpython',
  27. env: {},
  28. metadata: { debugger: true }
  29. },
  30. resources: {}
  31. }
  32. }
  33. };
  34. /**
  35. * Create new server connection settings.
  36. *
  37. * @param settings The server connection settings.
  38. */
  39. export function makeSettings(
  40. settings?: Partial<ServerConnection.ISettings>
  41. ): ServerConnection.ISettings {
  42. return ServerConnection.makeSettings(settings);
  43. }
  44. /**
  45. * An interface for a service that has server settings.
  46. */
  47. export interface IService {
  48. readonly serverSettings: ServerConnection.ISettings;
  49. }
  50. /**
  51. * Handle a single request with a mock response.
  52. *
  53. * @param item The service.
  54. * @param status The status code for the response.
  55. * @param body The body for the response.
  56. */
  57. export function handleRequest(item: IService, status: number, body: any): void {
  58. // Store the existing fetch function.
  59. const oldFetch = item.serverSettings.fetch;
  60. // A single use callback.
  61. const temp = (info: RequestInfo, init: RequestInit): Promise<void> => {
  62. // Restore fetch.
  63. (item.serverSettings as any).fetch = oldFetch;
  64. // Normalize the body.
  65. if (typeof body !== 'string') {
  66. body = JSON.stringify(body);
  67. }
  68. // Create the response and return it as a promise.
  69. const response = new Response(body, { status });
  70. return Promise.resolve(response as any);
  71. };
  72. // Override the fetch function.
  73. (item.serverSettings as any).fetch = temp;
  74. }