Java Code Examples for io.reactivex.observers.TestObserver#assertValue()

The following examples show how to use io.reactivex.observers.TestObserver#assertValue() . 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: TokenRequestResolverTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldResolveAuthorizationRequest_noRequestedScope_userDefaultScopes() {
    final String scope = "read";
    TokenRequest authorizationRequest = new TokenRequest();

    Client client = new Client();
    client.setEnhanceScopesWithUserPermissions(true);

    User user = new User();
    Role role = new Role();
    role.setOauthScopes(Collections.singletonList(scope));
    user.setRolesPermissions(Collections.singleton(role));

    TestObserver<TokenRequest> testObserver = tokenRequestResolver.resolve(authorizationRequest, client, user).test();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(request -> request.getScopes().iterator().next().equals(scope));
}
 
Example 2
Source File: SubscriptionProxyTest.java    From RxGroups with Apache License 2.0 6 votes vote down vote up
@Test public void testSubscribe() {
  TestObserver<Integer> observer = new TestObserver<>();
  Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
    @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter)
        throws Exception {
      emitter.onNext(1234);
      emitter.onComplete();
    }
  });
  SubscriptionProxy<Integer> proxy = SubscriptionProxy.create(observable);

  proxy.subscribe(observer);

  observer.assertComplete();
  observer.assertValue(1234);
}
 
Example 3
Source File: RxPermissionsTest.java    From RxPermissions with Apache License 2.0 6 votes vote down vote up
@Test
@TargetApi(Build.VERSION_CODES.M)
public void subscription_severalPermissions_oneRevoked() {
    TestObserver<Boolean> sub = new TestObserver<>();
    String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA};
    when(mRxPermissions.isGranted(Matchers.<String>anyVararg())).thenReturn(false);
    when(mRxPermissions.isRevoked(Manifest.permission.CAMERA)).thenReturn(true);

    trigger().compose(mRxPermissions.ensure(permissions)).subscribe(sub);
    mRxPermissions.onRequestPermissionsResult(
            new String[]{Manifest.permission.READ_PHONE_STATE},
            new int[]{PackageManager.PERMISSION_GRANTED});

    sub.assertNoErrors();
    sub.assertTerminated();
    sub.assertValue(false);
}
 
Example 4
Source File: MongoApplicationRepositoryTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() throws TechnicalException {
    // create app
    Application app = new Application();
    app.setName("testClientId");
    Application appCreated = applicationRepository.create(app).blockingGet();

    // fetch app
    TestObserver<Application> testObserver = applicationRepository.findById(appCreated.getId()).test();
    testObserver.awaitTerminalEvent();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(a -> a.getName().equals(app.getName()));

    // delete app
    TestObserver testObserver1 = applicationRepository.delete(appCreated.getId()).test();
    testObserver1.awaitTerminalEvent();

    // fetch app
    applicationRepository.findById(appCreated.getId()).test().assertEmpty();
}
 
Example 5
Source File: MongoCertificateRepositoryTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdate() throws TechnicalException {
    // create certificate
    Certificate certificate = new Certificate();
    certificate.setName("testName");
    Certificate certificateCreated = certificateRepository.create(certificate).blockingGet();

    // update certificate
    Certificate updatedCertificate = new Certificate();
    updatedCertificate.setId(certificateCreated.getId());
    updatedCertificate.setName("testUpdatedName");

    TestObserver<Certificate> testObserver = certificateRepository.update(updatedCertificate).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(d -> d.getName().equals(updatedCertificate.getName()));

}
 
Example 6
Source File: RxFirebaseStorageTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test public void testGetMetadata() {
  mockSuccessfulResultForTask(mockStorageMetadataTask, mockStorageMetadata);
  when(mockStorageReference.getMetadata()).thenReturn(mockStorageMetadataTask);
  when(mockStorageMetadata.getName()).thenReturn("Test");

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

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

  verifyAddOnCompleteListenerForTask(mockStorageMetadataTask);

  callOnComplete(mockStorageMetadataTask);
  obs.dispose();

  callOnComplete(mockStorageMetadataTask);

  obs.assertNoErrors();
  obs.assertComplete();
  obs.assertValue(new Predicate<StorageMetadata>() {
    @Override public boolean test(StorageMetadata storageMetadata) throws Exception {
      return "Test".equals(storageMetadata.getName());
    }
  });
}
 
