@Test public void testContinueOnSomeDbDirectoriesMissing() throws Exception { File targetDir1 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); File targetDir2 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); try { assertTrue(targetDir1.mkdirs()); assertTrue(targetDir2.mkdirs()); if (!targetDir1.setWritable(false, false)) { System.err.println( "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable"); return; } RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI); rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath()); try { rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE); } catch (Exception e) { e.printStackTrace(); fail("Backend initialization failed even though some paths were available"); } } finally { //noinspection ResultOfMethodCallIgnored targetDir1.setWritable(true, false); FileUtils.deleteDirectory(targetDir1); FileUtils.deleteDirectory(targetDir2); } }
@Override public Boolean call(JobContext jc) throws Exception { try { jc.streamingctx(); fail("Access before creation: Should throw IllegalStateException"); } catch (IllegalStateException ex) { } try { jc.stopStreamingCtx(); fail("Stop before creation: Should throw IllegalStateException"); } catch (IllegalStateException ex) { } try { jc.createStreamingContext(1000L); JavaStreamingContext streamingContext = jc.streamingctx(); jc.stopStreamingCtx(); jc.streamingctx(); fail(); } catch (IllegalStateException ex) { } jc.createStreamingContext(1000L); JavaStreamingContext streamingContext = jc.streamingctx(); jc.stopStreamingCtx(); return streamingContext != null; }
@Test public void shouldStubbingWithThrowableFailVerification() { when(mock.size()).thenThrow(new RuntimeException()); stubVoid(mock).toThrow(new RuntimeException()).on().clone(); verifyZeroInteractions(mock); mock.add("test"); try { verify(mock).size(); fail(); } catch (WantedButNotInvoked e) { } try { verify(mock).clone(); fail(); } catch (WantedButNotInvoked e) { } try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { } }
@Test public void testInterruptTerminalEventAwaitTimed() { TestSubscriber<Integer> ts = TestSubscriber.create(); final Thread t0 = Thread.currentThread(); Worker w = Schedulers.computation().createWorker(); try { w.schedule( new Action0() { @Override public void call() { t0.interrupt(); } }, 200, TimeUnit.MILLISECONDS); try { ts.awaitTerminalEvent(5, TimeUnit.SECONDS); fail("Did not interrupt wait!"); } catch (RuntimeException ex) { if (!(ex.getCause() instanceof InterruptedException)) { fail("The cause is not InterruptedException! " + ex.getCause()); } } } finally { w.unsubscribe(); } }
@Test public void testSetTerminalConfiguration() throws IOException { try { controller.setTerminalConfiguration(null); fail("Got no RuntimeException on calling 'setTerminalConfiguration(null)'!"); } catch (RuntimeException e) { // expected } try { controller.setTerminalConfiguration( new DeviceControllerTerminalConfiguration(null, false, false, false, false)); fail( "Got no RuntimeException on calling 'setTerminalConfiguration(tcon)' " + " where tcon.getChannel() is null!"); } catch (RuntimeException e) { // expected } // 0b0101010101 -> TCON-bits (see 4.2.2.2) mockReadResult(i2cDevice, (byte) 0, (byte) 0b0101010101, null); DeviceControllerTerminalConfiguration tconA = new DeviceControllerTerminalConfiguration( DeviceControllerChannel.A, true, true, true, false); controller.setTerminalConfiguration(tconA); // reading current configuration: // test for proper write-argument -> see FIGURE 7-5 and TABLE 4-1 testForWriteAndRead((byte) 0b1001100); // test for proper write-argument -> see FIGURE 7-5 and TABLE 4-1 // The first four bits of the second byte are the same four bits of // the mocked read-result. Those four bits represent the configuration // of wiper1. This test only modifies wiper0, so only the last four // bits have to be according to 'tconA'. verify(i2cDevice).write(new byte[] {(byte) 0b1000000, (byte) 0b01011110}, 0, 2); DeviceControllerTerminalConfiguration tconB = new DeviceControllerTerminalConfiguration( DeviceControllerChannel.B, false, false, false, true); controller.setTerminalConfiguration(tconB); // reading current configuration: // test for proper write-argument -> see FIGURE 7-5 and TABLE 4-1 testForWriteAndRead((byte) 0b1001100, 2); // test for proper write-argument -> see FIGURE 7-5 and TABLE 4-1 // The last four bits of the second byte are the same four bits of // the mocked read-result. Those four bits represent the configuration // of wiper0. This test only modifies wiper1, so only the last four // bits have to be according to 'tconB'. verify(i2cDevice).write(new byte[] {(byte) 0b1000000, (byte) 0b00010101}, 0, 2); }
@Test public void testPropagateExceptionsFromClose() { final ScheduledExecutorService timerService = Executors.newSingleThreadScheduledExecutor(); try { final CollectingOutput<Integer> out = new CollectingOutput<>(); final Object lock = new Object(); final StreamTask<?, ?> mockTask = createMockTaskWithTimer(timerService, lock); WindowFunction<Integer, Integer, Integer, TimeWindow> failingFunction = new FailingFunction(100); // the operator has a window time that is so long that it will not fire in this test final long hundredYears = 100L * 365 * 24 * 60 * 60 * 1000; AccumulatingProcessingTimeWindowOperator<Integer, Integer, Integer> op = new AccumulatingProcessingTimeWindowOperator<>( failingFunction, identitySelector, IntSerializer.INSTANCE, IntSerializer.INSTANCE, hundredYears, hundredYears); op.setup(mockTask, new StreamConfig(new Configuration()), out); op.open(); for (int i = 0; i < 150; i++) { synchronized (lock) { op.processElement(new StreamRecord<Integer>(i)); } } try { synchronized (lock) { op.close(); } fail("This should fail with an exception"); } catch (Exception e) { assertTrue( e.getMessage().contains("Artificial Test Exception") || (e.getCause() != null && e.getCause().getMessage().contains("Artificial Test Exception"))); } op.dispose(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { timerService.shutdown(); } }
@Test @SuppressWarnings("unchecked") public void testDoWithRetry_ReadTimeOut() throws Exception { AmazonElasticMapReduceCustomClient client = new AmazonElasticMapReduceCustomClient("dummy", "dummy"); client.setRequestInterval(100); Callable callable = mock(Callable.class); AmazonClientException exception = new AmazonClientException("Unable to execute HTTP request: Read timed out"); when(callable.call()).thenThrow(exception, exception, exception).thenReturn(new Object()); long startTime = System.currentTimeMillis(); Object result = client.doThrottleSafe(callable); assertNotNull(result); assertThat( (System.currentTimeMillis() - startTime), greaterThanOrEqualTo(3 * client.getRequestInterval())); // now exceed retries client.setMaxRetriesOnConnectionErrors(2); when(callable.call()).thenThrow(exception, exception, exception).thenReturn(new Object()); try { client.doThrottleSafe(callable); fail("should throw exception"); } catch (Exception e) { assertSame(exception, e); } }
@Test public void testDisruptorCommandBusRepositoryNotAvailableOutsideOfInvokerThread() { DisruptorCommandBus commandBus = new DisruptorCommandBus(eventStore, eventBus); Repository<Aggregate> repository = commandBus.createRepository(new GenericAggregateFactory<Aggregate>(Aggregate.class)); AggregateAnnotationCommandHandler<Aggregate> handler = new AggregateAnnotationCommandHandler<Aggregate>(Aggregate.class, repository); AggregateAnnotationCommandHandler.subscribe(handler, commandBus); DefaultCommandGateway gateway = new DefaultCommandGateway(commandBus); // Create the aggregate String aggregateId = "" + System.currentTimeMillis(); gateway.sendAndWait(new CreateCommandAndEvent(aggregateId)); // Load the aggretate from the repository -- from "worker" thread UnitOfWork uow = DefaultUnitOfWork.startAndGet(); try { Aggregate aggregate = repository.load(aggregateId); fail("Expected IllegalStateException"); } catch (IllegalStateException e) { assertTrue(e.getMessage().contains("DisruptorCommandBus")); } finally { uow.rollback(); } }
@Test public void testLoadWithConflictingChanges_NoConflictResolverSet() { UUID identifier = UUID.randomUUID(); DomainEventMessage event2 = new GenericDomainEventMessage<String>( identifier, (long) 2, "Mock contents", MetaData.emptyInstance()); DomainEventMessage event3 = new GenericDomainEventMessage<String>( identifier, (long) 3, "Mock contents", MetaData.emptyInstance()); when(mockEventStore.readEvents("test", identifier)) .thenReturn( new SimpleDomainEventStream( new GenericDomainEventMessage<String>( identifier, (long) 1, "Mock contents", MetaData.emptyInstance()), event2, event3)); try { testSubject.load(identifier, 1L); fail("Expected ConflictingAggregateVersionException"); } catch (ConflictingAggregateVersionException e) { assertEquals(identifier, e.getAggregateIdentifier()); assertEquals(1L, e.getExpectedVersion()); assertEquals(3L, e.getActualVersion()); } }
/** Ensures that transactions are rolled back when a runtime exception occurs. */ public void testTransactionRolledBackOnRuntimeException() { /* * Create mock entity manager factory which returns a mock * entity manager when asked. */ EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = mock(EntityManager.class); when(emf.create()).thenReturn(em); EntityTransaction tx = mock(EntityTransaction.class); when(em.getTransaction()).thenReturn(tx); Injector injector = Guice.createInjector(new TestModule(emf, true)); OuterTransactedClass outer = injector.getInstance(OuterTransactedClass.class); try { outer.doSomethingInATransaction(); fail("A runtime exception should have been thrown"); } catch (RuntimeException ignored) { } // emf.create should only have been called once. verify(emf).create(); verify(tx).begin(); verify(tx).rollback(); verify(em).close(); }
/** * The error from the user provided Observable is handled by the subscribe try/catch because this * is synchronous * * <p>Result: Passes */ @Test public void testCustomObservableWithErrorInObservableSynchronous() { final AtomicInteger count = new AtomicInteger(); final AtomicReference<Throwable> error = new AtomicReference<>(); // FIXME custom built??? Observable.just("1", "2") .concatWith(Observable.error(() -> new NumberFormatException())) .subscribe( new Observer<String>() { @Override public void onComplete() { System.out.println("completed"); } @Override public void onError(Throwable e) { error.set(e); System.out.println("error"); e.printStackTrace(); } @Override public void onNext(String v) { System.out.println(v); count.incrementAndGet(); } }); assertEquals(2, count.get()); assertNotNull(error.get()); if (!(error.get() instanceof NumberFormatException)) { fail("It should be a NumberFormatException"); } }
@Test public void testAuthenticatesWithAppHandle() { user = createUser( TEST_VISTA_ID, TEST_DIVISION, TEST_DUZ, TEST_REMOTE_HOSTNAME + "(" + TEST_REMOTE_ADDRESS + ")" + TEST_APP_HANDLE, true, true, true, true, new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority("ROLE_TWO")); when(mockUserDetailService.login( TEST_VISTA_ID, TEST_DIVISION, TEST_APP_HANDLE, TEST_REMOTE_ADDRESS, TEST_REMOTE_HOSTNAME)) .thenReturn(user); VistaAuthenticationToken token = new VistaAuthenticationToken( TEST_VISTA_ID, TEST_DIVISION, TEST_APP_HANDLE, TEST_REMOTE_ADDRESS, TEST_REMOTE_HOSTNAME); Authentication result = provider.authenticate(token); if (!(result instanceof VistaAuthenticationToken)) { fail("Should have returned instance of VistaAuthenticationToken"); } assertNotSame(token, result); VistaAuthenticationToken castResult = (VistaAuthenticationToken) result; assertTrue(VistaUserDetails.class.isAssignableFrom(castResult.getPrincipal().getClass())); assertEquals(TEST_VISTA_ID, castResult.getVistaId()); assertNull(castResult.getAccessCode()); assertNull(castResult.getVerifyCode()); assertEquals(TEST_APP_HANDLE, castResult.getAppHandle()); assertEquals(TEST_REMOTE_ADDRESS, castResult.getRemoteAddress()); assertEquals(TEST_REMOTE_HOSTNAME, castResult.getRemoteHostName()); assertEquals( "ROLE_ONE", new ArrayList<GrantedAuthority>(castResult.getAuthorities()).get(0).getAuthority()); assertEquals( "ROLE_TWO", new ArrayList<GrantedAuthority>(castResult.getAuthorities()).get(1).getAuthority()); assertEquals(TEST_REMOTE_HOSTNAME + "(" + TEST_REMOTE_ADDRESS + ")", castResult.getDetails()); verify(mockUserDetailService) .login( TEST_VISTA_ID, TEST_DIVISION, TEST_APP_HANDLE, TEST_REMOTE_ADDRESS, TEST_REMOTE_HOSTNAME); }
public static void assertChain(TestdataChainedObject... chainedObjects) { TestdataChainedObject chainedObject = chainedObjects[0]; for (int i = 1; i < chainedObjects.length; i++) { TestdataChainedEntity chainedEntity = (TestdataChainedEntity) chainedObjects[i]; if (!Objects.equals(chainedObject, chainedEntity.getChainedObject())) { fail( "Chain assertion failed for chainedEntity (" + chainedEntity + ").\n" + "Expected: " + chainedObject + "\n" + "Actual: " + chainedEntity.getChainedObject() + "\n" + "Expected chain: " + Arrays.toString(chainedObjects) + "\n" + "Actual chain: " + Arrays.toString(ArrayUtils.subarray(chainedObjects, 0, i)) + " ... [" + chainedEntity.getChainedObject() + ", " + chainedEntity + "] ..."); } chainedObject = chainedEntity; } }
/** * Set up the {@link ClientSession} to throw an exception when {@link * ClientSession#createProducer(String)} is called. Make sure, we throw up our hands saying "I am * not dealing with this". * * @throws Exception */ @Test(expected = RuntimeException.class) public void eventSinkShouldThrowExceptionWhenProducerCreationFailsInConstructor() throws Exception { doThrow(new HornetQException()).when(mockClientSession.createProducer(anyString())); createEventSink(mockSessionFactory); fail("Runtime exception should have been thrown."); }
@Test @Ignore // very incomplete public void testPathAnalysis() throws SolrServerException, IOException { SolrServer solr = getSolr(); // Not really unit testing the schema here because the path logic in the handler is too relevant // - could be switched to IndexingItemProgress p = mock(IndexingItemProgress.class); CmsRepository repo = new CmsRepository("http://ex.ampl:444/s/rep1"); when(p.getRepository()).thenReturn(repo); when(p.getRevision()).thenReturn(new RepoRevision(35L, new Date())); CmsChangesetItem item = mock(CmsChangesetItem.class); when(item.getPath()) .thenReturn(new CmsItemPath("/dir/doc main.xml")) .thenReturn(new CmsItemPath("/dir sect/doc appendix.xml")); ; IndexingDocIncrementalSolrj doc = new IndexingDocIncrementalSolrj(); when(p.getFields()).thenReturn(doc); when(p.getItem()).thenReturn(item); HandlerPathinfo handlerPathinfo = new HandlerPathinfo(); handlerPathinfo.handle(p); solr.add(doc.getSolrDoc()); fail( "need to test effects of analyzed path* fields and confirm the need for name and extension"); }
@Test public void testExpectedArrayTypeOnRecord() throws Exception { String columnNames = "arrayCol"; String columnTypes = "int"; ArrayWritable hiveRecord = createGroup(createInt(1)); String fileSchema = "message hive_schema {\n" + " optional group arrayCol (LIST) {\n" + " repeated group bag {\n" + " optional int32 array_element;\n" + " }\n" + " }\n" + "}\n"; try { writeParquetRecord(fileSchema, getParquetWritable(columnNames, columnTypes, hiveRecord)); fail(); } catch (RuntimeException e) { assertEquals( "Parquet record is malformed: Invalid data type: expected LIST type, but found: PRIMITIVE", e.getMessage()); } }
@Test public void testExpectedMapTypeOnRecord() throws Exception { String columnNames = "mapCol"; String columnTypes = "int"; ArrayWritable hiveRecord = createGroup(createInt(1)); String fileSchema = "message hive_schema {\n" + " optional group mapCol (MAP) {\n" + " repeated group map (MAP_KEY_VALUE) {\n" + " required binary key;\n" + " optional int32 value;\n" + " }\n" + " }\n" + "}\n"; try { writeParquetRecord(fileSchema, getParquetWritable(columnNames, columnTypes, hiveRecord)); fail(); } catch (RuntimeException e) { assertEquals( "Parquet record is malformed: Invalid data type: expected MAP type, but found: PRIMITIVE", e.getMessage()); } }
@Test public void rejectAllStorageOperationsBeingInInappropriateState() throws Exception { // -- generate list of "inappropriate" states final List<String> states = new LinkedList<>(); final EnumSet<StorageNode.StorageState> allowedStates = EnumSet.of(StorageNode.StorageState.RECOVERING, StorageNode.StorageState.RUNNING); for (StorageNode.StorageState s : StorageNode.StorageState.values()) { if (!allowedStates.contains(s)) { states.add(s.name()); } } // -- for (String s : states) { if (!node.getState().equals(s)) { manageNode(new ControlMessage.Builder().setState(s)); } assertEquals(s, node.getState()); for (StorageOperation op : allOperations) { // TODO: rewrite with Exception Matcher to introduce message checking try { node.onStorageRequest(op); fail(); } catch (IllegalStateException ex) { } } } }
@Test public void testMultipleErrors3() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); ts.onError(new TestException()); ts.onError(new TestException()); try { ts.assertError(new TestException()); } catch (AssertionError ex) { if (!(ex.getCause() instanceof CompositeException)) { fail("Multiple Error present but the reported error doesn't have a composite cause!"); } // expected return; } fail("Multiple Error present but no assertion error!"); }
@Test public void testTakeWithErrorInObserver() { final AtomicInteger count = new AtomicInteger(); final AtomicReference<Throwable> error = new AtomicReference<>(); Observable.just("1", "2", "three", "4") .take(3) .safeSubscribe( new Observer<String>() { @Override public void onComplete() { System.out.println("completed"); } @Override public void onError(Throwable e) { error.set(e); System.out.println("error"); e.printStackTrace(); } @Override public void onNext(String v) { int num = Integer.parseInt(v); System.out.println(num); // doSomething(num); count.incrementAndGet(); } }); assertEquals(2, count.get()); assertNotNull(error.get()); if (!(error.get() instanceof NumberFormatException)) { fail("It should be a NumberFormatException"); } }
@Test public void testAuthenticateFailsIfUserDisabled() { user = createUser("54321.123456789", TEST_DIVISION, TEST_DUZ, null, true, true, true, false); when(mockUserDetailService.login( TEST_VISTA_ID, TEST_DIVISION, TEST_ACCESS, TEST_VERIFY, null, null, TEST_REMOTE_ADDRESS, TEST_REMOTE_HOSTNAME)) .thenReturn(user); VistaAuthenticationToken token = new VistaAuthenticationToken( TEST_VISTA_ID, TEST_DIVISION, TEST_ACCESS, TEST_VERIFY, TEST_REMOTE_ADDRESS, TEST_REMOTE_HOSTNAME); try { provider.authenticate(token); fail("Should have thrown DisabledException"); } catch (DisabledException expected) { assertTrue(true); } }
@Test public void whenPostCommitTaskFails_exceptionThrown() { Transaction tx = new AbstractTransactionImpl(); tx.start(); RuntimeException exception = new RuntimeException(); TransactionLifecycleListener listener = mock(TransactionLifecycleListener.class); doThrow(exception).when(listener).notify(tx, TransactionLifecycleEvent.PostCommit); tx.registerLifecycleListener(listener); try { tx.commit(); fail(); } catch (RuntimeException found) { assertSame(exception, found); } assertIsCommitted(tx); verify(listener, times(1)).notify(tx, TransactionLifecycleEvent.PreCommit); verify(listener, times(1)).notify(tx, TransactionLifecycleEvent.PostCommit); verify(listener, times(0)).notify(tx, TransactionLifecycleEvent.PreAbort); verify(listener, times(0)).notify(tx, TransactionLifecycleEvent.PostAbort); }
@Test public void testDetectsNullBeingReturnedFromAuthenticationDao() { when(mockUserDetailService.login( TEST_VISTA_ID, TEST_DIVISION, TEST_ACCESS, TEST_VERIFY, null, null, TEST_REMOTE_ADDRESS, TEST_REMOTE_HOSTNAME)) .thenReturn(null); VistaAuthenticationToken token = new VistaAuthenticationToken( TEST_VISTA_ID, TEST_DIVISION, TEST_ACCESS, TEST_VERIFY, TEST_REMOTE_ADDRESS, TEST_REMOTE_HOSTNAME); try { provider.authenticate(token); fail("Should have thrown AuthenticationServiceException"); } catch (AuthenticationServiceException expected) { assertEquals( "VistaUserDetailsService returned null, which is an interface contract violation; it should either return an authenticated VistaUserDetails instance or throw an AuthenticationException", expected.getMessage()); } }
@Test public void testLoadUserByUsername() { UserDetails expectedUserDetails = new User( "EXISTING_USER", "PASSWORD", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B")); UserDetails userDetails = userDetailsServiceWrapper.loadUserByUsername("EXISTING_USER"); assertEquals(expectedUserDetails.getPassword(), userDetails.getPassword()); assertEquals(expectedUserDetails.getUsername(), userDetails.getUsername()); assertEquals(expectedUserDetails.isAccountNonExpired(), userDetails.isAccountNonExpired()); assertEquals(expectedUserDetails.isAccountNonLocked(), userDetails.isAccountNonLocked()); assertEquals( expectedUserDetails.isCredentialsNonExpired(), expectedUserDetails.isCredentialsNonExpired()); assertEquals(expectedUserDetails.isEnabled(), userDetails.isEnabled()); assertTrue( HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( expectedUserDetails.getAuthorities(), userDetails.getAuthorities())); try { userDetails = userDetailsServiceWrapper.loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION"); fail("testLoadUserByUsername() - UsernameNotFoundException did not bubble up!"); } catch (UsernameNotFoundException e) { } }
@Test(timeout = 1000L) public void testSynchronousError() { final Observable<Observable<String>> o1 = Observable.error(new RuntimeException("unit test")); final CountDownLatch latch = new CountDownLatch(1); Observable.mergeDelayError(o1) .subscribe( new Observer<String>() { @Override public void onComplete() { fail("Expected onError path"); } @Override public void onError(Throwable e) { latch.countDown(); } @Override public void onNext(String s) { fail("Expected onError path"); } }); try { latch.await(); } catch (InterruptedException ex) { fail("interrupted"); } }
@Test(expected = AccessDeniedException.class) public void accessIsDeniedIfPermissionIsNotGranted() { AclService service = mock(AclService.class); Acl acl = mock(Acl.class); when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(false); // Try a second time with no permissions found when(acl.isGranted(any(List.class), any(List.class), anyBoolean())) .thenThrow(new NotFoundException("")); when(service.readAclById(any(ObjectIdentity.class), any(List.class))).thenReturn(acl); AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class))); provider.setProcessConfigAttribute("MY_ATTRIBUTE"); provider.setMessageSource(new SpringSecurityMessageSource()); provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class)); provider.setProcessDomainObjectClass(Object.class); provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); try { provider.decide( mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()); fail("Expected Exception"); } catch (AccessDeniedException expected) { } // Second scenario with no acls found provider.decide( mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()); }
@Test public void testFormAdd() throws Exception { Form form = new Form(request); assertEquals(0, form.size()); Button button = Button.button("OK"); form.add(button); assertEquals(1, form.size()); TextField field = new TextField("name"); form.add(field, "Name"); form.add(null); // ignored form.add(null, "Name"); // ignored assertEquals(2, form.size()); assertSame(field, form.get(1)); assertSame(field, form.get("name")); assertNull(form.get("x")); assertNull(form.get(null)); try { // cannot add twice form.add(field); fail(); } catch (IllegalStateException e) { } form.setRequired(true); assertTrue(field.isRequired()); form.setReadOnly(true); assertTrue(field.isReadOnly()); assertTrue(form.validate(true)); form.remove(field); assertEquals(1, form.size()); }
@Test public void testResumeNext() { Subscription s = mock(Subscription.class); // Trigger failure on second element TestObservable f = new TestObservable(s, "one", "fail", "two", "three"); Observable<String> w = Observable.create(f); Observable<String> resume = Observable.from("twoResume", "threeResume"); Observable<String> observable = Observable.create(onErrorResumeNextViaObservable(w, resume)); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); observable.subscribe(observer); try { f.t.join(); } catch (InterruptedException e) { fail(e.getMessage()); } verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); verify(observer, times(1)).onNext("one"); verify(observer, Mockito.never()).onNext("two"); verify(observer, Mockito.never()).onNext("three"); verify(observer, times(1)).onNext("twoResume"); verify(observer, times(1)).onNext("threeResume"); }
@Test public void testRestoreWithInterrupt() throws Exception { Configuration taskConfig = new Configuration(); StreamConfig cfg = new StreamConfig(taskConfig); cfg.setTimeCharacteristic(TimeCharacteristic.ProcessingTime); cfg.setStreamOperator(new StreamSource<>(new TestSource())); StreamStateHandle lockingHandle = new InterruptLockingStateHandle(); TaskDeploymentDescriptor tdd = createTaskDeploymentDescriptor(taskConfig, lockingHandle); Task task = createTask(tdd); // start the task and wait until it is in "restore" task.startTaskThread(); IN_RESTORE_LATCH.await(); // trigger cancellation and signal to continue task.cancelExecution(); task.getExecutingThread().join(30000); if (task.getExecutionState() == ExecutionState.CANCELING) { fail("Task is stuck and not canceling"); } assertEquals(ExecutionState.CANCELED, task.getExecutionState()); assertNull(task.getFailureCause()); }
@Test public void testInterruptTerminalEventAwaitAndUnsubscribe() { TestSubscriber<Integer> ts = TestSubscriber.create(); final Thread t0 = Thread.currentThread(); Worker w = Schedulers.computation().createWorker(); try { w.schedule( new Action0() { @Override public void call() { t0.interrupt(); } }, 200, TimeUnit.MILLISECONDS); ts.awaitTerminalEventAndUnsubscribeOnTimeout(5, TimeUnit.SECONDS); if (!ts.isUnsubscribed()) { fail("Did not unsubscribe!"); } } finally { w.unsubscribe(); } }