io.reactivex.observers.TestObserver Java Examples

The following examples show how to use io.reactivex.observers.TestObserver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RxFirebaseUserTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testLinkWithCredential() {
    mockSuccessfulAuthResult();
    when(mockFirebaseUser.linkWithCredential(mockAuthCredential))
            .thenReturn(mockAuthTaskResult);

    TestObserver<FirebaseUser> obs = TestObserver.create();

    RxFirebaseUser.linkWithCredential(mockFirebaseUser, mockAuthCredential)
            .subscribe(obs);

    callOnComplete(mockAuthTaskResult);
    obs.dispose();

    // Ensure no more values are emitted after unsubscribe
    callOnComplete(mockAuthTaskResult);

    obs.assertComplete();
    obs.assertValueCount(1);
}
 
Example #2
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithWrongAudience() {
    String assertion = new PlainJWT(
            new JWTClaimsSet.Builder()
                    .issuer(ISSUER)
                    .subject(CLIENT_ID)
                    .audience("wrongAudience")
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    ).serialize();

    OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class);
    String basePath="/";

    when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE);
    when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata);

    TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test();

    testObserver.assertError(InvalidClientException.class);
    testObserver.assertNotComplete();
}
 
Example #3
Source File: DomainServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUpdate() {
    UpdateDomain updateDomain = Mockito.mock(UpdateDomain.class);
    when(domainRepository.findById("my-domain")).thenReturn(Maybe.just(new Domain()));
    when(domainRepository.update(any(Domain.class))).thenReturn(Single.just(new Domain()));
    when(eventService.create(any())).thenReturn(Single.just(new Event()));

    TestObserver testObserver = domainService.update("my-domain", updateDomain).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();

    verify(domainRepository, times(1)).findById(anyString());
    verify(domainRepository, times(1)).update(any(Domain.class));
    verify(eventService, times(1)).create(any());
}
 
Example #4
Source File: RxFirebaseStorageTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test public void testUpdateMetadata_notSuccessful() {
  mockNotSuccessfulResultForTask(mockStorageMetadataTask, new IllegalStateException());

  TestObserver<StorageMetadata> obs = TestObserver.create();
  when(mockStorageReference.updateMetadata(mockStorageMetadata)).thenReturn(
      mockStorageMetadataTask);
  RxFirebaseStorage.updateMetadata(mockStorageReference, mockStorageMetadata).subscribe(obs);

  verifyAddOnCompleteListenerForTask(mockStorageMetadataTask);

  callOnComplete(mockStorageMetadataTask);
  obs.dispose();

  callOnComplete(mockStorageMetadataTask);

  obs.assertError(IllegalStateException.class);
  obs.assertNoValues();
}
 
Example #5
Source File: ThreadDumpTest.java    From AndroidGodEye with Apache License 2.0 6 votes vote down vote up
@Test
public void work2() {
    ((TestScheduler) ThreadUtil.computationScheduler()).advanceTimeBy(5, TimeUnit.SECONDS);
    try {
        TestObserver<List<ThreadInfo>> subscriber = new TestObserver<>();
        GodEye.instance().<ThreadDump, List<ThreadInfo>>moduleObservable(GodEye.ModuleName.THREAD).subscribe(subscriber);
        subscriber.assertValue(new Predicate<List<ThreadInfo>>() {
            @Override
            public boolean test(List<ThreadInfo> threadInfos) throws Exception {
                return threadInfos != null && !threadInfos.isEmpty();
            }
        });
    } catch (UninstallException e) {
        Assert.fail();
    }
}
 
Example #6
Source File: RxFirebaseDatabaseTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testChildEvents_Query_notSuccessful() {
    TestObserver<ChildEvent> sub = TestObserver.create();

    RxFirebaseDatabase.childEvents(mockQuery)
            .subscribe(sub);

    verifyQueryAddChildEventListener();
    callChildOnCancelled();

    sub.assertNoValues();
    assertThat(sub.errorCount())
            .isEqualTo(1);

    sub.dispose();

    callChildOnCancelled();

    // Ensure no more values are emitted after unsubscribe
    assertThat(sub.errorCount())
            .isEqualTo(1);
}
 
