Skip to content

Commit

Permalink
fix: fix tests
Browse files Browse the repository at this point in the history
Signed-off-by: Sebastian Becker <[email protected]>
  • Loading branch information
sbckr committed Oct 10, 2024
1 parent 1774bd6 commit 11fb192
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 120 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,12 @@
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.powermock</groupId>
Expand Down
211 changes: 109 additions & 102 deletions src/test/java/io/carbynestack/cli/login/LoginCommandTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,9 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({BrowserLauncher.class})
public class LoginCommandTest {

@Rule public final TemporaryConfiguration temporaryConfiguration = new TemporaryConfiguration();
Expand All @@ -51,130 +46,142 @@ public class LoginCommandTest {
private OIDCTokens oidcTokens;

@Before
public void configureMocks() throws Exception {
PowerMockito.mockStatic(BrowserLauncher.class);
public void configureMocks() {
oidcTokens = TokenUtils.createToken();
}

@Test
public void whenLogin_thenStoreHasBeenCreated() throws Exception {
when(browse(any())).thenReturn(Option.none());
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(new AuthorizationCode())).when(callbackServer).getAuthorizationCode();
try (MockedStatic<BrowserLauncher> ms = mockStatic(BrowserLauncher.class)) {
ms.when(() -> browse(any())).thenReturn(Option.none());
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(new AuthorizationCode())).when(callbackServer).getAuthorizationCode();

LoginCommand command =
spy(new LoginCommand(DEFAULT_CALLBACK_PORTS, (url, state) -> callbackServer));
doReturn(new OIDCTokenResponse(oidcTokens))
.when(command)
.sendTokenRequest(Mockito.any(), anyBoolean(), anyList());
LoginCommand command =
spy(new LoginCommand(DEFAULT_CALLBACK_PORTS, (url, state) -> callbackServer));
doReturn(new OIDCTokenResponse(oidcTokens))
.when(command)
.sendTokenRequest(Mockito.any(), anyBoolean(), anyList());

command.login();
Either<VcpTokenStoreError, VcpTokenStore> store = load(false);
assertThat("store has not been created", store.isRight());
for (VcpToken t : store.get().getTokens()) {
assertEquals(
"stored access token does not equal expected token",
oidcTokens.getAccessToken().getValue(),
t.getAccessToken());
command.login();
Either<VcpTokenStoreError, VcpTokenStore> store = load(false);
assertThat("store has not been created", store.isRight());
for (VcpToken t : store.get().getTokens()) {
assertEquals(
"stored access token does not equal expected token",
oidcTokens.getAccessToken().getValue(),
t.getAccessToken());
}
}
}

@Test
public void givenLaunchingBrowserFails_whenLogin_thenThrows() throws Exception {
when(browse(any())).thenReturn(Option.some(NOT_SUPPORTED));
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(RandomStringUtils.randomAlphanumeric(10)))
.when(callbackServer)
.getAuthorizationCode();
LoginCommand command = new LoginCommand(DEFAULT_CALLBACK_PORTS, (cfg, state) -> callbackServer);
try {
command.login();
fail("expected exception has not been thrown");
} catch (CsCliLoginException scle) {
assertEquals("unexpected error returned", NOT_SUPPORTED, scle.getAuthenticationError());
try (MockedStatic<BrowserLauncher> ms = mockStatic(BrowserLauncher.class)) {
ms.when(() -> browse(any())).thenReturn(Option.some(NOT_SUPPORTED));
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(RandomStringUtils.randomAlphanumeric(10)))
.when(callbackServer)
.getAuthorizationCode();
LoginCommand command =
new LoginCommand(DEFAULT_CALLBACK_PORTS, (cfg, state) -> callbackServer);
try {
command.login();
fail("expected exception has not been thrown");
} catch (CsCliLoginException scle) {
assertEquals("unexpected error returned", NOT_SUPPORTED, scle.getAuthenticationError());
}
}
}

@Test
public void givenPortIsInUse_whenLogin_thenSucceedOnNextPort() throws Exception {
when(browse(any())).thenReturn(Option.none());
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(new AuthorizationCode())).when(callbackServer).getAuthorizationCode();
AtomicInteger attempt = new AtomicInteger(0);
int rounds = 5;
LoginCommand command =
spy(
new LoginCommand(
DEFAULT_CALLBACK_PORTS,
(cfg, state) -> {
if (attempt.getAndAdd(1) < rounds) {
throw new RuntimeException(new BindException());
} else {
return callbackServer;
}
}));
doReturn(new OIDCTokenResponse(oidcTokens))
.when(command)
.sendTokenRequest(Mockito.any(), anyBoolean(), anyList());
try (MockedStatic<BrowserLauncher> ms = mockStatic(BrowserLauncher.class)) {
ms.when(() -> browse(any())).thenReturn(Option.none());
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(new AuthorizationCode())).when(callbackServer).getAuthorizationCode();
AtomicInteger attempt = new AtomicInteger(0);
int rounds = 5;
LoginCommand command =
spy(
new LoginCommand(
DEFAULT_CALLBACK_PORTS,
(cfg, state) -> {
if (attempt.getAndAdd(1) < rounds) {
throw new RuntimeException(new BindException());
} else {
return callbackServer;
}
}));
doReturn(new OIDCTokenResponse(oidcTokens))
.when(command)
.sendTokenRequest(Mockito.any(), anyBoolean(), anyList());

command.login();
assertEquals("not enough attempts detected", rounds + 2, attempt.get());
command.login();
assertEquals("not enough attempts detected", rounds + 2, attempt.get());
}
}