Example 7
Source File: DynamicClientRegistrationServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void createFromTemplate() {
    Client template = new Client();
    template.setId(ID_SOURCE);
    template.setClientName("shouldBeRemoved");
    template.setClientId("shouldBeReplaced");
    template.setClientSecret("shouldBeRemoved");
    template.setRedirectUris(Arrays.asList("shouldBeRemoved"));
    template.setSectorIdentifierUri("shouldBeRemoved");
    template.setJwks(new JWKSet());
    template.setTemplate(true);

    DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest();
    request.setSoftwareId(Optional.of(ID_SOURCE));
    request.setApplicationType(Optional.of("app"));

    when(formService.copyFromClient(DOMAIN_ID, ID_SOURCE, ID_TARGET)).thenReturn(Single.just(Collections.emptyList()));
    when(emailTemplateService.copyFromClient(DOMAIN_ID, ID_SOURCE, ID_TARGET)).thenReturn(Single.just(Collections.emptyList()));
    when(domain.isDynamicClientRegistrationTemplateEnabled()).thenReturn(true);
    when(clientService.findById("123")).thenReturn(Maybe.just(template));

    TestObserver<Client> testObserver = dcrService.create(request,BASE_PATH).test();
    testObserver.assertComplete().assertNoErrors();
    testObserver.assertValue(client ->
            client.getId().equals("abc") &&
            client.getApplicationType().equals("app") &&
            client.getClientId() != null &&
            !client.getClientId().equals("shouldBeReplaced") &&
            client.getRedirectUris() == null &&
            client.getClientName().equals(ClientServiceImpl.DEFAULT_CLIENT_NAME) &&
            client.getClientSecret() == null &&
            client.getJwks() == null &&
            client.getSectorIdentifierUri() == null
    );
    verify(clientService, times(1)).create(any());
}
 
Example 8
Source File: ReactiveClientStandardServerInteropTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void oneToOne() {
    RxGreeterGrpc.RxGreeterStub stub = RxGreeterGrpc.newRxStub(channel);
    Single<String> rxRequest = Single.just("World");
    Single<String> rxResponse = rxRequest
            .map(this::toRequest)
            .compose(stub::sayHello)
            .map(this::fromResponse);

    TestObserver<String> test = rxResponse.test();
    test.awaitTerminalEvent(1, TimeUnit.SECONDS);

    test.assertNoErrors();
    test.assertValue("Hello World");
}
 
Example 9
Source File: RxPermissionsTest.java    From RxPermissions with Apache License 2.0 5 votes vote down vote up
@Test
@TargetApi(Build.VERSION_CODES.M)
public void eachSubscription_revoked() {
    TestObserver<Permission> sub = new TestObserver<>();
    String permission = Manifest.permission.READ_PHONE_STATE;
    when(mRxPermissions.isRevoked(permission)).thenReturn(true);

    trigger().compose(mRxPermissions.ensureEach(permission)).subscribe(sub);

    sub.assertNoErrors();
    sub.assertTerminated();
    sub.assertValue(new Permission(permission, false));
}
 
Example 10
Source File: RoleServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFindByIdsIn() {
    when(roleRepository.findByIdIn(Arrays.asList("my-role"))).thenReturn(Single.just(Collections.singleton(new Role())));
    TestObserver<Set<Role>> testObserver = roleService.findByIdIn(Arrays.asList("my-role")).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(roles -> roles.size() == 1);
}
 
Example 11
Source File: LdapBindAuthenticationProviderTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadUserByUsername_authentication() throws Exception {
    embeddedLdapRule.ldapConnection();

    String credentials = "bobspassword";
    String principal = "bob";

    TestObserver<User> testObserver = authenticationProvider.loadUserByUsername(new Authentication() {
        @Override
        public Object getCredentials() {
            return credentials;
        }

        @Override
        public Object getPrincipal() {
            return principal;
        }

        @Override
        public AuthenticationContext getContext() {
            return null;
        }
    }).test();

    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(u -> principal.equals(u.getUsername()));
}
 
