Skip to content

Commit

Permalink
Add unit tests for socket
Browse files Browse the repository at this point in the history
  • Loading branch information
brianegan committed Mar 6, 2024
1 parent 690d30c commit 28ac05e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/src/socket.dart
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ class PhoenixSocket {
}
} catch (err, stackTrace) {
_logger.severe('Raised Exception', err, stackTrace);
print('||| CONNECT EXCEPTION: $err');

_ws = null;
_socketState = SocketState.closed;
Expand Down
53 changes: 53 additions & 0 deletions test/socket_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import 'dart:async';
import 'dart:convert';

import 'package:mockito/mockito.dart';
import 'package:phoenix_socket/phoenix_socket.dart';
import 'package:rxdart/rxdart.dart';
import 'package:test/test.dart';

import 'mocks.dart';

void main() {
test('socket connect retries on unexpected error', () async {
final sink = MockWebSocketSink();
final websocket = MockWebSocketChannel();
final phoenixSocket = PhoenixSocket(
'endpoint',
webSocketChannelFactory: (_) => websocket,
);
int invocations = 0;
final excpetions = ['E', PhoenixException()];

when(websocket.sink).thenReturn(sink);

when(websocket.stream).thenAnswer((_) {
if (invocations < 2) {
// Return a never stream to keep the socket open on the first two
// attempts. If it is an empty Stream the socket will close immediately.
return NeverStream();
} else {
// Return a proper message on the third attempt which allows the socket
// to connect.
final controller = StreamController<String>()
..add(jsonEncode(Message.heartbeat('$invocations').encode()));
return controller.stream;
}
});

// Throw an error adding data to the sink on the first two attempts.
// On the third attempt, the sink add should work as expected.
when(sink.add(any)).thenAnswer((_) {
if (invocations < 2) {
throw excpetions[invocations++];
}
});

// Connect to the socket
await phoenixSocket.connect();
expect(phoenixSocket.isConnected, isTrue);

// Expect the first two unexpected failures to be retried
verify(sink.add(any)).called(3);
});
}

0 comments on commit 28ac05e

Please sign in to comment.