Skip to content

Commit 5973c66

Browse files
authored
Make sonar happier about our code & tests (#3388)
1 parent 3f48a95 commit 5973c66

File tree

15 files changed

+50
-106
lines changed

15 files changed

+50
-106
lines changed

spec/integ/crypto.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1111,7 +1111,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string,
11111111
} catch (e) {
11121112
expect((e as any).name).toEqual("UnknownDeviceError");
11131113
expect([...(e as any).devices.keys()]).toEqual([aliceClient.getUserId()!]);
1114-
expect((e as any).devices.get(aliceClient.getUserId()!).has("DEVICE_ID"));
1114+
expect((e as any).devices.get(aliceClient.getUserId()!).has("DEVICE_ID")).toBeTruthy();
11151115
}
11161116

11171117
// mark the device as known, and resend.

spec/olm-loader.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,5 @@ try {
2323
global.Olm = require("@matrix-org/olm");
2424
logger.log("loaded libolm");
2525
} catch (e) {
26-
logger.warn("unable to run crypto tests: libolm not available");
26+
logger.warn("unable to run crypto tests: libolm not available", e);
2727
}

spec/unit/crypto.spec.ts

Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -381,12 +381,7 @@ describe("Crypto", function () {
381381
event.senderCurve25519Key = null;
382382
// @ts-ignore private properties
383383
event.claimedEd25519Key = null;
384-
try {
385-
await bobClient.crypto!.decryptEvent(event);
386-
} catch (e) {
387-
// we expect this to fail because we don't have the
388-
// decryption keys yet
389-
}
384+
await expect(bobClient.crypto!.decryptEvent(event)).rejects.toBeTruthy();
390385
}),
391386
);
392387

@@ -617,12 +612,7 @@ describe("Crypto", function () {
617612
event.senderCurve25519Key = null;
618613
// @ts-ignore private properties
619614
event.claimedEd25519Key = null;
620-
try {
621-
await secondAliceClient.crypto!.decryptEvent(event);
622-
} catch (e) {
623-
// we expect this to fail because we don't have the
624-
// decryption keys yet
625-
}
615+
await expect(secondAliceClient.crypto!.decryptEvent(event)).rejects.toBeTruthy();
626616
}),
627617
);
628618

@@ -725,12 +715,7 @@ describe("Crypto", function () {
725715
event.senderCurve25519Key = null;
726716
// @ts-ignore private properties
727717
event.claimedEd25519Key = null;
728-
try {
729-
await bobClient.crypto!.decryptEvent(event);
730-
} catch (e) {
731-
// we expect this to fail because we don't have the
732-
// decryption keys yet
733-
}
718+
await expect(bobClient.crypto!.decryptEvent(event)).rejects.toBeTruthy();
734719
}),
735720
);
736721

@@ -805,12 +790,7 @@ describe("Crypto", function () {
805790
event.senderCurve25519Key = null;
806791
// @ts-ignore private properties
807792
event.claimedEd25519Key = null;
808-
try {
809-
await bobClient.crypto!.decryptEvent(event);
810-
} catch (e) {
811-
// we expect this to fail because we don't have the
812-
// decryption keys yet
813-
}
793+
await expect(bobClient.crypto!.decryptEvent(event)).rejects.toBeTruthy();
814794
}),
815795
);
816796

@@ -897,12 +877,7 @@ describe("Crypto", function () {
897877
event.senderCurve25519Key = null;
898878
// @ts-ignore private properties
899879
event.claimedEd25519Key = null;
900-
try {
901-
await bobClient.crypto!.decryptEvent(event);
902-
} catch (e) {
903-
// we expect this to fail because we don't have the
904-
// decryption keys yet
905-
}
880+
await expect(bobClient.crypto!.decryptEvent(event)).rejects.toBeTruthy();
906881
}),
907882
);
908883