Example #7
Source File: RxFirebaseStorageTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test public void testGetMetaData_notSuccessful() {
  mockNotSuccessfulResultForTask(mockStorageMetadataTask, new IllegalStateException());
  when(mockStorageReference.getMetadata()).thenReturn(mockStorageMetadataTask);

  TestObserver<StorageMetadata> obs = TestObserver.create();

  RxFirebaseStorage.getMetadata(mockStorageReference).subscribe(obs);
  verifyAddOnCompleteListenerForTask(mockStorageMetadataTask);

  callOnComplete(mockStorageMetadataTask);
  obs.dispose();

  callOnComplete(mockStorageMetadataTask);

  obs.assertError(IllegalStateException.class);
  obs.assertNoValues();
}
 
Example #8
Source File: ScopeServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreate_whiteSpaces() {
    NewScope newScope = Mockito.mock(NewScope.class);
    when(newScope.getKey()).thenReturn("MY scope");
    when(scopeRepository.findByDomainAndKey(DOMAIN, "MY_scope")).thenReturn(Maybe.empty());
    when(scopeRepository.create(any(Scope.class))).thenReturn(Single.just(new Scope()));
    when(eventService.create(any())).thenReturn(Single.just(new Event()));

    TestObserver testObserver = scopeService.create(DOMAIN, newScope).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();

    verify(scopeRepository, times(1)).create(any(Scope.class));
    verify(scopeRepository, times(1)).create(argThat(new ArgumentMatcher<Scope>() {
        @Override
        public boolean matches(Scope scope) {
            return scope.getKey().equals("MY_scope");
        }
    }));
    verify(eventService, times(1)).create(any());
}
 
Example #9
Source File: TokenEnhancerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEnhanceToken_withoutIDToken() {
    OAuth2Request oAuth2Request = new OAuth2Request();
    oAuth2Request.setClientId("client-id");
    // no openid scope for the request

    Client client = new Client();

    Token accessToken = new AccessToken("token-id");

    TestObserver<Token> testObserver = tokenEnhancer.enhance(accessToken, oAuth2Request, client, null, null).test();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(accessToken1 -> accessToken1.getAdditionalInformation().isEmpty());
}
 
Example #10
Source File: UserServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateUser_invalid_identity_provider() {
    final String domain = "domain";

    Domain domain1 = mock(Domain.class);
    when(domain1.getId()).thenReturn(domain);

    NewUser newUser = mock(NewUser.class);
    when(newUser.getUsername()).thenReturn("username");
    when(newUser.getSource()).thenReturn("unknown-idp");

    when(domainService.findById(domain)).thenReturn(Maybe.just(domain1));
    when(commonUserService.findByDomainAndUsernameAndSource(anyString(), anyString(), anyString())).thenReturn(Maybe.empty());
    when(identityProviderManager.getUserProvider(anyString())).thenReturn(Maybe.empty());

    TestObserver<User> testObserver = userService.create(domain, newUser).test();
    testObserver.assertNotComplete();
    testObserver.assertError(UserProviderNotFoundException.class);
    verify(commonUserService, never()).create(any());
}
 
Example #11
Source File: ResourceOwnerPasswordCredentialsTokenGranterTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGenerateAnAccessToken() {
    LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.set(Parameters.USERNAME, "my-username");
    parameters.set(Parameters.PASSWORD, "my-password");

    Client client = new Client();
    client.setClientId("my-client-id");
    client.setAuthorizedGrantTypes(Arrays.asList(new String[]{"password"}));

    Token accessToken = new AccessToken("test-token");

    when(tokenRequest.parameters()).thenReturn(parameters);
    when(tokenRequest.createOAuth2Request()).thenReturn(new OAuth2Request());

    when(tokenRequestResolver.resolve(any(), any(), any())).thenReturn(Single.just(tokenRequest));
    when(tokenService.create(any(), any(), any())).thenReturn(Single.just(accessToken));
    when(userAuthenticationManager.authenticate(any(Client.class), any(Authentication.class))).thenReturn(Single.just(new User()));

    TestObserver<Token> testObserver = granter.grant(tokenRequest, client).test();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(token -> token.getValue().equals("test-token"));

}
 
