src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
EndSubscriberHelper { public static boolean validate(Subscription upstream, Subscription next, Class<?> subscriber) { ObjectHelper.requireNonNull(next, "next is null"); if (upstream != null) { next.cancel(); if (upstream != SubscriptionHelper.CANCELLED) { reportDoubleSubscription(subscriber); } return false; } return t...
@Test public void validateSubscription() { BooleanSubscription d1 = new BooleanSubscription(); assertFalse(EndSubscriberHelper.validate(SubscriptionHelper.CANCELLED, d1, getClass())); assertTrue(d1.isCancelled()); assertTrue(errors.toString(), errors.isEmpty()); }
QueueDrainHelper { static boolean isCancelled(BooleanSupplier cancelled) { try { return cancelled.getAsBoolean(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); return true; } } private QueueDrainHelper(); static void drainMaxLoop(SimplePlainQueue<T> q, Subscriber<? super U> a, boolean delayError, D...
@Test public void isCancelled() { assertTrue(QueueDrainHelper.isCancelled(new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { throw new IOException(); } })); }
QueueDrainHelper { public static void request(Subscription s, int prefetch) { s.request(prefetch < 0 ? Long.MAX_VALUE : prefetch); } private QueueDrainHelper(); static void drainMaxLoop(SimplePlainQueue<T> q, Subscriber<? super U> a, boolean delayError, Disposable dispose, QueueDrain<T, U> qd); static bool...
@Test public void requestMaxInt() { QueueDrainHelper.request(new Subscription() { @Override public void request(long n) { assertEquals(Integer.MAX_VALUE, n); } @Override public void cancel() { } }, Integer.MAX_VALUE); } @Test public void requestMinInt() { QueueDrainHelper.request(new Subscription() { @Override public v...
QueueDrainHelper { public static <T> void postComplete(Subscriber<? super T> actual, Queue<T> queue, AtomicLong state, BooleanSupplier isCancelled) { if (queue.isEmpty()) { actual.onComplete(); return; } if (postCompleteDrain(state.get(), actual, queue, state, isCancelled)) { return; } for (; ; ) { long r = state.get()...
@Test public void postCompleteEmpty() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); ArrayDeque<Integer> queue = new ArrayDeque<Integer>(); AtomicLong state = new AtomicLong(); BooleanSupplier isCancelled = new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { return false; }...
MaybeToFlowable extends Flowable<T> implements HasUpstreamMaybeSource<T> { @Override public MaybeSource<T> source() { return source; } MaybeToFlowable(MaybeSource<T> source); @Override MaybeSource<T> source(); }
@Test public void source() { Maybe<Integer> m = Maybe.just(1); assertSame(m, (((HasUpstreamMaybeSource<?>)toFlowable(m)).source())); }
Functions { @SuppressWarnings("unchecked") public static <T> Function<T, T> identity() { return (Function<T, T>)IDENTITY; } private Functions(); static Function<Object[], R> toFunction(final BiFunction<? super T1, ? super T2, ? extends R> f); static Function<Object[], R> toFunction(final Function3<T1, T2, T3, R> f); s...
@Test public void identityFunctionToString() { assertEquals("IdentityFunction", Functions.identity().toString()); }
RxJavaCommonPlugins { public static void lockdown() { lockdown = true; } private RxJavaCommonPlugins(); static void lockdown(); static boolean isLockdown(); static void setFailOnNonBlockingScheduler(boolean enable); static boolean isFailOnNonBlockingScheduler(); @Nullable static Function<? super Scheduler, ? extends S...
@SuppressWarnings({ "rawtypes" }) @Test public void lockdown() throws Exception { RxJavaCommonPlugins.reset(); RxJavaCommonPlugins.lockdown(); try { assertTrue(RxJavaCommonPlugins.isLockdown()); Consumer a1 = Functions.emptyConsumer(); Callable f0 = new Callable() { @Override public Object call() { return null; } }; Fu...
RxJavaCommonPlugins { @NonNull public static Scheduler initSingleScheduler(@NonNull Callable<Scheduler> defaultScheduler) { ObjectHelper.requireNonNull(defaultScheduler, "Scheduler Callable can't be null"); Function<? super Callable<Scheduler>, ? extends Scheduler> f = onInitSingleHandler; if (f == null) { return callR...
@Test public void overrideInitSingleSchedulerCrashes() { try { RxJavaCommonPlugins.initSingleScheduler(null); fail("Should have thrown NullPointerException"); } catch (NullPointerException npe) { assertEquals("Scheduler Callable can't be null", npe.getMessage()); } try { RxJavaCommonPlugins.initSingleScheduler(nullResu...
RxJavaCommonPlugins { @NonNull public static Scheduler initComputationScheduler(@NonNull Callable<Scheduler> defaultScheduler) { ObjectHelper.requireNonNull(defaultScheduler, "Scheduler Callable can't be null"); Function<? super Callable<Scheduler>, ? extends Scheduler> f = onInitComputationHandler; if (f == null) { re...
@Test public void overrideInitComputationSchedulerCrashes() { try { RxJavaCommonPlugins.initComputationScheduler(null); fail("Should have thrown NullPointerException"); } catch (NullPointerException npe) { assertEquals("Scheduler Callable can't be null", npe.getMessage()); } try { RxJavaCommonPlugins.initComputationSch...
RxJavaCommonPlugins { @NonNull public static Scheduler initIoScheduler(@NonNull Callable<Scheduler> defaultScheduler) { ObjectHelper.requireNonNull(defaultScheduler, "Scheduler Callable can't be null"); Function<? super Callable<Scheduler>, ? extends Scheduler> f = onInitIoHandler; if (f == null) { return callRequireNo...
@Test public void overrideInitIoSchedulerCrashes() { try { RxJavaCommonPlugins.initIoScheduler(null); fail("Should have thrown NullPointerException"); } catch (NullPointerException npe) { assertEquals("Scheduler Callable can't be null", npe.getMessage()); } try { RxJavaCommonPlugins.initIoScheduler(nullResultCallable);...
RxJavaCommonPlugins { @NonNull public static Scheduler initNewThreadScheduler(@NonNull Callable<Scheduler> defaultScheduler) { ObjectHelper.requireNonNull(defaultScheduler, "Scheduler Callable can't be null"); Function<? super Callable<Scheduler>, ? extends Scheduler> f = onInitNewThreadHandler; if (f == null) { return...
@Test public void overrideInitNewThreadSchedulerCrashes() { try { RxJavaCommonPlugins.initNewThreadScheduler(null); fail("Should have thrown NullPointerException"); } catch (NullPointerException npe) { assertEquals("Scheduler Callable can't be null", npe.getMessage()); } try { RxJavaCommonPlugins.initNewThreadScheduler...
RxJavaCommonPlugins { @NonNull public static Runnable onSchedule(@NonNull Runnable run) { Function<? super Runnable, ? extends Runnable> f = onScheduleHandler; if (f == null) { return run; } return apply(f, run); } private RxJavaCommonPlugins(); static void lockdown(); static boolean isLockdown(); static void setFailO...
@Test public void onScheduleComputation() throws InterruptedException { onSchedule(Schedulers.computation().createWorker()); } @Test public void onScheduleIO() throws InterruptedException { onSchedule(Schedulers.io().createWorker()); } @Test public void onScheduleNewThread() throws InterruptedException { onSchedule(Sch...
RxJavaCommonPlugins { public static void onError(@NonNull Throwable error) { Consumer<? super Throwable> f = errorHandler; if (error == null) { error = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); } else { if (!isBug(error)) { error = new Und...
@Test public void onError() { try { final List<Throwable> list = new ArrayList<Throwable>(); RxJavaCommonPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable t) { list.add(t); } }); RxJavaCommonPlugins.onError(new TestException("Forced failure")); assertEquals(1, list.size()); asse...
RxJavaCommonPlugins { @NonNull public static Scheduler createComputationScheduler(@NonNull ThreadFactory threadFactory) { return new ComputationScheduler(ObjectHelper.requireNonNull(threadFactory, "threadFactory is null")); } private RxJavaCommonPlugins(); static void lockdown(); static boolean isLockdown(); static vo...
@Test public void createComputationScheduler() { final String name = "ComputationSchedulerTest"; ThreadFactory factory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, name); } }; final Scheduler customScheduler = RxJavaCommonPlugins.createComputationScheduler(factory); RxJav...
RxJavaCommonPlugins { @NonNull public static Scheduler createIoScheduler(@NonNull ThreadFactory threadFactory) { return new IoScheduler(ObjectHelper.requireNonNull(threadFactory, "threadFactory is null")); } private RxJavaCommonPlugins(); static void lockdown(); static boolean isLockdown(); static void setFailOnNonBlo...
@Test public void createIoScheduler() { final String name = "IoSchedulerTest"; ThreadFactory factory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, name); } }; final Scheduler customScheduler = RxJavaCommonPlugins.createIoScheduler(factory); RxJavaCommonPlugins.setIoSchedul...
RxJavaCommonPlugins { @NonNull public static Scheduler createNewThreadScheduler(@NonNull ThreadFactory threadFactory) { return new NewThreadScheduler(ObjectHelper.requireNonNull(threadFactory, "threadFactory is null")); } private RxJavaCommonPlugins(); static void lockdown(); static boolean isLockdown(); static void s...
@Test public void createNewThreadScheduler() { final String name = "NewThreadSchedulerTest"; ThreadFactory factory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, name); } }; final Scheduler customScheduler = RxJavaCommonPlugins.createNewThreadScheduler(factory); RxJavaCommo...
PixabayImage { public int getPreviewHeight() { return previewHeight; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previe...
@Test public void getPreviewHeight() throws Exception { assertEquals(pixabayImage.getPreviewHeight(), 180); }
PixabayImage { public String getPageURL() { return pageURL; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL, ...
@Test public void getPageURL() throws Exception { assertEquals(pixabayImage.getPageURL(), "http: }
PixabayImage { public String getPreviewURL() { return previewURL; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewUR...
@Test public void getPreviewURL() throws Exception { assertEquals(pixabayImage.getPreviewURL(), "http: }
PixabayImage { public String getWebformatURL() { return webformatURL; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previ...
@Test public void getWebformatURL() throws Exception { assertEquals(pixabayImage.getWebformatURL(), "http: }
PixabayImage { public int getImageWidth() { return imageWidth; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL, ...
@Test public void getImageWidth() throws Exception { assertEquals(pixabayImage.getImageWidth(), 1080); }
PixabayImage { public long getUserId() { return userId; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL, ...
@Test public void getUserId() throws Exception { assertEquals(pixabayImage.getUserId(), 123456); }
PixabayImage { public String getUser() { return "By: " + user; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL, ...
@Test public void getUser() throws Exception { assertEquals(pixabayImage.getUser(), "By: user"); }
PixabayImage { public PixabayImageType getType() { return type; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL,...
@Test public void getType() throws Exception { assertEquals(pixabayImage.getType(), PixabayImageType.illustration); }
PixabayImage { public long getId() { return id; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL, ...
@Test public void getId() throws Exception { assertEquals(pixabayImage.getId(), 987654); }
PixabayImage { public String getUserImageURL() { return userImageURL; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previ...
@Test public void getUserImageURL() throws Exception { assertEquals(pixabayImage.getUserImageURL(), "http: }
PixabayImage { public int getImageHeight() { return imageHeight; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL...
@Test public void getImageHeight() throws Exception { assertEquals(pixabayImage.getImageHeight(), 1024); }
PixabayImage { public String getLikes() { return String.valueOf(likes); } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String pre...
@Test public void getLikes() throws Exception { assertEquals(pixabayImage.getLikes(), "100"); }
PixabayImage { public String getFavorites() { return String.valueOf(favorites); } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, St...
@Test public void getFavorites() throws Exception { assertEquals(pixabayImage.getFavorites(), "50"); }
PixabayImage { public String getTags() { if (tags == null) return ""; if (tags.contains(", ")) { String[] splitTags = tags.toUpperCase().split(", "); return TextUtils.join(" - ", splitTags); } else return tags; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webforma...
@Test public void getTags() throws Exception { assertEquals(pixabayImage.getTags(), null); }
PixabayImage { public int getWebformatHeight() { return webformatHeight; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String pr...
@Test public void getWebformatHeight() throws Exception { assertEquals(pixabayImage.getWebformatHeight(), 90); }
PixabayImage { public long getViews() { return views; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL, ...
@Test public void getViews() throws Exception { assertEquals(pixabayImage.getViews(), 1234); }
PixabayImage { public int getWebformatWidth() { return webformatWidth; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String prev...
@Test public void getWebformatWidth() throws Exception { assertEquals(pixabayImage.getWebformatWidth(), 360); }
PixabayImage { public int getPreviewWidth() { return previewWidth; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewU...
@Test public void getPreviewWidth() throws Exception { assertEquals(pixabayImage.getPreviewWidth(), 180); }
PixabayImage { public String getComments() { return String.valueOf(comments); } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, Stri...
@Test public void getComments() throws Exception { assertEquals(pixabayImage.getComments(), "150"); }
PixabayImage { public long getDownloads() { return downloads; } PixabayImage(int previewHeight, int likes, int favorites, String tags, int webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL, ...
@Test public void getDownloads() throws Exception { assertEquals(pixabayImage.getDownloads(), 987); }
ClientSpanNameProvider { public static Function<HttpRequest, String> PREFIXED_REQUEST_METHOD_NAME(final String prefix) { return (request) -> replaceIfNull(prefix, "") + replaceIfNull(request.getRequestLine().getMethod(), "unknown"); } static Function<HttpRequest, String> PREFIXED_REQUEST_METHOD_NAME(final String prefi...
@Test public void prefixedRequestMethodSpanNameFormatsCorrectly() { Function<HttpRequest, String> spanNameProvider = ClientSpanNameProvider .PREFIXED_REQUEST_METHOD_NAME("ELASTICSEARCH - "); assertEquals("ELASTICSEARCH - GET", spanNameProvider.apply(getRequest)); assertEquals("ELASTICSEARCH - GET", spanNameProvider.app...
ClientSpanNameProvider { public static Function<HttpRequest, String> PREFIXED_REQUEST_TARGET_NAME(final String prefix) { return (request) -> replaceIfNull(prefix, "") + replaceIfNull(standardizeUri(request.getRequestLine().getUri()), "unknown"); } static Function<HttpRequest, String> PREFIXED_REQUEST_METHOD_NAME(final...
@Test public void prefixedRequestTargetSpanNameFormatsCorrectly() { Function<HttpRequest, String> spanNameProvider = ClientSpanNameProvider .PREFIXED_REQUEST_TARGET_NAME("ELASTICSEARCH - "); assertEquals("ELASTICSEARCH - /twitter/tweet/", spanNameProvider.apply(getRequest)); assertEquals("ELASTICSEARCH - /twitter/tweet...
ClientSpanNameProvider { public static Function<HttpRequest, String> PREFIXED_REQUEST_METHOD_TARGET_NAME( final String prefix) { return (request) -> replaceIfNull(prefix, "") + replaceIfNull(request.getRequestLine().getMethod(), "unknown") + " " + replaceIfNull(standardizeUri(request.getRequestLine().getUri()), "unknow...
@Test public void prefixedRequestMethodTargetSpanNameFormatsCorrectly() { Function<HttpRequest, String> spanNameProvider = ClientSpanNameProvider .PREFIXED_REQUEST_METHOD_TARGET_NAME("ELASTICSEARCH - "); assertEquals("ELASTICSEARCH - GET /twitter/tweet/", spanNameProvider.apply(getRequest)); assertEquals("ELASTICSEARCH...
RxReceiver { @NonNull public static Observable<Intent> receives(@NonNull final Context context, @NonNull final IntentFilter intentFilter) { return Observable.create(new ObservableOnSubscribe<Intent>() { @Override public void subscribe(final ObservableEmitter<Intent> emitter) { final BroadcastReceiver receiver = new Bro...
@Test public void test() { IntentFilter intentFilter = new IntentFilter("test"); Context context = RuntimeEnvironment.application.getApplicationContext(); TestObserver<Intent> tester = RxReceiver.receives(context, intentFilter) .test(); Intent foobar = new Intent("test").putExtra("foo", "bar"); context.sendBroadcast(fo...
RxReceiver { @NonNull @CheckResult public static Observable<Intent> receives(@NonNull final Context context, @NonNull final IntentFilter intentFilter) { return Observable.create(new Action1<Emitter<Intent>>() { @Override public void call(final Emitter<Intent> emitter) { final BroadcastReceiver receiver = new BroadcastR...
@Test public void subscribe() { IntentFilter intentFilter = new IntentFilter("test_action"); Application application = RuntimeEnvironment.application; TestSubscriber<Intent> o = new TestSubscriber<>(); Subscription subscription = RxReceiver.receives(application, intentFilter).subscribe(o); o.assertValues(); Intent inte...
RxReceiverLocal { @NonNull public static Observable<Intent> receives(@NonNull final Context context, @NonNull final IntentFilter intentFilter) { return Observable.create(new ObservableOnSubscribe<Intent>() { @Override public void subscribe(final ObservableEmitter<Intent> emitter) { final BroadcastReceiver receiver = ne...
@Test public void test() { IntentFilter intentFilter = new IntentFilter("test"); Context context = RuntimeEnvironment.application.getApplicationContext(); TestObserver<Intent> tester = RxReceiverLocal.receives(context, intentFilter) .test(); Intent foobar = new Intent("test").putExtra("foo", "bar"); LocalBroadcastManag...
RxReceiverLocal { @NonNull @CheckResult public static Observable<Intent> receives(@NonNull final Context context, @NonNull final IntentFilter intentFilter) { return Observable.create(new Action1<Emitter<Intent>>() { @Override public void call(final Emitter<Intent> emitter) { final BroadcastReceiver receiver = new Broad...
@Test public void subscribe() { IntentFilter intentFilter = new IntentFilter("test_action"); Application application = RuntimeEnvironment.application; TestSubscriber<Intent> o = new TestSubscriber<>(); Subscription subscription = RxReceiverLocal.receives(application, intentFilter).subscribe(o); o.assertValues(); Intent...
FlaxModel { protected void notifyModelChanged() { modelSubject.onNext((M)this); } FlaxModel(); }
@Test public void testNotifyModelChanged() throws Exception { TestObserver testSubscriber = flaxModel.getObservable().test(); flaxModel.notifyModelChanged(); flaxModel.notifyModelChanged(); testSubscriber.assertValueCount(3); testSubscriber.assertValues(flaxModel, flaxModel, flaxModel); }
FlaxStore { static<M extends FlaxModel> M getModel(Class modelClass) { return getModel(modelClass, 0); } private FlaxStore(); }
@Test public void testStoreReturnsSameValueForSameKeys() throws Exception { Foo fooOne = FlaxStore.getModel(Foo.class, 0); Foo fooTwo = FlaxStore.getModel(Foo.class, 0); assertEquals("fooOne and fooTwo should be the same but they are different.", fooOne, fooTwo); } @Test public void testStoreReturnsDifferentValuesForDi...
GrizzlyExecutorService extends AbstractExecutorService implements ExtendedThreadPool { public static GrizzlyExecutorService createInstance() { return createInstance(ThreadPoolConfig.DEFAULT); } protected GrizzlyExecutorService(ThreadPoolConfig config); protected GrizzlyExecutorService(ThreadPoolConfig config, boolean...
@Test public void testCreateInstance() throws Exception { int threads = 100; ThreadPoolConfig cfg = new ThreadPoolConfig("test", -1, threads, null, -1, 0, null, null, Thread.NORM_PRIORITY, null); GrizzlyExecutorService r = GrizzlyExecutorService.createInstance(cfg); final int tasks = 2000000; doTest(r,tasks); assertTru...
PCA9685 implements Closeable { public void setPwm(int channel, int on, int off) throws IOException { if (i2cDevice != null && channel >= 0 && channel < 16) { try { i2cDevice.writeRegByte(LED0_ON_L + 4 * channel, (byte) (on & 0xFF)); i2cDevice.writeRegByte(LED0_ON_H + 4 * channel, (byte) (on >> 8)); i2cDevice.writeRegBy...
@Test public void creation() throws Exception { InOrder inOrder = inOrder(i2cDeviceMock); when(peripheralManagerServiceMock.getI2cBusList()).thenReturn(i2cDevices); when(peripheralManagerServiceMock.openI2cDevice("I2C1",0x40)).thenReturn(i2cDeviceMock); when(i2cDeviceMock.readRegByte(MODE1)).thenReturn((byte)0x0); PCA9...
PCA9685 implements Closeable { public void setPwmFreq(int freqHz) throws IOException { try { double prescaleval = 25000000.0; prescaleval /= 4096.0; prescaleval /= freqHz; prescaleval -= 1.0; Log.d(TAG, String.format("Setting PWM frequency to %d Hz", freqHz)); Log.d(TAG, String.format("Estimated pre-scale: %.4f", presc...
@Test public void setPwmFreq() throws Exception { when(peripheralManagerServiceMock.getI2cBusList()).thenReturn(i2cDevices); when(peripheralManagerServiceMock.openI2cDevice("I2C1",0x40)).thenReturn(i2cDeviceMock); when(i2cDeviceMock.readRegByte(MODE1)).thenReturn((byte)0x0); PCA9685 device = new PCA9685((byte)0x40, per...
PCA9685 implements Closeable { public void setAllPwm(int on, int off) throws IOException { if (i2cDevice != null) { try { i2cDevice.writeRegByte(ALL_LED_ON_L, (byte) (on & 0xFF)); i2cDevice.writeRegByte(ALL_LED_ON_H, (byte) (on >> 8)); i2cDevice.writeRegByte(ALL_LED_OFF_L, (byte) (off & 0xFF)); i2cDevice.writeRegByte(A...
@Test public void setAllPwm() throws Exception { when(peripheralManagerServiceMock.getI2cBusList()).thenReturn(i2cDevices); when(peripheralManagerServiceMock.openI2cDevice("I2C1",0x40)).thenReturn(i2cDeviceMock); when(i2cDeviceMock.readRegByte(MODE1)).thenReturn((byte)0x0); PCA9685 device = new PCA9685((byte)0x40, peri...
PCA9685Servo extends PCA9685 { public void setServoAngle(int channel, int angle) throws IOException { setPwm(channel, 0, map(angle, minAngle, maxAngle, minPwm, maxPwm)); } PCA9685Servo(byte address, @NonNull PeripheralManager manager); void setServoMinMaxPwm(int minAngle, int maxAngle, int minPwm, int maxPwm); void set...
@Test public void setServoAngle() throws Exception { when(peripheralManagerServiceMock.getI2cBusList()).thenReturn(i2cDevices); when(peripheralManagerServiceMock.openI2cDevice("I2C1",0x40)).thenReturn(i2cDeviceMock); when(i2cDeviceMock.readRegByte(MODE1)).thenReturn((byte)0x0); PCA9685Servo device = new PCA9685Servo((b...
PCA9685Servo extends PCA9685 { public int map(int x, int inMin, int inMax, int outMin, int outMax) { return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; } PCA9685Servo(byte address, @NonNull PeripheralManager manager); void setServoMinMaxPwm(int minAngle, int maxAngle, int minPwm, int maxPwm); void setSe...
@Test public void map() throws Exception { PCA9685Servo device = new PCA9685Servo((byte)0x40, peripheralManagerServiceMock); assertEquals(20,device.map(0,10,20,30,40)); assertEquals(21,device.map(1,10,20,30,40)); assertEquals(22,device.map(2,10,20,30,40)); assertEquals(23,device.map(3,10,20,30,40)); assertEquals(24,dev...
Order { public double getTotal() { double total = 0; for (Product product : products) { total += product.getPrice(); } return total; } Order(Product ... products); double getTotal(); }
@Test public void should_sum_all_prices() { Order order = new Order(new Product(30), new Product(40.0)); assertEquals(70.0, order.getTotal(), ERROR); }
PgConfigurationProperties implements ApplicationListener<ApplicationReadyEvent> { public int getPageSizeForIds() { return pageSize * idOnlyFactor; } int getPageSizeForIds(); int getQueueSizeForIds(); int getFetchSizeForIds(); int getFetchSize(); @Override void onApplicationEvent(ApplicationReadyEvent event); }
@Test void testGetPageSizeForIds() { assertEquals(100000, uut.getPageSizeForIds()); }
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public Subscription subscribe(@NonNull SubscriptionRequestTO req, @NonNull FactObserver observer) { SubscriptionImpl<Fact> subscription = SubscriptionImpl.on(observer); StreamObserver<FactStoreProto.MSG_Notification> responseObserver = new Clien...
@Test void testSubscribe() throws Exception { assertThrows(NullPointerException.class, () -> uut.subscribe(mock( SubscriptionRequestTO.class), null)); assertThrows(NullPointerException.class, () -> uut.subscribe(null, null)); assertThrows(NullPointerException.class, () -> uut.subscribe(null, mock( FactObserver.class)))...
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public long currentTime() { MSG_Empty empty = converter.empty(); MSG_CurrentDatabaseTime resp; try { resp = blockingStub.currentTime(empty); } catch (StatusRuntimeException e) { throw wrapRetryable(e); } return converter.fromProto(resp); } @Supp...
@Test public void testCurrentTime() throws Exception { long l = 123L; when(blockingStub.currentTime(conv.empty())).thenReturn(conv.toProto(l)); Long t = uut.currentTime(); assertEquals(t, l); }
GrpcFactStore implements FactStore, SmartInitializingSingleton { @Override public Set<String> enumerateNamespaces() { MSG_Empty empty = converter.empty(); MSG_StringSet resp; try { resp = blockingStub.enumerateNamespaces(empty); } catch (StatusRuntimeException e) { throw wrapRetryable(e); } return converter.fromProto(r...
@Test void testCurrentTimePropagatesRetryableExceptionOnUnavailableStatus() { when(blockingStub.enumerateNamespaces(any())).thenThrow(new StatusRuntimeException( Status.UNAVAILABLE)); assertThrows(RetryableException.class, () -> uut.enumerateNamespaces()); } @Test void testEnumerateNamespacesPropagatesRetryableExceptio...
FactCastJson { @SneakyThrows public static <T> T copy(@NonNull T toCopy) { Class<?> c = toCopy.getClass(); return reader.forType(c).readValue(writer.forType(c).writeValueAsString(toCopy)); } @SneakyThrows static T copy(@NonNull T toCopy); @SneakyThrows static String writeValueAsString(@NonNull T value); @SneakyThrows ...
@Test void testCopyNull() { Assertions.assertThrows(NullPointerException.class, () -> { FactCastJson.copy(null); }); } @Test void testCopy() { final Foo foo = new Foo("bar", "baz"); Foo copy = FactCastJson.copy(foo); assertNotSame(foo, copy); assertNotEquals(foo, copy); assertEquals(foo.bar(), copy.bar()); assertNull(c...
FactCastJson { @SneakyThrows public static <T> T readValue(@NonNull Class<T> class1, String json) { return reader.forType(class1).readValue(json); } @SneakyThrows static T copy(@NonNull T toCopy); @SneakyThrows static String writeValueAsString(@NonNull T value); @SneakyThrows static T readValue(@NonNull Class<T> class...
@Test void testReadValueNull() { expectNPE(() -> FactCastJson.readValue(null, "")); expectNPE(() -> FactCastJson.readValue(null, (String) null)); expectNPE(() -> FactCastJson.readValue(FactCastJson.class, (String) null)); expectNPE(() -> FactCastJson.readValue(null, (InputStream) null)); expectNPE(() -> FactCastJson.re...
FactCastJson { @SneakyThrows public static <T> String writeValueAsString(@NonNull T value) { return writer.writeValueAsString(value); } @SneakyThrows static T copy(@NonNull T toCopy); @SneakyThrows static String writeValueAsString(@NonNull T value); @SneakyThrows static T readValue(@NonNull Class<T> class1, String jso...
@Test void testWriteValueNull() { expectNPE(() -> FactCastJson.writeValueAsString(null)); }
FactCastJson { public static ObjectNode newObjectNode() { return objectMapper.getNodeFactory().objectNode(); } @SneakyThrows static T copy(@NonNull T toCopy); @SneakyThrows static String writeValueAsString(@NonNull T value); @SneakyThrows static T readValue(@NonNull Class<T> class1, String json); @SneakyThrows static ...
@Test void testNewObjectNode() { assertNotNull(FactCastJson.newObjectNode()); assertTrue(FactCastJson.newObjectNode() instanceof ObjectNode); }
FactCastJson { public static ObjectNode toObjectNode(String json) { try { return (ObjectNode) objectMapper.readTree(json); } catch (IOException e) { throw new RuntimeException(e); } } @SneakyThrows static T copy(@NonNull T toCopy); @SneakyThrows static String writeValueAsString(@NonNull T value); @SneakyThrows static ...
@Test void testToObjectNodeNonJson() { Assertions.assertThrows(RuntimeException.class, () -> { FactCastJson.toObjectNode("no-json"); }); } @Test void testToObjectNode() { ObjectNode objectNode = FactCastJson.toObjectNode("{\"x\":1}"); JsonNode jsonNode = objectNode.get("x"); assertEquals(1, jsonNode.asInt()); assertNul...
PgFactExtractor implements RowMapper<Fact> { @Override @NonNull public Fact mapRow(@NonNull ResultSet rs, int rowNum) throws SQLException { serial.set(rs.getLong(PgConstants.COLUMN_SER)); return PgFact.from(rs); } @Override @NonNull Fact mapRow(@NonNull ResultSet rs, int rowNum); }
@Test void testMapRowNullContracts() throws Exception { assertThrows(NullPointerException.class, () -> { uut.mapRow(null, 1); }); } @Test void testMapRow() throws Exception { ResultSet rs = mock(ResultSet.class); final UUID id = UUID.randomUUID(); when(rs.getString(PgConstants.ALIAS_ID)).thenReturn(id.toString()); when...
FactCastJson { @SneakyThrows @Generated public static String writeValueAsPrettyString(Object o) { return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(o); } @SneakyThrows static T copy(@NonNull T toCopy); @SneakyThrows static String writeValueAsString(@NonNull T value); @SneakyThrows static T readVa...
@Test void testWriteValueAsPrettyString() { String json = "{\"a\":1}"; String pretty = FactCastJson.writeValueAsPrettyString(FactCastJson.toObjectNode(json)); assertTrue(pretty.contains("\n")); assertTrue(pretty.contains(" ")); } @Test void testWriteValueAsPrettyFromObject() { @Data class TestObject { String foo = "bar...
JavaScriptEngineSupplier implements Supplier<ScriptEngine> { @Override public ScriptEngine get() { ScriptEngine engine = getEngineByName("nashorn", "javascript", "js"); if (engine == null) throw new IllegalStateException("Cannot find any engine to run javascript code."); return engine; } JavaScriptEngineSupplier(); @Ov...
@Test void testGet() throws Exception { JavaScriptEngineSupplier uut = spy(new JavaScriptEngineSupplier()); uut.get(); verify(uut).getEngineByName(new String[] { "nashorn", "javascript", "js" }); }
FactSpec { public static FactSpec ns(String ns) { return new FactSpec(ns); } FactSpec(@NonNull @JsonProperty("ns") String ns); FactSpec meta(@NonNull String k, @NonNull String v); static FactSpec ns(String ns); FilterScript filterScript(); FactSpec filterScript(FilterScript script); @Deprecated FactSpec jsFilterScript(...
@SuppressWarnings("static-access") @Test void testFactSpecNs() { assertEquals("y", FactSpec.ns("x").ns("y").ns()); } @Test void testFactSpecType() { assertEquals("y", FactSpec.ns("x").type("y").type()); } @Test void testFactSpecAggId() { UUID id = UUID.randomUUID(); assertEquals(id, FactSpec.ns("x").aggId(id).aggId());...
FactSpec { public FilterScript filterScript() { if (filterScript != null) return filterScript; else if (jsFilterScript != null) return new FilterScript("js", jsFilterScript); else return null; } FactSpec(@NonNull @JsonProperty("ns") String ns); FactSpec meta(@NonNull String k, @NonNull String v); static FactSpec ns(Str...
@Test public void testJsFilterScriptDeserDownwardCompatibility() throws Exception { String script = "foo"; String json = "{\"ns\":\"x\",\"jsFilterScript\":\"" + script + "\"}"; FactSpec spec = FactCastJson.readValue(FactSpec.class, json); assertEquals(new FilterScript("js", script), spec.filterScript()); }
FactSpecMatcher implements Predicate<Fact> { protected boolean metaMatch(Fact t) { if ((meta.isEmpty())) { return true; } return meta.entrySet().stream().allMatch(e -> e.getValue().equals(t.meta(e.getKey()))); } FactSpecMatcher(@NonNull FactSpec spec); @Override boolean test(Fact t); static Predicate<Fact> matchesAnyOf...
@Test void testMetaMatch() { assertTrue(metaMatch(FactSpec.ns("default").meta("foo", "bar"), new TestFact().meta("foo", "bar"))); assertTrue( metaMatch(FactSpec.ns("default").meta("foo", "bar"), new TestFact().meta("x", "y") .meta("foo", "bar"))); assertTrue(metaMatch(FactSpec.ns("default"), new TestFact().meta("x", "y...
PgIdFactExtractor implements RowMapper<Fact> { @Override @NonNull public Fact mapRow(@NonNull ResultSet rs, int rowNum) throws SQLException { serial.set(rs.getLong(PgConstants.COLUMN_SER)); return new IdOnlyFact(UUID.fromString(rs.getString(PgConstants.ALIAS_ID))); } @Override @NonNull Fact mapRow(@NonNull ResultSet r...
@Test void testMapRow() throws Exception { ResultSet rs = mock(ResultSet.class); final UUID id = UUID.randomUUID(); when(rs.getString(PgConstants.ALIAS_ID)).thenReturn(id.toString()); when(rs.getLong(PgConstants.COLUMN_SER)).thenReturn(27L); Fact mapRow = uut.mapRow(rs, 1); assertEquals(27, serial.get()); assertEquals(...
FactSpecMatcher implements Predicate<Fact> { protected boolean nsMatch(Fact t) { return ns.equals(t.ns()); } FactSpecMatcher(@NonNull FactSpec spec); @Override boolean test(Fact t); static Predicate<Fact> matchesAnyOf(@NonNull List<FactSpec> spec); static Predicate<Fact> matches(@NonNull FactSpec spec); }
@Test void testNsMatch() { assertTrue(nsMatch(FactSpec.ns("default"), new TestFact().ns("default"))); assertFalse(nsMatch(FactSpec.ns("default"), new TestFact().ns("xxx"))); }
FactSpecMatcher implements Predicate<Fact> { protected boolean typeMatch(Fact t) { if (type == null) { return true; } String otherType = t.type(); return type.equals(otherType); } FactSpecMatcher(@NonNull FactSpec spec); @Override boolean test(Fact t); static Predicate<Fact> matchesAnyOf(@NonNull List<FactSpec> spec); ...
@Test void testTypeMatch() { assertTrue(typeMatch(FactSpec.ns("default").type("a"), new TestFact().type("a"))); assertTrue(typeMatch(FactSpec.ns("default"), new TestFact().type("a"))); assertFalse(typeMatch(FactSpec.ns("default").type("a"), new TestFact().type("x"))); assertFalse(typeMatch(FactSpec.ns("default").type("...
FactSpecMatcher implements Predicate<Fact> { protected boolean aggIdMatch(Fact t) { if (aggId == null) { return true; } return t.aggIds().contains(aggId); } FactSpecMatcher(@NonNull FactSpec spec); @Override boolean test(Fact t); static Predicate<Fact> matchesAnyOf(@NonNull List<FactSpec> spec); static Predicate<Fact> ...
@Test void testAggIdMatch() { UUID u1 = UUID.randomUUID(); UUID u2 = UUID.randomUUID(); assertTrue(aggIdMatch(FactSpec.ns("default").aggId(u1), new TestFact().aggId(u1))); assertTrue(aggIdMatch(FactSpec.ns("default"), new TestFact().aggId(u1))); assertFalse(aggIdMatch(FactSpec.ns("default").aggId(u1), new TestFact().ag...
FactSpecMatcher implements Predicate<Fact> { @SneakyThrows @Generated protected boolean scriptMatch(Fact t) { if (script == null) { return true; } return (Boolean) scriptEngine.eval("test(" + t.jsonHeader() + "," + t.jsonPayload() + ")"); } FactSpecMatcher(@NonNull FactSpec spec); @Override boolean test(Fact t); static...
@Test void testScriptMatch() { assertTrue(scriptMatch(FactSpec.ns("default"), new TestFact())); assertFalse( scriptMatch(FactSpec.ns("default").jsFilterScript("function (h,e){ return false }"), new TestFact())); assertTrue(scriptMatch(FactSpec.ns("default").jsFilterScript( "function (h,e){ return h.meta.x=='y' }"), new...
FactSpecMatcher implements Predicate<Fact> { public static Predicate<Fact> matchesAnyOf(@NonNull List<FactSpec> spec) { List<FactSpecMatcher> matchers = spec.stream() .map(FactSpecMatcher::new) .collect(Collectors.toList()); return f -> matchers.stream().anyMatch(p -> p.test(f)); } FactSpecMatcher(@NonNull FactSpec spe...
@Test void testMatchesAnyOfNull() { Assertions.assertThrows(NullPointerException.class, () -> { FactSpecMatcher.matchesAnyOf(null); }); } @Test void testMatchesAnyOf() { Predicate<Fact> p = FactSpecMatcher.matchesAnyOf(Arrays.asList(FactSpec.ns("1"), FactSpec .ns("2"))); assertTrue(p.test(new TestFact().ns("1"))); asse...
FactSpecMatcher implements Predicate<Fact> { public static Predicate<Fact> matches(@NonNull FactSpec spec) { return new FactSpecMatcher(spec); } FactSpecMatcher(@NonNull FactSpec spec); @Override boolean test(Fact t); static Predicate<Fact> matchesAnyOf(@NonNull List<FactSpec> spec); static Predicate<Fact> matches(@Non...
@Test public void testMatchesNull() throws Exception { TestHelper.expectNPE(() -> { FactSpecMatcher.matches(null); }); }
IdOnlyFact implements Fact { @Override public String ns() { throw new UnsupportedOperationException(); } @Override String ns(); @Override String type(); @Override Set<UUID> aggIds(); @Override String jsonHeader(); @Override String jsonPayload(); @Override String meta(String key); }
@Test void testNs() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).ns(); }); }
IdOnlyFact implements Fact { @Override public String type() { throw new UnsupportedOperationException(); } @Override String ns(); @Override String type(); @Override Set<UUID> aggIds(); @Override String jsonHeader(); @Override String jsonPayload(); @Override String meta(String key); }
@Test void testType() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).type(); }); }
IdOnlyFact implements Fact { @Override public Set<UUID> aggIds() { throw new UnsupportedOperationException(); } @Override String ns(); @Override String type(); @Override Set<UUID> aggIds(); @Override String jsonHeader(); @Override String jsonPayload(); @Override String meta(String key); }
@Test void testAggIds() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).aggIds(); }); }
IdOnlyFact implements Fact { @Override public String jsonHeader() { throw new UnsupportedOperationException(); } @Override String ns(); @Override String type(); @Override Set<UUID> aggIds(); @Override String jsonHeader(); @Override String jsonPayload(); @Override String meta(String key); }
@Test void testJsonHeader() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).jsonHeader(); }); }
IdOnlyFact implements Fact { @Override public String jsonPayload() { throw new UnsupportedOperationException(); } @Override String ns(); @Override String type(); @Override Set<UUID> aggIds(); @Override String jsonHeader(); @Override String jsonPayload(); @Override String meta(String key); }
@Test void testJsonPayload() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).jsonPayload(); }); }
IdOnlyFact implements Fact { @Override public String meta(String key) { throw new UnsupportedOperationException(); } @Override String ns(); @Override String type(); @Override Set<UUID> aggIds(); @Override String jsonHeader(); @Override String jsonPayload(); @Override String meta(String key); }
@Test void testMeta() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).meta(""); }); }
DefaultFact implements Fact, Externalizable { public static Fact of(@NonNull String jsonHeader, @NonNull String jsonPayload) { return new DefaultFact(jsonHeader, jsonPayload); } @Deprecated DefaultFact(); @SneakyThrows protected DefaultFact(String jsonHeader, String jsonPayload); DefaultFact(Header header, String pa...
@Test void testNullHeader() { Assertions.assertThrows(NullPointerException.class, () -> { DefaultFact.of("{}", null); }); } @Test void testNullPayload() { Assertions.assertThrows(NullPointerException.class, () -> { DefaultFact.of(null, "{}"); }); } @Test void testNullContracts() { Assertions.assertThrows(NullPointerExc...
PgFact implements Fact { @SneakyThrows @Generated public static Fact from(ResultSet resultSet) { String id = resultSet.getString(PgConstants.ALIAS_ID); String aggId = resultSet.getString(PgConstants.ALIAS_AGGID); String type = resultSet.getString(PgConstants.ALIAS_TYPE); String ns = resultSet.getString(PgConstants.ALIA...
@Test void testFrom() throws Exception { ResultSet rs = mock(ResultSet.class); when(rs.next()).thenReturn(true); String ns = "ns"; String type = "type"; String aggId = UUID.randomUUID().toString(); String aggIdArr = "[\"" + aggId + "\"]"; String header = "{\"meta\":{\"foo\":\"1\",\"bar\":\"2\",\"baz\":\"3\"}}"; String ...
DefaultFactCast implements FactCast { @Override @NonNull public Subscription subscribeEphemeral(@NonNull SubscriptionRequest req, @NonNull FactObserver observer) { return store.subscribe(SubscriptionRequestTO.forFacts(req), observer); } @Override @NonNull Subscription subscribeEphemeral(@NonNull SubscriptionRequest re...
@Test void testSubscribeEphemeral() { when(store.subscribe(csr.capture(), any())).thenReturn(mock(Subscription.class)); final UUID since = UUID.randomUUID(); SubscriptionRequest r = SubscriptionRequest.follow(FactSpec.ns("foo")) .or(FactSpec.ns("some").type("type")) .from(since); uut.subscribeEphemeral(r, f -> { }); ve...
DefaultFactCast implements FactCast { @Override public void publish(@NonNull List<? extends Fact> factsToPublish) { FactValidation.validate(factsToPublish); store.publish(factsToPublish); } @Override @NonNull Subscription subscribeEphemeral(@NonNull SubscriptionRequest req, @NonNull FactObserver observer);...
@Test void testPublish() { doNothing().when(store).publish(cfacts.capture()); final TestFact f = new TestFact(); uut.publish(f); final List<Fact> l = cfacts.getValue(); assertEquals(1, l.size()); assertTrue(l.contains(f)); } @Test void testNoId() { Assertions.assertThrows(IllegalArgumentException.class, () -> { uut.pub...
PgFact implements Fact { @VisibleForTesting static Set<UUID> toUUIDArray(String aggIdArrayAsString) { Set<UUID> set = new LinkedHashSet<>(); if (aggIdArrayAsString != null && aggIdArrayAsString.trim().length() > 2) { UUID[] readValue = FactCastJson.readValue(UUID[].class, aggIdArrayAsString); if (readValue != null) { s...
@Test void testToUUIDArrayNull() { Set<UUID> res = PgFact.toUUIDArray(null); assertTrue(res.isEmpty()); } @Test void testToUUIDArrayEmpty() { Set<UUID> res = PgFact.toUUIDArray("[]"); assertTrue(res.isEmpty()); } @Test void testToUUIDArraySingle() { UUID aggId1 = UUID.randomUUID(); Set<UUID> res = PgFact.toUUIDArray("[...
DefaultFactCast implements FactCast { @Override @NonNull public OptionalLong serialOf(@NonNull UUID id) { return store.serialOf(id); } @Override @NonNull Subscription subscribeEphemeral(@NonNull SubscriptionRequest req, @NonNull FactObserver observer); @Override void publish(@NonNull List<? extends Fact> f...
@Test void testSerialOf() { when(store.serialOf(any(UUID.class))).thenReturn(OptionalLong.empty()); UUID id = UUID.randomUUID(); uut.serialOf(id); verify(store).serialOf(same(id)); } @Test void testSerialOfNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.serialOf(null); }); }
DefaultFactCast implements FactCast { @Override public Set<String> enumerateNamespaces() { return store.enumerateNamespaces(); } @Override @NonNull Subscription subscribeEphemeral(@NonNull SubscriptionRequest req, @NonNull FactObserver observer); @Override void publish(@NonNull List<? extends Fact> factsTo...
@Test public void testEnumerateNamespaces() throws Exception { Set<String> set = new HashSet<>(); when(store.enumerateNamespaces()).thenReturn(set); assertSame(set, FactCast.from(store).enumerateNamespaces()); }
DefaultFactCast implements FactCast { @Override public Set<String> enumerateTypes(@NonNull String ns) { return store.enumerateTypes(ns); } @Override @NonNull Subscription subscribeEphemeral(@NonNull SubscriptionRequest req, @NonNull FactObserver observer); @Override void publish(@NonNull List<? extends Fac...
@Test public void testEnumerateTypesNullContract() throws Exception { assertThrows(NullPointerException.class, () -> { FactCast.from(store).enumerateTypes(null); }); } @Test public void testEnumerateTypes() throws Exception { Set<String> test = new HashSet<>(); LinkedHashSet<String> other = Sets.newLinkedHashSet("foo")...
DefaultFactCast implements FactCast { @Override public LockedOperationBuilder lock(@NonNull String ns) { if (ns.trim().isEmpty()) throw new IllegalArgumentException("Namespace must not be empty"); return new LockedOperationBuilder(this.store, ns); } @Override @NonNull Subscription subscribeEphemeral(@NonNull Subscript...
@Test public void testLockNullContract() throws Exception { assertThrows(NullPointerException.class, () -> { uut.lock(null); }); } @Test public void testLockNamespaceMustNotBeEmpty() throws Exception { assertThrows(IllegalArgumentException.class, () -> { uut.lock(" "); }); }
DefaultFactCast implements FactCast { @Override public Subscription subscribe(@NonNull SubscriptionRequest request, @NonNull FactObserver observer) { return new ReconnectingFactSubscriptionWrapper(store, SubscriptionRequestTO.forFacts( request), observer); } @Override @NonNull Subscription subscribeEphemeral(@NonNull ...
@Test public void testSubscribeNullContracts() throws Exception { assertThrows(NullPointerException.class, () -> { uut.subscribe(null, mock(FactObserver.class)); }); assertThrows(NullPointerException.class, () -> { uut.subscribe(null, null); }); assertThrows(NullPointerException.class, () -> { uut.subscribe(mock(Subscr...
StateToken { public StateToken() { this(UUID.randomUUID()); } StateToken(); }
@Test public void testStateToken() throws Exception { assertThat(new StateToken().uuid()).isNotNull(); }
IntermediatePublishResult { public Optional<Runnable> andThen() { return Optional.ofNullable(andThen); } Optional<Runnable> andThen(); }
@Test public void testNullContracts() throws Exception { assertThrows(NullPointerException.class, () -> { new IntermediatePublishResult(null); }); assertThrows(NullPointerException.class, () -> { new IntermediatePublishResult(new LinkedList<>()).andThen(null); }); } @Test public void testAndThen() throws Exception { In...
LockedOperationBuilder { public OnBuilderStep on(@NonNull UUID aggId, UUID... otherAggIds) { LinkedList<UUID> ids = new LinkedList<>(); ids.add(aggId); ids.addAll(Arrays.asList(otherAggIds)); return new OnBuilderStep(ids); } OnBuilderStep on(@NonNull UUID aggId, UUID... otherAggIds); }
@Test public void testOn() { UUID id = UUID.randomUUID(); OnBuilderStep on = uut.on(id); assertThat(on.ids()).hasSize(1).contains(id); UUID id2 = UUID.randomUUID(); on = uut.on(id, id2); assertThat(on.ids()).hasSize(2).contains(id).contains(id2); assertThrows(NullPointerException.class, () -> { uut.on(null); }); } @Tes...
ExceptionAfterPublish extends IllegalStateException { public ExceptionAfterPublish(@NonNull List<Fact> publishedFacts, @NonNull Throwable e) { super("An exception has happened in the 'andThen' part of your publishing attempt. " + "This is a programming error, as the runnable in andThen is not supposed to throw an Excep...
@Test public void testExceptionAfterPublish() throws Exception { Throwable e = Mockito.mock(Exception.class); List facts = new LinkedList<>(); ExceptionAfterPublish uut = new ExceptionAfterPublish(facts, e); assertThat(uut.publishedFacts()).isSameAs(facts); assertThat(uut.getCause()).isSameAs(e); }
WithOptimisticLock { @NonNull public PublishingResult attempt(@NonNull Attempt operation) throws AttemptAbortedException, OptimisticRetriesExceededException, ExceptionAfterPublish { while (++count <= retry) { StateToken token = store.stateFor(ids, Optional.ofNullable(ns)); try { IntermediatePublishResult r = runAndWrap...
@Test void attemptReturnsNullShouldBeAnAbort() { WithOptimisticLock uut = new WithOptimisticLock(Mockito.mock(FactStore.class), null, Collections.singletonList(UUID.randomUUID())); Assertions.assertThrows(AttemptAbortedException.class, () -> { uut.attempt(() -> null); } ); }
SubscriptionImpl implements Subscription { @Override public void close() { if (!closed.getAndSet(true)) { SubscriptionCancelledException closedException = new SubscriptionCancelledException( "Client closed the subscription"); catchup.completeExceptionally(closedException); complete.completeExceptionally(closedException...
@Test void testClose() throws Exception { expect(TimeoutException.class, () -> uut.awaitCatchup(10)); expect(TimeoutException.class, () -> uut.awaitComplete(10)); uut.close(); expect(SubscriptionCancelledException.class, () -> uut.awaitCatchup(10)); expect(SubscriptionCancelledException.class, () -> uut.awaitComplete(1...
SubscriptionImpl implements Subscription { @Override public Subscription awaitCatchup() throws SubscriptionCancelledException { try { catchup.get(); } catch (InterruptedException | ExecutionException e) { throw new SubscriptionCancelledException(e); } return this; } @Override void close(); @Override Subscription await...
@Test void testAwaitCatchup() { expect(TimeoutException.class, () -> uut.awaitCatchup(10)); expect(TimeoutException.class, () -> uut.awaitComplete(10)); uut.notifyCatchup(); uut.awaitCatchup(); expect(TimeoutException.class, () -> uut.awaitComplete(10)); }
SubscriptionImpl implements Subscription { @Override public Subscription awaitComplete() throws SubscriptionCancelledException { try { complete.get(); } catch (InterruptedException | ExecutionException e) { throw new SubscriptionCancelledException(e); } return this; } @Override void close(); @Override Subscription awa...
@Test void testAwaitComplete() { expect(TimeoutException.class, () -> uut.awaitCatchup(10)); expect(TimeoutException.class, () -> uut.awaitComplete(10)); uut.notifyComplete(); uut.awaitCatchup(); uut.awaitComplete(); }
SubscriptionImpl implements Subscription { public void notifyElement(@NonNull T e) { if (!closed.get()) { observer.onNext(e); } } @Override void close(); @Override Subscription awaitCatchup(); Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); Subscription awaitComplete(long wait...
@Test void testNotifyElementNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.notifyElement(null); }); }
SubscriptionImpl implements Subscription { public void notifyError(Throwable e) { if (!closed.get()) { observer.onError(e); if (!catchup.isDone()) { catchup.completeExceptionally(e); } if (!complete.isDone()) { complete.completeExceptionally(e); } tryClose(); } } @Override void close(); @Override Subscription awaitCat...
@Test void testNotifyErrorNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.notifyError(null); }); }