From 6e20c53b01671a5a8668382fed1884537e2baed5 Mon Sep 17 00:00:00 2001 From: Nicolas Werner Date: Thu, 28 Oct 2021 14:32:09 +0200 Subject: [PATCH] refactor: remove redundant null checks --- analysis_options.yaml | 3 - lib/encryption/cross_signing.dart | 7 +- .../utils/json_signature_check_extension.dart | 6 +- lib/encryption/utils/key_verification.dart | 17 ++--- lib/src/client.dart | 76 ++++++++----------- lib/src/database/hive_database.dart | 16 ++-- lib/src/event.dart | 27 ++++--- lib/src/room.dart | 48 +++++------- lib/src/timeline.dart | 5 +- lib/src/user.dart | 6 +- lib/src/utils/commands_extension.dart | 2 +- lib/src/utils/device_keys_list.dart | 3 - lib/src/voip_content.dart | 8 +- test/client_test.dart | 4 +- test/encryption/key_manager_test.dart | 10 +-- test/encryption/key_verification_test.dart | 4 - test/matrix_file_test.dart | 2 +- test_driver/matrixsdk_test.dart | 7 +- 18 files changed, 108 insertions(+), 143 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 2d42f778..41ff68ac 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -12,9 +12,6 @@ analyzer: errors: todo: ignore import_of_legacy_library_into_null_safe: ignore - # ignore those until we are completely nullsafe - invalid_null_aware_operator: ignore - unnecessary_null_comparison: ignore exclude: - example/main.dart # needed until crypto packages upgrade diff --git a/lib/encryption/cross_signing.dart b/lib/encryption/cross_signing.dart index 73637f5a..6d243f21 100644 --- a/lib/encryption/cross_signing.dart +++ b/lib/encryption/cross_signing.dart @@ -90,9 +90,11 @@ class CrossSigning { final masterPrivateKey = base64.decode(await handle.getStored(EventTypes.CrossSigningMasterKey)); final keyObj = olm.PkSigning(); - String masterPubkey; + String? masterPubkey; try { masterPubkey = keyObj.init_with_seed(masterPrivateKey); + } catch (e) { + masterPubkey = null; } finally { keyObj.free(); } @@ -131,9 +133,6 @@ class CrossSigning { final addSignature = (SignableKey key, SignableKey signedWith, String signature) { - if (key == null || signedWith == null || signature == null) { - return; - } final signedKey = key.cloneForSigning(); ((signedKey.signatures ??= >{})[signedWith.userId] ??= diff --git a/lib/encryption/utils/json_signature_check_extension.dart b/lib/encryption/utils/json_signature_check_extension.dart index 7c89bca8..63afe7b2 100644 --- a/lib/encryption/utils/json_signature_check_extension.dart +++ b/lib/encryption/utils/json_signature_check_extension.dart @@ -24,8 +24,10 @@ import '../../matrix.dart'; extension JsonSignatureCheckExtension on Map { /// Checks the signature of a signed json object. bool checkJsonSignature(String key, String userId, String deviceId) { - final Map signatures = this['signatures']; - if (signatures == null || !signatures.containsKey(userId)) return false; + final signatures = this['signatures']; + if (signatures == null || + !(signatures is Map) || + !signatures.containsKey(userId)) return false; remove('unsigned'); remove('signatures'); if (!signatures[userId].containsKey('ed25519:$deviceId')) return false; diff --git a/lib/encryption/utils/key_verification.dart b/lib/encryption/utils/key_verification.dart index 10fe9946..97984fec 100644 --- a/lib/encryption/utils/key_verification.dart +++ b/lib/encryption/utils/key_verification.dart @@ -152,9 +152,9 @@ class KeyVerification { List get knownVerificationMethods { final methods = []; - if (client.verificationMethods?.contains(KeyVerificationMethod.numbers) == + if (client.verificationMethods.contains(KeyVerificationMethod.numbers) == true || - client.verificationMethods?.contains(KeyVerificationMethod.emoji) == + client.verificationMethods.contains(KeyVerificationMethod.emoji) == true) { methods.add('m.sas.v1'); } @@ -358,10 +358,8 @@ class KeyVerification { if (_nextAction == 'request') { sendStart(); } else if (_nextAction == 'done') { - if (_verifiedDevices != null) { - // and now let's sign them all in the background - encryption.crossSigning.sign(_verifiedDevices); - } + // and now let's sign them all in the background + encryption.crossSigning.sign(_verifiedDevices); setState(KeyVerificationState.done); } }; @@ -532,8 +530,7 @@ class KeyVerification { } Future verifyActivity() async { - if (lastActivity != null && - lastActivity.add(Duration(minutes: 10)).isAfter(DateTime.now())) { + if (lastActivity.add(Duration(minutes: 10)).isAfter(DateTime.now())) { lastActivity = DateTime.now(); return true; } @@ -675,12 +672,12 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod { List get knownAuthentificationTypes { final types = []; if (request.client.verificationMethods - ?.contains(KeyVerificationMethod.emoji) == + .contains(KeyVerificationMethod.emoji) == true) { types.add('emoji'); } if (request.client.verificationMethods - ?.contains(KeyVerificationMethod.numbers) == + .contains(KeyVerificationMethod.numbers) == true) { types.add('decimal'); } diff --git a/lib/src/client.dart b/lib/src/client.dart index ea79b443..bf3393fd 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -431,10 +431,7 @@ class Client extends MatrixApi { final deviceId_ = response.deviceId; final userId = response.userId; final homeserver = this.homeserver; - if (accessToken == null || - deviceId_ == null || - userId == null || - homeserver == null) { + if (accessToken == null || deviceId_ == null || homeserver == null) { throw Exception( 'Registered but token, device ID, user ID or homeserver is null.'); } @@ -570,8 +567,6 @@ class Client extends MatrixApi { preset: CreateRoomPreset.trustedPrivateChat, ); - if (roomId == null) return roomId; - await Room(id: roomId, client: this).addToDirectChat(mxid); return roomId; @@ -1501,11 +1496,8 @@ class Client extends MatrixApi { void _updateRoomsByRoomUpdate(String roomId, SyncRoomUpdate chatUpdate) { // Update the chat list item. // Search the room in the rooms - var j = 0; - for (j = 0; j < rooms.length; j++) { - if (rooms[j].id == roomId) break; - } - final found = (j < rooms.length && rooms[j].id == roomId); + final roomIndex = rooms.indexWhere((r) => r.id == roomId); + final found = roomIndex != -1; final membership = chatUpdate is LeftRoomUpdate ? Membership.leave : chatUpdate is InvitedRoomUpdate @@ -1514,7 +1506,7 @@ class Client extends MatrixApi { // Does the chat already exist in the list rooms? if (!found && membership != Membership.leave) { - final position = membership == Membership.invite ? 0 : j; + final position = membership == Membership.invite ? 0 : rooms.length; // Add the new chat to the list final newRoom = chatUpdate is JoinedRoomUpdate ? Room( @@ -1533,38 +1525,39 @@ class Client extends MatrixApi { } // If the membership is "leave" then remove the item and stop here else if (found && membership == Membership.leave) { - rooms.removeAt(j); + rooms.removeAt(roomIndex); } // Update notification, highlight count and/or additional informations else if (found && chatUpdate is JoinedRoomUpdate && - (rooms[j].membership != membership || - rooms[j].notificationCount != + (rooms[roomIndex].membership != membership || + rooms[roomIndex].notificationCount != (chatUpdate.unreadNotifications?.notificationCount ?? 0) || - rooms[j].highlightCount != + rooms[roomIndex].highlightCount != (chatUpdate.unreadNotifications?.highlightCount ?? 0) || chatUpdate.summary != null || chatUpdate.timeline?.prevBatch != null)) { - rooms[j].membership = membership; - rooms[j].notificationCount = + rooms[roomIndex].membership = membership; + rooms[roomIndex].notificationCount = chatUpdate.unreadNotifications?.notificationCount ?? 0; - rooms[j].highlightCount = + rooms[roomIndex].highlightCount = chatUpdate.unreadNotifications?.highlightCount ?? 0; if (chatUpdate.timeline?.prevBatch != null) { - rooms[j].prev_batch = chatUpdate.timeline?.prevBatch; + rooms[roomIndex].prev_batch = chatUpdate.timeline?.prevBatch; } final summary = chatUpdate.summary; if (summary != null) { - final roomSummaryJson = rooms[j].summary.toJson() + final roomSummaryJson = rooms[roomIndex].summary.toJson() ..addAll(summary.toJson()); - rooms[j].summary = RoomSummary.fromJson(roomSummaryJson); + rooms[roomIndex].summary = RoomSummary.fromJson(roomSummaryJson); } - if (rooms[j].onUpdate != null) rooms[j].onUpdate.add(rooms[j].id); + rooms[roomIndex].onUpdate.add(rooms[roomIndex].id); if ((chatUpdate.timeline?.limited ?? false) && requestHistoryOnLimitedTimeline) { - Logs().v('Limited timeline for ${rooms[j].id} request history now'); - runInRoot(rooms[j].requestHistory); + Logs().v( + 'Limited timeline for ${rooms[roomIndex].id} request history now'); + runInRoot(rooms[roomIndex].requestHistory); } } } @@ -1637,7 +1630,7 @@ class Client extends MatrixApi { void _sortRooms() { if (prevBatch == null || _sortLock || rooms.length < 2) return; _sortLock = true; - rooms?.sort(sortRoomsBy); + rooms.sort(sortRoomsBy); _sortLock = false; } @@ -1808,10 +1801,8 @@ class Client extends MatrixApi { } } userKeys.outdated = false; - if (database != null) { - dbActions - .add(() => database.storeUserDeviceKeysInfo(userId, false)); - } + dbActions + .add(() => database.storeUserDeviceKeysInfo(userId, false)); } } // next we parse and persist the cross signing keys @@ -1837,7 +1828,7 @@ class Client extends MatrixApi { for (final oldEntry in oldKeys.entries) { if (!oldEntry.value.usage.contains(keyType)) { userKeys.crossSigningKeys[oldEntry.key] = oldEntry.value; - } else if (database != null) { + } else { // There is a previous cross-signing key with this usage, that we no // longer need/use. Clear it from the database. dbActions.add(() => @@ -1863,21 +1854,17 @@ class Client extends MatrixApi { // if we should instead use the new key with unknown verified / blocked status userKeys.crossSigningKeys[publicKey] = oldKey; } - if (database != null) { - dbActions.add(() => database.storeUserCrossSigningKey( - userId, - publicKey, - json.encode(entry.toJson()), - entry.directVerified, - entry.blocked, - )); - } + dbActions.add(() => database.storeUserCrossSigningKey( + userId, + publicKey, + json.encode(entry.toJson()), + entry.directVerified, + entry.blocked, + )); } _userDeviceKeys[userId]?.outdated = false; - if (database != null) { - dbActions - .add(() => database.storeUserDeviceKeysInfo(userId, false)); - } + dbActions + .add(() => database.storeUserDeviceKeysInfo(userId, false)); } } @@ -1992,7 +1979,6 @@ class Client extends MatrixApi { // then only send it to verified devices if (deviceKeys.isNotEmpty) { deviceKeys.removeWhere((DeviceKeys deviceKeys) => - deviceKeys == null || deviceKeys.blocked || (deviceKeys.userId == userID && deviceKeys.deviceId == deviceID) || (onlyVerified && !deviceKeys.verified)); diff --git a/lib/src/database/hive_database.dart b/lib/src/database/hive_database.dart index 84dcdfac..a5b81b57 100644 --- a/lib/src/database/hive_database.dart +++ b/lib/src/database/hive_database.dart @@ -518,8 +518,9 @@ class FamedlySdkHiveDatabase extends DatabaseApi { // We always need the member event for ourself final membersToPostload = {if (userID != null) userID}; // If the room is a direct chat, those IDs should be there too - if (room.isDirectChat) + if (room.isDirectChat) { membersToPostload.add(room.directChatMatrixID!); + } // the lastEvent message preview might have an author we need to fetch, if it is a group chat final lastEvent = room.getState(EventTypes.Message); if (lastEvent != null && !room.isDirectChat) { @@ -910,13 +911,12 @@ class FamedlySdkHiveDatabase extends DatabaseApi { return; } - final status = - newStatus.isError || prevEvent == null || prevEvent.status != null - ? newStatus - : latestEventStatus( - prevEvent.status, - newStatus, - ); + final status = newStatus.isError || prevEvent == null + ? newStatus + : latestEventStatus( + prevEvent.status, + newStatus, + ); // Add the status and the sort order to the content so it get stored eventUpdate.content['unsigned'] ??= {}; diff --git a/lib/src/event.dart b/lib/src/event.dart index 425bbd35..17fb4d18 100644 --- a/lib/src/event.dart +++ b/lib/src/event.dart @@ -118,7 +118,7 @@ class Event extends MatrixEvent { // Mark event as failed to send if status is `sending` and event is older // than the timeout. This should not happen with the deprecated Moor // database! - if (status.isSending && room?.client?.database != null) { + if (status.isSending && room?.client.database != null) { // Age of this event in milliseconds final age = DateTime.now().millisecondsSinceEpoch - originServerTs.millisecondsSinceEpoch; @@ -411,16 +411,21 @@ class Event extends MatrixEvent { : ''); /// Gets the underlying mxc url of an attachment of a file event, or null if not present - Uri get attachmentMxcUrl => Uri.parse( - isAttachmentEncrypted ? content['file']['url'] : content['url']); + Uri? get attachmentMxcUrl { + final url = isAttachmentEncrypted ? content['file']['url'] : content['url']; + return url is String ? Uri.tryParse(url) : null; + } /// Gets the underlying mxc url of a thumbnail of a file event, or null if not present - Uri get thumbnailMxcUrl => Uri.parse(isThumbnailEncrypted - ? infoMap['thumbnail_file']['url'] - : infoMap['thumbnail_url']); + Uri? get thumbnailMxcUrl { + final url = isThumbnailEncrypted + ? infoMap['thumbnail_file']['url'] + : infoMap['thumbnail_url']; + return url is String ? Uri.tryParse(url) : null; + } /// Gets the mxc url of an attachment/thumbnail of a file event, taking sizes into account, or null if not present - Uri attachmentOrThumbnailMxcUrl({bool getThumbnail = false}) { + Uri? attachmentOrThumbnailMxcUrl({bool getThumbnail = false}) { if (getThumbnail && infoMap['size'] is int && thumbnailInfoMap['size'] is int && @@ -599,7 +604,7 @@ class Event extends MatrixEvent { bool plaintextBody = false, }) { if (redacted) { - return i18n.removedBy(redactedBecause?.sender?.calcDisplayname() ?? ''); + return i18n.removedBy(redactedBecause?.sender.calcDisplayname() ?? ''); } var body = plaintextBody ? this.plaintextBody : this.body; @@ -643,7 +648,7 @@ class Event extends MatrixEvent { textOnlyMessageTypes.contains(messageType)) { final senderNameOrYou = senderId == room?.client.userID ? i18n.you - : (sender?.calcDisplayname() ?? ''); + : (sender.calcDisplayname()); localizedBody = '$senderNameOrYou: $localizedBody'; } @@ -670,7 +675,7 @@ class Event extends MatrixEvent { /// Get the relationship type of an event. `null` if there is none String? get relationshipType { - if (content?.tryGet>('m.relates_to') == null) { + if (content.tryGet>('m.relates_to') == null) { return null; } if (content['m.relates_to'].containsKey('m.in_reply_to')) { @@ -683,7 +688,7 @@ class Event extends MatrixEvent { /// Get the event ID that this relationship will reference. `null` if there is none String? get relationshipEventId { - if (content == null || !(content['m.relates_to'] is Map)) { + if (!(content['m.relates_to'] is Map)) { return null; } if (content['m.relates_to'].containsKey('event_id')) { diff --git a/lib/src/room.dart b/lib/src/room.dart index ee31ce9c..8721f685 100644 --- a/lib/src/room.dart +++ b/lib/src/room.dart @@ -239,13 +239,13 @@ class Room { /// Empty chats will become the localized version of 'Empty Chat'. /// This method requires a localization class which implements [MatrixLocalizations] String getLocalizedDisplayname(MatrixLocalizations i18n) { - if ((name?.isEmpty ?? true) && - (canonicalAlias?.isEmpty ?? true) && + if (name.isEmpty && + canonicalAlias.isEmpty && !isDirectChat && (summary.mHeroes != null && summary.mHeroes?.isNotEmpty == true)) { return i18n.groupWith(displayname); } - if (displayname?.isNotEmpty ?? false) { + if (displayname.isNotEmpty) { return displayname; } return i18n.emptyChat; @@ -356,9 +356,8 @@ class Room { states.forEach((final String key, final entry) { final state = entry['']; if (state == null) return; - if (state.originServerTs != null && - state.originServerTs.millisecondsSinceEpoch > - lastTime.millisecondsSinceEpoch) { + if (state.originServerTs.millisecondsSinceEpoch > + lastTime.millisecondsSinceEpoch) { lastTime = state.originServerTs; lastEvent = state; } @@ -405,9 +404,9 @@ class Room { /// Calculates the displayname. First checks if there is a name, then checks for a canonical alias and /// then generates a name from the heroes. String get displayname { - if (name != null && name.isNotEmpty) return name; + if (name.isNotEmpty) return name; - final canonicalAlias = this.canonicalAlias?.localpart; + final canonicalAlias = this.canonicalAlias.localpart; if (canonicalAlias != null && canonicalAlias.isNotEmpty) { return canonicalAlias; } @@ -529,7 +528,7 @@ class Room { content, ); final lastEvent = this.lastEvent; - if (unread == false && lastEvent != null) { + if (!unread && lastEvent != null) { await setReadMarker( lastEvent.eventId, mRead: lastEvent.eventId, @@ -1188,16 +1187,6 @@ class Room { bool ignoreErrors = false, bool requestProfile = true, }) async { - // TODO: Why is this bug happening at all? - if (mxID == null) { - // Show a warning but first generate a stacktrace. - try { - throw Exception(); - } catch (e, s) { - Logs().w('requestUser has been called with a null mxID', e, s); - } - return null; - } final stateUser = getState(EventTypes.RoomMember, mxID); if (stateUser != null) { return stateUser.asUser; @@ -1500,7 +1489,7 @@ class Room { /// intended for any member of the room other than the sender of the event. /// [party_id] The party ID for call, Can be set to client.deviceId. Future inviteToCall( - String callId, int lifetime, String party_id, String invitee, String sdp, + String callId, int lifetime, String party_id, String? invitee, String sdp, {String type = 'offer', String version = voipProtoVersion, String? txid, @@ -1678,7 +1667,8 @@ class Room { /// [callId] The ID of the call this event relates to. /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1. /// [party_id] The party ID for call, Can be set to client.deviceId. - Future hangupCall(String callId, String party_id, String hangupCause, + Future hangupCall( + String callId, String party_id, String? hangupCause, {String version = voipProtoVersion, String? txid}) async { txid ??= 'txid${DateTime.now().millisecondsSinceEpoch}'; @@ -1855,7 +1845,7 @@ class Room { /// Returns the encryption algorithm. Currently only `m.megolm.v1.aes-sha2` is supported. /// Returns null if there is no encryption algorithm. String? get encryptionAlgorithm => - getState(EventTypes.Encryption)?.parsedRoomEncryptionContent?.algorithm; + getState(EventTypes.Encryption)?.parsedRoomEncryptionContent.algorithm; /// Checks if this room is encrypted. bool get encrypted => encryptionAlgorithm != null; @@ -1920,7 +1910,7 @@ class Room { /// Checks if the `m.room.create` state has a `type` key with the value /// `m.space`. bool get isSpace => - getState(EventTypes.RoomCreate)?.content?.tryGet('type') == + getState(EventTypes.RoomCreate)?.content.tryGet('type') == RoomCreationTypes.mSpace; // TODO: Magic string! /// The parents of this room. Currently this SDK doesn't yet set the canonical @@ -1930,9 +1920,9 @@ class Room { List get spaceParents => states[EventTypes.spaceParent] ?.values - ?.map((state) => SpaceParent.fromState(state)) - ?.where((child) => child.via?.isNotEmpty ?? false) - ?.toList() ?? + .map((state) => SpaceParent.fromState(state)) + .where((child) => child.via?.isNotEmpty ?? false) + .toList() ?? []; /// List all children of this space. Children without a `via` domain will be @@ -1943,9 +1933,9 @@ class Room { ? throw Exception('Room is not a space!') : (states[EventTypes.spaceChild] ?.values - ?.map((state) => SpaceChild.fromState(state)) - ?.where((child) => child.via?.isNotEmpty ?? false) - ?.toList() ?? + .map((state) => SpaceChild.fromState(state)) + .where((child) => child.via?.isNotEmpty ?? false) + .toList() ?? []) ..sort((a, b) => a.order.isEmpty || b.order.isEmpty ? b.order.compareTo(a.order) diff --git a/lib/src/timeline.dart b/lib/src/timeline.dart index 1be71186..b4cc82b7 100644 --- a/lib/src/timeline.dart +++ b/lib/src/timeline.dart @@ -187,10 +187,7 @@ class Timeline { } int i; for (i = 0; i < events.length; i++) { - final searchHaystack = {}; - if (events[i].eventId != null) { - searchHaystack.add(events[i].eventId); - } + final searchHaystack = {events[i].eventId}; final txnid = events[i].unsigned?['transaction_id']; if (txnid != null) { diff --git a/lib/src/user.dart b/lib/src/user.dart index 87c67e89..f4183db0 100644 --- a/lib/src/user.dart +++ b/lib/src/user.dart @@ -72,7 +72,7 @@ class User extends Event { /// The displayname of the user if the user has set one. String? get displayName => - content?.tryGet('displayname') ?? + content.tryGet('displayname') ?? prevContent?.tryGet('displayname'); /// Returns the power level of this user. @@ -112,8 +112,8 @@ class User extends Event { bool? formatLocalpart, bool? mxidLocalPartFallback, }) { - formatLocalpart ??= room?.client?.formatLocalpart ?? true; - mxidLocalPartFallback ??= room?.client?.mxidLocalPartFallback ?? true; + formatLocalpart ??= room?.client.formatLocalpart ?? true; + mxidLocalPartFallback ??= room?.client.mxidLocalPartFallback ?? true; final displayName = this.displayName; if (displayName != null && displayName.isNotEmpty) { return displayName; diff --git a/lib/src/utils/commands_extension.dart b/lib/src/utils/commands_extension.dart index c86b6d46..4167ae9f 100644 --- a/lib/src/utils/commands_extension.dart +++ b/lib/src/utils/commands_extension.dart @@ -199,7 +199,7 @@ extension CommandsClientExtension on Client { }); addCommand('discardsession', (CommandArgs args) async { await encryption?.keyManager - ?.clearOrUseOutboundGroupSession(args.room.id, wipe: true); + .clearOrUseOutboundGroupSession(args.room.id, wipe: true); return ''; }); } diff --git a/lib/src/utils/device_keys_list.dart b/lib/src/utils/device_keys_list.dart index 58f25985..6babeb1e 100644 --- a/lib/src/utils/device_keys_list.dart +++ b/lib/src/utils/device_keys_list.dart @@ -75,9 +75,6 @@ class DeviceKeysList { if (userId != client.userID) { // in-room verification with someone else final roomId = await client.startDirectChat(userId); - if (roomId == null) { - throw Exception('Unable to start new room'); - } final room = client.getRoomById(roomId) ?? Room(id: roomId, client: client); diff --git a/lib/src/voip_content.dart b/lib/src/voip_content.dart index 1ac24ebf..c39dce7f 100644 --- a/lib/src/voip_content.dart +++ b/lib/src/voip_content.dart @@ -84,8 +84,8 @@ class CallCapabilities { transferee: json['m.call.transferee'] as bool? ?? false, ); Map toJson() => { - if (transferee != null) 'm.call.transferee': transferee, - if (dtmf != null) 'm.call.dtmf': dtmf, + 'm.call.transferee': transferee, + 'm.call.dtmf': dtmf, }; } @@ -118,8 +118,8 @@ class SDPStreamPurpose { Map toJson() => { 'purpose': purpose, - if (audio_muted != null) 'audio_muted': audio_muted, - if (video_muted != null) 'video_muted': video_muted, + 'audio_muted': audio_muted, + 'video_muted': video_muted, }; } diff --git a/test/client_test.dart b/test/client_test.dart index 1fe8e29f..09a720dd 100644 --- a/test/client_test.dart +++ b/test/client_test.dart @@ -86,7 +86,7 @@ void main() { try { await matrix.checkHomeserver('https://fakeserver.wrongaddress'); } catch (exception) { - expect(exception != null, true); + expect(exception.toString().isNotEmpty, true); } await matrix.checkHomeserver('https://fakeserver.notexisting', checkWellKnown: false); @@ -311,7 +311,7 @@ void main() { identifier: AuthenticationUserIdentifier(user: 'test'), password: '1234'); - expect(loginResp != null, true); + expect(loginResp.userId != null, true); }); test('setAvatar', () async { diff --git a/test/encryption/key_manager_test.dart b/test/encryption/key_manager_test.dart index 8606f617..c73af662 100644 --- a/test/encryption/key_manager_test.dart +++ b/test/encryption/key_manager_test.dart @@ -409,7 +409,7 @@ void main() { client.encryption!.keyManager .getInboundGroupSession(roomId, sessionId, senderKey) ?.forwardingCurve25519KeyChain - ?.length, + .length, 1); // not set one with a higher first known index @@ -435,7 +435,7 @@ void main() { client.encryption!.keyManager .getInboundGroupSession(roomId, sessionId, senderKey) ?.forwardingCurve25519KeyChain - ?.length, + .length, 1); // set one with a lower first known index @@ -461,7 +461,7 @@ void main() { client.encryption!.keyManager .getInboundGroupSession(roomId, sessionId, senderKey) ?.forwardingCurve25519KeyChain - ?.length, + .length, 1); // not set one with a longer forwarding chain @@ -487,7 +487,7 @@ void main() { client.encryption!.keyManager .getInboundGroupSession(roomId, sessionId, senderKey) ?.forwardingCurve25519KeyChain - ?.length, + .length, 1); // set one with a shorter forwarding chain @@ -513,7 +513,7 @@ void main() { client.encryption!.keyManager .getInboundGroupSession(roomId, sessionId, senderKey) ?.forwardingCurve25519KeyChain - ?.length, + .length, 0); // test that it decrypted the last event diff --git a/test/encryption/key_verification_test.dart b/test/encryption/key_verification_test.dart index 58362e00..8a622e44 100644 --- a/test/encryption/key_verification_test.dart +++ b/test/encryption/key_verification_test.dart @@ -130,7 +130,6 @@ void main() { await client2.encryption!.keyVerificationManager.handleEventUpdate(evt); await Future.delayed(Duration(milliseconds: 10)); await sub.cancel(); - expect(req2 != null, true); expect( client2.encryption!.keyVerificationManager @@ -254,7 +253,6 @@ void main() { await client2.encryption!.keyVerificationManager.handleEventUpdate(evt); await Future.delayed(Duration(milliseconds: 10)); await sub.cancel(); - expect(req2 != null, true); // send ready FakeMatrixApi.calledEndpoints.clear(); @@ -389,7 +387,6 @@ void main() { await client2.encryption!.keyVerificationManager.handleEventUpdate(evt); await Future.delayed(Duration(milliseconds: 10)); await sub.cancel(); - expect(req2 != null, true); // send ready FakeMatrixApi.calledEndpoints.clear(); @@ -451,7 +448,6 @@ void main() { await client2.encryption!.keyVerificationManager.handleEventUpdate(evt); await Future.delayed(Duration(milliseconds: 10)); await sub.cancel(); - expect(req2 != null, true); await client2.encryption!.keyVerificationManager .handleEventUpdate(EventUpdate( diff --git a/test/matrix_file_test.dart b/test/matrix_file_test.dart index 6b509461..d932bcbc 100644 --- a/test/matrix_file_test.dart +++ b/test/matrix_file_test.dart @@ -42,7 +42,7 @@ void main() { } if (olmEnabled) { final encryptedFile = await file.encrypt(); - expect(encryptedFile != null, true); + expect(encryptedFile.data.isNotEmpty, true); } }); }); diff --git a/test_driver/matrixsdk_test.dart b/test_driver/matrixsdk_test.dart index 3a24abdf..2e3294bf 100644 --- a/test_driver/matrixsdk_test.dart +++ b/test_driver/matrixsdk_test.dart @@ -55,7 +55,7 @@ void test() async { Logs().i('++++ (Alice) Leave all rooms ++++'); while (testClientA.rooms.isNotEmpty) { final room = testClientA.rooms.first; - if (room.canonicalAlias?.isNotEmpty ?? false) { + if (room.canonicalAlias.isNotEmpty) { break; } try { @@ -95,7 +95,6 @@ void test() async { await testClientA.createRoom(invite: [TestUser.username2]); await Future.delayed(Duration(seconds: 1)); final room = testClientA.rooms.first; - assert(room != null); final roomId = room.id; Logs().i('++++ (Bob) Join room ++++'); @@ -220,7 +219,7 @@ void test() async { .client.encryption!.keyManager .getOutboundGroupSession(inviteRoom.id)!; - assert(inviteRoomOutboundGroupSession != null); + assert(inviteRoomOutboundGroupSession.isValid); /*assert(inviteRoom.client.encryption.keyManager.getInboundGroupSession( inviteRoom.id, inviteRoomOutboundGroupSession.outboundGroupSession.session_id(), @@ -237,7 +236,7 @@ void test() async { "++++ (Alice) Received decrypted message: '${room.lastEvent!.body}' ++++"); Logs().i('++++ Login Bob in another client ++++'); - var testClientC = Client('TestClientC', databaseBuilder: getDatabase); + final testClientC = Client('TestClientC', databaseBuilder: getDatabase); await testClientC.checkHomeserver(TestUser.homeserver); await testClientC.login(LoginType.mLoginPassword, identifier: AuthenticationUserIdentifier(user: TestUser.username2),