Skip to content

Commit

Permalink
Added Configuration Tests and added jacoco.
Browse files Browse the repository at this point in the history
Applied Spotless.
Removed RequestBuilder.
  • Loading branch information
SanHalacogluImproving committed Jan 11, 2024
1 parent 4b83ad4 commit 3761294
Show file tree
Hide file tree
Showing 11 changed files with 188 additions and 90 deletions.
12 changes: 12 additions & 0 deletions java/client/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import java.nio.file.Paths

plugins {
id 'java-library'
id 'jacoco'
}

repositories {
Expand Down Expand Up @@ -103,4 +104,15 @@ tasks.withType(Test) {
showStandardStreams true
}
jvmArgs "-Djava.library.path=${projectDir}/../target/release:${projectDir}/../target/debug"
finalizedBy jacocoTestReport, jacocoTestCoverageVerification
}

jacocoTestReport {
afterEvaluate {
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: ['**/connection_request/**', '**/response/**', '**/redis_request/**'])
}))
}
}


Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@
* failures. The time between attempts grows exponentially, to the formula <code>rand(0 ... factor *
* (exponentBase ^ N))</code>, where <code>N</code> is the number of failed attempts.
*
* Once the maximum value is reached,
* that will remain the time between retry attempts until a reconnect attempt is successful. The
* client will attempt to reconnect indefinitely.
* <p>Once the maximum value is reached, that will remain the time between retry attempts until a
* reconnect attempt is successful. The client will attempt to reconnect indefinitely.
*/
@Getter
@Builder
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ public abstract class BaseClientConfiguration {
/**
* True if communication with the cluster should use Transport Level Security.
*
* <p> If the server/cluster requires TLS, not setting this will cause the connection attempt to fail.
* <p>If the server/cluster requires TLS, not setting this will cause the connection attempt to
* fail.
*
* <p>If the server/cluster doesn't require TLS, setting this will also cause the connection attempt to fail.
* <p>If the server/cluster doesn't require TLS, setting this will also cause the connection
* attempt to fail.
*/
@Builder.Default private final boolean useTLS = false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,23 @@ public ChannelHandler(CallbackDispatcher callbackDispatcher, String socketPath)
Platform.getClientUdsNettyChannelType(),
new ProtobufSocketChannelInitializer(callbackDispatcher),
new DomainSocketAddress(socketPath),
callbackDispatcher
);
callbackDispatcher);
}