Example #12
Source File: ObservableGroupTest.java    From RxGroups with Apache License 2.0 6 votes vote down vote up
@Test public void shouldAutoResubscribeAfterUnlock() throws InterruptedException {
  ObservableGroup group = observableManager.newGroup();
  TestObserver<String> testObserver = new TestObserver<>();
  PublishSubject<String> sourceObservable = PublishSubject.create();

  group.lock();
  sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver);

  sourceObservable.onNext("Chespirito");
  sourceObservable.onComplete();

  group.unlock();

  testObserver.assertComplete();
  testObserver.assertNoErrors();
  testObserver.assertValue("Chespirito");
  assertThat(group.hasObservables(fooObserver)).isEqualTo(false);
}
 
Example #13
Source File: ApplicationServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void update_implicitGrant_invalidRedirectUri() {

    when(applicationRepository.findById(any())).thenReturn(Maybe.just(new Application()));
    when(domainService.findById(any())).thenReturn(Maybe.just(new Domain()));

    Application toPatch = new Application();
    toPatch.setDomain(DOMAIN);
    ApplicationSettings settings = new ApplicationSettings();
    ApplicationOAuthSettings oAuthSettings = new ApplicationOAuthSettings();
    oAuthSettings.setGrantTypes(Arrays.asList("implicit"));
    oAuthSettings.setResponseTypes(Arrays.asList("token"));
    oAuthSettings.setClientType(ClientType.PUBLIC);
    settings.setOauth(oAuthSettings);
    toPatch.setSettings(settings);

    TestObserver testObserver = applicationService.update(toPatch).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertNotComplete();
    testObserver.assertError(InvalidRedirectUriException.class);

    verify(applicationRepository, times(1)).findById(any());
}
 
Example #14
Source File: GetKeystoreWalletRepoTest.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Test
public void testImportStore() {
	TestObserver<Wallet> subscriber = accountKeystoreService
			.importKeystore(STORE_1, PASS_1, PASS_1)
			.toObservable()
			.test();
	subscriber.awaitTerminalEvent();
	subscriber.assertComplete();
	subscriber.assertNoErrors();

	subscriber.assertOf(accountTestObserver -> {
		assertEquals(accountTestObserver.valueCount(), 1);
		assertEquals(accountTestObserver.values().get(0).address, ADDRESS_1);
		assertTrue(accountTestObserver.values().get(0).sameAddress(ADDRESS_1));
	});
	deleteAccountStore(ADDRESS_1, PASS_1);
}
 
Example #15
Source File: EntrypointServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateDefault() {

    when(entrypointRepository.create(any(Entrypoint.class))).thenAnswer(i -> Single.just(i.getArgument(0)));

    TestObserver<Entrypoint> obs = cut.createDefault(ORGANIZATION_ID).test();

    obs.awaitTerminalEvent();
    obs.assertValue(entrypoint -> entrypoint.getId() != null
            && entrypoint.isDefaultEntrypoint() && entrypoint.getOrganizationId().equals(ORGANIZATION_ID));

    verify(auditService, times(1)).report(argThat(builder -> {
        Audit audit = builder.build(new ObjectMapper());
        assertEquals(EventType.ENTRYPOINT_CREATED, audit.getType());
        assertEquals(ReferenceType.ORGANIZATION, audit.getReferenceType());
        assertEquals(ORGANIZATION_ID, audit.getReferenceId());
        assertEquals("system", audit.getActor().getId());

        return true;
    }));
}
 