Example 12
Source File: PermissionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void hasPermission_hasPermissionsOnAnotherReference() {

    DefaultUser user = new DefaultUser("user");
    user.setId(USER_ID);

    Membership membership = new Membership();
    membership.setMemberType(MemberType.USER);
    membership.setMemberId(USER_ID);
    membership.setReferenceType(ReferenceType.ORGANIZATION);
    membership.setReferenceId(ORGANIZATION_ID);
    membership.setRoleId(ROLE_ID);

    Role role = new Role();
    role.setId(ROLE_ID);
    role.setAssignableType(ReferenceType.ORGANIZATION);
    role.setPermissionAcls(Permission.of(DOMAIN, READ, CREATE)); // The permission create is set on organization but expected on a domain.

    when(groupService.findByMember(user.getId())).thenReturn(Single.just(emptyList()));
    when(membershipService.findByCriteria(eq(ReferenceType.ORGANIZATION), eq(ORGANIZATION_ID), any(MembershipCriteria.class))).thenReturn(Flowable.just(membership));
    when(membershipService.findByCriteria(eq(ReferenceType.DOMAIN), eq(DOMAIN_ID), any(MembershipCriteria.class))).thenReturn(Flowable.empty());
    when(roleService.findByIdIn(Arrays.asList(membership.getRoleId()))).thenReturn(Single.just(new HashSet<>(Arrays.asList(role))));

    TestObserver<Boolean> obs = cut.hasPermission(user,
            and(of(ReferenceType.ORGANIZATION, ORGANIZATION_ID, DOMAIN, READ),
                    of(ReferenceType.DOMAIN, DOMAIN_ID, Permission.DOMAIN, CREATE))).test();

    obs.awaitTerminalEvent();
    obs.assertComplete();
    obs.assertValue(false);
}
 
Example 13
Source File: Test_Mokito.java    From Reactive-Programming-With-Java-9 with MIT License 5 votes vote down vote up
@Test
public void test_fromArray() {
	int[] arr = { 12, 34, 54, 6, 7 };
	Mockito.when(myOperator.createObservable()).thenReturn(Observable.fromArray(arr));
	TestObserver<int[]> testObserver = myOperator.createObservable().test();
	testObserver.awaitTerminalEvent();
	testObserver.assertValue(arr);

}
 
Example 14
Source File: TokenRequestResolverTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldResolveTokenRequest_withUser_permissionsRequestedNone() {
    final String scope = "read";
    final List<String> userScopes = Arrays.asList("user1", "user2", "user3");
    
    TokenRequest tokenRequest = new TokenRequest();
    List<String> reqScopes = new ArrayList<>();
    reqScopes.add(scope);
    // Request none of the three user scopes
    tokenRequest.setScopes(new HashSet<>(reqScopes));
    
    Client client = new Client();
    client.setEnhanceScopesWithUserPermissions(true);
    client.setScopes(Collections.singletonList(scope));

    User user = new User();
    Role role = new Role();
    role.setOauthScopes(userScopes);
    user.setRolesPermissions(Collections.singleton(role));

    TestObserver<TokenRequest> testObserver = tokenRequestResolver.resolve(tokenRequest, client, user).test();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    
    // Request should have been enhanced with all of user's permissions, even though none of them has been requested
    List<String> expectedScopes = new ArrayList<>();
    expectedScopes.add(scope);
    expectedScopes.addAll(userScopes);
    testObserver.assertValue(request -> request.getScopes().containsAll(expectedScopes) && request.getScopes().contains(scope) && request.getScopes().size() == 4);
}
 
Example 15
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 16
Source File: RxPermissionsTest.java    From RxPermissions with Apache License 2.0 5 votes vote down vote up
@Test
@TargetApi(Build.VERSION_CODES.M)
public void subscription_granted() {
    TestObserver<Boolean> sub = new TestObserver<>();
    String permission = Manifest.permission.READ_PHONE_STATE;
    when(mRxPermissions.isGranted(permission)).thenReturn(false);
    int[] result = new int[]{PackageManager.PERMISSION_GRANTED};

    trigger().compose(mRxPermissions.ensure(permission)).subscribe(sub);
    mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result);

    sub.assertNoErrors();
    sub.assertTerminated();
    sub.assertValue(true);
}
 