spec/unit/crypto/secrets.spec.ts

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -148,22 +148,14 @@ describe("Secrets", function () {
148148
it("should throw if given a key that doesn't exist", async function () {
149149
const alice = await makeTestClient({ userId: "@alice:example.com", deviceId: "Osborne2" });
150150

151-
try {
152-
await alice.storeSecret("foo", "bar", ["this secret does not exist"]);
153-
// should be able to use expect(...).toThrow() but mocha still fails
154-
// the test even when it throws for reasons I have no inclination to debug
155-
expect(true).toBeFalsy();
156-
} catch (e) {}
151+
await expect(alice.storeSecret("foo", "bar", ["this secret does not exist"])).rejects.toBeTruthy();
157152
alice.stopClient();
158153
});
159154

160155
it("should refuse to encrypt with zero keys", async function () {
161156
const alice = await makeTestClient({ userId: "@alice:example.com", deviceId: "Osborne2" });
162157

163-
try {
164-
await alice.storeSecret("foo", "bar", []);
165-
expect(true).toBeFalsy();
166-
} catch (e) {}
158+
await expect(alice.storeSecret("foo", "bar", [])).rejects.toBeTruthy();
167159
alice.stopClient();
168160
});
169161

@@ -214,10 +206,7 @@ describe("Secrets", function () {
214206
it("should refuse to encrypt if no keys given and no default key", async function () {
215207
const alice = await makeTestClient({ userId: "@alice:example.com", deviceId: "Osborne2" });
216208

217-
try {
218-
await alice.storeSecret("foo", "bar");
219-
expect(true).toBeFalsy();
220-
} catch (e) {}
209+
await expect(alice.storeSecret("foo", "bar")).rejects.toBeTruthy();
221210
alice.stopClient();
222211
});
223212

spec/unit/crypto/verification/sas.spec.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ describe("SAS verification", function () {
144144
expect(e.sas).toEqual(aliceSasEvent.sas);
145145
e.confirm();
146146
aliceSasEvent.confirm();
147-
} catch (error) {
147+
} catch {
148148
e.mismatch();
149149
aliceSasEvent.mismatch();
150150
}
@@ -169,7 +169,7 @@ describe("SAS verification", function () {
169169
expect(e.sas).toEqual(bobSasEvent.sas);
170170
e.confirm();
171171
bobSasEvent.confirm();
172-
} catch (error) {
172+
} catch {
173173
e.mismatch();
174174
bobSasEvent.mismatch();
175175
}
@@ -519,7 +519,7 @@ describe("SAS verification", function () {
519519
expect(e.sas).toEqual(aliceSasEvent.sas);
520520
e.confirm();
521521
aliceSasEvent.confirm();
522-
} catch (error) {
522+
} catch {
523523
e.mismatch();
524524
aliceSasEvent.mismatch();
525525
}
@@ -543,7 +543,7 @@ describe("SAS verification", function () {
543543
expect(e.sas).toEqual(bobSasEvent.sas);
544544
e.confirm();
545545
bobSasEvent.confirm();
546-
} catch (error) {
546+
} catch {
547547
e.mismatch();
548548
bobSasEvent.mismatch();
549549
}

spec/unit/room.spec.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,13 +1932,7 @@ describe("Room", function () {
19321932
it("should allow retry on error", async function () {
19331933
const client = createClientMock(new Error("server says no"));
19341934
const room = new Room(roomId, client as any, null!, { lazyLoadMembers: true });
1935-
let hasThrown = false;
1936-
try {
1937-
await room.loadMembersIfNeeded();
1938-
} catch (err) {
1939-
hasThrown = true;
1940-
}
1941-
expect(hasThrown).toEqual(true);
1935+
await expect(room.loadMembersIfNeeded()).rejects.toBeTruthy();
19421936

19431937
client.members.mockReturnValue({ chunk: [memberEvent] });
19441938
await room.loadMembersIfNeeded();

spec/unit/webrtc/call.spec.ts

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1054,14 +1054,7 @@ describe("Call", function () {
10541054

10551055
mockSendEvent.mockReset();
10561056

1057-
let caught = false;
1058-
try {
1059-
call.reject();
1060-
} catch (e) {
1061-
caught = true;
1062-
}
1063-
1064-
expect(caught).toEqual(true);
1057+
expect(() => call.reject()).toThrow();
10651058
expect(client.client.sendEvent).not.toHaveBeenCalled();
10661059

10671060
call.hangup(CallErrorCode.UserHangup, true);

spec/unit/webrtc/groupCall.spec.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -186,10 +186,7 @@ describe("Group Call", function () {
186186
it("sets state to local call feed uninitialized when getUserMedia() fails", async () => {
187187
jest.spyOn(mockClient.getMediaHandler(), "getUserMediaStream").mockRejectedValue("Error");
188188

189-
try {
190-
await groupCall.initLocalCallFeed();
191-
} catch (e) {}
192-
189+
await expect(groupCall.initLocalCallFeed()).rejects.toBeTruthy();
193190
expect(groupCall.state).toBe(GroupCallState.LocalCallFeedUninitialized);
194191
});
195192

src/autodiscovery.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ export class AutoDiscovery {
142142
},
143143
};
144144

145-
if (!wellknown || !wellknown["m.homeserver"]) {
145+
if (!wellknown?.["m.homeserver"]) {
146146
logger.error("No m.homeserver key in config");
147147

148148
clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
@@ -171,7 +171,7 @@ export class AutoDiscovery {
171171

172172
// Step 3: Make sure the homeserver URL points to a homeserver.
173173
const hsVersions = await this.fetchWellKnownObject(`${hsUrl}/_matrix/client/versions`);
174-
if (!hsVersions || !hsVersions.raw?.["versions"]) {
174+
if (!hsVersions?.raw?.["versions"]) {
175175
logger.error("Invalid /versions response");
176176
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;
177177

@@ -345,7 +345,7 @@ export class AutoDiscovery {
345345

346346
const response = await this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`);
347347
if (!response) return {};
348-
return response.raw || {};
348+
return response.raw ?? {};
349349
}
350350

351351
/**

src/client.ts

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,11 @@ import { StubStore } from "./store/stub";
3636
import { CallEvent, CallEventHandlerMap, createNewMatrixCall, MatrixCall, supportsMatrixCall } from "./webrtc/call";
3737
import { Filter, IFilterDefinition, IRoomEventFilter } from "./filter";
3838
import { CallEventHandlerEvent, CallEventHandler, CallEventHandlerEventHandlerMap } from "./webrtc/callEventHandler";
39-
import { GroupCallEventHandlerEvent, GroupCallEventHandlerEventHandlerMap } from "./webrtc/groupCallEventHandler";
39+
import {
40+
GroupCallEventHandler,
41+
GroupCallEventHandlerEvent,
42+
GroupCallEventHandlerEventHandlerMap,
43+
} from "./webrtc/groupCallEventHandler";
4044
import * as utils from "./utils";
4145
import { replaceParam, QueryDict, sleep, noUnsafeEventProps, safeSet } from "./utils";
4246
import { Direction, EventTimeline } from "./models/event-timeline";
@@ -180,7 +184,6 @@ import { IThreepid } from "./@types/threepids";
180184
import { CryptoStore, OutgoingRoomKeyRequest } from "./crypto/store/base";
181185
import { GroupCall, IGroupCallDataChannelOptions, GroupCallIntent, GroupCallType } from "./webrtc/groupCall";
182186
import { MediaHandler } from "./webrtc/mediaHandler";
183-
import { GroupCallEventHandler } from "./webrtc/groupCallEventHandler";
184187
import { LoginTokenPostResponse, ILoginFlowsResponse, IRefreshTokenResponse, SSOAction } from "./@types/auth";
185188
import { TypedEventEmitter } from "./models/typed-event-emitter";
186189
import { MAIN_ROOM_TIMELINE, ReceiptType } from "./@types/read_receipts";
@@ -4087,27 +4090,23 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
40874090
queryString["server_name"] = opts.viaServers;
40884091
}
40894092

4090-
try {
4091-
const data: IJoinRequestBody = {};
4092-
const signedInviteObj = await signPromise;
4093-
if (signedInviteObj) {
4094-
data.third_party_signed = signedInviteObj;
4095-
}
4093+
const data: IJoinRequestBody = {};
4094+
const signedInviteObj = await signPromise;
4095+
if (signedInviteObj) {
4096+
data.third_party_signed = signedInviteObj;
4097+
}
40964098

4097-
const path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias });
4098-
const res = await this.http.authedRequest<{ room_id: string }>(Method.Post, path, queryString, data);
4099+
const path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias });
4100+
const res = await this.http.authedRequest<{ room_id: string }>(Method.Post, path, queryString, data);
40994101

4100-
const roomId = res.room_id;
4101-
const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());
4102-
const room = syncApi.createRoom(roomId);
4103-
if (opts.syncRoom) {
4104-
// v2 will do this for us
4105-
// return syncApi.syncRoom(room);
4106-
}
4107-
return room;
4108-
} catch (e) {
4109-
throw e; // rethrow for reject
4102+
const roomId = res.room_id;
4103+
const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());
4104+
const syncRoom = syncApi.createRoom(roomId);
4105+
if (opts.syncRoom) {
4106+
// v2 will do this for us
4107+
// return syncApi.syncRoom(room);
41104108
}
4109+
return syncRoom;
41114110
}
41124111

41134112
/**
@@ -4689,7 +4688,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
46894688
const eventType: string = EventType.RoomMessage;
46904689
const sendContent: IContent = content as IContent;
46914690

4692-
return this.sendEvent(roomId, threadId as string | null, eventType, sendContent, txnId);
4691+
return this.sendEvent(roomId, threadId, eventType, sendContent, txnId);
46934692
}
46944693

46954694
/**
@@ -5005,7 +5004,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
50055004
rpEvent?: MatrixEvent,
50065005
): Promise<{}> {
50075006
const room = this.getRoom(roomId);
5008-
if (room && room.hasPendingEvent(rmEventId)) {
5007+
if (room?.hasPendingEvent(rmEventId)) {
50095008
throw new Error(`Cannot set read marker to a pending event (${rmEventId})`);
50105009
}
50115010

@@ -5058,9 +5057,8 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
50585057
const key = ts + "_" + url;
50595058

50605059
// If there's already a request in flight (or we've handled it), return that instead.
5061-
const cachedPreview = this.urlPreviewCache[key];
5062-
if (cachedPreview) {
5063-
return cachedPreview;
5060+
if (key in this.urlPreviewCache) {
5061+
return this.urlPreviewCache[key];
50645062
}
50655063

50665064
const resp = this.http.authedRequest<IPreviewUrlResponse>(

0 commit comments

Comments
 (0)