Example #16
Source File: RxFirebaseAuthTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testSignInWithCredential() {
    mockSuccessfulAuthResult();

    when(mockFirebaseAuth.signInWithCredential(mockAuthCredential))
            .thenReturn(mockAuthResultTask);

    TestObserver<FirebaseUser> obs = TestObserver.create();

    RxFirebaseAuth
            .signInWithCredential(mockFirebaseAuth, mockAuthCredential)
            .subscribe(obs);

    callOnComplete(mockAuthResultTask);
    obs.dispose();

    // Ensure no more values are emitted after unsubscribe
    callOnComplete(mockAuthResultTask);

    obs.assertComplete();
    obs.assertValueCount(1);
}
 
Example #17
Source File: TagServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreate() {
    NewTag newTag = Mockito.mock(NewTag.class);
    when(newTag.getName()).thenReturn("my-tag");
    when(tagRepository.findById("my-tag", Organization.DEFAULT)).thenReturn(Maybe.empty());
    when(tagRepository.create(any(Tag.class))).thenReturn(Single.just(new Tag()));

    TestObserver testObserver = tagService.create(newTag, Organization.DEFAULT, null).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();

    verify(tagRepository, times(1)).findById(eq("my-tag"), eq(Organization.DEFAULT));
    verify(tagRepository, times(1)).create(any(Tag.class));
}
 
Example #18
Source File: UserServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldResetPassword_externalIdEmpty() {
    final String domain = "domain";
    final String password = "password";

    User user = mock(User.class);
    when(user.getId()).thenReturn("user-id");
    when(user.getUsername()).thenReturn("username");
    when(user.getSource()).thenReturn("default-idp");

    io.gravitee.am.identityprovider.api.User idpUser = mock(io.gravitee.am.identityprovider.api.DefaultUser.class);
    when(idpUser.getId()).thenReturn("idp-id");

    UserProvider userProvider = mock(UserProvider.class);
    when(userProvider.findByUsername(user.getUsername())).thenReturn(Maybe.just(idpUser));
    when(userProvider.update(anyString(), any())).thenReturn(Single.just(idpUser));

    when(commonUserService.findById(eq(ReferenceType.DOMAIN), eq(domain), eq("user-id"))).thenReturn(Single.just(user));
    when(identityProviderManager.getUserProvider(user.getSource())).thenReturn(Maybe.just(userProvider));
    when(commonUserService.update(any())).thenReturn(Single.just(user));
    when(loginAttemptService.reset(any())).thenReturn(Completable.complete());

    TestObserver testObserver = userService.resetPassword(domain, user.getId(), password).test();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
}
 
Example #19
Source File: MongoApplicationRepositoryTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearch_strict() {
    final String domain = "domain";
    // create app
    Application app = new Application();
    app.setDomain(domain);
    app.setName("clientId");
    applicationRepository.create(app).blockingGet();

    Application app2 = new Application();
    app2.setDomain(domain);
    app2.setName("clientId2");
    applicationRepository.create(app2).blockingGet();

    // fetch user
    TestObserver<Page<Application>> testObserver = applicationRepository.search(domain, "clientId", 0, Integer.MAX_VALUE).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(apps -> apps.getData().size() == 1);
    testObserver.assertValue(apps -> apps.getData().iterator().next().getName().equals(app.getName()));

}
 
Example #20
Source File: QueryTest.java    From sqlbrite with Apache License 2.0 6 votes vote down vote up
@Test public void mapToOneOrDefaultReturnsDefaultWhenNullCursor() {
  Employee defaultEmployee = new Employee("bob", "Bob Bobberson");
  Query nully = new Query() {
    @Nullable @Override public Cursor run() {
      return null;
    }
  };

  TestObserver<Employee> observer = new TestObserver<>();
  Observable.just(nully)
      .lift(Query.mapToOneOrDefault(MAPPER, defaultEmployee))
      .subscribe(observer);

  observer.assertValues(defaultEmployee);
  observer.assertComplete();
}
 
