fix(style): Format and lint test helpers

This commit is contained in:
PapaTutuWawa 2023-03-12 19:19:53 +01:00
parent f49eb66bb7
commit 9cb6346c4d
4 changed files with 91 additions and 58 deletions

View File

@ -5,6 +5,8 @@ void initLogger() {
Logger.root.level = Level.ALL; Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((record) { Logger.root.onRecord.listen((record) {
// ignore: avoid_print // ignore: avoid_print
print('[${record.level.name}] (${record.loggerName}) ${record.time}: ${record.message}'); print(
'[${record.level.name}] (${record.loggerName}) ${record.time}: ${record.message}',
);
}); });
} }

View File

@ -29,7 +29,14 @@ class TestingManagerHolder {
allowPlainAuth: true, allowPlainAuth: true,
); );
Future<XMLNode> _sendStanza(stanza, { StanzaFromType addFrom = StanzaFromType.full, bool addId = true, bool awaitable = true, bool encrypted = false, bool forceEncryption = false, }) async { Future<XMLNode> _sendStanza(
stanza, {
StanzaFromType addFrom = StanzaFromType.full,
bool addId = true,
bool awaitable = true,
bool encrypted = false,
bool forceEncryption = false,
}) async {
return XMLNode.fromString('<iq />'); return XMLNode.fromString('<iq />');
} }
@ -60,4 +67,4 @@ class TestingManagerHolder {
await manager.postRegisterCallback(); await manager.postRegisterCallback();
_managers[manager.id] = manager; _managers[manager.id] = manager;
} }
} }

View File

@ -1,28 +1,37 @@
import 'package:moxxmpp/moxxmpp.dart'; import 'package:moxxmpp/moxxmpp.dart';
bool compareXMLNodes(XMLNode actual, XMLNode expectation, { bool ignoreId = true}) { bool compareXMLNodes(
XMLNode actual,
XMLNode expectation, {
bool ignoreId = true,
}) {
// Compare attributes // Compare attributes
if (expectation.tag != actual.tag) return false; if (expectation.tag != actual.tag) return false;
final attributesEqual = expectation.attributes.keys.every((key) { final attributesEqual = expectation.attributes.keys.every((key) {
// Ignore the stanza ID // Ignore the stanza ID
if (key == 'id' && ignoreId) return true; if (key == 'id' && ignoreId) return true;
return actual.attributes[key] == expectation.attributes[key]; return actual.attributes[key] == expectation.attributes[key];
}); });
if (!attributesEqual) return false; if (!attributesEqual) return false;
final actualAttributeLength = !ignoreId ? actual.attributes.length : ( final actualAttributeLength = !ignoreId
actual.attributes.containsKey('id') ? actual.attributes.length - 1 : actual.attributes.length ? actual.attributes.length
); : (actual.attributes.containsKey('id')
final expectedAttributeLength = !ignoreId ? expectation.attributes.length : ( ? actual.attributes.length - 1
expectation.attributes.containsKey('id') ? expectation.attributes.length - 1 : expectation.attributes.length : actual.attributes.length);
); final expectedAttributeLength = !ignoreId
? expectation.attributes.length
: (expectation.attributes.containsKey('id')
? expectation.attributes.length - 1
: expectation.attributes.length);
if (actualAttributeLength != expectedAttributeLength) return false; if (actualAttributeLength != expectedAttributeLength) return false;
if (expectation.innerText() != '' && actual.innerText() != expectation.innerText()) return false; if (expectation.innerText() != '' &&
actual.innerText() != expectation.innerText()) return false;
return expectation.children.every((childe) { return expectation.children.every((childe) {
return actual.children.any((childa) => compareXMLNodes(childa, childe)); return actual.children.any((childa) => compareXMLNodes(childa, childe));
}); });
} }

View File

