Skip to content

Commit be15a70

Browse files
authored
Tests: gate logging behind DEBUG env var (#4903)
* Add `DebugLogger` type for logging matrix-js-sdk to `debug` * unit tests for DebugLogger * Use `DebugLogger` in some tests * Use `DebugLogger` in rust-crypto.spec * test-utils: silence some logging
1 parent 090b807 commit be15a70

File tree

9 files changed

+157
-25
lines changed

9 files changed

+157
-25
lines changed

spec/integ/crypto/cross-signing.spec.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@ limitations under the License.
1717
import fetchMock from "fetch-mock-jest";
1818
import "fake-indexeddb/auto";
1919
import { IDBFactory } from "fake-indexeddb";
20+
import debug from "debug";
2021

2122
import { syncPromise } from "../../test-utils/test-utils";
22-
import { type AuthDict, createClient, type MatrixClient } from "../../../src";
23+
import { type AuthDict, createClient, DebugLogger, type MatrixClient } from "../../../src";
2324
import { mockInitialApiRequests, mockSetupCrossSigningRequests } from "../../test-utils/mockEndpoints";
2425
import encryptAESSecretStorageItem from "../../../src/utils/encryptAESSecretStorageItem.ts";
2526
import { type CryptoCallbacks, CrossSigningKey } from "../../../src/crypto-api";
@@ -91,6 +92,7 @@ describe("cross-signing", () => {
9192
accessToken: "akjgkrgjs",
9293
deviceId: TEST_DEVICE_ID,
9394
cryptoCallbacks: createCryptoCallbacks(),
95+
logger: new DebugLogger(debug(`matrix-js-sdk:cross-signing`)),
9496
});
9597

9698
syncResponder = new SyncResponder(homeserverUrl);

spec/integ/crypto/device-dehydration.spec.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@ limitations under the License.
1616

1717
import "fake-indexeddb/auto";
1818
import fetchMock from "fetch-mock-jest";
19+
import debug from "debug";
1920

20-
import { ClientEvent, createClient, type MatrixClient, MatrixEvent } from "../../../src";
21+
import { ClientEvent, createClient, DebugLogger, type MatrixClient, MatrixEvent } from "../../../src";
2122
import { CryptoEvent } from "../../../src/crypto-api/index";
2223
import { type RustCrypto } from "../../../src/rust-crypto/rust-crypto";
2324
import { type AddSecretStorageKeyOpts } from "../../../src/secret-storage";
@@ -38,6 +39,7 @@ describe("Device dehydration", () => {
3839
return [[...Object.keys(keys.keys)][0], new Uint8Array(32)];
3940
},
4041
},
42+
logger: new DebugLogger(debug(`matrix-js-sdk:dehydration`)),
4143
});
4244

4345
await initializeSecretStorage(matrixClient, "@alice:localhost", "http://test.server");

spec/integ/crypto/verification.spec.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ limitations under the License.
1717
import "fake-indexeddb/auto";
1818

