### Question:
LoggedInUsers { public synchronized Optional<String> userTokenFor(String username, String password) throws LocalLoginUnavailableException, AuthenticationUnavailableException { Optional<String> id; Optional<String> token = Optional.empty(); id = authenticator.authenticate(username, password); if (id.isPresent()) { Optional<User> user = userStore.userFor(id.get()); if (user.isPresent()) { String uuid = UUID.randomUUID().toString(); token = Optional.of(uuid); users.put(uuid, user.get()); } } return token; } LoggedInUsers(Authenticator authenticator, UserStore userStore,
                       Timeout inactivityTimeout, AuthenticationHandler authenticationHandler); synchronized Optional<User> userFor(String authHeader); synchronized Optional<String> userTokenFor(String username, String password); static final Logger LOG; }### Answer:
@Test public void canStoreAUserAndReturnsAToken() throws Exception { LoggedInUsers instance = userStoreWithUserA; Optional<String> token = instance.userTokenFor("a", "b"); assertThat(token, is(present())); assertThat(token.get(), not(isEmptyString())); }
@Test public void willReturnAUniqueTokenForEachUser() throws Exception { LoggedInUsers instance = userStoreWithUserAAndB; String tokenA = instance.userTokenFor("a", "b").get(); String tokenB = instance.userTokenFor("c", "d").get(); assertThat(tokenA, is(not(tokenB))); }
@Test public void returnsNoTokenIfTheUserIsUnknown() throws Exception { LoggedInUsers instance = userStoreWithUserA; Optional<String> token = instance.userTokenFor("unknownUser", ""); assertThat(token, is(not(present()))); }
@Test public void willGenerateADifferentTokenEachSession() throws Exception { LoggedInUsers instance = this.userStoreWithUserA; String token = instance.userTokenFor("a", "b").get(); Thread.sleep(ONE_SECOND_TIMEOUT.toMilliseconds() + 1); String otherToken = instance.userTokenFor("a", "b").get(); assertThat(token, is(not(otherToken))); }
@Test public void throwsLocalLoginUnavailableExceptionWhenTheUserCouldNotBeAuthenticatedLocallyDueToASystemError() throws Exception { Authenticator authenticator = mock(JsonBasedAuthenticator.class); given(authenticator.authenticate(anyString(), anyString())).willThrow(new LocalLoginUnavailableException("")); LoggedInUsers instance = new LoggedInUsers(authenticator, null, ONE_SECOND_TIMEOUT, null); expectedException.expect(LocalLoginUnavailableException.class); instance.userTokenFor("", ""); }