@Test
public void givenAllPortsAreInUse_whenLogin_thenThrow() throws Exception {
when(browse(any())).thenReturn(Option.none());
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(RandomStringUtils.randomAlphanumeric(10)))
.when(callbackServer)
.getAuthorizationCode();
int basePort = 32768;
Range<Integer> portRange = Range.between(basePort, basePort + 7);
AtomicInteger attempts = new AtomicInteger(0);
LoginCommand command =
new LoginCommand(
portRange,
(cfg, state) -> {
attempts.getAndIncrement();
throw new RuntimeException(new BindException());
});
try {
command.login();
fail("expected exception has not been thrown");
} catch (CsCliLoginException scle) {
assertEquals(
"unexpected error returned",
LoginCommandError.PORT_RANGE_EXHAUSTION,
scle.getAuthenticationError());
assertEquals("wrong number of attempts", RangeUtils.getLength(portRange), attempts.get());
try (MockedStatic<BrowserLauncher> ms = mockStatic(BrowserLauncher.class)) {
ms.when(() -> browse(any())).thenReturn(Option.none());
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(RandomStringUtils.randomAlphanumeric(10)))
.when(callbackServer)
.getAuthorizationCode();
int basePort = 32768;
Range<Integer> portRange = Range.between(basePort, basePort + 7);
AtomicInteger attempts = new AtomicInteger(0);
LoginCommand command =
new LoginCommand(
portRange,
(cfg, state) -> {
attempts.getAndIncrement();
throw new RuntimeException(new BindException());
});
try {
command.login();
fail("expected exception has not been thrown");
} catch (CsCliLoginException scle) {
assertEquals(
"unexpected error returned",
LoginCommandError.PORT_RANGE_EXHAUSTION,
scle.getAuthenticationError());
assertEquals("wrong number of attempts", RangeUtils.getLength(portRange), attempts.get());
}
}
}

