From 1dc105071a120d203d92642e62b9911b3653b94a Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Thu, 18 Sep 2025 09:17:00 -0700 Subject: [PATCH 01/25] test(NODE-7160): migrate `node-mongodb-native/test/unit/assorted` tests --- .eslintrc.json | 2 - test/benchmarks/unitBench/list.bench.js | 3 +- test/integration/auth/mongodb_aws.test.ts | 1 - ...nt_side_encryption.prose.06.corpus.test.ts | 1 - ..._side_encryption.prose.12.deadlock.test.ts | 1 - ...ryption.prose.14.decryption_events.test.ts | 1 - ..._encryption.prose.17.on_demand_gcp.test.ts | 1 - ...ion.prose.18.azure_kms_mock_server.test.ts | 2 - ...ncryption.prose.19.on_demand_azure.test.ts | 2 - ....21.automatic_data_encryption_keys.test.ts | 2 - ...prose.22.range_explicit_encryption.test.ts | 2 - ...prose.23.range_encryption_defaults.test.ts | 1 - ...26.custom_aws_credential_providers.test.ts | 1 - .../client_side_encryption.prose.test.ts | 1 - .../client-side-encryption/driver.test.ts | 1 - ...lient_side_operations_timeout.unit.test.ts | 1 - .../node-specific/client_encryption.test.ts | 3 - test/mongodb.ts | 1 - test/tools/fixtures/shared_library_test.js | 5 +- .../unified-spec-runner/unified-utils.ts | 1 - test/unit/assorted/client.test.js | 4 +- test/unit/assorted/collations.test.js | 6 +- test/unit/assorted/max_staleness.spec.test.js | 7 +- test/unit/assorted/optional_require.test.ts | 14 +- ...records_for_mongos_discovery.prose.test.ts | 20 +-- test/unit/assorted/scram_iterations.test.ts | 11 +- ...rver_discovery_and_monitoring.spec.test.ts | 41 ++--- .../server_discovery_and_monitoring.test.ts | 16 +- .../assorted/server_selection.spec.test.ts | 2 +- .../server_selection_latency_window_utils.ts | 12 +- .../server_selection_logic_spec_utils.ts | 14 +- .../assorted/server_selection_spec_helper.js | 19 +- test/unit/assorted/sessions_client.test.js | 167 +++++++++--------- .../unit/assorted/sessions_collection.test.js | 4 +- test/unit/assorted/wire_version.test.ts | 9 +- test/unit/assorted/write_concern.test.js | 9 +- .../auto_encrypter.test.ts | 4 - .../client_encryption.test.ts | 4 - .../client-side-encryption/errors.test.ts | 1 - .../mongocryptd_manager.test.ts | 1 - .../providers/credentialsProvider.test.ts | 5 - .../requirements.helper.ts | 1 - .../state_machine.test.ts | 2 - .../automated_callback_workflow.test.ts | 2 - .../azure_machine_workflow.test.ts | 1 - .../mongodb_oidc/gcp_machine_workflow.test.ts | 1 - .../token_machine_workflow.test.ts | 1 - test/unit/commands.test.ts | 1 - test/unit/error.test.ts | 2 - test/unit/index.test.ts | 1 - 50 files changed, 169 insertions(+), 246 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index adf89319dca..59b2beaa206 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -178,7 +178,6 @@ { "patterns": [ "**/../lib/**", - "**/../src/**", "mongodb-mock-server" ] } @@ -217,7 +216,6 @@ { "patterns": [ "**/../lib/**", - "**/../src/**", "mongodb-mock-server" ] } diff --git a/test/benchmarks/unitBench/list.bench.js b/test/benchmarks/unitBench/list.bench.js index 025e531275e..7e1a8fba4c5 100644 --- a/test/benchmarks/unitBench/list.bench.js +++ b/test/benchmarks/unitBench/list.bench.js @@ -1,6 +1,5 @@ -/* eslint-disable no-restricted-modules */ const chalk = require('chalk'); -const { List } = require('../../../lib/utils'); +const { List } = require('../../../src/utils'); const { createHistogram } = require('perf_hooks'); const iterations = 100; diff --git a/test/integration/auth/mongodb_aws.test.ts b/test/integration/auth/mongodb_aws.test.ts index e65b9c60bda..18951514071 100644 --- a/test/integration/auth/mongodb_aws.test.ts +++ b/test/integration/auth/mongodb_aws.test.ts @@ -5,7 +5,6 @@ import * as http from 'http'; import { performance } from 'perf_hooks'; import * as sinon from 'sinon'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { refreshKMSCredentials } from '../../../src/client-side-encryption/providers'; import { AWSTemporaryCredentialProvider, diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.06.corpus.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.06.corpus.test.ts index c90ec8e888e..41c7c8cb94c 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.06.corpus.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.06.corpus.test.ts @@ -5,7 +5,6 @@ import { expect } from 'chai'; import * as fs from 'fs'; import * as path from 'path'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { getCSFLEKMSProviders } from '../../csfle-kms-providers'; import { type MongoClient, WriteConcern } from '../../mongodb'; diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.12.deadlock.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.12.deadlock.test.ts index 972bbb80f37..1c54b136c24 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.12.deadlock.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.12.deadlock.test.ts @@ -3,7 +3,6 @@ import { expect } from 'chai'; import { readFileSync } from 'fs'; import * as path from 'path'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { type CommandStartedEvent, type MongoClient, type MongoClientOptions } from '../../mongodb'; import { type TestConfiguration } from '../../tools/runner/config'; diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.14.decryption_events.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.14.decryption_events.test.ts index e3b4e4cb97e..9901cb08820 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.14.decryption_events.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.14.decryption_events.test.ts @@ -1,6 +1,5 @@ import { expect } from 'chai'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { Binary, diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.17.on_demand_gcp.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.17.on_demand_gcp.test.ts index 98c204fb2e3..566809cc2b5 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.17.on_demand_gcp.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.17.on_demand_gcp.test.ts @@ -1,7 +1,6 @@ import { expect } from 'chai'; import { env } from 'process'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { Binary } from '../../mongodb'; diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.18.azure_kms_mock_server.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.18.azure_kms_mock_server.test.ts index c99820b6f83..7b4c92ad53a 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.18.azure_kms_mock_server.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.18.azure_kms_mock_server.test.ts @@ -1,8 +1,6 @@ import { expect } from 'chai'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { MongoCryptAzureKMSRequestError } from '../../../src/client-side-encryption/errors'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { type AzureKMSRequestOptions, fetchAzureKMSToken diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.19.on_demand_azure.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.19.on_demand_azure.test.ts index aba12464f8a..b0b93d7655b 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.19.on_demand_azure.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.19.on_demand_azure.test.ts @@ -1,9 +1,7 @@ import { expect } from 'chai'; import { env } from 'process'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { MongoCryptAzureKMSRequestError } from '../../../src/client-side-encryption/errors'; import { Binary } from '../../mongodb'; diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts index f81ab73d982..24afe0e7315 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts @@ -1,8 +1,6 @@ import { expect } from 'chai'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { MongoCryptCreateEncryptedCollectionError } from '../../../src/client-side-encryption/errors'; import { getCSFLEKMSProviders, diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.22.range_explicit_encryption.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.22.range_explicit_encryption.test.ts index 3e23c685b43..08ab2bb096b 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.22.range_explicit_encryption.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.22.range_explicit_encryption.test.ts @@ -4,9 +4,7 @@ import { readFile } from 'fs/promises'; import { join } from 'path'; import { Decimal128, type Document, Double, Long, type MongoClient } from '../../../src'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { MongoCryptError } from '../../../src/client-side-encryption/errors'; import { getCSFLEKMSProviders } from '../../csfle-kms-providers'; diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.23.range_encryption_defaults.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.23.range_encryption_defaults.test.ts index ea4041f746b..c6deedc2f8d 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.23.range_encryption_defaults.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.23.range_encryption_defaults.test.ts @@ -1,6 +1,5 @@ import { expect } from 'chai'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { getCSFLEKMSProviders } from '../../csfle-kms-providers'; import { type Binary, Int32, Long } from '../../mongodb'; diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.26.custom_aws_credential_providers.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.26.custom_aws_credential_providers.test.ts index 59e32946baf..c1c3cac59d3 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.26.custom_aws_credential_providers.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.26.custom_aws_credential_providers.test.ts @@ -1,6 +1,5 @@ import { expect } from 'chai'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { AWSTemporaryCredentialProvider, Binary, MongoClient } from '../../mongodb'; import { getEncryptExtraOptions } from '../../tools/utils'; diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.test.ts index eaf1746f2b7..7d326fcaa15 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.test.ts @@ -3,7 +3,6 @@ import { expect } from 'chai'; import * as fs from 'fs/promises'; import * as path from 'path'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { getCSFLEKMSProviders } from '../../csfle-kms-providers'; import { diff --git a/test/integration/client-side-encryption/driver.test.ts b/test/integration/client-side-encryption/driver.test.ts index ffa0e69b97f..a7a5a9f8e7d 100644 --- a/test/integration/client-side-encryption/driver.test.ts +++ b/test/integration/client-side-encryption/driver.test.ts @@ -6,7 +6,6 @@ import * as sinon from 'sinon'; import { setTimeout } from 'timers/promises'; import * as tls from 'tls'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { getCSFLEKMSProviders } from '../../csfle-kms-providers'; import { diff --git a/test/integration/client-side-operations-timeout/client_side_operations_timeout.unit.test.ts b/test/integration/client-side-operations-timeout/client_side_operations_timeout.unit.test.ts index 73db0b9191d..0eef0318bac 100644 --- a/test/integration/client-side-operations-timeout/client_side_operations_timeout.unit.test.ts +++ b/test/integration/client-side-operations-timeout/client_side_operations_timeout.unit.test.ts @@ -10,7 +10,6 @@ import { setTimeout } from 'timers'; import { TLSSocket } from 'tls'; import { promisify } from 'util'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { StateMachine } from '../../../src/client-side-encryption/state_machine'; import { Connection, diff --git a/test/integration/node-specific/client_encryption.test.ts b/test/integration/node-specific/client_encryption.test.ts index d21de71a56f..90800f92903 100644 --- a/test/integration/node-specific/client_encryption.test.ts +++ b/test/integration/node-specific/client_encryption.test.ts @@ -2,14 +2,11 @@ import { expect } from 'chai'; import { readFileSync } from 'fs'; import * as sinon from 'sinon'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { ClientEncryption, type DataKey } from '../../../src/client-side-encryption/client_encryption'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { MongoCryptInvalidArgumentError } from '../../../src/client-side-encryption/errors'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { StateMachine } from '../../../src/client-side-encryption/state_machine'; import { Binary, type Collection, Int32, Long, type MongoClient, UUID } from '../../mongodb'; diff --git a/test/mongodb.ts b/test/mongodb.ts index 9c385b21c2b..4be7c6d2ce3 100644 --- a/test/mongodb.ts +++ b/test/mongodb.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-restricted-imports */ import * as fs from 'node:fs'; import * as path from 'node:path'; import * as process from 'node:process'; diff --git a/test/tools/fixtures/shared_library_test.js b/test/tools/fixtures/shared_library_test.js index e87140a4834..5a334bc98e6 100644 --- a/test/tools/fixtures/shared_library_test.js +++ b/test/tools/fixtures/shared_library_test.js @@ -1,7 +1,6 @@ -/* eslint-disable no-restricted-modules */ const { EJSON } = require('bson'); -const { AutoEncrypter } = require('../../../lib/client-side-encryption/auto_encrypter'); -const { MongoClient } = require('../../../lib/mongo_client'); +const { AutoEncrypter } = require('../../../src/client-side-encryption/auto_encrypter'); +const { MongoClient } = require('../../../src/mongo_client'); try { const extraOptions = JSON.parse(process.env.EXTRA_OPTIONS); diff --git a/test/tools/unified-spec-runner/unified-utils.ts b/test/tools/unified-spec-runner/unified-utils.ts index 79ba247f8e0..1b599a7ed9d 100644 --- a/test/tools/unified-spec-runner/unified-utils.ts +++ b/test/tools/unified-spec-runner/unified-utils.ts @@ -3,7 +3,6 @@ import ConnectionString from 'mongodb-connection-string-url'; import { coerce, gte as semverGte, lte as semverLte } from 'semver'; import { isDeepStrictEqual } from 'util'; -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { getCSFLEKMSProviders } from '../../csfle-kms-providers'; import { diff --git a/test/unit/assorted/client.test.js b/test/unit/assorted/client.test.js index 530b3931570..9d40b7decd4 100644 --- a/test/unit/assorted/client.test.js +++ b/test/unit/assorted/client.test.js @@ -2,8 +2,8 @@ const { expect } = require('chai'); const mock = require('../../tools/mongodb-mock/index'); -const { MongoClient } = require('../../mongodb'); -const { isHello } = require('../../mongodb'); +const { isHello } = require('../../../src/utils'); +const { MongoClient } = require('../../../src/mongo_client'); describe('Client (unit)', function () { let server, client; diff --git a/test/unit/assorted/collations.test.js b/test/unit/assorted/collations.test.js index 124d020afcf..6efc253c93b 100644 --- a/test/unit/assorted/collations.test.js +++ b/test/unit/assorted/collations.test.js @@ -1,9 +1,9 @@ 'use strict'; const mock = require('../../tools/mongodb-mock/index'); const { expect } = require('chai'); -const { Long } = require('../../mongodb'); -const { isHello } = require('../../mongodb'); -const { MongoClient } = require('../../mongodb'); +const { Long } = require('../../../src/bson'); +const { isHello } = require('../../../src/utils'); +const { MongoClient } = require('../../../src/mongo_client'); const testContext = {}; describe('Collation', function () { diff --git a/test/unit/assorted/max_staleness.spec.test.js b/test/unit/assorted/max_staleness.spec.test.js index f0355cb1cce..bb4b2a4d9db 100644 --- a/test/unit/assorted/max_staleness.spec.test.js +++ b/test/unit/assorted/max_staleness.spec.test.js @@ -2,7 +2,7 @@ const path = require('path'); const fs = require('fs'); const { executeServerSelectionTest } = require('./server_selection_spec_helper'); -const { Server } = require('../../mongodb'); +const { Server } = require('../../../src/sdam/server'); // src/sdam/server.ts const { EJSON } = require('bson'); @@ -47,10 +47,11 @@ describe('Max Staleness (spec)', function () { const specTests = collectStalenessTests(maxStalenessDir); for (const [specTestName, test] of Object.entries(specTests)) { describe(specTestName, () => { - for (const testData of test) + for (const testData of test) { it(testData.description, async function () { - return executeServerSelectionTest(testData); + await executeServerSelectionTest(testData); }); + } }); } }); diff --git a/test/unit/assorted/optional_require.test.ts b/test/unit/assorted/optional_require.test.ts index 83eb32cfc24..0a729d6fd4f 100644 --- a/test/unit/assorted/optional_require.test.ts +++ b/test/unit/assorted/optional_require.test.ts @@ -2,14 +2,12 @@ import { expect } from 'chai'; import { existsSync } from 'fs'; import { resolve } from 'path'; -import { - AuthContext, - compress, - GSSAPI, - HostAddress, - MongoDBAWS, - MongoMissingDependencyError -} from '../../mongodb'; +import { AuthContext } from '../../../src/cmap/auth/auth_provider'; +import { GSSAPI } from '../../../src/cmap/auth/gssapi'; +import { MongoDBAWS } from '../../../src/cmap/auth/mongodb_aws'; +import { compress } from '../../../src/cmap/wire_protocol/compression'; +import { MongoMissingDependencyError } from '../../../src/error'; +import { HostAddress } from '../../../src/utils'; function moduleExistsSync(moduleName) { return existsSync(resolve(__dirname, `../../../node_modules/${moduleName}`)); 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 8ec5cd8e29c..ae2a8116795 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 @@ -4,17 +4,11 @@ import { once } from 'events'; import { satisfies } from 'semver'; import * as sinon from 'sinon'; -import { - HostAddress, - isHello, - MongoClient, - SrvPoller, - type SrvPollerOptions, - SrvPollingEvent, - type Topology, - type TopologyOptions, - TopologyType -} from '../../mongodb'; +import { MongoClient } from '../../../src/mongo_client'; +import { TopologyType } from '../../../src/sdam/common'; +import { SrvPoller, type SrvPollerOptions, SrvPollingEvent } from '../../../src/sdam/srv_polling'; +import type { Topology, TopologyOptions } from '../../../src/sdam/topology'; +import { HostAddress, isHello } from '../../../src/utils'; import * as mock from '../../tools/mongodb-mock/index'; import type { MockServer } from '../../tools/mongodb-mock/src/server'; import { processTick, topologyWithPlaceholderClient } from '../../tools/utils'; @@ -75,10 +69,10 @@ describe('Polling Srv Records for Mongos Discovery', () => { } class FakeSrvPoller extends SrvPoller { - start() { + override start() { return; } - stop() { + override stop() { return; } trigger(srvRecords) { diff --git a/test/unit/assorted/scram_iterations.test.ts b/test/unit/assorted/scram_iterations.test.ts index 106550ae106..c28c6cf30be 100644 --- a/test/unit/assorted/scram_iterations.test.ts +++ b/test/unit/assorted/scram_iterations.test.ts @@ -1,12 +1,9 @@ import { expect } from 'chai'; -import { - isHello, - MongoClient, - MongoCredentials, - MongoNetworkError, - MongoRuntimeError -} from '../../mongodb'; +import { MongoCredentials } from '../../../src/cmap/auth/mongo_credentials'; +import { MongoNetworkError, MongoRuntimeError } from '../../../src/error'; +import { MongoClient } from '../../../src/mongo_client'; +import { isHello } from '../../../src/utils'; import * as mock from '../../tools/mongodb-mock/index'; describe('SCRAM Iterations Tests', function () { diff --git a/test/unit/assorted/server_discovery_and_monitoring.spec.test.ts b/test/unit/assorted/server_discovery_and_monitoring.spec.test.ts index d4df5685f7d..62a545417bb 100644 --- a/test/unit/assorted/server_discovery_and_monitoring.spec.test.ts +++ b/test/unit/assorted/server_discovery_and_monitoring.spec.test.ts @@ -1,42 +1,43 @@ -import { EJSON, ObjectId } from 'bson'; +import { type Document, EJSON, ObjectId } from 'bson'; import { expect } from 'chai'; import * as fs from 'fs'; import * as path from 'path'; import * as sinon from 'sinon'; +import { ConnectionPool } from '../../../src/cmap/connection_pool'; import { - ConnectionPool, HEARTBEAT_EVENTS, - isRecord, - MongoClient, + SERVER_CLOSED, + SERVER_DESCRIPTION_CHANGED, + SERVER_OPENING, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + TOPOLOGY_OPENING +} from '../../../src/constants'; +import { MongoCompatibilityError, MongoError, MongoNetworkError, MongoNetworkTimeoutError, - MongoServerError, - ns, - RunCommandOperation, - Server, - SERVER_CLOSED, - SERVER_DESCRIPTION_CHANGED, - SERVER_OPENING, + MongoServerError +} from '../../../src/error'; +import { MongoClient } from '../../../src/mongo_client'; +import { RunCommandOperation } from '../../../src/operations/run_command'; +import { ServerClosedEvent, - ServerDescription, ServerDescriptionChangedEvent, ServerHeartbeatFailedEvent, ServerHeartbeatStartedEvent, ServerHeartbeatSucceededEvent, ServerOpeningEvent, - squashError, - Topology, - TOPOLOGY_CLOSED, - TOPOLOGY_DESCRIPTION_CHANGED, - TOPOLOGY_OPENING, TopologyClosedEvent, TopologyDescriptionChangedEvent, - TopologyOpeningEvent, - type TopologyVersion -} from '../../mongodb'; + TopologyOpeningEvent +} from '../../../src/sdam/events'; +import { Server } from '../../../src/sdam/server'; +import { ServerDescription, type TopologyVersion } from '../../../src/sdam/server_description'; +import { Topology } from '../../../src/sdam/topology'; +import { isRecord, ns, squashError } from '../../../src/utils'; import { ejson } from '../../tools/utils'; const SDAM_EVENT_CLASSES = { diff --git a/test/unit/assorted/server_discovery_and_monitoring.test.ts b/test/unit/assorted/server_discovery_and_monitoring.test.ts index 1c58591fb85..2f6e312594f 100644 --- a/test/unit/assorted/server_discovery_and_monitoring.test.ts +++ b/test/unit/assorted/server_discovery_and_monitoring.test.ts @@ -1,15 +1,13 @@ +import { ObjectId } from 'bson'; import { expect } from 'chai'; -import { type TopologyDescription } from 'mongodb-legacy'; import * as sinon from 'sinon'; -import { - MongoClient, - ObjectId, - Server, - ServerDescription, - Topology, - type TopologyDescriptionChangedEvent -} from '../../mongodb'; +import { MongoClient } from '../../../src/mongo_client'; +import { type TopologyDescriptionChangedEvent } from '../../../src/sdam/events'; +import { Server } from '../../../src/sdam/server'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { Topology } from '../../../src/sdam/topology'; +import { type TopologyDescription } from '../../../src/sdam/topology_description'; describe('Server Discovery and Monitoring', function () { let serverConnect: sinon.SinonStub; diff --git a/test/unit/assorted/server_selection.spec.test.ts b/test/unit/assorted/server_selection.spec.test.ts index 44707aa7580..46ce5bbd677 100644 --- a/test/unit/assorted/server_selection.spec.test.ts +++ b/test/unit/assorted/server_selection.spec.test.ts @@ -1,7 +1,7 @@ import { join, resolve } from 'path'; import * as sinon from 'sinon'; -import { Server } from '../../mongodb'; +import { Server } from '../../../src/sdam/server'; import { loadLatencyWindowTests, runServerSelectionLatencyWindowTest diff --git a/test/unit/assorted/server_selection_latency_window_utils.ts b/test/unit/assorted/server_selection_latency_window_utils.ts index 9aa8dd24818..da4e8463569 100644 --- a/test/unit/assorted/server_selection_latency_window_utils.ts +++ b/test/unit/assorted/server_selection_latency_window_utils.ts @@ -3,14 +3,10 @@ import { expect } from 'chai'; import { readdirSync, readFileSync } from 'fs'; import { join } from 'path'; -import { - ReadPreference, - type Server, - type ServerType, - STATE_CONNECTED, - type Topology, - type TopologyType -} from '../../mongodb'; +import { ReadPreference } from '../../../src/read_preference'; +import { type ServerType, STATE_CONNECTED, type TopologyType } from '../../../src/sdam/common'; +import { type Server } from '../../../src/sdam/server'; +import { type Topology } from '../../../src/sdam/topology'; import { topologyWithPlaceholderClient } from '../../tools/utils'; import { serverDescriptionFromDefinition } from './server_selection_spec_helper'; diff --git a/test/unit/assorted/server_selection_logic_spec_utils.ts b/test/unit/assorted/server_selection_logic_spec_utils.ts index d489c682102..62a31fba189 100644 --- a/test/unit/assorted/server_selection_logic_spec_utils.ts +++ b/test/unit/assorted/server_selection_logic_spec_utils.ts @@ -6,15 +6,15 @@ import { basename, extname, join } from 'path'; import { ReadPreference, type ReadPreferenceMode, - type ReadPreferenceOptions, + type ReadPreferenceOptions +} from '../../../src/read_preference'; +import { type ServerType, type TopologyType } from '../../../src/sdam/common'; +import { type ServerDescription, type TagSet } from '../../../src/sdam/server_description'; +import { readPreferenceServerSelector, - type ServerDescription, - type ServerType, - type TagSet, - TopologyDescription, - type TopologyType, writableServerSelector -} from '../../mongodb'; +} from '../../../src/sdam/server_selection'; +import { TopologyDescription } from '../../../src/sdam/topology_description'; import { serverDescriptionFromDefinition } from './server_selection_spec_helper'; interface ServerSelectionLogicTestServer { diff --git a/test/unit/assorted/server_selection_spec_helper.js b/test/unit/assorted/server_selection_spec_helper.js index 20bcea87a23..0dccbeb7446 100644 --- a/test/unit/assorted/server_selection_spec_helper.js +++ b/test/unit/assorted/server_selection_spec_helper.js @@ -1,16 +1,17 @@ 'use strict'; -const { Topology } = require('../../mongodb'); -const { ServerType, TopologyType } = require('../../mongodb'); -const { ServerDescription } = require('../../mongodb'); -const { ReadPreference } = require('../../mongodb'); -const { MongoServerSelectionError } = require('../../mongodb'); -const ServerSelectors = require('../../mongodb'); + +import { MongoServerSelectionError } from '../../../src/error'; +import { ReadPreference } from '../../../src/read_preference'; +import { ServerType, TopologyType } from '../../../src/sdam/common'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import * as ServerSelectors from '../../../src/sdam/server_selection'; // src/sdam/server_selection.ts +import { Topology } from '../../../src/sdam/topology'; const sinon = require('sinon'); const { expect } = require('chai'); const { topologyWithPlaceholderClient } = require('../../tools/utils'); -function serverDescriptionFromDefinition(definition, hosts) { +export function serverDescriptionFromDefinition(definition, hosts) { hosts = hosts || []; const serverType = definition.type; @@ -80,7 +81,7 @@ function readPreferenceFromDefinition(definition) { return new ReadPreference(mode, tags, options); } -async function executeServerSelectionTest(testDefinition) { +export async function executeServerSelectionTest(testDefinition) { const topologyDescription = testDefinition.topology_description; const seedData = topologyDescription.servers.reduce( (result, seed) => { @@ -183,5 +184,3 @@ async function executeServerSelectionTest(testDefinition) { topology.close(); } } - -module.exports = { executeServerSelectionTest, serverDescriptionFromDefinition }; diff --git a/test/unit/assorted/sessions_client.test.js b/test/unit/assorted/sessions_client.test.js index 1b806543396..8f4eabc6353 100644 --- a/test/unit/assorted/sessions_client.test.js +++ b/test/unit/assorted/sessions_client.test.js @@ -3,21 +3,20 @@ const expect = require('chai').expect; const mock = require('../../tools/mongodb-mock/index'); const { ReplSetFixture } = require('../../tools/common'); -const { isHello } = require('../../mongodb'); -const { MongoClient } = require('../../mongodb'); +const { isHello } = require('../../../src/utils'); +const { MongoClient } = require('../../../src/mongo_client'); const test = {}; describe('Sessions - client/unit', function () { describe('Client', function () { - afterEach(() => mock.cleanup()); + afterEach(async () => await mock.cleanup()); - beforeEach(() => { - return mock.createServer().then(server => { - test.server = server; - }); + beforeEach(async () => { + const server = await mock.createServer(); + test.server = server; }); - it('should not throw a synchronous exception if sessions are not supported', function () { + it('should not throw a synchronous exception if sessions are not supported', async function () { test.server.setMessageHandler(request => { var doc = request.document; if (isHello(doc)) { @@ -28,84 +27,78 @@ describe('Sessions - client/unit', function () { }); const client = new MongoClient(`mongodb://${test.server.uri()}/test`); - return client.connect().then(() => { - expect(() => client.startSession()).to.not.throw( - 'Current topology does not support sessions' - ); - return client.close(); - }); + await client.connect(); + expect(() => client.startSession()).to.not.throw( + 'Current topology does not support sessions' + ); + await client.close(); }); - it('should throw an exception if sessions are not supported on some servers', function () { + it('should throw an exception if sessions are not supported on some servers', async function () { const replicaSetMock = new ReplSetFixture(); - let testClient; - return replicaSetMock - .setup({ doNotInitHandlers: true }) - .then(() => { - replicaSetMock.firstSecondaryServer.setMessageHandler(request => { - var doc = request.document; - if (isHello(doc)) { - const hello = replicaSetMock.firstSecondaryStates[0]; - hello.logicalSessionTimeoutMinutes = 20; - request.reply(hello); - } else if (doc.endSessions) { - request.reply({ ok: 1 }); - } - }); - - replicaSetMock.secondSecondaryServer.setMessageHandler(request => { - var doc = request.document; - if (isHello(doc)) { - const hello = replicaSetMock.secondSecondaryStates[0]; - hello.logicalSessionTimeoutMinutes = 10; - request.reply(hello); - } else if (doc.endSessions) { - request.reply({ ok: 1 }); - } - }); - - replicaSetMock.arbiterServer.setMessageHandler(request => { - var doc = request.document; - if (isHello(doc)) { - const hello = replicaSetMock.arbiterStates[0]; - hello.logicalSessionTimeoutMinutes = 30; - request.reply(hello); - } else if (doc.endSessions) { - request.reply({ ok: 1 }); - } - }); - - replicaSetMock.primaryServer.setMessageHandler(request => { - var doc = request.document; - if (isHello(doc)) { - const hello = replicaSetMock.primaryStates[0]; - hello.logicalSessionTimeoutMinutes = null; - request.reply(hello); - } else if (doc.endSessions) { - request.reply({ ok: 1 }); - } - }); - - return replicaSetMock.uri(); - }) - .then(uri => { - testClient = new MongoClient(uri); - return testClient.connect(); - }) - .then(client => { - const session = client.startSession(); - return client.db().collection('t').insertOne({ a: 1 }, { session }); - }) - .then(() => { - expect.fail('Expected an error to be thrown about not supporting sessions'); - }) - .catch(error => { - expect(error.message).to.equal('Current topology does not support sessions'); - }) - .finally(() => (testClient ? testClient.close() : null)); + await replicaSetMock.setup({ doNotInitHandlers: true }); + + replicaSetMock.firstSecondaryServer.setMessageHandler(request => { + var doc = request.document; + if (isHello(doc)) { + const hello = replicaSetMock.firstSecondaryStates[0]; + hello.logicalSessionTimeoutMinutes = 20; + request.reply(hello); + } else if (doc.endSessions) { + request.reply({ ok: 1 }); + } + }); + + replicaSetMock.secondSecondaryServer.setMessageHandler(request => { + var doc = request.document; + if (isHello(doc)) { + const hello = replicaSetMock.secondSecondaryStates[0]; + hello.logicalSessionTimeoutMinutes = 10; + request.reply(hello); + } else if (doc.endSessions) { + request.reply({ ok: 1 }); + } + }); + + replicaSetMock.arbiterServer.setMessageHandler(request => { + var doc = request.document; + if (isHello(doc)) { + const hello = replicaSetMock.arbiterStates[0]; + hello.logicalSessionTimeoutMinutes = 30; + request.reply(hello); + } else if (doc.endSessions) { + request.reply({ ok: 1 }); + } + }); + + replicaSetMock.primaryServer.setMessageHandler(request => { + var doc = request.document; + if (isHello(doc)) { + const hello = replicaSetMock.primaryStates[0]; + hello.logicalSessionTimeoutMinutes = null; + request.reply(hello); + } else if (doc.endSessions) { + request.reply({ ok: 1 }); + } + }); + + const uri = replicaSetMock.uri(); + + const client = new MongoClient(uri); + await client.connect(); + const session = client.startSession(); + + try { + await client.db().collection('t').insertOne({ a: 1 }, { session }); + expect.fail('Expected an error to be thrown about not supporting sessions'); + } catch (error) { + expect(error.message).to.equal('Current topology does not support sessions'); + } finally { + await client.close(); + } }); - it('should return a client session when requested if the topology supports it', function (done) { + it('should return a client session when requested if the topology supports it', async function () { test.server.setMessageHandler(request => { var doc = request.document; if (isHello(doc)) { @@ -120,14 +113,12 @@ describe('Sessions - client/unit', function () { }); const client = new MongoClient(`mongodb://${test.server.uri()}/test`); - client.connect(function (err, client) { - expect(err).to.not.exist; - let session = client.startSession(); - expect(session).to.exist; + await client.connect(); - session.endSession({ skipCommand: true }); - client.close(done); - }); + let session = client.startSession(); + expect(session).to.exist; + session.endSession({ skipCommand: true }); + client.close(); }); }); }); diff --git a/test/unit/assorted/sessions_collection.test.js b/test/unit/assorted/sessions_collection.test.js index e7711efb6b5..736d0e8be1d 100644 --- a/test/unit/assorted/sessions_collection.test.js +++ b/test/unit/assorted/sessions_collection.test.js @@ -2,8 +2,8 @@ const { Timestamp } = require('bson'); const { expect } = require('chai'); const mock = require('../../tools/mongodb-mock/index'); -const { isHello } = require('../../mongodb'); -const { MongoClient } = require('../../mongodb'); +import { MongoClient } from '../../../lib'; +import { isHello } from '../../../lib/utils'; const test = {}; describe('Sessions - unit/sessions', function () { diff --git a/test/unit/assorted/wire_version.test.ts b/test/unit/assorted/wire_version.test.ts index 448622ce20f..4bbab4fde5e 100644 --- a/test/unit/assorted/wire_version.test.ts +++ b/test/unit/assorted/wire_version.test.ts @@ -1,12 +1,11 @@ import { expect } from 'chai'; +import { MongoClient, MongoServerSelectionError } from '../../../src'; import { - isHello, MAX_SUPPORTED_WIRE_VERSION, - MIN_SUPPORTED_WIRE_VERSION, - MongoClient, - MongoServerSelectionError -} from '../../mongodb'; + MIN_SUPPORTED_WIRE_VERSION +} from '../../../src/cmap/wire_protocol/constants'; +import { isHello } from '../../../src/utils'; import * as mock from '../../tools/mongodb-mock/index'; const minCompatErrMsg = `minimum wire version ${ diff --git a/test/unit/assorted/write_concern.test.js b/test/unit/assorted/write_concern.test.js index 6e45ca69dca..418dd20f971 100644 --- a/test/unit/assorted/write_concern.test.js +++ b/test/unit/assorted/write_concern.test.js @@ -1,9 +1,12 @@ 'use strict'; const mock = require('../../tools/mongodb-mock/index'); const { expect } = require('chai'); -const { ObjectId, MongoClient } = require('../../mongodb'); -const { LEGACY_HELLO_COMMAND } = require('../../mongodb'); -const { isHello } = require('../../mongodb'); + +import { ObjectId } from 'bson'; + +import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; +import { MongoClient } from '../../../src/mongo_client'; +import { isHello } from '../../../src/utils'; const TEST_OPTIONS = { writeConcern: { w: 2, wtimeoutMS: 1000 } }; diff --git a/test/unit/client-side-encryption/auto_encrypter.test.ts b/test/unit/client-side-encryption/auto_encrypter.test.ts index 816b3a6cb93..7ccc391ece7 100644 --- a/test/unit/client-side-encryption/auto_encrypter.test.ts +++ b/test/unit/client-side-encryption/auto_encrypter.test.ts @@ -3,13 +3,9 @@ import * as fs from 'fs'; import * as net from 'net'; import * as sinon from 'sinon'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { AutoEncrypter } from '../../../src/client-side-encryption/auto_encrypter'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { MongocryptdManager } from '../../../src/client-side-encryption/mongocryptd_manager'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { StateMachine } from '../../../src/client-side-encryption/state_machine'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { MongoClient } from '../../../src/mongo_client'; import { BSON, type DataKey } from '../../mongodb'; import * as requirements from './requirements.helper'; diff --git a/test/unit/client-side-encryption/client_encryption.test.ts b/test/unit/client-side-encryption/client_encryption.test.ts index aeb1ac9beef..422ad8bdd82 100644 --- a/test/unit/client-side-encryption/client_encryption.test.ts +++ b/test/unit/client-side-encryption/client_encryption.test.ts @@ -3,16 +3,12 @@ import * as fs from 'fs'; import { resolve } from 'path'; import * as sinon from 'sinon'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import * as cryptoCallbacks from '../../../src/client-side-encryption/crypto_callbacks'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { MongoCryptCreateDataKeyError, MongoCryptCreateEncryptedCollectionError } from '../../../src/client-side-encryption/errors'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { StateMachine } from '../../../src/client-side-encryption/state_machine'; import { Binary, BSON, deserialize, MongoClient } from '../../mongodb'; diff --git a/test/unit/client-side-encryption/errors.test.ts b/test/unit/client-side-encryption/errors.test.ts index 6eaa0dbd6b5..b4b8b8224c2 100644 --- a/test/unit/client-side-encryption/errors.test.ts +++ b/test/unit/client-side-encryption/errors.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-restricted-imports */ import { expect } from 'chai'; import { diff --git a/test/unit/client-side-encryption/mongocryptd_manager.test.ts b/test/unit/client-side-encryption/mongocryptd_manager.test.ts index f8004781d8c..eb199eb7c26 100644 --- a/test/unit/client-side-encryption/mongocryptd_manager.test.ts +++ b/test/unit/client-side-encryption/mongocryptd_manager.test.ts @@ -1,6 +1,5 @@ import { expect } from 'chai'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { MongocryptdManager } from '../../../src/client-side-encryption/mongocryptd_manager'; describe('MongocryptdManager', function () { diff --git a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts index a21ac96ef33..aab342222f8 100644 --- a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts +++ b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts @@ -2,22 +2,17 @@ import { expect } from 'chai'; import * as http from 'http'; import * as sinon from 'sinon'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { MongoCryptAzureKMSRequestError } from '../../../../src/client-side-encryption/errors'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { isEmptyCredentials, type KMSProviders, refreshKMSCredentials } from '../../../../src/client-side-encryption/providers'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { fetchAzureKMSToken, tokenCache } from '../../../../src/client-side-encryption/providers/azure'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { AWSSDKCredentialProvider } from '../../../../src/cmap/auth/aws_temporary_credentials'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import * as utils from '../../../../src/utils'; import { MongoNetworkTimeoutError } from '../../../mongodb'; import * as requirements from '../requirements.helper'; diff --git a/test/unit/client-side-encryption/requirements.helper.ts b/test/unit/client-side-encryption/requirements.helper.ts index 68e6ecfce76..3aa8fa4b36a 100644 --- a/test/unit/client-side-encryption/requirements.helper.ts +++ b/test/unit/client-side-encryption/requirements.helper.ts @@ -1,4 +1,3 @@ -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { getAwsCredentialProvider, getGcpMetadata } from '../../../src/deps'; // Data Key Stuff diff --git a/test/unit/client-side-encryption/state_machine.test.ts b/test/unit/client-side-encryption/state_machine.test.ts index 920ce567dde..21cecd83574 100644 --- a/test/unit/client-side-encryption/state_machine.test.ts +++ b/test/unit/client-side-encryption/state_machine.test.ts @@ -8,9 +8,7 @@ import { setTimeout } from 'timers'; import { setTimeout as setTimeoutAsync } from 'timers/promises'; import * as tls from 'tls'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { StateMachine } from '../../../src/client-side-encryption/state_machine'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { Db } from '../../../src/db'; import { BSON, 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 33d37e593d7..fd2343eb913 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,9 +1,7 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { callback } from '../../../../../src/cmap/auth/mongodb_oidc/gcp_machine_workflow'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { TokenCache } from '../../../../../src/cmap/auth/mongodb_oidc/token_cache'; import { AutomatedCallbackWorkflow, 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 b61bbd62465..0db2db100b3 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,6 +1,5 @@ import { expect } from 'chai'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { callback } from '../../../../../src/cmap/auth/mongodb_oidc/azure_machine_workflow'; import { OIDC_VERSION, type OIDCCallbackParams } from '../../../../mongodb'; 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 f99465cb1f7..23b890fd988 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,6 +1,5 @@ import { expect } from 'chai'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { callback } from '../../../../../src/cmap/auth/mongodb_oidc/gcp_machine_workflow'; import { OIDC_VERSION, type OIDCCallbackParams } from '../../../../mongodb'; diff --git a/test/unit/cmap/auth/mongodb_oidc/token_machine_workflow.test.ts b/test/unit/cmap/auth/mongodb_oidc/token_machine_workflow.test.ts index 624c37dbb27..912be77be01 100644 --- a/test/unit/cmap/auth/mongodb_oidc/token_machine_workflow.test.ts +++ b/test/unit/cmap/auth/mongodb_oidc/token_machine_workflow.test.ts @@ -1,6 +1,5 @@ import { expect } from 'chai'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { callback } from '../../../../../src/cmap/auth/mongodb_oidc/token_machine_workflow'; describe('Token machine workflow', function () { diff --git a/test/unit/commands.test.ts b/test/unit/commands.test.ts index 3f601c678c0..b0e2c476018 100644 --- a/test/unit/commands.test.ts +++ b/test/unit/commands.test.ts @@ -1,7 +1,6 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import * as compression from '../../src/cmap/wire_protocol/compression'; import { compress, diff --git a/test/unit/error.test.ts b/test/unit/error.test.ts index 355b1dd0005..1a3ddd25403 100644 --- a/test/unit/error.test.ts +++ b/test/unit/error.test.ts @@ -2,9 +2,7 @@ import { expect } from 'chai'; import { setTimeout } from 'timers'; // Exception to the import from mongodb rule we're unit testing our public Errors API -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import * as importsFromErrorSrc from '../../src/error'; -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import * as importsFromEntryPoint from '../../src/index'; import { isHello, diff --git a/test/unit/index.test.ts b/test/unit/index.test.ts index 653792492ce..c39a09641e0 100644 --- a/test/unit/index.test.ts +++ b/test/unit/index.test.ts @@ -1,7 +1,6 @@ import { expect } from 'chai'; // Exception to the import from mongodb rule we're unit testing our public API -// eslint-disable-next-line @typescript-eslint/no-restricted-imports import * as mongodb from '../../src/index'; import { setDifference } from '../mongodb'; From bbdb366c206749cab024b6f6db37b3b7038e5f5c Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Thu, 18 Sep 2025 13:40:43 -0700 Subject: [PATCH 02/25] Update test/unit/assorted/max_staleness.spec.test.js remove extra comment Co-authored-by: Bailey Pearson --- test/unit/assorted/max_staleness.spec.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unit/assorted/max_staleness.spec.test.js b/test/unit/assorted/max_staleness.spec.test.js index bb4b2a4d9db..582787ce9ea 100644 --- a/test/unit/assorted/max_staleness.spec.test.js +++ b/test/unit/assorted/max_staleness.spec.test.js @@ -2,7 +2,7 @@ const path = require('path'); const fs = require('fs'); const { executeServerSelectionTest } = require('./server_selection_spec_helper'); -const { Server } = require('../../../src/sdam/server'); // src/sdam/server.ts +const { Server } = require('../../../src/sdam/server'); const { EJSON } = require('bson'); From 16f5dc51a80f845cb6b56e7fdbd2a440a69d7680 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Thu, 18 Sep 2025 14:04:07 -0700 Subject: [PATCH 03/25] fix: pr feedback --- test/unit/assorted/server_selection_spec_helper.js | 12 ++++++------ test/unit/assorted/sessions_collection.test.js | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test/unit/assorted/server_selection_spec_helper.js b/test/unit/assorted/server_selection_spec_helper.js index 0dccbeb7446..040d8fbdf10 100644 --- a/test/unit/assorted/server_selection_spec_helper.js +++ b/test/unit/assorted/server_selection_spec_helper.js @@ -1,11 +1,11 @@ 'use strict'; -import { MongoServerSelectionError } from '../../../src/error'; -import { ReadPreference } from '../../../src/read_preference'; -import { ServerType, TopologyType } from '../../../src/sdam/common'; -import { ServerDescription } from '../../../src/sdam/server_description'; -import * as ServerSelectors from '../../../src/sdam/server_selection'; // src/sdam/server_selection.ts -import { Topology } from '../../../src/sdam/topology'; +const { MongoServerSelectionError } = require('../../../src/error'); +const { ReadPreference } = require('../../../src/read_preference'); +const { ServerType, TopologyType } = require('../../../src/sdam/common'); +const { ServerDescription } = require('../../../src/sdam/server_description'); +const { Topology } = require('../../../src/sdam/topology'); +const ServerSelectors = require('../../../src/sdam/server_selection'); const sinon = require('sinon'); const { expect } = require('chai'); diff --git a/test/unit/assorted/sessions_collection.test.js b/test/unit/assorted/sessions_collection.test.js index 736d0e8be1d..0593ab8c42a 100644 --- a/test/unit/assorted/sessions_collection.test.js +++ b/test/unit/assorted/sessions_collection.test.js @@ -2,8 +2,8 @@ const { Timestamp } = require('bson'); const { expect } = require('chai'); const mock = require('../../tools/mongodb-mock/index'); -import { MongoClient } from '../../../lib'; -import { isHello } from '../../../lib/utils'; +const { isHello } = require('../../../src/utils'); +const { MongoClient } = require('../../../src'); const test = {}; describe('Sessions - unit/sessions', function () { From 88b54e324d7ab1bed1dfe79a5961b18d58b3959f Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Fri, 19 Sep 2025 08:11:26 -0700 Subject: [PATCH 04/25] fix: js files should not be using import --- test/unit/assorted/write_concern.test.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/unit/assorted/write_concern.test.js b/test/unit/assorted/write_concern.test.js index 418dd20f971..ed0368b5c95 100644 --- a/test/unit/assorted/write_concern.test.js +++ b/test/unit/assorted/write_concern.test.js @@ -2,11 +2,10 @@ const mock = require('../../tools/mongodb-mock/index'); const { expect } = require('chai'); -import { ObjectId } from 'bson'; - -import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; -import { MongoClient } from '../../../src/mongo_client'; -import { isHello } from '../../../src/utils'; +const { isHello } = require('../../../src/utils'); +const { LEGACY_HELLO_COMMAND } = require('../../../src/constants'); +const { MongoClient } = require('../../../src/mongo_client'); +const { ObjectId } = require('bson'); const TEST_OPTIONS = { writeConcern: { w: 2, wtimeoutMS: 1000 } }; From be1fb8e356b3f7bfd61cfed8167c3a1c9b439dd2 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Fri, 19 Sep 2025 09:02:57 -0700 Subject: [PATCH 05/25] fix: for shared library test, continue to reference `lib`, not `src`. --- test/tools/fixtures/shared_library_test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/tools/fixtures/shared_library_test.js b/test/tools/fixtures/shared_library_test.js index 5a334bc98e6..e87140a4834 100644 --- a/test/tools/fixtures/shared_library_test.js +++ b/test/tools/fixtures/shared_library_test.js @@ -1,6 +1,7 @@ +/* eslint-disable no-restricted-modules */ const { EJSON } = require('bson'); -const { AutoEncrypter } = require('../../../src/client-side-encryption/auto_encrypter'); -const { MongoClient } = require('../../../src/mongo_client'); +const { AutoEncrypter } = require('../../../lib/client-side-encryption/auto_encrypter'); +const { MongoClient } = require('../../../lib/mongo_client'); try { const extraOptions = JSON.parse(process.env.EXTRA_OPTIONS); From 9051b926cd5acd59cc827e7aa277e588fd29ff74 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Fri, 19 Sep 2025 10:44:57 -0700 Subject: [PATCH 06/25] starting work on updating all of unit tests --- test/unit/bson.test.ts | 3 +-- test/unit/change_stream.test.ts | 5 ++-- test/unit/commands.test.ts | 13 +++------ test/unit/connection_string.test.ts | 26 +++++------------- test/unit/db.test.ts | 5 ++-- test/unit/error.test.ts | 41 ++++++----------------------- 6 files changed, 25 insertions(+), 68 deletions(-) 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..b4f0bab7b92 100644 --- a/test/unit/change_stream.test.ts +++ b/test/unit/change_stream.test.ts @@ -1,8 +1,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/commands.test.ts b/test/unit/commands.test.ts index b0e2c476018..1e5199025a2 100644 --- a/test/unit/commands.test.ts +++ b/test/unit/commands.test.ts @@ -2,16 +2,9 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; import * as compression from '../../src/cmap/wire_protocol/compression'; -import { - compress, - Compressor, - OP_MSG, - OP_QUERY, - OpCompressedRequest, - OpMsgRequest, - OpQueryRequest, - uncompressibleCommands -} from '../mongodb'; +import { compress, Compressor, uncompressibleCommands } from '../../src/cmap/wire_protocol/compression'; +import { OpCompressedRequest, OpMsgRequest, OpQueryRequest } from '../../src/cmap/commands'; +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..76893c1d3e8 100644 --- a/test/unit/connection_string.test.ts +++ b/test/unit/connection_string.test.ts @@ -5,25 +5,13 @@ import { expect } from 'chai'; import * as dns from 'dns'; import * as sinon from 'sinon'; import { inspect } from 'util'; - -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'; +import { parseOptions, resolveSRVRecord } from '../../src/connection_string'; +import { MongoAPIError, MongoDriverError, MongoInvalidArgumentError, MongoParseError, MongoRuntimeError } from '../../src/error'; +import { DEFAULT_ALLOWED_HOSTS, MongoCredentials } from '../../src/cmap/auth/mongo_credentials'; +import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from '../../src/cmap/auth/providers'; +import { MongoClient, MongoOptions } from '../../src/mongo_client'; +import { 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/db.test.ts b/test/unit/db.test.ts index d9eaebfdbe4..ecf81968a4d 100644 --- a/test/unit/db.test.ts +++ b/test/unit/db.test.ts @@ -1,6 +1,7 @@ import { expect } from 'chai'; - -import { Db, type DbOptions, MongoClient, ReadPreference } from '../mongodb'; +import { MongoClient } from '../../src/mongo_client'; +import { Db, DbOptions } from '../../src/db'; +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..bfbe6417b73 100644 --- a/test/unit/error.test.ts +++ b/test/unit/error.test.ts @@ -4,42 +4,17 @@ import { setTimeout } from 'timers'; // 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, - MongoDriverError, - MongoError, - MongoErrorLabel, - MongoMissingDependencyError, - MongoNetworkError, - MongoNetworkTimeoutError, - MongoOperationTimeoutError, - MongoParseError, - MongoRuntimeError, - 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'; import { ReplSetFixture } from '../tools/common'; import { cleanup } from '../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../tools/utils'; - -describe('MongoErrors', () => { +import { isHello, ns, setDifference } from '../../src/utils'; +import { MongoDriverError, MongoError, MongoErrorLabel, MongoMissingDependencyError, MongoNetworkError, MongoNetworkTimeoutError, MongoOperationTimeoutError, MongoParseError, MongoRuntimeError, MongoServerError, MongoSystemError, MongoWriteConcernError, TopologyDescription, TopologyOptions } from '../../src/index'; +import { 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 { PoolClosedError as MongoPoolClosedError, WaitQueueTimeoutError as MongoWaitQueueTimeoutError } from '../../src/cmap/errors'; +import { RunCommandOperation } from '../../src/operations/run_command'; +import { TimeoutContext } from '../../src/timeout'; + +describe.only('MongoErrors', () => { let errorClassesFromEntryPoint = Object.fromEntries( Object.entries(importsFromEntryPoint).filter( ([key, value]) => key.endsWith('Error') && value.toString().startsWith('class') From 493b32d7e7ada56fb925e4e7abf09ee51f98c1f9 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Fri, 19 Sep 2025 13:32:04 -0700 Subject: [PATCH 07/25] more migrated tests --- test/action/dependency.test.ts | 2 +- test/integration/auth/auth.prose.test.ts | 5 +- test/integration/auth/mongodb_aws.test.ts | 22 +-- .../enumerate_databases.prose.test.ts | 3 +- test/integration/enumerate_databases.test.ts | 3 +- test/integration/index_management.test.ts | 13 +- .../auto_encrypter.test.ts | 3 +- .../client_encryption.test.ts | 3 +- .../client-side-encryption/errors.test.ts | 2 +- .../providers/credentialsProvider.test.ts | 2 +- .../state_machine.test.ts | 19 +-- test/unit/cmap/commands.test.ts | 2 +- test/unit/collection.test.ts | 157 +++++++----------- test/unit/error.test.ts | 2 +- test/unit/explain.test.ts | 6 +- test/unit/index.test.ts | 2 +- test/unit/mongo_client.test.ts | 26 +-- test/unit/mongo_logger.test.ts | 28 +--- test/unit/read_preference.test.ts | 2 +- test/unit/sessions.test.ts | 18 +- test/unit/timeout.test.ts | 12 +- test/unit/transactions.test.ts | 4 +- test/unit/utils.test.ts | 27 +-- test/unit/write_concern.test.ts | 3 +- 24 files changed, 131 insertions(+), 235 deletions(-) diff --git a/test/action/dependency.test.ts b/test/action/dependency.test.ts index c0c4206fe68..7a404a3c120 100644 --- a/test/action/dependency.test.ts +++ b/test/action/dependency.test.ts @@ -5,8 +5,8 @@ import * as path from 'node:path'; import { expect } from 'chai'; import { dependencies, peerDependencies, peerDependenciesMeta } from '../../package.json'; -import { setDifference } from '../mongodb'; import { alphabetically, itInNodeProcess, sorted } from '../tools/utils'; +import { setDifference } from '../../src/utils'; const EXPECTED_DEPENDENCIES = sorted( ['@mongodb-js/saslprep', 'bson', 'mongodb-connection-string-url'], diff --git a/test/integration/auth/auth.prose.test.ts b/test/integration/auth/auth.prose.test.ts index d9408a42001..3f1138c92b7 100644 --- a/test/integration/auth/auth.prose.test.ts +++ b/test/integration/auth/auth.prose.test.ts @@ -1,8 +1,11 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -import { Connection, LEGACY_HELLO_COMMAND, type MongoClient, ScramSHA256 } from '../../mongodb'; import { type TestConfiguration } from '../../tools/runner/config'; +import { MongoClient } from '../../../src/mongo_client'; +import { ScramSHA256 } from '../../../src/cmap/auth/scram'; +import { Connection } from '../../../src/cmap/connection'; +import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; function makeConnectionString(config, username, password) { return `mongodb://${username}:${password}@${config.host}:${config.port}/admin?`; diff --git a/test/integration/auth/mongodb_aws.test.ts b/test/integration/auth/mongodb_aws.test.ts index fdfaee62288..0ca28866022 100644 --- a/test/integration/auth/mongodb_aws.test.ts +++ b/test/integration/auth/mongodb_aws.test.ts @@ -6,21 +6,13 @@ import { performance } from 'perf_hooks'; import * as sinon from 'sinon'; import { refreshKMSCredentials } from '../../../src/client-side-encryption/providers'; -import { - AWSSDKCredentialProvider, - type CommandOptions, - Connection, - type Document, - MongoAWSError, - type MongoClient, - MongoDBAWS, - type MongoDBNamespace, - type MongoDBResponseConstructor, - MongoMissingCredentialsError, - MongoMissingDependencyError, - MongoServerError, - setDifference -} from '../../mongodb'; +import { MongoClient } from '../../../src/mongo_client'; +import { AWSSDKCredentialProvider } from '../../../src/cmap/auth/aws_temporary_credentials'; +import { MongoAWSError, MongoMissingDependencyError, MongoServerError } from '../../../src/error'; +import { MongoDBNamespace } from '../../../src/utils'; +import { Document } from 'bson'; +import { CommandOptions, Connection } from '../../../src/cmap/connection'; +import { MongoDBResponseConstructor } from '../../../src/cmap/wire_protocol/responses'; const isMongoDBAWSAuthEnvironment = (process.env.MONGODB_URI ?? '').includes('MONGODB-AWS'); diff --git a/test/integration/enumerate_databases.prose.test.ts b/test/integration/enumerate_databases.prose.test.ts index 9528d68fada..ecd24d911d4 100644 --- a/test/integration/enumerate_databases.prose.test.ts +++ b/test/integration/enumerate_databases.prose.test.ts @@ -1,6 +1,5 @@ import { expect } from 'chai'; - -import type { MongoClient } from '../mongodb'; +import { MongoClient } from '../../src/mongo_client'; const REQUIRED_DBS = ['admin', 'local', 'config']; const DB_NAME = 'listDatabasesTest'; diff --git a/test/integration/enumerate_databases.test.ts b/test/integration/enumerate_databases.test.ts index 0b52ade1303..3788337820a 100644 --- a/test/integration/enumerate_databases.test.ts +++ b/test/integration/enumerate_databases.test.ts @@ -1,8 +1,9 @@ import { expect } from 'chai'; import { once } from 'events'; -import { type MongoClient, MongoServerError } from '../mongodb'; import { TestBuilder, UnifiedTestSuiteBuilder } from '../tools/unified_suite_builder'; +import { MongoClient } from '../../src/mongo_client'; +import { MongoServerError } from '../../src/error'; const metadata: MongoDBMetadataUI = { requires: { diff --git a/test/integration/index_management.test.ts b/test/integration/index_management.test.ts index 05574a26be5..8a98484812c 100644 --- a/test/integration/index_management.test.ts +++ b/test/integration/index_management.test.ts @@ -1,15 +1,12 @@ import { expect } from 'chai'; -import { - type Collection, - type CommandStartedEvent, - type CommandSucceededEvent, - type Db, - type MongoClient, - MongoServerError -} from '../mongodb'; import { type FailCommandFailPoint } from '../tools/utils'; import { assert as test, filterForCommands, setupDatabase } from './shared'; +import { MongoClient } from '../../src/mongo_client'; +import { Db } from '../../src/db'; +import { Collection } from '../../src/collection'; +import { MongoServerError } from '../../src/error'; +import { CommandStartedEvent, CommandSucceededEvent } from '../../src/cmap/command_monitoring_events'; describe('Indexes', function () { let client: MongoClient; diff --git a/test/unit/client-side-encryption/auto_encrypter.test.ts b/test/unit/client-side-encryption/auto_encrypter.test.ts index 7ccc391ece7..5b9e8778a80 100644 --- a/test/unit/client-side-encryption/auto_encrypter.test.ts +++ b/test/unit/client-side-encryption/auto_encrypter.test.ts @@ -7,8 +7,9 @@ import { AutoEncrypter } from '../../../src/client-side-encryption/auto_encrypte 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'; +import { BSON } from 'bson'; +import { DataKey } from '../../../src/client-side-encryption/client_encryption'; const bson = BSON; const { EJSON } = 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..9eb13084904 100644 --- a/test/unit/client-side-encryption/client_encryption.test.ts +++ b/test/unit/client-side-encryption/client_encryption.test.ts @@ -10,7 +10,8 @@ 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 { Binary, BSON, deserialize } from 'bson'; +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..79c4af56d60 100644 --- a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts +++ b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts @@ -14,8 +14,8 @@ import { } from '../../../../src/client-side-encryption/providers/azure'; import { AWSSDKCredentialProvider } from '../../../../src/cmap/auth/aws_temporary_credentials'; import * as utils from '../../../../src/utils'; -import { MongoNetworkTimeoutError } from '../../../mongodb'; import * as requirements from '../requirements.helper'; +import { MongoNetworkTimeoutError } from '../../../../src/error'; const originalAccessKeyId = process.env.AWS_ACCESS_KEY_ID; const originalSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY; diff --git a/test/unit/client-side-encryption/state_machine.test.ts b/test/unit/client-side-encryption/state_machine.test.ts index 21cecd83574..555c30a58b5 100644 --- a/test/unit/client-side-encryption/state_machine.test.ts +++ b/test/unit/client-side-encryption/state_machine.test.ts @@ -10,19 +10,14 @@ import * as tls from 'tls'; import { StateMachine } from '../../../src/client-side-encryption/state_machine'; import { Db } from '../../../src/db'; -import { - BSON, - Collection, - CSOTTimeoutContext, - CursorTimeoutContext, - type FindOptions, - Int32, - Long, - MongoClient, - serialize, - squashError -} from '../../mongodb'; import { sleep } from '../../tools/utils'; +import { BSON, Int32, Long, serialize } from 'bson'; +import { MongoClient } from '../../../src/mongo_client'; +import { Collection } from '../../../src/collection'; +import { CSOTTimeoutContext } from '../../../src/timeout'; +import { squashError } from '../../../src/utils'; +import { CursorTimeoutContext } from '../../../src/cursor/abstract_cursor'; +import { FindOptions } from '../../../src/operations/find'; describe('StateMachine', function () { class MockRequest implements MongoCryptKMSRequest { 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/collection.test.ts b/test/unit/collection.test.ts index c45712abebc..9aff74af824 100644 --- a/test/unit/collection.test.ts +++ b/test/unit/collection.test.ts @@ -1,7 +1,9 @@ import { expect } from 'chai'; -import { isHello, MongoClient } from '../mongodb'; import { cleanup, createServer, HELLO } from '../tools/mongodb-mock'; +import { MongoClient } from '../../src/mongo_client'; +import { isHello } from '../../src/utils'; +import { Long } from 'bson'; describe('Collection', function () { let server = null; @@ -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,42 @@ 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(); } 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 +87,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 }; + 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); } - 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 +125,34 @@ 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 + }; + + await collection.bulkWrite([{ insertOne: { document: { a: 1 } } }], options); + }; - collection.bulkWrite([{ insertOne: { document: { a: 1 } } }], options, () => close(null)); - }); - } // 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/error.test.ts b/test/unit/error.test.ts index bfbe6417b73..d3ac0784173 100644 --- a/test/unit/error.test.ts +++ b/test/unit/error.test.ts @@ -14,7 +14,7 @@ import { PoolClosedError as MongoPoolClosedError, WaitQueueTimeoutError as Mongo import { RunCommandOperation } from '../../src/operations/run_command'; import { TimeoutContext } from '../../src/timeout'; -describe.only('MongoErrors', () => { +describe('MongoErrors', () => { let errorClassesFromEntryPoint = Object.fromEntries( Object.entries(importsFromEntryPoint).filter( ([key, value]) => key.endsWith('Error') && value.toString().startsWith('class') diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index adfcfd866c6..77e46eeb646 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -1,7 +1,9 @@ import { expect } from 'chai'; import { it } from 'mocha'; - -import { Explain, ExplainVerbosity, FindCursor, MongoClient, MongoDBNamespace } from '../mongodb'; +import { Explain, ExplainVerbosity } from '../../src/explain'; +import { MongoClient } from '../../src/mongo_client'; +import { MongoDBNamespace } from '../../src/utils'; +import { FindCursor } from '../../src/cursor/find_cursor'; 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..0eafabe2ec0 100644 --- a/test/unit/mongo_client.test.ts +++ b/test/unit/mongo_client.test.ts @@ -4,24 +4,14 @@ import * as os from 'os'; 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 { parseOptions, resolveSRVRecord } from '../../src/connection_string'; +import { MongoClient, MongoClientOptions, ServerApiVersion } from '../../src/mongo_client'; +import { WriteConcern } from '../../src/write_concern'; +import { MongoAPIError, MongoInvalidArgumentError, MongoParseError } from '../../src/error'; +import { ReadPreference } from '../../src/read_preference'; +import { MongoLoggableComponent, MongoLogger, SeverityLevel } from '../../src/mongo_logger'; +import { ReadConcern } from '../../src/read_concern'; +import { MongoCredentials } from '../../src/cmap/auth/mongo_credentials'; 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..02545fbf138 100644 --- a/test/unit/mongo_logger.test.ts +++ b/test/unit/mongo_logger.test.ts @@ -4,33 +4,9 @@ import * as sinon from 'sinon'; import { Readable, Writable } from 'stream'; import { inspect } from 'util'; -import { - COMMAND_FAILED, - COMMAND_STARTED, - COMMAND_SUCCEEDED, - CONNECTION_CHECK_OUT_FAILED, - CONNECTION_CHECK_OUT_STARTED, - CONNECTION_CHECKED_IN, - CONNECTION_CHECKED_OUT, - CONNECTION_CLOSED, - CONNECTION_CREATED, - CONNECTION_POOL_CLEARED, - CONNECTION_POOL_CLOSED, - CONNECTION_POOL_CREATED, - CONNECTION_POOL_READY, - CONNECTION_READY, - createStdioLogger, - DEFAULT_MAX_DOCUMENT_LENGTH, - type Log, - type MongoDBLogWritable, - MongoLoggableComponent, - MongoLogger, - type MongoLoggerOptions, - parseSeverityFromString, - SeverityLevel, - stringifyWithMaxLen -} from '../mongodb'; import { sleep } from '../tools/utils'; +import { createStdioLogger, DEFAULT_MAX_DOCUMENT_LENGTH, Log, MongoDBLogWritable, MongoLoggableComponent, MongoLogger, MongoLoggerOptions, parseSeverityFromString, SeverityLevel, stringifyWithMaxLen } from '../../src/mongo_logger'; +import { COMMAND_FAILED, COMMAND_STARTED, COMMAND_SUCCEEDED, CONNECTION_CHECK_OUT_FAILED, CONNECTION_CHECK_OUT_STARTED, CONNECTION_CHECKED_IN, CONNECTION_CHECKED_OUT, CONNECTION_CLOSED, CONNECTION_CREATED, CONNECTION_POOL_CLEARED, CONNECTION_POOL_CLOSED, CONNECTION_POOL_CREATED, CONNECTION_POOL_READY, CONNECTION_READY } from '../../src/constants'; class BufferingStream extends Writable { buffer: any[] = []; 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/sessions.test.ts b/test/unit/sessions.test.ts index 128e1b08e4b..a7ed28425b1 100644 --- a/test/unit/sessions.test.ts +++ b/test/unit/sessions.test.ts @@ -1,20 +1,14 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -import { - applySession, - BSON, - ClientSession, - isHello, - Long, - MongoClient, - MongoRuntimeError, - now, - ServerSession, - ServerSessionPool -} from '../mongodb'; import { genClusterTime } from '../tools/common'; import * as mock from '../tools/mongodb-mock/index'; +import { MongoClient } from '../../src/mongo_client'; +import { ClientSession, ServerSession, ServerSessionPool } from '../../src/sessions'; +import { applySession } from '../../src/sessions'; +import { isHello, now } from '../../src/utils'; +import { MongoRuntimeError } from '../../src/error'; +import { BSON, Long } from 'bson'; describe('Sessions - unit', function () { let client; diff --git a/test/unit/timeout.test.ts b/test/unit/timeout.test.ts index 1dd7e83feb5..a50a84f0c1d 100644 --- a/test/unit/timeout.test.ts +++ b/test/unit/timeout.test.ts @@ -1,14 +1,6 @@ import { expect } from 'chai'; - -import { - CSOTTimeoutContext, - LegacyTimeoutContext, - MongoInvalidArgumentError, - MongoRuntimeError, - Timeout, - TimeoutContext, - TimeoutError -} from '../mongodb'; +import { CSOTTimeoutContext, LegacyTimeoutContext, Timeout, TimeoutContext, TimeoutError } from '../../src/timeout'; +import { MongoInvalidArgumentError, MongoRuntimeError } from '../../src/error'; describe('Timeout', function () { let timeout: Timeout; diff --git a/test/unit/transactions.test.ts b/test/unit/transactions.test.ts index 789c0b1cb6f..7b70eb36717 100644 --- a/test/unit/transactions.test.ts +++ b/test/unit/transactions.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; - -import { ReadPreference, Transaction } from '../mongodb'; +import { Transaction } from '../../src/transactions'; +import { ReadPreference } from '../../src/read_preference'; describe('class Transaction', () => { describe('constructor()', () => { diff --git a/test/unit/utils.test.ts b/test/unit/utils.test.ts index 6fa7e9784af..062235ae107 100644 --- a/test/unit/utils.test.ts +++ b/test/unit/utils.test.ts @@ -3,29 +3,12 @@ import { setTimeout } from 'node:timers'; import { expect } from 'chai'; import * as sinon from 'sinon'; -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'; import { sleep } from '../tools/utils'; +import { abortable, BufferPool, ByteUtils, checkParentDomainMatch, compareObjectId, hasAtomicOperators, HostAddress, hostMatchesWildcards, isHello, isUint8Array, List, MongoDBCollectionNamespace, MongoDBNamespace, shuffle } from '../../src/utils'; +import { MongoInvalidArgumentError, MongoRuntimeError } from '../../src/error'; +import { decorateWithExplain, Explain } from '../../src/explain'; +import { ObjectId } from 'bson'; +import { LEGACY_HELLO_COMMAND } from '../../src/constants'; describe('driver utils', function () { describe('.hasAtomicOperators', function () { diff --git a/test/unit/write_concern.test.ts b/test/unit/write_concern.test.ts index 0f59a2c3b04..3ed3086202a 100644 --- a/test/unit/write_concern.test.ts +++ b/test/unit/write_concern.test.ts @@ -1,6 +1,5 @@ import { expect } from 'chai'; - -import { WriteConcern } from '../mongodb'; +import { WriteConcern } from '../../src/write_concern'; describe('WriteConcern', function () { describe('#constructor', function () { From ba0b5df54132d4d6a78ee84995a59db52d8a7679 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Fri, 19 Sep 2025 14:35:03 -0700 Subject: [PATCH 08/25] more migrations --- test/unit/cmap/auth/auth_provider.test.ts | 4 +-- test/unit/cmap/auth/gssapi.test.ts | 7 +--- .../automated_callback_workflow.test.ts | 10 +++--- .../azure_machine_workflow.test.ts | 2 +- .../cmap/command_monitoring_events.test.js | 4 +-- test/unit/cmap/connect.test.ts | 35 +++++++++---------- test/unit/cmap/connection.test.ts | 17 +++------ test/unit/cmap/connection_pool.test.js | 12 ++++--- test/unit/cmap/connection_pool_events.test.ts | 4 +-- .../cmap/handshake/client_metadata.test.ts | 11 ++---- test/unit/cmap/metrics.test.js | 2 +- .../cmap/wire_protocol/compression.test.ts | 3 +- .../unit/cmap/wire_protocol/constants.test.ts | 2 +- .../wire_protocol/on_demand/document.test.ts | 12 ++----- .../unit/cmap/wire_protocol/responses.test.ts | 13 +++---- test/unit/cursor/abstract_cursor.test.ts | 14 +++----- 16 files changed, 58 insertions(+), 94 deletions(-) diff --git a/test/unit/cmap/auth/auth_provider.test.ts b/test/unit/cmap/auth/auth_provider.test.ts index 7c9b530e69f..b69ba5b9739 100644 --- a/test/unit/cmap/auth/auth_provider.test.ts +++ b/test/unit/cmap/auth/auth_provider.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; - -import { type AuthContext, AuthProvider, MongoRuntimeError } from '../../../mongodb'; +import { 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..7723d63346d 100644 --- a/test/unit/cmap/auth/gssapi.test.ts +++ b/test/unit/cmap/auth/gssapi.test.ts @@ -1,12 +1,7 @@ import { expect } from 'chai'; import { promises as dns } from 'dns'; import * as sinon from 'sinon'; - -import { - GSSAPICanonicalizationValue, - performGSSAPICanonicalizeHostName, - resolveCname -} from '../../../mongodb'; +import { GSSAPICanonicalizationValue, performGSSAPICanonicalizeHostName, resolveCname } 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..2e91c8a5b6e 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 @@ -3,12 +3,10 @@ import * as sinon from 'sinon'; 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 { AutomatedCallbackWorkflow } from '../../../../../src/cmap/auth/mongodb_oidc/automated_callback_workflow'; +import { CallbackWorkflow } from '../../../../../src/cmap/auth/mongodb_oidc/callback_workflow'; +import { Connection } from '../../../../../src/cmap/connection'; +import { MongoCredentials } from '../../../../../src/cmap/auth/mongo_credentials'; 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..36d29c44c53 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 { callback } from '../../../../../src/cmap/auth/mongodb_oidc/azure_machine_workflow'; -import { OIDC_VERSION, type OIDCCallbackParams } from '../../../../mongodb'; +import { OIDC_VERSION, OIDCCallbackParams } from '../../../../../src/cmap/auth/mongodb_oidc'; describe('Azure 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/connect.test.ts b/test/unit/cmap/connect.test.ts index 7f172b860b3..3b57cc00caa 100644 --- a/test/unit/cmap/connect.test.ts +++ b/test/unit/cmap/connect.test.ts @@ -1,22 +1,18 @@ import { expect } from 'chai'; -import { - addContainerMetadata, - CancellationToken, - type ClientMetadata, - connect, - type Connection, - type ConnectionOptions, - HostAddress, - isHello, - LEGACY_HELLO_COMMAND, - MongoClientAuthProviders, - MongoCredentials, - MongoNetworkError, - prepareHandshakeDocument -} from '../../mongodb'; import { genClusterTime } from '../../tools/common'; import * as mock from '../../tools/mongodb-mock/index'; +import { Document } from 'bson'; +import { ConnectionOptions } from 'node:tls'; +import { connect, prepareHandshakeDocument } from '../../../src/cmap/connect'; +import { addContainerMetadata, ClientMetadata } from '../../../src/cmap/handshake/client_metadata'; +import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; +import { HostAddress, isHello } from '../../../src/utils'; +import { MongoCredentials } from '../../../src/cmap/auth/mongo_credentials'; +import { MongoClientAuthProviders } from '../../../src/mongo_client_auth_providers'; +import { Connection } from '../../../src/cmap/connection'; +import { MongoNetworkError } from '../../../src/error'; +import { CancellationToken } from '../../../src/mongo_types'; const CONNECT_DEFAULTS = { id: 1, @@ -181,10 +177,13 @@ describe('Connect Tests', function () { }); it('should emit `MongoNetworkError` for network errors', async function () { - const error = await connect({ - hostAddress: new HostAddress('non-existent:27018') - }).catch(e => e); + try { + await connect({ + hostAddress: new HostAddress('non-existent:27018') + }); + } catch (error) { expect(error).to.be.instanceOf(MongoNetworkError); +} }); describe('prepareHandshakeDocument', () => { diff --git a/test/unit/cmap/connection.test.ts b/test/unit/cmap/connection.test.ts index 79fe9ea863d..b53b6195721 100644 --- a/test/unit/cmap/connection.test.ts +++ b/test/unit/cmap/connection.test.ts @@ -5,19 +5,12 @@ 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 * as mock from '../../tools/mongodb-mock/index'; +import { Connection, SizedMessageTransform } from '../../../src/cmap/connection'; +import { isHello, MongoDBCollectionNamespace, ns, promiseWithResolvers } from '../../../src/utils'; +import { MongoClientAuthProviders } from '../../../src/mongo_client_auth_providers'; +import { MongoNetworkTimeoutError, MongoRuntimeError } from '../../../src/error'; const connectionOptionsDefaults = { id: 0, diff --git a/test/unit/cmap/connection_pool.test.js b/test/unit/cmap/connection_pool.test.js index 61fa73fc0e4..21db4a8bb8b 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..2b6ecc6d420 100644 --- a/test/unit/cmap/connection_pool_events.test.ts +++ b/test/unit/cmap/connection_pool_events.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; - -import { type ConnectionPool, ConnectionPoolCreatedEvent } from '../../mongodb'; +import { ConnectionPoolCreatedEvent } from '../../../src/cmap/connection_pool_events'; +import { ConnectionPool } from '../../../src/cmap/connection_pool'; 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..6b470302da2 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -5,14 +5,9 @@ import * as sinon from 'sinon'; import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; -import { - getFAASEnv, - Int32, - LimitedSizeDocument, - makeClientMetadata, - MongoInvalidArgumentError, - ObjectId -} from '../../../mongodb'; +import { getFAASEnv, LimitedSizeDocument, makeClientMetadata } from '../../../../src/cmap/handshake/client_metadata'; +import { Int32, ObjectId } from 'bson'; +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/wire_protocol/compression.test.ts b/test/unit/cmap/wire_protocol/compression.test.ts index e67fa0afb7b..5f4cdd4f606 100644 --- a/test/unit/cmap/wire_protocol/compression.test.ts +++ b/test/unit/cmap/wire_protocol/compression.test.ts @@ -1,7 +1,6 @@ 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..fb701b897fb 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,6 @@ +import { BSON, Timestamp, Binary, ObjectId, BSONType, BSONError } 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..5e250482864 100644 --- a/test/unit/cmap/wire_protocol/responses.test.ts +++ b/test/unit/cmap/wire_protocol/responses.test.ts @@ -1,13 +1,8 @@ import { expect } from 'chai'; - -import { - CursorResponse, - Int32, - MongoDBResponse, - MongoUnexpectedServerResponseError, - OnDemandDocument, - serialize -} from '../../../mongodb'; +import { CursorResponse, MongoDBResponse } from '../../../../src/cmap/wire_protocol/responses'; +import { Int32, serialize } from '../../../../src/bson'; +import { OnDemandDocument } from '../../../../src/cmap/wire_protocol/on_demand/document'; +import { MongoUnexpectedServerResponseError } from '../../../../src/error'; describe('class MongoDBResponse', () => { it('is a subclass of OnDemandDocument', () => { diff --git a/test/unit/cursor/abstract_cursor.test.ts b/test/unit/cursor/abstract_cursor.test.ts index 7665c8744f2..6cb8f04bf2b 100644 --- a/test/unit/cursor/abstract_cursor.test.ts +++ b/test/unit/cursor/abstract_cursor.test.ts @@ -1,14 +1,10 @@ import { expect } from 'chai'; - +import { AbstractCursor, AbstractCursorOptions } from '../../../src/cursor/abstract_cursor'; +import { MongoClient } from '../../../src/mongo_client'; +import { ClientSession } from '../../../src/sessions'; +import { Callback, ns } from '../../../src/utils'; import { - AbstractCursor, - type AbstractCursorOptions, - type Callback, - type ClientSession, - type ExecutionResult, - MongoClient, - ns, - type Server + ExecutionResult } from '../../mongodb'; /** Minimal do nothing cursor to focus on testing the base cursor behavior */ From dc82c35b69ce18297c19ebf0abdae9bb647476aa Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Fri, 19 Sep 2025 14:59:57 -0700 Subject: [PATCH 09/25] more migrations --- test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts | 2 +- test/unit/cmap/stream_description.test.js | 2 +- .../tools/unified_spec_runner/entity_event_registry.test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) 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..411e16f4f85 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 { callback } from '../../../../../src/cmap/auth/mongodb_oidc/gcp_machine_workflow'; -import { OIDC_VERSION, type OIDCCallbackParams } from '../../../../mongodb'; +import { OIDC_VERSION, OIDCCallbackParams } from '../../../../../src/cmap/auth/mongodb_oidc'; describe('GCP machine workflow', function () { describe('#callback', 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/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'; From 44d92326e73c33d49a3d01c017eea1afb40709f3 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Fri, 19 Sep 2025 15:38:06 -0700 Subject: [PATCH 10/25] more migrations --- .../client_bulk_write/command_builder.test.ts | 24 ++++----------- .../client_bulk_write/results_merger.test.ts | 13 +++----- test/unit/sdam/monitor.test.ts | 23 +++++--------- test/unit/sdam/server.test.ts | 18 ++++------- test/unit/sdam/server_description.test.ts | 12 ++------ ...ver_discovery_and_monitoring.prose.test.ts | 4 +-- test/unit/sdam/server_selection.test.ts | 21 +++++-------- test/unit/sdam/srv_polling.test.ts | 15 ++++------ test/unit/sdam/topology.test.ts | 30 +++++++------------ 9 files changed, 53 insertions(+), 107 deletions(-) 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..11b5a356036 100644 --- a/test/unit/operations/client_bulk_write/command_builder.test.ts +++ b/test/unit/operations/client_bulk_write/command_builder.test.ts @@ -1,23 +1,9 @@ +import { ObjectId } from 'bson'; import { expect } from 'chai'; - -import { - buildDeleteManyOperation, - buildDeleteOneOperation, - buildInsertOneOperation, - buildReplaceOneOperation, - buildUpdateManyOperation, - buildUpdateOneOperation, - ClientBulkWriteCommandBuilder, - type ClientDeleteManyModel, - type ClientDeleteOneModel, - type ClientInsertOneModel, - type ClientReplaceOneModel, - type ClientUpdateManyModel, - type ClientUpdateOneModel, - DEFAULT_PK_FACTORY, - DocumentSequence, - ObjectId -} from '../../../mongodb'; +import { ClientDeleteManyModel, ClientDeleteOneModel, ClientInsertOneModel, ClientReplaceOneModel, ClientUpdateManyModel, ClientUpdateOneModel } from '../../../../src/operations/client_bulk_write/common'; +import { buildDeleteManyOperation, buildDeleteOneOperation, buildInsertOneOperation, buildReplaceOneOperation, buildUpdateManyOperation, buildUpdateOneOperation, ClientBulkWriteCommandBuilder } from '../../../../src/operations/client_bulk_write/command_builder'; +import { DocumentSequence } from '../../../../src/cmap/commands'; +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..8988b3535f5 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,8 @@ +import { BSON, 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 { ClientBulkWriteResultsMerger } from '../../../../src/operations/client_bulk_write/results_merger'; +import { ClientBulkWriteResult } from '../../../../src/operations/client_bulk_write/common'; class MockCursor { operations: Document[]; diff --git a/test/unit/sdam/monitor.test.ts b/test/unit/sdam/monitor.test.ts index ef3cc98674e..a45d8834159 100644 --- a/test/unit/sdam/monitor.test.ts +++ b/test/unit/sdam/monitor.test.ts @@ -7,24 +7,17 @@ import * as sinon from 'sinon'; import { setTimeout } from 'timers'; import { setTimeout as setTimeoutPromise } from 'timers/promises'; -import { - isHello, - LEGACY_HELLO_COMMAND, - Long, - MongoClient, - Monitor, - MonitorInterval, - ObjectId, - RTTSampler, - ServerDescription, - type ServerHeartbeatFailedEvent, - type ServerHeartbeatStartedEvent, - ServerHeartbeatSucceededEvent, - ServerType -} from '../../mongodb'; import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; import { createTimerSandbox } from '../timer_sandbox'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { ServerType } from '../../../src/sdam/common'; +import { isHello } from '../../../src/utils'; +import { Monitor, MonitorInterval, RTTSampler } from '../../../src/sdam/monitor'; +import { ServerHeartbeatFailedEvent, ServerHeartbeatStartedEvent, ServerHeartbeatSucceededEvent } from '../../../src/sdam/events'; +import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; +import { Long, ObjectId } from 'bson'; +import { MongoClient } from '../../../src/mongo_client'; class MockServer { pool: any; diff --git a/test/unit/sdam/server.test.ts b/test/unit/sdam/server.test.ts index 399fb5bb50b..07e01c89f00 100644 --- a/test/unit/sdam/server.test.ts +++ b/test/unit/sdam/server.test.ts @@ -3,19 +3,13 @@ import { expect } from 'chai'; import { once } from 'events'; import * as sinon from 'sinon'; -import { - type Connection, - MongoError, - MongoErrorLabel, - MongoNetworkError, - MongoNetworkTimeoutError, - ObjectId, - Server, - ServerDescription, - ServerType, - TopologyType -} from '../../mongodb'; import { sleep, topologyWithPlaceholderClient } from '../../tools/utils'; +import { MongoError, MongoErrorLabel, MongoNetworkError, MongoNetworkTimeoutError } from '../../../src/error'; +import { Server } from '../../../src/sdam/server'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { Connection } from '../../../src/cmap/connection'; +import { ServerType, TopologyType } from '../../../src/sdam/common'; +import { ObjectId } from 'bson'; const handledErrors = [ { diff --git a/test/unit/sdam/server_description.test.ts b/test/unit/sdam/server_description.test.ts index 14c3ae0dbda..cc0d8293d87 100644 --- a/test/unit/sdam/server_description.test.ts +++ b/test/unit/sdam/server_description.test.ts @@ -1,13 +1,7 @@ import { expect } from 'chai'; - -import { - compareTopologyVersion, - Long, - MongoRuntimeError, - ObjectId, - ServerDescription, - type TopologyVersion -} from '../../mongodb'; +import { compareTopologyVersion, ServerDescription, TopologyVersion } from '../../../src/sdam/server_description'; +import { MongoRuntimeError } from '../../../src/error'; +import { Long, ObjectId } from 'bson'; 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..a949ee038ed 100644 --- a/test/unit/sdam/server_discovery_and_monitoring.prose.test.ts +++ b/test/unit/sdam/server_discovery_and_monitoring.prose.test.ts @@ -1,8 +1,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 { MongoClient } from '../../../src/mongo_client'; +import { SERVER_HEARTBEAT_FAILED, SERVER_HEARTBEAT_STARTED } from '../../../src/constants'; 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..c9d46bf06df 100644 --- a/test/unit/sdam/server_selection.test.ts +++ b/test/unit/sdam/server_selection.test.ts @@ -1,21 +1,16 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -import { - MIN_SECONDARY_WRITE_WIRE_VERSION, - MongoLogger, - ObjectId, - ReadPreference, - readPreferenceServerSelector, - sameServerSelector, - secondaryWritableServerSelector, - ServerDescription, - ServerSelectionEvent, - TopologyDescription, - TopologyType -} from '../../mongodb'; import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { TopologyDescription } from '../../../src/sdam/topology_description'; +import { MIN_SECONDARY_WRITE_WIRE_VERSION, readPreferenceServerSelector, sameServerSelector, secondaryWritableServerSelector } from '../../../src/sdam/server_selection'; +import { TopologyType } from '../../../src/sdam/common'; +import { ObjectId } from 'bson'; +import { ReadPreference } from '../../../src/read_preference'; +import { ServerSelectionEvent } from '../../../src/sdam/server_selection_events'; +import { MongoLogger } from '../../../src/mongo_logger'; describe('server selection', function () { const primary = new ServerDescription('127.0.0.1:27017', { diff --git a/test/unit/sdam/srv_polling.test.ts b/test/unit/sdam/srv_polling.test.ts index 908c5bf8013..28307c7ef99 100644 --- a/test/unit/sdam/srv_polling.test.ts +++ b/test/unit/sdam/srv_polling.test.ts @@ -4,15 +4,12 @@ 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 { topologyWithPlaceholderClient } from '../../tools/utils'; +import { TopologyDescription } from '../../../src/sdam/topology_description'; +import { TopologyType } from '../../../src/sdam/common'; +import { TopologyDescriptionChangedEvent } from '../../../src/sdam/events'; +import { MongoDriverError } from '../../../src/error'; +import { SrvPoller, SrvPollingEvent } from '../../../src/sdam/srv_polling'; describe('Mongos SRV Polling', function () { const SRV_HOST = 'darmok.tanagra.com'; @@ -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..113c3840019 100644 --- a/test/unit/sdam/topology.test.ts +++ b/test/unit/sdam/topology.test.ts @@ -6,27 +6,19 @@ import { satisfies } from 'semver'; import * as sinon from 'sinon'; import { clearTimeout } from 'timers'; -import { - isHello, - LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, - makeClientMetadata, - MongoClient, - MongoServerSelectionError, - ns, - ReadPreference, - RunCommandOperation, - RunCursorCommandOperation, - Server, - SrvPoller, - SrvPollingEvent, - TimeoutContext, - Topology, - TopologyDescription, - TopologyDescriptionChangedEvent, - TopologyType -} from '../../mongodb'; import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; +import { ReadPreference, SrvPollingEvent, TopologyDescriptionChangedEvent, TopologyType } from '../../../lib'; +import { makeClientMetadata } from '../../../src/cmap/handshake/client_metadata'; +import { LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, MongoServerSelectionError } from '../../../src/error'; +import { RunCursorCommandOperation, RunCommandOperation } from '../../../src/operations/run_command'; +import { SrvPoller } from '../../../src/sdam/srv_polling'; +import { Topology } from '../../../src/sdam/topology'; +import { TimeoutContext } from '../../../src/timeout'; +import { isHello, ns } from '../../../src/utils'; +import { MongoClient } from '../../../src/mongo_client'; +import { TopologyDescription } from '../../../src/sdam/topology_description'; +import { Server } from '../../../src/sdam/server'; describe('Topology (unit)', function () { let client, topology; From c68bdcb4380005e773ccba91a0f0b348c606c48f Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Fri, 19 Sep 2025 15:46:14 -0700 Subject: [PATCH 11/25] more migrations --- test/unit/cursor/aggregation_cursor.test.ts | 13 +++++-------- test/unit/cursor/run_command_cursor.test.ts | 4 ++-- test/unit/operations/aggregate.test.js | 2 +- test/unit/operations/find.test.ts | 4 ++-- test/unit/operations/get_more.test.ts | 16 +++++++--------- test/unit/operations/indexes.test.ts | 9 ++------- test/unit/operations/kill_cursors.test.ts | 13 +++++-------- test/unit/operations/list_collections.test.js | 3 ++- test/unit/operations/list_databases.test.ts | 4 ++-- 9 files changed, 28 insertions(+), 40 deletions(-) diff --git a/test/unit/cursor/aggregation_cursor.test.ts b/test/unit/cursor/aggregation_cursor.test.ts index e0d7a1223c1..86da07b6453 100644 --- a/test/unit/cursor/aggregation_cursor.test.ts +++ b/test/unit/cursor/aggregation_cursor.test.ts @@ -1,12 +1,9 @@ import { expect } from 'chai'; - -import { - AggregationCursor, - CursorTimeoutMode, - MongoAPIError, - MongoClient, - ns -} from '../../mongodb'; +import { MongoClient } from '../../../src/mongo_client'; +import { AggregationCursor } from '../../../src/cursor/aggregation_cursor'; +import { CursorTimeoutMode } from '../../../src/cursor/abstract_cursor'; +import { MongoAPIError } from '../../../src/error'; +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..719a2a848c9 100644 --- a/test/unit/cursor/run_command_cursor.test.ts +++ b/test/unit/cursor/run_command_cursor.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; - -import { MongoAPIError, MongoClient } from '../../mongodb'; +import { MongoClient } from '../../../src/mongo_client'; +import { MongoAPIError } from '../../../src/error'; describe('class RunCommandCursor', () => { let client: MongoClient; 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/find.test.ts b/test/unit/operations/find.test.ts index 81ab4f16718..7519a269dbe 100644 --- a/test/unit/operations/find.test.ts +++ b/test/unit/operations/find.test.ts @@ -1,7 +1,7 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; - -import { FindOperation, ns } from '../../mongodb'; +import { ns } from '../../../src/utils'; +import { FindOperation } from '../../../src/operations/find'; 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..1c300c2d3f7 100644 --- a/test/unit/operations/get_more.test.ts +++ b/test/unit/operations/get_more.test.ts @@ -1,15 +1,13 @@ import { expect } from 'chai'; -import { - Aspect, - GetMoreOperation, - Long, - ns, - ReadPreference, - Server, - ServerDescription -} from '../../mongodb'; import { topologyWithPlaceholderClient } from '../../tools/utils'; +import { ns } from '../../../src/utils'; +import { Long } from 'bson'; +import { ReadPreference } from '../../../src/read_preference'; +import { Server } from '../../../src/sdam/server'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { GetMoreOperation } from '../../../src/operations/get_more'; +import { Aspect } from '../../../src/operations/operation'; describe('GetMoreOperation', function () { const namespace = ns('db.coll'); diff --git a/test/unit/operations/indexes.test.ts b/test/unit/operations/indexes.test.ts index 8083cb5a6c5..ca59b8951bb 100644 --- a/test/unit/operations/indexes.test.ts +++ b/test/unit/operations/indexes.test.ts @@ -1,11 +1,6 @@ import { expect } from 'chai'; - -import { - CreateIndexesOperation, - type CreateIndexesOptions, - type IndexDirection, - ns -} from '../../mongodb'; +import { CreateIndexesOperation, CreateIndexesOptions, 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..7bd49c0b54b 100644 --- a/test/unit/operations/kill_cursors.test.ts +++ b/test/unit/operations/kill_cursors.test.ts @@ -1,14 +1,11 @@ import { expect } from 'chai'; -import { - KillCursorsOperation, - Long, - MongoDBNamespace, - ns, - Server, - ServerDescription -} from '../../mongodb'; import { topologyWithPlaceholderClient } from '../../tools/utils'; +import { Long } from 'bson'; +import { MongoDBNamespace, ns } from '../../../src/utils'; +import { Server } from '../../../src/sdam/server'; +import { ServerDescription } from '../../../src/sdam/server_description'; +import { KillCursorsOperation } from '../../../src/operations/kill_cursors'; describe('class KillCursorsOperation', () => { describe('constructor()', () => { 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..c79d0112960 100644 --- a/test/unit/operations/list_databases.test.ts +++ b/test/unit/operations/list_databases.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; - -import { ListDatabasesOperation, MongoDBNamespace } from '../../mongodb'; +import { MongoDBNamespace } from '../../../src/utils'; +import { ListDatabasesOperation } from '../../../src/operations/list_databases'; const mockDB = { s: { From abfb10efc21f729a60fa010a445cd948505cdf09 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Mon, 22 Sep 2025 10:55:23 -0700 Subject: [PATCH 12/25] last import fix --- test/unit/cursor/abstract_cursor.test.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/unit/cursor/abstract_cursor.test.ts b/test/unit/cursor/abstract_cursor.test.ts index 6cb8f04bf2b..96ac63c1528 100644 --- a/test/unit/cursor/abstract_cursor.test.ts +++ b/test/unit/cursor/abstract_cursor.test.ts @@ -1,11 +1,10 @@ import { expect } from 'chai'; -import { AbstractCursor, AbstractCursorOptions } from '../../../src/cursor/abstract_cursor'; +import { AbstractCursor, AbstractCursorOptions, InitialCursorResponse } from '../../../src/cursor/abstract_cursor'; import { MongoClient } from '../../../src/mongo_client'; import { ClientSession } from '../../../src/sessions'; -import { Callback, ns } from '../../../src/utils'; -import { - ExecutionResult -} from '../../mongodb'; +import { Server } from '../../../src/sdam/server'; +import { CursorResponse } from '../../../src/cmap/wire_protocol/responses'; +import { ns } from '../../../src/utils'; /** Minimal do nothing cursor to focus on testing the base cursor behavior */ class ConcreteCursor extends AbstractCursor { @@ -15,8 +14,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 }; } } From ac4c380d4f3f3d0956bbc75d1e179a54bd2785e8 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Mon, 22 Sep 2025 11:42:53 -0700 Subject: [PATCH 13/25] fixed imports --- test/unit/sdam/topology.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/unit/sdam/topology.test.ts b/test/unit/sdam/topology.test.ts index 113c3840019..c67fd0980d6 100644 --- a/test/unit/sdam/topology.test.ts +++ b/test/unit/sdam/topology.test.ts @@ -8,17 +8,19 @@ import { clearTimeout } from 'timers'; import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; -import { ReadPreference, SrvPollingEvent, TopologyDescriptionChangedEvent, TopologyType } from '../../../lib'; import { makeClientMetadata } from '../../../src/cmap/handshake/client_metadata'; import { LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, MongoServerSelectionError } from '../../../src/error'; import { RunCursorCommandOperation, RunCommandOperation } from '../../../src/operations/run_command'; -import { SrvPoller } from '../../../src/sdam/srv_polling'; +import { SrvPoller, SrvPollingEvent } from '../../../src/sdam/srv_polling'; import { Topology } from '../../../src/sdam/topology'; import { TimeoutContext } from '../../../src/timeout'; import { isHello, ns } from '../../../src/utils'; import { MongoClient } from '../../../src/mongo_client'; import { TopologyDescription } from '../../../src/sdam/topology_description'; import { Server } from '../../../src/sdam/server'; +import { TopologyDescriptionChangedEvent } from '../../../src/sdam/events'; +import { TopologyType } from '../../../src/sdam/common'; +import { ReadPreference } from '../../../src/read_preference'; describe('Topology (unit)', function () { let client, topology; From 1f9b43bd67408bde73c3121cc3cd35dfe39e40e4 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Mon, 22 Sep 2025 12:03:08 -0700 Subject: [PATCH 14/25] removing `done` from some tests --- test/unit/error.test.ts | 2 +- test/unit/sessions.test.ts | 18 +++++------------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/test/unit/error.test.ts b/test/unit/error.test.ts index d3ac0784173..c988c235975 100644 --- a/test/unit/error.test.ts +++ b/test/unit/error.test.ts @@ -405,7 +405,7 @@ describe('MongoErrors', () => { }); }); - it('should propagate writeConcernError.errInfo ', function (done) { + it('should propagate writeConcernError.errInfo ', function () { test.primaryServer.setMessageHandler(request => { const doc = request.document; if (isHello(doc)) { diff --git a/test/unit/sessions.test.ts b/test/unit/sessions.test.ts index a7ed28425b1..6c2ca1f22ba 100644 --- a/test/unit/sessions.test.ts +++ b/test/unit/sessions.test.ts @@ -491,7 +491,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); @@ -499,11 +499,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); @@ -512,11 +510,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 @@ -527,8 +523,6 @@ describe('Sessions - unit', function () { expect(session).to.exist; expect(session).to.not.eql(oldSession); pool.release(session); - - done(); }); describe('release()', () => { @@ -608,7 +602,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 @@ -616,10 +610,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(); @@ -636,7 +629,6 @@ describe('Sessions - unit', function () { pool.release(sessionC); pool.release(sessionD); - done(); }); }); }); From 0a910b82021e22f16ba9206cf1554a50195551a4 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Tue, 23 Sep 2025 08:31:03 -0700 Subject: [PATCH 15/25] more migrations --- test/tools/mongodb-mock/index.js | 2 +- test/tools/runner/config.ts | 18 +++----- test/tools/runner/filters/filter.ts | 2 +- test/tools/utils.ts | 18 +++----- test/unit/error.test.ts | 70 ++++++++++------------------- test/unit/sdam/topology.test.ts | 20 +++++++++ 6 files changed, 57 insertions(+), 73 deletions(-) diff --git a/test/tools/mongodb-mock/index.js b/test/tools/mongodb-mock/index.js index c05823e5177..1383fadde99 100644 --- a/test/tools/mongodb-mock/index.js +++ b/test/tools/mongodb-mock/index.js @@ -1,6 +1,6 @@ const fs = require('fs'); const { MockServer } = require('./src/server.js'); -const { LEGACY_HELLO_COMMAND } = require('../../mongodb'); +const { LEGACY_HELLO_COMMAND } = require('../../../src/constants.ts'); let mockServers = []; diff --git a/test/tools/runner/config.ts b/test/tools/runner/config.ts index 69314408a3f..95c7dc6b2de 100644 --- a/test/tools/runner/config.ts +++ b/test/tools/runner/config.ts @@ -8,21 +8,15 @@ import { type CompressorName } from 'mongodb-legacy'; import * as qs from 'querystring'; import * as url from 'url'; -import { - type AuthMechanism, - Double, - HostAddress, - Long, - MongoClient, - type MongoClientOptions, - ObjectId, - type ServerApi, - TopologyType, - type WriteConcernSettings -} from '../../mongodb'; import { getEnvironmentalOptions } from '../utils'; import { type Filter } from './filters/filter'; import { flakyTests } from './flaky'; +import { AuthMechanism } from '../../../src/cmap/auth/providers'; +import { MongoClient, MongoClientOptions, ServerApi } from '../../../src/mongo_client'; +import { TopologyType } from '../../../src/sdam/common'; +import { HostAddress } from '../../../src/utils'; +import { Double, Long, ObjectId } from 'bson'; +import { WriteConcernSettings } from '../../../src/write_concern'; interface ProxyParams { proxyHost?: string; diff --git a/test/tools/runner/filters/filter.ts b/test/tools/runner/filters/filter.ts index 6251cf44c8c..22590f0da51 100644 --- a/test/tools/runner/filters/filter.ts +++ b/test/tools/runner/filters/filter.ts @@ -1,4 +1,4 @@ -import { type MongoClient } from '../../../mongodb'; +import { MongoClient } from "../../../../src/mongo_client"; export abstract class Filter { async initializeFilter(_client: MongoClient, _context: Record): Promise { diff --git a/test/tools/utils.ts b/test/tools/utils.ts index 79d918a6897..67bdac2a515 100644 --- a/test/tools/utils.ts +++ b/test/tools/utils.ts @@ -3,25 +3,19 @@ import { on, once } from 'node:events'; import * as fs from 'node:fs/promises'; import * as path from 'node:path'; -import { EJSON } from 'bson'; +import { Document, EJSON } from 'bson'; import * as BSON from 'bson'; import { expect } from 'chai'; import { Readable } from 'stream'; import { setTimeout } from 'timers'; import { inspect, promisify } from 'util'; -import { - type AnyClientBulkWriteModel, - type Document, - type HostAddress, - MongoClient, - type MongoClientOptions, - now, - OP_MSG, - Topology, - type TopologyOptions -} from '../mongodb'; import { type TestConfiguration } from './runner/config'; +import { AnyClientBulkWriteModel } from '../../src/operations/client_bulk_write/common'; +import { HostAddress, now } from '../../src/utils'; +import { MongoClient, MongoClientOptions } from '../../src/mongo_client'; +import { Topology, TopologyOptions } from '../../src/sdam/topology'; +import { OP_MSG } from '../../src/cmap/wire_protocol/constants'; export function ensureCalledWith(stub: any, args: any[]) { args.forEach((m: any) => expect(stub).to.have.been.calledWith(m)); diff --git a/test/unit/error.test.ts b/test/unit/error.test.ts index c988c235975..302e70d24ab 100644 --- a/test/unit/error.test.ts +++ b/test/unit/error.test.ts @@ -13,6 +13,7 @@ import { isResumableError, isRetryableReadError, isSDAMUnrecoverableError, LEGAC import { PoolClosedError as MongoPoolClosedError, WaitQueueTimeoutError as MongoWaitQueueTimeoutError } from '../../src/cmap/errors'; import { RunCommandOperation } from '../../src/operations/run_command'; import { TimeoutContext } from '../../src/timeout'; +import { Topology } from '../../src/sdam/topology'; describe('MongoErrors', () => { let errorClassesFromEntryPoint = Object.fromEntries( @@ -334,31 +335,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 () { @@ -405,7 +389,7 @@ describe('MongoErrors', () => { }); }); - it('should propagate writeConcernError.errInfo ', function () { + it('should propagate writeConcernError.errInfo ', async function () { test.primaryServer.setMessageHandler(request => { const doc = request.document; if (isHello(doc)) { @@ -415,16 +399,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 @@ -435,23 +413,21 @@ 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 { + if (topology) { + topology.close(); + } + } }); }); diff --git a/test/unit/sdam/topology.test.ts b/test/unit/sdam/topology.test.ts index c67fd0980d6..25c14d6be44 100644 --- a/test/unit/sdam/topology.test.ts +++ b/test/unit/sdam/topology.test.ts @@ -6,6 +6,26 @@ import { satisfies } from 'semver'; import * as sinon from 'sinon'; import { clearTimeout } from 'timers'; +// import { +// isHello, +// LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, +// makeClientMetadata, +// MongoClient, +// MongoServerSelectionError, +// ns, +// ReadPreference, +// RunCommandOperation, +// RunCursorCommandOperation, +// Server, +// SrvPoller, +// SrvPollingEvent, +// TimeoutContext, +// Topology, +// TopologyDescription, +// TopologyDescriptionChangedEvent, +// TopologyType +// } from '../../mongodb'; + import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; import { makeClientMetadata } from '../../../src/cmap/handshake/client_metadata'; From 8d6bb36f55b99f98157a9f14e5560c2d9680d26d Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Tue, 23 Sep 2025 09:38:19 -0700 Subject: [PATCH 16/25] more migrations --- ...records_for_mongos_discovery.prose.test.ts | 5 +- .../state_machine.test.ts | 44 +++++++------ test/unit/sdam/topology.test.ts | 66 ++++++------------- 3 files changed, 45 insertions(+), 70 deletions(-) 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/client-side-encryption/state_machine.test.ts b/test/unit/client-side-encryption/state_machine.test.ts index 555c30a58b5..17a2d454115 100644 --- a/test/unit/client-side-encryption/state_machine.test.ts +++ b/test/unit/client-side-encryption/state_machine.test.ts @@ -124,7 +124,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'; @@ -138,22 +138,22 @@ 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); + }); }); @@ -191,13 +191,15 @@ 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 => { + it('rejects with the validation error', async function () { + try { + await stateMachine.kmsRequest(request); + expect.fail("should have failed with validation error"); + } catch (err) { expect(err.message).to.equal( `Insecure TLS options prohibited for aws: ${option}` ); - done(); - }); + } }); }); } diff --git a/test/unit/sdam/topology.test.ts b/test/unit/sdam/topology.test.ts index 25c14d6be44..6f503374759 100644 --- a/test/unit/sdam/topology.test.ts +++ b/test/unit/sdam/topology.test.ts @@ -6,26 +6,6 @@ import { satisfies } from 'semver'; import * as sinon from 'sinon'; import { clearTimeout } from 'timers'; -// import { -// isHello, -// LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, -// makeClientMetadata, -// MongoClient, -// MongoServerSelectionError, -// ns, -// ReadPreference, -// RunCommandOperation, -// RunCursorCommandOperation, -// Server, -// SrvPoller, -// SrvPollingEvent, -// TimeoutContext, -// Topology, -// TopologyDescription, -// TopologyDescriptionChangedEvent, -// TopologyType -// } from '../../mongodb'; - import * as mock from '../../tools/mongodb-mock/index'; import { topologyWithPlaceholderClient } from '../../tools/utils'; import { makeClientMetadata } from '../../../src/cmap/handshake/client_metadata'; @@ -109,7 +89,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; @@ -123,30 +103,26 @@ 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" + }); + try { + await server.command(new RunCursorCommandOperation(ns('admin.$cmd'), { ping: 1 }, {}), ctx); + expect.fail('expected command to fail') + } catch (err) { + expect(err).to.exist; + expect(err).to.match(/timed out/); + } finally { + topology.close(); + } + }); }); From 6ebbaca2a0d48f0deb770c19b2d77c1b09c87476 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Tue, 23 Sep 2025 09:54:28 -0700 Subject: [PATCH 17/25] lint autofixes --- test/action/dependency.test.ts | 2 +- test/integration/auth/auth.prose.test.ts | 4 +- test/integration/auth/mongodb_aws.test.ts | 10 ++--- .../enumerate_databases.prose.test.ts | 3 +- test/integration/enumerate_databases.test.ts | 4 +- test/integration/index_management.test.ts | 13 +++--- test/tools/runner/config.ts | 12 +++--- test/tools/runner/filters/filter.ts | 2 +- test/tools/utils.ts | 12 +++--- test/unit/change_stream.test.ts | 1 + .../auto_encrypter.test.ts | 4 +- .../client_encryption.test.ts | 2 +- .../providers/credentialsProvider.test.ts | 2 +- .../state_machine.test.ts | 14 +++---- test/unit/cmap/auth/auth_provider.test.ts | 3 +- test/unit/cmap/auth/gssapi.test.ts | 7 +++- .../automated_callback_workflow.test.ts | 6 +-- .../azure_machine_workflow.test.ts | 2 +- .../mongodb_oidc/gcp_machine_workflow.test.ts | 2 +- test/unit/cmap/connect.test.ts | 26 +++++++----- test/unit/cmap/connection.test.ts | 6 +-- test/unit/cmap/connection_pool.test.js | 2 +- test/unit/cmap/connection_pool_events.test.ts | 3 +- .../cmap/handshake/client_metadata.test.ts | 8 +++- .../cmap/wire_protocol/compression.test.ts | 1 + .../wire_protocol/on_demand/document.test.ts | 3 +- .../unit/cmap/wire_protocol/responses.test.ts | 3 +- test/unit/collection.test.ts | 6 +-- test/unit/commands.test.ts | 8 +++- test/unit/connection_string.test.ts | 15 +++++-- test/unit/cursor/abstract_cursor.test.ts | 13 ++++-- test/unit/cursor/aggregation_cursor.test.ts | 5 ++- test/unit/cursor/run_command_cursor.test.ts | 3 +- test/unit/db.test.ts | 3 +- test/unit/error.test.ts | 41 +++++++++++++++---- test/unit/explain.test.ts | 3 +- test/unit/mongo_client.test.ts | 9 ++-- test/unit/mongo_logger.test.ts | 30 +++++++++++++- .../client_bulk_write/command_builder.test.ts | 20 ++++++++- .../client_bulk_write/results_merger.test.ts | 5 ++- test/unit/operations/find.test.ts | 3 +- test/unit/operations/get_more.test.ts | 10 ++--- test/unit/operations/indexes.test.ts | 7 +++- test/unit/operations/kill_cursors.test.ts | 8 ++-- test/unit/operations/list_databases.test.ts | 3 +- test/unit/sdam/monitor.test.ts | 20 +++++---- test/unit/sdam/server.test.ts | 15 ++++--- test/unit/sdam/server_description.test.ts | 9 +++- ...ver_discovery_and_monitoring.prose.test.ts | 3 +- test/unit/sdam/server_selection.test.ts | 21 ++++++---- test/unit/sdam/srv_polling.test.ts | 6 +-- test/unit/sdam/topology.test.ts | 33 ++++++++------- test/unit/sessions.test.ts | 11 +++-- test/unit/timeout.test.ts | 9 +++- test/unit/transactions.test.ts | 3 +- test/unit/utils.test.ts | 23 +++++++++-- test/unit/write_concern.test.ts | 1 + 57 files changed, 335 insertions(+), 168 deletions(-) diff --git a/test/action/dependency.test.ts b/test/action/dependency.test.ts index 7a404a3c120..d68f34a20bb 100644 --- a/test/action/dependency.test.ts +++ b/test/action/dependency.test.ts @@ -5,8 +5,8 @@ import * as path from 'node:path'; import { expect } from 'chai'; import { dependencies, peerDependencies, peerDependenciesMeta } from '../../package.json'; -import { alphabetically, itInNodeProcess, sorted } from '../tools/utils'; import { setDifference } from '../../src/utils'; +import { alphabetically, itInNodeProcess, sorted } from '../tools/utils'; const EXPECTED_DEPENDENCIES = sorted( ['@mongodb-js/saslprep', 'bson', 'mongodb-connection-string-url'], diff --git a/test/integration/auth/auth.prose.test.ts b/test/integration/auth/auth.prose.test.ts index 3f1138c92b7..da9ea3b2c27 100644 --- a/test/integration/auth/auth.prose.test.ts +++ b/test/integration/auth/auth.prose.test.ts @@ -1,11 +1,11 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -import { type TestConfiguration } from '../../tools/runner/config'; -import { MongoClient } from '../../../src/mongo_client'; import { ScramSHA256 } from '../../../src/cmap/auth/scram'; import { Connection } from '../../../src/cmap/connection'; import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; +import { type MongoClient } from '../../../src/mongo_client'; +import { type TestConfiguration } from '../../tools/runner/config'; function makeConnectionString(config, username, password) { return `mongodb://${username}:${password}@${config.host}:${config.port}/admin?`; diff --git a/test/integration/auth/mongodb_aws.test.ts b/test/integration/auth/mongodb_aws.test.ts index 0ca28866022..a5011545d06 100644 --- a/test/integration/auth/mongodb_aws.test.ts +++ b/test/integration/auth/mongodb_aws.test.ts @@ -1,18 +1,18 @@ import * as process from 'node:process'; +import { type Document } from 'bson'; import { expect } from 'chai'; import * as http from 'http'; import { performance } from 'perf_hooks'; import * as sinon from 'sinon'; import { refreshKMSCredentials } from '../../../src/client-side-encryption/providers'; -import { MongoClient } from '../../../src/mongo_client'; import { AWSSDKCredentialProvider } from '../../../src/cmap/auth/aws_temporary_credentials'; +import { type CommandOptions, Connection } from '../../../src/cmap/connection'; +import { type MongoDBResponseConstructor } from '../../../src/cmap/wire_protocol/responses'; import { MongoAWSError, MongoMissingDependencyError, MongoServerError } from '../../../src/error'; -import { MongoDBNamespace } from '../../../src/utils'; -import { Document } from 'bson'; -import { CommandOptions, Connection } from '../../../src/cmap/connection'; -import { MongoDBResponseConstructor } from '../../../src/cmap/wire_protocol/responses'; +import { type MongoClient } from '../../../src/mongo_client'; +import { type MongoDBNamespace } from '../../../src/utils'; const isMongoDBAWSAuthEnvironment = (process.env.MONGODB_URI ?? '').includes('MONGODB-AWS'); diff --git a/test/integration/enumerate_databases.prose.test.ts b/test/integration/enumerate_databases.prose.test.ts index ecd24d911d4..20750b88919 100644 --- a/test/integration/enumerate_databases.prose.test.ts +++ b/test/integration/enumerate_databases.prose.test.ts @@ -1,5 +1,6 @@ import { expect } from 'chai'; -import { MongoClient } from '../../src/mongo_client'; + +import { type MongoClient } from '../../src/mongo_client'; const REQUIRED_DBS = ['admin', 'local', 'config']; const DB_NAME = 'listDatabasesTest'; diff --git a/test/integration/enumerate_databases.test.ts b/test/integration/enumerate_databases.test.ts index 3788337820a..e1da9754b29 100644 --- a/test/integration/enumerate_databases.test.ts +++ b/test/integration/enumerate_databases.test.ts @@ -1,9 +1,9 @@ import { expect } from 'chai'; import { once } from 'events'; -import { TestBuilder, UnifiedTestSuiteBuilder } from '../tools/unified_suite_builder'; -import { MongoClient } from '../../src/mongo_client'; import { MongoServerError } from '../../src/error'; +import { type MongoClient } from '../../src/mongo_client'; +import { TestBuilder, UnifiedTestSuiteBuilder } from '../tools/unified_suite_builder'; const metadata: MongoDBMetadataUI = { requires: { diff --git a/test/integration/index_management.test.ts b/test/integration/index_management.test.ts index 8a98484812c..391002fdc54 100644 --- a/test/integration/index_management.test.ts +++ b/test/integration/index_management.test.ts @@ -1,12 +1,15 @@ import { expect } from 'chai'; +import { + type CommandStartedEvent, + type CommandSucceededEvent +} from '../../src/cmap/command_monitoring_events'; +import { type Collection } from '../../src/collection'; +import { type Db } from '../../src/db'; +import { MongoServerError } from '../../src/error'; +import { type MongoClient } from '../../src/mongo_client'; import { type FailCommandFailPoint } from '../tools/utils'; import { assert as test, filterForCommands, setupDatabase } from './shared'; -import { MongoClient } from '../../src/mongo_client'; -import { Db } from '../../src/db'; -import { Collection } from '../../src/collection'; -import { MongoServerError } from '../../src/error'; -import { CommandStartedEvent, CommandSucceededEvent } from '../../src/cmap/command_monitoring_events'; describe('Indexes', function () { let client: MongoClient; diff --git a/test/tools/runner/config.ts b/test/tools/runner/config.ts index 95c7dc6b2de..5b537e26e80 100644 --- a/test/tools/runner/config.ts +++ b/test/tools/runner/config.ts @@ -1,6 +1,7 @@ import * as util from 'node:util'; import * as types from 'node:util/types'; +import { Double, Long, ObjectId } from 'bson'; import { expect } from 'chai'; import { type Context } from 'mocha'; import ConnectionString from 'mongodb-connection-string-url'; @@ -8,15 +9,14 @@ import { type CompressorName } from 'mongodb-legacy'; import * as qs from 'querystring'; import * as url from 'url'; +import { type AuthMechanism } from '../../../src/cmap/auth/providers'; +import { MongoClient, type MongoClientOptions, type ServerApi } from '../../../src/mongo_client'; +import { TopologyType } from '../../../src/sdam/common'; +import { HostAddress } from '../../../src/utils'; +import { type WriteConcernSettings } from '../../../src/write_concern'; import { getEnvironmentalOptions } from '../utils'; import { type Filter } from './filters/filter'; import { flakyTests } from './flaky'; -import { AuthMechanism } from '../../../src/cmap/auth/providers'; -import { MongoClient, MongoClientOptions, ServerApi } from '../../../src/mongo_client'; -import { TopologyType } from '../../../src/sdam/common'; -import { HostAddress } from '../../../src/utils'; -import { Double, Long, ObjectId } from 'bson'; -import { WriteConcernSettings } from '../../../src/write_concern'; interface ProxyParams { proxyHost?: string; diff --git a/test/tools/runner/filters/filter.ts b/test/tools/runner/filters/filter.ts index 22590f0da51..510d2370ea6 100644 --- a/test/tools/runner/filters/filter.ts +++ b/test/tools/runner/filters/filter.ts @@ -1,4 +1,4 @@ -import { MongoClient } from "../../../../src/mongo_client"; +import { type MongoClient } from '../../../../src/mongo_client'; export abstract class Filter { async initializeFilter(_client: MongoClient, _context: Record): Promise { diff --git a/test/tools/utils.ts b/test/tools/utils.ts index 67bdac2a515..cb30ada1cf5 100644 --- a/test/tools/utils.ts +++ b/test/tools/utils.ts @@ -3,19 +3,19 @@ import { on, once } from 'node:events'; import * as fs from 'node:fs/promises'; import * as path from 'node:path'; -import { Document, EJSON } from 'bson'; +import { type Document, EJSON } from 'bson'; import * as BSON from 'bson'; import { expect } from 'chai'; import { Readable } from 'stream'; import { setTimeout } from 'timers'; import { inspect, promisify } from 'util'; -import { type TestConfiguration } from './runner/config'; -import { AnyClientBulkWriteModel } from '../../src/operations/client_bulk_write/common'; -import { HostAddress, now } from '../../src/utils'; -import { MongoClient, MongoClientOptions } from '../../src/mongo_client'; -import { Topology, TopologyOptions } from '../../src/sdam/topology'; import { OP_MSG } from '../../src/cmap/wire_protocol/constants'; +import { MongoClient, type MongoClientOptions } from '../../src/mongo_client'; +import { type AnyClientBulkWriteModel } from '../../src/operations/client_bulk_write/common'; +import { Topology, type TopologyOptions } from '../../src/sdam/topology'; +import { type HostAddress, now } from '../../src/utils'; +import { type TestConfiguration } from './runner/config'; export function ensureCalledWith(stub: any, args: any[]) { args.forEach((m: any) => expect(stub).to.have.been.calledWith(m)); diff --git a/test/unit/change_stream.test.ts b/test/unit/change_stream.test.ts index b4f0bab7b92..36976181bd5 100644 --- a/test/unit/change_stream.test.ts +++ b/test/unit/change_stream.test.ts @@ -1,6 +1,7 @@ import { Long, Timestamp } from 'bson'; import { expect } from 'chai'; import * as sinon from 'sinon'; + import { ChangeStreamCursor } from '../../src/cursor/change_stream_cursor'; import { MongoClient } from '../../src/mongo_client'; import { MongoDBNamespace } from '../../src/utils'; diff --git a/test/unit/client-side-encryption/auto_encrypter.test.ts b/test/unit/client-side-encryption/auto_encrypter.test.ts index 5b9e8778a80..a7a00beba03 100644 --- a/test/unit/client-side-encryption/auto_encrypter.test.ts +++ b/test/unit/client-side-encryption/auto_encrypter.test.ts @@ -1,15 +1,15 @@ +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 * as requirements from './requirements.helper'; -import { BSON } from 'bson'; -import { DataKey } from '../../../src/client-side-encryption/client_encryption'; const bson = BSON; const { EJSON } = BSON; diff --git a/test/unit/client-side-encryption/client_encryption.test.ts b/test/unit/client-side-encryption/client_encryption.test.ts index 9eb13084904..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,6 @@ import { MongoCryptCreateEncryptedCollectionError } from '../../../src/client-side-encryption/errors'; import { StateMachine } from '../../../src/client-side-encryption/state_machine'; -import { Binary, BSON, deserialize } from 'bson'; import { MongoClient } from '../../../src/mongo_client'; const { EJSON } = BSON; diff --git a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts index 79c4af56d60..5dbca90dfb3 100644 --- a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts +++ b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts @@ -13,9 +13,9 @@ 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 * as requirements from '../requirements.helper'; -import { MongoNetworkTimeoutError } from '../../../../src/error'; const originalAccessKeyId = process.env.AWS_ACCESS_KEY_ID; const originalSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY; diff --git a/test/unit/client-side-encryption/state_machine.test.ts b/test/unit/client-side-encryption/state_machine.test.ts index 17a2d454115..9cf10d94912 100644 --- a/test/unit/client-side-encryption/state_machine.test.ts +++ b/test/unit/client-side-encryption/state_machine.test.ts @@ -1,23 +1,22 @@ +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 { sleep } from '../../tools/utils'; -import { BSON, Int32, Long, serialize } from 'bson'; import { MongoClient } from '../../../src/mongo_client'; -import { Collection } from '../../../src/collection'; +import { type FindOptions } from '../../../src/operations/find'; import { CSOTTimeoutContext } from '../../../src/timeout'; import { squashError } from '../../../src/utils'; -import { CursorTimeoutContext } from '../../../src/cursor/abstract_cursor'; -import { FindOptions } from '../../../src/operations/find'; +import { sleep } from '../../tools/utils'; describe('StateMachine', function () { class MockRequest implements MongoCryptKMSRequest { @@ -153,7 +152,6 @@ describe('StateMachine', function () { expect(status).to.equal('resolved'); expect(request.bytesNeeded).to.equal(0); - }); }); @@ -194,7 +192,7 @@ describe('StateMachine', function () { it('rejects with the validation error', async function () { try { await stateMachine.kmsRequest(request); - expect.fail("should have failed with validation error"); + expect.fail('should have failed with validation error'); } catch (err) { 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 b69ba5b9739..067a691dd5d 100644 --- a/test/unit/cmap/auth/auth_provider.test.ts +++ b/test/unit/cmap/auth/auth_provider.test.ts @@ -1,5 +1,6 @@ import { expect } from 'chai'; -import { AuthContext, AuthProvider } from '../../../../src/cmap/auth/auth_provider'; + +import { type AuthContext, AuthProvider } from '../../../../src/cmap/auth/auth_provider'; import { MongoRuntimeError } from '../../../../src/error'; describe('AuthProvider', function () { diff --git a/test/unit/cmap/auth/gssapi.test.ts b/test/unit/cmap/auth/gssapi.test.ts index 7723d63346d..9df2500b8e0 100644 --- a/test/unit/cmap/auth/gssapi.test.ts +++ b/test/unit/cmap/auth/gssapi.test.ts @@ -1,7 +1,12 @@ import { expect } from 'chai'; import { promises as dns } from 'dns'; import * as sinon from 'sinon'; -import { GSSAPICanonicalizationValue, performGSSAPICanonicalizeHostName, resolveCname } from '../../../../src/cmap/auth/gssapi'; + +import { + GSSAPICanonicalizationValue, + performGSSAPICanonicalizeHostName, + resolveCname +} 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 2e91c8a5b6e..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,12 +1,12 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -import { callback } from '../../../../../src/cmap/auth/mongodb_oidc/gcp_machine_workflow'; -import { TokenCache } from '../../../../../src/cmap/auth/mongodb_oidc/token_cache'; +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 { Connection } from '../../../../../src/cmap/connection'; -import { MongoCredentials } from '../../../../../src/cmap/auth/mongo_credentials'; 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 36d29c44c53..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, OIDCCallbackParams } from '../../../../../src/cmap/auth/mongodb_oidc'; 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 411e16f4f85..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, OIDCCallbackParams } from '../../../../../src/cmap/auth/mongodb_oidc'; describe('GCP machine workflow', function () { describe('#callback', function () { diff --git a/test/unit/cmap/connect.test.ts b/test/unit/cmap/connect.test.ts index 3b57cc00caa..4a69683ae97 100644 --- a/test/unit/cmap/connect.test.ts +++ b/test/unit/cmap/connect.test.ts @@ -1,18 +1,22 @@ +import { type ConnectionOptions } from 'node:tls'; + +import { type Document } from 'bson'; import { expect } from 'chai'; -import { genClusterTime } from '../../tools/common'; -import * as mock from '../../tools/mongodb-mock/index'; -import { Document } from 'bson'; -import { ConnectionOptions } from 'node:tls'; +import { MongoCredentials } from '../../../src/cmap/auth/mongo_credentials'; import { connect, prepareHandshakeDocument } from '../../../src/cmap/connect'; -import { addContainerMetadata, ClientMetadata } from '../../../src/cmap/handshake/client_metadata'; +import { type Connection } from '../../../src/cmap/connection'; +import { + addContainerMetadata, + type ClientMetadata +} from '../../../src/cmap/handshake/client_metadata'; import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; -import { HostAddress, isHello } from '../../../src/utils'; -import { MongoCredentials } from '../../../src/cmap/auth/mongo_credentials'; -import { MongoClientAuthProviders } from '../../../src/mongo_client_auth_providers'; -import { Connection } from '../../../src/cmap/connection'; 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'; const CONNECT_DEFAULTS = { id: 1, @@ -182,8 +186,8 @@ describe('Connect Tests', function () { hostAddress: new HostAddress('non-existent:27018') }); } catch (error) { - expect(error).to.be.instanceOf(MongoNetworkError); -} + expect(error).to.be.instanceOf(MongoNetworkError); + } }); describe('prepareHandshakeDocument', () => { diff --git a/test/unit/cmap/connection.test.ts b/test/unit/cmap/connection.test.ts index b53b6195721..fcd15a5dd38 100644 --- a/test/unit/cmap/connection.test.ts +++ b/test/unit/cmap/connection.test.ts @@ -6,11 +6,11 @@ import * as sinon from 'sinon'; import { setTimeout } from 'timers/promises'; import { connect } from '../../../src/cmap/connect'; -import * as mock from '../../tools/mongodb-mock/index'; import { Connection, SizedMessageTransform } from '../../../src/cmap/connection'; -import { isHello, MongoDBCollectionNamespace, ns, promiseWithResolvers } from '../../../src/utils'; -import { MongoClientAuthProviders } from '../../../src/mongo_client_auth_providers'; 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 = { id: 0, diff --git a/test/unit/cmap/connection_pool.test.js b/test/unit/cmap/connection_pool.test.js index 21db4a8bb8b..81bff92d0fd 100644 --- a/test/unit/cmap/connection_pool.test.js +++ b/test/unit/cmap/connection_pool.test.js @@ -1,7 +1,7 @@ 'use strict'; const { ConnectionPool } = require('../../../src/cmap/connection_pool'); -const { MongoError } = require( '../../../src/error'); +const { MongoError } = require('../../../src/error'); const { WaitQueueTimeoutError } = require('../../../src/cmap/errors'); const mock = require('../../tools/mongodb-mock/index'); const sinon = require('sinon'); diff --git a/test/unit/cmap/connection_pool_events.test.ts b/test/unit/cmap/connection_pool_events.test.ts index 2b6ecc6d420..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 } from '../../../src/cmap/connection_pool'; import { ConnectionPoolCreatedEvent } from '../../../src/cmap/connection_pool_events'; -import { ConnectionPool } from '../../../src/cmap/connection_pool'; 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 6b470302da2..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'; @@ -5,8 +6,11 @@ import * as sinon from 'sinon'; import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; -import { getFAASEnv, LimitedSizeDocument, makeClientMetadata } from '../../../../src/cmap/handshake/client_metadata'; -import { Int32, ObjectId } from 'bson'; +import { + getFAASEnv, + LimitedSizeDocument, + makeClientMetadata +} from '../../../../src/cmap/handshake/client_metadata'; import { MongoInvalidArgumentError } from '../../../../src/error'; describe('client metadata module', () => { diff --git a/test/unit/cmap/wire_protocol/compression.test.ts b/test/unit/cmap/wire_protocol/compression.test.ts index 5f4cdd4f606..77aec98e457 100644 --- a/test/unit/cmap/wire_protocol/compression.test.ts +++ b/test/unit/cmap/wire_protocol/compression.test.ts @@ -1,5 +1,6 @@ import * as zstd from '@mongodb-js/zstd'; import { expect } from 'chai'; + import { compress, Compressor, decompress } from '../../../../src/cmap/wire_protocol/compression'; describe('compression', 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 fb701b897fb..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,5 +1,6 @@ -import { BSON, Timestamp, Binary, ObjectId, BSONType, BSONError } from 'bson'; +import { Binary, BSON, BSONError, BSONType, ObjectId, Timestamp } from 'bson'; import { expect } from 'chai'; + import { OnDemandDocument } from '../../../../../src/cmap/wire_protocol/on_demand/document'; describe('class OnDemandDocument', () => { diff --git a/test/unit/cmap/wire_protocol/responses.test.ts b/test/unit/cmap/wire_protocol/responses.test.ts index 5e250482864..50368489190 100644 --- a/test/unit/cmap/wire_protocol/responses.test.ts +++ b/test/unit/cmap/wire_protocol/responses.test.ts @@ -1,7 +1,8 @@ import { expect } from 'chai'; -import { CursorResponse, MongoDBResponse } from '../../../../src/cmap/wire_protocol/responses'; + 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', () => { diff --git a/test/unit/collection.test.ts b/test/unit/collection.test.ts index 9aff74af824..0f82c33be2e 100644 --- a/test/unit/collection.test.ts +++ b/test/unit/collection.test.ts @@ -1,9 +1,9 @@ +import { Long } from 'bson'; import { expect } from 'chai'; -import { cleanup, createServer, HELLO } from '../tools/mongodb-mock'; import { MongoClient } from '../../src/mongo_client'; import { isHello } from '../../src/utils'; -import { Long } from 'bson'; +import { cleanup, createServer, HELLO } from '../tools/mongodb-mock'; describe('Collection', function () { let server = null; @@ -135,7 +135,7 @@ describe('Collection', function () { }; await collection.bulkWrite([{ insertOne: { document: { a: 1 } } }], options); - }; + } // ordered bulk write, testing change in ordered.js it('should only set bypass document validation if strictly true in ordered bulkWrite', async function () { diff --git a/test/unit/commands.test.ts b/test/unit/commands.test.ts index 1e5199025a2..fcf951dcd68 100644 --- a/test/unit/commands.test.ts +++ b/test/unit/commands.test.ts @@ -1,9 +1,13 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -import * as compression from '../../src/cmap/wire_protocol/compression'; -import { compress, Compressor, uncompressibleCommands } from '../../src/cmap/wire_protocol/compression'; import { OpCompressedRequest, OpMsgRequest, OpQueryRequest } from '../../src/cmap/commands'; +import * as compression from '../../src/cmap/wire_protocol/compression'; +import { + compress, + Compressor, + uncompressibleCommands +} from '../../src/cmap/wire_protocol/compression'; import { OP_MSG, OP_QUERY } from '../../src/cmap/wire_protocol/constants'; describe('class OpCompressedRequest', () => { diff --git a/test/unit/connection_string.test.ts b/test/unit/connection_string.test.ts index 76893c1d3e8..62adaab40bb 100644 --- a/test/unit/connection_string.test.ts +++ b/test/unit/connection_string.test.ts @@ -5,12 +5,19 @@ import { expect } from 'chai'; import * as dns from 'dns'; import * as sinon from 'sinon'; import { inspect } from 'util'; -import { parseOptions, resolveSRVRecord } from '../../src/connection_string'; -import { MongoAPIError, MongoDriverError, MongoInvalidArgumentError, MongoParseError, MongoRuntimeError } from '../../src/error'; + import { DEFAULT_ALLOWED_HOSTS, MongoCredentials } from '../../src/cmap/auth/mongo_credentials'; import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from '../../src/cmap/auth/providers'; -import { MongoClient, MongoOptions } from '../../src/mongo_client'; -import { Log } from '../../src/mongo_logger'; +import { parseOptions, resolveSRVRecord } from '../../src/connection_string'; +import { + MongoAPIError, + MongoDriverError, + MongoInvalidArgumentError, + MongoParseError, + 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 () { diff --git a/test/unit/cursor/abstract_cursor.test.ts b/test/unit/cursor/abstract_cursor.test.ts index 96ac63c1528..deb7784c83a 100644 --- a/test/unit/cursor/abstract_cursor.test.ts +++ b/test/unit/cursor/abstract_cursor.test.ts @@ -1,9 +1,14 @@ import { expect } from 'chai'; -import { AbstractCursor, AbstractCursorOptions, InitialCursorResponse } from '../../../src/cursor/abstract_cursor'; -import { MongoClient } from '../../../src/mongo_client'; -import { ClientSession } from '../../../src/sessions'; -import { Server } from '../../../src/sdam/server'; + import { CursorResponse } from '../../../src/cmap/wire_protocol/responses'; +import { + AbstractCursor, + type AbstractCursorOptions, + 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 */ diff --git a/test/unit/cursor/aggregation_cursor.test.ts b/test/unit/cursor/aggregation_cursor.test.ts index 86da07b6453..ac8b6c0d610 100644 --- a/test/unit/cursor/aggregation_cursor.test.ts +++ b/test/unit/cursor/aggregation_cursor.test.ts @@ -1,8 +1,9 @@ import { expect } from 'chai'; -import { MongoClient } from '../../../src/mongo_client'; -import { AggregationCursor } from '../../../src/cursor/aggregation_cursor'; + 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', () => { diff --git a/test/unit/cursor/run_command_cursor.test.ts b/test/unit/cursor/run_command_cursor.test.ts index 719a2a848c9..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 { MongoClient } from '../../../src/mongo_client'; + 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 ecf81968a4d..6535e49c78f 100644 --- a/test/unit/db.test.ts +++ b/test/unit/db.test.ts @@ -1,6 +1,7 @@ import { expect } from 'chai'; + +import { Db, type DbOptions } from '../../src/db'; import { MongoClient } from '../../src/mongo_client'; -import { Db, DbOptions } from '../../src/db'; import { ReadPreference } from '../../src/read_preference'; describe('class Db', function () { diff --git a/test/unit/error.test.ts b/test/unit/error.test.ts index 302e70d24ab..f6bb582897a 100644 --- a/test/unit/error.test.ts +++ b/test/unit/error.test.ts @@ -1,19 +1,46 @@ 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 { + 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, + MongoMissingDependencyError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoOperationTimeoutError, + MongoParseError, + MongoRuntimeError, + MongoServerError, + MongoSystemError, + MongoWriteConcernError, + type TopologyDescription, + 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'; -import { isHello, ns, setDifference } from '../../src/utils'; -import { MongoDriverError, MongoError, MongoErrorLabel, MongoMissingDependencyError, MongoNetworkError, MongoNetworkTimeoutError, MongoOperationTimeoutError, MongoParseError, MongoRuntimeError, MongoServerError, MongoSystemError, MongoWriteConcernError, TopologyDescription, TopologyOptions } from '../../src/index'; -import { 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 { PoolClosedError as MongoPoolClosedError, WaitQueueTimeoutError as MongoWaitQueueTimeoutError } from '../../src/cmap/errors'; -import { RunCommandOperation } from '../../src/operations/run_command'; -import { TimeoutContext } from '../../src/timeout'; -import { Topology } from '../../src/sdam/topology'; describe('MongoErrors', () => { let errorClassesFromEntryPoint = Object.fromEntries( diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index 77e46eeb646..403709e0b41 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -1,9 +1,10 @@ import { expect } from 'chai'; import { it } from 'mocha'; + +import { FindCursor } from '../../src/cursor/find_cursor'; import { Explain, ExplainVerbosity } from '../../src/explain'; import { MongoClient } from '../../src/mongo_client'; import { MongoDBNamespace } from '../../src/utils'; -import { FindCursor } from '../../src/cursor/find_cursor'; describe('class Explain {}', function () { describe('static .fromOptions()', function () { diff --git a/test/unit/mongo_client.test.ts b/test/unit/mongo_client.test.ts index 0eafabe2ec0..065cc306ba0 100644 --- a/test/unit/mongo_client.test.ts +++ b/test/unit/mongo_client.test.ts @@ -4,14 +4,15 @@ import * as os from 'os'; import * as sinon from 'sinon'; import { Writable } from 'stream'; import { inspect } from 'util'; + +import { MongoCredentials } from '../../src/cmap/auth/mongo_credentials'; import { parseOptions, resolveSRVRecord } from '../../src/connection_string'; -import { MongoClient, MongoClientOptions, ServerApiVersion } from '../../src/mongo_client'; -import { WriteConcern } from '../../src/write_concern'; import { MongoAPIError, MongoInvalidArgumentError, MongoParseError } from '../../src/error'; -import { ReadPreference } from '../../src/read_preference'; +import { MongoClient, type MongoClientOptions, ServerApiVersion } from '../../src/mongo_client'; import { MongoLoggableComponent, MongoLogger, SeverityLevel } from '../../src/mongo_logger'; import { ReadConcern } from '../../src/read_concern'; -import { MongoCredentials } from '../../src/cmap/auth/mongo_credentials'; +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 02545fbf138..c3b1aaec46b 100644 --- a/test/unit/mongo_logger.test.ts +++ b/test/unit/mongo_logger.test.ts @@ -4,9 +4,35 @@ import * as sinon from 'sinon'; import { Readable, Writable } from 'stream'; import { inspect } from 'util'; +import { + COMMAND_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECKED_IN, + CONNECTION_CHECKED_OUT, + CONNECTION_CLOSED, + CONNECTION_CREATED, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_POOL_CREATED, + CONNECTION_POOL_READY, + CONNECTION_READY +} from '../../src/constants'; +import { + createStdioLogger, + DEFAULT_MAX_DOCUMENT_LENGTH, + type Log, + type MongoDBLogWritable, + MongoLoggableComponent, + MongoLogger, + type MongoLoggerOptions, + parseSeverityFromString, + SeverityLevel, + stringifyWithMaxLen +} from '../../src/mongo_logger'; import { sleep } from '../tools/utils'; -import { createStdioLogger, DEFAULT_MAX_DOCUMENT_LENGTH, Log, MongoDBLogWritable, MongoLoggableComponent, MongoLogger, MongoLoggerOptions, parseSeverityFromString, SeverityLevel, stringifyWithMaxLen } from '../../src/mongo_logger'; -import { COMMAND_FAILED, COMMAND_STARTED, COMMAND_SUCCEEDED, CONNECTION_CHECK_OUT_FAILED, CONNECTION_CHECK_OUT_STARTED, CONNECTION_CHECKED_IN, CONNECTION_CHECKED_OUT, CONNECTION_CLOSED, CONNECTION_CREATED, CONNECTION_POOL_CLEARED, CONNECTION_POOL_CLOSED, CONNECTION_POOL_CREATED, CONNECTION_POOL_READY, CONNECTION_READY } from '../../src/constants'; class BufferingStream extends Writable { buffer: any[] = []; 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 11b5a356036..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,8 +1,24 @@ import { ObjectId } from 'bson'; import { expect } from 'chai'; -import { ClientDeleteManyModel, ClientDeleteOneModel, ClientInsertOneModel, ClientReplaceOneModel, ClientUpdateManyModel, ClientUpdateOneModel } from '../../../../src/operations/client_bulk_write/common'; -import { buildDeleteManyOperation, buildDeleteOneOperation, buildInsertOneOperation, buildReplaceOneOperation, buildUpdateManyOperation, buildUpdateOneOperation, ClientBulkWriteCommandBuilder } from '../../../../src/operations/client_bulk_write/command_builder'; + import { DocumentSequence } from '../../../../src/cmap/commands'; +import { + buildDeleteManyOperation, + buildDeleteOneOperation, + buildInsertOneOperation, + buildReplaceOneOperation, + buildUpdateManyOperation, + buildUpdateOneOperation, + ClientBulkWriteCommandBuilder +} from '../../../../src/operations/client_bulk_write/command_builder'; +import { + type ClientDeleteManyModel, + type ClientDeleteOneModel, + type ClientInsertOneModel, + type ClientReplaceOneModel, + type ClientUpdateManyModel, + type ClientUpdateOneModel +} from '../../../../src/operations/client_bulk_write/common'; import { DEFAULT_PK_FACTORY } from '../../../../src/utils'; describe('ClientBulkWriteCommandBuilder', 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 8988b3535f5..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,8 +1,9 @@ -import { BSON, Document, Long } from 'bson'; +import { BSON, type Document, Long } from 'bson'; import { expect } from 'chai'; + 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'; -import { ClientBulkWriteResult } from '../../../../src/operations/client_bulk_write/common'; class MockCursor { operations: Document[]; diff --git a/test/unit/operations/find.test.ts b/test/unit/operations/find.test.ts index 7519a269dbe..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 { ns } from '../../../src/utils'; + 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 1c300c2d3f7..3599e79cde4 100644 --- a/test/unit/operations/get_more.test.ts +++ b/test/unit/operations/get_more.test.ts @@ -1,13 +1,13 @@ +import { Long } from 'bson'; import { expect } from 'chai'; -import { topologyWithPlaceholderClient } from '../../tools/utils'; -import { ns } from '../../../src/utils'; -import { Long } from 'bson'; +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 { GetMoreOperation } from '../../../src/operations/get_more'; -import { Aspect } from '../../../src/operations/operation'; +import { ns } from '../../../src/utils'; +import { topologyWithPlaceholderClient } from '../../tools/utils'; describe('GetMoreOperation', function () { const namespace = ns('db.coll'); diff --git a/test/unit/operations/indexes.test.ts b/test/unit/operations/indexes.test.ts index ca59b8951bb..cbb9de56ce8 100644 --- a/test/unit/operations/indexes.test.ts +++ b/test/unit/operations/indexes.test.ts @@ -1,5 +1,10 @@ import { expect } from 'chai'; -import { CreateIndexesOperation, CreateIndexesOptions, IndexDirection } from '../../../src/operations/indexes'; + +import { + CreateIndexesOperation, + type CreateIndexesOptions, + type IndexDirection +} from '../../../src/operations/indexes'; import { ns } from '../../../src/utils'; describe('class CreateIndexesOperation', () => { diff --git a/test/unit/operations/kill_cursors.test.ts b/test/unit/operations/kill_cursors.test.ts index 7bd49c0b54b..f1c5e8ac708 100644 --- a/test/unit/operations/kill_cursors.test.ts +++ b/test/unit/operations/kill_cursors.test.ts @@ -1,11 +1,11 @@ +import { Long } from 'bson'; import { expect } from 'chai'; -import { topologyWithPlaceholderClient } from '../../tools/utils'; -import { Long } from 'bson'; -import { MongoDBNamespace, ns } from '../../../src/utils'; +import { KillCursorsOperation } from '../../../src/operations/kill_cursors'; import { Server } from '../../../src/sdam/server'; import { ServerDescription } from '../../../src/sdam/server_description'; -import { KillCursorsOperation } from '../../../src/operations/kill_cursors'; +import { MongoDBNamespace, ns } from '../../../src/utils'; +import { topologyWithPlaceholderClient } from '../../tools/utils'; describe('class KillCursorsOperation', () => { describe('constructor()', () => { diff --git a/test/unit/operations/list_databases.test.ts b/test/unit/operations/list_databases.test.ts index c79d0112960..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 { MongoDBNamespace } from '../../../src/utils'; + import { ListDatabasesOperation } from '../../../src/operations/list_databases'; +import { MongoDBNamespace } from '../../../src/utils'; const mockDB = { s: { diff --git a/test/unit/sdam/monitor.test.ts b/test/unit/sdam/monitor.test.ts index a45d8834159..07de7d84ddf 100644 --- a/test/unit/sdam/monitor.test.ts +++ b/test/unit/sdam/monitor.test.ts @@ -1,23 +1,27 @@ 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 { + type ServerHeartbeatFailedEvent, + type ServerHeartbeatStartedEvent, + 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'; -import { ServerDescription } from '../../../src/sdam/server_description'; -import { ServerType } from '../../../src/sdam/common'; -import { isHello } from '../../../src/utils'; -import { Monitor, MonitorInterval, RTTSampler } from '../../../src/sdam/monitor'; -import { ServerHeartbeatFailedEvent, ServerHeartbeatStartedEvent, ServerHeartbeatSucceededEvent } from '../../../src/sdam/events'; -import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; -import { Long, ObjectId } from 'bson'; -import { MongoClient } from '../../../src/mongo_client'; class MockServer { pool: any; diff --git a/test/unit/sdam/server.test.ts b/test/unit/sdam/server.test.ts index 07e01c89f00..4f4c9588d5a 100644 --- a/test/unit/sdam/server.test.ts +++ b/test/unit/sdam/server.test.ts @@ -1,15 +1,20 @@ /* 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 { sleep, topologyWithPlaceholderClient } from '../../tools/utils'; -import { MongoError, MongoErrorLabel, MongoNetworkError, MongoNetworkTimeoutError } from '../../../src/error'; +import { type Connection } from '../../../src/cmap/connection'; +import { + MongoError, + MongoErrorLabel, + MongoNetworkError, + 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 { Connection } from '../../../src/cmap/connection'; -import { ServerType, TopologyType } from '../../../src/sdam/common'; -import { ObjectId } from 'bson'; +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 cc0d8293d87..ac2edd7c5c2 100644 --- a/test/unit/sdam/server_description.test.ts +++ b/test/unit/sdam/server_description.test.ts @@ -1,7 +1,12 @@ +import { Long, ObjectId } from 'bson'; import { expect } from 'chai'; -import { compareTopologyVersion, ServerDescription, TopologyVersion } from '../../../src/sdam/server_description'; + import { MongoRuntimeError } from '../../../src/error'; -import { Long, ObjectId } from 'bson'; +import { + compareTopologyVersion, + ServerDescription, + type TopologyVersion +} 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 a949ee038ed..d7a76e1eaa1 100644 --- a/test/unit/sdam/server_discovery_and_monitoring.prose.test.ts +++ b/test/unit/sdam/server_discovery_and_monitoring.prose.test.ts @@ -1,8 +1,9 @@ import { expect } from 'chai'; import { once } from 'events'; import { createServer, type Server } from 'net'; -import { MongoClient } from '../../../src/mongo_client'; + 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 c9d46bf06df..4c0a45985de 100644 --- a/test/unit/sdam/server_selection.test.ts +++ b/test/unit/sdam/server_selection.test.ts @@ -1,16 +1,21 @@ +import { ObjectId } from 'bson'; import { expect } from 'chai'; import * as sinon from 'sinon'; -import * as mock from '../../tools/mongodb-mock/index'; -import { topologyWithPlaceholderClient } from '../../tools/utils'; -import { ServerDescription } from '../../../src/sdam/server_description'; -import { TopologyDescription } from '../../../src/sdam/topology_description'; -import { MIN_SECONDARY_WRITE_WIRE_VERSION, readPreferenceServerSelector, sameServerSelector, secondaryWritableServerSelector } from '../../../src/sdam/server_selection'; -import { TopologyType } from '../../../src/sdam/common'; -import { ObjectId } from 'bson'; +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, + readPreferenceServerSelector, + sameServerSelector, + secondaryWritableServerSelector +} from '../../../src/sdam/server_selection'; import { ServerSelectionEvent } from '../../../src/sdam/server_selection_events'; -import { MongoLogger } from '../../../src/mongo_logger'; +import { TopologyDescription } from '../../../src/sdam/topology_description'; +import * as mock from '../../tools/mongodb-mock/index'; +import { topologyWithPlaceholderClient } from '../../tools/utils'; describe('server selection', function () { const primary = new ServerDescription('127.0.0.1:27017', { diff --git a/test/unit/sdam/srv_polling.test.ts b/test/unit/sdam/srv_polling.test.ts index 28307c7ef99..f38dfd646de 100644 --- a/test/unit/sdam/srv_polling.test.ts +++ b/test/unit/sdam/srv_polling.test.ts @@ -4,12 +4,12 @@ import { EventEmitter, once } from 'events'; import * as sinon from 'sinon'; import { clearTimeout } from 'timers'; -import { topologyWithPlaceholderClient } from '../../tools/utils'; -import { TopologyDescription } from '../../../src/sdam/topology_description'; +import { MongoDriverError } from '../../../src/error'; import { TopologyType } from '../../../src/sdam/common'; import { TopologyDescriptionChangedEvent } from '../../../src/sdam/events'; -import { MongoDriverError } from '../../../src/error'; 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 () { const SRV_HOST = 'darmok.tanagra.com'; diff --git a/test/unit/sdam/topology.test.ts b/test/unit/sdam/topology.test.ts index 6f503374759..bc3901872be 100644 --- a/test/unit/sdam/topology.test.ts +++ b/test/unit/sdam/topology.test.ts @@ -6,21 +6,27 @@ import { satisfies } from 'semver'; import * as sinon from 'sinon'; import { clearTimeout } from 'timers'; -import * as mock from '../../tools/mongodb-mock/index'; -import { topologyWithPlaceholderClient } from '../../tools/utils'; import { makeClientMetadata } from '../../../src/cmap/handshake/client_metadata'; -import { LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, MongoServerSelectionError } from '../../../src/error'; -import { RunCursorCommandOperation, RunCommandOperation } from '../../../src/operations/run_command'; +import { + LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, + MongoServerSelectionError +} from '../../../src/error'; +import { MongoClient } from '../../../src/mongo_client'; +import { + RunCommandOperation, + 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 { MongoClient } from '../../../src/mongo_client'; -import { TopologyDescription } from '../../../src/sdam/topology_description'; -import { Server } from '../../../src/sdam/server'; -import { TopologyDescriptionChangedEvent } from '../../../src/sdam/events'; -import { TopologyType } from '../../../src/sdam/common'; -import { ReadPreference } from '../../../src/read_preference'; +import * as mock from '../../tools/mongodb-mock/index'; +import { topologyWithPlaceholderClient } from '../../tools/utils'; describe('Topology (unit)', function () { let client, topology; @@ -110,19 +116,18 @@ describe('Topology (unit)', function () { socketTimeoutMS: 250 }); const server = await topology.selectServer('primary', { - timeoutContext: ctx, - operationName: "none" + timeoutContext: ctx, + operationName: 'none' }); try { await server.command(new RunCursorCommandOperation(ns('admin.$cmd'), { ping: 1 }, {}), ctx); - expect.fail('expected command to fail') + expect.fail('expected command to fail'); } catch (err) { expect(err).to.exist; expect(err).to.match(/timed out/); } finally { topology.close(); } - }); }); diff --git a/test/unit/sessions.test.ts b/test/unit/sessions.test.ts index 6c2ca1f22ba..1c6c31ab237 100644 --- a/test/unit/sessions.test.ts +++ b/test/unit/sessions.test.ts @@ -1,14 +1,13 @@ +import { BSON, Long } from 'bson'; import { expect } from 'chai'; import * as sinon from 'sinon'; -import { genClusterTime } from '../tools/common'; -import * as mock from '../tools/mongodb-mock/index'; +import { MongoRuntimeError } from '../../src/error'; import { MongoClient } from '../../src/mongo_client'; -import { ClientSession, ServerSession, ServerSessionPool } from '../../src/sessions'; -import { applySession } from '../../src/sessions'; +import { applySession, ClientSession, ServerSession, ServerSessionPool } from '../../src/sessions'; import { isHello, now } from '../../src/utils'; -import { MongoRuntimeError } from '../../src/error'; -import { BSON, Long } from 'bson'; +import { genClusterTime } from '../tools/common'; +import * as mock from '../tools/mongodb-mock/index'; describe('Sessions - unit', function () { let client; diff --git a/test/unit/timeout.test.ts b/test/unit/timeout.test.ts index a50a84f0c1d..eca9681ac5b 100644 --- a/test/unit/timeout.test.ts +++ b/test/unit/timeout.test.ts @@ -1,6 +1,13 @@ import { expect } from 'chai'; -import { CSOTTimeoutContext, LegacyTimeoutContext, Timeout, TimeoutContext, TimeoutError } from '../../src/timeout'; + import { MongoInvalidArgumentError, MongoRuntimeError } from '../../src/error'; +import { + CSOTTimeoutContext, + LegacyTimeoutContext, + Timeout, + TimeoutContext, + TimeoutError +} from '../../src/timeout'; describe('Timeout', function () { let timeout: Timeout; diff --git a/test/unit/transactions.test.ts b/test/unit/transactions.test.ts index 7b70eb36717..09b0e91038e 100644 --- a/test/unit/transactions.test.ts +++ b/test/unit/transactions.test.ts @@ -1,6 +1,7 @@ import { expect } from 'chai'; -import { Transaction } from '../../src/transactions'; + 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 062235ae107..dc393fe0990 100644 --- a/test/unit/utils.test.ts +++ b/test/unit/utils.test.ts @@ -1,14 +1,29 @@ import { setTimeout } from 'node:timers'; +import { ObjectId } from 'bson'; import { expect } from 'chai'; import * as sinon from 'sinon'; -import { sleep } from '../tools/utils'; -import { abortable, BufferPool, ByteUtils, checkParentDomainMatch, compareObjectId, hasAtomicOperators, HostAddress, hostMatchesWildcards, isHello, isUint8Array, List, MongoDBCollectionNamespace, MongoDBNamespace, shuffle } from '../../src/utils'; +import { LEGACY_HELLO_COMMAND } from '../../src/constants'; import { MongoInvalidArgumentError, MongoRuntimeError } from '../../src/error'; import { decorateWithExplain, Explain } from '../../src/explain'; -import { ObjectId } from 'bson'; -import { LEGACY_HELLO_COMMAND } from '../../src/constants'; +import { + abortable, + BufferPool, + ByteUtils, + checkParentDomainMatch, + compareObjectId, + hasAtomicOperators, + HostAddress, + hostMatchesWildcards, + isHello, + isUint8Array, + List, + MongoDBCollectionNamespace, + MongoDBNamespace, + shuffle +} from '../../src/utils'; +import { sleep } from '../tools/utils'; describe('driver utils', function () { describe('.hasAtomicOperators', function () { diff --git a/test/unit/write_concern.test.ts b/test/unit/write_concern.test.ts index 3ed3086202a..420c6dce14c 100644 --- a/test/unit/write_concern.test.ts +++ b/test/unit/write_concern.test.ts @@ -1,4 +1,5 @@ import { expect } from 'chai'; + import { WriteConcern } from '../../src/write_concern'; describe('WriteConcern', function () { From 516686bbdb26d320e23c21702981eb9e54e29185 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Wed, 24 Sep 2025 12:21:20 -0700 Subject: [PATCH 18/25] update imports --- ...encryption.prose.21.automatic_data_encryption_keys.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts index 24afe0e7315..d6206d1f829 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts @@ -7,7 +7,9 @@ import { kmsCredentialsPresent, missingKeys } from '../../csfle-kms-providers'; -import { Collection, type Db, MongoServerError } from '../../mongodb'; +import { Collection } from '../../../src/collection'; +import { MongoServerError } from '../../../src/error'; +import { Db } from '../../../src/db'; const metadata: MongoDBMetadataUI = { requires: { From ffcc8d58bf4c023eb28e6d51832f42bb37d06c48 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Wed, 24 Sep 2025 13:00:39 -0700 Subject: [PATCH 19/25] fix: pr feedback --- test/unit/cmap/connect.test.ts | 15 ++++++--------- test/unit/collection.test.ts | 27 +++++++++++++++------------ test/unit/sdam/topology.test.ts | 23 ++++++++++------------- 3 files changed, 31 insertions(+), 34 deletions(-) diff --git a/test/unit/cmap/connect.test.ts b/test/unit/cmap/connect.test.ts index 4a69683ae97..a645b311460 100644 --- a/test/unit/cmap/connect.test.ts +++ b/test/unit/cmap/connect.test.ts @@ -1,11 +1,10 @@ -import { type ConnectionOptions } from 'node:tls'; 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 } from '../../../src/cmap/connection'; +import { ConnectionOptions, type Connection } from '../../../src/cmap/connection'; import { addContainerMetadata, type ClientMetadata @@ -181,15 +180,13 @@ describe('Connect Tests', function () { }); it('should emit `MongoNetworkError` for network errors', async function () { - try { - await connect({ - hostAddress: new HostAddress('non-existent:27018') - }); - } catch (error) { - expect(error).to.be.instanceOf(MongoNetworkError); - } + const error = await connect({ + hostAddress: new HostAddress('non-existent:27018') + }).catch(e => e); + expect(error).to.be.instanceOf(MongoNetworkError); }); + describe('prepareHandshakeDocument', () => { describe('client environment (containers and FAAS)', () => { const cachedEnv = process.env; diff --git a/test/unit/collection.test.ts b/test/unit/collection.test.ts index 0f82c33be2e..b9db37145eb 100644 --- a/test/unit/collection.test.ts +++ b/test/unit/collection.test.ts @@ -54,6 +54,7 @@ describe('Collection', function () { } ]; await collection.aggregate(pipeline, options).next(); + await client.close(); } context('bypass document validation', () => { @@ -80,12 +81,12 @@ describe('Collection', function () { }); } - if (isHello(doc)) { - request.reply(Object.assign({}, HELLO)); - } else if (doc.endSessions) { - request.reply({ ok: 1 }); - } - }); + if (isHello(doc)) { + request.reply(Object.assign({}, HELLO)); + } else if (doc.endSessions) { + request.reply({ ok: 1 }); + } + }); await client.connect(); const db = client.db('test'); @@ -94,6 +95,7 @@ describe('Collection', function () { const options = { bypassDocumentValidation: config.actual }; await collection.findOneAndUpdate({ name: 'Andy' }, { $inc: { score: 1 } }, options); + await client.close(); } it('should only set bypass document validation if strictly true in findOneAndUpdate', async function () { @@ -118,12 +120,12 @@ describe('Collection', function () { }); } - if (isHello(doc)) { - request.reply(Object.assign({}, HELLO)); - } else if (doc.endSessions) { - request.reply({ ok: 1 }); - } - }); + if (isHello(doc)) { + request.reply(Object.assign({}, HELLO)); + } else if (doc.endSessions) { + request.reply({ ok: 1 }); + } + }); await client.connect(); const db = client.db('test'); @@ -135,6 +137,7 @@ describe('Collection', function () { }; await collection.bulkWrite([{ insertOne: { document: { a: 1 } } }], options); + await client.close(); } // ordered bulk write, testing change in ordered.js diff --git a/test/unit/sdam/topology.test.ts b/test/unit/sdam/topology.test.ts index bc3901872be..678433c178c 100644 --- a/test/unit/sdam/topology.test.ts +++ b/test/unit/sdam/topology.test.ts @@ -115,19 +115,16 @@ describe('Topology (unit)', function () { serverSelectionTimeoutMS: 0, socketTimeoutMS: 250 }); - const server = await topology.selectServer('primary', { - timeoutContext: ctx, - operationName: 'none' - }); - try { - await server.command(new RunCursorCommandOperation(ns('admin.$cmd'), { ping: 1 }, {}), ctx); - expect.fail('expected command to fail'); - } catch (err) { - expect(err).to.exist; - expect(err).to.match(/timed out/); - } finally { - topology.close(); - } + 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(); }); }); From 7d7055fb261da528898ec20c70eb84cd65800300 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Wed, 24 Sep 2025 13:03:38 -0700 Subject: [PATCH 20/25] fix: lint --- ....21.automatic_data_encryption_keys.test.ts | 6 ++--- test/unit/cmap/connect.test.ts | 4 +--- test/unit/collection.test.ts | 24 +++++++++---------- test/unit/sdam/topology.test.ts | 8 +++---- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts index d6206d1f829..1f178265b54 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts @@ -2,14 +2,14 @@ import { expect } from 'chai'; import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { MongoCryptCreateEncryptedCollectionError } from '../../../src/client-side-encryption/errors'; +import { Collection } from '../../../src/collection'; +import { type Db } from '../../../src/db'; +import { MongoServerError } from '../../../src/error'; import { getCSFLEKMSProviders, kmsCredentialsPresent, missingKeys } from '../../csfle-kms-providers'; -import { Collection } from '../../../src/collection'; -import { MongoServerError } from '../../../src/error'; -import { Db } from '../../../src/db'; const metadata: MongoDBMetadataUI = { requires: { diff --git a/test/unit/cmap/connect.test.ts b/test/unit/cmap/connect.test.ts index a645b311460..ba54946f589 100644 --- a/test/unit/cmap/connect.test.ts +++ b/test/unit/cmap/connect.test.ts @@ -1,10 +1,9 @@ - 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 { ConnectionOptions, type Connection } from '../../../src/cmap/connection'; +import { type Connection, type ConnectionOptions } from '../../../src/cmap/connection'; import { addContainerMetadata, type ClientMetadata @@ -186,7 +185,6 @@ describe('Connect Tests', function () { expect(error).to.be.instanceOf(MongoNetworkError); }); - describe('prepareHandshakeDocument', () => { describe('client environment (containers and FAAS)', () => { const cachedEnv = process.env; diff --git a/test/unit/collection.test.ts b/test/unit/collection.test.ts index b9db37145eb..f7c3b017771 100644 --- a/test/unit/collection.test.ts +++ b/test/unit/collection.test.ts @@ -81,12 +81,12 @@ describe('Collection', function () { }); } - if (isHello(doc)) { - request.reply(Object.assign({}, HELLO)); - } else if (doc.endSessions) { - request.reply({ ok: 1 }); - } - }); + if (isHello(doc)) { + request.reply(Object.assign({}, HELLO)); + } else if (doc.endSessions) { + request.reply({ ok: 1 }); + } + }); await client.connect(); const db = client.db('test'); @@ -120,12 +120,12 @@ describe('Collection', function () { }); } - if (isHello(doc)) { - request.reply(Object.assign({}, HELLO)); - } else if (doc.endSessions) { - request.reply({ ok: 1 }); - } - }); + if (isHello(doc)) { + request.reply(Object.assign({}, HELLO)); + } else if (doc.endSessions) { + request.reply({ ok: 1 }); + } + }); await client.connect(); const db = client.db('test'); diff --git a/test/unit/sdam/topology.test.ts b/test/unit/sdam/topology.test.ts index 678433c178c..8fac7f52ee9 100644 --- a/test/unit/sdam/topology.test.ts +++ b/test/unit/sdam/topology.test.ts @@ -115,10 +115,10 @@ describe('Topology (unit)', function () { serverSelectionTimeoutMS: 0, socketTimeoutMS: 250 }); - const server = await topology - .selectServer('primary', { - timeoutContext: ctx, operationName: 'none' - }); + 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); From 01226ef931c892c74ff83c906c5e4b48300998ed Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Wed, 24 Sep 2025 13:22:49 -0700 Subject: [PATCH 21/25] fix: lint and missing import --- test/integration/auth/mongodb_aws.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/test/integration/auth/mongodb_aws.test.ts b/test/integration/auth/mongodb_aws.test.ts index a5011545d06..1daaa230d32 100644 --- a/test/integration/auth/mongodb_aws.test.ts +++ b/test/integration/auth/mongodb_aws.test.ts @@ -8,11 +8,17 @@ import * as sinon from 'sinon'; import { refreshKMSCredentials } from '../../../src/client-side-encryption/providers'; import { AWSSDKCredentialProvider } from '../../../src/cmap/auth/aws_temporary_credentials'; +import { MongoDBAWS } from '../../../src/cmap/auth/mongodb_aws'; import { type CommandOptions, Connection } from '../../../src/cmap/connection'; import { type MongoDBResponseConstructor } from '../../../src/cmap/wire_protocol/responses'; -import { MongoAWSError, MongoMissingDependencyError, MongoServerError } from '../../../src/error'; +import { + MongoAWSError, + MongoMissingCredentialsError, + MongoMissingDependencyError, + MongoServerError +} from '../../../src/error'; import { type MongoClient } from '../../../src/mongo_client'; -import { type MongoDBNamespace } from '../../../src/utils'; +import { type MongoDBNamespace, setDifference } from '../../../src/utils'; const isMongoDBAWSAuthEnvironment = (process.env.MONGODB_URI ?? '').includes('MONGODB-AWS'); From 0f11c1fe7c2fd1d8aa1d08d982b50d3a746caf19 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Wed, 24 Sep 2025 15:36:39 -0700 Subject: [PATCH 22/25] fix: pr feedback --- test/unit/error.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/unit/error.test.ts b/test/unit/error.test.ts index f6bb582897a..32e90a07857 100644 --- a/test/unit/error.test.ts +++ b/test/unit/error.test.ts @@ -451,9 +451,7 @@ describe('MongoErrors', () => { ); } } finally { - if (topology) { - topology.close(); - } + topology?.close(); } }); }); From afe4c9ef8e5512486bbaf70e2019e082c62be5cf Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Thu, 25 Sep 2025 09:16:10 -0700 Subject: [PATCH 23/25] reverting unnecessary changes outside of unit tests --- test/action/dependency.test.ts | 2 +- test/integration/auth/auth.prose.test.ts | 5 +---- test/integration/auth/mongodb_aws.test.ts | 20 ++++++++++--------- ....21.automatic_data_encryption_keys.test.ts | 4 +--- .../enumerate_databases.prose.test.ts | 2 +- test/integration/enumerate_databases.test.ts | 3 +-- test/integration/index_management.test.ts | 12 +++++------ test/tools/mongodb-mock/index.js | 2 +- test/tools/runner/config.ts | 18 +++++++++++------ test/tools/runner/filters/filter.ts | 2 +- test/tools/utils.ts | 18 +++++++++++------ 11 files changed, 48 insertions(+), 40 deletions(-) diff --git a/test/action/dependency.test.ts b/test/action/dependency.test.ts index d68f34a20bb..c0c4206fe68 100644 --- a/test/action/dependency.test.ts +++ b/test/action/dependency.test.ts @@ -5,7 +5,7 @@ import * as path from 'node:path'; import { expect } from 'chai'; import { dependencies, peerDependencies, peerDependenciesMeta } from '../../package.json'; -import { setDifference } from '../../src/utils'; +import { setDifference } from '../mongodb'; import { alphabetically, itInNodeProcess, sorted } from '../tools/utils'; const EXPECTED_DEPENDENCIES = sorted( diff --git a/test/integration/auth/auth.prose.test.ts b/test/integration/auth/auth.prose.test.ts index da9ea3b2c27..d9408a42001 100644 --- a/test/integration/auth/auth.prose.test.ts +++ b/test/integration/auth/auth.prose.test.ts @@ -1,10 +1,7 @@ import { expect } from 'chai'; import * as sinon from 'sinon'; -import { ScramSHA256 } from '../../../src/cmap/auth/scram'; -import { Connection } from '../../../src/cmap/connection'; -import { LEGACY_HELLO_COMMAND } from '../../../src/constants'; -import { type MongoClient } from '../../../src/mongo_client'; +import { Connection, LEGACY_HELLO_COMMAND, type MongoClient, ScramSHA256 } from '../../mongodb'; import { type TestConfiguration } from '../../tools/runner/config'; function makeConnectionString(config, username, password) { diff --git a/test/integration/auth/mongodb_aws.test.ts b/test/integration/auth/mongodb_aws.test.ts index 7cc81242460..cc7da87cef0 100644 --- a/test/integration/auth/mongodb_aws.test.ts +++ b/test/integration/auth/mongodb_aws.test.ts @@ -1,24 +1,26 @@ import * as process from 'node:process'; -import { type Document } from 'bson'; import { expect } from 'chai'; import * as http from 'http'; import { performance } from 'perf_hooks'; import * as sinon from 'sinon'; import { refreshKMSCredentials } from '../../../src/client-side-encryption/providers'; -import { AWSSDKCredentialProvider } from '../../../src/cmap/auth/aws_temporary_credentials'; -import { MongoDBAWS } from '../../../src/cmap/auth/mongodb_aws'; -import { type CommandOptions, Connection } from '../../../src/cmap/connection'; -import { type MongoDBResponseConstructor } from '../../../src/cmap/wire_protocol/responses'; import { + AWSSDKCredentialProvider, + type CommandOptions, + Connection, + type Document, MongoAWSError, + type MongoClient, + MongoDBAWS, + type MongoDBNamespace, + type MongoDBResponseConstructor, MongoMissingCredentialsError, MongoMissingDependencyError, - MongoServerError -} from '../../../src/error'; -import { type MongoClient } from '../../../src/mongo_client'; -import { type MongoDBNamespace, setDifference } from '../../../src/utils'; + MongoServerError, + setDifference +} from '../../mongodb'; const isMongoDBAWSAuthEnvironment = (process.env.MONGODB_URI ?? '').includes('MONGODB-AWS'); diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts index 1f178265b54..24afe0e7315 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts @@ -2,14 +2,12 @@ import { expect } from 'chai'; import { ClientEncryption } from '../../../src/client-side-encryption/client_encryption'; import { MongoCryptCreateEncryptedCollectionError } from '../../../src/client-side-encryption/errors'; -import { Collection } from '../../../src/collection'; -import { type Db } from '../../../src/db'; -import { MongoServerError } from '../../../src/error'; import { getCSFLEKMSProviders, kmsCredentialsPresent, missingKeys } from '../../csfle-kms-providers'; +import { Collection, type Db, MongoServerError } from '../../mongodb'; const metadata: MongoDBMetadataUI = { requires: { diff --git a/test/integration/enumerate_databases.prose.test.ts b/test/integration/enumerate_databases.prose.test.ts index 20750b88919..9528d68fada 100644 --- a/test/integration/enumerate_databases.prose.test.ts +++ b/test/integration/enumerate_databases.prose.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; -import { type MongoClient } from '../../src/mongo_client'; +import type { MongoClient } from '../mongodb'; const REQUIRED_DBS = ['admin', 'local', 'config']; const DB_NAME = 'listDatabasesTest'; diff --git a/test/integration/enumerate_databases.test.ts b/test/integration/enumerate_databases.test.ts index e1da9754b29..0b52ade1303 100644 --- a/test/integration/enumerate_databases.test.ts +++ b/test/integration/enumerate_databases.test.ts @@ -1,8 +1,7 @@ import { expect } from 'chai'; import { once } from 'events'; -import { MongoServerError } from '../../src/error'; -import { type MongoClient } from '../../src/mongo_client'; +import { type MongoClient, MongoServerError } from '../mongodb'; import { TestBuilder, UnifiedTestSuiteBuilder } from '../tools/unified_suite_builder'; const metadata: MongoDBMetadataUI = { diff --git a/test/integration/index_management.test.ts b/test/integration/index_management.test.ts index 391002fdc54..05574a26be5 100644 --- a/test/integration/index_management.test.ts +++ b/test/integration/index_management.test.ts @@ -1,13 +1,13 @@ import { expect } from 'chai'; import { + type Collection, type CommandStartedEvent, - type CommandSucceededEvent -} from '../../src/cmap/command_monitoring_events'; -import { type Collection } from '../../src/collection'; -import { type Db } from '../../src/db'; -import { MongoServerError } from '../../src/error'; -import { type MongoClient } from '../../src/mongo_client'; + type CommandSucceededEvent, + type Db, + type MongoClient, + MongoServerError +} from '../mongodb'; import { type FailCommandFailPoint } from '../tools/utils'; import { assert as test, filterForCommands, setupDatabase } from './shared'; diff --git a/test/tools/mongodb-mock/index.js b/test/tools/mongodb-mock/index.js index 1383fadde99..c05823e5177 100644 --- a/test/tools/mongodb-mock/index.js +++ b/test/tools/mongodb-mock/index.js @@ -1,6 +1,6 @@ const fs = require('fs'); const { MockServer } = require('./src/server.js'); -const { LEGACY_HELLO_COMMAND } = require('../../../src/constants.ts'); +const { LEGACY_HELLO_COMMAND } = require('../../mongodb'); let mockServers = []; diff --git a/test/tools/runner/config.ts b/test/tools/runner/config.ts index 5b537e26e80..69314408a3f 100644 --- a/test/tools/runner/config.ts +++ b/test/tools/runner/config.ts @@ -1,7 +1,6 @@ import * as util from 'node:util'; import * as types from 'node:util/types'; -import { Double, Long, ObjectId } from 'bson'; import { expect } from 'chai'; import { type Context } from 'mocha'; import ConnectionString from 'mongodb-connection-string-url'; @@ -9,11 +8,18 @@ import { type CompressorName } from 'mongodb-legacy'; import * as qs from 'querystring'; import * as url from 'url'; -import { type AuthMechanism } from '../../../src/cmap/auth/providers'; -import { MongoClient, type MongoClientOptions, type ServerApi } from '../../../src/mongo_client'; -import { TopologyType } from '../../../src/sdam/common'; -import { HostAddress } from '../../../src/utils'; -import { type WriteConcernSettings } from '../../../src/write_concern'; +import { + type AuthMechanism, + Double, + HostAddress, + Long, + MongoClient, + type MongoClientOptions, + ObjectId, + type ServerApi, + TopologyType, + type WriteConcernSettings +} from '../../mongodb'; import { getEnvironmentalOptions } from '../utils'; import { type Filter } from './filters/filter'; import { flakyTests } from './flaky'; diff --git a/test/tools/runner/filters/filter.ts b/test/tools/runner/filters/filter.ts index 510d2370ea6..6251cf44c8c 100644 --- a/test/tools/runner/filters/filter.ts +++ b/test/tools/runner/filters/filter.ts @@ -1,4 +1,4 @@ -import { type MongoClient } from '../../../../src/mongo_client'; +import { type MongoClient } from '../../../mongodb'; export abstract class Filter { async initializeFilter(_client: MongoClient, _context: Record): Promise { diff --git a/test/tools/utils.ts b/test/tools/utils.ts index cb30ada1cf5..79d918a6897 100644 --- a/test/tools/utils.ts +++ b/test/tools/utils.ts @@ -3,18 +3,24 @@ import { on, once } from 'node:events'; import * as fs from 'node:fs/promises'; import * as path from 'node:path'; -import { type Document, EJSON } from 'bson'; +import { EJSON } from 'bson'; import * as BSON from 'bson'; import { expect } from 'chai'; import { Readable } from 'stream'; import { setTimeout } from 'timers'; import { inspect, promisify } from 'util'; -import { OP_MSG } from '../../src/cmap/wire_protocol/constants'; -import { MongoClient, type MongoClientOptions } from '../../src/mongo_client'; -import { type AnyClientBulkWriteModel } from '../../src/operations/client_bulk_write/common'; -import { Topology, type TopologyOptions } from '../../src/sdam/topology'; -import { type HostAddress, now } from '../../src/utils'; +import { + type AnyClientBulkWriteModel, + type Document, + type HostAddress, + MongoClient, + type MongoClientOptions, + now, + OP_MSG, + Topology, + type TopologyOptions +} from '../mongodb'; import { type TestConfiguration } from './runner/config'; export function ensureCalledWith(stub: any, args: any[]) { From 91028b7b47aeafa6c9fb63f4a469ba1930cd09f0 Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Thu, 25 Sep 2025 10:34:21 -0700 Subject: [PATCH 24/25] pr feedback --- .../client-side-encryption/state_machine.test.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/test/unit/client-side-encryption/state_machine.test.ts b/test/unit/client-side-encryption/state_machine.test.ts index 9cf10d94912..a9d515c844a 100644 --- a/test/unit/client-side-encryption/state_machine.test.ts +++ b/test/unit/client-side-encryption/state_machine.test.ts @@ -190,14 +190,10 @@ describe('StateMachine', function () { const request = new MockRequest(Buffer.from('foobar'), 500); it('rejects with the validation error', async function () { - try { - await stateMachine.kmsRequest(request); - expect.fail('should have failed with validation error'); - } catch (err) { - expect(err.message).to.equal( - `Insecure TLS options prohibited for aws: ${option}` - ); - } + const err = await stateMachine.kmsRequest(request).catch(e => e); + expect(err.message).to.equal( + `Insecure TLS options prohibited for aws: ${option}` + ); }); }); } From cfa75a67eb153cc456a2e040799ba11f719ed31a Mon Sep 17 00:00:00 2001 From: Pavel Safronov Date: Thu, 25 Sep 2025 11:16:37 -0700 Subject: [PATCH 25/25] linter fix --- test/unit/client-side-encryption/state_machine.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/unit/client-side-encryption/state_machine.test.ts b/test/unit/client-side-encryption/state_machine.test.ts index a9d515c844a..1ce00c011e1 100644 --- a/test/unit/client-side-encryption/state_machine.test.ts +++ b/test/unit/client-side-encryption/state_machine.test.ts @@ -191,9 +191,7 @@ describe('StateMachine', function () { 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}` - ); + expect(err.message).to.equal(`Insecure TLS options prohibited for aws: ${option}`); }); }); }