method2testcases
stringlengths 118
3.08k
|
---|
### Question:
SystemMetrics implements Serializable { public abstract T diff(@Nullable T b, @Nullable T output); abstract T sum(@Nullable T b, @Nullable T output); abstract T diff(@Nullable T b, @Nullable T output); abstract T set(T b); T sum(@Nullable T b); T diff(@Nullable T b); }### Answer:
@Test public void testDiff() throws Exception { T a = createInitializedInstance(); T b = createInitializedInstance(); T diff = createInitializedInstance(); int index = 1; for (Field field : getClazz().getFields()) { if (MetricsUtil.isNumericField(field)) { field.set(a, 2 * index); index += 1; } } a.diff(b, diff); int increment = 1; for (Field field : getClazz().getFields()) { if (MetricsUtil.isNumericField(field)) { MetricsUtil.testValue(diff, field, increment); increment += 1; } } }
@Test public void testNullOutput() throws Exception { T instanceA = createInitializedInstance(); T instanceB = createInitializedInstance(); T diff = instanceA.diff(instanceB, null); assertThat(diff).isNotNull(); }
@Test public void testNullSubtrahend() throws Exception { T instanceA = createInitializedInstance(); T diff = createInitializedInstance(); instanceA.diff(null, diff); assertThat(instanceA).isEqualTo(diff); } |
### Question:
ProcFileReader { public ProcFileReader reset() { mIsValid = true; if (mFile != null) { try { mFile.seek(0); } catch (IOException ioe) { close(); } } if (mFile == null) { try { mFile = new RandomAccessFile(mPath, "r"); } catch (IOException ioe) { mIsValid = false; close(); } } if (mIsValid) { mPosition = -1; mBufferSize = 0; mChar = 0; mPrev = 0; mRewound = false; } return this; } ProcFileReader(String path); ProcFileReader(String path, int bufferSize); ProcFileReader start(); ProcFileReader reset(); boolean isValid(); boolean hasNext(); boolean hasReachedEOF(); CharBuffer readWord(CharBuffer buffer); long readNumber(); void skipSpaces(); void skipLine(); void skipPast(char skipPast); void close(); }### Answer:
@Test public void testReset() throws Exception { String contents = "notanumber"; String testPath = createFile(contents); ProcFileReader reader = new ProcFileReader(testPath).start(); assertThat(reader.readWord(CharBuffer.allocate(20)).toString()).isEqualTo(contents); assertThat(reader.hasReachedEOF()).isTrue(); reader.reset(); assertThat(reader.readWord(CharBuffer.allocate(20)).toString()).isEqualTo(contents); assertThat(reader.hasReachedEOF()).isTrue(); } |
### Question:
StatefulSystemMetricsCollector { @Nullable public R getLatestDiffAndReset() { if (getLatestDiff() == null) { return null; } R temp = mPrev; mPrev = mCurr; mCurr = temp; return mDiff; } StatefulSystemMetricsCollector(S collector); StatefulSystemMetricsCollector(S collector, R curr, R prev, R diff); S getCollector(); @Nullable R getLatestDiffAndReset(); @Nullable R getLatestDiff(); }### Answer:
@Test public void testGetLatestDiffAndReset() throws Exception { DummyMetricCollector collector = new DummyMetricCollector(); collector.currentValue = 10; StatefulSystemMetricsCollector<DummyMetric, DummyMetricCollector> statefulCollector = new StatefulSystemMetricsCollector<>(collector); assertThat(statefulCollector.getLatestDiffAndReset().value).isEqualTo(0); collector.currentValue = 20; assertThat(statefulCollector.getLatestDiffAndReset().value).isEqualTo(10); assertThat(statefulCollector.getLatestDiffAndReset().value).isEqualTo(0); } |
### Question:
StatefulSystemMetricsCollector { @Nullable public R getLatestDiff() { mIsValid &= mCollector.getSnapshot(this.mCurr); if (!mIsValid) { return null; } mCurr.diff(mPrev, mDiff); return mDiff; } StatefulSystemMetricsCollector(S collector); StatefulSystemMetricsCollector(S collector, R curr, R prev, R diff); S getCollector(); @Nullable R getLatestDiffAndReset(); @Nullable R getLatestDiff(); }### Answer:
@Test public void testCustomBaseSnapshot() throws Exception { DummyMetric metric = new DummyMetric(); metric.value = 0; DummyMetricCollector collector = new DummyMetricCollector(); collector.currentValue = 10; StatefulSystemMetricsCollector<DummyMetric, DummyMetricCollector> withCustomInitialSnapshot = new StatefulSystemMetricsCollector<>( collector, collector.createMetrics(), metric, collector.createMetrics()); StatefulSystemMetricsCollector<DummyMetric, DummyMetricCollector> defaultInitialSnapshot = new StatefulSystemMetricsCollector<>(collector); assertThat(withCustomInitialSnapshot.getLatestDiff().value).isEqualTo(10); assertThat(defaultInitialSnapshot.getLatestDiff().value).isEqualTo(0); }
@Test public void testGetLatestDiff() { DummyMetricCollector collector = new DummyMetricCollector(); collector.currentValue = 10; StatefulSystemMetricsCollector<DummyMetric, DummyMetricCollector> statefulCollector = new StatefulSystemMetricsCollector<>(collector); assertThat(statefulCollector.getLatestDiff().value).isEqualTo(0); collector.currentValue = 20; assertThat(statefulCollector.getLatestDiff().value).isEqualTo(10); collector.currentValue = 30; assertThat(statefulCollector.getLatestDiff().value).isEqualTo(20); } |
### Question:
HealthStatsMetrics extends SystemMetrics<HealthStatsMetrics> { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HealthStatsMetrics that = (HealthStatsMetrics) o; if (dataType != null ? !dataType.equals(that.dataType) : that.dataType != null) return false; return Utilities.sparseArrayEquals(measurement, that.measurement) && Utilities.sparseArrayEquals(measurements, that.measurements) && Utilities.sparseArrayEquals(timer, that.timer) && Utilities.sparseArrayEquals(timers, that.timers) && Utilities.sparseArrayEquals(stats, that.stats); } HealthStatsMetrics(); HealthStatsMetrics(HealthStats healthStats); HealthStatsMetrics(HealthStatsMetrics metrics); @Override HealthStatsMetrics sum(
@Nullable HealthStatsMetrics b, @Nullable HealthStatsMetrics output); @Override HealthStatsMetrics diff(
@Nullable HealthStatsMetrics b, @Nullable HealthStatsMetrics output); @Override HealthStatsMetrics set(HealthStatsMetrics b); HealthStatsMetrics set(HealthStats healthStats); @Override String toString(); static String getKeyName(int key); JSONObject toJSONObject(); @Override boolean equals(Object o); @Override int hashCode(); public String dataType; final SparseArray<Long> measurement; final SparseArray<TimerMetrics> timer; final SparseArray<ArrayMap<String, Long>> measurements; final SparseArray<ArrayMap<String, TimerMetrics>> timers; final SparseArray<ArrayMap<String, HealthStatsMetrics>> stats; }### Answer:
@Test public void testEquals() { HealthStatsMetrics metricsA = new HealthStatsMetrics(); HealthStatsMetrics metricsB = new HealthStatsMetrics(); assertThat(metricsA).isEqualTo(metricsB); } |
### Question:
SensorMetrics extends SystemMetrics<SensorMetrics> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SensorMetrics that = (SensorMetrics) o; return isAttributionEnabled == that.isAttributionEnabled && total.equals(that.total) && Utilities.sparseArrayEquals(sensorConsumption, that.sensorConsumption); } SensorMetrics(); SensorMetrics(boolean isAttributionEnabled); @Override SensorMetrics sum(@Nullable SensorMetrics b, @Nullable SensorMetrics output); @Override SensorMetrics diff(@Nullable SensorMetrics b, @Nullable SensorMetrics output); @Override SensorMetrics set(SensorMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Nullable JSONObject attributionToJSONObject(); public boolean isAttributionEnabled; final Consumption total; final SparseArray<Consumption> sensorConsumption; }### Answer:
@Test public void testEquals() { assertThat(new SensorMetrics()).isEqualTo(new SensorMetrics()); assertThat(createAttributedMetrics()).isEqualTo(createAttributedMetrics()); } |
### Question:
SensorMetrics extends SystemMetrics<SensorMetrics> { @Override public SensorMetrics set(SensorMetrics b) { total.set(b.total); if (isAttributionEnabled && b.isAttributionEnabled) { sensorConsumption.clear(); for (int i = 0, l = b.sensorConsumption.size(); i < l; i++) { sensorConsumption.put(b.sensorConsumption.keyAt(i), b.sensorConsumption.valueAt(i)); } } return this; } SensorMetrics(); SensorMetrics(boolean isAttributionEnabled); @Override SensorMetrics sum(@Nullable SensorMetrics b, @Nullable SensorMetrics output); @Override SensorMetrics diff(@Nullable SensorMetrics b, @Nullable SensorMetrics output); @Override SensorMetrics set(SensorMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Nullable JSONObject attributionToJSONObject(); public boolean isAttributionEnabled; final Consumption total; final SparseArray<Consumption> sensorConsumption; }### Answer:
@Test public void testSet() { SensorMetrics metrics = new SensorMetrics(true); metrics.set(createAttributedMetrics()); assertThat(metrics).isEqualTo(createAttributedMetrics()); }
@Test public void testUnattributedSet() { SensorMetrics metrics = new SensorMetrics(); metrics.set(createAttributedMetrics()); SensorMetrics comparisonMetrics = createAttributedMetrics(); comparisonMetrics.isAttributionEnabled = false; comparisonMetrics.sensorConsumption.clear(); assertThat(metrics).isEqualTo(comparisonMetrics); } |
### Question:
TimeMetricsCollector extends SystemMetricsCollector<TimeMetrics> { @Override @ThreadSafe(enableChecks = false) public boolean getSnapshot(TimeMetrics snapshot) { checkNotNull(snapshot, "Null value passed to getSnapshot!"); snapshot.realtimeMs = SystemClock.elapsedRealtime(); snapshot.uptimeMs = SystemClock.uptimeMillis(); return true; } @Override @ThreadSafe(enableChecks = false) boolean getSnapshot(TimeMetrics snapshot); @Override TimeMetrics createMetrics(); }### Answer:
@Test public void testTimes() { ShadowSystemClock.setUptimeMillis(1234); ShadowSystemClock.setElapsedRealtime(9876); TimeMetrics snapshot = new TimeMetrics(); TimeMetricsCollector collector = new TimeMetricsCollector(); collector.getSnapshot(snapshot); assertThat(snapshot.uptimeMs).isEqualTo(1234); assertThat(snapshot.realtimeMs).isEqualTo(9876); } |
### Question:
BluetoothMetrics extends SystemMetrics<BluetoothMetrics> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BluetoothMetrics that = (BluetoothMetrics) o; if (bleScanCount != that.bleScanCount || bleScanDurationMs != that.bleScanDurationMs || bleOpportunisticScanCount != that.bleOpportunisticScanCount || bleOpportunisticScanDurationMs != that.bleOpportunisticScanDurationMs) { return false; } return true; } @Override BluetoothMetrics sum(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output); @Override BluetoothMetrics diff(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output); @Override BluetoothMetrics set(BluetoothMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); public int bleScanCount; public long bleScanDurationMs; public int bleOpportunisticScanCount; public long bleOpportunisticScanDurationMs; }### Answer:
@Test public void testEquals() { BluetoothMetrics metricsA = new BluetoothMetrics(); metricsA.bleScanDurationMs = 1000; metricsA.bleScanCount = 2; metricsA.bleOpportunisticScanDurationMs = 4000; metricsA.bleOpportunisticScanCount = 8; BluetoothMetrics metricsB = new BluetoothMetrics(); metricsB.bleScanDurationMs = 1000; metricsB.bleScanCount = 2; metricsB.bleOpportunisticScanDurationMs = 4000; metricsB.bleOpportunisticScanCount = 8; assertThat(new BluetoothMetrics()).isEqualTo(new BluetoothMetrics()); assertThat(metricsA).isEqualTo(metricsB); } |
### Question:
BluetoothMetrics extends SystemMetrics<BluetoothMetrics> { @Override public BluetoothMetrics set(BluetoothMetrics b) { bleScanCount = b.bleScanCount; bleScanDurationMs = b.bleScanDurationMs; bleOpportunisticScanCount = b.bleOpportunisticScanCount; bleOpportunisticScanDurationMs = b.bleOpportunisticScanDurationMs; return this; } @Override BluetoothMetrics sum(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output); @Override BluetoothMetrics diff(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output); @Override BluetoothMetrics set(BluetoothMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); public int bleScanCount; public long bleScanDurationMs; public int bleOpportunisticScanCount; public long bleOpportunisticScanDurationMs; }### Answer:
@Test public void testSet() { BluetoothMetrics metrics = new BluetoothMetrics(); metrics.bleScanDurationMs = 1000; metrics.bleScanCount = 10; metrics.bleOpportunisticScanDurationMs = 5000; metrics.bleOpportunisticScanCount = 3; BluetoothMetrics alternate = new BluetoothMetrics(); alternate.set(metrics); assertThat(alternate).isEqualTo(metrics); } |
### Question:
BluetoothMetrics extends SystemMetrics<BluetoothMetrics> { @Override public BluetoothMetrics diff(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output) { if (output == null) { output = new BluetoothMetrics(); } if (b == null) { output.set(this); } else { output.bleScanCount = bleScanCount - b.bleScanCount; output.bleScanDurationMs = bleScanDurationMs - b.bleScanDurationMs; output.bleOpportunisticScanCount = bleOpportunisticScanCount - b.bleOpportunisticScanCount; output.bleOpportunisticScanDurationMs = bleOpportunisticScanDurationMs - b.bleOpportunisticScanDurationMs; } return output; } @Override BluetoothMetrics sum(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output); @Override BluetoothMetrics diff(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output); @Override BluetoothMetrics set(BluetoothMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); public int bleScanCount; public long bleScanDurationMs; public int bleOpportunisticScanCount; public long bleOpportunisticScanDurationMs; }### Answer:
@Test public void testDiff() { BluetoothMetrics metrics = new BluetoothMetrics(); metrics.bleScanDurationMs = 1000; metrics.bleScanCount = 10; metrics.bleOpportunisticScanDurationMs = 5000; metrics.bleOpportunisticScanCount = 3; BluetoothMetrics olderMetrics = new BluetoothMetrics(); olderMetrics.bleScanDurationMs = 800; olderMetrics.bleScanCount = 7; olderMetrics.bleOpportunisticScanDurationMs = 2000; olderMetrics.bleOpportunisticScanCount = 1; BluetoothMetrics deltaMetrics = new BluetoothMetrics(); deltaMetrics = metrics.diff(olderMetrics, deltaMetrics); assertThat(deltaMetrics.bleScanCount).isEqualTo(3); assertThat(deltaMetrics.bleScanDurationMs).isEqualTo(200); assertThat(deltaMetrics.bleOpportunisticScanCount).isEqualTo(2); assertThat(deltaMetrics.bleOpportunisticScanDurationMs).isEqualTo(3000); } |
### Question:
BluetoothMetrics extends SystemMetrics<BluetoothMetrics> { @Override public BluetoothMetrics sum(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output) { if (output == null) { output = new BluetoothMetrics(); } if (b == null) { output.set(this); } else { output.bleScanCount = bleScanCount + b.bleScanCount; output.bleScanDurationMs = bleScanDurationMs + b.bleScanDurationMs; output.bleOpportunisticScanCount = bleOpportunisticScanCount + b.bleOpportunisticScanCount; output.bleOpportunisticScanDurationMs = bleOpportunisticScanDurationMs + b.bleOpportunisticScanDurationMs; } return output; } @Override BluetoothMetrics sum(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output); @Override BluetoothMetrics diff(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output); @Override BluetoothMetrics set(BluetoothMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); public int bleScanCount; public long bleScanDurationMs; public int bleOpportunisticScanCount; public long bleOpportunisticScanDurationMs; }### Answer:
@Test public void testSum() { BluetoothMetrics metricsA = new BluetoothMetrics(); metricsA.bleScanDurationMs = 1000; metricsA.bleScanCount = 10; metricsA.bleOpportunisticScanDurationMs = 4000; metricsA.bleOpportunisticScanCount = 1; BluetoothMetrics metricsB = new BluetoothMetrics(); metricsB.bleScanDurationMs = 2000; metricsB.bleScanCount = 20; metricsB.bleOpportunisticScanDurationMs = 8000; metricsB.bleOpportunisticScanCount = 2; BluetoothMetrics output = new BluetoothMetrics(); metricsA.sum(metricsB, output); assertThat(output.bleScanCount).isEqualTo(30); assertThat(output.bleScanDurationMs).isEqualTo(3000); assertThat(output.bleOpportunisticScanCount).isEqualTo(3); assertThat(output.bleOpportunisticScanDurationMs).isEqualTo(12000); } |
### Question:
CpuFrequencyMetrics extends SystemMetrics<CpuFrequencyMetrics> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CpuFrequencyMetrics that = (CpuFrequencyMetrics) o; if (timeInStateS.length != that.timeInStateS.length) { return false; } for (int i = 0, size = timeInStateS.length; i < size; i++) { if (!sparseIntArrayEquals(timeInStateS[i], that.timeInStateS[i])) { return false; } } return true; } CpuFrequencyMetrics(); @Override CpuFrequencyMetrics sum(
@Nullable CpuFrequencyMetrics b, @Nullable CpuFrequencyMetrics output); @Override CpuFrequencyMetrics diff(
@Nullable CpuFrequencyMetrics b, @Nullable CpuFrequencyMetrics output); @Override CpuFrequencyMetrics set(CpuFrequencyMetrics b); @Override boolean equals(Object o); static boolean sparseIntArrayEquals(SparseIntArray a, SparseIntArray b); @Override int hashCode(); @Override String toString(); @Nullable JSONObject toJSONObject(); final SparseIntArray[] timeInStateS; }### Answer:
@Test public void testEquals() { CpuFrequencyMetrics metricsA = new CpuFrequencyMetrics(); metricsA.timeInStateS[0].put(200, 2000); metricsA.timeInStateS[0].put(100, 1000); metricsA.timeInStateS[1].put(300, 3000); CpuFrequencyMetrics metricsB = new CpuFrequencyMetrics(); metricsB.timeInStateS[0].put(100, 1000); metricsB.timeInStateS[0].put(200, 2000); metricsB.timeInStateS[1].put(300, 3000); assertThat(metricsA).isEqualTo(metricsB); } |
### Question:
SensorMetrics extends SystemMetrics<SensorMetrics> { @Override public SensorMetrics sum(@Nullable SensorMetrics b, @Nullable SensorMetrics output) { if (output == null) { output = new SensorMetrics(isAttributionEnabled); } if (b == null) { output.set(this); } else { total.sum(b.total, output.total); if (output.isAttributionEnabled) { op(+1, sensorConsumption, b.sensorConsumption, output.sensorConsumption); } } return output; } SensorMetrics(); SensorMetrics(boolean isAttributionEnabled); @Override SensorMetrics sum(@Nullable SensorMetrics b, @Nullable SensorMetrics output); @Override SensorMetrics diff(@Nullable SensorMetrics b, @Nullable SensorMetrics output); @Override SensorMetrics set(SensorMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Nullable JSONObject attributionToJSONObject(); public boolean isAttributionEnabled; final Consumption total; final SparseArray<Consumption> sensorConsumption; }### Answer:
@Test public void testAttributedSum() { SensorMetrics a = createAttributedMetrics(); SensorMetrics b = createAttributedMetrics(); SensorMetrics result = a.sum(b); assertThat(result.total.powerMah).isEqualTo(a.total.powerMah * 2); assertThat(result.total.wakeUpTimeMs).isEqualTo(a.total.wakeUpTimeMs * 2); assertThat(result.total.activeTimeMs).isEqualTo(a.total.activeTimeMs * 2); for (int i = 0, l = result.sensorConsumption.size(); i < l; i++) { int key = result.sensorConsumption.keyAt(i); SensorMetrics.Consumption value = result.sensorConsumption.valueAt(i); assertThat(value).isEqualTo(a.sensorConsumption.get(key).sum(b.sensorConsumption.get(key))); } } |
### Question:
WakeLockMetrics extends SystemMetrics<WakeLockMetrics> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WakeLockMetrics that = (WakeLockMetrics) o; if (isAttributionEnabled != that.isAttributionEnabled || heldTimeMs != that.heldTimeMs || acquiredCount != that.acquiredCount) { return false; } return Utilities.simpleArrayMapEquals(tagTimeMs, that.tagTimeMs); } WakeLockMetrics(); WakeLockMetrics(boolean isAttributionEnabled); @Override WakeLockMetrics sum(@Nullable WakeLockMetrics b, @Nullable WakeLockMetrics output); @Override WakeLockMetrics diff(@Nullable WakeLockMetrics b, @Nullable WakeLockMetrics output); @Override WakeLockMetrics set(WakeLockMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Nullable JSONObject attributionToJSONObject(); public boolean isAttributionEnabled; final SimpleArrayMap<String, Long> tagTimeMs; public long heldTimeMs; public long acquiredCount; }### Answer:
@Test public void testEquals() { assertThat(new WakeLockMetrics()).isEqualTo(new WakeLockMetrics()); assertThat(createInitializedMetrics()).isEqualTo(createInitializedMetrics()); } |
### Question:
SensorMetrics extends SystemMetrics<SensorMetrics> { @Override public SensorMetrics diff(@Nullable SensorMetrics b, @Nullable SensorMetrics output) { if (output == null) { output = new SensorMetrics(isAttributionEnabled); } if (b == null) { output.set(this); } else { total.diff(b.total, output.total); if (output.isAttributionEnabled) { op(-1, sensorConsumption, b.sensorConsumption, output.sensorConsumption); } } return output; } SensorMetrics(); SensorMetrics(boolean isAttributionEnabled); @Override SensorMetrics sum(@Nullable SensorMetrics b, @Nullable SensorMetrics output); @Override SensorMetrics diff(@Nullable SensorMetrics b, @Nullable SensorMetrics output); @Override SensorMetrics set(SensorMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Nullable JSONObject attributionToJSONObject(); public boolean isAttributionEnabled; final Consumption total; final SparseArray<Consumption> sensorConsumption; }### Answer:
@Test public void testAttributedDiff() { SensorMetrics a = createAttributedMetrics(); SensorMetrics b = createAttributedMetrics(); SensorMetrics result = a.diff(b); assertThat(result).isEqualTo(new SensorMetrics(true)); } |
### Question:
UndertowEndpointManager implements WebSocketConnectionCallback, XEndpointManager<UndertowEndpoint> { UndertowEndpoint createEndpoint(WebSocketChannel channel) { final UndertowEndpoint endpoint = new UndertowEndpoint(this, channel); try { channel.setOption(Options.TCP_NODELAY, NODELAY); } catch (IOException e) { throw new OptionAssignmentException("Error setting option", e); } channel.getReceiveSetter().set(endpoint); channel.resumeReceives(); scanner.addEndpoint(endpoint); listener.onConnect(endpoint); if (idleTimeoutMillis != 0) { channel.setIdleTimeout(idleTimeoutMillis); } return endpoint; } UndertowEndpointManager(XEndpointScanner<UndertowEndpoint> scanner, int idleTimeoutMillis, XEndpointConfig<?> config,
XEndpointListener<? super UndertowEndpoint> listener); @Override void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel); @Override Collection<UndertowEndpoint> getEndpoints(); }### Answer:
@Test(expected=OptionAssignmentException.class) public void testCreateEndpointWithError() throws IOException { @SuppressWarnings("unchecked") final XEndpointListener<UndertowEndpoint> listener = mock(XEndpointListener.class); final UndertowEndpointManager mgr = new UndertowEndpointManager(null, 0, new DerivedEndpointConfig(), listener); final WebSocketChannel channel = Mockito.mock(WebSocketChannel.class); when(channel.setOption(any(), any())).thenThrow(new IOException("Boom")); mgr.createEndpoint(channel); } |
### Question:
UndertowEndpoint extends AbstractReceiveListener implements XEndpoint { WebSocketCallback<Void> wrapCallback(XSendCallback callback) { return new WebSocketCallback<Void>() { private final AtomicBoolean onceOnly = new AtomicBoolean(); @Override public void complete(WebSocketChannel channel, Void context) { if (onceOnly.compareAndSet(false, true)) { backlog.decrementAndGet(); if (callback != null) callback.onComplete(UndertowEndpoint.this); } } @Override public void onError(WebSocketChannel channel, Void context, Throwable cause) { if (onceOnly.compareAndSet(false, true)) { backlog.decrementAndGet(); if (callback != null) callback.onError(UndertowEndpoint.this, cause); } } }; } UndertowEndpoint(UndertowEndpointManager manager, WebSocketChannel channel); @Override @SuppressWarnings("unchecked") T getContext(); @Override void setContext(Object context); @Override void send(String payload, XSendCallback callback); @Override void send(ByteBuffer payload, XSendCallback callback); WebSocketChannel getChannel(); @Override void flush(); @Override void sendPing(); @Override void close(); @Override void terminate(); @Override InetSocketAddress getRemoteAddress(); @Override long getBacklog(); @Override boolean isOpen(); @Override long getLastActivityTime(); @Override String toString(); }### Answer:
@Test public void testCallbackOnceOnlyComplete() { createEndpointManager(); final XSendCallback callback = mock(XSendCallback.class); final WebSocketCallback<Void> wsCallback = endpoint.wrapCallback(callback); wsCallback.complete(channel, null); verify(callback, times(1)).onComplete(eq(endpoint)); wsCallback.complete(channel, null); verify(callback, times(1)).onComplete(eq(endpoint)); } |
### Question:
SparseMatrix implements Matrix<SparseMatrixRow> { @Override public Iterator<SparseMatrixRow> iterator() { return new SparseMatrixIterator(); } SparseMatrix(File path); long lastModified(); @Override SparseMatrixRow getRow(int rowId); @Override int[] getRowIds(); @Override int getNumRows(); ValueConf getValueConf(); @Override Iterator<SparseMatrixRow> iterator(); void close(); @Override File getPath(); static final Logger LOG; static final int DEFAULT_HEADER_SIZE; static final int FILE_HEADER; }### Answer:
@Test public void testWrite() throws IOException { File tmp = File.createTempFile("matrix", null); SparseMatrixWriter.write(tmp, srcRows.iterator()); }
@Test public void testReadWrite() throws IOException { File tmp = File.createTempFile("matrix", null); SparseMatrixWriter.write(tmp, srcRows.iterator()); Matrix m1 = new SparseMatrix(tmp); Matrix m2 = new SparseMatrix(tmp); }
@Test public void testTranspose() throws IOException { for (int numOpenPages: new int[] { 1, Integer.MAX_VALUE}) { File tmp1 = File.createTempFile("matrix", null); File tmp2 = File.createTempFile("matrix", null); File tmp3 = File.createTempFile("matrix", null); SparseMatrixWriter.write(tmp1, srcRows.iterator()); SparseMatrix m = new SparseMatrix(tmp1); verifyIsSourceMatrix(m); new SparseMatrixTransposer(m, tmp2, 1).transpose(); SparseMatrix m2 = new SparseMatrix(tmp2); new SparseMatrixTransposer(m2, tmp3, 1).transpose(); Matrix m3 = new SparseMatrix(tmp3); verifyIsSourceMatrixUnordered(m3, .001); } }
@Test public void testRows() throws IOException { for (int numOpenPages: new int[] { 1, Integer.MAX_VALUE}) { File tmp = File.createTempFile("matrix", null); SparseMatrixWriter.write(tmp, srcRows.iterator()); Matrix m = new SparseMatrix(tmp); verifyIsSourceMatrix(m); } } |
### Question:
DenseMatrix implements Matrix<DenseMatrixRow> { @Override public Iterator<DenseMatrixRow> iterator() { return new DenseMatrixIterator(); } DenseMatrix(File path); @Override DenseMatrixRow getRow(int rowId); @Override int[] getRowIds(); int[] getColIds(); @Override int getNumRows(); ValueConf getValueConf(); @Override Iterator<DenseMatrixRow> iterator(); @Override File getPath(); @Override void close(); static final Logger LOG; static final int FILE_HEADER; static final int DEFAULT_HEADER_SIZE; }### Answer:
@Test public void testWrite() throws IOException { File tmp = File.createTempFile("matrix", null); DenseMatrixWriter.write(tmp, srcRows.iterator()); }
@Test public void testReadWrite() throws IOException { File tmp = File.createTempFile("matrix", null); DenseMatrixWriter.write(tmp, srcRows.iterator()); DenseMatrix m1 = new DenseMatrix(tmp); DenseMatrix m2 = new DenseMatrix(tmp); }
@Test public void testTranspose() throws IOException { for (int numOpenPages: new int[] { 1, Integer.MAX_VALUE}) { File tmp1 = File.createTempFile("matrix", null); File tmp2 = File.createTempFile("matrix", null); File tmp3 = File.createTempFile("matrix", null); DenseMatrixWriter.write(tmp1, srcRows.iterator()); DenseMatrix m = new DenseMatrix(tmp1); verifyIsSourceMatrix(m); } }
@Test public void testRows() throws IOException { for (int numOpenPages: new int[] { 1, Integer.MAX_VALUE}) { File tmp = File.createTempFile("matrix", null); DenseMatrixWriter.write(tmp, srcRows.iterator()); DenseMatrix m = new DenseMatrix(tmp); verifyIsSourceMatrix(m); } } |
### Question:
PageViewUtils { public static SortedSet<DateTime> timestampsInInterval(DateTime start, DateTime end) { if (start.isAfter(end)) { throw new IllegalArgumentException(); } DateTime current = new DateTime( start.year().get(), start.monthOfYear().get(), start.dayOfMonth().get(), start.hourOfDay().get(), 0); if (current.isBefore(start)) { current = current.plusHours(1); } SortedSet<DateTime> result = new TreeSet<DateTime>(); while (!current.isAfter(end)) { result.add(current); current = current.plusHours(1); } return result; } static SortedSet<DateTime> timestampsInInterval(DateTime start, DateTime end); }### Answer:
@Test public void testTstampsInRange() { long now = System.currentTimeMillis(); Random random = new Random(); for (int i = 0; i < 1000; i++) { long tstamp = (long) (random.nextDouble() * now); DateTime beg = new DateTime(tstamp); DateTime end = beg.plusHours(1); SortedSet<DateTime> tstamps = PageViewUtils.timestampsInInterval(beg, end); assertEquals(tstamps.size(), 1); DateTime dt = tstamps.first(); assertTrue(beg.isBefore(dt)); assertTrue(end.isAfter(dt)); } } |
### Question:
BorderingDistanceMetric implements SpatialDistanceMetric { @Override public List<Neighbor> getNeighbors(Geometry g, int maxNeighbors) { return getNeighbors(g, maxNeighbors, Double.MAX_VALUE); } BorderingDistanceMetric(SpatialDataDao dao, String layer); @Override void setValidConcepts(TIntSet concepts); @Override void enableCache(boolean enable); @Override String getName(); @Override double distance(Geometry g1, Geometry g2); @Override float[][] distance(List<Geometry> rowGeometries, List<Geometry> colGeometries); @Override float[][] distance(List<Geometry> geometries); @Override List<Neighbor> getNeighbors(Geometry g, int maxNeighbors); @Override List<Neighbor> getNeighbors(Geometry g, int maxNeighbors, double maxDistance); void setBufferWidth(double bufferWidth); void setMaxSteps(int maxSteps); void setForceContains(boolean forceContains); }### Answer:
@Test public void testKnn() throws DaoException { List<SpatialDistanceMetric.Neighbor> neighbors = metric.getNeighbors(g("Minnesota"), 100); for (int i = 0; i < neighbors.size(); i++) { SpatialDistanceMetric.Neighbor n = neighbors.get(i); String name = n(n.conceptId); if (i == 0) { assertEquals(name, "Minnesota"); } else if (i <= 4) { assertTrue(Arrays.asList("North Dakota", "Iowa", "Wisconsin", "South Dakota").contains(name)); } } SpatialDistanceMetric.Neighbor last = neighbors.get(neighbors.size() - 1); assertEquals(8.0, last.distance, 0.01); assertEquals("Maine", n(last.conceptId)); } |
### Question:
Title implements Externalizable { public Title(String text, LanguageInfo language) { this(text, false, language); } Title(String text, LanguageInfo language); Title(String text, boolean isCanonical, LanguageInfo lang); Title(String title, Language language); String getCanonicalTitle(); LanguageInfo getLanguageInfo(); Language getLanguage(); NameSpace getNamespace(); String getNamespaceString(); String getTitleStringWithoutNamespace(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object o); Title toUpperCase(); String toUrl(); long longHashCode(); static long longHashCode(Language l, String title, NameSpace ns); static long longHashCode(int langId, String title, int nsArbitraryId); String[] getNameAndDisambiguator(); static String canonicalize(String title, LanguageInfo lang); @Override void readExternal(ObjectInput in); @Override void writeExternal(ObjectOutput out); }### Answer:
@Test public void testTitle(){ LanguageInfo lang = LanguageInfo.getByLangCode("en"); Title pokemon = new Title("Pokemon: The Movie",lang); assert (pokemon.getNamespaceString() == null); assert (pokemon.getNamespace()==NameSpace.ARTICLE); assert (pokemon.getTitleStringWithoutNamespace().equals("Pokemon: The Movie")); Title axelson = new Title("Ax:son Johnson family",lang); assert (axelson.getNamespaceString() == null); assert (axelson.getNamespace()==NameSpace.ARTICLE); assert(axelson.getTitleStringWithoutNamespace().equals("Ax:son Johnson family")); Title pokemonTalk = new Title("Talk:Pokemon: The Movie",lang); assert (pokemonTalk.getNamespaceString().equals("Talk")); assert (pokemonTalk.getNamespace()==NameSpace.TALK); assert (pokemonTalk.getTitleStringWithoutNamespace().equals("Pokemon: The Movie")); Title badCategory = new Title("Category: ",lang); assert (badCategory.getNamespaceString().equals("Category")); assert (badCategory.getNamespace()==NameSpace.CATEGORY); assert (badCategory.getTitleStringWithoutNamespace().equals("")); } |
### Question:
GoogleSimilarity implements VectorSimilarity { public GoogleSimilarity(int numPages) { this.numPages = numPages; } GoogleSimilarity(int numPages); @Override synchronized void setMatrices(SparseMatrix features, SparseMatrix transpose, File dataDir); @Override double similarity(TIntFloatMap vector1, TIntFloatMap vector2); @Override double similarity(MatrixRow a, MatrixRow b); @Override SRResultList mostSimilar(TIntFloatMap query, int maxResults, TIntSet validIds); @Override double getMinValue(); @Override double getMaxValue(); }### Answer:
@Test public void testUtils() { TIntFloatMap row1 = getMap(ROW1_IDS, ROW1_VALS); TIntFloatMap row2 = getMap(ROW2_IDS, ROW2_VALS); double expected = googleSimilarity(row1, row2); double actual = SimUtils.googleSimilarity(6, 5, 3, NUM_PAGES); assertEquals(expected, actual, 0.0001); } |
### Question:
SimUtils { public static double cosineSimilarity(TIntDoubleMap X, TIntDoubleMap Y) { double xDotX = 0.0; double yDotY = 0.0; double xDotY = 0.0; for (int id : X.keys()) { double x = X.get(id); xDotX += x * x; if (Y.containsKey(id)) { xDotY += x * Y.get(id); } } for (double y : Y.values()) { yDotY += y * y; } return xDotX * yDotY != 0 ? xDotY / Math.sqrt(xDotX * yDotY): 0.0; } static double cosineSimilarity(TIntDoubleMap X, TIntDoubleMap Y); static double cosineSimilarity(TIntFloatMap X, TIntFloatMap Y); static double cosineSimilarity(MatrixRow a, MatrixRow b); static double googleSimilarity(int sizeA, int sizeB, int intersection, int numTotal); static TIntDoubleMap normalizeVector(TIntDoubleMap X); static TIntFloatMap normalizeVector(TIntFloatMap X); static Map sortByValue(TIntDoubleHashMap unsortMap); static WikiBrainScoreDoc[] pruneSimilar(WikiBrainScoreDoc[] wikibrainScoreDocs); static double cosineSimilarity(float[] X, float[] Y); }### Answer:
@Test public void testCosineSimilarity() { TIntDoubleHashMap zeroVector = zeroVector(keyList1); TIntDoubleHashMap testVector1 = testVector(keyList2, 0); TIntDoubleHashMap testVector2 = testVector(keyList2, 1); assertEquals("Cosine similarity between a vector and itself must be 1", 1.0, SimUtils.cosineSimilarity(testVector1, testVector1), 0.0); assertEquals("Cosine similarity between a vector and zero vector must be 0", 0.0, SimUtils.cosineSimilarity(testVector1, zeroVector), 0.0); } |
### Question:
DatasetDao { public static Collection<Info> readInfos() throws DaoException { try { return readInfos(WpIOUtils.openResource(RESOURCE_DATASET_INFO)); } catch (IOException e) { throw new DaoException(e); } } DatasetDao(); DatasetDao(Collection<Info> info); void setNormalize(boolean normalize); List<Dataset> getAllInLanguage(Language lang); Dataset read(Language language, File path); Dataset get(Language language, String name); boolean isGroup(String name); List<Dataset> getGroup(Language language, String name); List<Dataset> getDatasetOrGroup(Language language, String name); Info getInfo(String name); void setDisambiguator(Disambiguator dab); void setResolvePhrases(boolean resolvePhrases); void setGroups(Map<String, List<String>> groups); void write(Dataset dataset, File path); static Collection<Info> readInfos(); static Collection<Info> readInfos(BufferedReader reader); static final String RESOURCE_DATSET; static final String RESOURCE_DATASET_INFO; }### Answer:
@Test public void testInfos() throws DaoException { Collection<DatasetDao.Info> infos = DatasetDao.readInfos(); assertEquals(18, infos.size()); } |
### Question:
MostSimilarGuess { public PrecisionRecallAccumulator getPrecisionRecall(int n, double threshold) { PrecisionRecallAccumulator pr = new PrecisionRecallAccumulator(n, threshold); TIntDoubleMap actual = new TIntDoubleHashMap(); for (KnownSim ks : known.getMostSimilar()) { pr.observe(ks.similarity); actual.put(ks.wpId2, ks.similarity); } for (Observation o : observations) { if (o.rank > n) { break; } pr.observeRetrieved(actual.get(o.id)); } return pr; } MostSimilarGuess(KnownMostSim known, String str); MostSimilarGuess(KnownMostSim known, SRResultList guess); String toString(); List<Observation> getObservations(); int getLength(); KnownMostSim getKnown(); double getNDGC(); double getPenalizedNDGC(); PrecisionRecallAccumulator getPrecisionRecall(int n, double threshold); }### Answer:
@Test public void testPrecisionRecall() { PrecisionRecallAccumulator pr = guess.getPrecisionRecall(1, 0.7); assertEquals(pr.getN(), 1); assertEquals(1.0, pr.getPrecision(), 0.001); assertEquals(0.333333, pr.getRecall(), 0.001); pr = guess.getPrecisionRecall(2, 0.7); assertEquals(0.5, pr.getPrecision(), 0.001); assertEquals(0.333333, pr.getRecall(), 0.001); pr = guess.getPrecisionRecall(5, 0.7); assertEquals(0.6666, pr.getPrecision(), 0.001); assertEquals(0.6666, pr.getRecall(), 0.001); } |
### Question:
JvmUtils { public synchronized static String getFullClassName(String shortName) { if (NAME_TO_CLASS != null) { return NAME_TO_CLASS.get(shortName); } NAME_TO_CLASS = new HashMap<String, String>(); for (File file : getClassPathAsList()) { if (file.length() > MAX_FILE_SIZE) { LOG.debug("skipping looking for providers in large file " + file); continue; } ClassFinder finder = new ClassFinder(); finder.add(file); ClassFilter filter = new AndClassFilter( new RegexClassFilter(WIKIBRAIN_CLASS_PATTERN.pattern()), new NotClassFilter(new RegexClassFilter(WIKIBRAIN_CLASS_BLACKLIST.pattern())) ); Collection<ClassInfo> foundClasses = new ArrayList<ClassInfo>(); finder.findClasses(foundClasses,filter); for (ClassInfo info : foundClasses) { String tokens[] = info.getClassName().split("[.]"); if (tokens.length == 0) { continue; } String n = tokens[tokens.length - 1]; if (!NAME_TO_CLASS.containsKey(n)) { NAME_TO_CLASS.put(n, info.getClassName()); } } } LOG.info("found " + NAME_TO_CLASS.size() + " classes when constructing short to full class name mapping"); return NAME_TO_CLASS.get(shortName); } static String getClassPath(); synchronized static List<File> getClassPathAsList(); static Process launch(Class klass, String args[]); static Process launch(Class klass, String args[], OutputStream out, OutputStream err, String heapSize); static void setWikiBrainClassPattern(Pattern pattern, Pattern blacklist); static Class classForShortName(String shortName); synchronized static String getFullClassName(String shortName); static final int MAX_FILE_SIZE; }### Answer:
@Test public void testFullClassName() { assertEquals("org.wikibrain.utils.JvmUtils", JvmUtils.getFullClassName("JvmUtils")); assertNull(JvmUtils.getFullClassName("Foozkjasdf")); } |
### Question:
JvmUtils { public static Class classForShortName(String shortName) { String fullName = getFullClassName(shortName); if (fullName == null) { return null; } try { return Class.forName(fullName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } static String getClassPath(); synchronized static List<File> getClassPathAsList(); static Process launch(Class klass, String args[]); static Process launch(Class klass, String args[], OutputStream out, OutputStream err, String heapSize); static void setWikiBrainClassPattern(Pattern pattern, Pattern blacklist); static Class classForShortName(String shortName); synchronized static String getFullClassName(String shortName); static final int MAX_FILE_SIZE; }### Answer:
@Test public void testClassForShortName() { assertEquals(JvmUtils.class, JvmUtils.classForShortName("JvmUtils")); assertNull(JvmUtils.classForShortName("Foozkjasdf")); } |
### Question:
KafkaSinkFactory implements SinkFactory { @Override public String name() { return "kafka"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test public void testName() { assertThat(factory.name()).isEqualTo("kafka"); } |
### Question:
ReflectionHelper { static Sink<Object> getSinkOrFail(String name) { Sink<Object> sink = FluidRegistry.sink(Objects.requireNonNull(name)); if (sink == null) { throw new IllegalArgumentException("Unable to find the sink " + name); } return sink; } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test public void testGettingAMissingSink() { FluidRegistry.register("my-sink", Sink.list()); Sink<Object> sink = ReflectionHelper.getSinkOrFail("my-sink"); assertThat(sink).isNotNull(); try { ReflectionHelper.getSinkOrFail("missing"); fail("The sink should be missing"); } catch (IllegalArgumentException e) { } } |
### Question:
ReflectionHelper { static Source<Object> getSourceOrFail(String name) { Source<Object> src = FluidRegistry.source(Objects.requireNonNull(name)); if (src == null) { throw new IllegalArgumentException("Unable to find the source " + name); } return src; } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test public void testGettingAMissingSource() { FluidRegistry.register("my-source", Source.empty()); Source<Object> source = ReflectionHelper.getSourceOrFail("my-source"); assertThat(source).isNotNull(); try { ReflectionHelper.getSourceOrFail("missing"); fail("The source should be missing"); } catch (IllegalArgumentException e) { } } |
### Question:
FluidRegistry { public static synchronized <T> void register(Source<T> source) { sources.put(Objects.requireNonNull(source.name(), NAME_NOT_PROVIDED_MESSAGE), source); } private FluidRegistry(); static synchronized void initialize(Vertx vertx, FluidConfig config); static void reset(); static synchronized void register(Source<T> source); static synchronized void register(Sink<T> sink); static synchronized void register(String name, Source<T> source); static synchronized void register(String name, Sink<T> sink); static synchronized void unregisterSource(String name); static synchronized void unregisterSink(String name); @SuppressWarnings("unchecked") static Source<T> source(String name); @SuppressWarnings("unchecked") static Sink<T> sink(String name); @SuppressWarnings({"unused", "unchecked"}) static Source<T> source(String name, Class<T> clazz); }### Answer:
@Test(expected = NullPointerException.class) public void testRegistrationOfSinkWithNullName() { Sink<String> discard = Sink.discard(); FluidRegistry.register(null, discard); }
@Test(expected = NullPointerException.class) public void testRegistrationOfSourceWithNullName() { Source<String> source = Source.empty(); FluidRegistry.register(null, source); } |
### Question:
FluidRegistry { public static synchronized void initialize(Vertx vertx, FluidConfig config) { sinks.putAll(SourceAndSinkBuilder.createSinksFromConfiguration(vertx, config)); sources.putAll(SourceAndSinkBuilder.createSourcesFromConfiguration(vertx, config)); } private FluidRegistry(); static synchronized void initialize(Vertx vertx, FluidConfig config); static void reset(); static synchronized void register(Source<T> source); static synchronized void register(Sink<T> sink); static synchronized void register(String name, Source<T> source); static synchronized void register(String name, Sink<T> sink); static synchronized void unregisterSource(String name); static synchronized void unregisterSink(String name); @SuppressWarnings("unchecked") static Source<T> source(String name); @SuppressWarnings("unchecked") static Sink<T> sink(String name); @SuppressWarnings({"unused", "unchecked"}) static Source<T> source(String name, Class<T> clazz); }### Answer:
@Test public void testInitialize() { Fluid fluid = Fluid.create(); assertThat(FluidRegistry.source("unknown")).isNull(); assertThat(FluidRegistry.sink("unknown")).isNull(); fluid.vertx().close(); } |
### Question:
SourceAndSinkBuilder { public static Map<String, Source> createSourcesFromConfiguration(Vertx vertx, FluidConfig config) { Map<String, Source> map = new HashMap<>(); Optional<Config> sources = config.getConfig("sources"); if (sources.isPresent()) { Iterator<String> names = sources.get().names(); while (names.hasNext()) { String name = names.next(); LOGGER.info("Creating source from configuration `" + name + "`"); Optional<Config> conf = sources.get().getConfig(name); Source<?> source = buildSource(vertx, name, conf.orElseThrow(() -> new IllegalStateException("Illegal configuration for source `" + name + "`"))); map.put(name, source); } } else { LOGGER.warn("No sources configured from the fluid configuration"); } return map; } static Map<String, Source> createSourcesFromConfiguration(Vertx vertx, FluidConfig config); static Map<String, Sink> createSinksFromConfiguration(Vertx vertx, FluidConfig config); }### Answer:
@SuppressWarnings("unchecked") @Test public void loadSourceTest() { Map<String, Source> sources = SourceAndSinkBuilder.createSourcesFromConfiguration(vertx, fluid.getConfig()); assertThat(sources).hasSize(2); Source<String> source1 = sources.get("source1"); assertThat(source1).isNotNull(); Source<Integer> source2 = sources.get("source2"); assertThat(source2).isNotNull(); ListSink<String> list = new ListSink<>(); source1.to(list); assertThat(list.values()).containsExactly("a", "b", "c"); assertThat(source1.name()).isEqualTo("source1"); ListSink<Integer> list2 = new ListSink<>(); source2.to(list2); assertThat(list2.values()).containsExactly(0, 1, 2, 3); assertThat(source2.name()).isEqualTo("source2"); } |
### Question:
SourceAndSinkBuilder { public static Map<String, Sink> createSinksFromConfiguration(Vertx vertx, FluidConfig config) { Map<String, Sink> map = new HashMap<>(); Optional<Config> sinks = config.getConfig("sinks"); if (sinks.isPresent()) { Iterator<String> names = sinks.get().names(); while (names.hasNext()) { String name = names.next(); LOGGER.info("Creating sink from configuration `" + name + "`"); Optional<Config> conf = sinks.get().getConfig(name); Sink<?> sink = buildSink(vertx, name, conf.orElseThrow(() -> new IllegalStateException("Illegal configuration for source `" + name + "`"))); map.put(name, sink); } } else { LOGGER.warn("No sinks configured from the fluid configuration"); } return map; } static Map<String, Source> createSourcesFromConfiguration(Vertx vertx, FluidConfig config); static Map<String, Sink> createSinksFromConfiguration(Vertx vertx, FluidConfig config); }### Answer:
@SuppressWarnings("unchecked") @Test public void loadSinkTest() { Map<String, Sink> sinks = SourceAndSinkBuilder.createSinksFromConfiguration(vertx, fluid.getConfig()); assertThat(sinks).hasSize(2); Sink<String> sink1 = sinks.get("sink1"); assertThat(sink1).isNotNull().isInstanceOf(ListSink.class); Sink<Integer> sink2 = sinks.get("sink2"); assertThat(sink2).isNotNull().isInstanceOf(ListSink.class); Source.from("1", "2", "3").to(sink1); Source.from(4, 5).to(sink2); assertThat(((ListSink) sink1).values()).containsExactly("1", "2", "3"); assertThat(((ListSink) sink2).values()).containsExactly(4, 5); } |
### Question:
CommonHeaders { public static String address(Message message) { return (String) message.get(ADDRESS); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldGetRequiredAddress() { assertThat(address(messageWithCommonHeaders)).isEqualTo("address"); } |
### Question:
CommonHeaders { @SuppressWarnings("unchecked") public static Optional<String> addressOpt(Message message) { return message.getOpt(ADDRESS); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldHandleEmptyAddress() { assertThat(addressOpt(messageWithoutCommonHeaders)).isEmpty(); } |
### Question:
KafkaSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config config) { return Single.just(new KafkaSink<>(vertx, name, config)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test(expected = ConfigException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); }
@Test public void testCreationWithMinimalConfiguration() throws IOException { Single<Sink<Object>> single = factory.create(vertx, null, new Config(new JsonObject() .put("bootstrap.servers", "localhost:9092") .put("key.serializer", JsonObjectSerializer.class.getName()) .put("value.serializer", JsonObjectSerializer.class.getName()))); Sink<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(KafkaSink.class); } |
### Question:
CommonHeaders { public static String key(Message message) { return (String) message.get(KEY); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldGetRequiredKey() { assertThat(key(messageWithCommonHeaders)).isEqualTo("key"); } |
### Question:
CommonHeaders { @SuppressWarnings("unchecked") public static Optional<String> keyOpt(Message message) { return message.getOpt(KEY); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldHandleEmptyKey() { assertThat(keyOpt(messageWithoutCommonHeaders)).isEmpty(); } |
### Question:
CommonHeaders { @SuppressWarnings("unchecked") public static <T> T original(Message message) { return (T) message.get(ORIGINAL); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldGetRequiredOriginalData() { assertThat(CommonHeaders.<String>original(messageWithCommonHeaders)).isEqualTo("original"); } |
### Question:
CommonHeaders { @SuppressWarnings("unchecked") public static <T> Optional<T> originalOpt(Message message) { return message.getOpt(ORIGINAL); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldHandleEmptyOriginal() { assertThat(originalOpt(messageWithoutCommonHeaders)).isEmpty(); } |
### Question:
Tuple implements Iterable<Object> { Tuple(Object... items) { if (items == null) { this.items = Collections.emptyList(); } else { for (Object o : items) { if (o == null) { throw new IllegalArgumentException("A tuple cannot contain a `null` value"); } } this.items = Collections.unmodifiableList(Arrays.asList(items)); } } Tuple(Object... items); static Tuple tuple(Object... items); int size(); @SuppressWarnings("unchecked") T nth(int pos); @Override Iterator<Object> iterator(); boolean contains(Object value); final boolean containsAll(Collection<?> collection); final boolean containsAll(final Object... values); final int indexOf(Object value); final int lastIndexOf(Object value); final List<Object> asList(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testTupleWithNull() { Tuple.tuple("a", "b", null, "c"); } |
### Question:
EventBusSourceFactory implements SourceFactory { @Override public String name() { return "eventbus"; } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test public void testName() { assertThat(factory.name()).isEqualTo("eventbus"); } |
### Question:
EventBusSourceFactory implements SourceFactory { @Override public <T> Single<Source<T>> create(Vertx vertx, String name, Config config) { String address = config.getString("address") .orElse(name); if (address == null) { throw new IllegalArgumentException("Either address or name must be set"); } return Single.just(new EventBusSource<>(vertx, name, address, config)); } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); }
@Test public void testCreationWithAddress() throws IOException { Single<Source<Object>> single = factory.create(vertx, null, new Config(new JsonObject().put("address", "an-address"))); Source<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(EventBusSource.class); } |
### Question:
EventBusSinkFactory implements SinkFactory { @Override public String name() { return "eventbus"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config conf); }### Answer:
@Test public void testName() { assertThat(factory.name()).isEqualTo("eventbus"); } |
### Question:
EventBusSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config conf) { return Single.just(new EventBusSink<>(vertx, conf)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config conf); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); }
@Test public void testCreationWithAddress() throws IOException { Single<Sink<Object>> single = factory.create(vertx, null, new Config(new JsonObject().put("address", "an-address"))); Sink<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(EventBusSink.class); } |
### Question:
KafkaSourceFactory implements SourceFactory { @Override public String name() { return "kafka"; } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test public void testName() { assertThat(factory.name()).isEqualTo("kafka"); } |
### Question:
CamelSink implements Sink<T> { public CamelContext camelContext() { return camelContext; } CamelSink(String name, Config config); @Override String name(); @Override Completable dispatch(Message<T> message); CamelContext camelContext(); }### Answer:
@Test public void shouldWrapIntegersIntoCamelBodies(TestContext context) throws Exception { Async async = context.async(); CamelSink<Integer> sink = new CamelSink<>( null, new Config( new JsonObject().put("endpoint", "direct:test") ) ); CamelContext camelContext = sink.camelContext(); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:test").process(event -> { if (event.getIn().getBody(Integer.class) == 10) { context.assertEquals(event.getIn().getBody(Integer.class), 10); async.complete(); } }); } }); Source.from(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).to(sink); } |
### Question:
CamelSinkFactory implements SinkFactory { @Override public String name() { return "camel"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test public void testName() { CamelSinkFactory factory = new CamelSinkFactory(); assertThat(factory.name()).isEqualTo("camel"); } |
### Question:
CamelSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config config) { return Single.just(new CamelSink<>(name, config)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { CamelSinkFactory factory = new CamelSinkFactory(); factory.create(vertx, null , new Config(NullNode.getInstance())); }
@Test public void testCreationWithEndpoint() throws IOException { CamelSinkFactory factory = new CamelSinkFactory(); Single<Sink<Object>> single = factory.create(vertx, null , new Config(new JsonObject().put("endpoint", "my-endpoint"))); Sink<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(CamelSink.class); } |
### Question:
InMemoryDocumentView implements DocumentView { @Override public synchronized Completable save(String collection, String key, Map<String, Object> document) { Objects.requireNonNull(collection, NULL_COLLECTION_MESSAGE); Objects.requireNonNull(key, NULL_KEY_MESSAGE); Objects.requireNonNull(collection, "The `document` must not be `null`"); return Completable.fromAction(() -> { Map<String, Map<String, Object>> collectionData = documents.computeIfAbsent(collection, k -> new LinkedHashMap<>()); collectionData.put(key, document); }); } @Override synchronized Completable save(String collection, String key, Map<String, Object> document); @Override synchronized Single<Map<String, Object>> findById(String collection, String key); @Override synchronized Single<Long> count(String collection); @Override synchronized Flowable<DocumentWithKey> findAll(String collection); @Override synchronized Completable remove(String collection, String key); static final String NULL_COLLECTION_MESSAGE; static final String NULL_KEY_MESSAGE; }### Answer:
@Test public void shouldCallSubscriberOnSave(TestContext context) { Async async = context.async(); view.save(collection, key, document).subscribe(async::complete); } |
### Question:
KafkaSourceFactory implements SourceFactory { @Override public <T> Single<Source<T>> create(Vertx vertx, String name, Config config) { return Single.just(new KafkaSource<>(vertx, name, config)); } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test(expected = ConfigException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); }
@Test public void testCreationWithMinimalConfiguration() throws IOException { Single<Source<Object>> single = factory.create(vertx, null, new Config(new JsonObject() .put("bootstrap.servers", "localhost:9092") .put("key.deserializer", JsonObjectDeserializer.class.getName()) .put("value.deserializer", JsonObjectDeserializer.class.getName()))); Source<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(KafkaSource.class); } |
### Question:
ReflectionHelper { public static void set(Object mediator, Field field, Object source) { if (!field.isAccessible()) { field.setAccessible(true); } try { field.set(mediator, source); } catch (IllegalAccessException e) { throw new IllegalStateException("Unable to set field " + field.getName() + " from " + mediator.getClass().getName() + " to " + source, e); } } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test public void testValidSet() throws NoSuchFieldException { Test1 test = new Test1(); Field field = Test1.class.getDeclaredField("foo"); ReflectionHelper.set(test, field, "hello"); assertThat(test.foo).isEqualTo("hello"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidSet() throws NoSuchFieldException { Test1 test = new Test1(); Field field = Test1.class.getDeclaredField("foo"); ReflectionHelper.set(test, field, 10); } |
### Question:
ReflectionHelper { public static void invokeFunction(Object mediator, Method method) { method = ReflectionHelper.makeAccessibleIfNot(method); List<Flowable<Object>> sources = getFlowableForParameters(method); Function function = method.getAnnotation(Function.class); Sink<Object> sink = null; if (function.outbound().length() != 0) { sink = getSinkOrFail(function.outbound()); } Method methodToBeInvoked = method; Sink<Object> theSink = sink; Flowable<Optional<Object>> result; if (sources.size() == 1) { result = sources.get(0) .map(item -> Optional.ofNullable(methodToBeInvoked.invoke(mediator, item))); } else { result = Flowable.zip(sources, args -> args) .map(args -> Optional.ofNullable(methodToBeInvoked.invoke(mediator, args))); } result .flatMapCompletable(maybeResult -> { if (! maybeResult.isPresent()) { return Completable.complete(); } else { return propagateResult(maybeResult.get(), theSink); } }) .doOnError(Throwable::printStackTrace) .subscribe(); } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFunctionWithNotAnnotatedParameter() throws NoSuchMethodException { InvalidBecauseOfBadParams test = new InvalidBecauseOfBadParams(); Method method = test.getClass().getMethod("function", String.class); ReflectionHelper.invokeFunction(test, method); }
@Test(expected = IllegalArgumentException.class) public void testFunctionWithoutParam() throws NoSuchMethodException { InvalidBecauseOfBadParams test = new InvalidBecauseOfBadParams(); Method method = test.getClass().getMethod("functionWithoutParam"); ReflectionHelper.invokeFunction(test, method); } |
### Question:
PostgreSQLGuavaRangeType extends ImmutableType<Range> implements DynamicParameterizedType { public static Range<Integer> integerRange(String range) { return ofString(range, new Function<String, Integer>() { @Override public Integer apply(String s) { return Integer.parseInt(s); } }, Integer.class); } PostgreSQLGuavaRangeType(); @Override int[] sqlTypes(); @SuppressWarnings("unchecked") static Range<T> ofString(String str, Function<String, T> converter, Class<T> cls); static Range<BigDecimal> bigDecimalRange(String range); static Range<Integer> integerRange(String range); static Range<Long> longRange(String range); String asString(Range range); @Override void setParameterValues(Properties parameters); Class<?> getElementType(); static final PostgreSQLGuavaRangeType INSTANCE; }### Answer:
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { Throwable rootCause = Throwables.getRootCause(e); assertTrue(rootCause instanceof IllegalArgumentException); assertTrue(rootCause.getMessage().contains("Cannot find bound type")); } } |
### Question:
JacksonUtil { public static <T> T clone(T value) { return ObjectMapperWrapper.INSTANCE.clone(value); } static T fromString(String string, Class<T> clazz); static T fromString(String string, Type type); static String toString(Object value); static JsonNode toJsonNode(String value); static T clone(T value); }### Answer:
@Test public void cloneDeserializeStepErrorTest() { MyEntity entity = new MyEntity(); entity.setValue("some value"); entity.setPojos(Arrays.asList( createMyPojo("first value", MyType.A, "1.1", createOtherPojo("USD")), createMyPojo("second value", MyType.B, "1.2", createOtherPojo("BRL")) )); MyEntity clone = JacksonUtil.clone(entity); assertEquals(clone, entity); List<MyPojo> clonePojos = JacksonUtil.clone(entity.getPojos()); assertEquals(clonePojos, entity.getPojos()); } |
### Question:
JsonTypeDescriptor extends AbstractTypeDescriptor<Object> implements DynamicParameterizedType { @Override public boolean areEqual(Object one, Object another) { if (one == another) { return true; } if (one == null || another == null) { return false; } if (one instanceof String && another instanceof String) { return one.equals(another); } if (one instanceof Collection && another instanceof Collection) { return Objects.equals(one, another); } if (one.getClass().equals(another.getClass()) && ReflectionUtils.getDeclaredMethodOrNull(one.getClass(), "equals", Object.class) != null) { return one.equals(another); } return objectMapperWrapper.toJsonNode(objectMapperWrapper.toString(one)).equals( objectMapperWrapper.toJsonNode(objectMapperWrapper.toString(another)) ); } JsonTypeDescriptor(); JsonTypeDescriptor(Type type); JsonTypeDescriptor(final ObjectMapperWrapper objectMapperWrapper); JsonTypeDescriptor(final ObjectMapperWrapper objectMapperWrapper, Type type); @Override void setParameterValues(Properties parameters); @Override boolean areEqual(Object one, Object another); @Override String toString(Object value); @Override Object fromString(String string); @SuppressWarnings({"unchecked"}) @Override X unwrap(Object value, Class<X> type, WrapperOptions options); @Override Object wrap(X value, WrapperOptions options); }### Answer:
@Test public void testSetsAreEqual() { JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); Form theFirst = createForm(1, 2, 3); Form theSecond = createForm(3, 2, 1); assertTrue(descriptor.areEqual(theFirst, theSecond)); } |
### Question:
SQLExtractor { public static String from(Query query) { AbstractProducedQuery abstractProducedQuery = query.unwrap(AbstractProducedQuery.class); String[] sqls = abstractProducedQuery .getProducer() .getFactory() .getQueryPlanCache() .getHQLQueryPlan(abstractProducedQuery.getQueryString(), false, Collections.emptyMap()) .getSqlStrings(); return sqls.length > 0 ? sqls[0] : null; } private SQLExtractor(); static String from(Query query); }### Answer:
@Test public void testJPQL() { doInJPA(entityManager -> { Query jpql = entityManager .createQuery( "select " + " YEAR(p.createdOn) as year, " + " count(p) as postCount " + "from " + " Post p " + "group by " + " YEAR(p.createdOn)", Tuple.class); String sql = SQLExtractor.from(jpql); assertNotNull(sql); LOGGER.info( "The JPQL query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]", jpql.unwrap(org.hibernate.query.Query.class).getQueryString(), sql ); }); }
@Test public void testCriteriaAPI() { doInJPA(entityManager -> { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class); Root<PostComment> postComment = criteria.from(PostComment.class); Join<PostComment, Post> post = postComment.join("post"); criteria.where( builder.like(post.get("title"), "%Java%") ); criteria.orderBy( builder.asc(postComment.get("id")) ); Query criteriaQuery = entityManager.createQuery(criteria); String sql = SQLExtractor.from(criteriaQuery); assertNotNull(sql); LOGGER.info( "The Criteria API query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]", criteriaQuery.unwrap(org.hibernate.query.Query.class).getQueryString(), sql ); }); } |
### Question:
Configuration { public Properties getProperties() { return properties; } private Configuration(); Properties getProperties(); ObjectMapperWrapper getObjectMapperWrapper(); Integer integerProperty(PropertyKey propertyKey); Long longProperty(PropertyKey propertyKey); Boolean booleanProperty(PropertyKey propertyKey); Class<T> classProperty(PropertyKey propertyKey); static final Configuration INSTANCE; static final String PROPERTIES_FILE_PATH; static final String PROPERTIES_FILE_NAME; }### Answer:
@Test public void testHibernateProperties() { assertNull(Configuration.INSTANCE.getProperties().getProperty("hibernate.types.nothing")); assertEquals("def", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.abc")); }
@Test public void testHibernateTypesOverrideProperties() { assertEquals("ghi", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.def")); } |
### Question:
PostgreSQLHStoreType extends ImmutableType<Map> { @Override protected Map get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { return (Map) rs.getObject(names[0]); } PostgreSQLHStoreType(); @Override int[] sqlTypes(); static final PostgreSQLHStoreType INSTANCE; }### Answer:
@Test public void test() { doInJPA(entityManager -> { Book book = new Book(); book.setIsbn("978-9730228236"); book.getProperties().put("title", "High-Performance Java Persistence"); book.getProperties().put("author", "Vlad Mihalcea"); book.getProperties().put("publisher", "Amazon"); book.getProperties().put("price", "$44.95"); entityManager.persist(book); }); doInJPA(entityManager -> { Book book = entityManager.unwrap(Session.class) .bySimpleNaturalId(Book.class) .load("978-9730228236"); assertEquals("High-Performance Java Persistence", book.getProperties().get("title")); assertEquals("Vlad Mihalcea", book.getProperties().get("author")); }); } |
### Question:
PostgreSQLGuavaRangeType extends ImmutableType<Range> implements DynamicParameterizedType { public static Range<Integer> integerRange(String range) { return ofString(range, Integer::parseInt, Integer.class); } PostgreSQLGuavaRangeType(); @Override int[] sqlTypes(); @SuppressWarnings("unchecked") static Range<T> ofString(String str, Function<String, T> converter, Class<T> cls); static Range<BigDecimal> bigDecimalRange(String range); static Range<Integer> integerRange(String range); static Range<Long> longRange(String range); static Range<LocalDateTime> localDateTimeRange(String range); static Range<LocalDate> localDateRange(String range); static Range<ZonedDateTime> zonedDateTimeRange(String rangeStr); String asString(Range range); @Override void setParameterValues(Properties parameters); Class<?> getElementType(); static final PostgreSQLGuavaRangeType INSTANCE; }### Answer:
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { IllegalArgumentException rootCause = ExceptionUtil.rootCause(e); assertTrue(rootCause.getMessage().contains("Cannot find bound type")); } } |
### Question:
SQLExtractor { public static String from(Query query) { AbstractQueryImpl abstractQuery = query.unwrap(AbstractQueryImpl.class); SessionImplementor session = ReflectionUtils.getFieldValue(abstractQuery, "session"); String[] sqls = session.getFactory() .getQueryPlanCache() .getHQLQueryPlan(abstractQuery.getQueryString(), false, Collections.<String, Filter>emptyMap()) .getSqlStrings(); return sqls.length > 0 ? sqls[0] : null; } private SQLExtractor(); static String from(Query query); }### Answer:
@Test public void testJPQL() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Query query = entityManager .createQuery( "select " + " YEAR(p.createdOn) as year, " + " count(p) as postCount " + "from " + " Post p " + "group by " + " YEAR(p.createdOn)", Tuple.class); String sql = SQLExtractor.from(query); assertNotNull(sql); LOGGER.info("SQL query: {}", sql); return null; } }); }
@Test public void testCriteriaAPI() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class); Root<PostComment> postComment = criteria.from(PostComment.class); Join<PostComment, Post> post = postComment.join("post"); Path<String> postTitle = post.get("title"); criteria.where( builder.like(postTitle, "%Java%") ); criteria.orderBy( builder.asc(postComment.get("id")) ); Query query = entityManager.createQuery(criteria); String sql = SQLExtractor.from(query); assertNotNull(sql); LOGGER.info("SQL query: {}", sql); return null; } }); } |
### Question:
PostgreSQLGuavaRangeType extends ImmutableType<Range> { public static Range<Integer> integerRange(String range) { return ofString(range, new Function<String, Integer>() { @Override public Integer apply(String s) { return Integer.parseInt(s); } }, Integer.class); } PostgreSQLGuavaRangeType(); @Override int[] sqlTypes(); @SuppressWarnings("unchecked") static Range<T> ofString(String str, Function<String, T> converter, Class<T> cls); static Range<BigDecimal> bigDecimalRange(String range); static Range<Integer> integerRange(String range); static Range<Long> longRange(String range); String asString(Range range); static final PostgreSQLGuavaRangeType INSTANCE; }### Answer:
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { Throwable rootCause = Throwables.getRootCause(e); assertTrue(rootCause instanceof IllegalArgumentException); assertTrue(rootCause.getMessage().contains("Cannot find bound type")); } } |
### Question:
ACLFileParser { public static AuthorizationsCollector parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return AuthorizationsCollector.emptyImmutableCollector(); } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return AuthorizationsCollector.emptyImmutableCollector(); } try { FileReader reader = new FileReader(file); return parse(reader); } catch (FileNotFoundException fex) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); return AuthorizationsCollector.emptyImmutableCollector(); } } private ACLFileParser(); static AuthorizationsCollector parse(File file); static AuthorizationsCollector parse(Reader reader); }### Answer:
@Test public void testParseEmpty() throws ParseException { Reader conf = new StringReader(" "); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.isEmpty()); }
@Test public void testParseValidComment() throws ParseException { Reader conf = new StringReader("#simple comment"); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.isEmpty()); }
@Test(expected = ParseException.class) public void testParseInvalidComment() throws ParseException { Reader conf = new StringReader(" #simple comment"); ACLFileParser.parse(conf); }
@Test public void testParseSingleLineACL() throws ParseException { Reader conf = new StringReader("topic /weather/italy/anemometer"); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.canRead(new Topic("/weather/italy/anemometer"), "", "")); assertTrue(authorizations.canWrite(new Topic("/weather/italy/anemometer"), "", "")); } |
### Question:
ConfigurationParser { void parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return; } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return; } try { FileReader reader = new FileReader(file); parse(reader); } catch (FileNotFoundException fex) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); return; } } }### Answer:
@Test(expected = ParseException.class) public void parseInvalidComment() throws ParseException { Reader conf = new StringReader(" #simple comment"); m_parser.parse(conf); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyClientConnected(final MqttConnectMessage msg) { for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Sending MQTT CONNECT message to interceptor. CId={}, interceptorId={}", msg.payload().clientIdentifier(), handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onConnect(new InterceptConnectMessage(msg)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyClientConnected() throws Exception { interceptor.notifyClientConnected(MqttMessageBuilders.connect().build()); interval(); assertEquals(40, n.get()); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyClientDisconnected(final String clientID, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT client disconnection to interceptor. CId={}, username={}, interceptorId={}", clientID, username, handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onDisconnect(new InterceptDisconnectMessage(clientID, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyClientDisconnected() throws Exception { interceptor.notifyClientDisconnected("cli1234", "cli1234"); interval(); assertEquals(50, n.get()); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyTopicSubscribed(final Subscription sub, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptSubscribeMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT SUBSCRIBE message to interceptor. CId={}, topicFilter={}, interceptorId={}", sub.getClientId(), sub.getTopicFilter(), handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onSubscribe(new InterceptSubscribeMessage(sub, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyTopicSubscribed() throws Exception { interceptor.notifyTopicSubscribed(new Subscription("cli1", new Topic("o2"), MqttQoS.AT_MOST_ONCE), "cli1234"); interval(); assertEquals(70, n.get()); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyTopicUnsubscribed(final String topic, final String clientID, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptUnsubscribeMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT UNSUBSCRIBE message to interceptor. CId={}, topic={}, interceptorId={}", clientID, topic, handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onUnsubscribe(new InterceptUnsubscribeMessage(topic, clientID, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyTopicUnsubscribed() throws Exception { interceptor.notifyTopicUnsubscribed("o2", "cli1234", "cli1234"); interval(); assertEquals(80, n.get()); } |
### Question:
MapDBPersistentStore implements IStore { @Override public void close() { if (this.m_db.isClosed()) { LOG.warn("MapDB store is already closed. Nothing will be done"); return; } LOG.info("Performing last commit to MapDB"); this.m_db.commit(); LOG.info("Closing MapDB store"); this.m_db.close(); LOG.info("Stopping MapDB commit tasks"); this.m_scheduler.shutdown(); try { m_scheduler.awaitTermination(10L, TimeUnit.SECONDS); } catch (InterruptedException e) { } if (!m_scheduler.isTerminated()) { LOG.warn("Forcing shutdown of MapDB commit tasks"); m_scheduler.shutdown(); } LOG.info("MapDB store has been closed successfully"); } MapDBPersistentStore(IConfig props); @Override IMessagesStore messagesStore(); @Override ISessionsStore sessionsStore(); @Override void initStore(); @Override void close(); }### Answer:
@Test public void testCloseShutdownCommitTask() throws InterruptedException { m_storageService.close(); assertTrue("Storage service scheduler can't be stopped in 3 seconds", m_storageService.m_scheduler.awaitTermination(3, TimeUnit.SECONDS)); assertTrue(m_storageService.m_scheduler.isTerminated()); } |
### Question:
DBAuthenticator implements IAuthenticator { @Override public synchronized boolean checkValid(String clientId, String username, byte[] password) { if (username == null || password == null) { LOG.info("username or password was null"); return false; } ResultSet r = null; try { this.preparedStatement.setString(1, username); r = this.preparedStatement.executeQuery(); if (r.next()) { final String foundPwq = r.getString(1); messageDigest.update(password); byte[] digest = messageDigest.digest(); String encodedPasswd = new String(Hex.encodeHex(digest)); return foundPwq.equals(encodedPasswd); } r.close(); } catch (SQLException e) { e.printStackTrace(); } return false; } DBAuthenticator(IConfig conf); DBAuthenticator(String driver, String jdbcUrl, String sqlQuery, String digestMethod); @Override synchronized boolean checkValid(String clientId, String username, byte[] password); }### Answer:
@Test public void Db_verifyValid() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertTrue(dbAuthenticator.checkValid(null, "dbuser", "password".getBytes())); }
@Test public void Db_verifyInvalidLogin() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(null, "dbuser2", "password".getBytes())); }
@Test public void Db_verifyInvalidPassword() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(null, "dbuser", "wrongPassword".getBytes())); } |
### Question:
ChainingPrincipalResolver implements PrincipalResolver { public boolean supports(final Credential credential) { return this.chain.get(0).supports(credential); } void setChain(final List<PrincipalResolver> chain); Principal resolve(final Credential credential); boolean supports(final Credential credential); }### Answer:
@Test public void testSupports() throws Exception { final Credential credential = mock(Credential.class); when(credential.getId()).thenReturn("a"); final PrincipalResolver resolver1 = mock(PrincipalResolver.class); when(resolver1.supports(eq(credential))).thenReturn(true); final PrincipalResolver resolver2 = mock(PrincipalResolver.class); when(resolver2.supports(eq(credential))).thenReturn(false); final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver(); resolver.setChain(Arrays.asList(resolver1, resolver2)); assertTrue(resolver.supports(credential)); } |
### Question:
ChainingPrincipalResolver implements PrincipalResolver { public Principal resolve(final Credential credential) { Principal result = null; Credential input = credential; for (final PrincipalResolver resolver : this.chain) { if (result != null) { input = new IdentifiableCredential(result.getId()); } result = resolver.resolve(input); } return result; } void setChain(final List<PrincipalResolver> chain); Principal resolve(final Credential credential); boolean supports(final Credential credential); }### Answer:
@Test public void testResolve() throws Exception { final Credential credential = mock(Credential.class); when(credential.getId()).thenReturn("input"); final PrincipalResolver resolver1 = mock(PrincipalResolver.class); when(resolver1.supports(eq(credential))).thenReturn(true); when(resolver1.resolve((eq(credential)))).thenReturn(new SimplePrincipal("output")); final PrincipalResolver resolver2 = mock(PrincipalResolver.class); when(resolver2.supports(any(Credential.class))).thenReturn(false); when(resolver2.resolve(argThat(new ArgumentMatcher<Credential>() { @Override public boolean matches(final Object o) { return ((Credential) o).getId().equals("output"); } }))).thenReturn( new SimplePrincipal("final", Collections.<String, Object>singletonMap("mail", "[email protected]"))); final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver(); resolver.setChain(Arrays.asList(resolver1, resolver2)); final Principal principal = resolver.resolve(credential); assertEquals("final", principal.getId()); assertEquals("[email protected]", principal.getAttributes().get("mail")); } |
### Question:
LegacyAuthenticationHandlerAdapter implements AuthenticationHandler { @Override public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException, PreventedException { try { if (this.legacyHandler.authenticate(credentialsAdapter.convert(credential))) { final CredentialMetaData md; if (credential instanceof CredentialMetaData) { md = (CredentialMetaData) credential; } else { md = new BasicCredentialMetaData(credential); } return new HandlerResult(this, md); } else { throw new FailedLoginException( String.format("%s failed to authenticate %s", this.getName(), credential)); } } catch (final AuthenticationException e) { throw new GeneralSecurityException( String.format("%s failed to authenticate %s", this.getName(), credential), e); } } LegacyAuthenticationHandlerAdapter(final org.jasig.cas.authentication.handler.AuthenticationHandler legacy); LegacyAuthenticationHandlerAdapter(
final org.jasig.cas.authentication.handler.AuthenticationHandler legacy,
final CredentialsAdapter adapter); @Override HandlerResult authenticate(final Credential credential); @Override boolean supports(final Credential credential); @Override String getName(); }### Answer:
@Test public void testAuthenticateSuccess() throws Exception { final HandlerResult result = alwaysPassHandler.authenticate(new UsernamePasswordCredential("a", "b")); assertEquals("TestAlwaysPassAuthenticationHandler", result.getHandlerName()); }
@Test(expected = FailedLoginException.class) public void testAuthenticateFailure() throws Exception { alwaysFailHandler.authenticate(new UsernamePasswordCredential("a", "b")); } |
### Question:
JRadiusServerImpl implements RadiusServer { @Override public boolean authenticate(final String username, final String password) throws PreventedException { final AttributeList attributeList = new AttributeList(); attributeList.add(new Attr_UserName(username)); attributeList.add(new Attr_UserPassword(password)); RadiusClient client = null; try { client = this.radiusClientFactory.newInstance(); LOGGER.debug("Created RADIUS client instance {}", client); final AccessRequest request = new AccessRequest(client, attributeList); final RadiusPacket response = client.authenticate( request, RadiusClient.getAuthProtocol(this.protocol.getName()), this.retries); LOGGER.debug("RADIUS response from {}: {}", client.getRemoteInetAddress().getCanonicalHostName(), response.getClass().getName()); if (response instanceof AccessAccept) { return true; } } catch (final Exception e) { throw new PreventedException(e); } finally { if (client != null) { client.close(); } } return false; } JRadiusServerImpl(final RadiusProtocol protocol, final RadiusClientFactory clientFactory); @Override boolean authenticate(final String username, final String password); void setRetries(final int retries); static final int DEFAULT_RETRY_COUNT; }### Answer:
@Test public void testAuthenticate() { assertNotNull(this.radiusServer); } |
### Question:
SmartOpenIdController extends DelegateController implements Serializable { @Override public boolean canHandle(final HttpServletRequest request, final HttpServletResponse response) { String openIdMode = request.getParameter("openid.mode"); if (openIdMode != null && openIdMode.equals("associate")) { logger.info("Handling request. openid.mode : {}", openIdMode); return true; } logger.info("Cannot handle request. openid.mode : {}", openIdMode); return false; } Map<String, String> getAssociationResponse(final HttpServletRequest request); @Override boolean canHandle(final HttpServletRequest request, final HttpServletResponse response); void setSuccessView(final String successView); void setFailureView(final String failureView); @NotNull void setServerManager(final ServerManager serverManager); }### Answer:
@Test public void testCanHandle() { request.addParameter("openid.mode", "associate"); boolean canHandle = smartOpenIdController.canHandle(request, response); request.removeParameter("openid.mode"); assertEquals(true, canHandle); }
@Test public void testCannotHandle() { request.addParameter("openid.mode", "anythingElse"); boolean canHandle = smartOpenIdController.canHandle(request, response); request.removeParameter("openid.mode"); assertEquals(false, canHandle); } |
### Question:
AvailableForm extends BaseForm { public boolean isRegistrationForm(){ return Constants.FORM_DISCRIMINATOR_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_GENERIC_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_SHR_REGISTRATION.equalsIgnoreCase(getDiscriminator()); } Tag[] getTags(); void setTags(Tag[] tags); boolean isDownloaded(); void setDownloaded(boolean downloaded); boolean isRegistrationForm(); boolean isProviderReport(); boolean isRelationshipForm(); }### Answer:
@Test public void shouldReturnFalseIfHasNoRegistrationDiscriminator() { AvailableForm availableForm = new AvailableForm(); assertFalse(availableForm.isRegistrationForm()); for(String discriminator: nonRegistrationDiscriminators) { availableForm.setDiscriminator(discriminator); assertFalse(availableForm.isRegistrationForm()); } }
@Test public void shouldReturnTrueIfHasRegistrationDiscriminator() { AvailableForm availableForm = new AvailableForm(); for(String discriminator: registrationDiscriminators) { availableForm.setDiscriminator(discriminator); assertTrue(availableForm.isRegistrationForm()); } } |
### Question:
LocationController { public List<Location> downloadLocationFromServerByName(String name) throws LocationDownloadException { try { return locationService.downloadLocationsByName(name); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while searching for patients in the server", e); throw new LocationDownloadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }### Answer:
@Test public void shouldSearchOnServerForLocationsByNames() throws Exception, LocationController.LocationDownloadException { String name = "name"; List<Location> locations = new ArrayList<>(); when(locationService.downloadLocationsByName(name)).thenReturn(locations); assertThat(locationController.downloadLocationFromServerByName(name), is(locations)); verify(locationService).downloadLocationsByName(name); }
@Test(expected = LocationController.LocationDownloadException.class) public void shouldReturnEmptyListIsExceptionThrown() throws Exception, LocationController.LocationDownloadException { String searchString = "name"; doThrow(new IOException()).when(locationService).downloadLocationsByName(searchString); assertThat(locationController.downloadLocationFromServerByName(searchString).size(), is(0)); } |
### Question:
LocationController { public Location downloadLocationFromServerByUuid(String uuid) throws LocationDownloadException { try { return locationService.downloadLocationByUuid(uuid); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while searching for patients in the server", e); throw new LocationDownloadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }### Answer:
@Test public void shouldSearchOnServerForLocationByUuid() throws Exception, LocationController.LocationDownloadException { String uuid = "uuid"; Location location = new Location(); when(locationService.downloadLocationByUuid(uuid)).thenReturn(location); assertThat(locationController.downloadLocationFromServerByUuid(uuid), is(location)); verify(locationService).downloadLocationByUuid(uuid); } |
### Question:
LocationController { public List<Location> getAllLocations() throws LocationLoadException { try { return locationService.getAllLocations(); } catch (IOException e) { throw new LocationLoadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }### Answer:
@Test public void getAllLocations_shouldReturnAllAvailableLocations() throws IOException, LocationController.LocationLoadException { List<Location> locations = new ArrayList<>(); when(locationService.getAllLocations()).thenReturn(locations); assertThat(locationController.getAllLocations(), is(locations)); }
@Test(expected = LocationController.LocationLoadException.class) public void getAllLocations_shouldThrowLoLocationFetchExceptionIfExceptionThrownByLocationService() throws IOException, LocationController.LocationLoadException { doThrow(new IOException()).when(locationService).getAllLocations(); locationController.getAllLocations(); } |
### Question:
LocationController { public Location getLocationByUuid(String uuid) throws LocationLoadException { try { return locationService.getLocationByUuid(uuid); } catch (IOException e) { throw new LocationLoadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }### Answer:
@Test public void getLocationByUuid_shouldReturnLocationForId() throws Exception, LocationController.LocationLoadException { Location location = new Location(); String uuid = "uuid"; when(locationService.getLocationByUuid(uuid)).thenReturn(location); assertThat(locationController.getLocationByUuid(uuid), is(location)); } |
### Question:
MuzimaProgressDialog { @JavascriptInterface public void show(String title) { dialog.setTitle(title); dialog.setMessage(dialog.getContext().getResources().getString(R.string.general_progress_message)); dialog.show(); } MuzimaProgressDialog(Activity activity); MuzimaProgressDialog(ProgressDialog dialog); @JavascriptInterface void show(String title); @JavascriptInterface void updateMessage(String message); @JavascriptInterface void dismiss(); }### Answer:
@Test public void shouldShowProgressDialogWithGivenText() { dialog.show("title"); Mockito.verify(progressDialog).setCancelable(false); Mockito.verify(progressDialog).setTitle("title"); Mockito.verify(progressDialog).setMessage("This might take a while"); Mockito.verify(progressDialog).show(); } |
### Question:
MuzimaProgressDialog { @JavascriptInterface public void dismiss() { if (dialog.isShowing()) { dialog.dismiss(); } } MuzimaProgressDialog(Activity activity); MuzimaProgressDialog(ProgressDialog dialog); @JavascriptInterface void show(String title); @JavascriptInterface void updateMessage(String message); @JavascriptInterface void dismiss(); }### Answer:
@Test public void shouldDismissADialogOnlyWhenVisible() { when(progressDialog.isShowing()).thenReturn(true); dialog.dismiss(); Mockito.verify(progressDialog).dismiss(); }
@Test public void shouldNotCallDismissIfProgressBarISNotVisible() { when(progressDialog.isShowing()).thenReturn(false); dialog.dismiss(); Mockito.verify(progressDialog, Mockito.never()).dismiss(); } |
### Question:
FormDataStore { @JavascriptInterface public String getFormPayload() { return formData.getJsonPayload(); } FormDataStore(FormWebViewActivity formWebViewActivity, FormController formController, FormData formData); @JavascriptInterface void save(String jsonData, String xmlData, String status); @JavascriptInterface String getFormPayload(); @JavascriptInterface String getFormStatus(); @JavascriptInterface void showSaveProgressBar(); }### Answer:
@Test public void getFormPayload_shouldGetTheFormDataPayload() { formData.setJsonPayload("payload"); assertThat(store.getFormPayload(), is("payload")); } |
### Question:
StringUtils { public static String getCommaSeparatedStringFromList(final List<String> values){ if(values == null){ return ""; } StringBuilder builder = new StringBuilder(); for (String next : values) { builder.append(next).append(","); } String commaSeparated = builder.toString(); return commaSeparated.substring(0, commaSeparated.length() - 1); } static String getCommaSeparatedStringFromList(final List<String> values); static List<String> getListFromCommaSeparatedString(String value); static boolean isEmpty(String string); static String defaultString(String string); static boolean equals(String str1, String str2); static boolean equalsIgnoreCase(String str1, String str2); static int nullSafeCompare(String str1, String str2); static final String EMPTY; }### Answer:
@Test public void shouldReturnCommaSeparatedList(){ ArrayList<String> listOfStrings = new ArrayList<String>() {{ add("Patient"); add("Registration"); add("New Tag"); }}; String commaSeparatedValues = StringUtils.getCommaSeparatedStringFromList(listOfStrings); assertThat(commaSeparatedValues, is("Patient,Registration,New Tag")); } |
### Question:
PatientComparator implements Comparator<Patient> { @Override public int compare(Patient patient1, Patient patient2) { if (patient1 == null) { patient1 = new Patient(); } if (patient2 == null) { patient2 = new Patient(); } int familyNameCompareResult = StringUtils.nullSafeCompare(patient1.getFamilyName(), patient2.getFamilyName()); if (familyNameCompareResult != 0) { return familyNameCompareResult; } int givenNameCompareResult = StringUtils.nullSafeCompare(patient1.getGivenName(), patient2.getGivenName()); if (givenNameCompareResult != 0) { return givenNameCompareResult; } return StringUtils.nullSafeCompare(patient1.getMiddleName(), patient2.getMiddleName()); } @Override int compare(Patient patient1, Patient patient2); }### Answer:
@Test public void shouldSortByFamilyName() { Patient obama = patient("Obama", "Barack", "Hussein", "id1"); Patient bush = patient("Bush", "George", "W", "id2"); assertTrue(patientComparator.compare(obama, bush) > 0); }
@Test public void shouldSortByGivenNameIfFamilyNameIsSame() { Patient barack = patient("Obama", "Barack", "Hussein", "id1"); Patient george = patient("Obama", "George", "W", "id2"); assertTrue(patientComparator.compare(barack, george) < 0); }
@Test public void shouldSortByMiddleNameIfGivenNameAndFamilyNameAreSame() { Patient hussein = patient("Obama", "Barack", "Hussein", "id1"); Patient william = patient("Obama", "Barack", "William", "id2"); assertTrue(patientComparator.compare(hussein, william) < 0); } |
### Question:
Concepts extends ArrayList<ConceptWithObservations> { public void sortByDate() { Collections.sort(this, new Comparator<ConceptWithObservations>() { @Override public int compare(ConceptWithObservations lhs, ConceptWithObservations rhs) { return -(lhs.getObservations().get(0).getObservationDatetime() .compareTo(rhs.getObservations().get(0).getObservationDatetime())); } }); } Concepts(); Concepts(Observation... observations); Concepts(List<Observation> observationsByPatient); void sortByDate(); }### Answer:
@Test public void shouldSortTheConceptsByDate() { final Observation observation1 = createObservation(createConcept("c1"), "01", new Date(1)); final Observation observation2 = createObservation(createConcept("c2"), "02", new Date(3)); final Observation observation3 = createObservation(createConcept("c1"), "03", new Date(2)); final Concepts concepts = new Concepts(observation1, observation2, observation3); concepts.sortByDate(); final Concepts expectedOrderedConcept = new Concepts() {{ add(conceptWithObservations(observation2)); add(conceptWithObservations(observation3, observation1)); }}; assertThat(concepts, is(expectedOrderedConcept)); } |
### Question:
ObservationParserUtility { public List<Concept> getNewConceptList() { return newConceptList; } ObservationParserUtility(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid); Concept getConceptEntity(String rawConceptName, boolean isCoded, boolean createConceptIfNotAvailableLocally); Observation getObservationEntity(Concept concept, String value); List<Concept> getNewConceptList(); static boolean isFormattedAsConcept(String peek); String getObservationUuid(); }### Answer:
@Test public void shouldNotCreateNewConceptOrObservationForInvalidConceptName() { observationParserUtility = new ObservationParserUtility(muzimaApplication,true); assertThat(observationParserUtility.getNewConceptList().size(), is(0)); } |
### Question:
HTMLFormObservationCreator { public void createAndPersistObservations(String jsonResponse,String formDataUuid) { parseJSONResponse(jsonResponse,formDataUuid); try { saveObservationsAndRelatedEntities(); } catch (ConceptController.ConceptSaveException e) { Log.e(getClass().getSimpleName(), "Error while saving concept", e); } catch (EncounterController.SaveEncounterException e) { Log.e(getClass().getSimpleName(), "Error while saving Encounter", e); } catch (ObservationController.SaveObservationException e) { Log.e(getClass().getSimpleName(), "Error while saving Observation", e); } catch (Exception e) { Log.e(getClass().getSimpleName(), "Unexpected Exception occurred", e); } } HTMLFormObservationCreator(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); void createAndPersistObservations(String jsonResponse,String formDataUuid); void createObservationsAndRelatedEntities(String jsonResponse,String formDataUuid); List<Observation> getObservations(); Encounter getEncounter(); List<Concept> getNewConceptList(); Date getEncounterDateFromFormDate(String jsonResponse); }### Answer:
@Test public void shouldVerifyAllObservationsAndRelatedEntitiesAreSaved() throws EncounterController.SaveEncounterException, ConceptController.ConceptSaveException, ObservationController.SaveObservationException { htmlFormObservationCreator.createAndPersistObservations(readFile(),formDataUuid); verify(encounterController).saveEncounters(encounterArgumentCaptor.capture()); assertThat(encounterArgumentCaptor.getValue().size(), is(1)); verify(conceptController).saveConcepts(conceptArgumentCaptor.capture()); List<Concept> value = conceptArgumentCaptor.getValue(); assertThat(value.size(), is(33)); verify(observationController).saveObservations(observationArgumentCaptor.capture()); assertThat(observationArgumentCaptor.getValue().size(), is(30)); } |
### Question:
HTMLConceptParser { public List<String> parse(String html) { Set<String> concepts = new HashSet<>(); Document htmlDoc = Jsoup.parse(html); Elements elements = htmlDoc.select("*:not(div)[" + DATA_CONCEPT_TAG + "]"); for (Element element : elements) { concepts.add(getConceptName(element.attr(DATA_CONCEPT_TAG))); } return new ArrayList<>(concepts); } List<String> parse(String html); }### Answer:
@Test public void shouldReturnListOfConcepts() { String html = readFile(); List<String> concepts = new HTMLConceptParser().parse(html); assertThat(concepts.size(),is(7)); assertThat(concepts,hasItem("BODY PART")); assertThat(concepts,hasItem("PROCEDURES DONE THIS VISIT")); assertThat(concepts,hasItem("ANATOMIC LOCATION DESCRIPTION")); assertThat(concepts,hasItem("CLOCK FACE CERVICAL BIOPSY LOCATION ")); assertThat(concepts,hasItem("PATHOLOGICAL DIAGNOSIS ADDED")); assertThat(concepts,hasItem("FREETEXT GENERAL")); assertThat(concepts,hasItem("RETURN VISIT DATE")); } |
### Question:
ConceptParser { public List<String> parse(String model) { try { if (StringUtils.isEmpty(model)) { return new ArrayList<>(); } parser.setInput(new ByteArrayInputStream(model.getBytes()), null); parser.nextTag(); return readConceptName(parser); } catch (Exception e) { throw new ParseConceptException(e); } } ConceptParser(); ConceptParser(XmlPullParser parser); List<String> parse(String model); }### Answer:
@Test public void shouldParseConcept() { List<String> conceptNames = utils.parse(getModel("concept.xml")); assertThat(conceptNames, hasItem("PULSE")); }
@Test public void shouldParseConceptInObs() { List<String> conceptNames = utils.parse(getModel("concept_in_obs.xml")); assertThat(conceptNames, hasItem("WEIGHT (KG)")); }
@Test public void shouldNotAddItToConceptUnLessBothDateAndTimeArePresentInChildren() { List<String> conceptNames = utils.parse(getModel("concepts_in_concept.xml")); assertThat(conceptNames.size(), is(2)); assertThat(conceptNames, hasItem("PROBLEM ADDED")); assertThat(conceptNames, hasItem("PROBLEM RESOLVED")); }
@Test public void shouldNotConsiderOptionsAsConcepts() { List<String> conceptNames = utils.parse(getModel("concepts_with_options.xml")); assertThat(conceptNames.size(), is(1)); assertThat(conceptNames, hasItem("MOST RECENT PAPANICOLAOU SMEAR RESULT")); }
@Test(expected = ConceptParser.ParseConceptException.class) public void shouldThrowParseConceptExceptionWhenTheModelHasNoEndTag() { utils.parse(getModel("concept_no_end_tag.xml")); }
@Test public void shouldParseConceptTM() { List<String> conceptNames = utils.parse(getModel("dispensary_concept_in_obs.xml")); assertThat(conceptNames, hasItem("START TIME")); assertThat(conceptNames, hasItem("END TIME")); } |
### Question:
ConceptsByPatient extends ConceptAction { @Override Concepts get() throws ObservationController.LoadObservationException { return controller.getConceptWithObservations(patientUuid); } ConceptsByPatient(ConceptController conceptController, ObservationController controller, String patientUuid); @Override String toString(); }### Answer:
@Test public void shouldGetObservationsByPatientUUID() throws ObservationController.LoadObservationException { ObservationController controller = mock(ObservationController.class); ConceptController conceptController = mock(ConceptController.class); ConceptsByPatient byPatient = new ConceptsByPatient(conceptController,controller, "uuid"); byPatient.get(); verify(controller).getConceptWithObservations("uuid"); } |
### Question:
ConceptsBySearch extends ConceptAction { @Override Concepts get() throws ObservationController.LoadObservationException { return controller.searchObservationsGroupedByConcepts(term, patientUuid); } ConceptsBySearch(ConceptController conceptController, ObservationController controller, String patientUuid, String term); @Override String toString(); }### Answer:
@Test public void shouldSearchObservationsByUuidAndTerm() throws ObservationController.LoadObservationException { ObservationController controller = mock(ObservationController.class); ConceptController conceptController = mock(ConceptController.class); ConceptsBySearch conceptsBySearch = new ConceptsBySearch(conceptController,controller, "uuid", "term"); conceptsBySearch.get(); verify(controller).searchObservationsGroupedByConcepts("term", "uuid"); } |
### Question:
EntityUtils { @SuppressWarnings({ "unchecked", "rawtypes" }) public static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass) { if (entityClass.isAnnotationPresent(IdClass.class)) { return entityClass.getAnnotation(IdClass.class).value(); } Class clazz = PersistenceUnitDescriptorProvider.getInstance().primaryKeyIdClass(entityClass); if (clazz != null) { return clazz; } Property<Serializable> property = primaryKeyProperty(entityClass); return property.getJavaClass(); } private EntityUtils(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass); static Object primaryKeyValue(Object entity); static Object primaryKeyValue(Object entity, Property<Serializable> primaryKeyProperty); static String entityName(Class<?> entityClass); static String tableName(Class<?> entityClass, EntityManager entityManager); static boolean isEntityClass(Class<?> entityClass); static Property<Serializable> primaryKeyProperty(Class<?> entityClass); static Property<Serializable> getVersionProperty(Class<?> entityClass); }### Answer:
@Test public void should_find_id_property_class() { Class<? extends Serializable> pkClass = EntityUtils.primaryKeyClass(Tee.class); Assert.assertEquals(TeeId.class, pkClass); }
@Test public void should_find_id_class() { Class<? extends Serializable> pkClass = EntityUtils.primaryKeyClass(Tee2.class); Assert.assertEquals(TeeId.class, pkClass); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public void removeAndFlush(E entity) { entityManager().remove(entity); flush(); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_remove_and_flush() { Simple simple = testData.createSimple("testRemoveAndFlush"); repo.removeAndFlush(simple); Simple lookup = getEntityManager().find(Simple.class, simple.getId()); assertNull(lookup); } |
### Question:
EntityUtils { public static boolean isEntityClass(Class<?> entityClass) { return entityClass.isAnnotationPresent(Entity.class) || PersistenceUnitDescriptorProvider.getInstance().isEntity(entityClass); } private EntityUtils(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass); static Object primaryKeyValue(Object entity); static Object primaryKeyValue(Object entity, Property<Serializable> primaryKeyProperty); static String entityName(Class<?> entityClass); static String tableName(Class<?> entityClass, EntityManager entityManager); static boolean isEntityClass(Class<?> entityClass); static Property<Serializable> primaryKeyProperty(Class<?> entityClass); static Property<Serializable> getVersionProperty(Class<?> entityClass); }### Answer:
@Test public void should_accept_entity_class() { boolean isValid = EntityUtils.isEntityClass(Simple.class); Assert.assertTrue(isValid); }
@Test public void should_not_accept_class_without_entity_annotation() { boolean isValid = EntityUtils.isEntityClass(EntityWithoutId.class); Assert.assertFalse(isValid); } |
### Question:
PrincipalProvider extends AuditProvider { @Override public void prePersist(Object entity) { updatePrincipal(entity, true); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); }### Answer:
@Test public void should_set_users_for_creation() { String creator = "creator"; MockPrincipalProvider provider = new MockPrincipalProvider(creator); AuditedEntity entity = new AuditedEntity(); provider.prePersist(entity); assertNotNull(entity.getCreator()); assertNotNull(entity.getCreatorPrincipal()); assertNotNull(entity.getChanger()); assertEquals(entity.getCreator(), creator); assertEquals(entity.getCreatorPrincipal().getName(), creator); assertEquals(entity.getChanger(), creator); assertNull(entity.getChangerOnly()); assertNull(entity.getChangerOnlyPrincipal()); }
@Test(expected = AuditPropertyException.class) public void should_fail_on_invalid_entity() { PrincipalProviderTest.InvalidEntity entity = new PrincipalProviderTest.InvalidEntity(); new MockPrincipalProvider("").prePersist(entity); fail(); } |
### Question:
PrincipalProvider extends AuditProvider { @Override public void preUpdate(Object entity) { updatePrincipal(entity, false); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); }### Answer:
@Test public void should_set_users_for_update() { String changer = "changer"; MockPrincipalProvider provider = new MockPrincipalProvider(changer); AuditedEntity entity = new AuditedEntity(); provider.preUpdate(entity); assertNotNull(entity.getChanger()); assertNotNull(entity.getChangerOnly()); assertNotNull(entity.getChangerOnlyPrincipal()); assertEquals(entity.getChanger(), changer); assertEquals(entity.getChangerOnly(), changer); assertEquals(entity.getChangerOnlyPrincipal().getName(), changer); assertNull(entity.getCreator()); assertNull(entity.getCreatorPrincipal()); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.