@ -25,19 +25,23 @@ abstract class ExpectationBase {
/// Literally compare the input with the expectation /// Literally compare the input with the expectation
class StringExpectation extends ExpectationBase { class StringExpectation extends ExpectationBase {
StringExpectation(String expectation, String response) : super(expectation, response); StringExpectation(super.expectation, super.response);
@override @override
bool matches(String input) => input == expectation; bool matches(String input) => input == expectation;
} }
/// ///
class StanzaExpectation extends ExpectationBase { class StanzaExpectation extends ExpectationBase {
StanzaExpectation(String expectation, String response, {this.ignoreId = false, this.adjustId = false }) : super(expectation, response); StanzaExpectation(
super.expectation,
super.response, {
this.ignoreId = false,
this.adjustId = false,
});
final bool ignoreId; final bool ignoreId;
final bool adjustId; final bool adjustId;
@override @override
bool matches(String input) { bool matches(String input) {
final ex = XMLNode.fromString(expectation); final ex = XMLNode.fromString(expectation);
@ -52,7 +56,9 @@ class StanzaExpectation extends ExpectationBase {
List<ExpectationBase> buildAuthenticatedPlay(ConnectionSettings settings) { List<ExpectationBase> buildAuthenticatedPlay(ConnectionSettings settings) {
assert(settings.allowPlainAuth, 'SASL PLAIN must be allowed'); assert(settings.allowPlainAuth, 'SASL PLAIN must be allowed');
final plain = base64.encode(utf8.encode('\u0000${settings.jid.local}\u0000${settings.password}')); final plain = base64.encode(
utf8.encode('\u0000${settings.jid.local}\u0000${settings.password}'),
);
return [ return [
StringExpectation( StringExpectation(
"<stream:stream xmlns='jabber:client' version='1.0' xmlns:stream='http://etherx.jabber.org/streams' to='${settings.jid.domain}' xml:lang='en'>", "<stream:stream xmlns='jabber:client' version='1.0' xmlns:stream='http://etherx.jabber.org/streams' to='${settings.jid.domain}' xml:lang='en'>",
@ -68,14 +74,14 @@ List<ExpectationBase> buildAuthenticatedPlay(ConnectionSettings settings) {
<mechanism>PLAIN</mechanism> <mechanism>PLAIN</mechanism>
</mechanisms> </mechanisms>
</stream:features>''', </stream:features>''',
), ),
StringExpectation( StringExpectation(
"<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>$plain</auth>", "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>$plain</auth>",
'<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl" />' '<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl" />',
), ),
StringExpectation( StringExpectation(
"<stream:stream xmlns='jabber:client' version='1.0' xmlns:stream='http://etherx.jabber.org/streams' to='${settings.jid.domain}' xml:lang='en'>", "<stream:stream xmlns='jabber:client' version='1.0' xmlns:stream='http://etherx.jabber.org/streams' to='${settings.jid.domain}' xml:lang='en'>",
''' '''
<stream:stream <stream:stream
xmlns="jabber:client" xmlns="jabber:client"
version="1.0" version="1.0"
@ -88,30 +94,36 @@ List<ExpectationBase> buildAuthenticatedPlay(ConnectionSettings settings) {
</bind> </bind>
</stream:features> </stream:features>
''', ''',
), ),
StanzaExpectation( StanzaExpectation(
'<iq xmlns="jabber:client" type="set" id="a"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/></iq>', '<iq xmlns="jabber:client" type="set" id="a"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/></iq>',
'<iq xmlns="jabber:client" type="result" id="a"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><jid>${settings.jid.toBare()}/MU29eEZn</jid></bind></iq>', '<iq xmlns="jabber:client" type="result" id="a"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><jid>${settings.jid.toBare()}/MU29eEZn</jid></bind></iq>',
ignoreId: true, ignoreId: true,
), ),
StanzaExpectation( StanzaExpectation(
"<presence xmlns='jabber:client' from='${settings.jid.toBare()}/MU29eEZn'><show>chat</show></presence>", "<presence xmlns='jabber:client' from='${settings.jid.toBare()}/MU29eEZn'><show>chat</show></presence>",
'', '',
), ),
]; ];
} }
class StubTCPSocket extends BaseSocketWrapper { // Request -> Response(s) class StubTCPSocket extends BaseSocketWrapper {
// Request -> Response(s)
StubTCPSocket(this._play); StubTCPSocket(this._play);
StubTCPSocket.authenticated(ConnectionSettings settings, List<ExpectationBase> play) : _play = [ StubTCPSocket.authenticated(
...buildAuthenticatedPlay(settings), ConnectionSettings settings,
...play, List<ExpectationBase> play,
]; ) : _play = [
...buildAuthenticatedPlay(settings),
...play,
];
int _state = 0; int _state = 0;
final StreamController<String> _dataStream = StreamController<String>.broadcast(); final StreamController<String> _dataStream =
final StreamController<XmppSocketEvent> _eventStream = StreamController<XmppSocketEvent>.broadcast(); StreamController<String>.broadcast();
final StreamController<XmppSocketEvent> _eventStream =
StreamController<XmppSocketEvent>.broadcast();
final List<ExpectationBase> _play; final List<ExpectationBase> _play;
String? lastId; String? lastId;
@ -120,24 +132,26 @@ class StubTCPSocket extends BaseSocketWrapper { // Request -> Response(s)
@override @override
Future<bool> secure(String domain) async => true; Future<bool> secure(String domain) async => true;
@override @override
Future<bool> connect(String domain, { String? host, int? port }) async => true; Future<bool> connect(String domain, {String? host, int? port}) async => true;
@override @override
Stream<String> getDataStream() => _dataStream.stream.asBroadcastStream(); Stream<String> getDataStream() => _dataStream.stream.asBroadcastStream();
@override @override
Stream<XmppSocketEvent> getEventStream() => _eventStream.stream.asBroadcastStream(); Stream<XmppSocketEvent> getEventStream() =>
_eventStream.stream.asBroadcastStream();
/// Let the "connection" receive [data]. /// Let the "connection" receive [data].
void injectRawXml(String data) { void injectRawXml(String data) {
// ignore: avoid_print
print('<== $data'); print('<== $data');
_dataStream.add(data); _dataStream.add(data);
} }
@override @override
void write(Object? object, { String? redact }) { void write(Object? object, {String? redact}) {
var str = object as String; var str = object! as String;
// ignore: avoid_print // ignore: avoid_print
print('==> $str'); print('==> $str');
@ -148,7 +162,7 @@ class StubTCPSocket extends BaseSocketWrapper { // Request -> Response(s)
final expectation = _play[_state]; final expectation = _play[_state];
// TODO: Implement an XML matcher // TODO(Unknown): Implement an XML matcher
if (str.startsWith("<?xml version='1.0'?>")) { if (str.startsWith("<?xml version='1.0'?>")) {
str = str.substring(21); str = str.substring(21);
} }
@ -174,18 +188,19 @@ class StubTCPSocket extends BaseSocketWrapper { // Request -> Response(s)
if (expectation.adjustId) { if (expectation.adjustId) {
final outputNode = XMLNode.fromString(response); final outputNode = XMLNode.fromString(response);
outputNode.attributes['id'] = inputNode.attributes['id']!; outputNode.attributes['id'] = inputNode.attributes['id'];
response = outputNode.toXml(); response = outputNode.toXml();
} }
} }
print("<== $response"); // ignore: avoid_print
print('<== $response');
_dataStream.add(response); _dataStream.add(response);
} }
@override @override
void close() {} void close() {}
int getState() => _state; int getState() => _state;
void resetState() => _state = 0; void resetState() => _state = 0;
@ -194,4 +209,4 @@ class StubTCPSocket extends BaseSocketWrapper { // Request -> Response(s)
@override @override
bool managesKeepalives() => false; bool managesKeepalives() => false;
} }