utils.ts 2.4 KB

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