1919
import anotherjson from "another-json";
20+
import debug from "debug";
2021
import fetchMock from "fetch-mock-jest";
2122
import { IDBFactory } from "fake-indexeddb";
2223
import { createHash } from "crypto";
@@ -25,6 +26,7 @@ import Olm from "@matrix-org/olm";
2526
import type FetchMock from "fetch-mock";
2627
import {
2728
createClient,
29+
DebugLogger,
2830
DeviceVerification,
2931
type IContent,
3032
type ICreateClientOpts,
@@ -1475,6 +1477,7 @@ describe("verification", () => {
14751477
userId: TEST_USER_ID,
14761478
accessToken: "akjgkrgjs",
14771479
deviceId: "device_under_test",
1480+
logger: new DebugLogger(debug(`matrix-js-sdk:verification`)),
14781481
...opts,
14791482
});
14801483
await client.initRustCrypto();

spec/test-utils/test-utils.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import mkdebug from "debug";
2+
13
// eslint-disable-next-line no-restricted-imports
24
import type EventEmitter from "events";
3-
import { logger } from "../../src/logger";
45
import {
56
type IContent,
67
type IEvent,
@@ -24,6 +25,8 @@ import { eventMapperFor } from "../../src/event-mapper";
2425
import { TEST_ROOM_ID } from "./test-data";
2526
import { KnownMembership, type Membership } from "../../src/@types/membership";
2627

28+
const debug = mkdebug("test-utils");
29+
2730
/**
2831
* Return a promise that is resolved when the client next emits a
2932
* SYNCING event.
@@ -38,7 +41,7 @@ export function syncPromise(client: MatrixClient, count = 1): Promise<void> {
3841

3942
const p = new Promise<void>((resolve) => {
4043
const cb = (state: SyncState) => {
41-
logger.log(`${Date.now()} syncPromise(${count}): ${state}`);
44+
debug(`syncPromise(${count}): ${state}`);
4245
if (state === SyncState.Syncing) {
4346
resolve();
4447
} else {
@@ -519,25 +522,25 @@ export async function awaitDecryption(
519522
// already
520523
if (event.getClearContent() !== null) {
521524
if (waitOnDecryptionFailure && event.isDecryptionFailure()) {
522-
logger.log(`${Date.now()}: event ${event.getId()} got decryption error; waiting`);
525+
debug(`event ${event.getId()} got decryption error; waiting`);
523526
} else {
524527
return event;
525528
}
526529
} else {
527-
logger.log(`${Date.now()}: event ${event.getId()} is not yet decrypted; waiting`);
530+
debug(`event ${event.getId()} is not yet decrypted; waiting`);
528531
}
529532

530533
return new Promise((resolve) => {
531534
if (waitOnDecryptionFailure) {
532535
event.on(MatrixEventEvent.Decrypted, (ev, err) => {
533-
logger.log(`${Date.now()}: MatrixEventEvent.Decrypted for event ${event.getId()}: ${err ?? "success"}`);
536+
debug(`MatrixEventEvent.Decrypted for event ${event.getId()}: ${err ?? "success"}`);
534537
if (!err) {
535538
resolve(ev);
536539
}
537540
});
538541
} else {
539542
event.once(MatrixEventEvent.Decrypted, (ev, err) => {
540-
logger.log(`${Date.now()}: MatrixEventEvent.Decrypted for event ${event.getId()}: ${err ?? "success"}`);
543+
debug(`MatrixEventEvent.Decrypted for event ${event.getId()}: ${err ?? "success"}`);
541544
resolve(ev);
542545
});
543546
}

spec/unit/logger.spec.ts

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ limitations under the License.
1818

1919
import loglevel from "loglevel";
2020

21-
import { logger } from "../../src/logger.ts";
21+
import { DebugLogger, logger } from "../../src/logger.ts";
2222

2323
afterEach(() => {
2424
jest.restoreAllMocks();
@@ -49,3 +49,42 @@ describe("logger", () => {
4949
expect(console.debug).toHaveBeenCalledWith("[prefix1][prefix2]", "test2");
5050
});
5151
});
52+
53+
describe("DebugLogger", () => {
54+
it("should handle empty log messages", () => {
55+
const mockTarget = jest.fn();
56+
const logger = new DebugLogger(mockTarget as any);
57+
logger.info();
58+
expect(mockTarget).toHaveBeenCalledTimes(1);
59+
expect(mockTarget).toHaveBeenCalledWith("[INFO] ");
60+
});
61+
62+
it("should handle logging an Error", () => {
63+
const mockTarget = jest.fn();
64+
const logger = new DebugLogger(mockTarget as any);
65+
66+
// If there is a stack and a message, we use the stack.
67+
const error = new Error("I am an error");
68+
logger.error(error);
69+
expect(mockTarget).toHaveBeenCalledTimes(1);
70+
expect(mockTarget).toHaveBeenCalledWith(expect.stringMatching(/^\[ERROR\] Error: I am an error\n\s*at/));
71+
72+
mockTarget.mockClear();
73+
74+
// If there is only a message, we use that.
75+
error.stack = undefined;
76+
logger.error(error);
77+
expect(mockTarget).toHaveBeenCalledTimes(1);
78+
expect(mockTarget).toHaveBeenCalledWith("[ERROR] I am an error");
79+
});
80+
81+
it("should handle logging an object", () => {
82+
const mockTarget = jest.fn();
83+
const logger = new DebugLogger(mockTarget as any);
84+
85+
const obj = { a: 1 };
86+
logger.warn(obj);
87+
expect(mockTarget).toHaveBeenCalledTimes(1);
88+
expect(mockTarget).toHaveBeenCalledWith("[WARN] %O", obj);
89+
});
90+
});

spec/unit/rust-crypto/rust-crypto.spec.ts

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17+
import debug from "debug";
1718
import * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-wasm";
1819
import {
1920
BaseMigrationData,
@@ -31,6 +32,7 @@ import { RustCrypto } from "../../../src/rust-crypto/rust-crypto";
3132
import { initRustCrypto } from "../../../src/rust-crypto";
3233
import {
3334
type AccountDataEvents,
35+
DebugLogger,
3436
type Device,
3537
DeviceVerification,
3638
type EmptyObject,
@@ -68,7 +70,6 @@ import {
6870
import * as testData from "../../test-utils/test-data";
6971
import { E2EKeyReceiver } from "../../test-utils/E2EKeyReceiver";
7072
import { E2EKeyResponder } from "../../test-utils/E2EKeyResponder";
71-
import { logger } from "../../../src/logger";
7273
import { OutgoingRequestsManager } from "../../../src/rust-crypto/OutgoingRequestsManager";
7374
import { ClientEvent, type ClientEventHandlerMap } from "../../../src/client";
7475
import { type Curve25519AuthData } from "../../../src/crypto-api/keybackup";
@@ -117,6 +118,7 @@ describe("initRustCrypto", () => {
117118
const testOlmMachine = makeTestOlmMachine();
118119
jest.spyOn(OlmMachine, "initFromStore").mockResolvedValue(testOlmMachine);
119120

121+
const logger = new DebugLogger(debug("matrix-js-sdk:test:initRustCrypto"));
120122
await initRustCrypto({
121123
logger,
122124
http: {} as MatrixClient["http"],
@@ -140,6 +142,7 @@ describe("initRustCrypto", () => {
140142
jest.spyOn(OlmMachine, "initFromStore").mockResolvedValue(testOlmMachine);
141143

142144
const storeKey = new Uint8Array(32);
145+
const logger = new DebugLogger(debug("matrix-js-sdk:test:initRustCrypto"));
143146
await initRustCrypto({
144147
logger,
145148
http: {} as MatrixClient["http"],
@@ -162,6 +165,7 @@ describe("initRustCrypto", () => {
162165
const testOlmMachine = makeTestOlmMachine();
163166
jest.spyOn(OlmMachine, "initFromStore").mockResolvedValue(testOlmMachine);
164167

168+
const logger = new DebugLogger(debug("matrix-js-sdk:test:initRustCrypto"));
165169
await initRustCrypto({
166170
logger,
167171
http: {} as MatrixClient["http"],
@@ -186,7 +190,7 @@ describe("initRustCrypto", () => {
186190
jest.spyOn(OlmMachine, "initFromStore").mockResolvedValue(testOlmMachine);
187191

188192
await initRustCrypto({
189-
logger,
193+
logger: new DebugLogger(debug("matrix-js-sdk:test:initRustCrypto")),
190194
http: {} as MatrixClient["http"],
191195
userId: TEST_USER,
192196
deviceId: TEST_DEVICE_ID,
@@ -251,9 +255,10 @@ describe("initRustCrypto", () => {
251255
jest.spyOn(RustSdkCryptoJs.BackupDecryptionKey, "fromBase64").mockReturnValue(mockBackupDecryptionKey);
252256

253257
function legacyMigrationProgressListener(progress: number, total: number): void {
254-
logger.log(`migrated ${progress} of ${total}`);
258+
// console.log(`migrated ${progress} of ${total}`);
255259
}
256260

261+
const logger = new DebugLogger(debug("matrix-js-sdk:test:initRustCrypto"));
257262
await initRustCrypto({
258263
logger,
259264
http: makeMatrixHttpApi(),
@@ -358,11 +363,11 @@ describe("initRustCrypto", () => {
358363
fetchMock.get("path:/_matrix/client/v3/room_keys/version", 404);
359364

360365
function legacyMigrationProgressListener(progress: number, total: number): void {
361-
logger.log(`migrated ${progress} of ${total}`);
366+
// console.log(`migrated ${progress} of ${total}`);
362367
}
363368

364369
await initRustCrypto({
365-
logger,
370+
logger: new DebugLogger(debug("matrix-js-sdk:test:initRustCrypto")),
366371
http: makeMatrixHttpApi(),
367372
userId: TEST_USER,
368373
deviceId: TEST_DEVICE_ID,
@@ -400,6 +405,7 @@ describe("initRustCrypto", () => {
400405
);
401406

402407
const PICKLE_KEY = "pickle1234";
408+
const logger = new DebugLogger(debug("matrix-js-sdk:test:initRustCrypto"));
403409
await initRustCrypto({
404410
logger,
405411
http: makeMatrixHttpApi(),
@@ -813,7 +819,7 @@ describe("RustCrypto", () => {
813819
} as unknown as OlmMachine;
814820

815821
const rustCrypto = new RustCrypto(
816-
logger,
822+
new DebugLogger(debug("matrix-js-sdk:test:RustCrypto")),
817823
mockOlmMachine,
818824
fetchMock as unknown as MatrixHttpApi<any>,
819825
TEST_USER,
@@ -898,6 +904,7 @@ describe("RustCrypto", () => {
898904
makeOutgoingRequest: jest.fn(),
899905
} as unknown as Mocked<OutgoingRequestProcessor>;
900906

907+
const logger = new DebugLogger(debug("matrix-js-sdk:test:RustCrypto"));
901908
const outgoingRequestsManager = new OutgoingRequestsManager(logger, olmMachine, outgoingRequestProcessor);
902909

903910
rustCrypto = new RustCrypto(
@@ -957,7 +964,11 @@ describe("RustCrypto", () => {
957964

958965
const outgoingRequestProcessor = {} as unknown as OutgoingRequestProcessor;
959966
rustCrypto["outgoingRequestProcessor"] = outgoingRequestProcessor;
960-
const outgoingRequestsManager = new OutgoingRequestsManager(logger, olmMachine, outgoingRequestProcessor);
967+
const outgoingRequestsManager = new OutgoingRequestsManager(
968+
new DebugLogger(debug("matrix-js-sdk:test:RustCrypto")),
969+
olmMachine,
970+
outgoingRequestProcessor,
971+
);
961972
rustCrypto["outgoingRequestsManager"] = outgoingRequestsManager;
962973

963974
// The second time we do a /keys/upload, the `device_keys` property
@@ -1015,7 +1026,7 @@ describe("RustCrypto", () => {
10151026
getRoomEventEncryptionInfo: jest.fn(),
10161027
} as unknown as Mocked<RustSdkCryptoJs.OlmMachine>;
10171028
rustCrypto = new RustCrypto(
1018-
logger,
1029+
new DebugLogger(debug("matrix-js-sdk:test:RustCrypto")),
10191030
olmMachine,
10201031
{} as MatrixClient["http"],
10211032
TEST_USER,
@@ -1228,7 +1239,7 @@ describe("RustCrypto", () => {
12281239
getDevice: jest.fn(),
12291240
} as unknown as Mocked<RustSdkCryptoJs.OlmMachine>;
12301241
rustCrypto = new RustCrypto(
1231-
logger,
1242+
new DebugLogger(debug("matrix-js-sdk:test:RustCrypto")),
12321243
olmMachine,
12331244
{} as MatrixClient["http"],
12341245
TEST_USER,
@@ -1471,7 +1482,7 @@ describe("RustCrypto", () => {
14711482
getIdentity: jest.fn(),
14721483
} as unknown as Mocked<RustSdkCryptoJs.OlmMachine>;
14731484
rustCrypto = new RustCrypto(
1474-
logger,
1485+
new DebugLogger(debug("matrix-js-sdk:test:RustCrypto")),
14751486
olmMachine,
14761487
{} as MatrixClient["http"],
14771488
TEST_USER,
@@ -1558,7 +1569,7 @@ describe("RustCrypto", () => {
15581569
getIdentity: jest.fn(),
15591570
} as unknown as Mocked<RustSdkCryptoJs.OlmMachine>;
15601571
const rustCrypto = new RustCrypto(
1561-
logger,
1572+
new DebugLogger(debug("matrix-js-sdk:test:RustCrypto")),
15621573
olmMachine,
15631574
{} as MatrixClient["http"],
15641575
TEST_USER,
@@ -1630,7 +1641,7 @@ describe("RustCrypto", () => {
16301641
} as unknown as Mocked<RustSdkCryptoJs.OlmMachine>;
16311642

16321643
const rustCrypto = new RustCrypto(
1633-
logger,
1644+
new DebugLogger(debug("matrix-js-sdk:test:RustCrypto")),
16341645
olmMachine,
16351646
makeMatrixHttpApi(),
16361647
testData.TEST_USER_ID,
@@ -2371,7 +2382,7 @@ async function makeTestRustCrypto(
23712382
cryptoCallbacks: CryptoCallbacks = {} as CryptoCallbacks,
23722383
): Promise<RustCrypto> {
23732384
return await initRustCrypto({
2374-
logger,
2385+
logger: new DebugLogger(debug("matrix-js-sdk:test:rust-crypto.spec")),
23752386
http,
23762387
userId,
23772388
deviceId,

src/client.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -439,13 +439,13 @@ export interface ICreateClientOpts {
439439

440440
/**
441441
* If true, group calls will not establish media connectivity and only create the signaling events,
442-
* so that livekit media can be used in the application layert (js-sdk contains no livekit code).
442+
* so that livekit media can be used in the application layer (js-sdk contains no livekit code).
443443
*/
444444
useLivekitForGroupCalls?: boolean;
445445

446446
/**
447447
* A logger to associate with this MatrixClient.
448-
* Defaults to the built-in global logger.
448+
* Defaults to the built-in global logger; see {@link DebugLogger} for an alternative.
449449
*/
450450
logger?: Logger;
451451
}

0 commit comments

Comments
 (0)