Example #21
Source File: GroupServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRevokeRoles_roleNotFound() {
    List<String> rolesIds = Arrays.asList("role-1", "role-2");

    Group group = mock(Group.class);
    when(group.getId()).thenReturn("group-id");

    Set<Role> roles = new HashSet<>();
    Role role1 = new Role();
    role1.setId("role-1");
    Role role2 = new Role();
    role2.setId("role-2");
    roles.add(role1);
    roles.add(role2);

    when(groupRepository.findById(eq(ReferenceType.DOMAIN), eq(DOMAIN), eq("group-id"))).thenReturn(Maybe.just(group));
    when(roleService.findByIdIn(rolesIds)).thenReturn(Single.just(Collections.emptySet()));

    TestObserver testObserver = groupService.revokeRoles(ReferenceType.DOMAIN, DOMAIN, group.getId(), rolesIds).test();
    testObserver.assertNotComplete();
    testObserver.assertError(RoleNotFoundException.class);
    verify(groupRepository, never()).update(any());
}
 
Example #22
Source File: RevocationServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRevoke_accessToken() {
    final RevocationTokenRequest revocationTokenRequest = new RevocationTokenRequest("token");

    Client client = new Client();
    client.setClientId("client-id");

    AccessToken accessToken = new AccessToken("token");
    accessToken.setClientId("client-id");

    when(tokenService.getAccessToken("token", client)).thenReturn(Maybe.just(accessToken));
    when(tokenService.deleteAccessToken("token")).thenReturn(Completable.complete());

    TestObserver testObserver = revocationTokenService.revoke(revocationTokenRequest, client).test();

    testObserver.assertComplete();
    testObserver.assertNoErrors();

    verify(tokenService, times(1)).getAccessToken("token", client);
    verify(tokenService, times(1)).deleteAccessToken("token");
    verify(tokenService, never()).getRefreshToken(anyString(), any());
    verify(tokenService, never()).deleteRefreshToken(anyString());

}
 
Example #23
Source File: ResourceServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void countAccessPolicyByResource() {
    when(accessPolicyRepository.countByResource(RESOURCE_ID)).thenReturn(Single.just(1l));
    TestObserver<Long> testObserver = service.countAccessPolicyByResource(RESOURCE_ID).test();
    testObserver.assertComplete().assertNoErrors();
    testObserver.assertValue(accessPolicies -> accessPolicies == 1l);
    verify(accessPolicyRepository, times(1)).countByResource(RESOURCE_ID);
}
 
Example #24
Source File: PreparedGetNumberOfResultsTest.java    From storio with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWrapExceptionIntoStorIOExceptionForSingle() {
    final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class);

    //noinspection unchecked
    final GetResolver<Integer> getResolver = mock(GetResolver.class);

    when(getResolver.performGet(eq(storIOSQLite), any(Query.class)))
            .thenThrow(new IllegalStateException("test exception"));

    final TestObserver<Integer> testObserver = new TestObserver<Integer>();

    new PreparedGetNumberOfResults.Builder(storIOSQLite)
            .withQuery(Query.builder().table("test_table").build())
            .withGetResolver(getResolver)
            .prepare()
            .asRxSingle()
            .subscribe(testObserver);

    testObserver.awaitTerminalEvent(60, SECONDS);
    testObserver.assertError(StorIOException.class);

    assertThat(testObserver.errorCount()).isEqualTo(1);
    StorIOException storIOException = (StorIOException) testObserver.errors().get(0);
    IllegalStateException cause = (IllegalStateException) storIOException.getCause();
    assertThat(cause).hasMessage("test exception");
}
 
Example #25
Source File: MongoAuthorizationCodeRepositoryTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldStoreCode() {
    String code = "testCode";
    AuthorizationCode authorizationCode = new AuthorizationCode();
    authorizationCode.setCode(code);

    authorizationCodeRepository.create(authorizationCode).blockingGet();

    TestObserver<AuthorizationCode> testObserver = authorizationCodeRepository.findByCode(code).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(authorizationCode1 -> authorizationCode1.getCode().equals(code));
}
 