public ChannelHandler(EventLoopGroup eventLoopGroup,
Class<? extends DomainSocketChannel> domainSocketChannelClass,
ChannelInitializer<UnixChannel> channelInitializer,
DomainSocketAddress domainSocketAddress,
CallbackDispatcher callbackDispatcher) {
channel = new Bootstrap()
.group(eventLoopGroup)
.channel(domainSocketChannelClass)
.handler(channelInitializer)
.connect(domainSocketAddress)
// TODO call here .sync() if needed or remove this comment
.channel();
public ChannelHandler(
EventLoopGroup eventLoopGroup,
Class<? extends DomainSocketChannel> domainSocketChannelClass,
ChannelInitializer<UnixChannel> channelInitializer,
DomainSocketAddress domainSocketAddress,
CallbackDispatcher callbackDispatcher) {
channel =
new Bootstrap()
.group(eventLoopGroup)
.channel(domainSocketChannelClass)
.handler(channelInitializer)
.connect(domainSocketAddress)
// TODO call here .sync() if needed or remove this comment
.channel();
this.callbackDispatcher = callbackDispatcher;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ public class ReadHandler extends ChannelInboundHandlerAdapter {

/** Submit responses from glide to an instance {@link CallbackDispatcher} to handle them. */
@Override
public void channelRead(@NonNull ChannelHandlerContext ctx, @NonNull Object msg) throws RuntimeException {
public void channelRead(@NonNull ChannelHandlerContext ctx, @NonNull Object msg)
throws RuntimeException {
if (msg instanceof Response) {
Response response = (Response) msg;
callbackDispatcher.completeRequest(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,11 @@ private ConnectionRequest.Builder setupConnectionRequestBuilderBaseConfiguration
}

connectionRequestBuilder
.setTlsMode(
configuration.isUseTLS()
? TlsMode.SecureTls
: TlsMode.NoTls)
.setTlsMode(configuration.isUseTLS() ? TlsMode.SecureTls : TlsMode.NoTls)
.setReadFrom(mapReadFromEnum(configuration.getReadFrom()));

if (configuration.getCredentials() != null) {
AuthenticationInfo.Builder
authenticationInfoBuilder = AuthenticationInfo.newBuilder();
AuthenticationInfo.Builder authenticationInfoBuilder = AuthenticationInfo.newBuilder();
if (configuration.getCredentials().getUsername() != null) {
authenticationInfoBuilder.setUsername(configuration.getCredentials().getUsername());
}
Expand Down
54 changes: 0 additions & 54 deletions java/client/src/main/java/glide/models/RequestBuilder.java

This file was deleted.

138 changes: 138 additions & 0 deletions java/client/src/test/java/glide/api/ConfigurationTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package glide.api;

import static glide.api.models.configuration.NodeAddress.DEFAULT_HOST;
import static glide.api.models.configuration.NodeAddress.DEFAULT_PORT;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;

import glide.api.models.configuration.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;

public class ConfigurationTest {
private static String HOST = "aws.com";
private static int PORT = 9999;

private static String USERNAME = "JohnDoe";
private static String PASSWORD = "Password1";

private static int NUM_OF_RETRIES = 5;
private static int FACTOR = 10;
private static int EXPONENT_BASE = 50;

private static int DATABASE_ID = 1;

private static int REQUEST_TIMEOUT = 3;

@Test
public void NodeAddress_DefaultConfig() {
NodeAddress nodeAddress = NodeAddress.builder().build();

assertEquals(DEFAULT_HOST, nodeAddress.getHost());
assertEquals(DEFAULT_PORT, nodeAddress.getPort());
}

@Test
public void NodeAddress_CustomConfig() {
NodeAddress nodeAddress = NodeAddress.builder().host(HOST).port(PORT).build();

assertEquals(HOST, nodeAddress.getHost());
assertEquals(PORT, nodeAddress.getPort());
}

@Test
public void BackoffStrategy_CustomConfig() {
BackoffStrategy backoffStrategy =
BackoffStrategy.builder()
.numOfRetries(NUM_OF_RETRIES)
.factor(FACTOR)
.exponentBase(EXPONENT_BASE)
.build();

assertEquals(NUM_OF_RETRIES, backoffStrategy.getNumOfRetries());
assertEquals(FACTOR, backoffStrategy.getFactor());
assertEquals(EXPONENT_BASE, backoffStrategy.getExponentBase());
}

@Test
public void RedisCredentials_CustomConfig() {
RedisCredentials redisCredentials =
RedisCredentials.builder().password(PASSWORD).username(USERNAME).build();

assertEquals(PASSWORD, redisCredentials.getPassword());
assertEquals(USERNAME, redisCredentials.getUsername());
}

@Test
public void RedisClientConfiguration_DefaultConfig() {
RedisClientConfiguration redisClientConfiguration = RedisClientConfiguration.builder().build();

assertEquals(new ArrayList<NodeAddress>(), redisClientConfiguration.getAddresses());
assertFalse(redisClientConfiguration.isUseTLS());
assertEquals(ReadFrom.PRIMARY, redisClientConfiguration.getReadFrom());
assertNull(redisClientConfiguration.getCredentials());
assertNull(redisClientConfiguration.getRequestTimeout());
assertNull(redisClientConfiguration.getDatabaseId());
assertNull(redisClientConfiguration.getReconnectStrategy());
}

@Test
public void RedisClientConfiguration_CustomConfig() {
RedisClientConfiguration redisClientConfiguration =
RedisClientConfiguration.builder()
.address(NodeAddress.builder().host(HOST).port(PORT).build())
.address(NodeAddress.builder().host(DEFAULT_HOST).port(DEFAULT_PORT).build())
.useTLS(true)
.readFrom(ReadFrom.PREFER_REPLICA)
.credentials(RedisCredentials.builder().username(USERNAME).password(PASSWORD).build())
.requestTimeout(REQUEST_TIMEOUT)
.reconnectStrategy(
BackoffStrategy.builder()
.numOfRetries(NUM_OF_RETRIES)
.exponentBase(EXPONENT_BASE)
.factor(FACTOR)
.build())
.databaseId(DATABASE_ID)
.build();

List<NodeAddress> expectedAddresses = new ArrayList<>();
NodeAddress address1 = NodeAddress.builder().host(HOST).port(PORT).build();
NodeAddress address2 = NodeAddress.builder().host(DEFAULT_HOST).port(DEFAULT_PORT).build();
expectedAddresses.add(address1);
expectedAddresses.add(address2);

List<NodeAddress> actualAddresses = redisClientConfiguration.getAddresses();
assertEquals(
expectedAddresses.size(), actualAddresses.size(), "Lists should be of the same size");
for (int i = 0; i < actualAddresses.size(); i++) {
NodeAddress actualNodeAddress = actualAddresses.get(i);
NodeAddress expectedNodeAddress = expectedAddresses.get(i);
assertAll(
"Object fields should match",
() -> assertEquals(expectedNodeAddress.getHost(), actualNodeAddress.getHost()),
() -> assertEquals(expectedNodeAddress.getPort(), actualNodeAddress.getPort()));
}
assertTrue(redisClientConfiguration.isUseTLS());
assertEquals(ReadFrom.PREFER_REPLICA, redisClientConfiguration.getReadFrom());
assertEquals(PASSWORD, redisClientConfiguration.getCredentials().getPassword());
assertEquals(USERNAME, redisClientConfiguration.getCredentials().getUsername());
assertEquals(REQUEST_TIMEOUT, redisClientConfiguration.getRequestTimeout());
assertEquals(NUM_OF_RETRIES, redisClientConfiguration.getReconnectStrategy().getNumOfRetries());
assertEquals(FACTOR, redisClientConfiguration.getReconnectStrategy().getFactor());
assertEquals(EXPONENT_BASE, redisClientConfiguration.getReconnectStrategy().getExponentBase());
assertEquals(DATABASE_ID, redisClientConfiguration.getDatabaseId());
}

@Test
public void RedisClusterClientConfiguration_DefaultConfig() {
RedisClusterClientConfiguration redisClusterClientConfiguration =
RedisClusterClientConfiguration.builder().build();

assertEquals(new ArrayList<NodeAddress>(), redisClusterClientConfiguration.getAddresses());
assertFalse(redisClusterClientConfiguration.isUseTLS());
assertEquals(ReadFrom.PRIMARY, redisClusterClientConfiguration.getReadFrom());
assertNull(redisClusterClientConfiguration.getCredentials());
assertNull(redisClusterClientConfiguration.getRequestTimeout());
}
}
21 changes: 12 additions & 9 deletions java/client/src/test/java/glide/handlers/ReadHandlerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ public void teardown() {

@Test
public void readHandlerRead_testInboundProtobufMessages() {
ResponseOuterClass.Response msg = ResponseOuterClass.Response.newBuilder()
.setConstantResponse(ResponseOuterClass.ConstantResponse.OK)
.build();
ResponseOuterClass.Response msg =
ResponseOuterClass.Response.newBuilder()
.setConstantResponse(ResponseOuterClass.ConstantResponse.OK)
.build();

assertTrue(embeddedChannel.writeInbound(msg, msg, msg));
assertTrue(embeddedChannel.finish());
Expand All @@ -51,19 +52,21 @@ public void readHandlerRead_testInboundProtobufMessages_invalidMessage() {

String invalidMsg = "Invalid";

Exception e = assertThrows(Exception.class, () -> embeddedChannel.writeInbound(invalidMsg, invalidMsg, invalidMsg));
Exception e =
assertThrows(
Exception.class,
() -> embeddedChannel.writeInbound(invalidMsg, invalidMsg, invalidMsg));
assertEquals("Unexpected message in socket", e.getMessage());

verify(dispatcher, times(0)).completeRequest(any());

ResponseOuterClass.Response msg = ResponseOuterClass.Response.newBuilder()
.setConstantResponse(ResponseOuterClass.ConstantResponse.OK)
.build();
ResponseOuterClass.Response msg =
ResponseOuterClass.Response.newBuilder()
.setConstantResponse(ResponseOuterClass.ConstantResponse.OK)
.build();
assertTrue(embeddedChannel.writeInbound(msg));
assertTrue(embeddedChannel.finish());

verify(dispatcher, times(1)).completeRequest(msg);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,6 @@ public void CheckRedisResponse_ClosingError_throwsRuntimeException() {
assertTrue(exception.getCause() instanceof RuntimeException);
}


@SneakyThrows
@Test
public void CloseConnection_closesChannels() {
Expand Down
1 change: 1 addition & 0 deletions java/lombok.config
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lombok.addLombokGeneratedAnnotation = true

0 comments on commit 3761294

Please sign in to comment.