@Test
public void givenRuntimeExceptionDuringCallbackServerCreation_whenLogin_thenThrow()
throws Exception {
when(browse(any())).thenReturn(Option.none());
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(RandomStringUtils.randomAlphanumeric(10)))
.when(callbackServer)
.getAuthorizationCode();
LoginCommand command =
new LoginCommand(
DEFAULT_CALLBACK_PORTS,
(cfg, state) -> {
throw new RuntimeException(new SocketException());
});
try {
command.login();
fail("expected exception has not been thrown");
} catch (CsCliLoginException scle) {
assertEquals(
"unexpected error returned", LoginCommandError.UNEXPECTED, scle.getAuthenticationError());
try (MockedStatic<BrowserLauncher> ms = mockStatic(BrowserLauncher.class)) {
ms.when(() -> browse(any())).thenReturn(Option.none());
OAuth2AuthenticationCodeCallbackHttpServer callbackServer =
mock(OAuth2AuthenticationCodeCallbackHttpServer.class);
doReturn(Either.right(RandomStringUtils.randomAlphanumeric(10)))
.when(callbackServer)
.getAuthorizationCode();
LoginCommand command =
new LoginCommand(
DEFAULT_CALLBACK_PORTS,
(cfg, state) -> {
throw new RuntimeException(new SocketException());
});
try {
command.login();
fail("expected exception has not been thrown");
} catch (CsCliLoginException scle) {
assertEquals(
"unexpected error returned",
LoginCommandError.UNEXPECTED,
scle.getAuthenticationError());
}
}
}
}
24 changes: 6 additions & 18 deletions src/test/java/io/carbynestack/cli/login/VcpTokenStoreTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,11 @@
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Configuration.class, VcpTokenStore.class})
public class VcpTokenStoreTest {

@Rule TemporaryConfiguration temporaryConfiguration = new TemporaryConfiguration();
@Rule public TemporaryConfiguration temporaryConfiguration = new TemporaryConfiguration();
private OIDCTokens oidcTokens;

private static VcpTokenStore createStore(boolean expired) throws Exception {
Expand Down Expand Up @@ -97,8 +91,6 @@ public void givenWriterFails_whenPersist_thenFails() throws Exception {

@Test
public void givenValidTokens_whenRefresh_thenDoesNothing() throws Exception {
PowerMockito.mockStatic(Configuration.class);
when(Configuration.getInstance()).thenReturn(ConfigurationUtil.getConfiguration());
VcpTokenStore store = createStore(false).toBuilder().build();
assertThat(
"tokens in store are expired", store.getTokens().stream().noneMatch(VcpToken::isExpired));
Expand All @@ -107,18 +99,16 @@ public void givenValidTokens_whenRefresh_thenDoesNothing() throws Exception {

@Test
public void givenExpiredTokens_whenRefresh_thenRefreshesTokens() throws Exception {
PowerMockito.mockStatic(Configuration.class);
when(Configuration.getInstance()).thenReturn(ConfigurationUtil.getConfiguration());

VcpTokenStore store = PowerMockito.spy(createStore(true).toBuilder().build());
VcpTokenStore store = createStore(true).toBuilder().build();
VcpTokenStore spyStore = spy(store);
doReturn(new OIDCTokenResponse(oidcTokens.toOIDCTokens()))
.when(store)
.when(spyStore)
.sendRefreshToken(Mockito.any(), Mockito.any(), anyBoolean(), anyList());

assertThat(
"tokens in store are not expired",
store.getTokens().stream().allMatch(VcpToken::isExpired));
Either<VcpTokenStoreError, VcpTokenStore> refreshed = store.refresh();
spyStore.getTokens().stream().allMatch(VcpToken::isExpired));
Either<VcpTokenStoreError, VcpTokenStore> refreshed = spyStore.refresh();
assertThat("refresh failed", refreshed.isRight());
assertThat(
"tokens in store are expired after refresh",
Expand All @@ -127,8 +117,6 @@ public void givenExpiredTokens_whenRefresh_thenRefreshesTokens() throws Exceptio

@Test
public void givenExpiredTokensAndFailingProvider_whenRefresh_thenRefreshFails() throws Exception {
PowerMockito.mockStatic(Configuration.class);
when(Configuration.getInstance()).thenReturn(ConfigurationUtil.getConfiguration());
VcpTokenStore store = createStore(true).toBuilder().build();
Either<VcpTokenStoreError, VcpTokenStore> refreshed = store.refresh();
assertThat("refresh succeeded despite failing provider", refreshed.isLeft());
Expand Down

0 comments on commit 11fb192

Please sign in to comment.