Example 17
Source File: ReCaptchaServiceImplTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void isNotValidNoSuccess() {

    ReflectionTestUtils.setField(reCaptchaService, "minScore", 0.5d);
    ReflectionTestUtils.setField(reCaptchaService, "enabled", true);

    when(httpResponse.bodyAsString())
            .thenReturn(new JsonObject().put("success", false).put("score", 0.0d).toString());

    spyHttpRequest(client.post(eq("https://verif")));

    TestObserver<Boolean> obs = reCaptchaService.isValid("any").test();
    obs.awaitTerminalEvent();
    obs.assertValue(false);
}
 
Example 18
Source File: GetOperationTest.java    From storio with Apache License 2.0 5 votes vote down vote up
@Test
public void getNonExistedObjectExecuteAsSingle() {
    final TestSubscriber<Changes> changesTestSubscriber = new TestSubscriber<Changes>();

    storIOContentResolver
            .observeChangesOfUri(TestItem.CONTENT_URI, BackpressureStrategy.MISSING)
            .take(1)
            .subscribe(changesTestSubscriber);

    contentResolver.insert(TestItem.CONTENT_URI, TestItem.create(null, "value").toContentValues());

    Single<Optional<TestItem>> testItemSingle = storIOContentResolver
            .get()
            .object(TestItem.class)
            .withQuery(Query.builder()
                    .uri(TestItem.CONTENT_URI)
                    .where(TestItem.COLUMN_VALUE + "=?")
                    .whereArgs("some value")
                    .build())
            .prepare()
            .asRxSingle();

    TestObserver<Optional<TestItem>> testObserver = new TestObserver<Optional<TestItem>>();
    testItemSingle.subscribe(testObserver);

    testObserver.awaitTerminalEvent(5, SECONDS);
    testObserver.assertValue(Optional.<TestItem>empty());
    testObserver.assertNoErrors();

    changesTestSubscriber.awaitTerminalEvent(60, SECONDS);
    changesTestSubscriber.assertNoErrors();
    changesTestSubscriber.assertValue(Changes.newInstance(TestItem.CONTENT_URI));
}
 
Example 19
Source File: DynamicClientRegistrationServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void create_validateJWKsUriOk() {
    DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest();
    request.setRedirectUris(Optional.empty());
    request.setJwksUri(Optional.of("something"));

    when(jwkService.getKeys(anyString())).thenReturn(Maybe.just(new JWKSet()));

    TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test();
    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertValue(client -> defaultAssertion(client) && client.getJwksUri().equals("something"));
}
 
Example 20
Source File: GithubAuthenticationProviderTest.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldLoadUserByUsername_roleMapping() {
    // configure role mapping
    Map<String, String[]> roles = new HashMap<>();
    roles.put("admin", new String[] { "preferred_username=bob"});
    roleMapper.setRoles(roles);

    stubFor(any(urlPathEqualTo("/oauth/token"))
            .withHeader(HttpHeaders.CONTENT_TYPE, containing(URLEncodedUtils.CONTENT_TYPE))
            .withRequestBody(matching(".*"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withBody("access_token=test_token&token_type=bearer")));

    stubFor(any(urlPathEqualTo("/profile"))
            .withHeader(HttpHeaders.AUTHORIZATION, equalTo("token test_token"))
            .willReturn(okJson("{ \"login\": \"bob\", \"preferred_username\": \"bob\"}")));

    TestObserver<User> testObserver = authenticationProvider.loadUserByUsername(new Authentication() {
        @Override
        public Object getCredentials() {
            return "__social__";
        }

        @Override
        public Object getPrincipal() {
            return "__social__";
        }

        @Override
        public AuthenticationContext getContext() {
            DummyRequest dummyRequest = new DummyRequest();
            dummyRequest.setParameters(Collections.singletonMap("code", Arrays.asList("test-code")));
            return new DummyAuthenticationContext(Collections.singletonMap("redirect_uri", "http://redirect_uri"), dummyRequest);
        }
    }).test();

    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(u -> "bob".equals(u.getUsername()));
    testObserver.assertValue(u -> u.getRoles().contains("admin"));
}