split off into fake client

This commit is contained in:
Sorunome 2020-06-05 09:59:37 +02:00
parent e14cd61d6d
commit 0b1d6ae8dd
No known key found for this signature in database
GPG key ID: B19471D07FC9BE9C
10 changed files with 99 additions and 93 deletions

View file

@ -20,8 +20,7 @@ import 'package:famedlysdk/famedlysdk.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:olm/olm.dart' as olm; import 'package:olm/olm.dart' as olm;
import '../fake_matrix_api.dart'; import '../fake_client.dart';
import '../fake_database.dart';
void main() { void main() {
group('Encrypt/Decrypt room message', () { group('Encrypt/Decrypt room message', () {
@ -37,16 +36,14 @@ void main() {
if (!olmEnabled) return; if (!olmEnabled) return;
var client = Client('testclient', debug: true, httpClient: FakeMatrixApi()); Client client;
final roomId = '!726s6s6q:example.com'; final roomId = '!726s6s6q:example.com';
Room room; Room room;
Map<String, dynamic> payload; Map<String, dynamic> payload;
final now = DateTime.now(); final now = DateTime.now();
test('setupClient', () async { test('setupClient', () async {
client.database = getDatabase(); client = await getClient();
await client.checkServer('https://fakeServer.notExisting');
await client.login('test', '1234');
room = client.getRoomById(roomId); room = client.getRoomById(roomId);
}); });

View file

@ -20,14 +20,11 @@ import 'package:famedlysdk/famedlysdk.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:olm/olm.dart' as olm; import 'package:olm/olm.dart' as olm;
import '../fake_client.dart';
import '../fake_matrix_api.dart'; import '../fake_matrix_api.dart';
import '../fake_database.dart';
void main() { void main() {
// key @test:fakeServer.notExisting // key @othertest:fakeServer.notExisting
const pickledOlmAccount =
'N2v1MkIFGcl0mQpo2OCwSopxPQJ0wnl7oe7PKiT4141AijfdTIhRu+ceXzXKy3Kr00nLqXtRv7kid6hU4a+V0rfJWLL0Y51+3Rp/ORDVnQy+SSeo6Fn4FHcXrxifJEJ0djla5u98fBcJ8BSkhIDmtXRPi5/oJAvpiYn+8zMjFHobOeZUAxYR0VfQ9JzSYBsSovoQ7uFkNks1M4EDUvHtu/BjDjz0C3ioDgrrFdoSrn+GSeF5FGKsNu8OLkQ9Lq5+BrUutK5QSJI19uoZj2sj/OixvIpnun8XxYpXo7cfh9MEtKI8ob7lLM2OpZ8BogU70ORgkwthsPSOtxQGPhx8+y5Sg7B6KGlU';
const otherPickledOlmAccount = const otherPickledOlmAccount =
'VWhVApbkcilKAEGppsPDf9nNVjaK8/IxT3asSR0sYg0S5KgbfE8vXEPwoiKBX2cEvwX3OessOBOkk+ZE7TTbjlrh/KEd31p8Wo+47qj0AP+Ky+pabnhi+/rTBvZy+gfzTqUfCxZrkzfXI9Op4JnP6gYmy7dVX2lMYIIs9WCO1jcmIXiXum5jnfXu1WLfc7PZtO2hH+k9CDKosOFaXRBmsu8k/BGXPSoWqUpvu6WpEG9t5STk4FeAzA'; 'VWhVApbkcilKAEGppsPDf9nNVjaK8/IxT3asSR0sYg0S5KgbfE8vXEPwoiKBX2cEvwX3OessOBOkk+ZE7TTbjlrh/KEd31p8Wo+47qj0AP+Ky+pabnhi+/rTBvZy+gfzTqUfCxZrkzfXI9Op4JnP6gYmy7dVX2lMYIIs9WCO1jcmIXiXum5jnfXu1WLfc7PZtO2hH+k9CDKosOFaXRBmsu8k/BGXPSoWqUpvu6WpEG9t5STk4FeAzA';
@ -44,31 +41,16 @@ void main() {
if (!olmEnabled) return; if (!olmEnabled) return;
var client = Client('testclient', debug: true, httpClient: FakeMatrixApi()); Client client;
var otherClient = var otherClient =
Client('othertestclient', debug: true, httpClient: FakeMatrixApi()); Client('othertestclient', debug: true, httpClient: FakeMatrixApi());
DeviceKeys device; DeviceKeys device;
Map<String, dynamic> payload; Map<String, dynamic> payload;
test('setupClient', () async { test('setupClient', () async {
client.database = getDatabase(); client = await getClient();
otherClient.database = client.database; otherClient.database = client.database;
await client.checkServer('https://fakeServer.notExisting');
await otherClient.checkServer('https://fakeServer.notExisting'); await otherClient.checkServer('https://fakeServer.notExisting');
final resp = await client.api.login(
type: 'm.login.password',
user: 'test',
password: '1234',
initialDeviceDisplayName: 'Fluffy Matrix Client',
);
client.connect(
newToken: resp.accessToken,
newUserID: resp.userId,
newHomeserver: client.api.homeserver,
newDeviceName: 'Text Matrix Client',
newDeviceID: resp.deviceId,
newOlmAccount: pickledOlmAccount,
);
otherClient.connect( otherClient.connect(
newToken: 'abc', newToken: 'abc',
newUserID: '@othertest:fakeServer.notExisting', newUserID: '@othertest:fakeServer.notExisting',
@ -78,14 +60,14 @@ void main() {
newOlmAccount: otherPickledOlmAccount, newOlmAccount: otherPickledOlmAccount,
); );
await Future.delayed(Duration(milliseconds: 50)); await Future.delayed(Duration(milliseconds: 10));
device = DeviceKeys( device = DeviceKeys(
userId: resp.userId, userId: client.userID,
deviceId: resp.deviceId, deviceId: client.deviceID,
algorithms: ['m.olm.v1.curve25519-aes-sha2', 'm.megolm.v1.aes-sha2'], algorithms: ['m.olm.v1.curve25519-aes-sha2', 'm.megolm.v1.aes-sha2'],
keys: { keys: {
'curve25519:${resp.deviceId}': client.identityKey, 'curve25519:${client.deviceID}': client.identityKey,
'ed25519:${resp.deviceId}': client.fingerprintKey, 'ed25519:${client.deviceID}': client.fingerprintKey,
}, },
verified: true, verified: true,
blocked: false, blocked: false,

View file

@ -19,9 +19,10 @@
import 'dart:convert'; import 'dart:convert';
import 'package:famedlysdk/famedlysdk.dart'; import 'package:famedlysdk/famedlysdk.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:olm/olm.dart' as olm;
import '../fake_client.dart';
import '../fake_matrix_api.dart'; import '../fake_matrix_api.dart';
import '../fake_database.dart';
Map<String, dynamic> jsonDecode(dynamic payload) { Map<String, dynamic> jsonDecode(dynamic payload) {
if (payload is String) { if (payload is String) {
@ -38,18 +39,22 @@ Map<String, dynamic> jsonDecode(dynamic payload) {
void main() { void main() {
/// All Tests related to device keys /// All Tests related to device keys
group('Key Request', () { group('Key Request', () {
var olmEnabled = true;
try {
olm.init();
olm.Account();
} catch (_) {
olmEnabled = false;
print('[LibOlm] Failed to load LibOlm: ' + _.toString());
}
print('[LibOlm] Enabled: $olmEnabled');
if (!olmEnabled) return;
final validSessionId = 'ciM/JWTPrmiWPPZNkRLDPQYf9AW/I46bxyLSr+Bx5oU'; final validSessionId = 'ciM/JWTPrmiWPPZNkRLDPQYf9AW/I46bxyLSr+Bx5oU';
final validSenderKey = '3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI'; final validSenderKey = '3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI';
test('Create Request', () async { test('Create Request', () async {
var matrix = var matrix = await getClient();
Client('testclient', debug: true, httpClient: FakeMatrixApi());
matrix.database = getDatabase();
await matrix.checkServer('https://fakeServer.notExisting');
await matrix.login('test', '1234');
if (!matrix.encryptionEnabled) {
await matrix.dispose(closeDatabase: true);
return;
}
final requestRoom = matrix.getRoomById('!726s6s6q:example.com'); final requestRoom = matrix.getRoomById('!726s6s6q:example.com');
await matrix.encryption.keyManager await matrix.encryption.keyManager
.request(requestRoom, 'sessionId', validSenderKey); .request(requestRoom, 'sessionId', validSenderKey);
@ -75,15 +80,7 @@ void main() {
await matrix.dispose(closeDatabase: true); await matrix.dispose(closeDatabase: true);
}); });
test('Reply To Request', () async { test('Reply To Request', () async {
var matrix = var matrix = await getClient();
Client('testclient', debug: true, httpClient: FakeMatrixApi());
matrix.database = getDatabase();
await matrix.checkServer('https://fakeServer.notExisting');
await matrix.login('test', '1234');
if (!matrix.encryptionEnabled) {
await matrix.dispose(closeDatabase: true);
return;
}
matrix.setUserId('@alice:example.com'); // we need to pretend to be alice matrix.setUserId('@alice:example.com'); // we need to pretend to be alice
FakeMatrixApi.calledEndpoints.clear(); FakeMatrixApi.calledEndpoints.clear();
await matrix await matrix
@ -224,15 +221,7 @@ void main() {
await matrix.dispose(closeDatabase: true); await matrix.dispose(closeDatabase: true);
}); });
test('Receive shared keys', () async { test('Receive shared keys', () async {
var matrix = var matrix = await getClient();
Client('testclient', debug: true, httpClient: FakeMatrixApi());
matrix.database = getDatabase();
await matrix.checkServer('https://fakeServer.notExisting');
await matrix.login('test', '1234');
if (!matrix.encryptionEnabled) {
await matrix.dispose(closeDatabase: true);
return;
}
final requestRoom = matrix.getRoomById('!726s6s6q:example.com'); final requestRoom = matrix.getRoomById('!726s6s6q:example.com');
await matrix.encryption.keyManager await matrix.encryption.keyManager
.request(requestRoom, validSessionId, validSenderKey); .request(requestRoom, validSessionId, validSenderKey);

View file

@ -21,8 +21,7 @@ import 'package:famedlysdk/encryption.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:olm/olm.dart' as olm; import 'package:olm/olm.dart' as olm;
import '../fake_matrix_api.dart'; import '../fake_client.dart';
import '../fake_database.dart';
void main() { void main() {
/// All Tests related to the ChatTime /// All Tests related to the ChatTime
@ -37,17 +36,17 @@ void main() {
} }
print('[LibOlm] Enabled: $olmEnabled'); print('[LibOlm] Enabled: $olmEnabled');
var client = Client('testclient', debug: true, httpClient: FakeMatrixApi()); if (!olmEnabled) return;
var room = Room(id: '!localpart:server.abc', client: client);
Client client;
Room room;
var updateCounter = 0; var updateCounter = 0;
KeyVerification keyVerification; KeyVerification keyVerification;
if (!olmEnabled) return;
test('setupClient', () async { test('setupClient', () async {
client.database = getDatabase(); client = await getClient();
await client.checkServer('https://fakeServer.notExisting'); room = Room(id: '!localpart:server.abc', client: client);
await client.login('test', '1234');
keyVerification = KeyVerification( keyVerification = KeyVerification(
encryption: client.encryption, encryption: client.encryption,
room: room, room: room,

View file

@ -21,8 +21,8 @@ import 'package:famedlysdk/famedlysdk.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:olm/olm.dart' as olm; import 'package:olm/olm.dart' as olm;
import '../fake_client.dart';
import '../fake_matrix_api.dart'; import '../fake_matrix_api.dart';
import '../fake_database.dart';
void main() { void main() {
group('Olm Manager', () { group('Olm Manager', () {
@ -38,12 +38,10 @@ void main() {
if (!olmEnabled) return; if (!olmEnabled) return;
var client = Client('testclient', debug: true, httpClient: FakeMatrixApi()); Client client;
test('setupClient', () async { test('setupClient', () async {
client.database = getDatabase(); client = await getClient();
await client.checkServer('https://fakeServer.notExisting');
await client.login('test', '1234');
}); });
test('signatures', () async { test('signatures', () async {

View file

@ -220,7 +220,7 @@ void main() {
event.status = -1; event.status = -1;
final resp2 = await event.sendAgain(txid: '1234'); final resp2 = await event.sendAgain(txid: '1234');
expect(resp1, null); expect(resp1, null);
expect(resp2, '42'); expect(resp2, '\$event0');
await matrix.dispose(closeDatabase: true); await matrix.dispose(closeDatabase: true);
}); });

48
test/fake_client.dart Normal file
View file

@ -0,0 +1,48 @@
/*
* Ansible inventory script used at Famedly GmbH for managing many hosts
* Copyright (C) 2020 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'package:famedlysdk/famedlysdk.dart';
import 'fake_matrix_api.dart';
import 'fake_database.dart';
// key @test:fakeServer.notExisting
const pickledOlmAccount =
'N2v1MkIFGcl0mQpo2OCwSopxPQJ0wnl7oe7PKiT4141AijfdTIhRu+ceXzXKy3Kr00nLqXtRv7kid6hU4a+V0rfJWLL0Y51+3Rp/ORDVnQy+SSeo6Fn4FHcXrxifJEJ0djla5u98fBcJ8BSkhIDmtXRPi5/oJAvpiYn+8zMjFHobOeZUAxYR0VfQ9JzSYBsSovoQ7uFkNks1M4EDUvHtu/BjDjz0C3ioDgrrFdoSrn+GSeF5FGKsNu8OLkQ9Lq5+BrUutK5QSJI19uoZj2sj/OixvIpnun8XxYpXo7cfh9MEtKI8ob7lLM2OpZ8BogU70ORgkwthsPSOtxQGPhx8+y5Sg7B6KGlU';
Future<Client> getClient() async {
final client = Client('testclient', debug: true, httpClient: FakeMatrixApi());
client.database = getDatabase();
await client.checkServer('https://fakeServer.notExisting');
final resp = await client.api.login(
type: 'm.login.password',
user: 'test',
password: '1234',
initialDeviceDisplayName: 'Fluffy Matrix Client',
);
client.connect(
newToken: resp.accessToken,
newUserID: resp.userId,
newHomeserver: client.api.homeserver,
newDeviceName: 'Text Matrix Client',
newDeviceID: resp.deviceId,
newOlmAccount: pickledOlmAccount,
);
await Future.delayed(Duration(milliseconds: 10));
return client;
}

View file

@ -25,6 +25,7 @@ import 'package:http/testing.dart';
class FakeMatrixApi extends MockClient { class FakeMatrixApi extends MockClient {
static final calledEndpoints = <String, List<dynamic>>{}; static final calledEndpoints = <String, List<dynamic>>{};
static int eventCounter = 0;
FakeMatrixApi() FakeMatrixApi()
: super((request) async { : super((request) async {
@ -1754,13 +1755,13 @@ class FakeMatrixApi extends MockClient {
'/client/r0/directory/room/%23testalias%3Aexample.com': (var reqI) => {}, '/client/r0/directory/room/%23testalias%3Aexample.com': (var reqI) => {},
'/client/r0/rooms/%21localpart%3Aserver.abc/send/m.room.message/testtxid': '/client/r0/rooms/%21localpart%3Aserver.abc/send/m.room.message/testtxid':
(var reqI) => { (var reqI) => {
'event_id': '42', 'event_id': '\$event${FakeMatrixApi.eventCounter++}',
}, },
'/client/r0/rooms/!localpart%3Aexample.com/typing/%40alice%3Aexample.com': '/client/r0/rooms/!localpart%3Aexample.com/typing/%40alice%3Aexample.com':
(var req) => {}, (var req) => {},
'/client/r0/rooms/%211234%3Aexample.com/send/m.room.message/1234': '/client/r0/rooms/%211234%3Aexample.com/send/m.room.message/1234':
(var reqI) => { (var reqI) => {
'event_id': '42', 'event_id': '\$event${FakeMatrixApi.eventCounter++}',
}, },
'/client/r0/user/%40alice%3Aexample.com/rooms/%21localpart%3Aexample.com/tags/testtag': '/client/r0/user/%40alice%3Aexample.com/rooms/%21localpart%3Aexample.com/tags/testtag':
(var req) => {}, (var req) => {},

View file

@ -26,7 +26,7 @@ import 'package:famedlysdk/src/database/database.dart'
show DbRoom, DbRoomState, DbRoomAccountData; show DbRoom, DbRoomState, DbRoomAccountData;
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'fake_matrix_api.dart'; import 'fake_client.dart';
import 'dart:typed_data'; import 'dart:typed_data';
@ -37,15 +37,7 @@ void main() {
/// All Tests related to the Event /// All Tests related to the Event
group('Room', () { group('Room', () {
test('Login', () async { test('Login', () async {
matrix = Client('testclient', debug: true, httpClient: FakeMatrixApi()); matrix = await getClient();
final checkResp =
await matrix.checkServer('https://fakeServer.notExisting');
final loginResp = await matrix.login('test', '1234');
expect(checkResp, true);
expect(loginResp, true);
}); });
test('Create from json', () async { test('Create from json', () async {
@ -315,7 +307,7 @@ void main() {
test('getTimeline', () async { test('getTimeline', () async {
final timeline = await room.getTimeline(); final timeline = await room.getTimeline();
expect(timeline.events.length, 1); expect(timeline.events.length, 0);
}); });
test('getUserByMXID', () async { test('getUserByMXID', () async {
@ -338,13 +330,13 @@ void main() {
final dynamic resp = await room.sendEvent( final dynamic resp = await room.sendEvent(
{'msgtype': 'm.text', 'body': 'hello world'}, {'msgtype': 'm.text', 'body': 'hello world'},
txid: 'testtxid'); txid: 'testtxid');
expect(resp, '42'); expect(resp, '\$event0');
}); });
test('sendEvent', () async { test('sendEvent', () async {
final dynamic resp = final dynamic resp =
await room.sendTextEvent('Hello world', txid: 'testtxid'); await room.sendTextEvent('Hello world', txid: 'testtxid');
expect(resp, '42'); expect(resp, '\$event1');
}); });
// Not working because there is no real file to test it... // Not working because there is no real file to test it...

View file

@ -143,7 +143,7 @@ void main() {
expect(updateCount, 5); expect(updateCount, 5);
expect(insertList, [0, 0, 0]); expect(insertList, [0, 0, 0]);
expect(insertList.length, timeline.events.length); expect(insertList.length, timeline.events.length);
expect(timeline.events[0].eventId, '42'); expect(timeline.events[0].eventId, '\$event0');
expect(timeline.events[0].status, 1); expect(timeline.events[0].status, 1);
client.onEvent.add(EventUpdate( client.onEvent.add(EventUpdate(
@ -155,7 +155,7 @@ void main() {
'content': {'msgtype': 'm.text', 'body': 'test'}, 'content': {'msgtype': 'm.text', 'body': 'test'},
'sender': '@alice:example.com', 'sender': '@alice:example.com',
'status': 2, 'status': 2,
'event_id': '42', 'event_id': '\$event0',
'unsigned': {'transaction_id': '1234'}, 'unsigned': {'transaction_id': '1234'},
'origin_server_ts': DateTime.now().millisecondsSinceEpoch 'origin_server_ts': DateTime.now().millisecondsSinceEpoch
}, },
@ -166,7 +166,7 @@ void main() {
expect(updateCount, 6); expect(updateCount, 6);
expect(insertList, [0, 0, 0]); expect(insertList, [0, 0, 0]);
expect(insertList.length, timeline.events.length); expect(insertList.length, timeline.events.length);
expect(timeline.events[0].eventId, '42'); expect(timeline.events[0].eventId, '\$event0');
expect(timeline.events[0].status, 2); expect(timeline.events[0].status, 2);
}); });