diff --git a/README.md b/README.md index 834bb10c72..36f1adff02 100644 --- a/README.md +++ b/README.md @@ -177,7 +177,8 @@ Run `npm run lint` or install an editor plugin. # Testing -Tests are written using the [Chai](http://chaijs.com/) library. See +Tests are written using the [Mocha](https://mochajs.org/) test runner and +[`node:assert`](https://nodejs.org/api/assert.html) assertion library. See [`config_test.ts`](./src/config_test.ts) for an example. To run tests, execute the following: diff --git a/eslint.config.js b/eslint.config.js index 4f2be15e7b..3d83c71ee6 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -21,7 +21,6 @@ export default tseslint.config( '@typescript-eslint/no-empty-object-type': 'off', '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-non-null-assertion': 'off', - '@typescript-eslint/no-unused-expressions': 'off', '@typescript-eslint/no-unused-vars': ['error', { args: 'none' }], }, }, diff --git a/src/attach_test.ts b/src/attach_test.ts index 3fadbc563f..883514eac3 100644 --- a/src/attach_test.ts +++ b/src/attach_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { strictEqual } from 'node:assert'; import WebSocket from 'isomorphic-ws'; import { ReadableStreamBuffer, WritableStreamBuffer } from 'stream-buffers'; import { anyFunction, anything, capture, instance, mock, verify, when } from 'ts-mockito'; @@ -73,7 +73,7 @@ describe('Attach', () => { await attach.attach(namespace, pod, container, osStream, errStream, isStream, false); const [, , outputFn] = capture(fakeWebSocketInterface.connect).last(); - expect(outputFn).to.not.be.null; + strictEqual(typeof outputFn, 'function'); // this is redundant but needed for the compiler, sigh... if (!outputFn) { @@ -83,18 +83,18 @@ describe('Attach', () => { let buffer = Buffer.alloc(1024, 10); outputFn(WebSocketHandler.StdoutStream, buffer); - expect(osStream.size()).to.equal(1024); + strictEqual(osStream.size(), 1024); let buff = osStream.getContents() as Buffer; for (let i = 0; i < 1024; i++) { - expect(buff[i]).to.equal(10); + strictEqual(buff[i], 10); } buffer = Buffer.alloc(1024, 20); outputFn(WebSocketHandler.StderrStream, buffer); - expect(errStream.size()).to.equal(1024); + strictEqual(errStream.size(), 1024); buff = errStream.getContents() as Buffer; for (let i = 0; i < 1024; i++) { - expect(buff[i]).to.equal(20); + strictEqual(buff[i], 20); } const initialTerminalSize: TerminalSize = { height: 0, width: 0 }; diff --git a/src/azure_auth_test.ts b/src/azure_auth_test.ts index 9067131b34..44b7a0355f 100644 --- a/src/azure_auth_test.ts +++ b/src/azure_auth_test.ts @@ -1,5 +1,4 @@ -import { use, expect } from 'chai'; -import chaiAsPromised from 'chai-as-promised'; +import { rejects, strictEqual } from 'node:assert'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -10,8 +9,6 @@ import { HttpMethod, RequestContext } from './index.js'; const __dirname = dirname(fileURLToPath(import.meta.url)); -use(chaiAsPromised); - describe('AzureAuth', () => { const testUrl1 = 'https://test1.com'; let auth: AzureAuth; @@ -26,7 +23,7 @@ describe('AzureAuth', () => { }, } as User; - expect(auth.isAuthProvider(user)).to.equal(true); + strictEqual(auth.isAuthProvider(user), true); }); it('should be false for other user', () => { @@ -36,13 +33,13 @@ describe('AzureAuth', () => { }, } as User; - expect(auth.isAuthProvider(user)).to.equal(false); + strictEqual(auth.isAuthProvider(user), false); }); it('should be false for null user.authProvider', () => { const user = {} as User; - expect(auth.isAuthProvider(user)).to.equal(false); + strictEqual(auth.isAuthProvider(user), false); }); it('should populate from auth provider', async () => { @@ -63,12 +60,11 @@ describe('AzureAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); requestContext.setHeaderParam('Host', 'foo.com'); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders().Authorization).to.equal(`Bearer ${token}`); + strictEqual(requestContext.getHeaders().Authorization, `Bearer ${token}`); }); it('should populate from auth provider without expiry', async () => { @@ -88,8 +84,7 @@ describe('AzureAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); it('should populate rejectUnauthorized=false when skipTLSVerify is set', async () => { @@ -110,7 +105,7 @@ describe('AzureAuth', () => { await config.applySecurityAuthentication(requestContext); // @ts-expect-error - expect(requestContext.getAgent().options.rejectUnauthorized).to.equal(false); + strictEqual(requestContext.getAgent().options.rejectUnauthorized, false); }); it('should not set rejectUnauthorized if skipTLSVerify is not set', async () => { @@ -133,10 +128,10 @@ describe('AzureAuth', () => { await config.applySecurityAuthentication(requestContext); // @ts-expect-error - expect(requestContext.getAgent().options.rejectUnauthorized).to.equal(undefined); + strictEqual(requestContext.getAgent().options.rejectUnauthorized, undefined); }); - it('should throw with expired token and no cmd', () => { + it('should throw with expired token and no cmd', async () => { const config = new KubeConfig(); config.loadFromClusterAndUser( { skipTLSVerify: false } as Cluster, @@ -151,12 +146,12 @@ describe('AzureAuth', () => { ); const requestContext = new RequestContext(testUrl1, HttpMethod.GET); - return expect(config.applySecurityAuthentication(requestContext)).to.eventually.be.rejectedWith( - 'Token is expired!', - ); + await rejects(config.applySecurityAuthentication(requestContext), { + message: 'Token is expired!', + }); }); - it('should throw with bad command', () => { + it('should throw with bad command', async () => { const config = new KubeConfig(); config.loadFromClusterAndUser( { skipTLSVerify: false } as Cluster, @@ -173,9 +168,9 @@ describe('AzureAuth', () => { ); const requestContext = new RequestContext(testUrl1, HttpMethod.GET); - return expect(config.applySecurityAuthentication(requestContext)).to.eventually.be.rejectedWith( - /Failed to refresh token/, - ); + await rejects(config.applySecurityAuthentication(requestContext), { + message: /Failed to refresh token/, + }); }); it('should exec when no cmd and token is not expired', async () => { @@ -224,8 +219,7 @@ describe('AzureAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); it('should exec without access-token', async () => { // TODO: fix this test for Windows @@ -252,8 +246,7 @@ describe('AzureAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); it('should exec without access-token', async () => { // TODO: fix this test for Windows @@ -280,8 +273,7 @@ describe('AzureAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); it('should exec succesfully with spaces in cmd', async () => { // TODO: fix this test for Windows @@ -308,7 +300,6 @@ describe('AzureAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); }); diff --git a/src/cache_test.ts b/src/cache_test.ts index ac94ce097d..bfcd7114f3 100644 --- a/src/cache_test.ts +++ b/src/cache_test.ts @@ -1,6 +1,4 @@ -import { expect, use } from 'chai'; -import chaiAsPromised from 'chai-as-promised'; - +import { deepStrictEqual, notStrictEqual, strictEqual, throws } from 'node:assert'; import mock from 'ts-mockito'; import { V1Namespace, V1NamespaceList, V1ObjectMeta, V1Pod, V1PodList, V1ListMeta } from './api.js'; @@ -9,8 +7,6 @@ import { KubeConfig } from './config.js'; import { Cluster, Context, User } from './config_types.js'; import { ListPromise } from './informer.js'; -use(chaiAsPromised); - import nock from 'nock'; import { Watch } from './watch.js'; @@ -57,7 +53,9 @@ describe('ListWatchCache', () => { const verb = 'FOOBAR'; // The 'as any' is a hack to get around Typescript which prevents an unknown verb from being // passed. We want to test for Javascript clients also, where this is possible - expect(() => (lw as any).on(verb, (obj?: V1Namespace) => {})).to.throw(`Unknown verb: ${verb}`); + throws(() => (lw as any).on(verb, (obj?: V1Namespace) => {}), { + message: `Unknown verb: ${verb}`, + }); }); it('should perform basic caching', async () => { @@ -117,11 +115,10 @@ describe('ListWatchCache', () => { const cache = new ListWatch('/some/path', mock.instance(fakeWatch), listFn); await promise; const [pathOut, , watchHandler, doneHandler] = mock.capture(fakeWatch.watch).last(); - expect(pathOut).to.equal('/some/path'); - expect(cache.list()).to.deep.equal(list); - - expect(cache.list('default')).to.deep.equal(list); - expect(cache.list('non-existent')).to.deep.equal([]); + strictEqual(pathOut, '/some/path'); + deepStrictEqual(cache.list(), list); + deepStrictEqual(cache.list('default'), list); + deepStrictEqual(cache.list('non-existent'), []); watchHandler('ADDED', { metadata: { @@ -130,12 +127,11 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Pod); - expect(cache.list().length).to.equal(3); - expect(cache.get('name3')).to.not.equal(null); - - expect(cache.list('default').length).to.equal(2); - expect(cache.list('other').length).to.equal(1); - expect(cache.list('non-existent')).to.deep.equal([]); + strictEqual(cache.list().length, 3); + notStrictEqual(cache.get('name3'), null); + strictEqual(cache.list('default').length, 2); + strictEqual(cache.list('other').length, 1); + deepStrictEqual(cache.list('non-existent'), []); watchHandler('MODIFIED', { metadata: { @@ -144,12 +140,12 @@ describe('ListWatchCache', () => { resourceVersion: 'baz', } as V1ObjectMeta, } as V1Pod); - expect(cache.list().length).to.equal(3); + strictEqual(cache.list().length, 3); const obj3 = cache.get('name3'); - expect(obj3).to.not.equal(null); + notStrictEqual(obj3, null); if (obj3) { - expect(obj3.metadata!.name).to.equal('name3'); - expect(obj3.metadata!.resourceVersion).to.equal('baz'); + strictEqual(obj3.metadata!.name, 'name3'); + strictEqual(obj3.metadata!.resourceVersion, 'baz'); } watchHandler('DELETED', { @@ -158,11 +154,11 @@ describe('ListWatchCache', () => { namespace: 'default', } as V1ObjectMeta, } as V1Pod); - expect(cache.list().length).to.equal(2); - expect(cache.get('name2')).to.equal(undefined); + strictEqual(cache.list().length, 2); + strictEqual(cache.get('name2'), undefined); - expect(cache.list('default').length).to.equal(1); - expect(cache.list('other').length).to.equal(1); + strictEqual(cache.list('default').length, 1); + strictEqual(cache.list('other').length, 1); watchHandler('ADDED', { metadata: { @@ -174,9 +170,9 @@ describe('ListWatchCache', () => { const error = new Error('Gone') as Error & { statusCode: number | undefined }; error.statusCode = 410; await doneHandler(error); - expect(cache.list().length, 'all pod list').to.equal(1); - expect(cache.list('default').length, 'default pod list').to.equal(1); - expect(cache.list('other'), 'other pod list').to.deep.equal([]); + strictEqual(cache.list().length, 1); + strictEqual(cache.list('default').length, 1); + deepStrictEqual(cache.list('other'), []); }); it('should perform work as an informer', async () => { @@ -215,7 +211,7 @@ describe('ListWatchCache', () => { const informer = new ListWatch('/some/path', mock.instance(fakeWatch), listFn); await promise; const [pathOut, , watchHandler] = mock.capture(fakeWatch.watch).last(); - expect(pathOut).to.equal('/some/path'); + strictEqual(pathOut, '/some/path'); const addPromise = new Promise((resolve: (V1Namespace) => void) => { informer.on('add', (obj?: V1Namespace) => { @@ -254,13 +250,14 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Namespace); - return Promise.all([ - expect(addPromise).to.eventually.have.property('metadata').that.deep.equals({ name: 'name3' }), - expect(updatePromise) - .to.eventually.have.property('metadata') - .that.deep.equals({ name: 'name3', resourceVersion: 'baz' }), - expect(deletePromise).to.eventually.have.property('metadata').that.deep.equals({ name: 'name2' }), + const [addResult, updateResult, deleteResult] = await Promise.all([ + addPromise, + updatePromise, + deletePromise, ]); + deepStrictEqual(addResult.metadata, { name: 'name3' }); + deepStrictEqual(updateResult.metadata, { name: 'name3', resourceVersion: 'baz' }); + deepStrictEqual(deleteResult.metadata, { name: 'name2' }); }); it('should handle change events correctly', async () => { @@ -299,7 +296,7 @@ describe('ListWatchCache', () => { const informer = new ListWatch('/some/path', mock.instance(fakeWatch), listFn); await promise; const [pathOut, , watchHandler] = mock.capture(fakeWatch.watch).last(); - expect(pathOut).to.equal('/some/path'); + strictEqual(pathOut, '/some/path'); let count = 0; const changePromise = new Promise((resolve: (V1Namespace) => void) => { @@ -330,7 +327,7 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Namespace); - expect(changePromise).to.eventually.be.true; + strictEqual(await changePromise, true); }); it('should perform work as an informer with multiple handlers', async () => { @@ -357,7 +354,7 @@ describe('ListWatchCache', () => { const informer = new ListWatch('/some/path', mock.instance(fakeWatch), listFn); await promise; const [pathOut, , watchHandler] = mock.capture(fakeWatch.watch).last(); - expect(pathOut).to.equal('/some/path'); + strictEqual(pathOut, '/some/path'); const addPromise = new Promise((resolve: (V1Namespace) => void) => { informer.on('add', (obj?: V1Namespace) => { @@ -377,10 +374,9 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Namespace); - return Promise.all([ - expect(addPromise).to.eventually.have.property('metadata').that.deep.equals({ name: 'name3' }), - expect(addPromise2).to.eventually.have.property('metadata').that.deep.equals({ name: 'name3' }), - ]); + const [result1, result2] = await Promise.all([addPromise, addPromise2]); + deepStrictEqual(result1.metadata, { name: 'name3' }); + deepStrictEqual(result2.metadata, { name: 'name3' }); }); it('should perform work as an informer with initial list', async () => { @@ -429,9 +425,9 @@ describe('ListWatchCache', () => { await promise; const [pathOut, , , doneHandler] = mock.capture(fakeWatch.watch).last(); - expect(pathOut).to.equal('/some/path'); - expect(addObjects).to.deep.equal(list); - expect(updateObjects).to.deep.equal([]); + strictEqual(pathOut, '/some/path'); + deepStrictEqual(addObjects, list); + deepStrictEqual(updateObjects, []); promise = new Promise((resolve) => { mock.when( @@ -442,8 +438,8 @@ describe('ListWatchCache', () => { }); doneHandler(null); await promise; - expect(addObjects).to.deep.equal(list); - expect(updateObjects).to.deep.equal([]); + deepStrictEqual(addObjects, list); + deepStrictEqual(updateObjects, []); }); it('should perform work as an informer with initial list and delete after', async () => { @@ -501,9 +497,9 @@ describe('ListWatchCache', () => { await promise; const [pathOut, , , doneHandler] = mock.capture(fakeWatch.watch).last(); - expect(pathOut).to.equal('/some/path'); - expect(addObjects).to.deep.equal(list); - expect(updateObjects).to.deep.equal([]); + strictEqual(pathOut, '/some/path'); + deepStrictEqual(addObjects, list); + deepStrictEqual(updateObjects, []); promise = new Promise((resolve) => { mock.when( @@ -517,9 +513,9 @@ describe('ListWatchCache', () => { error.statusCode = 410; await doneHandler(error); await promise; - expect(addObjects).to.deep.equal(list); - expect(updateObjects).to.deep.equal(list2); - expect(deleteObjects).to.deep.equal([ + deepStrictEqual(addObjects, list); + deepStrictEqual(updateObjects, list2); + deepStrictEqual(deleteObjects, [ { metadata: { name: 'name2', @@ -567,14 +563,14 @@ describe('ListWatchCache', () => { const cache = new ListWatch('/some/path', mock.instance(fakeWatch), listFn); await promise; const [pathOut, , watchHandler] = mock.capture(fakeWatch.watch).last(); - expect(pathOut).to.equal('/some/path'); - expect(cache.list()).to.deep.equal(list); + strictEqual(pathOut, '/some/path'); + deepStrictEqual(cache.list(), list); - expect(cache.list('ns1').length).to.equal(1); - expect(cache.list('ns1')[0].metadata!.name).to.equal('name1'); + strictEqual(cache.list('ns1').length, 1); + strictEqual(cache.list('ns1')[0].metadata!.name, 'name1'); - expect(cache.list('ns2').length).to.equal(1); - expect(cache.list('ns2')[0].metadata!.name).to.equal('name2'); + strictEqual(cache.list('ns2').length, 1); + strictEqual(cache.list('ns2')[0].metadata!.name, 'name2'); watchHandler('ADDED', { metadata: { @@ -583,8 +579,8 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Pod); - expect(cache.list().length).to.equal(3); - expect(cache.get('name3', 'ns3')).to.not.equal(null); + strictEqual(cache.list().length, 3); + notStrictEqual(cache.get('name3', 'ns3'), null); watchHandler('MODIFIED', { metadata: { @@ -593,12 +589,12 @@ describe('ListWatchCache', () => { resourceVersion: 'baz', } as V1ObjectMeta, } as V1Pod); - expect(cache.list().length).to.equal(3); + strictEqual(cache.list().length, 3); const obj3 = cache.get('name3', 'ns3'); - expect(obj3).to.not.equal(null); + notStrictEqual(obj3, null); if (obj3) { - expect(obj3.metadata!.name).to.equal('name3'); - expect(obj3.metadata!.resourceVersion).to.equal('baz'); + strictEqual(obj3.metadata!.name, 'name3'); + strictEqual(obj3.metadata!.resourceVersion, 'baz'); } watchHandler('DELETED', { @@ -607,8 +603,8 @@ describe('ListWatchCache', () => { namespace: 'other-ns', } as V1ObjectMeta, } as V1Pod); - expect(cache.list().length).to.equal(3); - expect(cache.get('name2')).to.not.equal(null); + strictEqual(cache.list().length, 3); + notStrictEqual(cache.get('name2'), null); watchHandler('DELETED', { metadata: { @@ -616,9 +612,9 @@ describe('ListWatchCache', () => { namespace: 'ns2', } as V1ObjectMeta, } as V1Pod); - expect(cache.list().length).to.equal(2); - expect(cache.list('ns2').length).to.equal(0); - expect(cache.get('name2', 'ns2')).to.equal(undefined); + strictEqual(cache.list().length, 2); + strictEqual(cache.list('ns2').length, 0); + strictEqual(cache.get('name2', 'ns2'), undefined); }); it('should perform non-namespace caching', async () => { @@ -657,12 +653,11 @@ describe('ListWatchCache', () => { const cache = new ListWatch('/some/path', mock.instance(fakeWatch), listFn); await promise; const [pathOut, , watchHandler] = mock.capture(fakeWatch.watch).last(); - expect(pathOut).to.equal('/some/path'); - expect(cache.list()).to.deep.equal(list); - expect(cache.get('name1')).to.not.equal(null); - expect(cache.get('name2')).to.not.equal(null); - - expect(cache.list('ns1')).to.deep.equal([]); + strictEqual(pathOut, '/some/path'); + deepStrictEqual(cache.list(), list); + notStrictEqual(cache.get('name1'), null); + notStrictEqual(cache.get('name2'), null); + deepStrictEqual(cache.list('ns1'), []); watchHandler('ADDED', { metadata: { @@ -670,8 +665,8 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Namespace); - expect(cache.list().length).to.equal(3); - expect(cache.get('name3')).to.not.equal(null); + strictEqual(cache.list().length, 3); + notStrictEqual(cache.get('name3'), null); watchHandler('MODIFIED', { metadata: { @@ -679,12 +674,12 @@ describe('ListWatchCache', () => { resourceVersion: 'baz', } as V1ObjectMeta, } as V1Namespace); - expect(cache.list().length).to.equal(3); + strictEqual(cache.list().length, 3); const obj3 = cache.get('name3'); - expect(obj3).to.not.equal(null); + notStrictEqual(obj3, null); if (obj3) { - expect(obj3.metadata!.name).to.equal('name3'); - expect(obj3.metadata!.resourceVersion).to.equal('baz'); + strictEqual(obj3.metadata!.name, 'name3'); + strictEqual(obj3.metadata!.resourceVersion, 'baz'); } watchHandler('DELETED', { @@ -692,8 +687,8 @@ describe('ListWatchCache', () => { name: 'name2', } as V1ObjectMeta, } as V1Namespace); - expect(cache.list().length).to.equal(2); - expect(cache.get('name2', 'ns2')).to.equal(undefined); + strictEqual(cache.list().length, 2); + strictEqual(cache.get('name2', 'ns2'), undefined); }); it('should delete an object correctly', () => { @@ -721,21 +716,21 @@ describe('ListWatchCache', () => { namespace: 'ns1', }, } as V1Pod); - expect(objs.size).to.equal(2); + strictEqual(objs.size, 2); deleteObject(objs, { metadata: { name: 'name1', namespace: 'ns2', }, } as V1Pod); - expect(objs.size).to.equal(2); + strictEqual(objs.size, 2); deleteObject(objs, { metadata: { name: 'name1', namespace: 'ns1', }, } as V1Pod); - expect(objs.size).to.equal(1); + strictEqual(objs.size, 1); }); it('should not call handlers which have been unregistered', async () => { @@ -790,8 +785,8 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Namespace); - expect(addedList1.length).to.equal(2); - expect(addedList2.length).to.equal(1); + strictEqual(addedList1.length, 2); + strictEqual(addedList2.length, 1); }); it('mutating handlers in a callback should not affect those which remain', async () => { @@ -837,7 +832,7 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Namespace); - expect(addedList.length).to.equal(1); + strictEqual(addedList.length, 1); }); it('should resolve start promise after seeding the cache', async () => { @@ -871,9 +866,9 @@ describe('ListWatchCache', () => { }; const cache = new ListWatch('/some/path', mock.instance(fakeWatch), listFn, false); const startPromise: Promise = cache.start(); - expect(cache.list().length).to.equal(0); + strictEqual(cache.list().length, 0); await startPromise; - expect(cache.list().length).to.equal(2); + strictEqual(cache.list().length, 2); }); it('should only call update handlers once', async () => { @@ -932,9 +927,9 @@ describe('ListWatchCache', () => { } as V1ObjectMeta, } as V1Namespace); - expect(adds).to.equal(2); - expect(addedList1.length).to.equal(2); - expect(addedList2.length).to.equal(1); + strictEqual(adds, 2); + strictEqual(addedList1.length, 2); + strictEqual(addedList2.length, 1); }); it('should not auto-restart after explicitly stopping until restarted again', async () => { @@ -1045,7 +1040,7 @@ describe('ListWatchCache', () => { mock.verify( fakeWatch.watch(mock.anything(), mock.anything(), mock.anything(), mock.anything()), ).once(); - expect(errorEmitted).to.equal(true); + strictEqual(errorEmitted, true); }); it('should not re-list if the watch can be restarted from the latest resourceVersion', async () => { @@ -1098,7 +1093,7 @@ describe('ListWatchCache', () => { }); informer.start(); await promise; - expect(listCalls).to.be.equal(1); + strictEqual(listCalls, 1); }); it('should list if the watch cannot be restarted from the latest resourceVersion', async () => { @@ -1167,8 +1162,8 @@ describe('ListWatchCache', () => { mock.verify( fakeWatch.watch(mock.anything(), mock.anything(), mock.anything(), mock.anything()), ).thrice(); - expect(errorEmitted).to.equal(false); - expect(listCalls).to.be.equal(2); + strictEqual(errorEmitted, false); + strictEqual(listCalls, 2); }); it('should list if the watch cannot be restarted from the latest resourceVersion with an ERROR event', async () => { @@ -1236,8 +1231,8 @@ describe('ListWatchCache', () => { mock.verify( fakeWatch.watch(mock.anything(), mock.anything(), mock.anything(), mock.anything()), ).twice(); - expect(errorEmitted).to.equal(false); - expect(listCalls).to.be.equal(2); + strictEqual(errorEmitted, false); + strictEqual(listCalls, 2); }); it('should send label selector', async () => { @@ -1317,7 +1312,7 @@ describe('ListWatchCache', () => { const value = await donePromise; - expect(value).to.deep.equal({ + deepStrictEqual(value, { metadata: { labels: { app: 'foo3', @@ -1376,7 +1371,7 @@ describe('delete items', () => { }); deleteItems(objs, listB, [(obj?: V1Pod) => pods.push(obj!)]); - expect(pods).to.deep.equal(expected); + deepStrictEqual(pods, expected); }); it('should call the connect handler', async () => { @@ -1401,7 +1396,7 @@ describe('delete items', () => { }); informer.start(); - expect(connectPromise).to.eventually.be.true; + strictEqual(await connectPromise, true); }); it('does calls connect after a restart after an error', async () => { @@ -1454,7 +1449,7 @@ describe('delete items', () => { mock.verify( fakeWatch.watch(mock.anything(), mock.anything(), mock.anything(), mock.anything()), ).once(); - expect(errorEmitted).to.equal(true); + strictEqual(errorEmitted, true); const connectPromise = new Promise((resolve: (boolean) => void) => { cache.on('connect', (obj?: V1Namespace) => { @@ -1463,6 +1458,6 @@ describe('delete items', () => { }); cache.start(); - expect(connectPromise).to.eventually.be.true; + strictEqual(await connectPromise, true); }); }); diff --git a/src/config_test.ts b/src/config_test.ts index 7f1397ffaa..0a5f4b15a6 100644 --- a/src/config_test.ts +++ b/src/config_test.ts @@ -1,11 +1,10 @@ +import { deepEqual, deepStrictEqual, notStrictEqual, rejects, strictEqual, throws } from 'node:assert'; import { readFileSync } from 'node:fs'; import https from 'node:https'; import { Agent, RequestOptions } from 'node:https'; import path, { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { expect, use } from 'chai'; -import chaiAsPromised from 'chai-as-promised'; import mockfs from 'mock-fs'; import { Headers } from 'node-fetch'; @@ -32,71 +31,69 @@ const kcTlsServerNameFileName = 'testdata/tls-server-name-kubeconfig.yaml'; const __dirname = dirname(fileURLToPath(import.meta.url)); -use(chaiAsPromised); - describe('Config', () => {}); function validateFileLoad(kc: KubeConfig) { // check clusters const clusters = kc.getClusters(); - expect(clusters.length).to.equal(2, 'there are 2 clusters'); + strictEqual(clusters.length, 2, 'there are 2 clusters'); const cluster1 = clusters[0]; const cluster2 = clusters[1]; - expect(cluster1.name).to.equal('cluster1'); - expect(cluster1.caData).to.equal('Q0FEQVRB'); - expect(cluster1.server).to.equal('http://example.com'); - expect(cluster1.proxyUrl).to.equal('socks5://localhost:1181'); - expect(cluster2.name).to.equal('cluster2'); - expect(cluster2.caData).to.equal('Q0FEQVRBMg=='); - expect(cluster2.server).to.equal('http://example2.com'); - expect(cluster2.skipTLSVerify).to.equal(true); + strictEqual(cluster1.name, 'cluster1'); + strictEqual(cluster1.caData, 'Q0FEQVRB'); + strictEqual(cluster1.server, 'http://example.com'); + strictEqual(cluster1.proxyUrl, 'socks5://localhost:1181'); + strictEqual(cluster2.name, 'cluster2'); + strictEqual(cluster2.caData, 'Q0FEQVRBMg=='); + strictEqual(cluster2.server, 'http://example2.com'); + strictEqual(cluster2.skipTLSVerify, true); // check users const users = kc.getUsers(); - expect(users.length).to.equal(3, 'there are 3 users'); + strictEqual(users.length, 3, 'there are 3 users'); const user1 = users[0]; const user2 = users[1]; const user3 = users[2]; - expect(user1.name).to.equal('user1'); - expect(user1.certData).to.equal('VVNFUl9DQURBVEE='); - expect(user1.keyData).to.equal('VVNFUl9DS0RBVEE='); - expect(user2.name).to.equal('user2'); - expect(user2.certData).to.equal('VVNFUjJfQ0FEQVRB'); - expect(user2.keyData).to.equal('VVNFUjJfQ0tEQVRB'); - expect(user3.name).to.equal('user3'); - expect(user3.username).to.equal('foo'); - expect(user3.password).to.equal('bar'); + strictEqual(user1.name, 'user1'); + strictEqual(user1.certData, 'VVNFUl9DQURBVEE='); + strictEqual(user1.keyData, 'VVNFUl9DS0RBVEE='); + strictEqual(user2.name, 'user2'); + strictEqual(user2.certData, 'VVNFUjJfQ0FEQVRB'); + strictEqual(user2.keyData, 'VVNFUjJfQ0tEQVRB'); + strictEqual(user3.name, 'user3'); + strictEqual(user3.username, 'foo'); + strictEqual(user3.password, 'bar'); // check contexts const contexts = kc.getContexts(); - expect(contexts.length).to.equal(3, 'there are three contexts'); + strictEqual(contexts.length, 3, 'there are three contexts'); const context1 = contexts[0]; const context2 = contexts[1]; const context3 = contexts[2]; - expect(context1.name).to.equal('context1'); - expect(context1.user).to.equal('user1'); - expect(context1.namespace).to.equal(undefined); - expect(context1.cluster).to.equal('cluster1'); - expect(context2.name).to.equal('context2'); - expect(context2.user).to.equal('user2'); - expect(context2.namespace).to.equal('namespace2'); - expect(context2.cluster).to.equal('cluster2'); - expect(context3.name).to.equal('passwd'); - expect(context3.user).to.equal('user3'); - expect(context3.cluster).to.equal('cluster2'); - - expect(kc.getCurrentContext()).to.equal('context2'); + strictEqual(context1.name, 'context1'); + strictEqual(context1.user, 'user1'); + strictEqual(context1.namespace, undefined); + strictEqual(context1.cluster, 'cluster1'); + strictEqual(context2.name, 'context2'); + strictEqual(context2.user, 'user2'); + strictEqual(context2.namespace, 'namespace2'); + strictEqual(context2.cluster, 'cluster2'); + strictEqual(context3.name, 'passwd'); + strictEqual(context3.user, 'user3'); + strictEqual(context3.cluster, 'cluster2'); + + strictEqual(kc.getCurrentContext(), 'context2'); } describe('KubeConfig', () => { it('should return null on no contexts', () => { const kc = new KubeConfig() as any; kc.contexts = undefined; - expect(kc.getContextObject('non-existent')).to.be.null; + strictEqual(kc.getContextObject('non-existent'), null); }); describe('findObject', () => { it('should return null on undefined', () => { - expect(findObject(undefined as any, 'foo', 'bar')).to.equal(null); + strictEqual(findObject(undefined as any, 'foo', 'bar'), null); }); it('should find objects', () => { interface MyNamed { @@ -123,19 +120,15 @@ describe('KubeConfig', () => { // Validate that if the named object ('cluster' in this case) is inside we pick it out const obj1 = findObject(list, 'foo', 'cluster'); - expect(obj1).to.not.equal(null); - if (obj1) { - expect(obj1.some).to.equal('sub-object'); - } + notStrictEqual(obj1, null); + strictEqual(obj1!.some, 'sub-object'); // Validate that if the named object is missing, we just return the full object const obj2 = findObject(list, 'bar', 'context'); - expect(obj2).to.not.equal(null); - if (obj2) { - expect(obj2.some).to.equal('object'); - } + notStrictEqual(obj2, null); + strictEqual(obj2!.some, 'object'); // validate that we do the right thing if it is missing const obj3 = findObject(list, 'nonexistent', 'context'); - expect(obj3).to.equal(null); + strictEqual(obj3, null); }); }); @@ -155,10 +148,10 @@ describe('KubeConfig', () => { kc.loadFromClusterAndUser(cluster, user); const clusterOut = kc.getCurrentCluster(); - expect(clusterOut).to.equal(cluster); + strictEqual(clusterOut, cluster); const userOut = kc.getCurrentUser(); - expect(userOut).to.equal(user); + strictEqual(userOut, user); }); }); @@ -189,10 +182,10 @@ describe('KubeConfig', () => { }); const clusterOut = kc.getCurrentCluster(); - expect(clusterOut).to.equal(cluster); + strictEqual(clusterOut, cluster); const userOut = kc.getCurrentUser(); - expect(userOut).to.equal(user); + strictEqual(userOut, user); }); }); @@ -204,24 +197,24 @@ describe('KubeConfig', () => { }); it('should fail to load a missing kubeconfig file', () => { const kc = new KubeConfig(); - expect(kc.loadFromFile.bind('missing.yaml')).to.throw(); + throws(kc.loadFromFile.bind('missing.yaml')); }); describe('filter vs throw tests', () => { it('works for invalid users', () => { const kc = new KubeConfig(); kc.loadFromFile(kcNoUserFileName, { onInvalidEntry: ActionOnInvalid.FILTER }); - expect(kc.getUsers().length).to.be.eq(2); + strictEqual(kc.getUsers().length, 2); }); it('works for invalid contexts', () => { const kc = new KubeConfig(); kc.loadFromFile(kcInvalidContextFileName, { onInvalidEntry: ActionOnInvalid.FILTER }); - expect(kc.getContexts().length).to.be.eq(2); + strictEqual(kc.getContexts().length, 2); }); it('works for invalid clusters', () => { const kc = new KubeConfig(); kc.loadFromFile(kcInvalidClusterFileName, { onInvalidEntry: ActionOnInvalid.FILTER }); - expect(kc.getClusters().length).to.be.eq(1); + strictEqual(kc.getClusters().length, 1); }); }); }); @@ -267,9 +260,9 @@ describe('KubeConfig', () => { rejectUnauthorized: false, }); - expect(requestInit.method).to.equal('POST'); - expect(requestInit.timeout).to.equal(5); - expect((requestInit.headers as Headers).raw()).to.deep.equal({ + strictEqual(requestInit.method, 'POST'); + strictEqual(requestInit.timeout, 5); + deepEqual((requestInit.headers as Headers).raw(), { Authorization: ['Basic Zm9vOmJhcg=='], list: ['a', 'b'], number: ['5'], @@ -374,11 +367,11 @@ describe('KubeConfig', () => { const expectedProxyHost = 'example'; const expectedProxyPort = 1187; - expect(rc.getAgent()).to.be.instanceOf(SocksProxyAgent); + strictEqual(rc.getAgent() instanceof SocksProxyAgent, true); const agent = rc.getAgent() as SocksProxyAgent; - expect(agent.options.ca?.toString()).to.equal(expectedCA.toString()); - expect(agent.proxy.host).to.equal(expectedProxyHost); - expect(agent.proxy.port).to.equal(expectedProxyPort); + strictEqual(agent.options.ca?.toString(), expectedCA.toString()); + strictEqual(agent.proxy.host, expectedProxyHost); + strictEqual(agent.proxy.port, expectedProxyPort); }); it('should apply https proxy', async () => { const kc = new KubeConfig(); @@ -392,10 +385,10 @@ describe('KubeConfig', () => { const expectedCA = Buffer.from('CADAT@', 'utf-8'); const expectedProxyHref = 'http://example:9443/'; - expect(rc.getAgent()).to.be.instanceOf(HttpsProxyAgent); + strictEqual(rc.getAgent() instanceof HttpsProxyAgent, true); const agent = rc.getAgent() as HttpsProxyAgent; - expect(agent.options.ca?.toString()).to.equal(expectedCA.toString()); - expect((agent as any).proxy.href).to.equal(expectedProxyHref); + strictEqual(agent.options.ca?.toString(), expectedCA.toString()); + strictEqual((agent as any).proxy.href, expectedProxyHref); }); it('should apply http proxy', async () => { const kc = new KubeConfig(); @@ -409,10 +402,10 @@ describe('KubeConfig', () => { const expectedCA = Buffer.from('CADAT@', 'utf-8'); const expectedProxyHref = 'http://example:8080/'; - expect(rc.getAgent()).to.be.instanceOf(HttpProxyAgent); + strictEqual(rc.getAgent() instanceof HttpProxyAgent, true); const agent = rc.getAgent() as HttpProxyAgent; - expect((agent as any).options.ca?.toString()).to.equal(expectedCA.toString()); - expect((agent as any).proxy.href).to.equal(expectedProxyHref); + strictEqual((agent as any).options.ca?.toString(), expectedCA.toString()); + strictEqual((agent as any).proxy.href, expectedProxyHref); }); it('should throw an error if proxy-url is provided but the server protocol is not http or https', async () => { const kc = new KubeConfig(); @@ -422,72 +415,86 @@ describe('KubeConfig', () => { const testServerName = 'https://example.com'; const rc = new RequestContext(testServerName, HttpMethod.GET); - return expect(kc.applySecurityAuthentication(rc)).to.be.rejectedWith('Unsupported proxy type'); + return rejects(kc.applySecurityAuthentication(rc), { + message: 'Unsupported proxy type', + }); }); }); describe('loadClusterConfigObjects', () => { it('should fail if name is missing from cluster', () => { - expect(() => { - newClusters([ - { - name: 'some-cluster', - cluster: { - server: 'some.server.com', + throws( + () => { + newClusters([ + { + name: 'some-cluster', + cluster: { + server: 'some.server.com', + }, }, - }, - { - foo: 'bar', - }, - ]); - }).to.throw('clusters[1].name is missing'); + { + foo: 'bar', + }, + ]); + }, + { message: 'clusters[1].name is missing' }, + ); }); it('should fail if cluster is missing from cluster', () => { - expect(() => { - newClusters([ - { - name: 'some-cluster', - cluster: { - server: 'some.server.com', + throws( + () => { + newClusters([ + { + name: 'some-cluster', + cluster: { + server: 'some.server.com', + }, }, - }, - { - name: 'bar', - }, - ]); - }).to.throw('clusters[1].cluster is missing'); + { + name: 'bar', + }, + ]); + }, + { message: 'clusters[1].cluster is missing' }, + ); }); it('should fail if cluster.server is missing from cluster', () => { - expect(() => { - newClusters([ - { - name: 'some-cluster', - cluster: { - server: 'some.server.com', + throws( + () => { + newClusters([ + { + name: 'some-cluster', + cluster: { + server: 'some.server.com', + }, }, - }, - { - name: 'bar', - cluster: {}, - }, - ]); - }).to.throw('clusters[1].cluster.server is missing'); + { + name: 'bar', + cluster: {}, + }, + ]); + }, + { message: 'clusters[1].cluster.server is missing' }, + ); }); }); describe('loadUserConfigObjects', () => { it('should fail if name is missing from user', () => { - expect(() => { - newUsers([ - { - name: 'some-user', - user: {}, - }, - { - foo: 'bar', - }, - ]); - }).to.throw('users[1].name is missing'); + throws( + () => { + newUsers([ + { + name: 'some-user', + user: {}, + }, + { + foo: 'bar', + }, + ]); + }, + { message: 'users[1].name is missing' }, + ); }); it('should load correctly with just name', () => { const name = 'some-name'; @@ -496,7 +503,7 @@ describe('KubeConfig', () => { name, }, ]); - expect(name).to.equal(users[0].name); + strictEqual(name, users[0].name); }); it('should load token correctly', () => { const name = 'some-name'; @@ -509,8 +516,8 @@ describe('KubeConfig', () => { }, }, ]); - expect(name).to.equal(users[0].name); - expect(token).to.equal(users[0].token); + strictEqual(name, users[0].name); + strictEqual(token, users[0].token); }); it('should load token file correctly', () => { const name = 'some-name'; @@ -529,8 +536,8 @@ describe('KubeConfig', () => { }, ]); mockfs.restore(); - expect(name).to.equal(users[0].name); - expect(token).to.equal(users[0].token); + strictEqual(name, users[0].name); + strictEqual(token, users[0].token); }); it('should load extra auth stuff correctly', () => { const authProvider = 'authProvider'; @@ -555,14 +562,14 @@ describe('KubeConfig', () => { }, }, ]); - expect(authProvider).to.equal(users[0].authProvider); - expect(certData).to.equal(users[0].certData); - expect(certFile).to.equal(users[0].certFile); - expect(keyData).to.equal(users[0].keyData); - expect(keyFile).to.equal(users[0].keyFile); - expect(password).to.equal(users[0].password); - expect(username).to.equal(users[0].username); - expect(name).to.equal(users[0].name); + strictEqual(authProvider, users[0].authProvider); + strictEqual(certData, users[0].certData); + strictEqual(certFile, users[0].certFile); + strictEqual(keyData, users[0].keyData); + strictEqual(keyFile, users[0].keyFile); + strictEqual(password, users[0].password); + strictEqual(username, users[0].username); + strictEqual(name, users[0].name); }); }); @@ -581,7 +588,7 @@ describe('KubeConfig', () => { mockfs.restore(); process.env.HOME = currentHome; - expect(home).to.equal(expectedHome); + strictEqual(home, expectedHome); }); }); @@ -618,7 +625,7 @@ describe('KubeConfig', () => { it('should return null if no home-ish env vars are set', () => { const dir = findHomeDir(); - expect(dir).to.equal(null); + strictEqual(dir, null); }); describe('look for an existing .kube/config', () => { @@ -643,7 +650,7 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(dir); + strictEqual(home, dir); }); it('should favor HOME when present', () => { const dir = process.env.HOME as string; @@ -655,7 +662,7 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(dir); + strictEqual(home, dir); }); it('should load from HOMEDRIVE/HOMEPATH if present', () => { @@ -666,7 +673,7 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(dir); + strictEqual(home, dir); }); it('should favor HOMEDRIVE/HOMEPATH over USERPROFILE', () => { @@ -678,7 +685,7 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(dir); + strictEqual(home, dir); }); it('should load from USERPROFILE if present', () => { @@ -689,7 +696,7 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(dir); + strictEqual(home, dir); }); }); @@ -715,7 +722,7 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(dir); + strictEqual(home, dir); }); it('should load from USERPROFILE if present', () => { allDirs[homeDrive] = 'data'; @@ -725,7 +732,7 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(process.env.USERPROFILE); + strictEqual(home, process.env.USERPROFILE); }); it('should load from homeDrive if present', () => { allDirs[homeDrive] = 'data'; @@ -734,7 +741,7 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(homeDrive); + strictEqual(home, homeDrive); }); it('should return HOME when no home-ish directories are present', () => { mockfs({}); @@ -742,62 +749,71 @@ describe('KubeConfig', () => { const home = findHomeDir(); mockfs.restore(); - expect(home).to.equal(process.env.HOME); + strictEqual(home, process.env.HOME); }); }); }); describe('loadContextConfigObjects', () => { it('should fail if name is missing from context', () => { - expect(() => { - newContexts([ - { - name: 'some-cluster', - context: { - cluster: 'foo', - user: 'bar', + throws( + () => { + newContexts([ + { + name: 'some-cluster', + context: { + cluster: 'foo', + user: 'bar', + }, }, - }, - { - foo: 'bar', - }, - ]); - }).to.throw('contexts[1].name is missing'); + { + foo: 'bar', + }, + ]); + }, + { message: 'contexts[1].name is missing' }, + ); }); it('should fail if context is missing from context', () => { - expect(() => { - newContexts([ - { - name: 'some-cluster', - context: { - cluster: 'foo', - user: 'bar', + throws( + () => { + newContexts([ + { + name: 'some-cluster', + context: { + cluster: 'foo', + user: 'bar', + }, }, - }, - { - name: 'bar', - }, - ]); - }).to.throw('contexts[1].context is missing'); + { + name: 'bar', + }, + ]); + }, + { message: 'contexts[1].context is missing' }, + ); }); it('should fail if context is missing from context', () => { - expect(() => { - newContexts([ - { - name: 'some-cluster', - context: { - cluster: 'foo', - user: 'bar', + throws( + () => { + newContexts([ + { + name: 'some-cluster', + context: { + cluster: 'foo', + user: 'bar', + }, }, - }, - { - name: 'bar', - context: { - user: 'user', + { + name: 'bar', + context: { + user: 'user', + }, }, - }, - ]); - }).to.throw('contexts[1].context.cluster is missing'); + ]); + }, + { message: 'contexts[1].context.cluster is missing' }, + ); }); }); @@ -811,7 +827,7 @@ describe('KubeConfig', () => { const opts = {} as https.RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.auth).to.equal(`${user}:${passwd}`); + strictEqual(opts.auth, `${user}:${passwd}`); }); it('should populate options for request', async () => { const config = new KubeConfig(); @@ -831,11 +847,8 @@ describe('KubeConfig', () => { await config.applyToHTTPSOptions(opts); - expect(opts.auth).to.not.be.undefined; - if (opts.auth) { - expect(opts.auth).to.equal(`${user}:${passwd}`); - } - expect(opts.rejectUnauthorized).to.equal(false); + strictEqual(opts.auth, `${user}:${passwd}`); + strictEqual(opts.rejectUnauthorized, false); }); it('should not populate strict ssl', async () => { const config = new KubeConfig(); @@ -845,7 +858,7 @@ describe('KubeConfig', () => { await config.applyToHTTPSOptions(opts); - expect(opts.rejectUnauthorized).to.equal(undefined); + strictEqual(opts.rejectUnauthorized, undefined); }); it('should populate from token', async () => { const config = new KubeConfig(); @@ -859,10 +872,7 @@ describe('KubeConfig', () => { const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should populate from auth provider', async () => { const config = new KubeConfig(); @@ -882,14 +892,11 @@ describe('KubeConfig', () => { const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); opts.headers = {}; opts.headers.Host = 'foo.com'; await config.applyToHTTPSOptions(opts); - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); + strictEqual(opts.headers.Authorization, `Bearer ${token}`); }); it('should populate from auth provider without expirty', async () => { @@ -909,10 +916,7 @@ describe('KubeConfig', () => { const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should populate rejectUnauthorized=false when skipTLSVerify is set', async () => { @@ -932,7 +936,7 @@ describe('KubeConfig', () => { const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.rejectUnauthorized).to.equal(false); + strictEqual(opts.rejectUnauthorized, false); }); it('should not set rejectUnauthorized if skipTLSVerify is not set', async () => { @@ -954,7 +958,7 @@ describe('KubeConfig', () => { const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.rejectUnauthorized).to.equal(undefined); + strictEqual(opts.rejectUnauthorized, undefined); }); it('should throw with expired token and no cmd', () => { @@ -972,9 +976,9 @@ describe('KubeConfig', () => { ); const opts = {} as RequestOptions; - return expect(config.applyToHTTPSOptions(opts)).to.eventually.be.rejectedWith( - 'Token is expired!', - ); + return rejects(config.applyToHTTPSOptions(opts), { + message: 'Token is expired!', + }); }); it('should throw with bad command', () => { @@ -993,9 +997,7 @@ describe('KubeConfig', () => { } as User, ); const opts = {} as RequestOptions; - return expect(config.applyToHTTPSOptions(opts)).to.eventually.be.rejectedWith( - /Failed to refresh token/, - ); + return rejects(config.applyToHTTPSOptions(opts), /Failed to refresh token/); }); it('should exec with expired token', async () => { @@ -1023,10 +1025,7 @@ describe('KubeConfig', () => { ); const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should exec with expired token', async () => { @@ -1054,10 +1053,7 @@ describe('KubeConfig', () => { ); const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should exec without access-token', async () => { @@ -1084,10 +1080,7 @@ describe('KubeConfig', () => { ); const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should exec without access-token', async () => { // TODO: fix this test for Windows @@ -1113,10 +1106,7 @@ describe('KubeConfig', () => { ); const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should exec succesfully with spaces in cmd', async () => { // TODO: fix this test for Windows @@ -1142,10 +1132,7 @@ describe('KubeConfig', () => { ); const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should exec with exec auth and env vars', async () => { // TODO: fix this test for Windows @@ -1178,10 +1165,7 @@ describe('KubeConfig', () => { // TODO: inject the exec command here and validate env vars? const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should exec with exec auth', async () => { // TODO: fix this test for Windows @@ -1214,10 +1198,7 @@ describe('KubeConfig', () => { // TODO: inject the exec command here? const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should exec with exec auth (other location)', async () => { // TODO: fix this test for Windows @@ -1245,10 +1226,7 @@ describe('KubeConfig', () => { // TODO: inject the exec command here? const opts = {} as RequestOptions; await config.applyToHTTPSOptions(opts); - expect(opts.headers).to.not.be.undefined; - if (opts.headers) { - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); - } + strictEqual(opts.headers!.Authorization, `Bearer ${token}`); }); it('should cache exec with name', async () => { // TODO: fix this test for Windows @@ -1280,7 +1258,7 @@ describe('KubeConfig', () => { const execAuthenticator = (KubeConfig as any).authenticators.find( (authenticator) => authenticator instanceof ExecAuth, ); - expect(execAuthenticator.tokenCache.exec).to.deep.equal(JSON.parse(responseStr)); + deepStrictEqual(execAuthenticator.tokenCache.exec, JSON.parse(responseStr)); }); it('should throw with no command.', () => { @@ -1297,9 +1275,9 @@ describe('KubeConfig', () => { } as User, ); const opts = {} as RequestOptions; - return expect(config.applyToHTTPSOptions(opts)).to.eventually.be.rejectedWith( - 'No command was specified for exec authProvider!', - ); + return rejects(config.applyToHTTPSOptions(opts), { + message: 'No command was specified for exec authProvider!', + }); }); }); @@ -1311,10 +1289,10 @@ describe('KubeConfig', () => { kc.loadFromDefault(); // 2 in the first config, 1 in the second config - expect(kc.clusters.length).to.equal(3); - expect(kc.users.length).to.equal(6); - expect(kc.contexts.length).to.equal(4); - expect(kc.getCurrentContext()).to.equal('contextA'); + strictEqual(kc.clusters.length, 3); + strictEqual(kc.users.length, 6); + strictEqual(kc.contexts.length, 4); + strictEqual(kc.getCurrentContext(), 'contextA'); }); it('should preserve starting file context', () => { process.env.KUBECONFIG = kcFileName + path.delimiter + kc2FileName; @@ -1322,27 +1300,27 @@ describe('KubeConfig', () => { const kc = new KubeConfig(); kc.loadFromDefault({}, true); - expect(kc.getCurrentContext()).to.equal('context2'); + strictEqual(kc.getCurrentContext(), 'context2'); }); it('should throw with duplicate clusters', () => { process.env.KUBECONFIG = kcFileName + path.delimiter + kcDupeCluster; const kc = new KubeConfig(); - expect(() => kc.loadFromDefault()).to.throw('Duplicate cluster: cluster1'); + throws(() => kc.loadFromDefault(), { message: 'Duplicate cluster: cluster1' }); }); it('should throw with duplicate contexts', () => { process.env.KUBECONFIG = kcFileName + path.delimiter + kcDupeContext; const kc = new KubeConfig(); - expect(() => kc.loadFromDefault()).to.throw('Duplicate context: context1'); + throws(() => kc.loadFromDefault(), { message: 'Duplicate context: context1' }); }); it('should throw with duplicate users', () => { process.env.KUBECONFIG = kcFileName + path.delimiter + kcDupeUser; const kc = new KubeConfig(); - expect(() => kc.loadFromDefault()).to.throw('Duplicate user: user1'); + throws(() => kc.loadFromDefault(), { message: 'Duplicate user: user1' }); }); it('should ignore extra path delimiters', () => { @@ -1351,10 +1329,10 @@ describe('KubeConfig', () => { const kc = new KubeConfig(); kc.loadFromDefault(); - expect(kc.clusters.length).to.equal(2); - expect(kc.users.length).to.equal(3); - expect(kc.contexts.length).to.equal(3); - expect(kc.getCurrentContext()).to.equal('context2'); + strictEqual(kc.clusters.length, 2); + strictEqual(kc.users.length, 3); + strictEqual(kc.contexts.length, 3); + strictEqual(kc.getCurrentContext(), 'context2'); }); }); @@ -1382,17 +1360,17 @@ describe('KubeConfig', () => { keyFile: 'user/user.key', }); kc.makePathsAbsolute('/tmp'); - expect(kc.clusters[0].caFile).to.equal(platformPath('/tmp/foo/bar.crt')); - expect(kc.users[0].certFile).to.equal(platformPath('/tmp/user/user.crt')); - expect(kc.users[0].keyFile).to.equal(platformPath('/tmp/user/user.key')); + strictEqual(kc.clusters[0].caFile, platformPath('/tmp/foo/bar.crt')); + strictEqual(kc.users[0].certFile, platformPath('/tmp/user/user.crt')); + strictEqual(kc.users[0].keyFile, platformPath('/tmp/user/user.key')); }); it('should correctly make absolute paths', () => { const relative = 'foo/bar'; const absolute = '/tmp/foo/bar'; const root = '/usr/'; - expect(makeAbsolutePath(root, relative)).to.equal(platformPath('/usr/foo/bar')); - expect(makeAbsolutePath(root, absolute)).to.equal(absolute); + strictEqual(makeAbsolutePath(root, relative), platformPath('/usr/foo/bar')); + strictEqual(makeAbsolutePath(root, absolute), absolute); }); }); @@ -1450,25 +1428,17 @@ describe('KubeConfig', () => { delete process.env.KUBERNETES_SERVICE_PORT; const cluster = kc.getCurrentCluster(); - expect(cluster).to.not.be.null; - if (!cluster) { - return; - } - expect(cluster.caFile).to.equal('/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'); - expect(cluster.server).to.equal('https://kubernetes:443'); + strictEqual(cluster!.caFile, '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'); + strictEqual(cluster!.server, 'https://kubernetes:443'); const user = kc.getCurrentUser(); - expect(user).to.not.be.null; - if (user) { - expect(user.authProvider.config.tokenFile).to.equal( - '/var/run/secrets/kubernetes.io/serviceaccount/token', - ); - } + strictEqual( + user!.authProvider.config.tokenFile, + '/var/run/secrets/kubernetes.io/serviceaccount/token', + ); + const contextName = kc.getCurrentContext(); const currentContext = kc.getContextObject(contextName); - expect(currentContext).to.not.be.null; - if (currentContext) { - expect(currentContext.namespace).to.equal('myNamespace'); - } + strictEqual(currentContext!.namespace, 'myNamespace'); }); it('should load from cluster with http port', () => { @@ -1494,11 +1464,7 @@ describe('KubeConfig', () => { delete process.env.KUBERNETES_SERVICE_PORT; const cluster = kc.getCurrentCluster(); - expect(cluster).to.not.be.null; - if (!cluster) { - return; - } - expect(cluster.server).to.equal('http://kubernetes:80'); + strictEqual(cluster!.server, 'http://kubernetes:80'); }); it('should load from cluster with ipv6', () => { @@ -1524,11 +1490,7 @@ describe('KubeConfig', () => { delete process.env.KUBERNETES_SERVICE_PORT; const cluster = kc.getCurrentCluster(); - expect(cluster).to.not.be.null; - if (!cluster) { - return; - } - expect(cluster.server).to.equal('http://[::1234:5678]:80'); + strictEqual(cluster!.server, 'http://[::1234:5678]:80'); }); it('should default to localhost', () => { @@ -1543,18 +1505,11 @@ describe('KubeConfig', () => { process.env.HOME = currentHome; const cluster = kc.getCurrentCluster(); - expect(cluster).to.not.be.null; - if (!cluster) { - return; - } - expect(cluster.name).to.equal('cluster'); - expect(cluster.server).to.equal('http://localhost:8080'); + strictEqual(cluster!.name, 'cluster'); + strictEqual(cluster!.server, 'http://localhost:8080'); const user = kc.getCurrentUser(); - expect(user).to.not.be.null; - if (user) { - expect(user.name).to.equal('user'); - } + strictEqual(user!.name, 'user'); }); }); @@ -1568,30 +1523,30 @@ describe('KubeConfig', () => { kc.loadFromFile(kcFileName); const client = kc.makeApiClient(CoreV1Api); - expect(client instanceof CoreV1Api).to.equal(true); + strictEqual(client instanceof CoreV1Api, true); }); }); describe('EmptyConfig', () => { const emptyConfig = new KubeConfig(); it('should throw if you try to make a client', () => { - expect(() => emptyConfig.makeApiClient(CoreV1Api)).to.throw('No active cluster!'); + throws(() => emptyConfig.makeApiClient(CoreV1Api), { message: 'No active cluster!' }); }); it('should get a null current cluster', () => { - expect(emptyConfig.getCurrentCluster()).to.equal(null); + strictEqual(emptyConfig.getCurrentCluster(), null); }); it('should get empty user', () => { - expect(emptyConfig.getCurrentUser()).to.equal(null); + strictEqual(emptyConfig.getCurrentUser(), null); }); it('should get empty cluster', () => { - expect(emptyConfig.getCurrentCluster()).to.equal(null); + strictEqual(emptyConfig.getCurrentCluster(), null); }); it('should get empty context', () => { - expect(emptyConfig.getCurrentContext()).to.be.undefined; + strictEqual(emptyConfig.getCurrentContext(), undefined); }); it('should apply to request', async () => { @@ -1623,8 +1578,8 @@ describe('KubeConfig', () => { }); kc.setCurrentContext('test'); - expect(kc.getCurrentCluster()!.name).to.equal('testCluster'); - expect(kc.getCurrentUser()!.username).to.equal('username'); + strictEqual(kc.getCurrentCluster()!.name, 'testCluster'); + strictEqual(kc.getCurrentUser()!.username, 'username'); }); }); @@ -1638,10 +1593,7 @@ describe('KubeConfig', () => { }; mockfs(arg); const inputData = bufferFromFileOrString('configDir/config'); - expect(inputData).to.not.equal(null); - if (inputData) { - expect(inputData.toString()).to.equal(data); - } + strictEqual(inputData!.toString(), data); mockfs.restore(); }); it('should load from a file if present', () => { @@ -1651,10 +1603,7 @@ describe('KubeConfig', () => { }; mockfs(arg); const inputData = bufferFromFileOrString('config'); - expect(inputData).to.not.equal(null); - if (inputData) { - expect(inputData.toString()).to.equal(data); - } + strictEqual(inputData!.toString(), data); mockfs.restore(); }); }); diff --git a/src/exec_auth_test.ts b/src/exec_auth_test.ts index 9ec599a9dd..dfdcfdad02 100644 --- a/src/exec_auth_test.ts +++ b/src/exec_auth_test.ts @@ -1,7 +1,4 @@ -import { expect, use } from 'chai'; -import chaiAsPromised from 'chai-as-promised'; -use(chaiAsPromised); - +import { rejects, strictEqual } from 'node:assert'; import https from 'node:https'; import { OutgoingHttpHeaders } from 'node:http'; @@ -15,22 +12,22 @@ describe('ExecAuth', () => { const auth = new ExecAuth(); const unk: unknown = null; - expect(auth.isAuthProvider(unk as User)).to.be.false; + strictEqual(auth.isAuthProvider(unk as User), false); const empty = {} as User; - expect(auth.isAuthProvider(empty)).to.be.false; + strictEqual(auth.isAuthProvider(empty), false); const exec = { exec: {}, } as User; - expect(auth.isAuthProvider(exec)).to.be.true; + strictEqual(auth.isAuthProvider(exec), true); const execName = { authProvider: { name: 'exec', }, } as User; - expect(auth.isAuthProvider(execName)).to.be.true; + strictEqual(auth.isAuthProvider(execName), true); const execConfig = { authProvider: { @@ -39,7 +36,7 @@ describe('ExecAuth', () => { }, }, } as User; - expect(auth.isAuthProvider(execConfig)).to.be.true; + strictEqual(auth.isAuthProvider(execConfig), true); const azureConfig = { authProvider: { @@ -49,7 +46,7 @@ describe('ExecAuth', () => { }, }, } as User; - expect(auth.isAuthProvider(azureConfig)).to.be.false; + strictEqual(auth.isAuthProvider(azureConfig), false); }); it('should correctly exec', async () => { @@ -96,7 +93,7 @@ describe('ExecAuth', () => { }, opts, ); - expect(opts.headers.Authorization).to.equal('Bearer foo'); + strictEqual(opts.headers.Authorization, 'Bearer foo'); }); it('should correctly exec for certs', async () => { @@ -150,9 +147,9 @@ describe('ExecAuth', () => { opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.be.undefined; - expect(opts.cert).to.equal('foo'); - expect(opts.key).to.equal('bar'); + strictEqual(opts.headers.Authorization, undefined); + strictEqual(opts.cert, 'foo'); + strictEqual(opts.key, 'bar'); }); it('should correctly exec and cache', async () => { @@ -210,21 +207,21 @@ describe('ExecAuth', () => { opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.equal(`Bearer ${tokenValue}`); - expect(execCount).to.equal(1); + strictEqual(opts.headers.Authorization, `Bearer ${tokenValue}`); + strictEqual(execCount, 1); // old token should be expired, set expiration for the new token for the future. expire = '29 Mar 2095 00:00:00 GMT'; tokenValue = 'bar'; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.equal(`Bearer ${tokenValue}`); - expect(execCount).to.equal(2); + strictEqual(opts.headers.Authorization, `Bearer ${tokenValue}`); + strictEqual(execCount, 2); // Should use cached token, execCount should stay at two, token shouldn't change tokenValue = 'baz'; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.equal('Bearer bar'); - expect(execCount).to.equal(2); + strictEqual(opts.headers.Authorization, 'Bearer bar'); + strictEqual(execCount, 2); }); it('should return null on no exec info', async () => { @@ -233,10 +230,10 @@ describe('ExecAuth', () => { opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication({} as User, opts); - expect(opts.headers.Authorization).to.be.undefined; + strictEqual(opts.headers.Authorization, undefined); }); - it('should throw on spawnSync errors', () => { + it('should throw on spawnSync errors', async () => { // TODO: fix this test for Windows if (process.platform === 'win32') { return; @@ -288,7 +285,7 @@ describe('ExecAuth', () => { opts.headers = {} as OutgoingHttpHeaders; const promise = auth.applyAuthentication(user, opts); - return expect(promise).to.eventually.be.rejected.and.not.instanceOf(TypeError); + await rejects(promise, { name: 'Error' }); }); it('should throw on exec errors', () => { @@ -338,7 +335,7 @@ describe('ExecAuth', () => { opts.headers = {} as OutgoingHttpHeaders; const promise = auth.applyAuthentication(user, opts); - return expect(promise).to.eventually.be.rejected; + return rejects(promise); }); it('should exec with env vars', async () => { @@ -396,9 +393,9 @@ describe('ExecAuth', () => { }, opts, ); - expect(optsOut.env!.foo).to.equal('bar'); - expect(optsOut.env!.PATH).to.equal(process.env.PATH); - expect(optsOut.env!.BLABBLE).to.equal(process.env.BLABBLE); + strictEqual(optsOut.env!.foo, 'bar'); + strictEqual(optsOut.env!.PATH, process.env.PATH); + strictEqual(optsOut.env!.BLABBLE, process.env.BLABBLE); }); it('should handle empty headers array correctly', async () => { @@ -445,6 +442,6 @@ describe('ExecAuth', () => { }, opts, ); - expect(opts.headers?.Authorization).to.equal('Bearer foo'); + strictEqual(opts.headers?.Authorization, 'Bearer foo'); }); }); diff --git a/src/exec_test.ts b/src/exec_test.ts index 6ad875d6ae..e74a8c04f0 100644 --- a/src/exec_test.ts +++ b/src/exec_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { deepStrictEqual, strictEqual } from 'node:assert'; import WebSocket from 'isomorphic-ws'; import { ReadableStreamBuffer, WritableStreamBuffer } from 'stream-buffers'; import { anyFunction, anything, capture, instance, mock, verify, when } from 'ts-mockito'; @@ -95,7 +95,7 @@ describe('Exec', () => { const [, , outputFn] = capture(fakeWebSocketInterface.connect).last(); - expect(outputFn).to.not.be.null; + strictEqual(typeof outputFn, 'function'); // this is redundant but needed for the compiler, sigh... if (!outputFn) { @@ -105,18 +105,18 @@ describe('Exec', () => { let buffer = Buffer.alloc(1024, 10); outputFn(WebSocketHandler.StdoutStream, buffer); - expect(osStream.size()).to.equal(1024); + strictEqual(osStream.size(), 1024); let buff = osStream.getContents() as Buffer; for (let i = 0; i < 1024; i++) { - expect(buff[i]).to.equal(10); + strictEqual(buff[i], 10); } buffer = Buffer.alloc(1024, 20); outputFn(WebSocketHandler.StderrStream, buffer); - expect(errStream.size()).to.equal(1024); + strictEqual(errStream.size(), 1024); buff = errStream.getContents() as Buffer; for (let i = 0; i < 1024; i++) { - expect(buff[i]).to.equal(20); + strictEqual(buff[i], 20); } const initialTerminalSize: TerminalSize = { height: 0, width: 0 }; @@ -148,7 +148,7 @@ describe('Exec', () => { message: 'this is a test', } as V1Status; outputFn(WebSocketHandler.StatusStream, Buffer.from(JSON.stringify(statusIn))); - expect(statusOut).to.deep.equal(statusIn); + deepStrictEqual(statusOut, statusIn); const closePromise = callAwaiter.awaitCall('close'); isStream.stop(); diff --git a/src/file_auth_test.ts b/src/file_auth_test.ts index 6dadc045ec..2b3af3b82a 100644 --- a/src/file_auth_test.ts +++ b/src/file_auth_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { strictEqual } from 'node:assert'; import { OutgoingHttpHeaders } from 'node:http'; import https from 'node:https'; import mockfs from 'mock-fs'; @@ -28,7 +28,7 @@ describe('FileAuth', () => { opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); + strictEqual(opts.headers.Authorization, `Bearer ${token}`); mockfs.restore(); }); it('should refresh when expired', async () => { @@ -53,7 +53,7 @@ describe('FileAuth', () => { opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); + strictEqual(opts.headers.Authorization, `Bearer ${token}`); mockfs.restore(); }); it('should claim correctly', async () => { @@ -77,13 +77,13 @@ describe('FileAuth', () => { opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); + strictEqual(opts.headers.Authorization, `Bearer ${token}`); // Set the file to non-existent, but shouldn't matter b/c token is cached. user.authProvider.config.tokenFile = '/non/existent/file/token.txt'; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); + strictEqual(opts.headers.Authorization, `Bearer ${token}`); mockfs.restore(); }); }); diff --git a/src/gcp_auth_test.ts b/src/gcp_auth_test.ts index ea592778e9..510bad616e 100644 --- a/src/gcp_auth_test.ts +++ b/src/gcp_auth_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { rejects, strictEqual } from 'node:assert'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -24,7 +24,7 @@ describe('GoogleCloudPlatformAuth', () => { }, } as User; - expect(auth.isAuthProvider(user)).to.equal(true); + strictEqual(auth.isAuthProvider(user), true); }); it('should be false for other user', () => { @@ -34,13 +34,13 @@ describe('GoogleCloudPlatformAuth', () => { }, } as User; - expect(auth.isAuthProvider(user)).to.equal(false); + strictEqual(auth.isAuthProvider(user), false); }); it('should be false for null user.authProvider', () => { const user = {} as User; - expect(auth.isAuthProvider(user)).to.equal(false); + strictEqual(auth.isAuthProvider(user), false); }); it('should populate from auth provider', async () => { @@ -61,14 +61,11 @@ describe('GoogleCloudPlatformAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - if (requestContext.getHeaders()) { - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); - } + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); requestContext.setUrl('http://www.foo.com'); //opts.headers.Host = 'foo.com'; await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); + strictEqual(requestContext.getHeaders()['Authorization'], `Bearer ${token}`); }); it('should populate from auth provider without expirty', async () => { @@ -88,10 +85,7 @@ describe('GoogleCloudPlatformAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - if (requestContext.getHeaders()) { - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); - } + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); it('should populate rejectUnauthorized=false when skipTLSVerify is set', async () => { @@ -114,7 +108,7 @@ describe('GoogleCloudPlatformAuth', () => { // @ts-expect-error const agent: Agent = requestContext.getAgent(); - expect(agent.options.rejectUnauthorized).to.equal(false); + strictEqual(agent.options.rejectUnauthorized, false); }); it('should not set rejectUnauthorized if skipTLSVerify is not set', async () => { @@ -136,7 +130,7 @@ describe('GoogleCloudPlatformAuth', () => { const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()['rejectUnauthorized']).to.equal(undefined); + strictEqual(requestContext.getHeaders()['rejectUnauthorized'], undefined); }); it('should throw with expired token and no cmd', () => { @@ -154,9 +148,9 @@ describe('GoogleCloudPlatformAuth', () => { ); const requestContext = new RequestContext(testUrl1, HttpMethod.GET); - return expect(config.applySecurityAuthentication(requestContext)).to.eventually.be.rejectedWith( - 'Token is expired!', - ); + return rejects(config.applySecurityAuthentication(requestContext), { + message: 'Token is expired!', + }); }); it('should throw with bad command', () => { @@ -175,9 +169,7 @@ describe('GoogleCloudPlatformAuth', () => { } as User, ); const requestContext = new RequestContext(testUrl1, HttpMethod.GET); - return expect(config.applySecurityAuthentication(requestContext)).to.eventually.be.rejectedWith( - /Failed to refresh token/, - ); + return rejects(config.applySecurityAuthentication(requestContext), /Failed to refresh token/); }); it('should exec with expired token', async () => { @@ -205,10 +197,7 @@ describe('GoogleCloudPlatformAuth', () => { ); const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - if (requestContext.getHeaders()) { - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); - } + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); it('should exec without access-token', async () => { // TODO: fix this test for Windows @@ -234,10 +223,7 @@ describe('GoogleCloudPlatformAuth', () => { ); const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - if (requestContext.getHeaders()) { - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); - } + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); it('should exec without access-token', async () => { // TODO: fix this test for Windows @@ -263,10 +249,7 @@ describe('GoogleCloudPlatformAuth', () => { ); const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - if (requestContext.getHeaders()) { - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); - } + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); it('should exec succesfully with spaces in cmd', async () => { // TODO: fix this test for Windows @@ -292,9 +275,6 @@ describe('GoogleCloudPlatformAuth', () => { ); const requestContext = new RequestContext(testUrl1, HttpMethod.GET); await config.applySecurityAuthentication(requestContext); - expect(requestContext.getHeaders()).to.not.be.undefined; - if (requestContext.getHeaders()) { - expect(requestContext.getHeaders()['Authorization']).to.equal(`Bearer ${token}`); - } + strictEqual(requestContext.getHeaders()?.['Authorization'], `Bearer ${token}`); }); }); diff --git a/src/health_test.ts b/src/health_test.ts index 293142107f..8684f9dfeb 100644 --- a/src/health_test.ts +++ b/src/health_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { rejects, strictEqual } from 'node:assert'; import nock from 'nock'; import { KubeConfig } from './config.js'; @@ -10,7 +10,7 @@ describe('Health', () => { it('should throw an error if no current active cluster', async () => { const kc = new KubeConfig(); const health = new Health(kc); - await expect(health.livez({})).to.be.rejectedWith('No currently active cluster'); + await rejects(health.livez({}), { message: 'No currently active cluster' }); }); it('should return true if /livez returns with status 200', async () => { @@ -30,7 +30,7 @@ describe('Health', () => { const health = new Health(kc); const r = await health.livez({}); - expect(r).to.be.true; + strictEqual(r, true); scope.done(); }); @@ -51,7 +51,7 @@ describe('Health', () => { const health = new Health(kc); const r = await health.livez({}); - expect(r).to.be.false; + strictEqual(r, false); scope.done(); }); @@ -74,7 +74,7 @@ describe('Health', () => { const health = new Health(kc); const r = await health.livez({}); - expect(r).to.be.true; + strictEqual(r, true); scope.done(); }); @@ -97,7 +97,7 @@ describe('Health', () => { const health = new Health(kc); const r = await health.livez({}); - expect(r).to.be.false; + strictEqual(r, false); scope.done(); }); @@ -120,7 +120,7 @@ describe('Health', () => { const health = new Health(kc); const r = await health.livez({}); - expect(r).to.be.true; + strictEqual(r, true); scope.done(); }); @@ -141,7 +141,7 @@ describe('Health', () => { scope.get('/livez').replyWithError(new Error('an error')); const health = new Health(kc); - await expect(health.livez({})).to.be.rejectedWith('Error occurred in health request'); + await rejects(health.livez({}), { message: 'Error occurred in health request' }); scope.done(); }); }); diff --git a/src/integration_test.ts b/src/integration_test.ts index fc8b589f1d..9749c75dc3 100644 --- a/src/integration_test.ts +++ b/src/integration_test.ts @@ -1,16 +1,13 @@ -import { expect, use } from 'chai'; -import chaiAsPromised from 'chai-as-promised'; +import { deepEqual } from 'node:assert'; import nock from 'nock'; import { CoreV1Api } from './api.js'; import { KubeConfig } from './config.js'; import { Cluster, User } from './config_types.js'; -use(chaiAsPromised); - describe('FullRequest', () => { describe('getPods', () => { - it('should get pods successfully', () => { + it('should get pods successfully', async () => { const kc = new KubeConfig(); const cluster = { name: 'foo', @@ -41,9 +38,9 @@ describe('FullRequest', () => { .get('/api/v1/namespaces/default/pods') .reply(200, result); - const promise = k8sApi.listNamespacedPod({ namespace: 'default' }); + const list = await k8sApi.listNamespacedPod({ namespace: 'default' }); - return expect(promise).to.eventually.deep.equals(result); + return deepEqual(list, result); }); }); }); diff --git a/src/log_test.ts b/src/log_test.ts index a55898453b..ef5862aaf7 100644 --- a/src/log_test.ts +++ b/src/log_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { strictEqual, throws } from 'node:assert'; import { AddOptionsToSearchParams, LogOptions } from './log.js'; describe('Log', () => { @@ -15,28 +15,28 @@ describe('Log', () => { timestamps: true, }; AddOptionsToSearchParams(options, searchParams); - expect(searchParams.get('follow')).to.equal('true'); - expect(searchParams.get('limitBytes')).to.equal('100'); - expect(searchParams.get('pretty')).to.equal('true'); - expect(searchParams.get('previous')).to.equal('true'); - expect(searchParams.get('sinceSeconds')).to.equal('1'); - expect(searchParams.get('tailLines')).to.equal('1'); - expect(searchParams.get('timestamps')).to.equal('true'); + strictEqual(searchParams.get('follow'), 'true'); + strictEqual(searchParams.get('limitBytes'), '100'); + strictEqual(searchParams.get('pretty'), 'true'); + strictEqual(searchParams.get('previous'), 'true'); + strictEqual(searchParams.get('sinceSeconds'), '1'); + strictEqual(searchParams.get('tailLines'), '1'); + strictEqual(searchParams.get('timestamps'), 'true'); const sinceTime = new Date().toISOString(); searchParams = new URLSearchParams(); options = { sinceTime }; AddOptionsToSearchParams(options, searchParams); - expect(searchParams.get('sinceTime')).to.equal(sinceTime); + strictEqual(searchParams.get('sinceTime'), sinceTime); }); it('should use defaults for', () => { const searchParams = new URLSearchParams(); const options: LogOptions = {}; AddOptionsToSearchParams(options, searchParams); - expect(searchParams.get('follow')).to.equal('false'); - expect(searchParams.get('pretty')).to.equal('false'); - expect(searchParams.get('previous')).to.equal('false'); - expect(searchParams.get('timestamps')).to.equal('false'); + strictEqual(searchParams.get('follow'), 'false'); + strictEqual(searchParams.get('pretty'), 'false'); + strictEqual(searchParams.get('previous'), 'false'); + strictEqual(searchParams.get('timestamps'), 'false'); }); it('sinceTime and sinceSeconds cannot be used together', () => { const searchParams = new URLSearchParams(); @@ -45,9 +45,9 @@ describe('Log', () => { sinceSeconds: 1, sinceTime, }; - expect(() => { + throws(() => { AddOptionsToSearchParams(options, searchParams); - }).to.throw('at most one of sinceTime or sinceSeconds may be specified'); + }, /at most one of sinceTime or sinceSeconds may be specified/); }); }); }); diff --git a/src/metrics_test.ts b/src/metrics_test.ts index c7abf51946..cd5ef9a982 100644 --- a/src/metrics_test.ts +++ b/src/metrics_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { deepStrictEqual, ok, match, rejects, strictEqual } from 'node:assert'; import nock from 'nock'; import { KubeConfig } from './config.js'; import { V1Status, ApiException } from './gen/index.js'; @@ -97,7 +97,7 @@ describe('Metrics', () => { const s = scope.get('/apis/metrics.k8s.io/v1beta1/pods').reply(200, emptyPodMetrics); const response = await metricsClient.getPodMetrics(); - expect(response).to.deep.equal(emptyPodMetrics); + deepStrictEqual(response, emptyPodMetrics); s.done(); }); it('should return cluster scope empty pods list when namespace is empty string', async () => { @@ -105,7 +105,7 @@ describe('Metrics', () => { const s = scope.get('/apis/metrics.k8s.io/v1beta1/pods').reply(200, emptyPodMetrics); const response = await metricsClient.getPodMetrics(''); - expect(response).to.deep.equal(emptyPodMetrics); + deepStrictEqual(response, emptyPodMetrics); s.done(); }); it('should return namespace scope empty pods list', async () => { @@ -115,7 +115,7 @@ describe('Metrics', () => { .reply(200, emptyPodMetrics); const response = await metricsClient.getPodMetrics(TEST_NAMESPACE); - expect(response).to.deep.equal(emptyPodMetrics); + deepStrictEqual(response, emptyPodMetrics); s.done(); }); it('should return cluster scope pods metrics list', async () => { @@ -123,7 +123,7 @@ describe('Metrics', () => { const s = scope.get('/apis/metrics.k8s.io/v1beta1/pods').reply(200, mockedPodMetrics); const response = await metricsClient.getPodMetrics(); - expect(response).to.deep.equal(mockedPodMetrics); + deepStrictEqual(response, mockedPodMetrics); s.done(); }); @@ -134,7 +134,7 @@ describe('Metrics', () => { .reply(200, mockedPodMetrics); const response = await metricsClient.getPodMetrics(TEST_NAMESPACE); - expect(response).to.deep.equal(mockedPodMetrics); + deepStrictEqual(response, mockedPodMetrics); s.done(); }); it('should when connection refused', async () => { @@ -146,10 +146,11 @@ describe('Metrics', () => { currentContext: 'currentContext', }); const metricsClient = new Metrics(kc); - await expect(metricsClient.getPodMetrics()).to.be.rejectedWith( - ApiException, - 'connect ECONNREFUSED 127.0.0.1:51011', - ); + await rejects(metricsClient.getPodMetrics(), (err) => { + ok(err instanceof ApiException); + match(err.message, /connect ECONNREFUSED 127.0.0.1:51011/); + return true; + }); }); it('should throw when no current cluster', async () => { const [metricsClient, scope] = systemUnderTest({ @@ -157,10 +158,10 @@ describe('Metrics', () => { users: [{ name: 'user', password: 'password' }], contexts: [{ name: 'currentContext', cluster: 'cluster', user: 'user' }], }); - await expect(metricsClient.getPodMetrics()).to.be.rejectedWith( - Error, - 'No currently active cluster', - ); + await rejects(metricsClient.getPodMetrics(), { + name: 'Error', + message: 'No currently active cluster', + }); scope.done(); }); it('should resolve to error when 500 - V1 Status', async () => { @@ -171,10 +172,11 @@ describe('Metrics', () => { const [metricsClient, scope] = systemUnderTest(); const s = scope.get('/apis/metrics.k8s.io/v1beta1/pods').reply(500, response); - await expect(metricsClient.getPodMetrics()).to.be.rejected.then((e) => { - expect(e).to.be.an.instanceOf(ApiException); - expect(e.code).to.equal(response.code); - expect(e.body.message).to.equal(response.message); + await rejects(metricsClient.getPodMetrics(), (e) => { + ok(e instanceof ApiException); + strictEqual(e.code, response.code); + strictEqual(e.body.message, response.message); + return true; }); s.done(); }); @@ -183,10 +185,11 @@ describe('Metrics', () => { const [metricsClient, scope] = systemUnderTest(); const s = scope.get('/apis/metrics.k8s.io/v1beta1/pods').reply(500, response); - await expect(metricsClient.getPodMetrics()).to.be.rejected.then((e) => { - expect(e).to.be.an.instanceOf(ApiException); - expect(e.code).to.equal(500); - expect(e.message).to.include('Error occurred in metrics request'); + await rejects(metricsClient.getPodMetrics(), (e) => { + ok(e instanceof ApiException); + strictEqual(e.code, 500); + match(e.message, /Error occurred in metrics request/); + return true; }); s.done(); }); @@ -197,7 +200,7 @@ describe('Metrics', () => { const s = scope.get('/apis/metrics.k8s.io/v1beta1/nodes').reply(200, emptyNodeMetrics); const response = await metricsClient.getNodeMetrics(); - expect(response).to.deep.equal(emptyNodeMetrics); + deepStrictEqual(response, emptyNodeMetrics); s.done(); }); it('should return nodes metrics list', async () => { @@ -205,7 +208,7 @@ describe('Metrics', () => { const s = scope.get('/apis/metrics.k8s.io/v1beta1/nodes').reply(200, mockedNodeMetrics); const response = await metricsClient.getNodeMetrics(); - expect(response).to.deep.equal(mockedNodeMetrics); + deepStrictEqual(response, mockedNodeMetrics); s.done(); }); @@ -217,10 +220,11 @@ describe('Metrics', () => { const [metricsClient, scope] = systemUnderTest(); const s = scope.get('/apis/metrics.k8s.io/v1beta1/nodes').reply(500, response); - await expect(metricsClient.getNodeMetrics()).to.be.rejected.then((e) => { - expect(e).to.be.an.instanceOf(ApiException); - expect(e.code).to.equal(response.code); - expect(e.body.message).to.equal(response.message); + await rejects(metricsClient.getNodeMetrics(), (e) => { + ok(e instanceof ApiException); + strictEqual(e.code, response.code); + strictEqual(e.body.message, response.message); + return true; }); s.done(); }); diff --git a/src/object_test.ts b/src/object_test.ts index f5f7ad542b..1da88931db 100644 --- a/src/object_test.ts +++ b/src/object_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { deepStrictEqual, ok, rejects, strictEqual } from 'node:assert'; import nock from 'nock'; import { Configuration, V1APIResource, V1APIResourceList, V1Secret } from './api.js'; import { KubeConfig } from './config.js'; @@ -19,8 +19,7 @@ describe('KubernetesObject', () => { const kc = new KubeConfig(); kc.loadFromOptions(testConfigOptions); const c = KubernetesObjectApi.makeApiClient(kc); - expect(c).to.be.ok; - expect((c as any).defaultNamespace).to.equal('default'); + strictEqual((c as any).defaultNamespace, 'default'); }); it('should set the default namespace from context', () => { @@ -32,8 +31,7 @@ describe('KubernetesObject', () => { currentContext: 'dischord', }); const c = KubernetesObjectApi.makeApiClient(kc); - expect(c).to.be.ok; - expect((c as any).defaultNamespace).to.equal('straight-edge'); + strictEqual((c as any).defaultNamespace, 'straight-edge'); }); }); @@ -492,7 +490,7 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const r = await c.specUriPath(o, 'patch'); - expect(r).to.equal('/api/v1/namespaces/fugazi/services/repeater'); + strictEqual(r, '/api/v1/namespaces/fugazi/services/repeater'); scope.done(); }); @@ -509,7 +507,7 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const r = await c.specUriPath(o, 'patch'); - expect(r).to.equal('/api/v1/namespaces/fugazi/serviceaccounts/repeater'); + strictEqual(r, '/api/v1/namespaces/fugazi/serviceaccounts/repeater'); scope.done(); }); @@ -533,7 +531,7 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const r = await c.specUriPath(o, 'patch'); - expect(r).to.equal('/api/v1/namespaces/straight-edge/pods/repeater'); + strictEqual(r, '/api/v1/namespaces/straight-edge/pods/repeater'); scope.done(); }); @@ -557,7 +555,7 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const r = await c.specUriPath(o, 'patch'); - expect(r).to.equal('/api/v1/namespaces/default/pods/repeater'); + strictEqual(r, '/api/v1/namespaces/default/pods/repeater'); scope.done(); }); @@ -574,7 +572,7 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const r = await c.specUriPath(o, 'delete'); - expect(r).to.equal('/api/v1/namespaces/repeater'); + strictEqual(r, '/api/v1/namespaces/repeater'); scope.done(); }); @@ -591,7 +589,7 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const r = await c.specUriPath(o, 'create'); - expect(r).to.equal('/api/v1/namespaces/fugazi/services'); + strictEqual(r, '/api/v1/namespaces/fugazi/services'); scope.done(); }); @@ -608,7 +606,7 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const r = await c.specUriPath(o, 'create'); - expect(r).to.equal('/api/v1/namespaces'); + strictEqual(r, '/api/v1/namespaces'); scope.done(); }); @@ -626,7 +624,7 @@ describe('KubernetesObject', () => { .get('/apis/apps/v1') .reply(200, resourceBodies.apps, contentTypeJsonHeader); const r = await c.specUriPath(o, 'read'); - expect(r).to.equal('/apis/apps/v1/namespaces/fugazi/deployments/repeater'); + strictEqual(r, '/apis/apps/v1/namespaces/fugazi/deployments/repeater'); scope.done(); }); @@ -643,7 +641,7 @@ describe('KubernetesObject', () => { .get('/apis/rbac.authorization.k8s.io/v1') .reply(200, resourceBodies.rbac, contentTypeJsonHeader); const r = await c.specUriPath(o, 'read'); - expect(r).to.equal('/apis/rbac.authorization.k8s.io/v1/clusterroles/repeater'); + strictEqual(r, '/apis/rbac.authorization.k8s.io/v1/clusterroles/repeater'); scope.done(); }); @@ -761,7 +759,7 @@ describe('KubernetesObject', () => { } const scope = nock('https://d.i.y').get(k.p).reply(200, k.b, contentTypeJsonHeader); const r = await c.specUriPath(o, 'patch'); - expect(r).to.equal(k.e); + strictEqual(r, k.e); scope.done(); } }); @@ -876,7 +874,7 @@ describe('KubernetesObject', () => { } const scope = nock('https://d.i.y').get(k.p).reply(200, k.b, contentTypeJsonHeader); const r = await c.specUriPath(o, 'create'); - expect(r).to.equal(k.e); + strictEqual(r, k.e); scope.done(); } }); @@ -890,10 +888,10 @@ describe('KubernetesObject', () => { namespace: 'fugazi', }, }; - await expect(c.specUriPath(o, 'create')).to.be.rejectedWith( - Error, - 'Required spec property kind is not set', - ); + await rejects(c.specUriPath(o, 'create'), { + name: 'Error', + message: 'Required spec property kind is not set', + }); }); it('should throw an error if name required and missing', async () => { @@ -909,10 +907,10 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); - await expect(c.specUriPath(o, 'read')).to.be.rejectedWith( - Error, - 'Required spec property name is not set', - ); + await rejects(c.specUriPath(o, 'read'), { + name: 'Error', + message: 'Required spec property name is not set', + }); scope.done(); }); @@ -929,10 +927,11 @@ describe('KubernetesObject', () => { const scope = nock('https://d.i.y') .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); - await expect(c.specUriPath(o, 'create')).to.be.rejectedWith( - Error, - 'Unrecognized API version and kind: v1 Ingress', - ); + + await rejects(c.specUriPath(o, 'create'), { + name: 'Error', + message: 'Unrecognized API version and kind: v1 Ingress', + }); scope.done(); }); }); @@ -945,19 +944,19 @@ describe('KubernetesObject', () => { it('should throw an error if apiVersion not set', async () => { for (const a of [null, undefined]) { - await expect(client.resource(a as unknown as string, 'Service')).to.be.rejectedWith( - Error, - 'Required parameter apiVersion was null or undefined when calling resource', - ); + await rejects(client.resource(a as unknown as string, 'Service'), { + name: 'Error', + message: 'Required parameter apiVersion was null or undefined when calling resource', + }); } }); it('should throw an error if kind not set', async () => { for (const a of [null, undefined]) { - await expect(client.resource('v1', a as unknown as string)).to.be.rejectedWith( - Error, - 'Required parameter kind was null or undefined when calling resource', - ); + await rejects(client.resource('v1', a as unknown as string), { + name: 'Error', + message: 'Required parameter kind was null or undefined when calling resource', + }); } }); @@ -981,8 +980,8 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); await c.resource('v1', 'Service'); - expect(preMiddlewareCalled).to.be.true; - expect(postMiddlewareCalled).to.be.true; + strictEqual(preMiddlewareCalled, true); + strictEqual(postMiddlewareCalled, true); scope.done(); }); @@ -992,39 +991,35 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const s = await c.resource('v1', 'Service'); - expect(s).to.be.ok; if (!s) { throw new Error('old TypeScript compiler'); } - expect(s.kind).to.equal('Service'); - expect(s.name).to.equal('services'); - expect(s.namespaced).to.be.true; - expect(c.apiVersionResourceCache).to.be.ok; - expect(c.apiVersionResourceCache.v1).to.be.ok; + strictEqual(s.kind, 'Service'); + strictEqual(s.name, 'services'); + strictEqual(s.namespaced, true); + ok(c.apiVersionResourceCache); + ok(c.apiVersionResourceCache.v1); const sa = await c.resource('v1', 'ServiceAccount'); - expect(sa).to.be.ok; if (!sa) { throw new Error('old TypeScript compiler'); } - expect(sa.kind).to.equal('ServiceAccount'); - expect(sa.name).to.equal('serviceaccounts'); - expect(sa.namespaced).to.be.true; + strictEqual(sa.kind, 'ServiceAccount'); + strictEqual(sa.name, 'serviceaccounts'); + strictEqual(sa.namespaced, true); const p = await c.resource('v1', 'Pod'); if (!p) { throw new Error('old TypeScript compiler'); } - expect(p).to.be.ok; - expect(p.kind).to.equal('Pod'); - expect(p.name).to.equal('pods'); - expect(p.namespaced).to.be.true; + strictEqual(p.kind, 'Pod'); + strictEqual(p.name, 'pods'); + strictEqual(p.namespaced, true); const pv = await c.resource('v1', 'PersistentVolume'); if (!pv) { throw new Error('old TypeScript compiler'); } - expect(pv).to.be.ok; - expect(pv.kind).to.equal('PersistentVolume'); - expect(pv.name).to.equal('persistentvolumes'); - expect(pv.namespaced).to.be.false; + strictEqual(pv.kind, 'PersistentVolume'); + strictEqual(pv.name, 'persistentvolumes'); + strictEqual(pv.namespaced, false); scope.done(); }); @@ -1050,16 +1045,16 @@ describe('KubernetesObject', () => { .get('/api/v1') .reply(200, resourceBodies.core, contentTypeJsonHeader); const s = await c.resource('v1', 'Service'); - expect(s).to.be.ok; if (!s) { throw new Error('old TypeScript compiler'); } - expect(s.kind).to.equal('Service'); - expect(s.name).to.equal('services'); - expect(s.namespaced).to.be.true; - expect(c.apiVersionResourceCache).to.be.ok; - expect(c.apiVersionResourceCache.v1).to.be.ok; - expect(c.apiVersionResourceCache.v1.resources.length).to.deep.equal( + strictEqual(s.kind, 'Service'); + strictEqual(s.name, 'services'); + strictEqual(s.namespaced, true); + ok(c.apiVersionResourceCache); + ok(c.apiVersionResourceCache.v1); + strictEqual( + c.apiVersionResourceCache.v1.resources.length, JSON.parse(resourceBodies.core).resources.length, ); scope.done(); @@ -1678,9 +1673,10 @@ describe('KubernetesObject', () => { const c = await client.create(s, undefined, undefined, 'ManageField'); (c.metadata.annotations as Record).test = '1'; const r = await client.replace(c, 'true'); - expect((r.metadata.annotations as Record).test).to.equal('1'); - expect(parseInt((r.metadata as any).resourceVersion, 10)).to.be.greaterThan( - parseInt((c.metadata as any).resourceVersion, 10), + strictEqual((r.metadata.annotations as Record).test, '1'); + ok( + parseInt((r.metadata as any).resourceVersion, 10) > + parseInt((c.metadata as any).resourceVersion, 10), ); await client.delete(s, undefined, undefined, 7, undefined, 'Foreground'); scope.done(); @@ -1714,12 +1710,12 @@ describe('KubernetesObject', () => { namespace: 'default', }, }); - expect(secret).to.be.instanceof(V1Secret); - expect(secret.data).to.deep.equal({ + strictEqual(secret instanceof V1Secret, true); + deepStrictEqual(secret.data, { key: 'value', }); - expect(secret.metadata).to.be.ok; - expect(secret.metadata!.creationTimestamp).to.deep.equal(new Date('2022-01-01T00:00:00.000Z')); + ok(secret.metadata); + deepStrictEqual(secret.metadata!.creationTimestamp, new Date('2022-01-01T00:00:00.000Z')); scope.done(); }); @@ -1767,11 +1763,11 @@ describe('KubernetesObject', () => { namespace: 'default', }, }); - expect(custom.spec).to.deep.equal({ + deepStrictEqual(custom.spec, { key: 'value', }); - expect(custom.metadata).to.be.ok; - expect(custom.metadata!.creationTimestamp).to.deep.equal(new Date('2022-01-01T00:00:00.000Z')); + ok(custom.metadata); + deepStrictEqual(custom.metadata!.creationTimestamp, new Date('2022-01-01T00:00:00.000Z')); scope.done(); }); @@ -1802,8 +1798,8 @@ describe('KubernetesObject', () => { ); const lr = await client.list('v1', 'Secret', 'default'); const items = lr.items; - expect(items).to.have.length(1); - expect(items[0]).to.be.instanceof(V1Secret); + strictEqual(items.length, 1); + strictEqual(items[0] instanceof V1Secret, true); scope.done(); }); @@ -1846,7 +1842,7 @@ describe('KubernetesObject', () => { 5, ); const items = lr.items; - expect(items).to.have.length(1); + strictEqual(items.length, 1); scope.done(); }); }); @@ -1865,10 +1861,10 @@ describe('KubernetesObject', () => { for (const m of methods) { // TODO: Figure out why Typescript barfs if we do m.call const hack_m = m as any; - await expect(hack_m.call(client, s)).to.be.rejectedWith( - Error, - 'Required parameter spec was null or undefined when calling ', - ); + await rejects(hack_m.call(client, s), { + name: 'Error', + message: /Required parameter spec was null or undefined when calling /, + }); } } }); @@ -1895,7 +1891,10 @@ describe('KubernetesObject', () => { }, }; nock('https://d.i.y'); - await expect(client.read(s)).to.be.rejectedWith(Error, 'Nock: No match for request'); + await rejects(client.read(s), { + code: 'ERR_NOCK_NO_MATCH', + message: /Nock: No match for request/, + }); }); it('should throw an error if name not valid', async () => { @@ -1948,9 +1947,9 @@ describe('KubernetesObject', () => { contentTypeJsonHeader, ); - await expect(client.create(s)).to.be.rejected.then((e) => { - expect(e).to.be.an.instanceOf(Error); - expect(e.code).to.equal(422); + await rejects(client.create(s), { + name: 'Error', + code: 422, }); scope.done(); }); @@ -1992,28 +1991,26 @@ describe('KubernetesObject', () => { const scope = nock('https://d.i.y') .get('/apis/applications/v1') .reply(404, '{}', contentTypeJsonHeader); - await expect(client.create(d)).to.be.rejected.then((e) => { - expect(e).to.be.an.instanceOf(Error); - expect(e.code).to.equal(404); - expect(e.message).to.contain( - 'Failed to fetch resource metadata for applications/v1/Deployment', - ); + await rejects(client.create(d), { + name: 'Error', + code: 404, + message: /Failed to fetch resource metadata for applications\/v1\/Deployment/, }); scope.done(); }); it('should throw error if no apiVersion', async () => { - await expect((client.list as any)(undefined, undefined)).to.be.rejectedWith( - Error, - 'Required parameter apiVersion was null or undefined when calling ', - ); + await rejects((client.list as any)(undefined, undefined), { + name: 'Error', + message: 'Required parameter apiVersion was null or undefined when calling list.', + }); }); it('should throw error if no kind', async () => { - await expect((client.list as any)('', undefined)).to.be.rejectedWith( - Error, - 'Required parameter kind was null or undefined when calling ', - ); + await rejects((client.list as any)('', undefined), { + name: 'Error', + message: 'Required parameter kind was null or undefined when calling list.', + }); }); }); }); diff --git a/src/oidc_auth_test.ts b/src/oidc_auth_test.ts index bca567b9c2..07891aa836 100644 --- a/src/oidc_auth_test.ts +++ b/src/oidc_auth_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { notStrictEqual, strictEqual } from 'node:assert'; import { OutgoingHttpHeaders } from 'node:http'; import https from 'node:https'; import { base64url } from 'rfc4648'; @@ -24,7 +24,7 @@ describe('OIDCAuth', () => { const jwt = OpenIDConnectAuth.decodeJWT( 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.5mhBHqs5_DTLdINd9p5m7ZJ6XD0Xc55kIaCRY5r6HRA', ); - expect(jwt).to.not.be.null; + notStrictEqual(jwt, null); }); it('should correctly parse time from token', () => { @@ -32,7 +32,7 @@ describe('OIDCAuth', () => { const token = makeJWT('{}', { exp: time }, 'fake'); const timeOut = OpenIDConnectAuth.expirationFromToken(token); - expect(timeOut).to.equal(time); + strictEqual(timeOut, time); }); it('should be true for oidc user', () => { @@ -42,7 +42,7 @@ describe('OIDCAuth', () => { }, } as User; - expect(auth.isAuthProvider(user)).to.equal(true); + strictEqual(auth.isAuthProvider(user), true); }); it('should be false for other user', () => { @@ -52,13 +52,13 @@ describe('OIDCAuth', () => { }, } as User; - expect(auth.isAuthProvider(user)).to.equal(false); + strictEqual(auth.isAuthProvider(user), false); }); it('should be false for null user.authProvider', () => { const user = {} as User; - expect(auth.isAuthProvider(user)).to.equal(false); + strictEqual(auth.isAuthProvider(user), false); }); it('authorization should be undefined if token missing', async () => { @@ -77,7 +77,7 @@ describe('OIDCAuth', () => { const opts = {} as https.RequestOptions; opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.be.undefined; + strictEqual(opts.headers.Authorization, undefined); }); it('authorization should be undefined if client-id missing', async () => { @@ -98,7 +98,7 @@ describe('OIDCAuth', () => { const opts = {} as https.RequestOptions; opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.be.undefined; + strictEqual(opts.headers.Authorization, undefined); }); it('authorization should be work if client-secret missing', async () => { @@ -118,7 +118,7 @@ describe('OIDCAuth', () => { opts.headers = {} as OutgoingHttpHeaders; (auth as any).currentTokenExpiration = Date.now() / 1000 + 1000; await auth.applyAuthentication(user, opts, {}); - expect(opts.headers.Authorization).to.equal('Bearer fakeToken'); + strictEqual(opts.headers.Authorization, 'Bearer fakeToken'); }); it('authorization should be undefined if refresh-token missing', async () => { @@ -139,7 +139,7 @@ describe('OIDCAuth', () => { const opts = {} as https.RequestOptions; opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.be.undefined; + strictEqual(opts.headers.Authorization, undefined); }); it('authorization should work if refresh-token missing but token is unexpired', async () => { @@ -160,7 +160,7 @@ describe('OIDCAuth', () => { const opts = {} as https.RequestOptions; opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts); - expect(opts.headers.Authorization).to.equal(`Bearer ${token}`); + strictEqual(opts.headers.Authorization, `Bearer ${token}`); }); it('authorization should be undefined if idp-issuer-url missing', async () => { @@ -181,7 +181,7 @@ describe('OIDCAuth', () => { const opts = {} as https.RequestOptions; opts.headers = {} as OutgoingHttpHeaders; await auth.applyAuthentication(user, opts, {}); - expect(opts.headers.Authorization).to.be.undefined; + strictEqual(opts.headers.Authorization, undefined); }); it('return token when it is still active', async () => { @@ -202,7 +202,7 @@ describe('OIDCAuth', () => { opts.headers = {} as OutgoingHttpHeaders; (auth as any).currentTokenExpiration = Date.now() / 1000 + 1000; await auth.applyAuthentication(user, opts, {}); - expect(opts.headers.Authorization).to.equal('Bearer fakeToken'); + strictEqual(opts.headers.Authorization, 'Bearer fakeToken'); }); it('return new token when the current expired', async () => { @@ -232,10 +232,10 @@ describe('OIDCAuth', () => { }; }, }); - expect(opts.headers.Authorization).to.equal('Bearer newToken'); - expect((auth as any).currentTokenExpiration).to.equal(newExpiration); + strictEqual(opts.headers.Authorization, 'Bearer newToken'); + strictEqual((auth as any).currentTokenExpiration, newExpiration); // Check also the new refresh token sticks in the user config - expect(user.authProvider.config['refresh-token']).to.equal('newRefreshToken'); + strictEqual(user.authProvider.config['refresh-token'], 'newRefreshToken'); }); it('return a new token when the its the first time we see this user', async () => { @@ -264,7 +264,7 @@ describe('OIDCAuth', () => { }; }, }); - expect(opts.headers.Authorization).to.equal('Bearer newToken'); - expect((auth as any).currentTokenExpiration).to.equal(newExpiration); + strictEqual(opts.headers.Authorization, 'Bearer newToken'); + strictEqual((auth as any).currentTokenExpiration, newExpiration); }); }); diff --git a/src/package_test.ts b/src/package_test.ts index e5171d87fa..0e5c589717 100644 --- a/src/package_test.ts +++ b/src/package_test.ts @@ -1,5 +1,5 @@ +import { strictEqual } from 'node:assert'; import { createRequire } from 'node:module'; -import { expect } from 'chai'; const require = createRequire(import.meta.url); // Generic set of tests to verify the package is built and configured correctly @@ -7,10 +7,10 @@ describe('package', () => { it('package-lock.json should match package.json', () => { const v1 = require('../package.json').version; const v2 = require('../package-lock.json').version; - expect(v1).to.equal(v2); + strictEqual(v1, v2); const v3 = require('../package-lock.json').packages[''].version; - expect(v1).to.equal(v3); + strictEqual(v1, v3); }); it('package-lock should only reference npm', () => { @@ -21,8 +21,8 @@ describe('package', () => { for (const key in deps.dependencies) { const dep = deps.dependencies[key]; const resolved = new URL(dep.resolved); - expect(resolved.hostname).to.equal('registry.npmjs.org'); - expect(resolved.protocol).to.equal('https:'); + strictEqual(resolved.hostname, 'registry.npmjs.org'); + strictEqual(resolved.protocol, 'https:'); validateDependencies(dep); } }; diff --git a/src/portforward_test.ts b/src/portforward_test.ts index d3f843192c..fc6ecad80e 100644 --- a/src/portforward_test.ts +++ b/src/portforward_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { strictEqual, rejects } from 'node:assert'; import { ReadableStreamBuffer, WritableStreamBuffer } from 'stream-buffers'; import { anyFunction, capture, instance, mock, verify } from 'ts-mockito'; @@ -36,7 +36,7 @@ describe('PortForward', () => { const [, , outputFn] = capture(fakeWebSocket.connect).last(); - expect(outputFn).to.not.be.null; + strictEqual(typeof outputFn, 'function'); // this is redundant but needed for the compiler, sigh... if (!outputFn) { return; @@ -48,7 +48,7 @@ describe('PortForward', () => { outputFn(0, buffer); // first time, drop two bytes for the port number. - expect(osStream.size()).to.equal(1022); + strictEqual(osStream.size(), 1022); }); it('should correctly port-forward streams if err is null', async () => { @@ -62,7 +62,7 @@ describe('PortForward', () => { const [, , outputFn] = capture(fakeWebSocket.connect).last(); - expect(outputFn).to.not.be.null; + strictEqual(typeof outputFn, 'function'); // this is redundant but needed for the compiler, sigh... if (!outputFn) { return; @@ -72,7 +72,7 @@ describe('PortForward', () => { // error stream, drop two bytes for the port number. outputFn(1, buffer); // error stream is null, expect output to be dropped and nothing to change. - expect(osStream.size()).to.equal(0); + strictEqual(osStream.size(), 0); }); it('should correctly port-forward streams', async () => { @@ -87,7 +87,7 @@ describe('PortForward', () => { const [, , outputFn] = capture(fakeWebSocket.connect).last(); - expect(outputFn).to.not.be.null; + strictEqual(typeof outputFn, 'function'); // this is redundant but needed for the compiler, sigh... if (!outputFn) { return; @@ -96,22 +96,22 @@ describe('PortForward', () => { outputFn(0, buffer); // first time, drop two bytes for the port number. - expect(osStream.size()).to.equal(1022); + strictEqual(osStream.size(), 1022); outputFn(0, buffer); - expect(osStream.size()).to.equal(2046); + strictEqual(osStream.size(), 2046); // error stream, drop two bytes for the port number. outputFn(1, buffer); - expect(errStream.size()).to.equal(1022); + strictEqual(errStream.size(), 1022); outputFn(1, buffer); - expect(errStream.size()).to.equal(2046); + strictEqual(errStream.size(), 2046); // unknown stream, shouldn't change anything. outputFn(2, buffer); - expect(osStream.size()).to.equal(2046); - expect(errStream.size()).to.equal(2046); + strictEqual(osStream.size(), 2046); + strictEqual(errStream.size(), 2046); }); it('should throw with no ports or too many', async () => { @@ -120,11 +120,13 @@ describe('PortForward', () => { const osStream = new WritableStreamBuffer(); const isStream = new ReadableStreamBuffer(); - await expect( - portForward.portForward('ns', 'pod', [], osStream, osStream, isStream), - ).to.be.rejectedWith(Error, 'You must provide at least one port to forward to.'); - await expect( - portForward.portForward('ns', 'pod', [1, 2], osStream, osStream, isStream), - ).to.be.rejectedWith(Error, 'Only one port is currently supported for port-forward'); + await rejects(portForward.portForward('ns', 'pod', [], osStream, osStream, isStream), { + name: 'Error', + message: 'You must provide at least one port to forward to.', + }); + await rejects(portForward.portForward('ns', 'pod', [1, 2], osStream, osStream, isStream), { + name: 'Error', + message: 'Only one port is currently supported for port-forward', + }); }); }); diff --git a/src/serializer_test.ts b/src/serializer_test.ts index e20ab63ac3..975fe9f9a3 100644 --- a/src/serializer_test.ts +++ b/src/serializer_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { deepEqual, deepStrictEqual } from 'node:assert'; import { ObjectSerializer } from './serializer.js'; describe('ObjectSerializer', () => { @@ -17,7 +17,7 @@ describe('ObjectSerializer', () => { }, }; const res = ObjectSerializer.serialize(s, 'V1Secret'); - expect(res).to.deep.equal({ + deepStrictEqual(res, { apiVersion: 'v1', kind: 'Secret', metadata: { @@ -60,7 +60,7 @@ describe('ObjectSerializer', () => { }, }; const res = ObjectSerializer.serialize(s, 'v1alpha1MyCustomResource'); - expect(res).to.deep.equal({ + deepStrictEqual(res, { apiVersion: 'v1alpha1', kind: 'MyCustomResource', metadata: { @@ -91,7 +91,7 @@ describe('ObjectSerializer', () => { key: 'value', }; const res = ObjectSerializer.serialize(s, 'unknown'); - expect(res).to.deep.equal(s); + deepStrictEqual(res, s); }); }); @@ -110,7 +110,7 @@ describe('ObjectSerializer', () => { }, }; const res = ObjectSerializer.deserialize(s, 'V1Secret'); - expect(res).to.deep.equal({ + deepEqual(res, { apiVersion: 'v1', kind: 'Secret', metadata: { @@ -138,7 +138,7 @@ describe('ObjectSerializer', () => { }, }; const res = ObjectSerializer.deserialize(s, 'v1alpha1MyCustomResource'); - expect(res).to.deep.equal({ + deepEqual(res, { apiVersion: 'v1alpha1', kind: 'MyCustomResource', metadata: { @@ -157,7 +157,7 @@ describe('ObjectSerializer', () => { key: 'value', }; const res = ObjectSerializer.serialize(s, 'unknown'); - expect(res).to.deep.equal(s); + deepStrictEqual(res, s); }); }); }); diff --git a/src/test/match-buffer.ts b/src/test/match-buffer.ts index 63747dabcb..5bb3a2c387 100644 --- a/src/test/match-buffer.ts +++ b/src/test/match-buffer.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { deepStrictEqual, strictEqual } from 'node:assert'; import { RequestOptions, Agent } from 'node:https'; import { Matcher } from 'ts-mockito/lib/matcher/type/Matcher.js'; @@ -56,9 +56,9 @@ export function assertRequestAgentsEqual(agent1: Agent, agent2: Agent): void { throw 'unequal agent key buffer'; } - expect(agent1.options.passphrase).to.equal(agent2.options.passphrase); - expect(agent1.options.pfx).to.equal(agent2.options.pfx); - expect(agent1.options.rejectUnauthorized).to.equal(agent2.options.rejectUnauthorized); + strictEqual(agent1.options.passphrase, agent2.options.passphrase); + strictEqual(agent1.options.pfx, agent2.options.pfx); + strictEqual(agent1.options.rejectUnauthorized, agent2.options.rejectUnauthorized); } export function assertRequestOptionsEqual(options1: RequestOptions, options2: RequestOptions): void { @@ -68,8 +68,8 @@ export function assertRequestOptionsEqual(options1: RequestOptions, options2: Re const agent2: Agent = options2.agent; assertRequestAgentsEqual(agent1, agent2); - expect(options1.auth).to.equal(options2.auth); - expect(options1.headers).to.deep.equal(options2.headers); - expect(options1.rejectUnauthorized).to.equal(options2.rejectUnauthorized); - expect(options1.servername).to.equal(options2.servername); + strictEqual(options1.auth, options2.auth); + deepStrictEqual(options1.headers, options2.headers); + strictEqual(options1.rejectUnauthorized, options2.rejectUnauthorized); + strictEqual(options1.servername, options2.servername); } diff --git a/src/top_test.ts b/src/top_test.ts index 5a6d3b6497..e149d723b7 100644 --- a/src/top_test.ts +++ b/src/top_test.ts @@ -1,8 +1,8 @@ -import { expect } from 'chai'; +import { deepEqual, deepStrictEqual, strictEqual } from 'assert'; import nock from 'nock'; import { KubeConfig } from './config.js'; import { Metrics, PodMetricsList } from './metrics.js'; -import { topPods } from './top.js'; +import { CurrentResourceUsage, topPods } from './top.js'; import { CoreV1Api, V1Pod } from './api.js'; const emptyPodMetrics: PodMetricsList = { @@ -155,7 +155,7 @@ describe('Top', () => { items: [], }); const result = await topPodsFunc(); - expect(result).to.deep.equal([]); + deepStrictEqual(result, []); podMetrics.done(); pods.done(); }); @@ -166,7 +166,7 @@ describe('Top', () => { items: [], }); const result = await topPodsFunc(); - expect(result).to.deep.equal([]); + deepStrictEqual(result, []); podMetrics.done(); pods.done(); }); @@ -177,18 +177,13 @@ describe('Top', () => { items: podList, }); const result = await topPodsFunc(); - expect(result.length).to.equal(2); - expect(result[0].CPU).to.deep.equal({ - CurrentUsage: 0.05, - LimitTotal: 0.1, - RequestTotal: 0.1, - }); - expect(result[0].Memory).to.deep.equal({ - CurrentUsage: BigInt('4005888'), - RequestTotal: BigInt('104857600'), - LimitTotal: BigInt('104857600'), - }); - expect(result[0].Containers).to.deep.equal([ + strictEqual(result.length, 2); + deepStrictEqual(result[0].CPU, new CurrentResourceUsage(0.05, 0.1, 0.1)); + deepStrictEqual( + result[0].Memory, + new CurrentResourceUsage(BigInt('4005888'), BigInt('104857600'), BigInt('104857600')), + ); + deepEqual(result[0].Containers, [ { CPUUsage: { CurrentUsage: 0.05, @@ -203,17 +198,12 @@ describe('Top', () => { }, }, ]); - expect(result[1].CPU).to.deep.equal({ - CurrentUsage: 1.4, - LimitTotal: 2.1, - RequestTotal: 2.1, - }); - expect(result[1].Memory).to.deep.equal({ - CurrentUsage: BigInt('7192576'), - LimitTotal: BigInt('209715200'), - RequestTotal: BigInt('157286400'), - }); - expect(result[1].Containers).to.deep.equal([ + deepStrictEqual(result[1].CPU, new CurrentResourceUsage(1.4, 2.1, 2.1)); + deepStrictEqual( + result[1].Memory, + new CurrentResourceUsage(BigInt('7192576'), BigInt('157286400'), BigInt('209715200')), + ); + deepEqual(result[1].Containers, [ { CPUUsage: { CurrentUsage: 0, @@ -251,18 +241,10 @@ describe('Top', () => { items: bestEffortPodList, }); const result = await topPodsFunc(); - expect(result.length).to.equal(1); - expect(result[0].CPU).to.deep.equal({ - CurrentUsage: 0.05, - LimitTotal: 0, - RequestTotal: 0, - }); - expect(result[0].Memory).to.deep.equal({ - CurrentUsage: BigInt('4005888'), - RequestTotal: 0, - LimitTotal: 0, - }); - expect(result[0].Containers).to.deep.equal([ + strictEqual(result.length, 1); + deepStrictEqual(result[0].CPU, new CurrentResourceUsage(0.05, 0, 0)); + deepStrictEqual(result[0].Memory, new CurrentResourceUsage(BigInt('4005888'), 0, 0)); + deepEqual(result[0].Containers, [ { CPUUsage: { CurrentUsage: 0.05, @@ -287,29 +269,19 @@ describe('Top', () => { items: podList, }); const result = await topPodsFunc(); - expect(result.length).to.equal(2); - expect(result[0].CPU).to.deep.equal({ - CurrentUsage: 0, - LimitTotal: 0.1, - RequestTotal: 0.1, - }); - expect(result[0].Memory).to.deep.equal({ - CurrentUsage: 0, - RequestTotal: BigInt('104857600'), - LimitTotal: BigInt('104857600'), - }); - expect(result[0].Containers).to.deep.equal([]); - expect(result[1].CPU).to.deep.equal({ - CurrentUsage: 0, - LimitTotal: 2.1, - RequestTotal: 2.1, - }); - expect(result[1].Memory).to.deep.equal({ - CurrentUsage: 0, - LimitTotal: BigInt('209715200'), - RequestTotal: BigInt('157286400'), - }); - expect(result[1].Containers).to.deep.equal([]); + strictEqual(result.length, 2); + deepStrictEqual(result[0].CPU, new CurrentResourceUsage(0, 0.1, 0.1)); + deepStrictEqual( + result[0].Memory, + new CurrentResourceUsage(0, BigInt('104857600'), BigInt('104857600')), + ); + deepStrictEqual(result[0].Containers, []); + deepStrictEqual(result[1].CPU, new CurrentResourceUsage(0, 2.1, 2.1)); + deepStrictEqual( + result[1].Memory, + new CurrentResourceUsage(0, BigInt('157286400'), BigInt('209715200')), + ); + deepStrictEqual(result[1].Containers, []); podMetrics.done(); pods.done(); }); @@ -320,7 +292,7 @@ describe('Top', () => { items: [], }); const result = await topPodsFunc(); - expect(result.length).to.equal(0); + strictEqual(result.length, 0); podMetrics.done(); pods.done(); }); @@ -333,18 +305,13 @@ describe('Top', () => { items: podList, }); const result = await topPodsFunc(); - expect(result.length).to.equal(2); - expect(result[0].CPU).to.deep.equal({ - CurrentUsage: 0.05, - LimitTotal: 0.1, - RequestTotal: 0.1, - }); - expect(result[0].Memory).to.deep.equal({ - CurrentUsage: BigInt('4005888'), - RequestTotal: BigInt('104857600'), - LimitTotal: BigInt('104857600'), - }); - expect(result[0].Containers).to.deep.equal([ + strictEqual(result.length, 2); + deepStrictEqual(result[0].CPU, new CurrentResourceUsage(0.05, 0.1, 0.1)); + deepStrictEqual( + result[0].Memory, + new CurrentResourceUsage(BigInt('4005888'), BigInt('104857600'), BigInt('104857600')), + ); + deepEqual(result[0].Containers, [ { CPUUsage: { CurrentUsage: 0.05, @@ -359,17 +326,12 @@ describe('Top', () => { }, }, ]); - expect(result[1].CPU).to.deep.equal({ - CurrentUsage: 1.4, - LimitTotal: 2.1, - RequestTotal: 2.1, - }); - expect(result[1].Memory).to.deep.equal({ - CurrentUsage: BigInt('7192576'), - LimitTotal: BigInt('209715200'), - RequestTotal: BigInt('157286400'), - }); - expect(result[1].Containers).to.deep.equal([ + deepStrictEqual(result[1].CPU, new CurrentResourceUsage(1.4, 2.1, 2.1)); + deepStrictEqual( + result[1].Memory, + new CurrentResourceUsage(BigInt('7192576'), BigInt('157286400'), BigInt('209715200')), + ); + deepEqual(result[1].Containers, [ { CPUUsage: { CurrentUsage: 0, diff --git a/src/util_test.ts b/src/util_test.ts index 5d98223697..47cb7073af 100644 --- a/src/util_test.ts +++ b/src/util_test.ts @@ -1,4 +1,4 @@ -import { expect, assert } from 'chai'; +import { deepStrictEqual, strictEqual, throws } from 'node:assert'; import { Response } from 'node-fetch'; import { CoreV1Api, V1Container, V1Pod } from './api.js'; import { @@ -24,7 +24,7 @@ describe('Utils', () => { }; const pods = await podsForNode(mockApi as CoreV1Api, 'foo'); - expect(pods.length).to.equal(0); + strictEqual(pods.length, 0); }); it('should only gets for pods named node', async () => { @@ -51,42 +51,41 @@ describe('Utils', () => { }; const pods = await podsForNode(mockApi as CoreV1Api, 'foo'); - expect(pods.length).to.equal(1); - expect(pods[0].spec!.nodeName).to.equal('foo'); + strictEqual(pods.length, 1); + strictEqual(pods[0].spec!.nodeName, 'foo'); }); it('should parse quantities', () => { - expect(quantityToScalar('')).to.equal(0); - - expect(quantityToScalar('2n')).to.equal(2 / 1_000_000_000); - expect(quantityToScalar('3u')).to.equal(3 / 1_000_000); - expect(quantityToScalar('100m')).to.equal(0.1); - expect(quantityToScalar('3k')).to.equal(BigInt(3000)); - expect(quantityToScalar('3M')).to.equal(BigInt(3 * 1000 * 1000)); - expect(quantityToScalar('3G')).to.equal(BigInt(3 * 1000 * 1000 * 1000)); - expect(quantityToScalar('5T')).to.equal(BigInt(5 * 1000 * 1000 * 1000) * BigInt(1000)); - expect(quantityToScalar('3P')).to.equal(BigInt(3 * 1000 * 1000 * 1000) * BigInt(1000 * 1000)); - expect(quantityToScalar('14E')).to.equal( - BigInt(14 * 1000 * 1000 * 1000) * BigInt(1000 * 1000 * 1000), - ); - - expect(quantityToScalar('0.2')).to.equal(0.2); - expect(quantityToScalar('1976m')).to.equal(1.976); - - expect(quantityToScalar('1024')).to.equal(1024); - expect(quantityToScalar('10e3')).to.equal(10000); - - expect(quantityToScalar('10Ki')).to.equal(BigInt(10240)); - expect(quantityToScalar('20Mi')).to.equal(BigInt(1024 * 1024 * 20)); - expect(quantityToScalar('30Gi')).to.equal(BigInt(1024 * 1024 * 1024 * 30)); - expect(quantityToScalar('40Ti')).to.equal(BigInt(1024 * 1024 * 1024 * 1024 * 40)); - expect(quantityToScalar('50Pi')).to.equal(BigInt(1024 * 1024 * 1024 * 1024 * 1024 * 50)); - expect(quantityToScalar('60Ei')).to.equal( - BigInt(1024 * 1024 * 1024) * BigInt(1024 * 1024 * 1024 * 60), - ); - - expect(() => quantityToScalar('foobar')).to.throw('Unknown quantity foobar'); - expect(() => quantityToScalar('100foobar')).to.throw('Unknown suffix: foobar'); + strictEqual(quantityToScalar(''), 0); + strictEqual(quantityToScalar('2n'), 2 / 1_000_000_000); + strictEqual(quantityToScalar('3u'), 3 / 1_000_000); + strictEqual(quantityToScalar('100m'), 0.1); + strictEqual(quantityToScalar('3k'), BigInt(3000)); + strictEqual(quantityToScalar('3M'), BigInt(3 * 1000 * 1000)); + strictEqual(quantityToScalar('3G'), BigInt(3 * 1000 * 1000 * 1000)); + strictEqual(quantityToScalar('5T'), BigInt(5 * 1000 * 1000 * 1000) * BigInt(1000)); + strictEqual(quantityToScalar('3P'), BigInt(3 * 1000 * 1000 * 1000) * BigInt(1000 * 1000)); + strictEqual(quantityToScalar('14E'), BigInt(14 * 1000 * 1000 * 1000) * BigInt(1000 * 1000 * 1000)); + + strictEqual(quantityToScalar('0.2'), 0.2); + strictEqual(quantityToScalar('1976m'), 1.976); + + strictEqual(quantityToScalar('1024'), 1024); + strictEqual(quantityToScalar('10e3'), 10000); + + strictEqual(quantityToScalar('10Ki'), BigInt(10240)); + strictEqual(quantityToScalar('20Mi'), BigInt(1024 * 1024 * 20)); + strictEqual(quantityToScalar('30Gi'), BigInt(1024 * 1024 * 1024 * 30)); + strictEqual(quantityToScalar('40Ti'), BigInt(1024 * 1024 * 1024 * 1024 * 40)); + strictEqual(quantityToScalar('50Pi'), BigInt(1024 * 1024 * 1024 * 1024 * 1024 * 50)); + strictEqual(quantityToScalar('60Ei'), BigInt(1024 * 1024 * 1024) * BigInt(1024 * 1024 * 1024 * 60)); + + throws(() => quantityToScalar('foobar'), { + message: 'Unknown quantity foobar', + }); + throws(() => quantityToScalar('100foobar'), { + message: 'Unknown suffix: foobar', + }); }); it('should get resources for pod', () => { @@ -121,18 +120,18 @@ describe('Utils', () => { } as V1Pod; const cpuResult = totalCPU(pod); - expect(cpuResult.request).to.equal(1.1); - expect(cpuResult.limit).to.equal(0.2); + strictEqual(cpuResult.request, 1.1); + strictEqual(cpuResult.limit, 0.2); const memResult = totalMemory(pod); - expect(memResult.request).to.equal(BigInt(10240)); - expect(memResult.limit).to.equal(BigInt(20480)); + strictEqual(memResult.request, BigInt(10240)); + strictEqual(memResult.limit, BigInt(20480)); }); it('should find the suffix correctly', () => { - expect(findSuffix('1234567')).to.equal(''); - expect(findSuffix('1234asdf')).to.equal('asdf'); - expect(findSuffix('1.0')).to.equal(''); + strictEqual(findSuffix('1234567'), ''); + strictEqual(findSuffix('1234asdf'), 'asdf'); + strictEqual(findSuffix('1.0'), ''); }); it('shoult extract the headers for ApiException correctly', () => { @@ -140,6 +139,6 @@ describe('Utils', () => { response.headers.set('foo', 'bar'); response.headers.set('baz', 'k8s'); - assert.deepEqual(normalizeResponseHeaders(response), { foo: 'bar', baz: 'k8s' }); + deepStrictEqual(normalizeResponseHeaders(response), { foo: 'bar', baz: 'k8s' }); }); }); diff --git a/src/watch_test.ts b/src/watch_test.ts index 461639e82d..38e169d9fc 100644 --- a/src/watch_test.ts +++ b/src/watch_test.ts @@ -1,4 +1,4 @@ -import { expect } from 'chai'; +import { deepStrictEqual, rejects, strictEqual } from 'node:assert'; import nock from 'nock'; import { PassThrough } from 'node:stream'; import { KubeConfig } from './config.js'; @@ -65,8 +65,8 @@ describe('Watch', () => { doneErr = err; }, ); - expect(doneCalled).to.equal(true); - expect(doneErr.toString()).to.equal('Error: Internal Server Error'); + strictEqual(doneCalled, true); + strictEqual(doneErr.toString(), 'Error: Internal Server Error'); s.done(); }); @@ -148,18 +148,18 @@ describe('Watch', () => { await handledAllObjectsPromise; - expect(receivedTypes).to.deep.equal([obj1.type, obj2.type]); - expect(receivedObjects).to.deep.equal([obj1.object, obj2.object]); + deepStrictEqual(receivedTypes, [obj1.type, obj2.type]); + deepStrictEqual(receivedObjects, [obj1.object, obj2.object]); - expect(doneCalled).to.equal(0); + strictEqual(doneCalled, 0); const errIn = new Error('err'); (response as IncomingMessage).socket.destroy(errIn); await donePromise; - expect(doneCalled).to.equal(1); - expect(doneErr).to.deep.equal(errIn); + strictEqual(doneCalled, 1); + deepStrictEqual(doneErr, errIn); s.done(); @@ -226,18 +226,18 @@ describe('Watch', () => { await handledAllObjectsPromise; - expect(receivedTypes).to.deep.equal([obj1.type]); - expect(receivedObjects).to.deep.equal([obj1.object]); + deepStrictEqual(receivedTypes, [obj1.type]); + deepStrictEqual(receivedObjects, [obj1.object]); - expect(doneErr.length).to.equal(0); + strictEqual(doneErr.length, 0); const errIn = new Error('err'); (response as IncomingMessage).socket.destroy(errIn); await donePromise; - expect(doneErr.length).to.equal(1); - expect(doneErr[0]).to.deep.equal(errIn); + strictEqual(doneErr.length, 1); + deepStrictEqual(doneErr[0], errIn); s.done(); @@ -299,17 +299,16 @@ describe('Watch', () => { await handledAllObjectsPromise; - expect(receivedTypes).to.deep.equal([obj1.type]); - expect(receivedObjects).to.deep.equal([obj1.object]); - - expect(doneErr.length).to.equal(0); + deepStrictEqual(receivedTypes, [obj1.type]); + deepStrictEqual(receivedObjects, [obj1.object]); + strictEqual(doneErr.length, 0); stream.end(); await donePromise; - expect(doneErr.length).to.equal(1); - expect(doneErr[0]).to.equal(null); + strictEqual(doneErr.length, 1); + strictEqual(doneErr[0], null); s.done(); @@ -364,13 +363,13 @@ describe('Watch', () => { await donePromise; - expect(receivedTypes).to.deep.equal([obj.type]); - expect(receivedObjects).to.deep.equal([obj.object]); + deepStrictEqual(receivedTypes, [obj.type]); + deepStrictEqual(receivedObjects, [obj.object]); s.done(); }); - it('should throw on empty config', () => { + it('should throw on empty config', async () => { const kc = new KubeConfig(); const watch = new Watch(kc); @@ -380,6 +379,6 @@ describe('Watch', () => { () => {}, () => {}, ); - expect(promise).to.be.rejected; + await rejects(promise); }); }); diff --git a/src/web-socket-handler_test.ts b/src/web-socket-handler_test.ts index fc5d90f6c6..84f7b6512e 100644 --- a/src/web-socket-handler_test.ts +++ b/src/web-socket-handler_test.ts @@ -1,6 +1,6 @@ +import { deepStrictEqual, notStrictEqual, rejects, strictEqual, throws } from 'node:assert'; import { Readable, Writable } from 'node:stream'; import { setImmediate as setImmediatePromise } from 'node:timers/promises'; -import { expect } from 'chai'; import WebSocket from 'isomorphic-ws'; import { ReadableStreamBuffer, WritableStreamBuffer } from 'stream-buffers'; @@ -16,9 +16,9 @@ describe('WebSocket', () => { const buff = Buffer.alloc(30, 20); const badStream = 10; - expect(() => WebSocketHandler.handleStandardStreams(badStream, buff, osStream, errStream)).to.throw( - `Unknown stream: ${badStream}`, - ); + throws(() => WebSocketHandler.handleStandardStreams(badStream, buff, osStream, errStream), { + message: `Unknown stream: ${badStream}`, + }); }); it('should handle a status to end', () => { const osStream = new WritableStreamBuffer(); @@ -39,9 +39,9 @@ describe('WebSocket', () => { errStream, ); - expect(osStream.size()).to.equal(0); - expect(errStream.size()).to.equal(0); - expect(output).to.not.be.null; + strictEqual(osStream.size(), 0); + strictEqual(errStream.size(), 0); + notStrictEqual(output, null); }); it('should handle empty buffers', () => { const osStream = new WritableStreamBuffer(); @@ -50,8 +50,8 @@ describe('WebSocket', () => { WebSocketHandler.handleStandardStreams(WebSocketHandler.StdoutStream, buff, osStream, errStream); - expect(osStream.size()).to.equal(0); - expect(errStream.size()).to.equal(0); + strictEqual(osStream.size(), 0); + strictEqual(errStream.size(), 0); }); it('should handle output streams', () => { const osStream = new WritableStreamBuffer(); @@ -65,30 +65,28 @@ describe('WebSocket', () => { WebSocketHandler.handleStandardStreams(WebSocketHandler.StdoutStream, buff1, osStream, errStream); - expect(osStream.size()).to.equal(1024); - expect(errStream.size()).to.equal(0); + strictEqual(osStream.size(), 1024); + strictEqual(errStream.size(), 0); WebSocketHandler.handleStandardStreams(WebSocketHandler.StderrStream, buff2, osStream, errStream); - expect(osStream.size()).to.equal(1024); - expect(errStream.size()).to.equal(512); + strictEqual(osStream.size(), 1024); + strictEqual(errStream.size(), 512); const outputBuffer1 = osStream.getContents() as Buffer; for (let i = 0; i < 1024; i++) { - expect(outputBuffer1[i]).to.equal(fill1); + strictEqual(outputBuffer1[i], fill1); } const outputBuffer2 = errStream.getContents() as Buffer; for (let i = 0; i < 512; i++) { - expect(outputBuffer2[i]).to.equal(fill2); + strictEqual(outputBuffer2[i], fill2); } }); - it('should throw on a config with no cluster', () => { + it('should throw on a config with no cluster', async () => { const config = new KubeConfig(); const handler = new WebSocketHandler(config); - return expect(handler.connect('/some/path', null, null)).to.eventually.be.rejectedWith( - 'No cluster is defined.', - ); + await rejects(handler.connect('/some/path', null, null), { message: 'No cluster is defined.' }); }); it('should error on bad connection', async () => { const kc = new KubeConfig(); @@ -130,7 +128,7 @@ describe('WebSocket', () => { target: mockWs, }); - await expect(promise).to.be.rejected; + await rejects(promise); }); it('should connect properly', async () => { const kc = new KubeConfig(); @@ -169,7 +167,7 @@ describe('WebSocket', () => { const promise = handler.connect(path, null, null); await setImmediatePromise(); - expect(uriOut).to.equal(`wss://${host}${path}`); + strictEqual(uriOut, `wss://${host}${path}`); const event = { error: {}, @@ -253,7 +251,7 @@ describe('WebSocket', () => { const promise = handler.connect(path, textHandler, binaryHandler); await setImmediatePromise(); - expect(uriOut).to.equal(`wss://${host}${path}`); + strictEqual(uriOut, `wss://${host}${path}`); const event = { error: {}, @@ -283,13 +281,13 @@ describe('WebSocket', () => { mockWs.onerror!(errEvt); await promise; - expect(closeCount).to.equal(2); - expect(textReceived).to.equal('string data'); + strictEqual(closeCount, 2); + strictEqual(textReceived, 'string data'); - expect(streamNumber).to.equal(fill); - expect(dataReceived.length).to.equal(size - 1); + strictEqual(streamNumber, fill); + strictEqual(dataReceived.length, size - 1); for (const datum of dataReceived) { - expect(datum).to.equal(fill); + strictEqual(datum, fill); } }); it('handles multi-byte characters', () => { @@ -298,7 +296,7 @@ describe('WebSocket', () => { const mockWs = { close() {}, send(data) { - expect(data).to.deep.equal(Buffer.from([0x0f, 0xe2, 0x98, 0x83])); + deepStrictEqual(data, Buffer.from([0x0f, 0xe2, 0x98, 0x83])); resolve(undefined); }, } as WebSocket.WebSocket; @@ -359,7 +357,7 @@ describe('V5 protocol support', () => { const promise = handler.connect(path, null, null); await setImmediatePromise(); - expect(uriOut).to.equal(`wss://${host}${path}`); + strictEqual(uriOut, `wss://${host}${path}`); const event = { target: mockWs, @@ -376,7 +374,7 @@ describe('V5 protocol support', () => { target: mockWs, }); await promise; - expect(endCalled).to.be.true; + strictEqual(endCalled, true); }); it('should handle closing stdin < v4 protocol', () => { const ws = { @@ -401,18 +399,20 @@ describe('V5 protocol support', () => { const stdinStream = new ReadableStreamBuffer(); WebSocketHandler.handleStandardInput(ws, stdinStream); stdinStream.emit('end'); - expect(sent).to.not.be.null; - expect(sent!.readUint8(0)).to.equal(255); // CLOSE signal - expect(sent!.readUInt8(1)).to.equal(0); // Stdin stream is #0 + notStrictEqual(sent, null); + strictEqual(sent!.readUint8(0), 255); // CLOSE signal + strictEqual(sent!.readUInt8(1), 0); // Stdin stream is #0 }); }); describe('Restartable Handle Standard Input', () => { it('should throw on negative retry', () => { const p = new Promise(() => {}); - expect(() => - WebSocketHandler.restartableHandleStandardInput(() => p, new Readable({ read() {} }), 0, -1), - ).to.throw("retryCount can't be lower than 0."); + throws( + () => + WebSocketHandler.restartableHandleStandardInput(() => p, new Readable({ read() {} }), 0, -1), + { message: "retryCount can't be lower than 0." }, + ); }); it('should retry n times', () => { @@ -433,7 +433,7 @@ describe('Restartable Handle Standard Input', () => { 0, retryTimes, ).catch(() => { - expect(count).to.equal(retryTimes); + strictEqual(count, retryTimes); }); }); }); diff --git a/src/yaml_test.ts b/src/yaml_test.ts index 71269e56ff..deb9d895fe 100644 --- a/src/yaml_test.ts +++ b/src/yaml_test.ts @@ -1,5 +1,4 @@ -import { expect } from 'chai'; - +import { deepStrictEqual, strictEqual } from 'node:assert'; import { V1Namespace } from './api.js'; import { dumpYaml, loadAllYaml, loadYaml } from './yaml.js'; @@ -8,9 +7,9 @@ describe('yaml', () => { const yaml = 'apiVersion: v1\n' + 'kind: Namespace\n' + 'metadata:\n' + ' name: some-namespace\n'; const ns = loadYaml(yaml); - expect(ns.apiVersion).to.equal('v1'); - expect(ns.kind).to.equal('Namespace'); - expect(ns.metadata!.name).to.equal('some-namespace'); + strictEqual(ns.apiVersion, 'v1'); + strictEqual(ns.kind, 'Namespace'); + strictEqual(ns.metadata!.name, 'some-namespace'); }); it('should load all safely', () => { const yaml = @@ -26,12 +25,12 @@ describe('yaml', () => { ' namespace: some-ns\n'; const objects = loadAllYaml(yaml); - expect(objects.length).to.equal(2); - expect(objects[0].kind).to.equal('Namespace'); - expect(objects[1].kind).to.equal('Pod'); - expect(objects[0].metadata.name).to.equal('some-namespace'); - expect(objects[1].metadata.name).to.equal('some-pod'); - expect(objects[1].metadata.namespace).to.equal('some-ns'); + strictEqual(objects.length, 2); + strictEqual(objects[0].kind, 'Namespace'); + strictEqual(objects[1].kind, 'Pod'); + strictEqual(objects[0].metadata.name, 'some-namespace'); + strictEqual(objects[1].metadata.name, 'some-pod'); + strictEqual(objects[1].metadata.namespace, 'some-ns'); }); it('should round trip successfully', () => { const expected = { @@ -41,6 +40,6 @@ describe('yaml', () => { }; const yamlString = dumpYaml(expected); const actual = loadYaml(yamlString); - expect(actual).to.deep.equal(expected); + deepStrictEqual(actual, expected); }); });