diff --git a/test/unit/assorted/polling_srv_records_for_mongos_discovery.prose.test.ts b/test/unit/assorted/polling_srv_records_for_mongos_discovery.prose.test.ts index ae2a8116795..258e1922fce 100644 --- a/test/unit/assorted/polling_srv_records_for_mongos_discovery.prose.test.ts +++ b/test/unit/assorted/polling_srv_records_for_mongos_discovery.prose.test.ts @@ -98,12 +98,9 @@ describe('Polling Srv Records for Mongos Discovery', () => { return mock.cleanup(); }); - afterEach(function (done) { + afterEach(function () { if (context.topology) { context.topology.close(); - done(); - } else { - done(); } }); diff --git a/test/unit/bson.test.ts b/test/unit/bson.test.ts index 6218933c3bf..4f4ff2f95a5 100644 --- a/test/unit/bson.test.ts +++ b/test/unit/bson.test.ts @@ -1,7 +1,6 @@ +import { BSON } from 'bson'; import { expect } from 'chai'; -import { BSON } from '../mongodb'; - describe('When importing BSON', function () { const types = [ ['Long', 23], diff --git a/test/unit/change_stream.test.ts b/test/unit/change_stream.test.ts index 0b1b2b7c301..36976181bd5 100644 --- a/test/unit/change_stream.test.ts +++ b/test/unit/change_stream.test.ts @@ -2,7 +2,9 @@ import { Long, Timestamp } from 'bson'; import { expect } from 'chai'; import * as sinon from 'sinon'; -import { ChangeStreamCursor, MongoClient, MongoDBNamespace } from '../mongodb'; +import { ChangeStreamCursor } from '../../src/cursor/change_stream_cursor'; +import { MongoClient } from '../../src/mongo_client'; +import { MongoDBNamespace } from '../../src/utils'; describe('ChangeStreamCursor', function () { afterEach(function () { diff --git a/test/unit/client-side-encryption/auto_encrypter.test.ts b/test/unit/client-side-encryption/auto_encrypter.test.ts index 7ccc391ece7..a7a00beba03 100644 --- a/test/unit/client-side-encryption/auto_encrypter.test.ts +++ b/test/unit/client-side-encryption/auto_encrypter.test.ts @@ -1,13 +1,14 @@ +import { BSON } from 'bson'; import { expect } from 'chai'; import * as fs from 'fs'; import * as net from 'net'; import * as sinon from 'sinon'; import { AutoEncrypter } from '../../../src/client-side-encryption/auto_encrypter'; +import { type DataKey } from '../../../src/client-side-encryption/client_encryption'; import { MongocryptdManager } from '../../../src/client-side-encryption/mongocryptd_manager'; import { StateMachine } from '../../../src/client-side-encryption/state_machine'; import { MongoClient } from '../../../src/mongo_client'; -import { BSON, type DataKey } from '../../mongodb'; import * as requirements from './requirements.helper'; const bson = BSON; diff --git a/test/unit/client-side-encryption/client_encryption.test.ts b/test/unit/client-side-encryption/client_encryption.test.ts index 422ad8bdd82..c178231139d 100644 --- a/test/unit/client-side-encryption/client_encryption.test.ts +++ b/test/unit/client-side-encryption/client_encryption.test.ts @@ -1,3 +1,4 @@ +import { Binary, BSON, deserialize } from 'bson'; import { expect } from 'chai'; import * as fs from 'fs'; import { resolve } from 'path'; @@ -10,7 +11,7 @@ import { MongoCryptCreateEncryptedCollectionError } from '../../../src/client-side-encryption/errors'; import { StateMachine } from '../../../src/client-side-encryption/state_machine'; -import { Binary, BSON, deserialize, MongoClient } from '../../mongodb'; +import { MongoClient } from '../../../src/mongo_client'; const { EJSON } = BSON; diff --git a/test/unit/client-side-encryption/errors.test.ts b/test/unit/client-side-encryption/errors.test.ts index b4b8b8224c2..885fc7dab85 100644 --- a/test/unit/client-side-encryption/errors.test.ts +++ b/test/unit/client-side-encryption/errors.test.ts @@ -7,7 +7,7 @@ import { MongoCryptError, MongoCryptInvalidArgumentError } from '../../../src/client-side-encryption/errors'; -import { MongoError } from '../../mongodb'; +import { MongoError } from '../../../src/error'; describe('MongoCryptError', function () { const errors = [ diff --git a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts index aab342222f8..5dbca90dfb3 100644 --- a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts +++ b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts @@ -13,8 +13,8 @@ import { tokenCache } from '../../../../src/client-side-encryption/providers/azure'; import { AWSSDKCredentialProvider } from '../../../../src/cmap/auth/aws_temporary_credentials'; +import { MongoNetworkTimeoutError } from '../../../../src/error'; import * as utils from '../../../../src/utils'; -import { MongoNetworkTimeoutError } from '../../../mongodb'; import * as requirements from '../requirements.helper'; const originalAccessKeyId = process.env.AWS_ACCESS_KEY_ID; diff --git a/test/unit/client-side-encryption/state_machine.test.ts b/test/unit/client-side-encryption/state_machine.test.ts index 21cecd83574..1ce00c011e1 100644 --- a/test/unit/client-side-encryption/state_machine.test.ts +++ b/test/unit/client-side-encryption/state_machine.test.ts @@ -1,27 +1,21 @@ +import { BSON, Int32, Long, serialize } from 'bson'; import { expect } from 'chai'; import { EventEmitter, once } from 'events'; import * as fs from 'fs/promises'; import { type MongoCryptKMSRequest } from 'mongodb-client-encryption'; import * as net from 'net'; import * as sinon from 'sinon'; -import { setTimeout } from 'timers'; import { setTimeout as setTimeoutAsync } from 'timers/promises'; import * as tls from 'tls'; import { StateMachine } from '../../../src/client-side-encryption/state_machine'; +import { Collection } from '../../../src/collection'; +import { CursorTimeoutContext } from '../../../src/cursor/abstract_cursor'; import { Db } from '../../../src/db'; -import { - BSON, - Collection, - CSOTTimeoutContext, - CursorTimeoutContext, - type FindOptions, - Int32, - Long, - MongoClient, - serialize, - squashError -} from '../../mongodb'; +import { MongoClient } from '../../../src/mongo_client'; +import { type FindOptions } from '../../../src/operations/find'; +import { CSOTTimeoutContext } from '../../../src/timeout'; +import { squashError } from '../../../src/utils'; import { sleep } from '../../tools/utils'; describe('StateMachine', function () { @@ -129,7 +123,7 @@ describe('StateMachine', function () { }); }); - it('should only resolve once bytesNeeded drops to zero', function (done) { + it('should only resolve once bytesNeeded drops to zero', async function () { const stateMachine = new StateMachine({} as any); const request = new MockRequest(Buffer.from('foobar'), 500); let status = 'pending'; @@ -143,22 +137,21 @@ describe('StateMachine', function () { .catch(() => {}); this.fakeSocket.emit('connect'); - setTimeout(() => { - expect(status).to.equal('pending'); - expect(request.bytesNeeded).to.equal(500); - expect(request.kmsProvider).to.equal('aws'); - this.fakeSocket.emit('data', Buffer.alloc(300)); - setTimeout(() => { - expect(status).to.equal('pending'); - expect(request.bytesNeeded).to.equal(200); - this.fakeSocket.emit('data', Buffer.alloc(200)); - setTimeout(() => { - expect(status).to.equal('resolved'); - expect(request.bytesNeeded).to.equal(0); - done(); - }); - }); - }); + await sleep(); + + expect(status).to.equal('pending'); + expect(request.bytesNeeded).to.equal(500); + expect(request.kmsProvider).to.equal('aws'); + this.fakeSocket.emit('data', Buffer.alloc(300)); + await sleep(); + + expect(status).to.equal('pending'); + expect(request.bytesNeeded).to.equal(200); + this.fakeSocket.emit('data', Buffer.alloc(200)); + await sleep(); + + expect(status).to.equal('resolved'); + expect(request.bytesNeeded).to.equal(0); }); }); @@ -196,13 +189,9 @@ describe('StateMachine', function () { } as any); const request = new MockRequest(Buffer.from('foobar'), 500); - it('rejects with the validation error', function (done) { - stateMachine.kmsRequest(request).catch(err => { - expect(err.message).to.equal( - `Insecure TLS options prohibited for aws: ${option}` - ); - done(); - }); + it('rejects with the validation error', async function () { + const err = await stateMachine.kmsRequest(request).catch(e => e); + expect(err.message).to.equal(`Insecure TLS options prohibited for aws: ${option}`); }); }); } diff --git a/test/unit/cmap/auth/auth_provider.test.ts b/test/unit/cmap/auth/auth_provider.test.ts index 7c9b530e69f..067a691dd5d 100644 --- a/test/unit/cmap/auth/auth_provider.test.ts +++ b/test/unit/cmap/auth/auth_provider.test.ts @@ -1,6 +1,7 @@ import { expect } from 'chai'; -import { type AuthContext, AuthProvider, MongoRuntimeError } from '../../../mongodb'; +import { type AuthContext, AuthProvider } from '../../../../src/cmap/auth/auth_provider'; +import { MongoRuntimeError } from '../../../../src/error'; describe('AuthProvider', function () { describe('#reauth', function () { diff --git a/test/unit/cmap/auth/gssapi.test.ts b/test/unit/cmap/auth/gssapi.test.ts index 1d803a05528..9df2500b8e0 100644 --- a/test/unit/cmap/auth/gssapi.test.ts +++ b/test/unit/cmap/auth/gssapi.test.ts @@ -6,7 +6,7 @@ import { GSSAPICanonicalizationValue, performGSSAPICanonicalizeHostName, resolveCname -} from '../../../mongodb'; +} from '../../../../src/cmap/auth/gssapi'; describe('GSSAPI', () => { let lookupSpy; diff --git a/test/unit/cmap/auth/mongodb_oidc/automated_callback_workflow.test.ts b/test/unit/cmap/auth/mongodb_oidc/automated_callback_workflow.test.ts index fd2343eb913..017387685b8 100644 --- a/test/unit/cmap/auth/mongodb_oidc/automated_callback_workflow.test.ts +++ b/test/unit/cmap/auth/mongodb_oidc/automated_callback_workflow.test.ts @@ -1,14 +1,12 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; +import { MongoCredentials } from '../../../../../src/cmap/auth/mongo_credentials'; +import { AutomatedCallbackWorkflow } from '../../../../../src/cmap/auth/mongodb_oidc/automated_callback_workflow'; +import { CallbackWorkflow } from '../../../../../src/cmap/auth/mongodb_oidc/callback_workflow'; import { callback } from '../../../../../src/cmap/auth/mongodb_oidc/gcp_machine_workflow'; import { TokenCache } from '../../../../../src/cmap/auth/mongodb_oidc/token_cache'; -import { - AutomatedCallbackWorkflow, - CallbackWorkflow, - Connection, - MongoCredentials -} from '../../../../mongodb'; +import { Connection } from '../../../../../src/cmap/connection'; describe('AutomatedCallbackWorkflow', function () { describe('#execute', function () { diff --git a/test/unit/cmap/auth/mongodb_oidc/azure_machine_workflow.test.ts b/test/unit/cmap/auth/mongodb_oidc/azure_machine_workflow.test.ts index 0db2db100b3..26d0795cd11 100644 --- a/test/unit/cmap/auth/mongodb_oidc/azure_machine_workflow.test.ts +++ b/test/unit/cmap/auth/mongodb_oidc/azure_machine_workflow.test.ts @@ -1,7 +1,7 @@ import { expect } from 'chai'; +import { OIDC_VERSION, type OIDCCallbackParams } from '../../../../../src/cmap/auth/mongodb_oidc'; import { callback } from '../../../../../src/cmap/auth/mongodb_oidc/azure_machine_workflow'; -import { OIDC_VERSION, type OIDCCallbackParams } from '../../../../mongodb'; describe('Azure machine workflow', function () { describe('#callback', function () { diff --git a/test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts b/test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts index 23b890fd988..56f1ed673d7 100644 --- a/test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts +++ b/test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts @@ -1,7 +1,7 @@ import { expect } from 'chai'; +import { OIDC_VERSION, type OIDCCallbackParams } from '../../../../../src/cmap/auth/mongodb_oidc'; import { callback } from '../../../../../src/cmap/auth/mongodb_oidc/gcp_machine_workflow'; -import { OIDC_VERSION, type OIDCCallbackParams } from '../../../../mongodb'; describe('GCP machine workflow', function () { describe('#callback', function () { diff --git a/test/unit/cmap/command_monitoring_events.test.js b/test/unit/cmap/command_monitoring_events.test.js index 08d06b0ed2a..8ae42bb32bf 100644 --- a/test/unit/cmap/command_monitoring_events.test.js +++ b/test/unit/cmap/command_monitoring_events.test.js @@ -1,7 +1,7 @@ 'use strict'; -const { OpQueryRequest, OpMsgRequest } = require('../../mongodb'); -const { CommandStartedEvent } = require('../../mongodb'); +const { OpQueryRequest, OpMsgRequest } = require('../../../src/cmap/commands'); +const { CommandStartedEvent } = require('../../../src/cmap/command_monitoring_events'); const { expect } = require('chai'); describe('Command Monitoring Events - unit/cmap', function () { diff --git a/test/unit/cmap/commands.test.ts b/test/unit/cmap/commands.test.ts index 5725f5b2490..7666a4a6552 100644 --- a/test/unit/cmap/commands.test.ts +++ b/test/unit/cmap/commands.test.ts @@ -1,7 +1,7 @@ import * as BSON from 'bson'; import { expect } from 'chai'; -import { DocumentSequence, OpMsgRequest, OpReply } from '../../mongodb'; +import { DocumentSequence, OpMsgRequest, OpReply } from '../../../src/cmap/commands'; describe('commands', function () { describe('OpMsgRequest', function () { diff --git a/test/unit/cmap/connect.test.ts b/test/unit/cmap/connect.test.ts index 7f172b860b3..ba54946f589 100644 --- a/test/unit/cmap/connect.test.ts +++ b/test/unit/cmap/connect.test.ts @@ -1,20 +1,18 @@ +import { type Document } from 'bson'; import { expect } from 'chai'; +import { MongoCredentials } from '../../../src/cmap/auth/mongo_credentials'; +import { connect, prepareHandshakeDocument } from '../../../src/cmap/connect'; +import { type Connection, type ConnectionOptions } from '../../../src/cmap/connection'; import { addContainerMetadata, - CancellationToken, - type ClientMetadata, - connect, - type Connection, - type ConnectionOptions, - HostAddress, - isHello, - LEGACY_HELLO_COMMAND, - MongoClientAuthProviders, - MongoCredentials, - MongoNetworkError, - prepareHandshakeDocument -} from '../../mongodb'; + type ClientMetadata +} from '../../../src/cmap/handshake/client_metadata'; +import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; +import { MongoNetworkError } from '../../../src/error'; +import { MongoClientAuthProviders } from '../../../src/mongo_client_auth_providers'; +import { CancellationToken } from '../../../src/mongo_types'; +import { HostAddress, isHello } from '../../../src/utils'; import { genClusterTime } from '../../tools/common'; import * as mock from '../../tools/mongodb-mock/index'; diff --git a/test/unit/cmap/connection.test.ts b/test/unit/cmap/connection.test.ts index 79fe9ea863d..fcd15a5dd38 100644 --- a/test/unit/cmap/connection.test.ts +++ b/test/unit/cmap/connection.test.ts @@ -5,18 +5,11 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; import { setTimeout } from 'timers/promises'; -import { - connect, - Connection, - isHello, - MongoClientAuthProviders, - MongoDBCollectionNamespace, - MongoNetworkTimeoutError, - MongoRuntimeError, - ns, - promiseWithResolvers, - SizedMessageTransform -} from '../../mongodb'; +import { connect } from '../../../src/cmap/connect'; +import { Connection, SizedMessageTransform } from '../../../src/cmap/connection'; +import { MongoNetworkTimeoutError, MongoRuntimeError } from '../../../src/error'; +import { MongoClientAuthProviders } from '../../../src/mongo_client_auth_providers'; +import { isHello, MongoDBCollectionNamespace, ns, promiseWithResolvers } from '../../../src/utils'; import * as mock from '../../tools/mongodb-mock/index'; const connectionOptionsDefaults = { diff --git a/test/unit/cmap/connection_pool.test.js b/test/unit/cmap/connection_pool.test.js index 61fa73fc0e4..81bff92d0fd 100644 --- a/test/unit/cmap/connection_pool.test.js +++ b/test/unit/cmap/connection_pool.test.js @@ -1,16 +1,18 @@ 'use strict'; -const { ConnectionPool, MongoError } = require('../../mongodb'); -const { WaitQueueTimeoutError } = require('../../mongodb'); +const { ConnectionPool } = require('../../../src/cmap/connection_pool'); +const { MongoError } = require('../../../src/error'); +const { WaitQueueTimeoutError } = require('../../../src/cmap/errors'); const mock = require('../../tools/mongodb-mock/index'); const sinon = require('sinon'); const { expect } = require('chai'); const { setImmediate } = require('timers/promises'); -const { ns, isHello } = require('../../mongodb'); +const { isHello } = require('../../../src/utils'); +const { ns } = require('../../../src/utils'); const { createTimerSandbox } = require('../timer_sandbox'); const { topologyWithPlaceholderClient } = require('../../tools/utils'); -const { MongoClientAuthProviders } = require('../../mongodb'); -const { TimeoutContext } = require('../../mongodb'); +const { MongoClientAuthProviders } = require('../../../src/mongo_client_auth_providers'); +const { TimeoutContext } = require('../../../src/timeout'); describe('Connection Pool', function () { let timeoutContext; diff --git a/test/unit/cmap/connection_pool_events.test.ts b/test/unit/cmap/connection_pool_events.test.ts index 54337fbaa27..5281f66f9ec 100644 --- a/test/unit/cmap/connection_pool_events.test.ts +++ b/test/unit/cmap/connection_pool_events.test.ts @@ -1,6 +1,7 @@ import { expect } from 'chai'; -import { type ConnectionPool, ConnectionPoolCreatedEvent } from '../../mongodb'; +import { type ConnectionPool } from '../../../src/cmap/connection_pool'; +import { ConnectionPoolCreatedEvent } from '../../../src/cmap/connection_pool_events'; describe('Connection Pool Events', function () { const connectionPoolMock = { diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 0ca413f4fdf..09c5a06d1cd 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -1,3 +1,4 @@ +import { Int32, ObjectId } from 'bson'; import { expect } from 'chai'; import * as os from 'os'; import * as process from 'process'; @@ -7,12 +8,10 @@ import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; import { getFAASEnv, - Int32, LimitedSizeDocument, - makeClientMetadata, - MongoInvalidArgumentError, - ObjectId -} from '../../../mongodb'; + makeClientMetadata +} from '../../../../src/cmap/handshake/client_metadata'; +import { MongoInvalidArgumentError } from '../../../../src/error'; describe('client metadata module', () => { afterEach(() => sinon.restore()); diff --git a/test/unit/cmap/metrics.test.js b/test/unit/cmap/metrics.test.js index bef221121f6..50e2fc3d4e0 100644 --- a/test/unit/cmap/metrics.test.js +++ b/test/unit/cmap/metrics.test.js @@ -1,7 +1,7 @@ 'use strict'; const { expect } = require('chai'); -const { ConnectionPoolMetrics } = require('../../mongodb'); +const { ConnectionPoolMetrics } = require('../../../src/cmap/metrics'); describe('ConnectionPoolMetrics', function () { describe('#constructor', function () { diff --git a/test/unit/cmap/stream_description.test.js b/test/unit/cmap/stream_description.test.js index 687a0342053..8af7ba85947 100644 --- a/test/unit/cmap/stream_description.test.js +++ b/test/unit/cmap/stream_description.test.js @@ -1,7 +1,7 @@ 'use strict'; const { Double, Long } = require('bson'); -const { StreamDescription } = require('../../mongodb'); +const { StreamDescription } = require('../../../src/cmap/stream_description'); const { expect } = require('chai'); describe('StreamDescription - unit/cmap', function () { diff --git a/test/unit/cmap/wire_protocol/compression.test.ts b/test/unit/cmap/wire_protocol/compression.test.ts index e67fa0afb7b..77aec98e457 100644 --- a/test/unit/cmap/wire_protocol/compression.test.ts +++ b/test/unit/cmap/wire_protocol/compression.test.ts @@ -1,7 +1,7 @@ import * as zstd from '@mongodb-js/zstd'; import { expect } from 'chai'; -import { compress, Compressor, decompress } from '../../../mongodb'; +import { compress, Compressor, decompress } from '../../../../src/cmap/wire_protocol/compression'; describe('compression', function () { describe('.compress()', function () { diff --git a/test/unit/cmap/wire_protocol/constants.test.ts b/test/unit/cmap/wire_protocol/constants.test.ts index e43b2051926..3ba696b7293 100644 --- a/test/unit/cmap/wire_protocol/constants.test.ts +++ b/test/unit/cmap/wire_protocol/constants.test.ts @@ -5,7 +5,7 @@ import { MAX_SUPPORTED_WIRE_VERSION, MIN_SUPPORTED_SERVER_VERSION, MIN_SUPPORTED_WIRE_VERSION -} from '../../../mongodb'; +} from '../../../../src/cmap/wire_protocol/constants'; describe('Wire Protocol Constants', function () { describe('MIN_SUPPORTED_SERVER_VERSION', function () { diff --git a/test/unit/cmap/wire_protocol/on_demand/document.test.ts b/test/unit/cmap/wire_protocol/on_demand/document.test.ts index 82ed4040f64..1ab39d8c46f 100644 --- a/test/unit/cmap/wire_protocol/on_demand/document.test.ts +++ b/test/unit/cmap/wire_protocol/on_demand/document.test.ts @@ -1,14 +1,7 @@ +import { Binary, BSON, BSONError, BSONType, ObjectId, Timestamp } from 'bson'; import { expect } from 'chai'; -import { - Binary, - BSON, - BSONError, - BSONType, - ObjectId, - OnDemandDocument, - Timestamp -} from '../../../../mongodb'; +import { OnDemandDocument } from '../../../../../src/cmap/wire_protocol/on_demand/document'; describe('class OnDemandDocument', () => { context('when given an empty BSON sequence', () => { diff --git a/test/unit/cmap/wire_protocol/responses.test.ts b/test/unit/cmap/wire_protocol/responses.test.ts index 9f2527d8a3c..50368489190 100644 --- a/test/unit/cmap/wire_protocol/responses.test.ts +++ b/test/unit/cmap/wire_protocol/responses.test.ts @@ -1,13 +1,9 @@ import { expect } from 'chai'; -import { - CursorResponse, - Int32, - MongoDBResponse, - MongoUnexpectedServerResponseError, - OnDemandDocument, - serialize -} from '../../../mongodb'; +import { Int32, serialize } from '../../../../src/bson'; +import { OnDemandDocument } from '../../../../src/cmap/wire_protocol/on_demand/document'; +import { CursorResponse, MongoDBResponse } from '../../../../src/cmap/wire_protocol/responses'; +import { MongoUnexpectedServerResponseError } from '../../../../src/error'; describe('class MongoDBResponse', () => { it('is a subclass of OnDemandDocument', () => { diff --git a/test/unit/collection.test.ts b/test/unit/collection.test.ts index c45712abebc..f7c3b017771 100644 --- a/test/unit/collection.test.ts +++ b/test/unit/collection.test.ts @@ -1,6 +1,8 @@ +import { Long } from 'bson'; import { expect } from 'chai'; -import { isHello, MongoClient } from '../mongodb'; +import { MongoClient } from '../../src/mongo_client'; +import { isHello } from '../../src/utils'; import { cleanup, createServer, HELLO } from '../tools/mongodb-mock'; describe('Collection', function () { @@ -16,29 +18,21 @@ describe('Collection', function () { context('#aggregate', () => { // general test for aggregate function - function testAggregate(config, done) { + async function testAggregate(config) { const client = new MongoClient(`mongodb://${server.uri()}/test`); - let close = e => { - close = () => null; - client.close(() => done(e)); - }; server.setMessageHandler(request => { const doc = request.document; if (doc.aggregate) { - try { - expect(doc.bypassDocumentValidation).equal(config.expected); - request.reply({ - ok: 1, - cursor: { - firstBatch: [{}], - id: 0, - ns: 'test.test' - } - }); - } catch (e) { - close(e); - } + expect(doc.bypassDocumentValidation).equal(config.expected); + request.reply({ + ok: 1, + cursor: { + firstBatch: [{}], + id: Long.ZERO, + ns: 'test.test' + } + }); } if (isHello(doc)) { @@ -48,52 +42,43 @@ describe('Collection', function () { } }); - client.connect(function (err, client) { - expect(err).to.not.exist; - const db = client.db('test'); - const collection = db.collection('test_c'); + await client.connect(); + const db = client.db('test'); + const collection = db.collection('test_c'); - const options = { bypassDocumentValidation: config.actual }; + const options = { bypassDocumentValidation: config.actual }; - const pipeline = [ - { - $project: {} - } - ]; - collection.aggregate(pipeline, options).next(() => close(null)); - }); + const pipeline = [ + { + $project: {} + } + ]; + await collection.aggregate(pipeline, options).next(); + await client.close(); } context('bypass document validation', () => { - it('should only set bypass document validation if strictly true in aggregate', function (done) { - testAggregate({ expected: true, actual: true }, done); + it('should only set bypass document validation if strictly true in aggregate', async function () { + await testAggregate({ expected: true, actual: true }); }); - it('should not set bypass document validation if not strictly true in aggregate', function (done) { - testAggregate({ expected: undefined, actual: false }, done); + it('should not set bypass document validation if not strictly true in aggregate', async function () { + await testAggregate({ expected: undefined, actual: false }); }); }); }); context('#findOneAndModify', () => { - function testFindOneAndUpdate(config, done) { + async function testFindOneAndUpdate(config) { const client = new MongoClient(`mongodb://${server.uri()}/test`); - let close = e => { - close = () => null; - client.close(() => done(e)); - }; server.setMessageHandler(request => { const doc = request.document; if (doc.findAndModify) { - try { - expect(doc.bypassDocumentValidation).equal(config.expected); - request.reply({ - ok: 1 - }); - } catch (e) { - close(e); - } + expect(doc.bypassDocumentValidation).equal(config.expected); + request.reply({ + ok: 1 + }); } if (isHello(doc)) { @@ -103,47 +88,36 @@ describe('Collection', function () { } }); - client.connect(function (err, client) { - expect(err).to.not.exist; - const db = client.db('test'); - const collection = db.collection('test_c'); + await client.connect(); + const db = client.db('test'); + const collection = db.collection('test_c'); - const options = { bypassDocumentValidation: config.actual }; + const options = { bypassDocumentValidation: config.actual }; - collection.findOneAndUpdate({ name: 'Andy' }, { $inc: { score: 1 } }, options, e => { - close(e); - }); - }); + await collection.findOneAndUpdate({ name: 'Andy' }, { $inc: { score: 1 } }, options); + await client.close(); } - it('should only set bypass document validation if strictly true in findOneAndUpdate', function (done) { - testFindOneAndUpdate({ expected: true, actual: true }, done); + it('should only set bypass document validation if strictly true in findOneAndUpdate', async function () { + await testFindOneAndUpdate({ expected: true, actual: true }); }); - it('should not set bypass document validation if not strictly true in findOneAndUpdate', function (done) { - testFindOneAndUpdate({ expected: undefined, actual: false }, done); + it('should not set bypass document validation if not strictly true in findOneAndUpdate', async function () { + await testFindOneAndUpdate({ expected: undefined, actual: false }); }); }); context('#bulkWrite', () => { - function testBulkWrite(config, done) { + async function testBulkWrite(config) { const client = new MongoClient(`mongodb://${server.uri()}/test`); - let close = e => { - close = () => null; - client.close(() => done(e)); - }; server.setMessageHandler(request => { const doc = request.document; if (doc.insert) { - try { - expect(doc.bypassDocumentValidation).equal(config.expected); - request.reply({ - ok: 1 - }); - } catch (e) { - close(e); - } + expect(doc.bypassDocumentValidation).equal(config.expected); + request.reply({ + ok: 1 + }); } if (isHello(doc)) { @@ -153,35 +127,35 @@ describe('Collection', function () { } }); - client.connect(function (err, client) { - expect(err).to.not.exist; - const db = client.db('test'); - const collection = db.collection('test_c'); + await client.connect(); + const db = client.db('test'); + const collection = db.collection('test_c'); - const options = { - bypassDocumentValidation: config.actual, - ordered: config.ordered - }; + const options = { + bypassDocumentValidation: config.actual, + ordered: config.ordered + }; - collection.bulkWrite([{ insertOne: { document: { a: 1 } } }], options, () => close(null)); - }); + await collection.bulkWrite([{ insertOne: { document: { a: 1 } } }], options); + await client.close(); } + // ordered bulk write, testing change in ordered.js - it('should only set bypass document validation if strictly true in ordered bulkWrite', function (done) { - testBulkWrite({ expected: true, actual: true, ordered: true }, done); + it('should only set bypass document validation if strictly true in ordered bulkWrite', async function () { + await testBulkWrite({ expected: true, actual: true, ordered: true }); }); - it('should not set bypass document validation if not strictly true in ordered bulkWrite', function (done) { - testBulkWrite({ expected: undefined, actual: false, ordered: true }, done); + it('should not set bypass document validation if not strictly true in ordered bulkWrite', async function () { + await testBulkWrite({ expected: undefined, actual: false, ordered: true }); }); // unordered bulk write, testing change in ordered.js - it('should only set bypass document validation if strictly true in unordered bulkWrite', function (done) { - testBulkWrite({ expected: true, actual: true, ordered: false }, done); + it('should only set bypass document validation if strictly true in unordered bulkWrite', async function () { + await testBulkWrite({ expected: true, actual: true, ordered: false }); }); - it('should not set bypass document validation if not strictly true in unordered bulkWrite', function (done) { - testBulkWrite({ expected: undefined, actual: false, ordered: false }, done); + it('should not set bypass document validation if not strictly true in unordered bulkWrite', async function () { + await testBulkWrite({ expected: undefined, actual: false, ordered: false }); }); }); }); diff --git a/test/unit/commands.test.ts b/test/unit/commands.test.ts index b0e2c476018..fcf951dcd68 100644 --- a/test/unit/commands.test.ts +++ b/test/unit/commands.test.ts @@ -1,17 +1,14 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; +import { OpCompressedRequest, OpMsgRequest, OpQueryRequest } from '../../src/cmap/commands'; import * as compression from '../../src/cmap/wire_protocol/compression'; import { compress, Compressor, - OP_MSG, - OP_QUERY, - OpCompressedRequest, - OpMsgRequest, - OpQueryRequest, uncompressibleCommands -} from '../mongodb'; +} from '../../src/cmap/wire_protocol/compression'; +import { OP_MSG, OP_QUERY } from '../../src/cmap/wire_protocol/constants'; describe('class OpCompressedRequest', () => { context('canCompress()', () => { diff --git a/test/unit/connection_string.test.ts b/test/unit/connection_string.test.ts index 744ed5e5213..62adaab40bb 100644 --- a/test/unit/connection_string.test.ts +++ b/test/unit/connection_string.test.ts @@ -6,24 +6,19 @@ import * as dns from 'dns'; import * as sinon from 'sinon'; import { inspect } from 'util'; +import { DEFAULT_ALLOWED_HOSTS, MongoCredentials } from '../../src/cmap/auth/mongo_credentials'; +import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from '../../src/cmap/auth/providers'; +import { parseOptions, resolveSRVRecord } from '../../src/connection_string'; import { - AUTH_MECHS_AUTH_SRC_EXTERNAL, - AuthMechanism, - COSMOS_DB_MSG, - DEFAULT_ALLOWED_HOSTS, - DOCUMENT_DB_MSG, - type Log, MongoAPIError, - MongoClient, - MongoCredentials, MongoDriverError, MongoInvalidArgumentError, - type MongoOptions, MongoParseError, - MongoRuntimeError, - parseOptions, - resolveSRVRecord -} from '../mongodb'; + MongoRuntimeError +} from '../../src/error'; +import { MongoClient, type MongoOptions } from '../../src/mongo_client'; +import { type Log } from '../../src/mongo_logger'; +import { COSMOS_DB_MSG, DOCUMENT_DB_MSG } from '../../src/utils'; describe('Connection String', function () { context('when serverMonitoringMode is set', function () { diff --git a/test/unit/cursor/abstract_cursor.test.ts b/test/unit/cursor/abstract_cursor.test.ts index 7665c8744f2..deb7784c83a 100644 --- a/test/unit/cursor/abstract_cursor.test.ts +++ b/test/unit/cursor/abstract_cursor.test.ts @@ -1,15 +1,15 @@ import { expect } from 'chai'; +import { CursorResponse } from '../../../src/cmap/wire_protocol/responses'; import { AbstractCursor, type AbstractCursorOptions, - type Callback, - type ClientSession, - type ExecutionResult, - MongoClient, - ns, - type Server -} from '../../mongodb'; + type InitialCursorResponse +} from '../../../src/cursor/abstract_cursor'; +import { MongoClient } from '../../../src/mongo_client'; +import { type Server } from '../../../src/sdam/server'; +import { type ClientSession } from '../../../src/sessions'; +import { ns } from '../../../src/utils'; /** Minimal do nothing cursor to focus on testing the base cursor behavior */ class ConcreteCursor extends AbstractCursor { @@ -19,8 +19,9 @@ class ConcreteCursor extends AbstractCursor { clone(): ConcreteCursor { return new ConcreteCursor(new MongoClient('mongodb://iLoveJavascript')); } - _initialize(session: ClientSession, callback: Callback): void { - return callback(undefined, { server: {} as Server, session, response: { ok: 1 } }); + async _initialize(session: ClientSession): Promise { + const response = CursorResponse.emptyGetMore; + return { server: {} as Server, session, response }; } } diff --git a/test/unit/cursor/aggregation_cursor.test.ts b/test/unit/cursor/aggregation_cursor.test.ts index e0d7a1223c1..ac8b6c0d610 100644 --- a/test/unit/cursor/aggregation_cursor.test.ts +++ b/test/unit/cursor/aggregation_cursor.test.ts @@ -1,12 +1,10 @@ import { expect } from 'chai'; -import { - AggregationCursor, - CursorTimeoutMode, - MongoAPIError, - MongoClient, - ns -} from '../../mongodb'; +import { CursorTimeoutMode } from '../../../src/cursor/abstract_cursor'; +import { AggregationCursor } from '../../../src/cursor/aggregation_cursor'; +import { MongoAPIError } from '../../../src/error'; +import { MongoClient } from '../../../src/mongo_client'; +import { ns } from '../../../src/utils'; describe('class AggregationCursor', () => { let client: MongoClient; diff --git a/test/unit/cursor/run_command_cursor.test.ts b/test/unit/cursor/run_command_cursor.test.ts index 361fb2df889..12a820e27d6 100644 --- a/test/unit/cursor/run_command_cursor.test.ts +++ b/test/unit/cursor/run_command_cursor.test.ts @@ -1,6 +1,7 @@ import { expect } from 'chai'; -import { MongoAPIError, MongoClient } from '../../mongodb'; +import { MongoAPIError } from '../../../src/error'; +import { MongoClient } from '../../../src/mongo_client'; describe('class RunCommandCursor', () => { let client: MongoClient; diff --git a/test/unit/db.test.ts b/test/unit/db.test.ts index d9eaebfdbe4..6535e49c78f 100644 --- a/test/unit/db.test.ts +++ b/test/unit/db.test.ts @@ -1,6 +1,8 @@ import { expect } from 'chai'; -import { Db, type DbOptions, MongoClient, ReadPreference } from '../mongodb'; +import { Db, type DbOptions } from '../../src/db'; +import { MongoClient } from '../../src/mongo_client'; +import { ReadPreference } from '../../src/read_preference'; describe('class Db', function () { describe('secondaryOk', function () { diff --git a/test/unit/error.test.ts b/test/unit/error.test.ts index 1a3ddd25403..32e90a07857 100644 --- a/test/unit/error.test.ts +++ b/test/unit/error.test.ts @@ -1,17 +1,24 @@ import { expect } from 'chai'; import { setTimeout } from 'timers'; +import { + PoolClosedError as MongoPoolClosedError, + WaitQueueTimeoutError as MongoWaitQueueTimeoutError +} from '../../src/cmap/errors'; // Exception to the import from mongodb rule we're unit testing our public Errors API import * as importsFromErrorSrc from '../../src/error'; -import * as importsFromEntryPoint from '../../src/index'; import { - isHello, isResumableError, isRetryableReadError, isSDAMUnrecoverableError, LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE, LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, MONGODB_ERROR_CODES, + needsRetryableWriteLabel, + NODE_IS_RECOVERING_ERROR_MESSAGE +} from '../../src/error'; +import * as importsFromEntryPoint from '../../src/index'; +import { MongoDriverError, MongoError, MongoErrorLabel, @@ -24,17 +31,13 @@ import { MongoServerError, MongoSystemError, MongoWriteConcernError, - needsRetryableWriteLabel, - NODE_IS_RECOVERING_ERROR_MESSAGE, - ns, - PoolClosedError as MongoPoolClosedError, - RunCommandOperation, - setDifference, - TimeoutContext, type TopologyDescription, - type TopologyOptions, - WaitQueueTimeoutError as MongoWaitQueueTimeoutError -} from '../mongodb'; + type TopologyOptions +} from '../../src/index'; +import { RunCommandOperation } from '../../src/operations/run_command'; +import { type Topology } from '../../src/sdam/topology'; +import { TimeoutContext } from '../../src/timeout'; +import { isHello, ns, setDifference } from '../../src/utils'; import { ReplSetFixture } from '../tools/common'; import { cleanup } from '../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../tools/utils'; @@ -359,31 +362,14 @@ describe('MongoErrors', () => { beforeEach(() => test.setup()); - function makeAndConnectReplSet(cb) { - let invoked = false; + async function makeAndConnectReplSet(): Promise { const replSet = topologyWithPlaceholderClient( [test.primaryServer.hostAddress(), test.firstSecondaryServer.hostAddress()], { replicaSet: 'rs' } as TopologyOptions ); - replSet.once('error', err => { - if (invoked) { - return; - } - invoked = true; - cb(err); - }); - - replSet.on('connect', () => { - if (invoked) { - return; - } - - invoked = true; - cb(undefined, replSet); - }); - - replSet.connect(); + const topology = await replSet.connect(); + return topology; } it('should expose a user command writeConcern error like a normal WriteConcernError', function () { @@ -430,7 +416,7 @@ describe('MongoErrors', () => { }); }); - it('should propagate writeConcernError.errInfo ', function (done) { + it('should propagate writeConcernError.errInfo ', async function () { test.primaryServer.setMessageHandler(request => { const doc = request.document; if (isHello(doc)) { @@ -440,16 +426,10 @@ describe('MongoErrors', () => { } }); - makeAndConnectReplSet((err, topology) => { - // cleanup the server before calling done - const cleanup = err => { - topology.close(); - done(err); - }; + let topology: Topology; + try { + topology = await makeAndConnectReplSet(); - if (err) { - return cleanup(err); - } const timeoutContext = TimeoutContext.create({ serverSelectionTimeoutMS: 0, waitQueueTimeoutMS: 0 @@ -460,23 +440,19 @@ describe('MongoErrors', () => { Object.assign({}, RAW_USER_WRITE_CONCERN_CMD), {} ); - topology.selectServer('primary', { timeoutContext }).then(server => { - server.command(op, timeoutContext).then(expect.fail, err => { - let _err; - try { - expect(err).to.be.an.instanceOf(MongoWriteConcernError); - expect(err.result).to.exist; - expect(err.result.writeConcernError).to.deep.equal( - RAW_USER_WRITE_CONCERN_ERROR_INFO.writeConcernError - ); - } catch (e) { - _err = e; - } finally { - cleanup(_err); - } - }); - }, expect.fail); - }); + const server = await topology.selectServer('primary', { timeoutContext }); + try { + await server.command(op, timeoutContext); + } catch (err) { + expect(err).to.be.an.instanceOf(MongoWriteConcernError); + expect(err.result).to.exist; + expect(err.result.writeConcernError).to.deep.equal( + RAW_USER_WRITE_CONCERN_ERROR_INFO.writeConcernError + ); + } + } finally { + topology?.close(); + } }); }); diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index adfcfd866c6..403709e0b41 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -1,7 +1,10 @@ import { expect } from 'chai'; import { it } from 'mocha'; -import { Explain, ExplainVerbosity, FindCursor, MongoClient, MongoDBNamespace } from '../mongodb'; +import { FindCursor } from '../../src/cursor/find_cursor'; +import { Explain, ExplainVerbosity } from '../../src/explain'; +import { MongoClient } from '../../src/mongo_client'; +import { MongoDBNamespace } from '../../src/utils'; describe('class Explain {}', function () { describe('static .fromOptions()', function () { diff --git a/test/unit/index.test.ts b/test/unit/index.test.ts index c39a09641e0..5b0658d1038 100644 --- a/test/unit/index.test.ts +++ b/test/unit/index.test.ts @@ -2,7 +2,7 @@ import { expect } from 'chai'; // Exception to the import from mongodb rule we're unit testing our public API import * as mongodb from '../../src/index'; -import { setDifference } from '../mongodb'; +import { setDifference } from '../../src/utils'; const EXPECTED_EXPORTS = [ 'AbstractCursor', diff --git a/test/unit/mongo_client.test.ts b/test/unit/mongo_client.test.ts index fe8c2e034c0..065cc306ba0 100644 --- a/test/unit/mongo_client.test.ts +++ b/test/unit/mongo_client.test.ts @@ -5,23 +5,14 @@ import * as sinon from 'sinon'; import { Writable } from 'stream'; import { inspect } from 'util'; -import { - MongoAPIError, - MongoClient, - type MongoClientOptions, - MongoCredentials, - MongoInvalidArgumentError, - MongoLoggableComponent, - MongoLogger, - MongoParseError, - parseOptions, - ReadConcern, - ReadPreference, - resolveSRVRecord, - ServerApiVersion, - SeverityLevel, - WriteConcern -} from '../mongodb'; +import { MongoCredentials } from '../../src/cmap/auth/mongo_credentials'; +import { parseOptions, resolveSRVRecord } from '../../src/connection_string'; +import { MongoAPIError, MongoInvalidArgumentError, MongoParseError } from '../../src/error'; +import { MongoClient, type MongoClientOptions, ServerApiVersion } from '../../src/mongo_client'; +import { MongoLoggableComponent, MongoLogger, SeverityLevel } from '../../src/mongo_logger'; +import { ReadConcern } from '../../src/read_concern'; +import { ReadPreference } from '../../src/read_preference'; +import { WriteConcern } from '../../src/write_concern'; describe('MongoClient', function () { it('programmatic options should override URI options', function () { diff --git a/test/unit/mongo_logger.test.ts b/test/unit/mongo_logger.test.ts index da47bd8399c..c3b1aaec46b 100644 --- a/test/unit/mongo_logger.test.ts +++ b/test/unit/mongo_logger.test.ts @@ -18,7 +18,9 @@ import { CONNECTION_POOL_CLOSED, CONNECTION_POOL_CREATED, CONNECTION_POOL_READY, - CONNECTION_READY, + CONNECTION_READY +} from '../../src/constants'; +import { createStdioLogger, DEFAULT_MAX_DOCUMENT_LENGTH, type Log, @@ -29,7 +31,7 @@ import { parseSeverityFromString, SeverityLevel, stringifyWithMaxLen -} from '../mongodb'; +} from '../../src/mongo_logger'; import { sleep } from '../tools/utils'; class BufferingStream extends Writable { diff --git a/test/unit/operations/aggregate.test.js b/test/unit/operations/aggregate.test.js index 363572e8362..f6aa95f5056 100644 --- a/test/unit/operations/aggregate.test.js +++ b/test/unit/operations/aggregate.test.js @@ -1,7 +1,7 @@ 'use strict'; const { expect } = require('chai'); -const { AggregateOperation } = require('../../mongodb'); +const { AggregateOperation } = require('../../../src/operations/aggregate'); describe('AggregateOperation', function () { const db = 'test'; diff --git a/test/unit/operations/client_bulk_write/command_builder.test.ts b/test/unit/operations/client_bulk_write/command_builder.test.ts index ef3cc6f0b0a..d19caf1d0d2 100644 --- a/test/unit/operations/client_bulk_write/command_builder.test.ts +++ b/test/unit/operations/client_bulk_write/command_builder.test.ts @@ -1,5 +1,7 @@ +import { ObjectId } from 'bson'; import { expect } from 'chai'; +import { DocumentSequence } from '../../../../src/cmap/commands'; import { buildDeleteManyOperation, buildDeleteOneOperation, @@ -7,17 +9,17 @@ import { buildReplaceOneOperation, buildUpdateManyOperation, buildUpdateOneOperation, - ClientBulkWriteCommandBuilder, + ClientBulkWriteCommandBuilder +} from '../../../../src/operations/client_bulk_write/command_builder'; +import { type ClientDeleteManyModel, type ClientDeleteOneModel, type ClientInsertOneModel, type ClientReplaceOneModel, type ClientUpdateManyModel, - type ClientUpdateOneModel, - DEFAULT_PK_FACTORY, - DocumentSequence, - ObjectId -} from '../../../mongodb'; + type ClientUpdateOneModel +} from '../../../../src/operations/client_bulk_write/common'; +import { DEFAULT_PK_FACTORY } from '../../../../src/utils'; describe('ClientBulkWriteCommandBuilder', function () { describe('#buildBatch', function () { diff --git a/test/unit/operations/client_bulk_write/results_merger.test.ts b/test/unit/operations/client_bulk_write/results_merger.test.ts index d1ec999d059..cfe3da67fbb 100644 --- a/test/unit/operations/client_bulk_write/results_merger.test.ts +++ b/test/unit/operations/client_bulk_write/results_merger.test.ts @@ -1,13 +1,9 @@ +import { BSON, type Document, Long } from 'bson'; import { expect } from 'chai'; -import { - BSON, - ClientBulkWriteCursorResponse, - type ClientBulkWriteResult, - ClientBulkWriteResultsMerger, - type Document, - Long -} from '../../../mongodb'; +import { ClientBulkWriteCursorResponse } from '../../../../src/cmap/wire_protocol/responses'; +import { type ClientBulkWriteResult } from '../../../../src/operations/client_bulk_write/common'; +import { ClientBulkWriteResultsMerger } from '../../../../src/operations/client_bulk_write/results_merger'; class MockCursor { operations: Document[]; diff --git a/test/unit/operations/find.test.ts b/test/unit/operations/find.test.ts index 81ab4f16718..883588535ea 100644 --- a/test/unit/operations/find.test.ts +++ b/test/unit/operations/find.test.ts @@ -1,7 +1,8 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -import { FindOperation, ns } from '../../mongodb'; +import { FindOperation } from '../../../src/operations/find'; +import { ns } from '../../../src/utils'; describe('FindOperation', function () { const namespace = ns('db.coll'); diff --git a/test/unit/operations/get_more.test.ts b/test/unit/operations/get_more.test.ts index 9f2245f77fb..3599e79cde4 100644 --- a/test/unit/operations/get_more.test.ts +++ b/test/unit/operations/get_more.test.ts @@ -1,14 +1,12 @@ +import { Long } from 'bson'; import { expect } from 'chai'; -import { - Aspect, - GetMoreOperation, - Long, - ns, - ReadPreference, - Server, - ServerDescription -} from '../../mongodb'; +import { GetMoreOperation } from '../../../src/operations/get_more'; +import { Aspect } from '../../../src/operations/operation'; +import { ReadPreference } from '../../../src/read_preference'; +import { Server } from '../../../src/sdam/server'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { ns } from '../../../src/utils'; import { topologyWithPlaceholderClient } from '../../tools/utils'; describe('GetMoreOperation', function () { diff --git a/test/unit/operations/indexes.test.ts b/test/unit/operations/indexes.test.ts index 8083cb5a6c5..cbb9de56ce8 100644 --- a/test/unit/operations/indexes.test.ts +++ b/test/unit/operations/indexes.test.ts @@ -3,9 +3,9 @@ import { expect } from 'chai'; import { CreateIndexesOperation, type CreateIndexesOptions, - type IndexDirection, - ns -} from '../../mongodb'; + type IndexDirection +} from '../../../src/operations/indexes'; +import { ns } from '../../../src/utils'; describe('class CreateIndexesOperation', () => { const testCases = [ diff --git a/test/unit/operations/kill_cursors.test.ts b/test/unit/operations/kill_cursors.test.ts index f732ab04270..f1c5e8ac708 100644 --- a/test/unit/operations/kill_cursors.test.ts +++ b/test/unit/operations/kill_cursors.test.ts @@ -1,13 +1,10 @@ +import { Long } from 'bson'; import { expect } from 'chai'; -import { - KillCursorsOperation, - Long, - MongoDBNamespace, - ns, - Server, - ServerDescription -} from '../../mongodb'; +import { KillCursorsOperation } from '../../../src/operations/kill_cursors'; +import { Server } from '../../../src/sdam/server'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { MongoDBNamespace, ns } from '../../../src/utils'; import { topologyWithPlaceholderClient } from '../../tools/utils'; describe('class KillCursorsOperation', () => { diff --git a/test/unit/operations/list_collections.test.js b/test/unit/operations/list_collections.test.js index 3e5d12991d0..46a91e46e1d 100644 --- a/test/unit/operations/list_collections.test.js +++ b/test/unit/operations/list_collections.test.js @@ -1,7 +1,8 @@ 'use strict'; const { expect } = require('chai'); -const { ListCollectionsOperation, StreamDescription } = require('../../mongodb'); +const { StreamDescription } = require('../../../src/cmap/stream_description'); +const { ListCollectionsOperation } = require('../../../src/operations/list_collections'); describe('ListCollectionsOperation', function () { const db = 'test'; diff --git a/test/unit/operations/list_databases.test.ts b/test/unit/operations/list_databases.test.ts index b5f49f4b0aa..7daf7eb3d14 100644 --- a/test/unit/operations/list_databases.test.ts +++ b/test/unit/operations/list_databases.test.ts @@ -1,6 +1,7 @@ import { expect } from 'chai'; -import { ListDatabasesOperation, MongoDBNamespace } from '../../mongodb'; +import { ListDatabasesOperation } from '../../../src/operations/list_databases'; +import { MongoDBNamespace } from '../../../src/utils'; const mockDB = { s: { diff --git a/test/unit/read_preference.test.ts b/test/unit/read_preference.test.ts index 2744e8cf774..4dbcd91517f 100644 --- a/test/unit/read_preference.test.ts +++ b/test/unit/read_preference.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; -import { ReadPreference } from '../mongodb'; +import { ReadPreference } from '../../src/read_preference'; describe('class ReadPreference', function () { const maxStalenessSeconds = 1234; diff --git a/test/unit/sdam/monitor.test.ts b/test/unit/sdam/monitor.test.ts index ef3cc98674e..07de7d84ddf 100644 --- a/test/unit/sdam/monitor.test.ts +++ b/test/unit/sdam/monitor.test.ts @@ -1,27 +1,24 @@ import { once } from 'node:events'; import * as net from 'node:net'; +import { Long, ObjectId } from 'bson'; import { expect } from 'chai'; import { satisfies } from 'semver'; import * as sinon from 'sinon'; import { setTimeout } from 'timers'; import { setTimeout as setTimeoutPromise } from 'timers/promises'; +import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; +import { MongoClient } from '../../../src/mongo_client'; +import { ServerType } from '../../../src/sdam/common'; import { - isHello, - LEGACY_HELLO_COMMAND, - Long, - MongoClient, - Monitor, - MonitorInterval, - ObjectId, - RTTSampler, - ServerDescription, type ServerHeartbeatFailedEvent, type ServerHeartbeatStartedEvent, - ServerHeartbeatSucceededEvent, - ServerType -} from '../../mongodb'; + ServerHeartbeatSucceededEvent +} from '../../../src/sdam/events'; +import { Monitor, MonitorInterval, RTTSampler } from '../../../src/sdam/monitor'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { isHello } from '../../../src/utils'; import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; import { createTimerSandbox } from '../timer_sandbox'; diff --git a/test/unit/sdam/server.test.ts b/test/unit/sdam/server.test.ts index 399fb5bb50b..4f4c9588d5a 100644 --- a/test/unit/sdam/server.test.ts +++ b/test/unit/sdam/server.test.ts @@ -1,20 +1,19 @@ /* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { ObjectId } from 'bson'; import { expect } from 'chai'; import { once } from 'events'; import * as sinon from 'sinon'; +import { type Connection } from '../../../src/cmap/connection'; import { - type Connection, MongoError, MongoErrorLabel, MongoNetworkError, - MongoNetworkTimeoutError, - ObjectId, - Server, - ServerDescription, - ServerType, - TopologyType -} from '../../mongodb'; + MongoNetworkTimeoutError +} from '../../../src/error'; +import { ServerType, TopologyType } from '../../../src/sdam/common'; +import { Server } from '../../../src/sdam/server'; +import { ServerDescription } from '../../../src/sdam/server_description'; import { sleep, topologyWithPlaceholderClient } from '../../tools/utils'; const handledErrors = [ diff --git a/test/unit/sdam/server_description.test.ts b/test/unit/sdam/server_description.test.ts index 14c3ae0dbda..ac2edd7c5c2 100644 --- a/test/unit/sdam/server_description.test.ts +++ b/test/unit/sdam/server_description.test.ts @@ -1,13 +1,12 @@ +import { Long, ObjectId } from 'bson'; import { expect } from 'chai'; +import { MongoRuntimeError } from '../../../src/error'; import { compareTopologyVersion, - Long, - MongoRuntimeError, - ObjectId, ServerDescription, type TopologyVersion -} from '../../mongodb'; +} from '../../../src/sdam/server_description'; describe('ServerDescription', function () { describe('constructor()', () => { diff --git a/test/unit/sdam/server_discovery_and_monitoring.prose.test.ts b/test/unit/sdam/server_discovery_and_monitoring.prose.test.ts index debd4a233a4..d7a76e1eaa1 100644 --- a/test/unit/sdam/server_discovery_and_monitoring.prose.test.ts +++ b/test/unit/sdam/server_discovery_and_monitoring.prose.test.ts @@ -2,7 +2,8 @@ import { expect } from 'chai'; import { once } from 'events'; import { createServer, type Server } from 'net'; -import { MongoClient, SERVER_HEARTBEAT_FAILED, SERVER_HEARTBEAT_STARTED } from '../../mongodb'; +import { SERVER_HEARTBEAT_FAILED, SERVER_HEARTBEAT_STARTED } from '../../../src/constants'; +import { MongoClient } from '../../../src/mongo_client'; describe('Heartbeat tests', function () { let client: MongoClient; diff --git a/test/unit/sdam/server_selection.test.ts b/test/unit/sdam/server_selection.test.ts index b372178479f..4c0a45985de 100644 --- a/test/unit/sdam/server_selection.test.ts +++ b/test/unit/sdam/server_selection.test.ts @@ -1,19 +1,19 @@ +import { ObjectId } from 'bson'; import { expect } from 'chai'; import * as sinon from 'sinon'; +import { MongoLogger } from '../../../src/mongo_logger'; +import { ReadPreference } from '../../../src/read_preference'; +import { TopologyType } from '../../../src/sdam/common'; +import { ServerDescription } from '../../../src/sdam/server_description'; import { MIN_SECONDARY_WRITE_WIRE_VERSION, - MongoLogger, - ObjectId, - ReadPreference, readPreferenceServerSelector, sameServerSelector, - secondaryWritableServerSelector, - ServerDescription, - ServerSelectionEvent, - TopologyDescription, - TopologyType -} from '../../mongodb'; + secondaryWritableServerSelector +} from '../../../src/sdam/server_selection'; +import { ServerSelectionEvent } from '../../../src/sdam/server_selection_events'; +import { TopologyDescription } from '../../../src/sdam/topology_description'; import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; diff --git a/test/unit/sdam/srv_polling.test.ts b/test/unit/sdam/srv_polling.test.ts index 908c5bf8013..f38dfd646de 100644 --- a/test/unit/sdam/srv_polling.test.ts +++ b/test/unit/sdam/srv_polling.test.ts @@ -4,14 +4,11 @@ import { EventEmitter, once } from 'events'; import * as sinon from 'sinon'; import { clearTimeout } from 'timers'; -import { - MongoDriverError, - SrvPoller, - SrvPollingEvent, - TopologyDescription, - TopologyType -} from '../../mongodb'; -import * as sdamEvents from '../../mongodb'; +import { MongoDriverError } from '../../../src/error'; +import { TopologyType } from '../../../src/sdam/common'; +import { TopologyDescriptionChangedEvent } from '../../../src/sdam/events'; +import { SrvPoller, SrvPollingEvent } from '../../../src/sdam/srv_polling'; +import { TopologyDescription } from '../../../src/sdam/topology_description'; import { topologyWithPlaceholderClient } from '../../tools/utils'; describe('Mongos SRV Polling', function () { @@ -243,7 +240,7 @@ describe('Mongos SRV Polling', function () { function emit(prev, current) { topology.emit( 'topologyDescriptionChanged', - new sdamEvents.TopologyDescriptionChangedEvent(topology.s.id, prev, current) + new TopologyDescriptionChangedEvent(topology.s.id, prev, current) ); } diff --git a/test/unit/sdam/topology.test.ts b/test/unit/sdam/topology.test.ts index 444ff7d3e86..8fac7f52ee9 100644 --- a/test/unit/sdam/topology.test.ts +++ b/test/unit/sdam/topology.test.ts @@ -6,25 +6,25 @@ import { satisfies } from 'semver'; import * as sinon from 'sinon'; import { clearTimeout } from 'timers'; +import { makeClientMetadata } from '../../../src/cmap/handshake/client_metadata'; import { - isHello, LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, - makeClientMetadata, - MongoClient, - MongoServerSelectionError, - ns, - ReadPreference, + MongoServerSelectionError +} from '../../../src/error'; +import { MongoClient } from '../../../src/mongo_client'; +import { RunCommandOperation, - RunCursorCommandOperation, - Server, - SrvPoller, - SrvPollingEvent, - TimeoutContext, - Topology, - TopologyDescription, - TopologyDescriptionChangedEvent, - TopologyType -} from '../../mongodb'; + RunCursorCommandOperation +} from '../../../src/operations/run_command'; +import { ReadPreference } from '../../../src/read_preference'; +import { TopologyType } from '../../../src/sdam/common'; +import { TopologyDescriptionChangedEvent } from '../../../src/sdam/events'; +import { Server } from '../../../src/sdam/server'; +import { SrvPoller, SrvPollingEvent } from '../../../src/sdam/srv_polling'; +import { Topology } from '../../../src/sdam/topology'; +import { TopologyDescription } from '../../../src/sdam/topology_description'; +import { TimeoutContext } from '../../../src/timeout'; +import { isHello, ns } from '../../../src/utils'; import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; @@ -95,7 +95,7 @@ describe('Topology (unit)', function () { afterEach(() => mock.cleanup()); - it('should time out operations against servers that have been blackholed', function (done) { + it('should time out operations against servers that have been blackholed', async function () { mockServer.setMessageHandler(request => { const doc = request.document; @@ -109,30 +109,22 @@ describe('Topology (unit)', function () { }); const topology = topologyWithPlaceholderClient(mockServer.hostAddress(), {}); - topology.connect().then(() => { - const ctx = TimeoutContext.create({ - waitQueueTimeoutMS: 0, - serverSelectionTimeoutMS: 0, - socketTimeoutMS: 250 - }); - topology - .selectServer('primary', { - timeoutContext: ctx - }) - .then(server => { - server - .command(new RunCursorCommandOperation(ns('admin.$cmd'), { ping: 1 }, {}), ctx) - .then( - () => expect.fail('expected command to fail'), - err => { - expect(err).to.exist; - expect(err).to.match(/timed out/); - topology.close(); - done(); - } - ); - }, expect.fail); - }, expect.fail); + await topology.connect(); + const ctx = TimeoutContext.create({ + waitQueueTimeoutMS: 0, + serverSelectionTimeoutMS: 0, + socketTimeoutMS: 250 + }); + const server = await topology.selectServer('primary', { + timeoutContext: ctx, + operationName: 'none' + }); + const err = await server + .command(new RunCursorCommandOperation(ns('admin.$cmd'), { ping: 1 }, {}), ctx) + .catch(e => e); + expect(err).to.exist; + expect(err).to.match(/timed out/); + topology.close(); }); }); diff --git a/test/unit/sessions.test.ts b/test/unit/sessions.test.ts index 128e1b08e4b..1c6c31ab237 100644 --- a/test/unit/sessions.test.ts +++ b/test/unit/sessions.test.ts @@ -1,18 +1,11 @@ +import { BSON, Long } from 'bson'; import { expect } from 'chai'; import * as sinon from 'sinon'; -import { - applySession, - BSON, - ClientSession, - isHello, - Long, - MongoClient, - MongoRuntimeError, - now, - ServerSession, - ServerSessionPool -} from '../mongodb'; +import { MongoRuntimeError } from '../../src/error'; +import { MongoClient } from '../../src/mongo_client'; +import { applySession, ClientSession, ServerSession, ServerSessionPool } from '../../src/sessions'; +import { isHello, now } from '../../src/utils'; import { genClusterTime } from '../tools/common'; import * as mock from '../tools/mongodb-mock/index'; @@ -497,7 +490,7 @@ describe('Sessions - unit', function () { expect(() => new ServerSessionPool()).to.throw(MongoRuntimeError); }); - it('should create a new session if the pool is empty', function (done) { + it('should create a new session if the pool is empty', function () { const pool = new ServerSessionPool(client); expect(pool.sessions).to.have.length(0); @@ -505,11 +498,9 @@ describe('Sessions - unit', function () { expect(session).to.exist; expect(pool.sessions).to.have.length(0); pool.release(session); - - done(); }); - it('should reuse sessions which have not timed out yet on acquire', function (done) { + it('should reuse sessions which have not timed out yet on acquire', function () { const oldSession = new ServerSession(); const pool = new ServerSessionPool(client); pool.sessions.push(oldSession); @@ -518,11 +509,9 @@ describe('Sessions - unit', function () { expect(session).to.exist; expect(session).to.eql(oldSession); pool.release(session); - - done(); }); - it('should remove sessions which have timed out on acquire, and return a fresh session', function (done) { + it('should remove sessions which have timed out on acquire, and return a fresh session', function () { const oldSession = new ServerSession(); oldSession.lastUse = now() - 30 * 60 * 1000; // add 30min @@ -533,8 +522,6 @@ describe('Sessions - unit', function () { expect(session).to.exist; expect(session).to.not.eql(oldSession); pool.release(session); - - done(); }); describe('release()', () => { @@ -614,7 +601,7 @@ describe('Sessions - unit', function () { }); }); - it('should not reintroduce a soon-to-expire session to the pool on release', function (done) { + it('should not reintroduce a soon-to-expire session to the pool on release', function () { const session = new ServerSession(); session.lastUse = now() - 9.5 * 60 * 1000; // add 9.5min @@ -622,10 +609,9 @@ describe('Sessions - unit', function () { pool.release(session); expect(pool.sessions).to.have.length(0); - done(); }); - it('should maintain a LIFO queue of sessions', function (done) { + it('should maintain a LIFO queue of sessions', function () { const pool = new ServerSessionPool(client); const sessionA = new ServerSession(); @@ -642,7 +628,6 @@ describe('Sessions - unit', function () { pool.release(sessionC); pool.release(sessionD); - done(); }); }); }); diff --git a/test/unit/timeout.test.ts b/test/unit/timeout.test.ts index 1dd7e83feb5..eca9681ac5b 100644 --- a/test/unit/timeout.test.ts +++ b/test/unit/timeout.test.ts @@ -1,14 +1,13 @@ import { expect } from 'chai'; +import { MongoInvalidArgumentError, MongoRuntimeError } from '../../src/error'; import { CSOTTimeoutContext, LegacyTimeoutContext, - MongoInvalidArgumentError, - MongoRuntimeError, Timeout, TimeoutContext, TimeoutError -} from '../mongodb'; +} from '../../src/timeout'; describe('Timeout', function () { let timeout: Timeout; diff --git a/test/unit/tools/unified_spec_runner/entity_event_registry.test.ts b/test/unit/tools/unified_spec_runner/entity_event_registry.test.ts index 8457ff4026b..0fd3bb08224 100644 --- a/test/unit/tools/unified_spec_runner/entity_event_registry.test.ts +++ b/test/unit/tools/unified_spec_runner/entity_event_registry.test.ts @@ -15,7 +15,7 @@ import { CONNECTION_POOL_CREATED, CONNECTION_POOL_READY, CONNECTION_READY -} from '../../../mongodb'; +} from '../../../../src/constants'; import { EntitiesMap, UnifiedMongoClient } from '../../../tools/unified-spec-runner/entities'; import { EntityEventRegistry } from '../../../tools/unified-spec-runner/entity_event_registry'; diff --git a/test/unit/transactions.test.ts b/test/unit/transactions.test.ts index 789c0b1cb6f..09b0e91038e 100644 --- a/test/unit/transactions.test.ts +++ b/test/unit/transactions.test.ts @@ -1,6 +1,7 @@ import { expect } from 'chai'; -import { ReadPreference, Transaction } from '../mongodb'; +import { ReadPreference } from '../../src/read_preference'; +import { Transaction } from '../../src/transactions'; describe('class Transaction', () => { describe('constructor()', () => { diff --git a/test/unit/utils.test.ts b/test/unit/utils.test.ts index 6fa7e9784af..dc393fe0990 100644 --- a/test/unit/utils.test.ts +++ b/test/unit/utils.test.ts @@ -1,30 +1,28 @@ import { setTimeout } from 'node:timers'; +import { ObjectId } from 'bson'; import { expect } from 'chai'; import * as sinon from 'sinon'; +import { LEGACY_HELLO_COMMAND } from '../../src/constants'; +import { MongoInvalidArgumentError, MongoRuntimeError } from '../../src/error'; +import { decorateWithExplain, Explain } from '../../src/explain'; import { abortable, BufferPool, ByteUtils, checkParentDomainMatch, compareObjectId, - decorateWithExplain, - Explain, hasAtomicOperators, HostAddress, hostMatchesWildcards, isHello, isUint8Array, - LEGACY_HELLO_COMMAND, List, MongoDBCollectionNamespace, MongoDBNamespace, - MongoInvalidArgumentError, - MongoRuntimeError, - ObjectId, shuffle -} from '../mongodb'; +} from '../../src/utils'; import { sleep } from '../tools/utils'; describe('driver utils', function () { diff --git a/test/unit/write_concern.test.ts b/test/unit/write_concern.test.ts index 0f59a2c3b04..420c6dce14c 100644 --- a/test/unit/write_concern.test.ts +++ b/test/unit/write_concern.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; -import { WriteConcern } from '../mongodb'; +import { WriteConcern } from '../../src/write_concern'; describe('WriteConcern', function () { describe('#constructor', function () {