src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
SubscriptionImpl implements Subscription { public SubscriptionImpl<T> onClose(Runnable e) { onClose = e; return this; } @Override void close(); @Override Subscription awaitCatchup(); Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); Subscription awaitComplete(long waitTimeInMill... | @Test void testOnClose() throws Exception { CountDownLatch l = new CountDownLatch(1); uut.onClose(l::countDown); uut.close(); l.await(); } |
SubscriptionImpl implements Subscription { public static <T> SubscriptionImpl<T> on(@NonNull GenericObserver<T> o) { return new SubscriptionImpl<>(o); } @Override void close(); @Override Subscription awaitCatchup(); Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); Subscription ... | @Test void testOnNull() { Assertions.assertThrows(NullPointerException.class, () -> { SubscriptionImpl.on(null); }); }
@Test void testOn() { SubscriptionImpl<Integer> on = SubscriptionImpl.on(obs); verify(obs, never()).onNext(any()); on.notifyElement(1); verify(obs).onNext(1); verify(obs, never()).onCatchup(); on.notif... |
ReconnectingFactSubscriptionWrapper implements Subscription { @Override public Subscription awaitComplete() throws SubscriptionCancelledException { for (;;) { assertSubscriptionStateNotClosed(); Subscription cur = currentSubscription.get(); if (cur != null) { try { cur.awaitComplete(); return this; } catch (Subscriptio... | @Test public void testAwaitComplete() throws Exception { observerAC.getValue().onComplete(); assertTimeout(Duration.ofMillis(1000), () -> { uut.awaitComplete(); }); }
@Test public void testAwaitCompleteLong() throws Exception { when(subscription.awaitComplete(anyLong())).thenThrow(TimeoutException.class) .then(x -> sub... |
ReconnectingFactSubscriptionWrapper implements Subscription { @Override public Subscription awaitCatchup() throws SubscriptionCancelledException { for (;;) { assertSubscriptionStateNotClosed(); Subscription cur = currentSubscription.get(); if (cur != null) { try { cur.awaitCatchup(); return this; } catch (SubscriptionC... | @Test public void testAwaitCatchup() throws Exception { observerAC.getValue().onCatchup(); assertTimeout(Duration.ofMillis(1000), () -> { uut.awaitCatchup(); }); }
@Test public void testAwaitCatchupLong() throws Exception { when(subscription.awaitCatchup(anyLong())).thenThrow(TimeoutException.class) .then(x -> subscrip... |
ReconnectingFactSubscriptionWrapper implements Subscription { private void assertSubscriptionStateNotClosed() { if (closed.get()) { throw new SubscriptionCancelledException("Subscription already cancelled"); } } ReconnectingFactSubscriptionWrapper(@NonNull FactStore store,
@NonNull SubscriptionRequestTO req... | @Test public void testAssertSubscriptionStateNotClosed() throws Exception { uut.close(); assertThrows(SubscriptionCancelledException.class, () -> { uut.awaitCatchup(); }); assertThrows(SubscriptionCancelledException.class, () -> { uut.awaitCatchup(1L); }); assertThrows(SubscriptionCancelledException.class, () -> { uut.... |
CondensedQueryExecutor { public void trigger() { if (connectionStateSupplier.get()) { if (maxDelayInMillis < 1) { runTarget(); } else if (!currentlyScheduled.getAndSet(true)) { timer.schedule(new TimerTask() { @Override public void run() { currentlyScheduled.set(false); try { CondensedQueryExecutor.this.runTarget(); } ... | @Test void testDelayedExecution() { CondensedQueryExecutor uut = new CondensedQueryExecutor(1, callback, () -> true, mockTimer); uut.trigger(); verify(mockTimer).schedule(any(), eq(1L)); task.getValue().run(); verify(callback).run(anyBoolean()); }
@Test void testDelayedMultipleExecution() { CondensedQueryExecutor uut =... |
FluentSubscriptionRequest implements SubscriptionRequest { @Override public String toString() { return debugInfo; } FluentSubscriptionRequest(); @Override java.util.Optional<UUID> startingAfter(); @Override String toString(); } | @Test void testToString() { SubscriptionRequest r = SubscriptionRequest.catchup(FactSpec.ns("foo")).fromScratch(); assertSame(r.debugInfo(), r.toString()); } |
SubscriptionRequestTO implements SubscriptionRequest { public static SubscriptionRequestTO forFacts(SubscriptionRequest request) { SubscriptionRequestTO t = new SubscriptionRequestTO(request); t.idOnly(false); return t; } SubscriptionRequestTO(SubscriptionRequest request); boolean hasAnyScriptFilters(); @Override java.... | @Test void testDebugInfo() { SubscriptionRequest r = SubscriptionRequest.catchup(FactSpec.ns("foo")).fromScratch(); SubscriptionRequestTO uut = SubscriptionRequestTO.forFacts(r); assertEquals(r.debugInfo(), uut.debugInfo()); }
@Test void testMaxDelay() { final FactSpec s = FactSpec.ns("foo"); SubscriptionRequest r = Su... |
SubscriptionRequestTO implements SubscriptionRequest { @Override public String toString() { return debugInfo; } SubscriptionRequestTO(SubscriptionRequest request); boolean hasAnyScriptFilters(); @Override java.util.Optional<UUID> startingAfter(); static SubscriptionRequestTO forFacts(SubscriptionRequest request); stati... | @Test void testToString() { SubscriptionRequest r = SubscriptionRequest.catchup(FactSpec.ns("foo")).fromScratch(); String debugInfo = r.debugInfo(); SubscriptionRequestTO uut = SubscriptionRequestTO.forFacts(r); assertEquals(debugInfo, uut.toString()); } |
SubscriptionRequestTO implements SubscriptionRequest { public boolean hasAnyScriptFilters() { return specs.stream().anyMatch(s -> s.jsFilterScript() != null); } SubscriptionRequestTO(SubscriptionRequest request); boolean hasAnyScriptFilters(); @Override java.util.Optional<UUID> startingAfter(); static SubscriptionReque... | @Test void testHasAnyScriptFilters() { final FactSpec s = FactSpec.ns("foo"); SubscriptionRequest r = SubscriptionRequest.catchup(s).fromScratch(); SubscriptionRequestTO uut = SubscriptionRequestTO.forFacts(r); assertFalse(uut.hasAnyScriptFilters()); uut.addSpecs(Collections.singletonList(FactSpec.ns("buh").jsFilterScr... |
SubscriptionRequestTO implements SubscriptionRequest { public void addSpecs(@NonNull List<FactSpec> factSpecs) { checkArgument(!factSpecs.isEmpty()); specs.addAll(factSpecs); } SubscriptionRequestTO(SubscriptionRequest request); boolean hasAnyScriptFilters(); @Override java.util.Optional<UUID> startingAfter(); static S... | @Test void testAddSpecs() { final FactSpec s = FactSpec.ns("foo"); SubscriptionRequest r = SubscriptionRequest.catchup(s).fromScratch(); SubscriptionRequestTO uut = SubscriptionRequestTO.forFacts(r); assertEquals(1, uut.specs().size()); final String js = "function (h,e){ return true }"; uut.addSpecs(Collections.singlet... |
Lz4GrpcServerCodec implements Codec { @Override public String getMessageEncoding() { return "lz4"; } @Override String getMessageEncoding(); @Override InputStream decompress(InputStream inputStream); @Override OutputStream compress(OutputStream outputStream); } | @Test void getMessageEncoding() { assertEquals("lz4", uut.getMessageEncoding()); } |
SnappyGrpcServerCodec implements Codec { @Override public String getMessageEncoding() { return "snappy"; } @Override String getMessageEncoding(); @Override InputStream decompress(InputStream inputStream); @Override OutputStream compress(OutputStream outputStream); } | @Test void getMessageEncoding() { assertEquals("snappy", uut.getMessageEncoding()); } |
BlockingStreamObserver implements StreamObserver<T> { @Override public void onCompleted() { delegate.onCompleted(); } BlockingStreamObserver(@NonNull String id, @NonNull ServerCallStreamObserver<T> delegate); @Override void onNext(T value); @Override void onError(Throwable t); @Override void onCompleted(); } | @Test void testOnCompleted() { verify(delegate, never()).onCompleted(); uut.onCompleted(); verify(delegate).onCompleted(); } |
BlockingStreamObserver implements StreamObserver<T> { @Override public void onError(Throwable t) { delegate.onError(t); } BlockingStreamObserver(@NonNull String id, @NonNull ServerCallStreamObserver<T> delegate); @Override void onNext(T value); @Override void onError(Throwable t); @Override void onCompleted(); } | @Test void testOnError() { verify(delegate, never()).onError(any()); uut.onError(new Exception()); verify(delegate).onError(any()); } |
PgConfigurationProperties implements ApplicationListener<ApplicationReadyEvent> { public int getQueueSizeForIds() { return queueSize * idOnlyFactor; } int getPageSizeForIds(); int getQueueSizeForIds(); int getFetchSizeForIds(); int getFetchSize(); @Override void onApplicationEvent(ApplicationReadyEvent event); } | @Test void testGetQueueSizeForIds() { assertEquals(100000, uut.getQueueSizeForIds()); } |
BlockingStreamObserver implements StreamObserver<T> { @Override public void onNext(T value) { if (!delegate.isCancelled()) { synchronized (lock) { if (!delegate.isReady()) { for (int i = 1; i <= RETRY_COUNT; i++) { log.debug("{} channel not ready. Slow client? Attempt: {}/{}", id, i, RETRY_COUNT); try { lock.wait(WAIT_... | @Test void testOnNextWhenReady() { when(delegate.isReady()).thenReturn(true); uut.onNext(new Object()); verify(delegate).onNext(any()); } |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override @Secured(FactCastRole.WRITE) public void publish(@NonNull MSG_Facts request, StreamObserver<MSG_Empty> responseObserver) { List<Fact> facts = request.getFactList() .stream() .map(converter::fromProto) .collect( Collectors.toList()); final int size = facts... | @Test void testPublishNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.publish(null, mock(StreamObserver.class)); }); }
@Test void testPublishNone() { doNothing().when(backend).publish(acFactList.capture()); MSG_Facts r = MSG_Facts.newBuilder().build(); uut.publish(r, mock(StreamObserver.class))... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override public void fetchById(MSG_UUID request, StreamObserver<MSG_OptionalFact> responseObserver) { try { enableResponseCompression(responseObserver); UUID fromProto = converter.fromProto(request); log.trace("fetchById {}", fromProto); Optional<Fact> fetchById =... | @Test void testFetchById() { UUID id = UUID.randomUUID(); uut.fetchById(conv.toProto(id), mock(ServerCallStreamObserver.class)); verify(backend).fetchById(eq(id)); }
@Test void testFetchByIdThrows() { UUID id = UUID.randomUUID(); when(backend.fetchById(any(UUID.class))).thenThrow(UnsupportedOperationException.class); S... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override public void subscribe(MSG_SubscriptionRequest request, StreamObserver<MSG_Notification> responseObserver) { enableResponseCompression(responseObserver); SubscriptionRequestTO req = converter.fromProto(request); resetDebugInfo(req); BlockingStreamObserver<... | @Test void testSubscribeFacts() { SubscriptionRequest req = SubscriptionRequest.catchup(FactSpec.ns("foo")).fromNowOn(); when(backend.subscribe(this.reqCaptor.capture(), any())).thenReturn(null); uut.subscribe(new ProtoConverter().toProto(SubscriptionRequestTO.forFacts(req)), mock(ServerCallStreamObserver.class)); veri... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override public void serialOf(MSG_UUID request, StreamObserver<MSG_OptionalSerial> responseObserver) { OptionalLong serialOf = store.serialOf(converter.fromProto(request)); responseObserver.onNext(converter.toProto(serialOf)); responseObserver.onCompleted(); } @O... | @Test public void testSerialOf() throws Exception { uut = new FactStoreGrpcService(backend); StreamObserver so = mock(StreamObserver.class); assertThrows(NullPointerException.class, () -> { uut.serialOf(null, so); }); UUID id = new UUID(0, 1); OptionalLong twenty_two = OptionalLong.of(22); when(backend.serialOf(id)).th... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override public void enumerateNamespaces(MSG_Empty request, StreamObserver<MSG_StringSet> responseObserver) { try { responseObserver.onNext(converter.toProto(store.enumerateNamespaces())); responseObserver.onCompleted(); } catch (Throwable e) { responseObserver.on... | @Test public void testEnumerateNamespaces() throws Exception { uut = new FactStoreGrpcService(backend); StreamObserver so = mock(StreamObserver.class); when(backend.enumerateNamespaces()).thenReturn(Sets.newHashSet("foo", "bar")); uut.enumerateNamespaces(conv.empty(), so); verify(so).onCompleted(); verify(so).onNext(eq... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override public void enumerateTypes(MSG_String request, StreamObserver<MSG_StringSet> responseObserver) { enableResponseCompression(responseObserver); try { Set<String> types = store.enumerateTypes(converter.fromProto( request)); responseObserver.onNext(converter.... | @Test public void testEnumerateTypes() throws Exception { uut = new FactStoreGrpcService(backend); StreamObserver so = mock(StreamObserver.class); when(backend.enumerateTypes(eq("ns"))).thenReturn(Sets.newHashSet("foo", "bar")); uut.enumerateTypes(conv.toProto("ns"), so); verify(so).onCompleted(); verify(so).onNext(eq(... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override public void handshake(MSG_Empty request, StreamObserver<MSG_ServerConfig> responseObserver) { ServerConfig cfg = ServerConfig.of(PROTOCOL_VERSION, collectProperties()); responseObserver.onNext(converter.toProto(cfg)); responseObserver.onCompleted(); } @O... | @Test public void testHandshake() throws Exception { StreamObserver so = mock(StreamObserver.class); uut.handshake(conv.empty(), so); verify(so).onCompleted(); verify(so).onNext(any(MSG_ServerConfig.class)); } |
FactStoreGrpcService extends RemoteFactStoreImplBase { @VisibleForTesting void retrieveImplementationVersion(HashMap<String, String> properties) { String implVersion = "UNKNOWN"; URL propertiesUrl = getProjectProperties(); Properties buildProperties = new Properties(); if (propertiesUrl != null) { try { InputStream is ... | @Test public void testRetrieveImplementationVersion() throws Exception { uut = spy(uut); when(uut.getProjectProperties()).thenReturn(this.getClass() .getResource( "/test.properties")); HashMap<String, String> map = new HashMap<>(); uut.retrieveImplementationVersion(map); assertEquals("9.9.9", map.get(Capabilities.FACTC... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override @Secured(FactCastRole.WRITE) public void invalidate(MSG_UUID request, StreamObserver<MSG_Empty> responseObserver) { try { UUID tokenId = converter.fromProto(request); store.invalidate(new StateToken(tokenId)); responseObserver.onNext(MSG_Empty.getDefaultI... | @Test public void testInvalidate() throws Exception { { UUID id = UUID.randomUUID(); MSG_UUID req = conv.toProto(id); StreamObserver o = mock(StreamObserver.class); uut.invalidate(req, o); verify(backend).invalidate(eq(new StateToken(id))); verify(o).onNext(any()); verify(o).onCompleted(); } { doThrow(new StatusRuntime... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override @Secured(FactCastRole.WRITE) public void stateFor(MSG_StateForRequest request, StreamObserver<MSG_UUID> responseObserver) { try { StateForRequest req = converter.fromProto(request); StateToken token = store.stateFor(req.aggIds(), Optional.ofNullable(req.n... | @Test public void testStateFor() throws Exception { { UUID id = UUID.randomUUID(); StateForRequest sfr = new StateForRequest(Lists.newArrayList(id), "foo"); MSG_StateForRequest req = conv.toProto(sfr); StreamObserver o = mock(StreamObserver.class); UUID token = UUID.randomUUID(); when(backend.stateFor(any(), any())).th... |
FactStoreGrpcService extends RemoteFactStoreImplBase { @Override @Secured(FactCastRole.WRITE) public void publishConditional(MSG_ConditionalPublishRequest request, StreamObserver<MSG_ConditionalPublishResult> responseObserver) { try { ConditionalPublishRequest req = converter.fromProto(request); boolean result = store.... | @Test public void testPublishConditional() throws Exception { { UUID id = UUID.randomUUID(); ConditionalPublishRequest sfr = new ConditionalPublishRequest(Lists.newArrayList(), id); MSG_ConditionalPublishRequest req = conv.toProto(sfr); StreamObserver o = mock(StreamObserver.class); when(backend.publishIfUnchanged(any(... |
PgListener implements InitializingBean, DisposableBean { private void listen() { log.trace("Starting instance Listener"); CountDownLatch l = new CountDownLatch(1); listenerThread = new Thread(() -> { while (running.get()) { postEvent("scheduled-poll"); try (PgConnection pc = pgConnectionSupplier.get()) { while (running... | @Test void testListen() throws Exception { Mockito.when(ds.get()).thenReturn(conn); Mockito.when(conn.prepareStatement(anyString())).thenReturn(ps); PgListener l = new PgListener(ds, bus, tester); l.afterPropertiesSet(); sleep(100); verify(bus).post(any(FactInsertionEvent.class)); verifyNoMoreInteractions(bus); verify(... |
GrpcCompressionInterceptor implements ServerInterceptor { @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { codecs.selectFrom(headers.get(GRPC_ACCEPT_ENCODING)).ifPresent(c -> { call.setCompression(c); call.setMessageCompre... | @Test void interceptCallWithoutCompression() { ServerCall call = mock(ServerCall.class); Metadata metadata = mock(Metadata.class); ServerCallHandler next = mock(ServerCallHandler.class); uut.interceptCall(call, metadata, next); verify(next).startCall(call, metadata); verifyNoMoreInteractions(call); verifyNoMoreInteract... |
GrpcObserverAdapter implements FactObserver { @Override public void onComplete() { log.info("{} onComplete – sending complete notification", id); observer.onNext(converter.createCompleteNotification()); tryComplete(); } @Override void onComplete(); @Override void onError(Throwable e); @Override void onCatchup(); @Over... | @Test void testOnComplete() { GrpcObserverAdapter uut = new GrpcObserverAdapter("foo", observer, projection); uut.onComplete(); verify(observer).onCompleted(); }
@Test void testOnCompleteWithException() { GrpcObserverAdapter uut = new GrpcObserverAdapter("foo", observer, projection); doThrow(UnsupportedOperationExcepti... |
GrpcObserverAdapter implements FactObserver { @Override public void onCatchup() { log.info("{} onCatchup – sending catchup notification", id); observer.onNext(converter.createCatchupNotification()); } @Override void onComplete(); @Override void onError(Throwable e); @Override void onCatchup(); @Override void onNext(Fa... | @Test void testOnCatchup() { GrpcObserverAdapter uut = new GrpcObserverAdapter("foo", observer, projection); doNothing().when(observer).onNext(msg.capture()); verify(observer, never()).onNext(any()); uut.onCatchup(); verify(observer).onNext(any()); assertEquals(MSG_Notification.Type.Catchup, msg.getValue().getType()); ... |
GrpcObserverAdapter implements FactObserver { @Override public void onError(Throwable e) { log.warn("{} onError – sending Error notification {}", id, e.getMessage()); observer.onError(e); tryComplete(); } @Override void onComplete(); @Override void onError(Throwable e); @Override void onCatchup(); @Override void onNex... | @Test void testOnError() { GrpcObserverAdapter uut = new GrpcObserverAdapter("foo", observer, projection); verify(observer, never()).onNext(any()); uut.onError(new Exception()); verify(observer).onError(any()); } |
GrpcObserverAdapter implements FactObserver { @Override public void onNext(Fact element) { observer.onNext(projection.apply(element)); } @Override void onComplete(); @Override void onError(Throwable e); @Override void onCatchup(); @Override void onNext(Fact element); } | @Test void testOnNext() { ProtoConverter conv = new ProtoConverter(); GrpcObserverAdapter uut = new GrpcObserverAdapter("foo", observer, conv::createNotificationFor); doNothing().when(observer).onNext(msg.capture()); verify(observer, never()).onNext(any()); Fact f = Fact.builder().ns("test").build("{}"); uut.onNext(f);... |
PgListener implements InitializingBean, DisposableBean { @Override public void destroy() { this.running.set(false); if (listenerThread != null) { listenerThread.interrupt(); } } @Override void afterPropertiesSet(); @Override void destroy(); } | @Test void testStopWithoutStarting() { PgListener l = new PgListener(ds, bus, tester); l.destroy(); verifyNoMoreInteractions(conn); } |
PgConnectionSupplier { @VisibleForTesting Properties buildPgConnectionProperties(org.apache.tomcat.jdbc.pool.DataSource ds) { Properties dbp = new Properties(); final PoolConfiguration poolProperties = ds.getPoolProperties(); if (poolProperties != null) { setProperty(dbp, "user", poolProperties.getUsername()); setPrope... | @Test void test_noRelevantPropertySet() { setupConnectionProperties("sockettimeout=30"); uut.buildPgConnectionProperties(ds); }
@Test void test_propertySyntaxBroken() { Assertions.assertThrows(IllegalArgumentException.class, () -> { setupConnectionProperties("sockettimeout:30"); uut.buildPgConnectionProperties(ds); });... |
RdsDataSourceFactoryBeanPostProcessor implements BeanPostProcessor { @Override @NonNull public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException { return bean; } @Override @NonNull Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String bea... | @Test public void shouldReturnFromAfterInitSameBeanAsPassed() throws Exception { UUID instance = UUID.randomUUID(); Object afterInit = uut.postProcessAfterInitialization(instance, "foo"); assertThat(afterInit).isSameAs(instance); } |
RdsDataSourceFactoryBeanPostProcessor implements BeanPostProcessor { @Override @NonNull public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException { if (bean instanceof AmazonRdsDataSourceFactoryBean) { ((AmazonRdsDataSourceFactoryBean) bean).setDataSourceFactory... | @Test public void shouldReturnFromBeforeSameBeanAsPassed() throws Exception { UUID instance = UUID.randomUUID(); Object beforeInit = uut.postProcessBeforeInitialization(instance, "foo"); assertThat(beforeInit).isSameAs(instance); }
@Test public void shouldReplaceJdbcCP() throws Exception { AmazonRdsDataSourceFactoryBea... |
PgConfigurationProperties implements ApplicationListener<ApplicationReadyEvent> { public int getFetchSizeForIds() { return getQueueSizeForIds() / queueFetchRatio; } int getPageSizeForIds(); int getQueueSizeForIds(); int getFetchSizeForIds(); int getFetchSize(); @Override void onApplicationEvent(ApplicationReadyEvent e... | @Test void testGetFetchSizeForIds() { assertEquals(25000, uut.getFetchSizeForIds()); } |
InMemFact extends DefaultFact { @Override public String toString() { return FactCastJson.writeValueAsPrettyString(this); } InMemFact(long ser, Fact toCopyFrom); @Override String toString(); } | @Test public void testToString() throws Exception { Fact f = Fact.of("{\"ns\":\"someNs\",\"id\":\"" + UUID.randomUUID() + "\"}", "{}"); InMemFact f1 = new InMemFact(32, f); Fact d = FactCastJson.readValue(DefaultFact.class, f1.toString()); Fact fact = Fact.of(d.jsonHeader(), d.jsonPayload()); InMemFact f2 = new InMemFa... |
FactRenderer { public String render(Fact f) { return "Fact: id=" + f.id() + CR + TAB + "header: " + renderJson(f.jsonHeader()).replaceAll( CR, CR + TAB + TAB) + CR + TAB + "payload: " + renderJson(f.jsonPayload()).replaceAll(CR, CR + TAB + TAB) + CR + CR; } String render(Fact f); } | @Test void testRender() throws Exception { FactRenderer uut = new FactRenderer(new Options()); assertEquals("Fact: id=00000000-0000-0000-0000-000000000000\n" + " header: {\"id\":\"00000000-0000-0000-0000-000000000000\",\"ns\":\"ns\",\"type\":\"type\",\"aggIds\":[\"00000000-0000-0000-0000-000000000001\"],\"meta\":{\"foo... |
Catchup implements Command { @Override public void runWith(FactCast fc, Options opt) { ConsoleFactObserver obs = new ConsoleFactObserver(opt); SpecBuilder catchup = SubscriptionRequest.catchup(FactSpec.ns(ns)); if (from == null) fc.subscribeEphemeral(catchup.fromScratch(), obs); else fc.subscribeEphemeral(catchup.from(... | @Test void testCatchup() { String ns = "foo"; UUID startId = new UUID(0, 1); Catchup cmd = new Catchup(ns, startId); fc = spy(FactCast.from(fs)); Options opt = new Options(); when(fs.subscribe(any(), any(ConsoleFactObserver.class))).thenAnswer(invocation -> { Object[] args = invocation.getArguments(); GenericObserver<?... |
ProtoConverter { @NonNull public MSG_UUID toProto(@NonNull UUID id) { return MSG_UUID.newBuilder() .setLsb(id.getLeastSignificantBits()) .setMsb(id.getMostSignificantBits()) .build(); } MSG_Notification createCatchupNotification(); MSG_Notification createCompleteNotification(); MSG_Notification createNotificationFor(@... | @Test void testToProtoUUIDNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.toProto((UUID) null); }); }
@Test void testToProtoFactNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.toProto((Fact) null); }); }
@Test void testToProtoFacts_empty() { MSG_Facts proto = uut.toProt... |
ProtoConverter { public SubscriptionRequestTO fromProto(@NonNull MSG_SubscriptionRequest request) { return FactCastJson.readValue(SubscriptionRequestTO.class, request.getJson()); } MSG_Notification createCatchupNotification(); MSG_Notification createCompleteNotification(); MSG_Notification createNotificationFor(@NonNu... | @Test void testFromProtoOptionalNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.fromProto((MSG_OptionalFact) null); }); }
@Test void testFromProtoMSG_SubscriptionRequestNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.fromProto((MSG_SubscriptionRequest) null); }); }
@Tes... |
ProtoConverter { public MSG_Notification createCatchupNotification() { return MSG_Notification.newBuilder().setType(MSG_Notification.Type.Catchup).build(); } MSG_Notification createCatchupNotification(); MSG_Notification createCompleteNotification(); MSG_Notification createNotificationFor(@NonNull Fact t); MSG_Notific... | @Test void testCreateCatchupNotification() { MSG_Notification n = uut.createCatchupNotification(); assertNotNull(n); assertEquals(MSG_Notification.Type.Catchup, n.getType()); } |
PgConfigurationProperties implements ApplicationListener<ApplicationReadyEvent> { public int getFetchSize() { return getQueueSize() / queueFetchRatio; } int getPageSizeForIds(); int getQueueSizeForIds(); int getFetchSizeForIds(); int getFetchSize(); @Override void onApplicationEvent(ApplicationReadyEvent event); } | @Test void testGetFetchSize() { assertEquals(250, uut.getFetchSize()); } |
ProtoConverter { public MSG_Notification createCompleteNotification() { return MSG_Notification.newBuilder().setType(MSG_Notification.Type.Complete).build(); } MSG_Notification createCatchupNotification(); MSG_Notification createCompleteNotification(); MSG_Notification createNotificationFor(@NonNull Fact t); MSG_Notif... | @Test void testCreateCompleteNotification() { MSG_Notification n = uut.createCompleteNotification(); assertNotNull(n); assertEquals(MSG_Notification.Type.Complete, n.getType()); } |
ProtoConverter { public MSG_Notification createNotificationFor(@NonNull Fact t) { MSG_Notification.Builder builder = MSG_Notification.newBuilder() .setType(MSG_Notification.Type.Fact); builder.setFact(toProto(t)); return builder.build(); } MSG_Notification createCatchupNotification(); MSG_Notification createCompleteNo... | @Test void testCreateNotificationForFactNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.createNotificationFor((Fact) null); }); }
@Test void testCreateNotificationForIdNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.createNotificationFor((UUID) null); }); } |
ProtoConverter { public MSG_Empty empty() { return EMPTY; } MSG_Notification createCatchupNotification(); MSG_Notification createCompleteNotification(); MSG_Notification createNotificationFor(@NonNull Fact t); MSG_Notification createNotificationFor(@NonNull UUID id); @NonNull MSG_UUID toProto(@NonNull UUID id); Subscr... | @Test void testEmpty() { assertEquals(MSG_Empty.newBuilder().build(), uut.empty()); } |
PgQueryBuilder { public PgQueryBuilder(@NonNull SubscriptionRequestTO request) { this.req = request; selectIdOnly = request.idOnly() && !request.hasAnyScriptFilters(); } PgQueryBuilder(@NonNull SubscriptionRequestTO request); PreparedStatementSetter createStatementSetter(@NonNull AtomicLong serial); String createSQL();... | @Test public void testPGQueryBuilder() throws Exception { assertThrows(NullPointerException.class, () -> { new PgQueryBuilder(null); }); PgQueryBuilder uut = new PgQueryBuilder(mock(SubscriptionRequestTO.class)); assertThrows(NullPointerException.class, () -> { uut.createStatementSetter(null); }); } |
ProtocolVersion { public boolean isCompatibleTo(ProtocolVersion other) { return (major == other.major) && (minor <= other.minor); } boolean isCompatibleTo(ProtocolVersion other); @Override String toString(); } | @Test void testIsCompatibleTo() { assertTrue(ProtocolVersion.of(1, 0, 0).isCompatibleTo(ProtocolVersion.of(1, 0, 0))); assertTrue(ProtocolVersion.of(1, 0, 0).isCompatibleTo(ProtocolVersion.of(1, 0, 1))); assertTrue(ProtocolVersion.of(1, 0, 0).isCompatibleTo(ProtocolVersion.of(1, 1, 0))); assertFalse(ProtocolVersion.of(... |
ProtocolVersion { @Override public String toString() { StringJoiner joiner = new StringJoiner("."); joiner.add(String.valueOf(major)).add(String.valueOf(minor)).add(String.valueOf(patch)); return joiner.toString(); } boolean isCompatibleTo(ProtocolVersion other); @Override String toString(); } | @Test void testToString() { assertEquals("3.1.2", ProtocolVersion.of(3, 1, 2).toString()); } |
PgSynchronizedQuery { @SuppressWarnings("SameReturnValue") public synchronized void run(boolean useIndex) { long latest = latestFetcher.retrieveLatestSer(); transactionTemplate.execute(status -> { if (!useIndex) jdbcTemplate.execute("SET LOCAL enable_bitmapscan=0;"); jdbcTemplate.query(sql, setter, rowHandler); return ... | @Test public void testRunWithIndex() throws Exception { uut = new PgSynchronizedQuery(jdbcTemplate, sql, setter, rowHandler, serialToContinueFrom, fetcher); uut.run(true); verify(jdbcTemplate, never()).execute(startsWith("SET LOCAL enable_bitmapscan")); }
@Test public void testRunWithoutIndex() throws Exception { uut =... |
SnappyGrpcClientCodec implements Codec { @Override public String getMessageEncoding() { return "snappy"; } @Override String getMessageEncoding(); @Override OutputStream compress(OutputStream os); @Override InputStream decompress(InputStream is); } | @Test void getMessageEncoding() { assertEquals("snappy", uut.getMessageEncoding()); } |
Lz4GrpcClientCodec implements Codec { @Override public String getMessageEncoding() { return "lz4"; } @Override String getMessageEncoding(); @Override InputStream decompress(InputStream inputStream); @Override OutputStream compress(OutputStream outputStream); } | @Test void getMessageEncoding() { assertEquals("lz4", uut.getMessageEncoding()); } |
ClientStreamObserver implements StreamObserver<FactStoreProto.MSG_Notification> { @Override public void onNext(MSG_Notification f) { log.trace("observer got msg: {}", f); switch (f.getType()) { case Catchup: log.debug("received onCatchup signal"); subscription.notifyCatchup(); break; case Complete: log.debug("received ... | @Test void testOnNext() { Fact f = Fact.of("{\"ns\":\"ns\",\"id\":\"" + UUID.randomUUID() + "\"}", "{}"); MSG_Notification n = converter.createNotificationFor(f); uut.onNext(n); verify(factObserver).onNext(eq(f)); }
@Test void testOnNextFailsOnUnknownMessage() { assertThrows(IllegalArgumentException.class, () -> { MSG_... |
ClientStreamObserver implements StreamObserver<FactStoreProto.MSG_Notification> { @Override public void onCompleted() { subscription.notifyComplete(); } @Override void onNext(MSG_Notification f); @Override void onError(Throwable t); @Override void onCompleted(); } | @Test void testOnTransportComplete() { uut.onCompleted(); verify(factObserver).onComplete(); } |
ClientStreamObserver implements StreamObserver<FactStoreProto.MSG_Notification> { @Override public void onError(Throwable t) { subscription.notifyError(t); } @Override void onNext(MSG_Notification f); @Override void onError(Throwable t); @Override void onCompleted(); } | @Test void testOnError() { uut.onError(new IOException()); verify(factObserver).onError(any()); } |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public Optional<Fact> fetchById(UUID id) { log.trace("fetching {} from remote store", id); MSG_OptionalFact fetchById; try { fetchById = blockingStub.fetchById(converter.toProto(id)); } catch (StatusRuntimeException e) { throw wrapRetryable(e); ... | @Test void testFetchByIdNotFound() { UUID id = UUID.randomUUID(); when(blockingStub.fetchById(eq(conv.toProto(id)))).thenReturn(conv.toProto(Optional .empty())); Optional<Fact> fetchById = uut.fetchById(id); assertFalse(fetchById.isPresent()); }
@Test void testFetchByIdFound() { UUID id = UUID.randomUUID(); when(blocki... |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public void publish(@NonNull List<? extends Fact> factsToPublish) { log.trace("publishing {} facts to remote store", factsToPublish.size()); List<MSG_Fact> mf = factsToPublish.stream() .map(converter::toProto) .collect(Collectors .toList()); MSG... | @Test void testPublish() { when(blockingStub.publish(factsCap.capture())).thenReturn(MSG_Empty.newBuilder().build()); final TestFact fact = new TestFact(); uut.publish(Collections.singletonList(fact)); verify(blockingStub).publish(any()); final MSG_Facts pfacts = factsCap.getValue(); Fact published = conv.fromProto(pfa... |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @VisibleForTesting void configureCompression(String codecListFromServer) { codecs.selectFrom(codecListFromServer).ifPresent(c -> { log.info("configuring Codec " + c); this.blockingStub = blockingStub.withCompression(c); this.stub = stub.withCompression(c)... | @Test void configureCompressionChooseGzipIfAvail() { uut.configureCompression(" gzip,lz3,lz4, lz99"); verify(stub).withCompression("gzip"); }
@Test void configureCompressionSkipCompression() { uut.configureCompression("zip,lz3,lz4, lz99"); verifyNoMoreInteractions(stub); } |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @VisibleForTesting void cancel(final ClientCall<MSG_SubscriptionRequest, MSG_Notification> call) { call.cancel("Client is no longer interested", null); } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Autowired @Generated GrpcFactStore(FactCast... | @SuppressWarnings("unchecked") @Test void testCancelNotRetryableExceptionOnUnavailableStatus() { ClientCall<MSG_SubscriptionRequest, MSG_Notification> call = mock(ClientCall.class); doThrow(new StatusRuntimeException(Status.UNAVAILABLE)).when(call).cancel(any(), any()); assertThrows(StatusRuntimeException.class, () -> ... |
PgFactStream { void connect(@NonNull SubscriptionRequestTO request) { this.request = request; log.debug("{} connecting subscription {}", request, request.dump()); postQueryMatcher = new PgPostQueryMatcher(request); PgQueryBuilder q = new PgQueryBuilder(request); initializeSerialToStartAfter(); String sql = q.createSQL(... | @Test public void testConnectNullParameter() throws Exception { assertThrows(NullPointerException.class, () -> { uut.connect(null); }); } |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public OptionalLong serialOf(@NonNull UUID l) { MSG_UUID protoMessage = converter.toProto(l); MSG_OptionalSerial responseMessage; try { responseMessage = blockingStub.serialOf(protoMessage); } catch (StatusRuntimeException e) { throw wrapRetryab... | @Test void testSerialOfPropagatesRetryableExceptionOnUnavailableStatus() { when(blockingStub.serialOf(any())).thenThrow(new StatusRuntimeException( Status.UNAVAILABLE)); assertThrows(RetryableException.class, () -> uut.serialOf(mock(UUID.class))); }
@Test void testSerialOf() { OptionalLong seven = OptionalLong.of(7); w... |
GrpcFactStore implements FactStore, SmartInitializingSingleton { public synchronized void initialize() { if (!initialized.getAndSet(true)) { log.debug("Invoking handshake"); Map<String, String> serverProperties; ProtocolVersion serverProtocolVersion; try { ServerConfig cfg = converter.fromProto(blockingStub.handshake(c... | @Test void testInitializePropagatesRetryableExceptionOnUnavailableStatus() { when(blockingStub.handshake(any())).thenThrow(new StatusRuntimeException( Status.UNAVAILABLE)); assertThrows(RetryableException.class, () -> uut.initialize()); }
@Test void testCompatibleProtocolVersion() { when(blockingStub.handshake(any())) ... |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public Set<String> enumerateTypes(String ns) { MSG_String ns_message = converter.toProto(ns); MSG_StringSet resp; try { resp = blockingStub.enumerateTypes(ns_message); } catch (StatusRuntimeException e) { throw wrapRetryable(e); } return convert... | @Test void testEnumerateTypesPropagatesRetryableExceptionOnUnavailableStatus() { when(blockingStub.enumerateTypes(any())).thenThrow(new StatusRuntimeException( Status.UNAVAILABLE)); assertThrows(RetryableException.class, () -> uut.enumerateTypes("ns")); }
@Test void testEnumerateTypes() { HashSet<String> types = Sets.n... |
PgPostQueryMatcher implements Predicate<Fact> { PgPostQueryMatcher(@NonNull SubscriptionRequest req) { canBeSkipped = req.specs().stream().noneMatch(s -> s.jsFilterScript() != null); if (canBeSkipped) { log.trace("{} post query filtering has been disabled", req); } else { this.matchers.addAll(req.specs() .stream() .map... | @Test public void testPGPostQueryMatcher() throws Exception { assertThrows(NullPointerException.class, () -> { new PgPostQueryMatcher(null); }); } |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @VisibleForTesting static RuntimeException wrapRetryable(StatusRuntimeException e) { if (e.getStatus().getCode() == Code.UNAVAILABLE) { return new RetryableException(e); } else { return e; } } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Autow... | @Test void testWrapRetryable_nonRetryable() throws Exception { StatusRuntimeException cause = new StatusRuntimeException(Status.DEADLINE_EXCEEDED); RuntimeException e = GrpcFactStore.wrapRetryable(cause); assertTrue(e instanceof StatusRuntimeException); assertSame(e, cause); }
@Test void testWrapRetryable() throws Exce... |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public void invalidate(@NonNull StateToken token) { MSG_UUID msg = converter.toProto(token.uuid()); try { MSG_Empty msgEmpty = blockingStub.invalidate(msg); } catch (StatusRuntimeException e) { throw wrapRetryable(e); } } @SuppressWarnings("Opti... | @Test void testInvalidate() throws Exception { assertThrows(NullPointerException.class, () -> uut.invalidate(null)); { UUID id = new UUID(0, 1); StateToken token = new StateToken(id); uut.invalidate(token); verify(blockingStub).invalidate(eq(conv.toProto(id))); } { when(blockingStub.invalidate(any())).thenThrow( new St... |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public StateToken stateFor(@NonNull Collection<UUID> forAggIds, @NonNull Optional<String> ns) { StateForRequest req = new StateForRequest(Lists.newArrayList(forAggIds), ns.orElse(null)); MSG_StateForRequest msg = converter.toProto(req); try { MS... | @Test void testStateFor() throws Exception { assertThrows(NullPointerException.class, () -> uut.stateFor(Lists.emptyList(), null)); assertThrows(NullPointerException.class, () -> uut.stateFor(null, null)); assertThrows(NullPointerException.class, () -> uut.stateFor(null, Optional.of("foo"))); { UUID id = new UUID(0, 1)... |
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public boolean publishIfUnchanged(@NonNull List<? extends Fact> factsToPublish, @NonNull Optional<StateToken> token) { ConditionalPublishRequest req = new ConditionalPublishRequest(factsToPublish, token.map( StateToken::uuid).orElse(null)); MSG_... | @Test void testPublishIfUnchanged() throws Exception { assertThrows(NullPointerException.class, () -> uut.publishIfUnchanged(Lists.emptyList(), null)); assertThrows(NullPointerException.class, () -> uut.publishIfUnchanged(null, null)); assertThrows(NullPointerException.class, () -> uut.publishIfUnchanged(null, Optional... |
JadxCLIArgs { public boolean isReplaceConsts() { return replaceConsts; } boolean processArgs(String[] args); boolean overrideProvided(String[] args); JadxArgs toJadxArgs(); List<String> getFiles(); String getOutDir(); String getOutDirSrc(); String getOutDirRes(); boolean isSkipResources(); boolean isSkipSources(); int... | @Test public void testInvertedBooleanOption() { assertThat(parse("--no-replace-consts").isReplaceConsts(), is(false)); assertThat(parse("").isReplaceConsts(), is(true)); } |
CertificateManager { public String generateSignature() { StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.serialSigType"), x509cert.getSigAlgName()); append(builder, NLS.str("certificate.serialSigOID"), x509cert.getSigAlgOID()); return builder.toString(); } CertificateManager(Certificat... | @Test public void decodeRSAKeySignature() { String string = certificateManagerRSA.generateSignature(); assertTrue(string.contains("SHA256withRSA")); assertTrue(string.contains("1.2.840.113549.1.1.11")); }
@Test public void decodeDSAKeySignature() { String string = certificateManagerDSA.generateSignature(); assertTrue(s... |
CertificateManager { public String generateFingerprint() { StringBuilder builder = new StringBuilder(); try { append(builder, NLS.str("certificate.serialMD5"), getThumbPrint(x509cert, "MD5")); append(builder, NLS.str("certificate.serialSHA1"), getThumbPrint(x509cert, "SHA-1")); append(builder, NLS.str("certificate.seri... | @Test public void decodeRSAFingerprint() { String string = certificateManagerRSA.generateFingerprint(); assertTrue(string.contains("61 18 0A 71 3F C9 55 16 4E 04 E3 C5 45 08 D9 11")); assertTrue(string.contains("A0 6E A6 06 DB 2C 6F 3A 16 56 7F 75 97 7B AE 85 C2 13 09 37")); assertTrue(string.contains("12 53 E8 BB C8 A... |
CertificateManager { public String generatePublicKey() { PublicKey publicKey = x509cert.getPublicKey(); if (publicKey instanceof RSAPublicKey) { return generateRSAPublicKey(); } if (publicKey instanceof DSAPublicKey) { return generateDSAPublicKey(); } return ""; } CertificateManager(Certificate cert); static String dec... | @Test public void decodeRSAPubKey() { String string = certificateManagerRSA.generatePublicKey(); assertTrue(string.contains("RSA")); assertTrue(string.contains("65537")); assertTrue(string.contains("1681953129031804462554643735709908030601939275292568895111488068832920121318010916" + "8890384305768067101521914473763638... |
StringRef implements CharSequence { public static StringRef subString(String str, int from, int to) { return new StringRef(str, from, to - from); } private StringRef(String str, int from, int length); static StringRef subString(String str, int from, int to); static StringRef subString(String str, int from); static Str... | @Test public void testSubstring() { checkStr(subString("a", 0), "a"); checkStr(subString("a", 1), ""); checkStr(subString("a", 0, 0), ""); checkStr(subString("a", 0, 1), "a"); checkStr(subString("abc", 1, 2), "b"); checkStr(subString("abc", 2), "c"); checkStr(subString("abc", 2, 3), "c"); } |
StringRef implements CharSequence { public StringRef trim() { int start = offset; int end = start + length; String str = refStr; while ((start < end) && (str.charAt(start) <= ' ')) { start++; } while ((start < end) && (str.charAt(end - 1) <= ' ')) { end--; } if ((start > offset) || (end < offset + length)) { return sub... | @Test public void testTrim() { checkTrim(fromStr("a"), "a"); checkTrim(fromStr(" a "), "a"); checkTrim(fromStr("\ta"), "a"); checkTrim(subString("a b c", 1), "b c"); checkTrim(subString("a b\tc", 1, 4), "b"); checkTrim(subString("a b\tc", 2, 3), "b"); } |
StringRef implements CharSequence { public static List<StringRef> split(String str, String splitBy) { int len = str.length(); int targetLen = splitBy.length(); if (len == 0 || targetLen == 0) { return Collections.emptyList(); } int pos = -targetLen; List<StringRef> list = new ArrayList<>(); while (true) { int start = p... | @Test public void testSplit() { checkSplit("abc", "b", "a", "c"); checkSplit("abc", "a", "", "bc"); checkSplit("abc", "c", "ab"); checkSplit("abc", "d", "abc"); checkSplit("abbbc", "b", "a", "", "", "c"); checkSplit("abbbc", "bb", "a", "bc"); checkSplit("abbbc", "bbb", "a", "c"); checkSplit("abbbc", "bbc", "ab"); check... |
VersionComparator { public static int compare(String str1, String str2) { String[] s1 = str1.split("\\."); int l1 = s1.length; String[] s2 = str2.split("\\."); int l2 = s2.length; int i = 0; while (i < l1 && i < l2) { if (!s1[i].equals(s2[i])) { break; } i++; } if (i < l1 && i < l2) { return Integer.valueOf(s1[i]).comp... | @Test public void testCompare() { checkCompare("", "", 0); checkCompare("1", "1", 0); checkCompare("1", "2", -1); checkCompare("1.1", "1.1", 0); checkCompare("0.5", "0.5", 0); checkCompare("0.5", "0.5.0", 0); checkCompare("0.5", "0.5.00", 0); checkCompare("0.5", "0.5.0.0", 0); checkCompare("0.5", "0.5.0.1", -1); checkC... |
JadxCLIArgs { public boolean isEscapeUnicode() { return escapeUnicode; } boolean processArgs(String[] args); boolean overrideProvided(String[] args); JadxArgs toJadxArgs(); List<String> getFiles(); String getOutDir(); String getOutDirSrc(); String getOutDirRes(); boolean isSkipResources(); boolean isSkipSources(); int... | @Test public void testEscapeUnicodeOption() { assertThat(parse("--escape-unicode").isEscapeUnicode(), is(true)); assertThat(parse("").isEscapeUnicode(), is(false)); } |
TypeCompare { public TypeCompareEnum compareTypes(ClassNode first, ClassNode second) { return compareObjects(first.getType(), second.getType()); } TypeCompare(RootNode root); TypeCompareEnum compareTypes(ClassNode first, ClassNode second); TypeCompareEnum compareTypes(ArgType first, ArgType second); Comparator<ArgType>... | @Test public void compareTypes() { firstIsNarrow(INT, UNKNOWN); firstIsNarrow(array(UNKNOWN), UNKNOWN); firstIsNarrow(array(UNKNOWN), NARROW); } |
TypeUtils { @Nullable public ArgType replaceTypeVariablesUsingMap(ArgType replaceType, Map<ArgType, ArgType> replaceMap) { if (replaceMap.isEmpty()) { return null; } if (replaceType.isGenericType()) { return replaceMap.get(replaceType); } if (replaceType.isArray()) { ArgType replaced = replaceTypeVariablesUsingMap(repl... | @Test void replaceTypeVariablesUsingMap() { ArgType typeVar = genericType("T"); ArgType listCls = object("java.util.List"); Map<ArgType, ArgType> typeMap = Collections.singletonMap(typeVar, STRING); replaceTypeVar(typeVar, typeMap, STRING); replaceTypeVar(generic(listCls, typeVar), typeMap, generic(listCls, STRING)); r... |
AccessInfo { public AccessInfo changeVisibility(int flag) { int currentVisFlags = accFlags & VISIBILITY_FLAGS; if (currentVisFlags == flag) { return this; } int unsetAllVisFlags = accFlags & ~VISIBILITY_FLAGS; return new AccessInfo(unsetAllVisFlags | flag, type); } AccessInfo(int accessFlags, AFType type); boolean cont... | @Test public void changeVisibility() { AccessInfo accessInfo = new AccessInfo(AccessFlags.PROTECTED | AccessFlags.STATIC, AFType.METHOD); AccessInfo result = accessInfo.changeVisibility(AccessFlags.PUBLIC); assertThat(result.isPublic(), is(true)); assertThat(result.isPrivate(), is(false)); assertThat(result.isProtected... |
NameMapper { public static boolean isValidIdentifier(String str) { return notEmpty(str) && !isReserved(str) && VALID_JAVA_IDENTIFIER.matcher(str).matches(); } private NameMapper(); static boolean isReserved(String str); static boolean isValidIdentifier(String str); static boolean isValidFullIdentifier(String str); sta... | @Test public void validIdentifiers() { assertThat(isValidIdentifier("ACls"), is(true)); }
@Test public void notValidIdentifiers() { assertThat(isValidIdentifier("1cls"), is(false)); assertThat(isValidIdentifier("-cls"), is(false)); assertThat(isValidIdentifier("A-cls"), is(false)); } |
NameMapper { public static String removeInvalidCharsMiddle(String name) { if (isValidIdentifier(name) && isAllCharsPrintable(name)) { return name; } int len = name.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { int codePoint = name.codePointAt(i); if (isPrintableChar(codePoint) && ... | @Test public void testRemoveInvalidCharsMiddle() { assertThat(removeInvalidCharsMiddle("1cls"), is("1cls")); assertThat(removeInvalidCharsMiddle("-cls"), is("cls")); assertThat(removeInvalidCharsMiddle("A-cls"), is("Acls")); } |
NameMapper { public static String removeInvalidChars(String name, String prefix) { String result = removeInvalidCharsMiddle(name); if (!result.isEmpty()) { int codePoint = result.codePointAt(0); if (!isValidIdentifierStart(codePoint)) { return prefix + result; } } return result; } private NameMapper(); static boolean ... | @Test public void testRemoveInvalidChars() { assertThat(removeInvalidChars("1cls", "C"), is("C1cls")); assertThat(removeInvalidChars("-cls", "C"), is("cls")); assertThat(removeInvalidChars("A-cls", "C"), is("Acls")); } |
JadxCLIArgs { public boolean isSkipSources() { return skipSources; } boolean processArgs(String[] args); boolean overrideProvided(String[] args); JadxArgs toJadxArgs(); List<String> getFiles(); String getOutDir(); String getOutDirSrc(); String getOutDirRes(); boolean isSkipResources(); boolean isSkipSources(); int get... | @Test public void testSrcOption() { assertThat(parse("--no-src").isSkipSources(), is(true)); assertThat(parse("-s").isSkipSources(), is(true)); assertThat(parse("").isSkipSources(), is(false)); } |
JSources extends JNode { List<JPackage> getHierarchyPackages(List<JavaPackage> packages) { Map<String, JPackage> pkgMap = new HashMap<>(); for (JavaPackage pkg : packages) { addPackage(pkgMap, new JPackage(pkg, wrapper)); } boolean repeat; do { repeat = false; for (JPackage pkg : pkgMap.values()) { List<JPackage> inner... | @Test public void testHierarchyPackages() { String pkgName = "a.b.c.d.e"; List<JavaPackage> packages = Collections.singletonList(newPkg(pkgName)); List<JPackage> out = sources.getHierarchyPackages(packages); assertThat(out, hasSize(1)); JPackage jPkg = out.get(0); assertThat(jPkg.getName(), is(pkgName)); assertThat(jPk... |
CertificateManager { public static String decode(InputStream in) { StringBuilder strBuild = new StringBuilder(); Collection<? extends Certificate> certificates = readCertificates(in); if (certificates != null) { for (Certificate cert : certificates) { CertificateManager certificateManager = new CertificateManager(cert)... | @Test public void decodeNotCertificateFile() throws IOException { try (InputStream in = new FileInputStream(emptyPath)) { String result = CertificateManager.decode(in); assertEquals("", result); } } |
CertificateManager { public String generateHeader() { StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.cert_type"), x509cert.getType()); append(builder, NLS.str("certificate.serialSigVer"), ((Integer) x509cert.getVersion()).toString()); append(builder, NLS.str("certificate.serialNumber"... | @Test public void decodeRSAKeyHeader() { String string = certificateManagerRSA.generateHeader(); assertTrue(string.contains("X.509")); assertTrue(string.contains("0x4bd68052")); assertTrue(string.contains("CN=test cert, OU=test unit, O=OOO TestOrg, L=St.Peterburg, ST=Russia, C=123456")); }
@Test public void decodeDSAKe... |
CatalogService { public CompletableFuture<String> addProductToCatalog(AddProductToCatalogCommand command) { LOG.debug("Processing AddProductToCatalogCommand command: {}", command); return this.commandGateway.send(command); } CatalogService(CommandGateway commandGateway); CompletableFuture<String> addProductToCatalog(Ad... | @Test public void testApi() throws Exception { when(commandGateway.send(any())) .thenAnswer(i -> { AddProductToCatalogCommand command = i.getArgumentAt(0, AddProductToCatalogCommand.class); assertEquals(id, command.getId()); CompletableFuture<String> response = new CompletableFuture<String>(); response.complete(command... |
CatalogApiController { @PostMapping("/add") public CompletableFuture<String> addProductToCatalog(@RequestBody Map<String, String> request) { AddProductToCatalogCommand command = new AddProductToCatalogCommand(request.get("id"), request.get("name")); LOG.info("Executing command: {}", command); return catalogService.addP... | @Test public void checkControllerCallsServiceCorrectly() throws ExecutionException, InterruptedException { assertNotNull(request); assertNotNull(request.containsKey("id")); assertNotNull(request.containsKey("name")); when(commandGateway.addProductToCatalog(any(AddProductToCatalogCommand.class))) .thenAnswer(i -> { AddP... |
EventProcessor { @EventHandler public void on(ProductAddedEvent productAddedEvent) { repo.save(new Product(productAddedEvent.getId(), productAddedEvent.getName())); LOG.info("A product was added! Id={} Name={}", productAddedEvent.getId(), productAddedEvent.getName()); } EventProcessor(ProductRepository repository); @Ev... | @Test public void testOn(){ List<Product> products = new ArrayList<>(); when(repo.save(any(Product.class))) .thenAnswer(i -> { Product prod = i.getArgumentAt(0, Product.class); products.add(prod); return prod; }); processor.on(event); verify(repo, times(1)).save(any(Product.class)); verifyNoMoreInteractions(repo); Asse... |
DriftMethodInvocation extends AbstractFuture<Object> { static <A extends Address> DriftMethodInvocation<A> createDriftMethodInvocation( MethodInvoker invoker, MethodMetadata metadata, Map<String, String> headers, List<Object> parameters, RetryPolicy retryPolicy, AddressSelector<A> addressSelector, Optional<String> addr... | @Test(timeOut = 60000) public void testFirstTrySuccess() throws Exception { TestingMethodInvocationStat stat = new TestingMethodInvocationStat(); DriftMethodInvocation<?> methodInvocation = createDriftMethodInvocation(RetryPolicy.NO_RETRY_POLICY, stat, () -> immediateFuture(SUCCESS)); assertEquals(methodInvocation.get(... |
ThriftEnumMetadata { public ThriftEnumMetadata( String enumName, Class<T> enumClass) throws RuntimeException { this.enumName = requireNonNull(enumName, "enumName must not be null"); this.enumClass = requireNonNull(enumClass, "enumClass must not be null"); Method enumValueMethod = null; for (Method method : enumClass.ge... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Enum class .*DuplicateValues returned duplicate enum values: 42") public void testDuplicateValues() { thriftEnumMetadata(DuplicateValues.class); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMe... |
ReflectionHelper { public static List<String> extractParameterNames(Executable methodOrConstructor) { return PARAMETER_NAMES.getUnchecked(methodOrConstructor); } private ReflectionHelper(); static boolean isArray(Type type); static boolean isOptional(Type type); static Class<?> getArrayOfType(Type componentType); stat... | @Test public void testExtractParameterNamesNoAnnotations() throws Exception { assertEquals( extractParameterNames(getClass().getDeclaredMethod("noAnnotations", String.class, String.class, String.class)), ImmutableList.of("a", "b", "c")); }
@Test public void testExtractParameterNamesThriftFieldAnnotation() throws Except... |
ThriftUnionMetadataBuilder extends AbstractThriftMetadataBuilder { @Override public ThriftStructMetadata build() { metadataErrors.throwIfHasErrors(); ThriftMethodInjection builderMethodInjection = buildBuilderConstructorInjections(); ThriftConstructorInjection constructorInjection = buildConstructorInjection(); Iterabl... | @Test public void testNonFinalUnionOk() { ThriftUnionMetadataBuilder builder = new ThriftUnionMetadataBuilder(new ThriftCatalog(), NotFinalUnion.class); builder.build(); } |
ThriftStructMetadataBuilder extends AbstractThriftMetadataBuilder { @Override public ThriftStructMetadata build() { metadataErrors.throwIfHasErrors(); ThriftMethodInjection builderMethodInjection = buildBuilderConstructorInjections(); ThriftConstructorInjection constructorInjections = buildConstructorInjection(); Itera... | @Test public void testGenericBuilder() { Type structType = new TypeToken<GenericStruct<String>>() {}.getType(); ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), structType); builder.build(); }
@Test(expectedExceptions = MetadataErrorException.class) public void testGenericBuild... |
RetryPolicy { public ExceptionClassification classifyException(Throwable throwable, boolean idempotent) { if (throwable instanceof ConnectionFailedException) { return new ExceptionClassification(Optional.of(TRUE), DOWN); } if (idempotent && throwable instanceof RequestTimeoutException) { return new ExceptionClassificat... | @Test public void testRetryUserException() { ExceptionClassification overloaded = new ExceptionClassification(Optional.of(true), OVERLOADED); RetryPolicy policy = new RetryPolicy(new DriftClientConfig(), classifier -> { if (classifier instanceof TestingUserException) { return overloaded; } return NORMAL_EXCEPTION; }); ... |
ThriftCatalog { public <T extends Enum<T>> ThriftEnumMetadata<?> getThriftEnumMetadata(Class<?> enumClass) { checkArgument(enumClass.isEnum(), "Class %s is not an enum", enumClass.getName()); ThriftEnumMetadata<?> enumMetadata = enums.get(enumClass); if (enumMetadata == null) { enumMetadata = thriftEnumMetadata((Class<... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Class .*NotEnum is not an enum") public void testEnumMetadataForNonEnum() { new ThriftCatalog().getThriftEnumMetadata(NotEnum.class); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.