method2testcases
stringlengths
118
3.08k
### Question: 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 previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getPreviewHeight() throws Exception { assertEquals(pixabayImage.getPreviewHeight(), 180); }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getPageURL() throws Exception { assertEquals(pixabayImage.getPageURL(), "http: }
### Question: 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 previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getPreviewURL() throws Exception { assertEquals(pixabayImage.getPreviewURL(), "http: }
### Question: 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 previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getWebformatURL() throws Exception { assertEquals(pixabayImage.getWebformatURL(), "http: }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getImageWidth() throws Exception { assertEquals(pixabayImage.getImageWidth(), 1080); }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getUserId() throws Exception { assertEquals(pixabayImage.getUserId(), 123456); }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getUser() throws Exception { assertEquals(pixabayImage.getUser(), "By: user"); }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getType() throws Exception { assertEquals(pixabayImage.getType(), PixabayImageType.illustration); }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getId() throws Exception { assertEquals(pixabayImage.getId(), 987654); }
### Question: 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 previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getUserImageURL() throws Exception { assertEquals(pixabayImage.getUserImageURL(), "http: }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getImageHeight() throws Exception { assertEquals(pixabayImage.getImageHeight(), 1024); }
### Question: 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 previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getLikes() throws Exception { assertEquals(pixabayImage.getLikes(), "100"); }
### Question: 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, String previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getFavorites() throws Exception { assertEquals(pixabayImage.getFavorites(), "50"); }
### Question: 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 webformatHeight, long views, int webformatWidth, int previewWidth, int comments, long downloads, String pageURL, String previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getTags() throws Exception { assertEquals(pixabayImage.getTags(), null); }
### Question: 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 previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getWebformatHeight() throws Exception { assertEquals(pixabayImage.getWebformatHeight(), 90); }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getViews() throws Exception { assertEquals(pixabayImage.getViews(), 1234); }
### Question: 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 previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getWebformatWidth() throws Exception { assertEquals(pixabayImage.getWebformatWidth(), 360); }
### Question: 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 previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getPreviewWidth() throws Exception { assertEquals(pixabayImage.getPreviewWidth(), 180); }
### Question: 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, String previewURL, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getComments() throws Exception { assertEquals(pixabayImage.getComments(), "150"); }
### Question: 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, String webformatURL, int imageWidth, long userId, String user, PixabayImageType type, long id, String userImageURL, int imageHeight); int getPreviewHeight(); String getLikes(); String getFavorites(); String getTags(); int getWebformatHeight(); long getViews(); int getWebformatWidth(); int getPreviewWidth(); String getComments(); long getDownloads(); String getPageURL(); String getPreviewURL(); String getWebformatURL(); int getImageWidth(); long getUserId(); String getUser(); PixabayImageType getType(); long getId(); String getUserImageURL(); int getImageHeight(); }### Answer: @Test public void getDownloads() throws Exception { assertEquals(pixabayImage.getDownloads(), 987); }
### Question: 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 prefix); static Function<HttpRequest, String> PREFIXED_REQUEST_TARGET_NAME(final String prefix); static Function<HttpRequest, String> PREFIXED_REQUEST_METHOD_TARGET_NAME( final String prefix); static Function<HttpRequest, String> REQUEST_METHOD_NAME; static Function<HttpRequest, String> REQUEST_TARGET_NAME; static Function<HttpRequest, String> REQUEST_METHOD_TARGET_NAME; }### Answer: @Test public void prefixedRequestMethodSpanNameFormatsCorrectly() { Function<HttpRequest, String> spanNameProvider = ClientSpanNameProvider .PREFIXED_REQUEST_METHOD_NAME("ELASTICSEARCH - "); assertEquals("ELASTICSEARCH - GET", spanNameProvider.apply(getRequest)); assertEquals("ELASTICSEARCH - GET", spanNameProvider.apply(getRequestWithID)); assertEquals("ELASTICSEARCH - GET", spanNameProvider.apply(getIndexRequestWithIDAndParameters)); assertEquals("ELASTICSEARCH - GET", spanNameProvider.apply(getRequestWithIDWithSource)); assertEquals("ELASTICSEARCH - POST", spanNameProvider.apply(postRequestCancelTaskID)); } @Test public void prefixedRequestMethodSpanNameHandlesNull() { Function<HttpRequest, String> spanNameProvider = ClientSpanNameProvider .PREFIXED_REQUEST_METHOD_NAME(null); assertEquals("GET", spanNameProvider.apply(getRequest)); assertEquals("GET", spanNameProvider.apply(getRequestWithID)); assertEquals("GET", spanNameProvider.apply(getIndexRequestWithIDAndParameters)); assertEquals("GET", spanNameProvider.apply(getRequestWithIDWithSource)); assertEquals("POST", spanNameProvider.apply(postRequestCancelTaskID)); }
### Question: 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 BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { emitter.onNext(intent); } }; context.registerReceiver(receiver, intentFilter); emitter.setCancellable(new Cancellable() { @Override public void cancel() throws Exception { if (Looper.getMainLooper() == Looper.myLooper()) { context.unregisterReceiver(receiver); } else { final Scheduler.Worker inner = mainThread().createWorker(); inner.schedule(new Runnable() { @Override public void run() { context.unregisterReceiver(receiver); inner.dispose(); } }); } } }); } }); } @NonNull static Observable<Intent> receives(@NonNull final Context context, @NonNull final IntentFilter intentFilter); }### Answer: @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(foobar); tester.assertValues(foobar); Intent barbaz = new Intent("test").putExtra("bar", "baz"); context.sendBroadcast(barbaz); tester.assertValues(foobar, barbaz); Intent nullIntent = new Intent("test_null").putExtra("bar", "baz"); context.sendBroadcast(nullIntent); tester.assertValues(foobar, barbaz); context.sendBroadcast(barbaz); tester.assertValues(foobar, barbaz, barbaz); }
### Question: 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 BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { emitter.onNext(intent); } }; emitter.setCancellation(new Cancellable() { @Override public void cancel() throws Exception { if (Looper.getMainLooper() == Looper.myLooper()) { context.unregisterReceiver(receiver); } else { final Scheduler.Worker inner = mainThread().createWorker(); inner.schedule(new Action0() { @Override public void call() { context.unregisterReceiver(receiver); inner.unsubscribe(); } }); } } }); context.registerReceiver(receiver, intentFilter); } }, Emitter.BackpressureMode.BUFFER); } @NonNull @CheckResult static Observable<Intent> receives(@NonNull final Context context, @NonNull final IntentFilter intentFilter); }### Answer: @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 intent1 = new Intent("test_action").putExtra("foo", "bar"); application.sendBroadcast(intent1); o.assertValues(intent1); Intent intent2 = new Intent("test_action").putExtra("bar", "baz"); application.sendBroadcast(intent2); o.assertValues(intent1, intent2); Intent intent3 = new Intent("test_action_ignored"); application.sendBroadcast(intent3); o.assertValues(intent1, intent2); Intent intent4 = new Intent("test_action").putExtra("bar", "baz"); subscription.unsubscribe(); application.sendBroadcast(intent4); o.assertValues(intent1, intent2); }
### Question: 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 = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { emitter.onNext(intent); } }; LocalBroadcastManager.getInstance(context).registerReceiver(receiver, intentFilter); emitter.setCancellable(new Cancellable() { @Override public void cancel() throws Exception { if (Looper.getMainLooper() == Looper.myLooper()) { LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver); } else { final Scheduler.Worker inner = mainThread().createWorker(); inner.schedule(new Runnable() { @Override public void run() { LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver); inner.dispose(); } }); } } }); } }); } @NonNull static Observable<Intent> receives(@NonNull final Context context, @NonNull final IntentFilter intentFilter); }### Answer: @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"); LocalBroadcastManager.getInstance(context).sendBroadcast(foobar); tester.assertValues(foobar); Intent barbaz = new Intent("test").putExtra("bar", "baz"); LocalBroadcastManager.getInstance(context).sendBroadcast(barbaz); tester.assertValues(foobar, barbaz); Intent nullIntent = new Intent("test_null").putExtra("bar", "baz"); LocalBroadcastManager.getInstance(context).sendBroadcast(nullIntent); tester.assertValues(foobar, barbaz); LocalBroadcastManager.getInstance(context).sendBroadcast(barbaz); tester.assertValues(foobar, barbaz, barbaz); }
### Question: FlaxModel { protected void notifyModelChanged() { modelSubject.onNext((M)this); } FlaxModel(); }### Answer: @Test public void testNotifyModelChanged() throws Exception { TestObserver testSubscriber = flaxModel.getObservable().test(); flaxModel.notifyModelChanged(); flaxModel.notifyModelChanged(); testSubscriber.assertValueCount(3); testSubscriber.assertValues(flaxModel, flaxModel, flaxModel); }
### Question: FlaxStore { static<M extends FlaxModel> M getModel(Class modelClass) { return getModel(modelClass, 0); } private FlaxStore(); }### Answer: @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 testStoreReturnsDifferentValuesForDifferentKeys() throws Exception { Foo fooOne = FlaxStore.getModel(Foo.class, 0); Foo fooTwo = FlaxStore.getModel(Foo.class, 1); assertNotEquals("fooOne and fooTwo should be different but they are the same.", fooOne, fooTwo); }
### Question: 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 setServoAngle(int channel, int angle); int map(int x, int inMin, int inMax, int outMin, int outMax); }### Answer: @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,device.map(4,10,20,30,40)); assertEquals(25,device.map(5,10,20,30,40)); assertEquals(26,device.map(6,10,20,30,40)); assertEquals(27,device.map(7,10,20,30,40)); assertEquals(28,device.map(8,10,20,30,40)); assertEquals(29,device.map(9,10,20,30,40)); }
### Question: Order { public double getTotal() { double total = 0; for (Product product : products) { total += product.getPrice(); } return total; } Order(Product ... products); double getTotal(); }### Answer: @Test public void should_sum_all_prices() { Order order = new Order(new Product(30), new Product(40.0)); assertEquals(70.0, order.getTotal(), ERROR); }
### Question: PgConfigurationProperties implements ApplicationListener<ApplicationReadyEvent> { public int getPageSizeForIds() { return pageSize * idOnlyFactor; } int getPageSizeForIds(); int getQueueSizeForIds(); int getFetchSizeForIds(); int getFetchSize(); @Override void onApplicationEvent(ApplicationReadyEvent event); }### Answer: @Test void testGetPageSizeForIds() { assertEquals(100000, uut.getPageSizeForIds()); }
### Question: 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); } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Autowired @Generated GrpcFactStore(FactCastGrpcChannelFactory channelFactory, @Value("${grpc.client.factstore.credentials:#{null}}") Optional<String> credentials); @Generated @VisibleForTesting GrpcFactStore(Channel channel, Optional<String> credentials); private GrpcFactStore(RemoteFactStoreBlockingStub newBlockingStub, RemoteFactStoreStub newStub, Optional<String> credentials); @Override Optional<Fact> fetchById(UUID id); @Override void publish(@NonNull List<? extends Fact> factsToPublish); @Override Subscription subscribe(@NonNull SubscriptionRequestTO req, @NonNull FactObserver observer); @Override OptionalLong serialOf(@NonNull UUID l); synchronized void initialize(); @Override synchronized void afterSingletonsInstantiated(); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(String ns); @Override boolean publishIfUnchanged(@NonNull List<? extends Fact> factsToPublish, @NonNull Optional<StateToken> token); @Override void invalidate(@NonNull StateToken token); @Override StateToken stateFor(@NonNull Collection<UUID> forAggIds, @NonNull Optional<String> ns); @Override long currentTime(); }### Answer: @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); }
### Question: 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 static T readValue(@NonNull Class<T> class1, String json); @SneakyThrows static T readValue(@NonNull Class<T> class1, @NonNull InputStream json); static ObjectNode toObjectNode(String json); static ObjectNode newObjectNode(); @SneakyThrows @Generated static String writeValueAsPrettyString(Object o); }### Answer: @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(copy.baz()); }
### Question: 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> class1, String json); @SneakyThrows static T readValue(@NonNull Class<T> class1, @NonNull InputStream json); static ObjectNode toObjectNode(String json); static ObjectNode newObjectNode(); @SneakyThrows @Generated static String writeValueAsPrettyString(Object o); }### Answer: @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.readValue(FactCastJson.class, (InputStream) null)); } @Test void testReadValueFromInputStream() { X x = FactCastJson.readValue(X.class, new ByteArrayInputStream("{\"foo\":\"baz\",\"bar\":7}" .getBytes())); assertThat(x.foo).isEqualTo("baz"); assertThat(x.bar).isEqualTo(7); }
### Question: 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 json); @SneakyThrows static T readValue(@NonNull Class<T> class1, @NonNull InputStream json); static ObjectNode toObjectNode(String json); static ObjectNode newObjectNode(); @SneakyThrows @Generated static String writeValueAsPrettyString(Object o); }### Answer: @Test void testWriteValueNull() { expectNPE(() -> FactCastJson.writeValueAsString(null)); }
### Question: 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 T readValue(@NonNull Class<T> class1, @NonNull InputStream json); static ObjectNode toObjectNode(String json); static ObjectNode newObjectNode(); @SneakyThrows @Generated static String writeValueAsPrettyString(Object o); }### Answer: @Test void testNewObjectNode() { assertNotNull(FactCastJson.newObjectNode()); assertTrue(FactCastJson.newObjectNode() instanceof ObjectNode); }
### Question: 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 T readValue(@NonNull Class<T> class1, String json); @SneakyThrows static T readValue(@NonNull Class<T> class1, @NonNull InputStream json); static ObjectNode toObjectNode(String json); static ObjectNode newObjectNode(); @SneakyThrows @Generated static String writeValueAsPrettyString(Object o); }### Answer: @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()); assertNull(objectNode.get("y")); }
### Question: 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); }### Answer: @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(rs.getString(PgConstants.ALIAS_NS)).thenReturn("ns"); when(rs.getString(PgConstants.COLUMN_HEADER)).thenReturn("{\"ns\":\"ns\",\"id\":\"" + id + "\"}"); when(rs.getString(PgConstants.COLUMN_PAYLOAD)).thenReturn("{}"); when(rs.getLong(PgConstants.COLUMN_SER)).thenReturn(27L); Fact mapRow = uut.mapRow(rs, 1); assertEquals(27, serial.get()); assertEquals(id, mapRow.id()); }
### Question: 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 readValue(@NonNull Class<T> class1, String json); @SneakyThrows static T readValue(@NonNull Class<T> class1, @NonNull InputStream json); static ObjectNode toObjectNode(String json); static ObjectNode newObjectNode(); @SneakyThrows @Generated static String writeValueAsPrettyString(Object o); }### Answer: @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"; } String pretty = FactCastJson.writeValueAsPrettyString(new TestObject()); System.out.println(pretty); assertTrue(pretty.contains("\"foo\" : \"bar\"")); }
### Question: 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(); @Override ScriptEngine get(); }### Answer: @Test void testGet() throws Exception { JavaScriptEngineSupplier uut = spy(new JavaScriptEngineSupplier()); uut.get(); verify(uut).getEngineByName(new String[] { "nashorn", "javascript", "js" }); }
### Question: 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(String script); @Deprecated String jsFilterScript(); }### Answer: @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()); } @Test void testFactSpecEquality() { FactSpec f1 = FactSpec.ns("x"); FactSpec f2 = FactSpec.ns("x"); assertEquals(f1, f2); assertNotSame(f1, f2); }
### Question: 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(String ns); FilterScript filterScript(); FactSpec filterScript(FilterScript script); @Deprecated FactSpec jsFilterScript(String script); @Deprecated String jsFilterScript(); }### Answer: @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()); }
### Question: 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(@NonNull List<FactSpec> spec); static Predicate<Fact> matches(@NonNull FactSpec spec); }### Answer: @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").meta("foo", "bar"))); assertFalse(metaMatch(FactSpec.ns("default").meta("foo", "bar"), new TestFact().meta("foo", "baz"))); assertFalse(metaMatch(FactSpec.ns("default").meta("foo", "bar"), new TestFact())); }
### Question: 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 rs, int rowNum); }### Answer: @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(id, mapRow.id()); } @Test void testMapRowNullContracts() throws Exception { assertThrows(NullPointerException.class, () -> { uut.mapRow(null, 1); }); }
### Question: 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); }### Answer: @Test void testNsMatch() { assertTrue(nsMatch(FactSpec.ns("default"), new TestFact().ns("default"))); assertFalse(nsMatch(FactSpec.ns("default"), new TestFact().ns("xxx"))); }
### Question: 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); static Predicate<Fact> matches(@NonNull FactSpec spec); }### Answer: @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("a"), new TestFact())); }
### Question: 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> matches(@NonNull FactSpec spec); }### Answer: @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().aggId(u2))); assertFalse(aggIdMatch(FactSpec.ns("default").aggId(u1), new TestFact())); }
### Question: 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 Predicate<Fact> matchesAnyOf(@NonNull List<FactSpec> spec); static Predicate<Fact> matches(@NonNull FactSpec spec); }### Answer: @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 TestFact().meta("x", "y"))); }
### Question: 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 spec); @Override boolean test(Fact t); static Predicate<Fact> matchesAnyOf(@NonNull List<FactSpec> spec); static Predicate<Fact> matches(@NonNull FactSpec spec); }### Answer: @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"))); assertTrue(p.test(new TestFact().ns("2"))); assertFalse(p.test(new TestFact().ns("3"))); }
### Question: 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(@NonNull FactSpec spec); }### Answer: @Test public void testMatchesNull() throws Exception { TestHelper.expectNPE(() -> { FactSpecMatcher.matches(null); }); }
### Question: 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); }### Answer: @Test void testNs() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).ns(); }); }
### Question: 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); }### Answer: @Test void testType() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).type(); }); }
### Question: 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); }### Answer: @Test void testAggIds() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).aggIds(); }); }
### Question: 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); }### Answer: @Test void testJsonHeader() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).jsonHeader(); }); }
### Question: 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); }### Answer: @Test void testJsonPayload() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).jsonPayload(); }); }
### Question: 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); }### Answer: @Test void testMeta() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new IdOnlyFact(UUID.randomUUID()).meta(""); }); }
### Question: 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 req, @NonNull FactObserver observer); @Override void publish(@NonNull List<? extends Fact> factsToPublish); @Override @NonNull OptionalLong serialOf(@NonNull UUID id); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(@NonNull String ns); @Override LockedOperationBuilder lock(@NonNull String ns); @Override LockedOperationBuilder lockGlobally(); @Override Subscription subscribe(@NonNull SubscriptionRequest request, @NonNull FactObserver observer); }### Answer: @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 -> { }); verify(store).subscribe(any(), any()); final SubscriptionRequestTO req = csr.getValue(); assertTrue(req.continuous()); assertFalse(req.idOnly()); assertEquals(since, req.startingAfter().get()); assertFalse(req.ephemeral()); } @Test void testSubscribeFactsNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.subscribeEphemeral(null, null); }); } @Test void testSubscribeFacts1stArgNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.subscribeEphemeral(null, f -> { }); }); } @Test void testSubscribeFacts2ndArgNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.subscribeEphemeral(SubscriptionRequest.follow(FactSpec.ns("foo")).fromScratch(), null); }); }
### Question: 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); @Override void publish(@NonNull List<? extends Fact> factsToPublish); @Override @NonNull OptionalLong serialOf(@NonNull UUID id); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(@NonNull String ns); @Override LockedOperationBuilder lock(@NonNull String ns); @Override LockedOperationBuilder lockGlobally(); @Override Subscription subscribe(@NonNull SubscriptionRequest request, @NonNull FactObserver observer); }### Answer: @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.publish(new TestFact().id(null)); }); } @Test void testNoNamespace() { Assertions.assertThrows(IllegalArgumentException.class, () -> { uut.publish(new TestFact().ns(null)); }); } @Test void testPublishOneNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.publish((Fact) null); }); } @Test void testPublishWithAggregatedException() { try { uut.publish(new NullFact()); fail(); } catch (FactValidationException e) { assertThat(e.getMessage()).contains("lacks required namespace"); assertThat(e.getMessage()).contains("lacks required id"); } } @Test void testPublishManyNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.publish((List<Fact>) null); }); }
### Question: 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) { set.addAll(Arrays.asList(readValue)); } } return set; } @Override String meta(String key); @SneakyThrows @Generated static Fact from(ResultSet resultSet); }### Answer: @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("[\"" + aggId1 + "\"]"); assertEquals(1, res.size()); assertTrue(res.contains(aggId1)); } @Test void testToUUIDArrayMutli() { UUID aggId1 = UUID.randomUUID(); UUID aggId2 = UUID.randomUUID(); Set<UUID> res = PgFact.toUUIDArray("[\"" + aggId1 + "\",\"" + aggId2 + "\"]"); assertEquals(2, res.size()); assertTrue(res.contains(aggId1)); assertTrue(res.contains(aggId2)); }
### Question: 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> factsToPublish); @Override @NonNull OptionalLong serialOf(@NonNull UUID id); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(@NonNull String ns); @Override LockedOperationBuilder lock(@NonNull String ns); @Override LockedOperationBuilder lockGlobally(); @Override Subscription subscribe(@NonNull SubscriptionRequest request, @NonNull FactObserver observer); }### Answer: @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); }); }
### Question: 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> factsToPublish); @Override @NonNull OptionalLong serialOf(@NonNull UUID id); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(@NonNull String ns); @Override LockedOperationBuilder lock(@NonNull String ns); @Override LockedOperationBuilder lockGlobally(); @Override Subscription subscribe(@NonNull SubscriptionRequest request, @NonNull FactObserver observer); }### Answer: @Test public void testEnumerateNamespaces() throws Exception { Set<String> set = new HashSet<>(); when(store.enumerateNamespaces()).thenReturn(set); assertSame(set, FactCast.from(store).enumerateNamespaces()); }
### Question: 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 Fact> factsToPublish); @Override @NonNull OptionalLong serialOf(@NonNull UUID id); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(@NonNull String ns); @Override LockedOperationBuilder lock(@NonNull String ns); @Override LockedOperationBuilder lockGlobally(); @Override Subscription subscribe(@NonNull SubscriptionRequest request, @NonNull FactObserver observer); }### Answer: @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"); when(store.enumerateTypes("test")).thenReturn(test); assertSame(test, FactCast.from(store).enumerateTypes("test")); }
### Question: 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 SubscriptionRequest req, @NonNull FactObserver observer); @Override void publish(@NonNull List<? extends Fact> factsToPublish); @Override @NonNull OptionalLong serialOf(@NonNull UUID id); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(@NonNull String ns); @Override LockedOperationBuilder lock(@NonNull String ns); @Override LockedOperationBuilder lockGlobally(); @Override Subscription subscribe(@NonNull SubscriptionRequest request, @NonNull FactObserver observer); }### Answer: @Test public void testLockNullContract() throws Exception { assertThrows(NullPointerException.class, () -> { uut.lock(null); }); } @Test public void testLockNamespaceMustNotBeEmpty() throws Exception { assertThrows(IllegalArgumentException.class, () -> { uut.lock(" "); }); }
### Question: StateToken { public StateToken() { this(UUID.randomUUID()); } StateToken(); }### Answer: @Test public void testStateToken() throws Exception { assertThat(new StateToken().uuid()).isNotNull(); }
### Question: IntermediatePublishResult { public Optional<Runnable> andThen() { return Optional.ofNullable(andThen); } Optional<Runnable> andThen(); }### Answer: @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 { IntermediatePublishResult uut = new IntermediatePublishResult(new LinkedList<>()).andThen( () -> { }); assertThat(uut.andThen()).isPresent(); }
### Question: 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); }### Answer: @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); }); } @Test public void testOptimistic() throws Exception { UUID id = new UUID(1, 2); WithOptimisticLock wol = uut.on(id).optimistic(); assertThat(wol).isNotNull(); assertThat(wol.ns()).isEqualTo("ns"); assertThat(wol.ids().get(0)).isEqualTo(id); assertThat(wol.ids().size()).isEqualTo(1); } @Test public void testAttemptNullContracts() throws Exception { assertThrows(NullPointerException.class, () -> { uut.on(UUID.randomUUID()).attempt(null); }); } @Test public void testAttemptAbortsOnNull() throws Exception { assertThrows(AttemptAbortedException.class, () -> { uut.on(UUID.randomUUID()).attempt(() -> null); }); } @Test public void testAttemptWithoutPublishing() throws Exception { assertThrows(IllegalArgumentException.class, () -> { @NonNull PublishingResult attempt = uut.on(UUID.randomUUID()).attempt(() -> mock(IntermediatePublishResult.class) ); }); }
### Question: 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 Exception. " + "Note that publish actually worked, and the ids of your the published facts are " + render(publishedFacts), e); this.publishedFacts = publishedFacts; } ExceptionAfterPublish(@NonNull List<Fact> publishedFacts, @NonNull Throwable e); }### Answer: @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); }
### Question: 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 = runAndWrapException(operation); List<Fact> factsToPublish = r.factsToPublish(); if (factsToPublish == null || factsToPublish.isEmpty()) { throw new IllegalArgumentException( "Attempt exited without abort, but does not publish any facts."); } if (store.publishIfUnchanged(r.factsToPublish(), Optional.of(token))) { try { r.andThen().ifPresent(Runnable::run); } catch (Throwable e) { throw new ExceptionAfterPublish(factsToPublish, e); } return new PublishingResult(factsToPublish); } else { sleep(); } } finally { store.invalidate(token); } } throw new OptimisticRetriesExceededException(retry); } @NonNull PublishingResult attempt(@NonNull Attempt operation); }### Answer: @Test void attemptReturnsNullShouldBeAnAbort() { WithOptimisticLock uut = new WithOptimisticLock(Mockito.mock(FactStore.class), null, Collections.singletonList(UUID.randomUUID())); Assertions.assertThrows(AttemptAbortedException.class, () -> { uut.attempt(() -> null); } ); }
### Question: 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); onClose.run(); } } @Override void close(); @Override Subscription awaitCatchup(); Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); Subscription awaitComplete(long waitTimeInMillis); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyCatchup(); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyComplete(); void notifyError(Throwable e); void notifyElement(@NonNull T e); SubscriptionImpl<T> onClose(Runnable e); static SubscriptionImpl<T> on(@NonNull GenericObserver<T> o); }### Answer: @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(10)); }
### Question: 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 awaitCatchup(); Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); Subscription awaitComplete(long waitTimeInMillis); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyCatchup(); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyComplete(); void notifyError(Throwable e); void notifyElement(@NonNull T e); SubscriptionImpl<T> onClose(Runnable e); static SubscriptionImpl<T> on(@NonNull GenericObserver<T> o); }### Answer: @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)); }
### Question: 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 awaitCatchup(); Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); Subscription awaitComplete(long waitTimeInMillis); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyCatchup(); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyComplete(); void notifyError(Throwable e); void notifyElement(@NonNull T e); SubscriptionImpl<T> onClose(Runnable e); static SubscriptionImpl<T> on(@NonNull GenericObserver<T> o); }### Answer: @Test void testAwaitComplete() { expect(TimeoutException.class, () -> uut.awaitCatchup(10)); expect(TimeoutException.class, () -> uut.awaitComplete(10)); uut.notifyComplete(); uut.awaitCatchup(); uut.awaitComplete(); }
### Question: 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 waitTimeInMillis); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyCatchup(); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyComplete(); void notifyError(Throwable e); void notifyElement(@NonNull T e); SubscriptionImpl<T> onClose(Runnable e); static SubscriptionImpl<T> on(@NonNull GenericObserver<T> o); }### Answer: @Test void testNotifyElementNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.notifyElement(null); }); }
### Question: 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 awaitCatchup(); Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); Subscription awaitComplete(long waitTimeInMillis); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyCatchup(); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyComplete(); void notifyError(Throwable e); void notifyElement(@NonNull T e); SubscriptionImpl<T> onClose(Runnable e); static SubscriptionImpl<T> on(@NonNull GenericObserver<T> o); }### Answer: @Test void testNotifyErrorNull() { Assertions.assertThrows(NullPointerException.class, () -> { uut.notifyError(null); }); }
### Question: 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 waitTimeInMillis); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyCatchup(); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyComplete(); void notifyError(Throwable e); void notifyElement(@NonNull T e); SubscriptionImpl<T> onClose(Runnable e); static SubscriptionImpl<T> on(@NonNull GenericObserver<T> o); }### Answer: @Test void testOnClose() throws Exception { CountDownLatch l = new CountDownLatch(1); uut.onClose(l::countDown); uut.close(); l.await(); }
### Question: 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 awaitComplete(long waitTimeInMillis); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyCatchup(); @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") void notifyComplete(); void notifyError(Throwable e); void notifyElement(@NonNull T e); SubscriptionImpl<T> onClose(Runnable e); static SubscriptionImpl<T> on(@NonNull GenericObserver<T> o); }### Answer: @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.notifyCatchup(); verify(obs).onCatchup(); verify(obs, never()).onComplete(); on.notifyComplete(); verify(obs).onComplete(); }
### Question: ReconnectingFactSubscriptionWrapper implements Subscription { @Override public Subscription awaitComplete() throws SubscriptionCancelledException { for (;;) { assertSubscriptionStateNotClosed(); Subscription cur = currentSubscription.get(); if (cur != null) { try { cur.awaitComplete(); return this; } catch (SubscriptionCancelledException ignore) { } } else { sleep(); } } } ReconnectingFactSubscriptionWrapper(@NonNull FactStore store, @NonNull SubscriptionRequestTO req, @NonNull FactObserver obs); @Override void close(); @Override Subscription awaitCatchup(); @Override Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); @Override Subscription awaitComplete(long waitTimeInMillis); }### Answer: @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 -> subscription); assertThrows(TimeoutException.class, () -> { uut.awaitComplete(51); }); assertTimeout(Duration.ofMillis(1000), () -> { assertThat(uut.awaitComplete(52)).isSameAs(uut); }); verify(subscription).awaitComplete(52); }
### Question: ReconnectingFactSubscriptionWrapper implements Subscription { @Override public Subscription awaitCatchup() throws SubscriptionCancelledException { for (;;) { assertSubscriptionStateNotClosed(); Subscription cur = currentSubscription.get(); if (cur != null) { try { cur.awaitCatchup(); return this; } catch (SubscriptionCancelledException ignore) { } } else { sleep(); } } } ReconnectingFactSubscriptionWrapper(@NonNull FactStore store, @NonNull SubscriptionRequestTO req, @NonNull FactObserver obs); @Override void close(); @Override Subscription awaitCatchup(); @Override Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); @Override Subscription awaitComplete(long waitTimeInMillis); }### Answer: @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 -> subscription); assertThrows(TimeoutException.class, () -> { uut.awaitCatchup(51); }); assertTimeout(Duration.ofMillis(1000), () -> { assertThat(uut.awaitCatchup(52)).isSameAs(uut); }); verify(subscription).awaitCatchup(52); }
### Question: ReconnectingFactSubscriptionWrapper implements Subscription { private void assertSubscriptionStateNotClosed() { if (closed.get()) { throw new SubscriptionCancelledException("Subscription already cancelled"); } } ReconnectingFactSubscriptionWrapper(@NonNull FactStore store, @NonNull SubscriptionRequestTO req, @NonNull FactObserver obs); @Override void close(); @Override Subscription awaitCatchup(); @Override Subscription awaitCatchup(long waitTimeInMillis); @Override Subscription awaitComplete(); @Override Subscription awaitComplete(long waitTimeInMillis); }### Answer: @Test public void testAssertSubscriptionStateNotClosed() throws Exception { uut.close(); assertThrows(SubscriptionCancelledException.class, () -> { uut.awaitCatchup(); }); assertThrows(SubscriptionCancelledException.class, () -> { uut.awaitCatchup(1L); }); assertThrows(SubscriptionCancelledException.class, () -> { uut.awaitComplete(); }); assertThrows(SubscriptionCancelledException.class, () -> { uut.awaitComplete(1L); }); }
### Question: FluentSubscriptionRequest implements SubscriptionRequest { @Override public String toString() { return debugInfo; } FluentSubscriptionRequest(); @Override java.util.Optional<UUID> startingAfter(); @Override String toString(); }### Answer: @Test void testToString() { SubscriptionRequest r = SubscriptionRequest.catchup(FactSpec.ns("foo")).fromScratch(); assertSame(r.debugInfo(), r.toString()); }
### Question: 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.util.Optional<UUID> startingAfter(); static SubscriptionRequestTO forFacts(SubscriptionRequest request); static SubscriptionRequestTO forIds(SubscriptionRequest request); void addSpecs(@NonNull List<FactSpec> factSpecs); @Override List<FactSpec> specs(); String dump(); @Override String toString(); }### Answer: @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 = SubscriptionRequest.catchup(s).fromScratch(); SubscriptionRequestTO uut = SubscriptionRequestTO.forFacts(r); assertEquals(0, uut.maxBatchDelayInMs()); uut.maxBatchDelayInMs(7); assertEquals(7, uut.maxBatchDelayInMs()); }
### Question: 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); static SubscriptionRequestTO forIds(SubscriptionRequest request); void addSpecs(@NonNull List<FactSpec> factSpecs); @Override List<FactSpec> specs(); String dump(); @Override String toString(); }### Answer: @Test void testToString() { SubscriptionRequest r = SubscriptionRequest.catchup(FactSpec.ns("foo")).fromScratch(); String debugInfo = r.debugInfo(); SubscriptionRequestTO uut = SubscriptionRequestTO.forFacts(r); assertEquals(debugInfo, uut.toString()); }
### Question: 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 SubscriptionRequestTO forFacts(SubscriptionRequest request); static SubscriptionRequestTO forIds(SubscriptionRequest request); void addSpecs(@NonNull List<FactSpec> factSpecs); @Override List<FactSpec> specs(); String dump(); @Override String toString(); }### Answer: @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").jsFilterScript( "function (h,e){ return true }"))); assertTrue(uut.hasAnyScriptFilters()); }
### Question: 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 SubscriptionRequestTO forFacts(SubscriptionRequest request); static SubscriptionRequestTO forIds(SubscriptionRequest request); void addSpecs(@NonNull List<FactSpec> factSpecs); @Override List<FactSpec> specs(); String dump(); @Override String toString(); }### Answer: @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.singletonList(FactSpec.ns("buh").jsFilterScript(js))); assertEquals(2, uut.specs().size()); assertEquals(js, uut.specs().get(1).jsFilterScript()); }
### Question: Lz4GrpcServerCodec implements Codec { @Override public String getMessageEncoding() { return "lz4"; } @Override String getMessageEncoding(); @Override InputStream decompress(InputStream inputStream); @Override OutputStream compress(OutputStream outputStream); }### Answer: @Test void getMessageEncoding() { assertEquals("lz4", uut.getMessageEncoding()); }
### Question: SnappyGrpcServerCodec implements Codec { @Override public String getMessageEncoding() { return "snappy"; } @Override String getMessageEncoding(); @Override InputStream decompress(InputStream inputStream); @Override OutputStream compress(OutputStream outputStream); }### Answer: @Test void getMessageEncoding() { assertEquals("snappy", uut.getMessageEncoding()); }
### Question: 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(); }### Answer: @Test void testOnCompleted() { verify(delegate, never()).onCompleted(); uut.onCompleted(); verify(delegate).onCompleted(); }
### Question: 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(); }### Answer: @Test void testOnError() { verify(delegate, never()).onError(any()); uut.onError(new Exception()); verify(delegate).onError(any()); }
### Question: PgConfigurationProperties implements ApplicationListener<ApplicationReadyEvent> { public int getQueueSizeForIds() { return queueSize * idOnlyFactor; } int getPageSizeForIds(); int getQueueSizeForIds(); int getFetchSizeForIds(); int getFetchSize(); @Override void onApplicationEvent(ApplicationReadyEvent event); }### Answer: @Test void testGetQueueSizeForIds() { assertEquals(100000, uut.getQueueSizeForIds()); }
### Question: 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_TIME); } catch (InterruptedException meh) { } if (delegate.isReady()) { break; } if (delegate.isCancelled()) { break; } } if (!delegate.isReady() && !delegate.isCancelled()) { throw new TransportLayerException("channel not coming back."); } } if (!delegate.isCancelled()) delegate.onNext(value); } } } BlockingStreamObserver(@NonNull String id, @NonNull ServerCallStreamObserver<T> delegate); @Override void onNext(T value); @Override void onError(Throwable t); @Override void onCompleted(); }### Answer: @Test void testOnNextWhenReady() { when(delegate.isReady()).thenReturn(true); uut.onNext(new Object()); verify(delegate).onNext(any()); }
### Question: 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(); } @Override void fetchById(MSG_UUID request, StreamObserver<MSG_OptionalFact> responseObserver); @Override @Secured(FactCastRole.WRITE) void publish(@NonNull MSG_Facts request, StreamObserver<MSG_Empty> responseObserver); @Override void subscribe(MSG_SubscriptionRequest request, StreamObserver<MSG_Notification> responseObserver); @Override void handshake(MSG_Empty request, StreamObserver<MSG_ServerConfig> responseObserver); @Override void serialOf(MSG_UUID request, StreamObserver<MSG_OptionalSerial> responseObserver); @Override void enumerateNamespaces(MSG_Empty request, StreamObserver<MSG_StringSet> responseObserver); @Override void enumerateTypes(MSG_String request, StreamObserver<MSG_StringSet> responseObserver); @Override @Secured(FactCastRole.WRITE) void publishConditional(MSG_ConditionalPublishRequest request, StreamObserver<MSG_ConditionalPublishResult> responseObserver); @Override @Secured(FactCastRole.WRITE) void stateFor(MSG_StateForRequest request, StreamObserver<MSG_UUID> responseObserver); @Override @Secured(FactCastRole.WRITE) void invalidate(MSG_UUID request, StreamObserver<MSG_Empty> responseObserver); @Override void currentTime(MSG_Empty request, StreamObserver<MSG_CurrentDatabaseTime> responseObserver); }### Answer: @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)); }
### Question: 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.setMessageCompression(false); }); return next.startCall(call, headers); } @Override Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next); final Metadata.Key<String> GRPC_ACCEPT_ENCODING; }### Answer: @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); verifyNoMoreInteractions(next); } @Test void interceptCallGZip() { ServerCall call = mock(ServerCall.class); Metadata metadata = mock(Metadata.class); when(metadata.get(uut.GRPC_ACCEPT_ENCODING)).thenReturn("gzip"); ServerCallHandler next = mock(ServerCallHandler.class); uut.interceptCall(call, metadata, next); verify(next).startCall(call, metadata); verify(call).setCompression("gzip"); verify(call).setMessageCompression(false); }
### Question: 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(); @Override void onNext(Fact element); }### Answer: @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(UnsupportedOperationException.class).when(observer).onCompleted(); uut.onComplete(); verify(observer).onCompleted(); }
### Question: 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(Fact element); }### Answer: @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()); }
### Question: 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 onNext(Fact element); }### Answer: @Test void testOnError() { GrpcObserverAdapter uut = new GrpcObserverAdapter("foo", observer, projection); verify(observer, never()).onNext(any()); uut.onError(new Exception()); verify(observer).onError(any()); }
### Question: 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); }### Answer: @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); verify(observer).onNext(any()); assertEquals(MSG_Notification.Type.Fact, msg.getValue().getType()); assertEquals(f.id(), conv.fromProto(msg.getValue().getFact()).id()); }
### Question: PgListener implements InitializingBean, DisposableBean { @Override public void destroy() { this.running.set(false); if (listenerThread != null) { listenerThread.interrupt(); } } @Override void afterPropertiesSet(); @Override void destroy(); }### Answer: @Test void testStopWithoutStarting() { PgListener l = new PgListener(ds, bus, tester); l.destroy(); verifyNoMoreInteractions(conn); }
### Question: 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()); setProperty(dbp, "password", poolProperties.getPassword()); final String connectionProperties = poolProperties.getConnectionProperties(); if (connectionProperties != null) { try { @SuppressWarnings("UnstableApiUsage") Map<String, String> singleConnectionProperties = Splitter.on(";") .omitEmptyStrings() .withKeyValueSeparator("=") .split(connectionProperties); setProperty(dbp, "socketTimeout", singleConnectionProperties.get( "socketTimeout")); setProperty(dbp, "connectTimeout", singleConnectionProperties.get( "connectTimeout")); setProperty(dbp, "loginTimeout", singleConnectionProperties.get( "loginTimeout")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("illegal connectionProperties: " + connectionProperties); } } } return dbp; } PgConnectionSupplier(DataSource dataSource); PgConnection get(); }### Answer: @Test void test_noRelevantPropertySet() { setupConnectionProperties("sockettimeout=30"); uut.buildPgConnectionProperties(ds); } @Test void test_propertySyntaxBroken() { Assertions.assertThrows(IllegalArgumentException.class, () -> { setupConnectionProperties("sockettimeout:30"); uut.buildPgConnectionProperties(ds); }); } @Test void test_nullProperties() { setupConnectionProperties(null); uut.buildPgConnectionProperties(ds); } @Test void test_invalidConnectionProperties() { Assertions.assertThrows(IllegalArgumentException.class, () -> { setupConnectionProperties("socketTimeout=30;connectTimeout=20,loginTimeout=10;"); uut.buildPgConnectionProperties(ds); failBecauseExceptionWasNotThrown(IllegalArgumentException.class); }); }
### Question: 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 beanName); @Override @NonNull Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName); }### Answer: @Test public void shouldReturnFromAfterInitSameBeanAsPassed() throws Exception { UUID instance = UUID.randomUUID(); Object afterInit = uut.postProcessAfterInitialization(instance, "foo"); assertThat(afterInit).isSameAs(instance); }
### Question: RdsDataSourceFactoryBeanPostProcessor implements BeanPostProcessor { @Override @NonNull public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException { if (bean instanceof AmazonRdsDataSourceFactoryBean) { ((AmazonRdsDataSourceFactoryBean) bean).setDataSourceFactory( tomcatJdbcDataSourceFactory()); } return bean; } @Override @NonNull Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName); @Override @NonNull Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName); }### Answer: @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 { AmazonRdsDataSourceFactoryBean instance = mock(AmazonRdsDataSourceFactoryBean.class); when(env.getProperty(any(), any(), anyBoolean())).thenReturn(true); AmazonRdsDataSourceFactoryBean afterInit = (AmazonRdsDataSourceFactoryBean) uut .postProcessBeforeInitialization(instance, "foo"); assertThat(afterInit).isSameAs(instance); verify(instance).setDataSourceFactory(any()); }
### Question: PgConfigurationProperties implements ApplicationListener<ApplicationReadyEvent> { public int getFetchSizeForIds() { return getQueueSizeForIds() / queueFetchRatio; } int getPageSizeForIds(); int getQueueSizeForIds(); int getFetchSizeForIds(); int getFetchSize(); @Override void onApplicationEvent(ApplicationReadyEvent event); }### Answer: @Test void testGetFetchSizeForIds() { assertEquals(25000, uut.getFetchSizeForIds()); }
### Question: InMemFact extends DefaultFact { @Override public String toString() { return FactCastJson.writeValueAsPrettyString(this); } InMemFact(long ser, Fact toCopyFrom); @Override String toString(); }### Answer: @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 InMemFact(fact.serial(), fact); assertNotSame(f1, f2); assertEquals(f1, f2); }
### Question: 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(from), obs); obs.awaitTermination(); } @Override void runWith(FactCast fc, Options opt); }### Answer: @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<?> o = (GenericObserver<?>) args[1]; o.onCatchup(); o.onComplete(); SubscriptionRequest r = (SubscriptionRequest) args[0]; List<FactSpec> specs = new ArrayList<>(r.specs()); assertEquals(startId, r.startingAfter().get()); assertEquals(ns, specs.iterator().next().ns()); return null; }); cmd.runWith(fc, opt); verify(fc).subscribeEphemeral(any(SubscriptionRequest.class), any(ConsoleFactObserver.class)); }