Skip to content

Commit

Permalink
Refactored ably-java tests, removed unnecessary callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
sacOO7 committed Feb 4, 2024
1 parent e791f8f commit 1291486
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 68 deletions.
24 changes: 16 additions & 8 deletions lib/src/test/java/io/ably/lib/test/common/Helpers.java
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ public synchronized ErrorInfo waitFor(ConnectionState state) {
while (currentState() != state) {
try {
wait();
} catch (InterruptedException e) {
} catch (InterruptedException ignored) {
}
}
Log.d(TAG, "waitFor done: state=" + targetStateName + ")");
Expand All @@ -493,8 +493,8 @@ public synchronized void waitFor(ConnectionState state, int count) {
Log.d(TAG, "waitFor(state=" + state.getConnectionEvent().name() + ", count=" + count + ")");

while(getStateCount(state) < count)
try { wait(); } catch(InterruptedException e) {}
Log.d(TAG, "waitFor done: state=" + latestChange.current.getConnectionEvent().name() + ", count=" + getStateCount(state) + ")");
try { wait(); } catch(InterruptedException ignored) {}
Log.d(TAG, "waitFor done: state=" + lastStateChange().current.getConnectionEvent().name() + ", count=" + getStateCount(state) + ")");
}

/**
Expand All @@ -511,7 +511,7 @@ public synchronized boolean waitFor(ConnectionState state, int count, long time)
long remaining = time;
while(getStateCount(state) < count && remaining > 0) {
Log.d(TAG, "waitFor(state=" + state.getConnectionEvent().name() + ", waiting for=" + remaining + ")");
try { wait(remaining); } catch(InterruptedException e) {}
try { wait(remaining); } catch(InterruptedException ignored) {}
remaining = targetTime - System.currentTimeMillis();
}
int stateCount = getStateCount(state);
Expand Down Expand Up @@ -552,7 +552,7 @@ public synchronized void reset() {
@Override
public void onConnectionStateChanged(ConnectionStateListener.ConnectionStateChange state) {
synchronized(this) {
latestChange = state;
stateChanges.add(state);
reason = state.reason;
Counter counter = stateCounts.get(state.current); if(counter == null) stateCounts.put(state.current, (counter = new Counter()));
counter.incr();
Expand All @@ -573,15 +573,23 @@ private synchronized int getStateCount(ConnectionState state) {
}

private synchronized ConnectionState currentState() {
return latestChange == null ? connection.state : latestChange.current;
ConnectionStateChange stateChange = lastStateChange();
return stateChange == null ? connection.state : stateChange.current;
}

public synchronized ConnectionStateChange lastStateChange() {
if (stateChanges.size() == 0) {
return null;
}
return stateChanges.get(stateChanges.size() -1);
}

/**
* Internal
*/
private Connection connection;
private final Connection connection;
private ErrorInfo reason;
private ConnectionStateChange latestChange;
private final List<ConnectionStateChange> stateChanges = new ArrayList<>();
private Map<ConnectionState, Counter> stateCounts;
private static final String TAG = ConnectionWaiter.class.getName();
}
Expand Down
47 changes: 23 additions & 24 deletions lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ public void realtime_connection_with_auth_url_in_query_string_connects() {
* Spec: RSA4d, RSA4d1
*/
@Test
public void auth_client_fails_authorize_server_forbidden() {
public void auth_client_fails() {
AblyRealtime ablyRealtime = null;
try {
/* init ably for token */
ClientOptions optsForToken = createOptions(testVars.keys[0].keyStr);
Expand All @@ -163,25 +164,13 @@ public void auth_client_fails_authorize_server_forbidden() {
opts.authUrl = "https://echo.ably.io/respondwith";
opts.authParams = new Param[]{ new Param("status", 403)};

final AblyRealtime ablyRealtime = new AblyRealtime(opts);
ablyRealtime = new AblyRealtime(opts);
ablyRealtime.connection.connect();

/* wait for connected state */
Helpers.ConnectionWaiter connectionWaiter = new Helpers.ConnectionWaiter(ablyRealtime.connection);
connectionWaiter.waitFor(ConnectionState.connected);

/* create listener for ConnectionEvent.failed */
ablyRealtime.connection.once(ConnectionEvent.failed, new ConnectionStateListener() {
@Override
public void onConnectionStateChanged(ConnectionStateChange stateChange) {
/* assert that state changes correctly */
assertEquals(ConnectionState.connected, stateChange.previous);
assertEquals(80019, stateChange.reason.code);
assertEquals(80019, ablyRealtime.connection.reason.code);
assertEquals(403, ablyRealtime.connection.reason.statusCode);
}
});

try {
opts.tokenDetails = null;
/* try to authorize */
Expand All @@ -194,11 +183,21 @@ public void onConnectionStateChanged(ConnectionStateChange stateChange) {

/* wait for failed state */
connectionWaiter.waitFor(ConnectionState.failed);
ConnectionStateListener.ConnectionStateChange lastStateChange = connectionWaiter.lastStateChange();
assertEquals(ConnectionState.failed, lastStateChange.current);
assertEquals(80019, lastStateChange.reason.code);
assertEquals(403, lastStateChange.reason.statusCode);

assertEquals("Verify connected state has failed", ConnectionState.failed, ablyRealtime.connection.state);
assertEquals("Check correct cause error code", 403, ablyRealtime.connection.reason.statusCode);
assertEquals(80019, ablyRealtime.connection.reason.code);

} catch (AblyException e) {
e.printStackTrace();
fail();
} finally {
assert ablyRealtime != null;
ablyRealtime.close();
}
}

Expand Down Expand Up @@ -350,7 +349,7 @@ public void auth_client_match_token_null_clientId() {
assertEquals("Verify connected state is reached", ConnectionState.connected, ablyRealtime.connection.state);

/* check expected clientId */
assertEquals("Auth#clientId is expected to be null", null, ablyRealtime.auth.clientId);
assertNull("Auth#clientId is expected to be null", ablyRealtime.auth.clientId);

ablyRealtime.close();
} catch (AblyException e) {
Expand Down Expand Up @@ -383,7 +382,7 @@ public void auth_clientid_null_before_auth() {
AblyRealtime ablyRealtime = new AblyRealtime(opts);

/* check expected clientId */
assertEquals("Auth#clientId is expected to be null", null, ablyRealtime.auth.clientId);
assertNull("Auth#clientId is expected to be null", ablyRealtime.auth.clientId);

/* wait for connected state */
ablyRealtime.connection.connect();
Expand Down Expand Up @@ -688,7 +687,7 @@ public void auth_client_match_tokendetails_clientId_fail() {
ClientOptions opts = createOptions();
opts.clientId = "options clientId";
opts.tokenDetails = tokenDetails;
AblyRealtime ablyRealtime = new AblyRealtime(opts);
new AblyRealtime(opts);
} catch (AblyException e) {
assertEquals("Verify error code indicates clientId mismatch", e.errorInfo.code, 40101);
}
Expand Down Expand Up @@ -773,7 +772,7 @@ public void auth_clientid_publish_implicit() {

/* Get sent message */
Message messagePublished = protocolListener.sentMessages.get(0).messages[0];
assertEquals("Sent message does not contain clientId", messagePublished.clientId, null);
assertNull("Sent message does not contain clientId", messagePublished.clientId);

/* wait until message received on transport */
protocolListener.waitForRecv(1);
Expand Down Expand Up @@ -819,7 +818,7 @@ public void auth_clientid_publish_implicit() {
channel.publish(messageToPublish, pubComplete.add());
pubComplete.waitFor();
assertTrue("Verify publish callback called on completion", pubComplete.pending.isEmpty());
assertTrue("Verify publish callback returns an error", pubComplete.errors.size() == 1);
assertEquals("Verify publish callback returns an error", 1, pubComplete.errors.size());
assertEquals("Verify publish callback error has expected error code", pubComplete.errors.iterator().next().code, 40012);

/* verify no message sent or received on transport */
Expand All @@ -838,7 +837,7 @@ public void auth_clientid_publish_implicit() {

/* Get sent message */
messagePublished = protocolListener.sentMessages.get(0).messages[0];
assertEquals("Sent message does not contain clientId", messagePublished.clientId, null);
assertNull("Sent message does not contain clientId", messagePublished.clientId);

/* wait until message received on transport */
protocolListener.waitForRecv(1);
Expand Down Expand Up @@ -927,7 +926,7 @@ public void auth_clientid_publish_explicit_before_identified() {

/* Get sent message */
messagePublished = protocolListener.sentMessages.get(0).messages[0];
assertEquals("Sent message does not contain clientId", messagePublished.clientId, null);
assertNull("Sent message does not contain clientId", messagePublished.clientId);

/* wait until message received on transport */
protocolListener.waitForRecv(1);
Expand Down Expand Up @@ -996,7 +995,7 @@ public Object getTokenRequest(Auth.TokenParams params) {
ably.connect();
try {
opts.wait();
} catch(InterruptedException ie) {}
} catch(InterruptedException ignored) {}
ably.auth.renew();
}

Expand Down Expand Up @@ -1066,7 +1065,7 @@ public Object getTokenRequest(Auth.TokenParams params) {
ably.connect();
try {
opts.wait();
} catch(InterruptedException ie) {}
} catch(InterruptedException ignored) {}

ably.auth.renewAuth((success, tokenDetails1, errorInfo) -> {
//Ignore completion handling
Expand Down Expand Up @@ -1183,7 +1182,7 @@ public void auth_expired_token_expire_before_connect_renew() {
assertNotNull("Expected token value", tokenDetails.token);

/* allow to expire */
try { Thread.sleep(200L); } catch(InterruptedException ie) {}
try { Thread.sleep(200L); } catch(InterruptedException ignored) {}

/* create Ably realtime instance with token and authCallback */
ClientOptions opts = createOptions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ public void channelhistory_wait_b() {
/* wait for the history to be persisted */
try {
Thread.sleep(16000);
} catch(InterruptedException ie) {}
} catch(InterruptedException ignored) {}

/* get the history for this channel */
PaginatedResult<Message> messages = channel.history(null);
Expand Down Expand Up @@ -455,7 +455,7 @@ public void channelhistory_mixed_b() {
/* wait for the history to be persisted */
try {
Thread.sleep(16000);
} catch(InterruptedException ie) {}
} catch(InterruptedException ignored) {}

/* publish to the channel */
msgComplete = new CompletionWaiter();
Expand Down Expand Up @@ -517,7 +517,7 @@ public void channelhistory_mixed_f() {
/* wait for the history to be persisted */
try {
Thread.sleep(16000);
} catch(InterruptedException ie) {}
} catch(InterruptedException ignored) {}

/* publish to the channel */
msgComplete = new CompletionWaiter();
Expand Down Expand Up @@ -654,7 +654,6 @@ public void channelhistory_limit_b() {
} catch (AblyException e) {
e.printStackTrace();
fail("channelhistory_limit_b: Unexpected exception");
return;
} finally {
if(ably != null)
ably.close();
Expand Down Expand Up @@ -720,10 +719,7 @@ public void channelhistory_time_f() {
for(int i = 20; i < 40; i++)
expectedMessageHistory[i - 20] = messageContents.get("history" + i);
Assert.assertArrayEquals("Expect messages in forward order", messages.items(), expectedMessageHistory);
} catch (AblyException e) {
e.printStackTrace();
fail("channelhistory_time_f: Unexpected exception");
} catch (InterruptedException e) {
} catch (AblyException | InterruptedException e) {
e.printStackTrace();
fail("channelhistory_time_f: Unexpected exception");
} finally {
Expand Down Expand Up @@ -791,10 +787,7 @@ public void channelhistory_time_b() {
for(int i = 20; i < 40; i++)
expectedMessageHistory[i - 20] = messageContents.get("history" + (59 - i));
Assert.assertArrayEquals("Expect messages in backwards order", messages.items(), expectedMessageHistory);
} catch (AblyException e) {
e.printStackTrace();
fail("channelhistory_time_b: Unexpected exception");
} catch (InterruptedException e) {
} catch (AblyException | InterruptedException e) {
e.printStackTrace();
fail("channelhistory_time_b: Unexpected exception");
} finally {
Expand Down Expand Up @@ -1205,7 +1198,7 @@ public void run() {
/* wait 2 seconds */
try {
Thread.sleep(2000L);
} catch(InterruptedException ie) {}
} catch(InterruptedException ignored) {}

/* subscribe; this will trigger the attach */
MessageWaiter messageWaiter = new MessageWaiter(rxChannel);
Expand Down
37 changes: 14 additions & 23 deletions lib/src/test/java/io/ably/lib/test/realtime/RealtimeResumeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -583,19 +583,16 @@ public void resume_publish_queue() {
final Channel senderChannel = sender.channels.get(channelName);
senderChannel.attach();
(new ChannelWaiter(senderChannel)).waitFor(ChannelState.attached);
assertEquals(
"The sender's channel should be attached",
senderChannel.state, ChannelState.attached
);
assertEquals("The sender's channel should be attached",
senderChannel.state, ChannelState.attached);

/* create and attach channel to recv on */
final Channel receiverChannel = receiver.channels.get(channelName);
receiverChannel.attach();
(new ChannelWaiter(receiverChannel)).waitFor(ChannelState.attached);
assertEquals(
"The receiver's channel should be attached",
receiverChannel.state, ChannelState.attached
);
assertEquals("The receiver's channel should be attached",
receiverChannel.state, ChannelState.attached);

/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(receiverChannel);

Expand All @@ -612,10 +609,8 @@ public void resume_publish_queue() {

/* wait for the subscription callback to be called */
messageWaiter.waitFor(messageCount);
assertEquals(
"Did not receive the entire first round of messages",
messageWaiter.receivedMessages.size(), messageCount
);
assertEquals("Did not receive the entire first round of messages",
messageWaiter.receivedMessages.size(), messageCount);
messageWaiter.reset();

/* disconnect the sender, without closing;
Expand All @@ -641,7 +636,6 @@ public void resume_publish_queue() {
sender.connection.connect();
(new ConnectionWaiter(sender.connection)).waitFor(ConnectionState.connected);


/* wait for the publish callback to be called.*/
errors = msgComplete2.waitFor();
assertEquals("Second round of messages (queued) has errors", 0, errors.length);
Expand All @@ -655,10 +649,8 @@ public void resume_publish_queue() {
received.size(), messageCount
);
for(int i=0; i<received.size(); i++) {
assertEquals(
"Received unexpected queued message",
received.get(i).name, "queued_message_" + i
);
assertEquals("Received unexpected queued message", received.get(i).name,
"queued_message_" + i);
}
} catch (AblyException e) {
e.printStackTrace();
Expand Down Expand Up @@ -694,10 +686,8 @@ public void resume_publish_resend_pending_messages_when_resume_is_successful() {
final Channel senderChannel = sender.channels.get(channelName);
senderChannel.attach();
(new ChannelWaiter(senderChannel)).waitFor(ChannelState.attached);
assertEquals(
"The sender's channel should be attached",
senderChannel.state, ChannelState.attached
);
assertEquals("The sender's channel should be attached",
senderChannel.state, ChannelState.attached);

MockWebsocketFactory.MockWebsocketTransport transport = mockWebsocketFactory.getCreatedTransport();

Expand All @@ -713,7 +703,9 @@ public void resume_publish_resend_pending_messages_when_resume_is_successful() {
assertEquals("First completion has errors", 0, errors.length);

//assert that messages sent till now are sent with correct size and serials
assertEquals("First round of messages has incorrect size", 3, transport.getPublishedMessages().size());
assertEquals("First round of messages has incorrect size", 3,
transport.getPublishedMessages().size());

for (int i = 0; i < transport.getPublishedMessages().size(); i++) {
ProtocolMessage protocolMessage = transport.getPublishedMessages().get(i);
assertEquals("Sent serial incorrect", Long.valueOf(i), protocolMessage.msgSerial);
Expand All @@ -724,7 +716,6 @@ public void resume_publish_resend_pending_messages_when_resume_is_successful() {

//block ack/nack messages to simulate pending message
//note that this will only block ack/nack messages received by connection manager

mockWebsocketFactory.blockReceiveProcessing(message -> message.action == ProtocolMessage.Action.ack ||
message.action == ProtocolMessage.Action.nack);

Expand Down

0 comments on commit 1291486

Please sign in to comment.