Example #26
Source File: RxRelayIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenObserverSubscribedToBehaviorRelayWithoutDefaultValue_thenItIsEmpty() {
    BehaviorRelay<Integer> behaviorRelay = BehaviorRelay.create();
    TestObserver<Integer> firstObserver = new TestObserver<>();
    behaviorRelay.subscribe(firstObserver);
    firstObserver.assertEmpty();
}
 
Example #27
Source File: TimeLimiterTransformerObservableTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void timeoutEmpty() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ZERO));
    TestObserver<?> observer = Observable.empty()
        .delay(1, TimeUnit.MINUTES)
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    observer.assertError(TimeoutException.class);
    then(timeLimiter).should()
        .onError(any(TimeoutException.class));
}
 
Example #28
Source File: JWEServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void encryptIdToken_noEncryption() {
    String jwt = "JWT";
    TestObserver testObserver = jweService.encryptIdToken(jwt, new Client()).test();
    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertResult(jwt);
}
 
Example #29
Source File: RoleServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotDelete_systemRole() {
    Role role = Mockito.mock(Role.class);
    when(role.isSystem()).thenReturn(true);
    when(roleRepository.findById(eq(ReferenceType.DOMAIN), eq(DOMAIN), eq("my-role"))).thenReturn(Maybe.just(role));

    TestObserver testObserver = roleService.delete(ReferenceType.DOMAIN, DOMAIN, "my-role").test();
    testObserver.awaitTerminalEvent();

    testObserver.assertNotComplete();
    testObserver.assertError(SystemRoleDeleteException.class);

    verify(roleRepository, never()).delete("my-role");
}
 
Example #30
Source File: IDTokenServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
// ignore due to map order and current timestamp (local test)
public void shouldCreateIDToken_withUser_scopesRequest_email_address() {
    OAuth2Request oAuth2Request = new OAuth2Request();
    oAuth2Request.setClientId("client-id");
    oAuth2Request.setScopes(new HashSet<>(Arrays.asList("openid", "email", "address")));
    oAuth2Request.setSubject("subject");

    Client client = new Client();

    User user = createUser();

    JWT expectedJwt = new JWT();
    expectedJwt.setSub(user.getId());
    expectedJwt.setAud("client-id");
    expectedJwt.put(StandardClaims.ADDRESS, user.getAdditionalInformation().get(StandardClaims.ADDRESS));
    expectedJwt.put(StandardClaims.EMAIL_VERIFIED, user.getAdditionalInformation().get(StandardClaims.EMAIL_VERIFIED));
    expectedJwt.setIss(null);
    expectedJwt.setExp((System.currentTimeMillis() / 1000l) + 14400);
    expectedJwt.setIat(System.currentTimeMillis() / 1000l);
    expectedJwt.put(StandardClaims.EMAIL, user.getAdditionalInformation().get(StandardClaims.EMAIL));

    when(certificateManager.defaultCertificateProvider()).thenReturn(new io.gravitee.am.gateway.certificate.CertificateProvider(defaultCertificateProvider));
    when(certificateManager.get(anyString())).thenReturn(Maybe.just(new io.gravitee.am.gateway.certificate.CertificateProvider(certificateProvider)));
    when(jwtService.encode(any(), any(io.gravitee.am.gateway.certificate.CertificateProvider.class))).thenReturn(Single.just("test"));

    TestObserver<String> testObserver = idTokenService.create(oAuth2Request, client, user).test();

    testObserver.assertComplete();
    testObserver.assertNoErrors();

    verify(certificateManager, times(1)).get(anyString());
    verify(jwtService, times(1)).encode(eq(expectedJwt), any(io.gravitee.am.gateway.certificate.CertificateProvider.class));
}