method2testcases
stringlengths
118
6.63k
### Question: PostgresTypeConverter extends AbstractTypeConverter { @Override public BlobType getBlobType() { return new BlobType("BYTEA"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override DateTimeType getDateTimeType(); @Override NumberType getNumberType(); @Override TinyIntType getTinyIntType(); @Override DoubleType getDoubleType(); }### Answer: @Test public void getBlobType() { assertEquals("BYTEA", new PostgresTypeConverter().getBlobType().toString()); }
### Question: PostgresTypeConverter extends AbstractTypeConverter { @Override public ClobType getClobType() { return new ClobType("TEXT"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override DateTimeType getDateTimeType(); @Override NumberType getNumberType(); @Override TinyIntType getTinyIntType(); @Override DoubleType getDoubleType(); }### Answer: @Test public void getClobType() { assertEquals("TEXT", new PostgresTypeConverter().getClobType().toString()); }
### Question: PostgresTypeConverter extends AbstractTypeConverter { @Override public DateTimeType getDateTimeType() { return new DateTimeType("TIMESTAMP WITH TIME ZONE"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override DateTimeType getDateTimeType(); @Override NumberType getNumberType(); @Override TinyIntType getTinyIntType(); @Override DoubleType getDoubleType(); }### Answer: @Test public void getDateTimeType() { assertEquals("TIMESTAMP WITH TIME ZONE", new PostgresTypeConverter().getDateTimeType().toString()); }
### Question: PostgresTypeConverter extends AbstractTypeConverter { @Override public DataType getDataType(String columnTypeString, Boolean autoIncrement) { DataType type = super.getDataType(columnTypeString, autoIncrement); if (type.getDataTypeName().toLowerCase().contains("text")) { type = getClobType(); } else if (type.getDataTypeName().toLowerCase().contains("blob")) { type = getBlobType(); } else if (type.getDataTypeName().toLowerCase().startsWith("float8")) { type.setDataTypeName("FLOAT8"); } else if (type.getDataTypeName().toLowerCase().startsWith("float4")) { type.setDataTypeName("FLOAT4"); } if (autoIncrement != null && autoIncrement) { if ("integer".equals(type.getDataTypeName().toLowerCase())) { type.setDataTypeName("serial"); } else if ("bigint".equals(type.getDataTypeName().toLowerCase()) || "bigserial".equals(type.getDataTypeName().toLowerCase())) { type.setDataTypeName("bigserial"); } else { type.setDataTypeName("serial"); } } return type; } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override DateTimeType getDateTimeType(); @Override NumberType getNumberType(); @Override TinyIntType getTinyIntType(); @Override DoubleType getDoubleType(); }### Answer: @Test public void getColumnType_BigSerial_AutoIncrement() { assertEquals("bigserial", new PostgresTypeConverter().getDataType("bigserial", true).toString()); } @Test public void getColumnType_BigInt_AutoIncrement() { assertEquals("bigserial", new PostgresTypeConverter().getDataType("bigint", true).toString()); } @Test public void getColumnType_TinyText() { assertEquals("TEXT", new PostgresTypeConverter().getDataType("TINYTEXT", false).toString()); } @Test public void getColumnType_Text() { assertEquals("TEXT", new PostgresTypeConverter().getDataType("TEXT", false).toString()); } @Test public void getColumnType_MediumText() { assertEquals("TEXT", new PostgresTypeConverter().getDataType("MEDIUMTEXT", false).toString()); } @Test public void getColumnType_LongText() { assertEquals("TEXT", new PostgresTypeConverter().getDataType("LONGTEXT", false).toString()); } @Test public void getColumnType_TinyBlob() { assertEquals("BYTEA", new PostgresTypeConverter().getDataType("TINYBLOB", false).toString()); } @Test public void getColumnType_Blob() { assertEquals("BYTEA", new PostgresTypeConverter().getDataType("BLOB", false).toString()); } @Test public void getColumnType_MediumBlob() { assertEquals("BYTEA", new PostgresTypeConverter().getDataType("MEDIUMBLOB", false).toString()); } @Test public void getColumnType_LongBlob() { assertEquals("BYTEA", new PostgresTypeConverter().getDataType("LONGBLOB", false).toString()); }
### Question: H2TypeConverter extends AbstractTypeConverter { @Override public BlobType getBlobType() { return new BlobType("LONGVARBINARY"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DateTimeType getDateTimeType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); }### Answer: @Test public void getBlobType() { assertEquals("LONGVARBINARY", new H2TypeConverter().getBlobType().toString()); }
### Question: H2TypeConverter extends AbstractTypeConverter { @Override public UUIDType getUUIDType() { return new UUIDType("UUID"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DateTimeType getDateTimeType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); }### Answer: @Test public void getUUIDType() { assertEquals("UUID", new H2TypeConverter().getUUIDType().toString()); }
### Question: H2TypeConverter extends AbstractTypeConverter { @Override public ClobType getClobType() { return new ClobType("LONGVARCHAR"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DateTimeType getDateTimeType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); }### Answer: @Test public void getClobType() { assertEquals("LONGVARCHAR", new H2TypeConverter().getClobType().toString()); }
### Question: H2TypeConverter extends AbstractTypeConverter { @Override public DateTimeType getDateTimeType() { return new DateTimeType("TIMESTAMP"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DateTimeType getDateTimeType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); }### Answer: @Test public void getDateTimeType() { assertEquals("TIMESTAMP", new H2TypeConverter().getDateTimeType().toString()); }
### Question: CacheTypeConverter extends AbstractTypeConverter { @Override public BooleanType getBooleanType() { return new BooleanType.NumericBooleanType(); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override BlobType getBlobType(); @Override BooleanType getBooleanType(); @Override ClobType getClobType(); @Override CurrencyType getCurrencyType(); }### Answer: @Test public void getFalseBooleanValue() { assertEquals("0", new CacheTypeConverter().getBooleanType().getFalseBooleanValue()); } @Test public void getTrueBooleanValue() { assertEquals("1", new CacheTypeConverter().getBooleanType().getTrueBooleanValue()); } @Test public void getBooleanType() { assertEquals("INT", new CacheTypeConverter().getBooleanType().toString()); }
### Question: CacheTypeConverter extends AbstractTypeConverter { @Override public BlobType getBlobType() { return new BlobType("LONGVARBINARY"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override BlobType getBlobType(); @Override BooleanType getBooleanType(); @Override ClobType getClobType(); @Override CurrencyType getCurrencyType(); }### Answer: @Test public void getBlobType() { assertEquals("LONGVARBINARY", new CacheTypeConverter().getBlobType().toString()); }
### Question: CacheTypeConverter extends AbstractTypeConverter { @Override public ClobType getClobType() { return new ClobType("LONGVARCHAR"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override BlobType getBlobType(); @Override BooleanType getBooleanType(); @Override ClobType getClobType(); @Override CurrencyType getCurrencyType(); }### Answer: @Test public void getClobType() { assertEquals("LONGVARCHAR", new CacheTypeConverter().getClobType().toString()); }
### Question: CacheTypeConverter extends AbstractTypeConverter { @Override public CurrencyType getCurrencyType() { return new CurrencyType("MONEY"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override BlobType getBlobType(); @Override BooleanType getBooleanType(); @Override ClobType getClobType(); @Override CurrencyType getCurrencyType(); }### Answer: @Test public void getCurrencyType() { assertEquals("MONEY", new CacheTypeConverter().getCurrencyType().toString()); }
### Question: MySQLTypeConverter extends AbstractTypeConverter { @Override public BooleanType getBooleanType() { return new BooleanType.NumericBooleanType("TINYINT(1)"); } int getPriority(); boolean supports(Database database); @Override BooleanType getBooleanType(); @Override ClobType getClobType(); @Override BlobType getLongBlobType(); @Override NumberType getNumberType(); }### Answer: @Test public void getBooleanType() { assertEquals("TINYINT(1)", new MySQLTypeConverter().getBooleanType().toString()); }
### Question: MySQLTypeConverter extends AbstractTypeConverter { @Override public ClobType getClobType() { return new ClobType("LONGTEXT"); } int getPriority(); boolean supports(Database database); @Override BooleanType getBooleanType(); @Override ClobType getClobType(); @Override BlobType getLongBlobType(); @Override NumberType getNumberType(); }### Answer: @Test public void getClobType() { assertEquals("LONGTEXT", new MySQLTypeConverter().getClobType().toString()); }
### Question: ChangeLogSerializerFactory { public static ChangeLogSerializerFactory getInstance() { if (instance == null) { instance = new ChangeLogSerializerFactory(); } return instance; } private ChangeLogSerializerFactory(); static void reset(); static ChangeLogSerializerFactory getInstance(); Map<String, ChangeLogSerializer> getSerializers(); ChangeLogSerializer getSerializer(String fileNameOrExtension); void register(ChangeLogSerializer changeLogSerializer); void unregister(ChangeLogSerializer changeLogSerializer); }### Answer: @Test public void getInstance() { assertNotNull(ChangeLogSerializerFactory.getInstance()); assertTrue(ChangeLogSerializerFactory.getInstance() == ChangeLogSerializerFactory.getInstance()); }
### Question: ChangeLogSerializerFactory { public void register(ChangeLogSerializer changeLogSerializer) { for (String extension : changeLogSerializer.getValidFileExtensions()) { serializers.put(extension, changeLogSerializer); } } private ChangeLogSerializerFactory(); static void reset(); static ChangeLogSerializerFactory getInstance(); Map<String, ChangeLogSerializer> getSerializers(); ChangeLogSerializer getSerializer(String fileNameOrExtension); void register(ChangeLogSerializer changeLogSerializer); void unregister(ChangeLogSerializer changeLogSerializer); }### Answer: @Test public void register() { ChangeLogSerializerFactory.getInstance().getSerializers().clear(); assertEquals(0, ChangeLogSerializerFactory.getInstance().getSerializers().size()); ChangeLogSerializerFactory.getInstance().register(new MockChangeLogSerializer("mock")); assertEquals(1, ChangeLogSerializerFactory.getInstance().getSerializers().size()); }
### Question: ChangeLogSerializerFactory { public static void reset() { instance = new ChangeLogSerializerFactory(); } private ChangeLogSerializerFactory(); static void reset(); static ChangeLogSerializerFactory getInstance(); Map<String, ChangeLogSerializer> getSerializers(); ChangeLogSerializer getSerializer(String fileNameOrExtension); void register(ChangeLogSerializer changeLogSerializer); void unregister(ChangeLogSerializer changeLogSerializer); }### Answer: @Test public void reset() { ChangeLogSerializerFactory instance1 = ChangeLogSerializerFactory.getInstance(); ChangeLogSerializerFactory.reset(); assertFalse(instance1 == ChangeLogSerializerFactory.getInstance()); }
### Question: ChangeLogSerializerFactory { public Map<String, ChangeLogSerializer> getSerializers() { return serializers; } private ChangeLogSerializerFactory(); static void reset(); static ChangeLogSerializerFactory getInstance(); Map<String, ChangeLogSerializer> getSerializers(); ChangeLogSerializer getSerializer(String fileNameOrExtension); void register(ChangeLogSerializer changeLogSerializer); void unregister(ChangeLogSerializer changeLogSerializer); }### Answer: @Test public void getSerializers() { ChangeLogSerializer serializer = ChangeLogSerializerFactory.getInstance().getSerializer("xml"); assertNotNull(serializer); assertTrue(serializer instanceof XMLChangeLogSerializer); }
### Question: PrintPreview { public int determineHeight() { int height = 0; for (PrintRow row : processRowsBeforePreviewing(printPayload.getRows())) { if (row instanceof TextRow) { PrinterFont font = getFont(((TextRow) row).getPrinterFontId()); height += font.getLineHeight(); } else if (row instanceof ImageRow) { height += ((ImageRow) row).getImage().getHeight() + VERTICAL_MARGIN * 2; } } return height + VERTICAL_MARGIN * 2; } PrintPreview(PrintPayload printPayload, PrinterSettings printerSettings); Bitmap getBitmap(); Bitmap getScaledBitmap(Context context); byte[] getCompressedBitmap(); int determineHeight(); }### Answer: @Test public void canDetermineHeight() { PrintPayload payload = new PrintPayload(); payload.append("Line1"); payload.append("Line2"); payload.append("Line3"); payload.append("Line4"); PrintPreview printPreview = new PrintPreview(payload, getPrinterSettings()); assertThat(printPreview.determineHeight()).isEqualTo(144); }
### Question: PrintPayload implements Jsonable { public TextRow append(String text) { return append(text, null); } PrintPayload(); PrintPayload(String printerId); TextRow append(String text); TextRow append(String text, PrinterFont printerFont); void append(PrintPayload toAppendPayload); void appendEmptyLine(); TextRow appendLineOfChar(int columns, String character); TextRow appendLeftRight(int columns, String left, String right); ImageRow append(Bitmap image); ImageRow append(Bitmap image, boolean scaleToFit); PrintRow[] getRows(); int getCodePage(); void setCodePage(int codePage); String getLanguage(); void setLanguage(String languageCode); void setPrinterId(String printerId); String getPrinterId(); boolean hasPrinterId(); @Override String toJson(); static PrintPayload fromJson(String json); }### Answer: @Test(expected = IllegalArgumentException.class) public void appendNullImageWillThrow() { PrintPayload payload = new PrintPayload(); payload.append((Bitmap) null); } @Test(expected = IllegalArgumentException.class) public void appendNullPayloadWillThrow() { PrintPayload payload = new PrintPayload(); payload.append((PrintPayload) null); } @Test public void canSetFont() { PrintPayload payload = new PrintPayload(); PrinterFont printerFont = new PrinterFont(56, "FontyMcFontFace", 0, 0, false, 0, 0, null); TextRow textRow = payload.append("Hello", printerFont); assertThat(textRow.getPrinterFontId()).isEqualTo(56); } @Test public void canSetImageScale() { PrintPayload payload = new PrintPayload(); Bitmap bmp = getBitmap(); ImageRow imageRow = payload.append(bmp, true); assertThat(imageRow.isScaleToFit()).isTrue(); } @Test(expected = IllegalArgumentException.class) public void appendNullWillThrow() { PrintPayload payload = new PrintPayload(); payload.append((String) null); }
### Question: PrintPreview { public Bitmap getBitmap() { return bitmap; } PrintPreview(PrintPayload printPayload, PrinterSettings printerSettings); Bitmap getBitmap(); Bitmap getScaledBitmap(Context context); byte[] getCompressedBitmap(); int determineHeight(); }### Answer: @Test public void canGetBitmap() { PrintPreview printPreview = setupValidPrintPreview(true); ShadowBitmap bitmap = Shadows.shadowOf(printPreview.getBitmap()); assertThat(bitmap).isNotNull(); assertThat(bitmap.getDescription()).isEqualTo("Bitmap (576 x 48)\n" + "Bitmap (9 x 32)"); assertThat(printPreview.availableWidth).isEqualTo(576); }
### Question: PrintPreview { public Bitmap getScaledBitmap(Context context) { cursor = VERTICAL_MARGIN; DisplayMetrics metrics = context.getResources().getDisplayMetrics(); Bitmap bitmap = getBitmap(); float pxPerMm = metrics.xdpi / 25.4f; int width = bitmap.getWidth(); float scale = (printerSettings.getPrintableWidth() * pxPerMm) / (float) width; return Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * scale), (int) (bitmap.getHeight() * scale), true); } PrintPreview(PrintPayload printPayload, PrinterSettings printerSettings); Bitmap getBitmap(); Bitmap getScaledBitmap(Context context); byte[] getCompressedBitmap(); int determineHeight(); }### Answer: @Test public void canGetScaledBitmap() { PrintPreview printPreview = setupValidPrintPreview(true); ShadowBitmap bitmap = Shadows.shadowOf(printPreview.getScaledBitmap(RuntimeEnvironment.application)); assertThat(bitmap).isNotNull(); assertThat(bitmap.getDescription()).isEqualTo("Bitmap (576 x 48)\n" + "Bitmap (9 x 32) scaled to 708 x 59 with filter true"); } @Test public void handlesNoFonts() { PrintPreview printPreview = setupValidPrintPreview(false); Bitmap bitmap = printPreview.getScaledBitmap(RuntimeEnvironment.application); assertThat(bitmap).isNotNull(); }
### Question: PrintPreview { protected List<TextRow> splitLongTextRow(TextRow textRow) { List<TextRow> result = new ArrayList<>(); PrinterFont font = getFont(textRow.getPrinterFontId()); String line = textRow.getText(); String remaining = ""; while (line.length() > 0) { if (line.length() > font.getNumColumns()) { remaining = line.charAt(line.length() - 1) + remaining; line = line.substring(0, line.length() - 1); } else { TextRow newRow = new TextRow(line) .align(textRow.getAlignmentStyle()) .fontStyle(textRow.getFontStyle()) .underline(textRow.getUnderlineStyle()) .setFont(font); result.add(newRow); line = remaining; remaining = ""; } } return result; } PrintPreview(PrintPayload printPayload, PrinterSettings printerSettings); Bitmap getBitmap(); Bitmap getScaledBitmap(Context context); byte[] getCompressedBitmap(); int determineHeight(); }### Answer: @Test public void willSplitLongLineCorrectly() { PrintPayload payload = new PrintPayload(); TextRow row = payload.append("this is a very long line of text that should be split across multiple lines"); PrintPreview printPreview = new PrintPreview(payload, getPrinterSettings()); List<TextRow> rows = printPreview.splitLongTextRow(row); assertThat(rows).hasSize(2); assertThat(rows.get(0).getText()).isEqualTo("this is a very long line of text that should be "); assertThat(rows.get(1).getText()).isEqualTo("split across multiple lines"); assertThat(rows.get(0).getText().length()).isLessThanOrEqualTo(FONT_A.getNumColumns()); assertThat(rows.get(1).getText().length()).isLessThanOrEqualTo(FONT_A.getNumColumns()); }
### Question: PrintPayload implements Jsonable { public String getPrinterId() { return printerId; } PrintPayload(); PrintPayload(String printerId); TextRow append(String text); TextRow append(String text, PrinterFont printerFont); void append(PrintPayload toAppendPayload); void appendEmptyLine(); TextRow appendLineOfChar(int columns, String character); TextRow appendLeftRight(int columns, String left, String right); ImageRow append(Bitmap image); ImageRow append(Bitmap image, boolean scaleToFit); PrintRow[] getRows(); int getCodePage(); void setCodePage(int codePage); String getLanguage(); void setLanguage(String languageCode); void setPrinterId(String printerId); String getPrinterId(); boolean hasPrinterId(); @Override String toJson(); static PrintPayload fromJson(String json); }### Answer: @Test public void willSetPrinterId() { PrintPayload payload = new PrintPayload("17676767"); assertThat(payload.getPrinterId()).isEqualTo("17676767"); }
### Question: PrintPayload implements Jsonable { public TextRow appendLeftRight(int columns, String left, String right) { String space = getSpaces(columns - left.length() - right.length()); return append(left + space + right); } PrintPayload(); PrintPayload(String printerId); TextRow append(String text); TextRow append(String text, PrinterFont printerFont); void append(PrintPayload toAppendPayload); void appendEmptyLine(); TextRow appendLineOfChar(int columns, String character); TextRow appendLeftRight(int columns, String left, String right); ImageRow append(Bitmap image); ImageRow append(Bitmap image, boolean scaleToFit); PrintRow[] getRows(); int getCodePage(); void setCodePage(int codePage); String getLanguage(); void setLanguage(String languageCode); void setPrinterId(String printerId); String getPrinterId(); boolean hasPrinterId(); @Override String toJson(); static PrintPayload fromJson(String json); }### Answer: @Test public void checkAlignLeftRight() { PrintPayload payload = new PrintPayload(); TextRow row = payload.appendLeftRight(30, "Left", "Right"); assertThat(row.getText()).isEqualTo("Left Right"); }
### Question: PrintPayload implements Jsonable { public TextRow appendLineOfChar(int columns, String character) { String line = character; while (line.length() < columns) { line += character; } return append(line); } PrintPayload(); PrintPayload(String printerId); TextRow append(String text); TextRow append(String text, PrinterFont printerFont); void append(PrintPayload toAppendPayload); void appendEmptyLine(); TextRow appendLineOfChar(int columns, String character); TextRow appendLeftRight(int columns, String left, String right); ImageRow append(Bitmap image); ImageRow append(Bitmap image, boolean scaleToFit); PrintRow[] getRows(); int getCodePage(); void setCodePage(int codePage); String getLanguage(); void setLanguage(String languageCode); void setPrinterId(String printerId); String getPrinterId(); boolean hasPrinterId(); @Override String toJson(); static PrintPayload fromJson(String json); }### Answer: @Test public void checkAppendLineOfChar() { PrintPayload payload = new PrintPayload(); TextRow row = payload.appendLineOfChar(30, "="); assertThat(row.getText()).isEqualTo("=============================="); }
### Question: MessengerChannelServer extends BaseChannelServer { @Override public boolean send(MessageException error) { Bundle b = new Bundle(); b.putString(KEY_DATA_RESPONSE, error.toJson()); Message message = createMessage(b, MESSAGE_ERROR); return send(message); } MessengerChannelServer(String serviceComponentName, String clientPackageName); @Override void handleMessage(Message msg); @Override void disposeClient(); @Override boolean send(MessageException error); @Override String getClientPackageName(); @Override boolean send(String senddata); @Override boolean sendEndStream(); }### Answer: @Test public void willSendMessage() throws RemoteException { setupReplyTo(); String message = "hellooooooo"; boolean sent = messengerChannelServer.send(message); assertThat(sent).isTrue(); verifySentMessage(MESSAGE_RESPONSE, message); } @Test public void willSendExceptionMessage() throws RemoteException { setupReplyTo(); MessageException message = new MessageException("bleep", "bloop"); boolean sent = messengerChannelServer.send(message); assertThat(sent).isTrue(); verifySentMessage(MESSAGE_ERROR, message.toJson()); }
### Question: ObservableWebSocketClient extends ObservableMessengerClient { @Override public Observable<String> sendMessage(final String message) { if (!super.isConnected()) { return connectAndSendMessage(message); } else { if (responseEmitter == null || responseEmitter.hasComplete()) { responseEmitter = PublishSubject.create(); } if (okWebSocketClient != null && okWebSocketClient.isConnected()) { okWebSocketClient.updateCallbackEmitter(responseEmitter); okWebSocketClient.sendMessage(message); } else { super.sendMessage(message); } return responseEmitter; } } ObservableWebSocketClient(Context context, ComponentName serviceComponentName); @Override Completable connect(); @Override boolean isConnected(); @Override Observable<String> sendMessage(final String message); @Override void closeConnection(); }### Answer: @Test public void willSendMessageViaWebsocket() throws RemoteException { setupMockBoundMessengerService(); createObservableSendDataAndSubscribe("hellooooo"); sendConnectionParamsFromServer(); setWebSocketConnectedState(true); observableWebSocketClient.sendMessage("This is ground control to Major Tom").test(); verify(observableWebSocketClient.okWebSocketClient).sendMessage("This is ground control to Major Tom"); } @Test public void willFallbackToMessengerIfNotConnected() throws RemoteException { setupMockBoundMessengerService(); createObservableSendDataAndSubscribe("connect with me"); sendConnectionParamsFromServer(); setWebSocketConnectedState(false); observableWebSocketClient.sendMessage("Stop messaging me").test(); verify(observableWebSocketClient.okWebSocketClient, times(0)).sendMessage(anyString()); verifyMessagesSentToServerViaMessenger(2); }
### Question: ObservableWebSocketClient extends ObservableMessengerClient { @Override public void closeConnection() { if (okWebSocketClient != null && okWebSocketClient.isConnected()) { okWebSocketClient.close(); } super.closeConnection(); } ObservableWebSocketClient(Context context, ComponentName serviceComponentName); @Override Completable connect(); @Override boolean isConnected(); @Override Observable<String> sendMessage(final String message); @Override void closeConnection(); }### Answer: @Test public void willCloseWebSocket() throws RemoteException { setupMockBoundMessengerService(); createObservableSendDataAndSubscribe("lets connect"); sendConnectionParamsFromServer(); setWebSocketConnectedState(true); observableWebSocketClient.closeConnection(); verify(observableWebSocketClient.okWebSocketClient).close(); }
### Question: MessengerChannelServer extends BaseChannelServer { @Override public boolean sendEndStream() { Message message = createMessage(null, MESSAGE_END_STREAM); closeClient(); return send(message); } MessengerChannelServer(String serviceComponentName, String clientPackageName); @Override void handleMessage(Message msg); @Override void disposeClient(); @Override boolean send(MessageException error); @Override String getClientPackageName(); @Override boolean send(String senddata); @Override boolean sendEndStream(); }### Answer: @Test public void willSendEndMessage() throws RemoteException { setupReplyTo(); boolean sent = messengerChannelServer.sendEndStream(); assertThat(sent).isTrue(); verifySentMessage(MESSAGE_END_STREAM, null); }
### Question: WebSocketChannelServer extends MessengerChannelServer { private void startServer() { setupSendQueue(); setupWebServer(); } WebSocketChannelServer(Context context, String serviceComponentName, String clientPackageName); @Override void handleMessage(Message msg); @Override boolean send(final String message); @Override boolean sendEndStream(); static final String CONNECT_PLEASE; static final String CLOSE_MESSAGE; }### Answer: @Test public void willStartServerOnFirstMessage() { setupWebserverConnectionNever(); sendFirstMessage(); verify(webSocketServer).startServer(); }
### Question: WebSocketChannelServer extends MessengerChannelServer { @Override public boolean sendEndStream() { disconnectedWithEndStreamCall = true; sendMessageQueue.onNext(CLOSE_MESSAGE); Observable.timer(WAIT_FOR_CLOSE_TIMEOUT, TimeUnit.SECONDS, getSendScheduler()) .subscribe(new Consumer<Long>() { @Override public void accept(Long aLong) throws Exception { if (!sendMessageQueue.hasComplete()) { sendMessageQueue.onComplete(); } } }); return true; } WebSocketChannelServer(Context context, String serviceComponentName, String clientPackageName); @Override void handleMessage(Message msg); @Override boolean send(final String message); @Override boolean sendEndStream(); static final String CONNECT_PLEASE; static final String CLOSE_MESSAGE; }### Answer: @Test public void willDisconnectOnEndStream() { setupWebserverConnection(); sendFirstMessage(); webSocketChannelServer.sendEndStream(); verify(webSocketConnection).disconnect(); }
### Question: WebSocketChannelServer extends MessengerChannelServer { @Override public boolean send(final String message) { if (webSocketConnection != null && webSocketConnection.isConnected()) { sendMessageQueue.onNext(message); return true; } else { return super.send(message); } } WebSocketChannelServer(Context context, String serviceComponentName, String clientPackageName); @Override void handleMessage(Message msg); @Override boolean send(final String message); @Override boolean sendEndStream(); static final String CONNECT_PLEASE; static final String CLOSE_MESSAGE; }### Answer: @Test public void canSendMessageToClient() throws IOException { setupWebserverConnection(); sendFirstMessage(); String msg = "Hello client, are you are ok?"; webSocketChannelServer.send(msg); verify(webSocketConnection).send(msg); }
### Question: AbstractChannelService extends Service { @Override @NonNull public final IBinder onBind(Intent intent) { String clientId = getClientIdFromIntent(intent); String channelType = getChannelTypeFromIntent(intent); String clientPackageName = getClientPackageNameFromIntent(intent); Log.d(TAG, String.format("Bound to client %s channel type: %s", clientId, channelType)); return createServiceIncomingHandler(clientId, channelType, clientPackageName); } @Override @NonNull final IBinder onBind(Intent intent); @NonNull IBinder createServiceIncomingHandler(String clientId, String channelType, String clientPackageName); void setStopSelfOnEndOfStream(boolean stopSelfOnEndOfStream); @Override boolean onUnbind(Intent intent); @Nullable ChannelServer getChannelServerForId(String clientMessageId); }### Answer: @Test public void willSetupChannelOnFirstMessageIntent() { Intent intent = new Intent(); testAbstractChannelService.onBind(intent); assertThat(testAbstractChannelService.incomingHandler).isNotNull(); testAbstractChannelService.incomingHandler.handleMessage(setupEmptyMessage()); assertThat(testAbstractChannelService.channelServerMap).hasSize(1); assertThat(testAbstractChannelService.channelType).isEqualTo(CHANNEL_MESSENGER); }
### Question: ObservableMessengerClient extends BaseChannelClient implements ChannelClient { public void closeConnection() { if (messengerConnection != null) { Log.d(TAG, "Closing connection with id: " + messengerConnection.getClientId()); try { context.unbindService(messengerConnection); } catch (Throwable t) { } messengerConnection = null; if (responseEmitter != null) { responseEmitter.onComplete(); responseEmitter = null; } } } ObservableMessengerClient(Context context, ComponentName serviceComponentName); ObservableMessengerClient(Context context, ComponentName serviceComponentName, OnHandleMessageCallback onHandleMessageCallback); boolean isConnected(); Completable connect(); Observable<String> sendMessage(final String requestData); void closeConnection(); }### Answer: @Test public void checkCloseConnectionWillUnbindService() throws RemoteException { setupMockBoundMessengerService(); TestObserver<String> obs = createObservableSendDataAndSubscribe(new DataObject()); DataObject response = new DataObject(); sendReply(response); observableMessengerClient.closeConnection(); obs.awaitDone(2000, TimeUnit.MILLISECONDS).assertNoErrors().assertComplete().assertValue(response.toJson()); verifyServiceIsUnbound(); } @Test public void checkWillUseDifferentClientIdsForEachConnection() throws Exception { setupMockBoundMessengerService(); DataObject msg = new DataObject(); createObservableSendDataAndSubscribe(msg); Bundle firstMessage = getReceivedBundle(0); String firstClientId = firstMessage.getString(KEY_CLIENT_ID); observableMessengerClient.closeConnection(); msg = new DataObject(); createObservableSendDataAndSubscribe(msg); Bundle secondMessage = getReceivedBundle(1); String secondClientId = secondMessage.getString(KEY_CLIENT_ID); assertThat(firstClientId).isNotEqualTo(secondClientId); }
### Question: ObservableWebSocketClient extends ObservableMessengerClient { @NonNull protected Intent getServiceIntent(String clientId) { Intent intent = super.getServiceIntent(clientId); intent.putExtra(KEY_CHANNEL_TYPE, CHANNEL_WEBSOCKET); return intent; } ObservableWebSocketClient(Context context, ComponentName serviceComponentName); @Override Completable connect(); @Override boolean isConnected(); @Override Observable<String> sendMessage(final String message); @Override void closeConnection(); }### Answer: @Test public void checkBindIntentWillContainCorrectChannel() { Intent bindIntent = observableWebSocketClient.getServiceIntent("7878"); assertThat(bindIntent).isNotNull(); assertThat(bindIntent.hasExtra(KEY_CHANNEL_TYPE)).isTrue(); assertThat(bindIntent.getStringExtra(KEY_CHANNEL_TYPE)).isEqualTo(CHANNEL_WEBSOCKET); assertThat(bindIntent.hasExtra(KEY_CLIENT_ID)).isTrue(); assertThat(bindIntent.getStringExtra(KEY_CLIENT_ID)).isEqualTo("7878"); }
### Question: BaseHumanName extends BaseResource { public String getDisplayName(){ List<String> names = Arrays.asList(getPrefix(), getGivenName(), getFamilyName(), getSuffix()); return names.stream().filter(Objects::nonNull).collect(Collectors.joining(" ")); } HumanName.NameUse getNameUse(); void setNameUse(HumanName.NameUse nameUse); String getPrefix(); void setPrefix(String prefix); String getGivenName(); void setGivenName(String givenName); String getFamilyName(); void setFamilyName(String familyName); String getSuffix(); void setSuffix(String suffix); String getDisplayName(); @Override Long getId(); }### Answer: @Test public void testDisplayName_Empty(){ BaseHumanName name = new BaseHumanName(); String displayName = name.getDisplayName(); assertThat(displayName, not(nullValue())); assertThat(displayName, equalTo("")); }
### Question: ValidateUtils { public static boolean validateUrl(String urlStr) { Matcher matcher = VALID_URL_REGEX .matcher(urlStr); return matcher.find(); } private ValidateUtils(); static boolean validateEmail(String emailStr); static boolean validateUrl(String urlStr); }### Answer: @Test public void testValidateUrl() { assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("http: assertTrue(ValidateUtils.validateUrl("ftp: assertTrue(ValidateUtils.validateUrl("file: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertTrue(ValidateUtils.validateUrl("https: assertFalse(ValidateUtils.validateUrl("")); assertFalse(ValidateUtils.validateUrl("ht: assertFalse(ValidateUtils.validateUrl("http/www.test.com")); assertFalse(ValidateUtils.validateUrl("http: assertFalse(ValidateUtils.validateUrl("http: assertFalse(ValidateUtils.validateUrl("http: assertFalse(ValidateUtils.validateUrl("http56: assertFalse(ValidateUtils.validateUrl("http assertFalse(ValidateUtils.validateUrl("http assertFalse(ValidateUtils.validateUrl("httpstest.com")); assertFalse(ValidateUtils.validateUrl("test")); assertFalse(ValidateUtils.validateUrl("test.co.in")); assertFalse(ValidateUtils.validateUrl(".com")); }
### Question: ValidateUtils { public static boolean validateEmail(String emailStr) { Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(emailStr); return matcher.find(); } private ValidateUtils(); static boolean validateEmail(String emailStr); static boolean validateUrl(String urlStr); }### Answer: @Test public void testValidateEmail() { assertTrue(ValidateUtils.validateEmail("abcd@efg.com")); assertTrue(ValidateUtils.validateEmail("ABCD@efg.com")); assertTrue(ValidateUtils.validateEmail("abc898d@efg.com")); assertTrue(ValidateUtils.validateEmail("abcd@efg.COM")); assertTrue(ValidateUtils.validateEmail("abc@EFG.co")); assertTrue(ValidateUtils.validateEmail("abc@efg.co.in")); assertTrue(ValidateUtils.validateEmail("abcd@efg.com")); assertTrue(ValidateUtils.validateEmail("abcd@efg.in")); assertTrue(ValidateUtils.validateEmail("abcd@efg.bhj")); assertTrue(ValidateUtils.validateEmail("abcd@ef56g.bhj")); assertTrue(ValidateUtils.validateEmail("abc+-%d@abc.com")); assertFalse(ValidateUtils.validateEmail("")); assertFalse(ValidateUtils.validateEmail("abcdefg.com")); assertFalse(ValidateUtils.validateEmail("abc@.com")); assertFalse(ValidateUtils.validateEmail("ab*-c@defg.com")); assertFalse(ValidateUtils.validateEmail("abcd")); assertFalse(ValidateUtils.validateEmail("abc@abc")); assertFalse(ValidateUtils.validateEmail("abc@@hjg.com")); assertFalse(ValidateUtils.validateEmail("abc@abc.co++-")); assertFalse(ValidateUtils.validateEmail("abc@ab/*c")); assertFalse(ValidateUtils.validateEmail("abc@ab/*c.com")); assertFalse(ValidateUtils.validateEmail("abcd@efg.co565m")); assertFalse(ValidateUtils.validateEmail("abcd@ghs.l")); assertFalse(ValidateUtils.validateEmail("abcd@efg.cojjjhjhjhjhjhjhjhm")); }
### Question: AuthRepository { @NonNull public FirebaseAuthLiveData getFirebaseAuthLiveData() { return firebaseAuthLiveData; } @Inject AuthRepository(FirebaseAuthLiveData firebaseAuthLiveData); @NonNull FirebaseAuthLiveData getFirebaseAuthLiveData(); }### Answer: @Test public void shouldReturnFireBaseLiveData() { FirebaseAuthLiveData expectedData = authRepository.getFirebaseAuthLiveData(); assertThat(expectedData, equalTo(firebaseAuthLiveData)); }
### Question: ProfileRepository { public void setUser(User user) { databaseReference.setValue(user); } @Inject ProfileRepository(DatabaseReference databaseReference, FirebaseAuth firebaseAuth); @NonNull LiveData<DataSnapshot> getUser(); void setUser(User user); void setField(UserFieldType userFieldType, String profileField); @VisibleForTesting public FirebaseDatabaseLiveData firebaseDatabaseLiveData; public DatabaseReference databaseReference; }### Answer: @Test public void shouldSetUser() { profileRepository.setUser(MOCK_USER); Mockito.verify(databaseReference).setValue(MOCK_USER); }
### Question: ProfileRepository { public void setField(UserFieldType userFieldType, String profileField) { databaseReference.child(userFieldType.key).setValue(profileField); } @Inject ProfileRepository(DatabaseReference databaseReference, FirebaseAuth firebaseAuth); @NonNull LiveData<DataSnapshot> getUser(); void setUser(User user); void setField(UserFieldType userFieldType, String profileField); @VisibleForTesting public FirebaseDatabaseLiveData firebaseDatabaseLiveData; public DatabaseReference databaseReference; }### Answer: @Test public void shouldSetField() { Mockito.when(databaseReference.child(UserFieldType.USERNAME.key)) .thenReturn(databaseReference); profileRepository.setField(UserFieldType.USERNAME, "test_username"); Mockito.verify(databaseReference).setValue("test_username"); }
### Question: ProfileRepository { @NonNull public LiveData<DataSnapshot> getUser() { return firebaseDatabaseLiveData; } @Inject ProfileRepository(DatabaseReference databaseReference, FirebaseAuth firebaseAuth); @NonNull LiveData<DataSnapshot> getUser(); void setUser(User user); void setField(UserFieldType userFieldType, String profileField); @VisibleForTesting public FirebaseDatabaseLiveData firebaseDatabaseLiveData; public DatabaseReference databaseReference; }### Answer: @Test public void shouldReturnUserLiveData() { LiveData<DataSnapshot> userLiveData = profileRepository.getUser(); Assert.assertSame(userLiveData, profileRepository.firebaseDatabaseLiveData); }
### Question: CodingCalendarViewModel extends ViewModel { protected LiveData<Resource<List<Contest>>> loadContests(boolean reload) { if (reload || repoListRateLimit.shouldFetch(CONTEST_VIEW_MODEL)) { contests = codingCalendarRepository.fetchContests(reload); repoListRateLimit.refreshRateLimiter(CONTEST_VIEW_MODEL); } return contests; } @Inject CodingCalendarViewModel(CodingCalendarRepository codingCalendarRepository, RateLimiter<String> repoListRateLimit); void openContestDetails(Long id); }### Answer: @Test public void shouldLoadContests_when_reloadFalse_and_rateLimitFalse() { Mockito.when(repoListRateLimit.shouldFetch(CodingCalendarViewModel.CONTEST_VIEW_MODEL)) .thenReturn(false); codingCalendarViewModel.loadContests(false); Mockito.verify(codingCalendarRepository, Mockito.never()).fetchContests(Mockito.anyBoolean()); Mockito.verify(repoListRateLimit, Mockito.never()).refreshRateLimiter(CodingCalendarViewModel.CONTEST_VIEW_MODEL); } @Test public void shouldLoadContests_when_reloadTrue_and_rateLimitFalse() { codingCalendarViewModel.loadContests(true); Mockito.verify(codingCalendarRepository).fetchContests(true); Mockito.verify(repoListRateLimit).refreshRateLimiter(CodingCalendarViewModel.CONTEST_VIEW_MODEL); } @Test public void shouldLoadContests_when_reloadFalse_and_rateLimitTrue() { Mockito.when(repoListRateLimit.shouldFetch(CodingCalendarViewModel.CONTEST_VIEW_MODEL)) .thenReturn(true); codingCalendarViewModel.loadContests(false); Mockito.verify(codingCalendarRepository).fetchContests(false); Mockito.verify(repoListRateLimit).refreshRateLimiter(CodingCalendarViewModel.CONTEST_VIEW_MODEL); }
### Question: MetricSampleAggregator extends LongGenerationed { public Long earliestWindow() { return _rawMetrics.isEmpty() ? null : _oldestWindowIndex * _windowMs; } MetricSampleAggregator(int numWindows, long windowMs, byte minSamplesPerWindow, int completenessCacheSize, MetricDef metricDef); boolean addSample(MetricSample<G, E> sample); MetricSampleAggregationResult<G, E> aggregate(long from, long to, AggregationOptions<G, E> options); Map<E, ValuesAndExtrapolations> peekCurrentWindow(); MetricSampleCompleteness<G, E> completeness(long from, long to, AggregationOptions<G, E> options); List<Long> availableWindows(); int numAvailableWindows(); int numAvailableWindows(long from, long to); List<Long> allWindows(); Long earliestWindow(); int numSamples(); void retainEntities(Set<E> entities); void removeEntities(Set<E> entities); void retainEntityGroup(Set<G> entityGroups); void removeEntityGroup(Set<G> entityGroups); void clear(); long monitoringPeriodMs(); }### Answer: @Test public void testEarliestWindow() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); assertNull(aggregator.earliestWindow()); CruiseControlUnitTestUtils.populateSampleAggregator(NUM_WINDOWS, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY1, 0, WINDOW_MS, _metricDef); assertEquals(WINDOW_MS, aggregator.earliestWindow().longValue()); CruiseControlUnitTestUtils.populateSampleAggregator(2, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY1, NUM_WINDOWS, WINDOW_MS, _metricDef); assertEquals(2 * WINDOW_MS, aggregator.earliestWindow().longValue()); }
### Question: MetricSampleAggregator extends LongGenerationed { public Map<E, ValuesAndExtrapolations> peekCurrentWindow() { _windowRollingLock.lock(); try { Map<E, ValuesAndExtrapolations> result = new HashMap<>(); _rawMetrics.forEach((entity, rawMetric) -> { ValuesAndExtrapolations vae = rawMetric.peekCurrentWindow(_currentWindowIndex, _metricDef); SortedSet<Long> currentWindows = new TreeSet<>(Collections.singleton(_currentWindowIndex)); vae.setWindows(toWindows(currentWindows)); result.put(entity, vae); }); return result; } finally { _windowRollingLock.unlock(); } } MetricSampleAggregator(int numWindows, long windowMs, byte minSamplesPerWindow, int completenessCacheSize, MetricDef metricDef); boolean addSample(MetricSample<G, E> sample); MetricSampleAggregationResult<G, E> aggregate(long from, long to, AggregationOptions<G, E> options); Map<E, ValuesAndExtrapolations> peekCurrentWindow(); MetricSampleCompleteness<G, E> completeness(long from, long to, AggregationOptions<G, E> options); List<Long> availableWindows(); int numAvailableWindows(); int numAvailableWindows(long from, long to); List<Long> allWindows(); Long earliestWindow(); int numSamples(); void retainEntities(Set<E> entities); void removeEntities(Set<E> entities); void retainEntityGroup(Set<G> entityGroups); void removeEntityGroup(Set<G> entityGroups); void clear(); long monitoringPeriodMs(); }### Answer: @Test public void testPeekCurrentWindow() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); populateSampleAggregator(2, 1, aggregator, ENTITY1); populateSampleAggregator(2, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY2); CruiseControlUnitTestUtils.populateSampleAggregator(1, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY3, 0, WINDOW_MS, _metricDef); Map<IntegerEntity, ValuesAndExtrapolations> currentWindowMetrics = aggregator.peekCurrentWindow(); assertEquals(FORCED_INSUFFICIENT, currentWindowMetrics.get(ENTITY1).extrapolations().get(0)); assertTrue(currentWindowMetrics.get(ENTITY2).extrapolations().isEmpty()); assertEquals(NO_VALID_EXTRAPOLATION, currentWindowMetrics.get(ENTITY3).extrapolations().get(0)); }
### Question: AggregatedMetricValues { public void add(short metricId, MetricValues metricValuesToAdd) { if (metricValuesToAdd == null) { throw new IllegalArgumentException("The metric values to be added cannot be null"); } if (!_metricValues.isEmpty() && metricValuesToAdd.length() != length()) { throw new IllegalArgumentException("The existing metric length is " + length() + " which is different from the" + " metric length of " + metricValuesToAdd.length() + " that is being added."); } MetricValues metricValues = _metricValues.computeIfAbsent(metricId, id -> new MetricValues(metricValuesToAdd.length())); metricValues.add(metricValuesToAdd); } AggregatedMetricValues(); AggregatedMetricValues(Map<Short, MetricValues> valuesByMetricId); MetricValues valuesFor(short metricId); AggregatedMetricValues valuesFor(Collection<Short> metricIds, boolean shareValueArray); MetricValues valuesForGroup(String group, MetricDef metricDef, boolean shareValueArray); int length(); boolean isEmpty(); Set<Short> metricIds(); void add(short metricId, MetricValues metricValuesToAdd); void add(AggregatedMetricValues other); void subtract(AggregatedMetricValues other); void clear(); void writeTo(OutputStream out); @Override String toString(); }### Answer: @Test public void testAdd() { Map<Short, MetricValues> valuesByMetricId = getValuesByMetricId(); AggregatedMetricValues aggregatedMetricValues = new AggregatedMetricValues(valuesByMetricId); aggregatedMetricValues.add(aggregatedMetricValues); for (Map.Entry<Short, MetricValues> entry : valuesByMetricId.entrySet()) { MetricValues values = entry.getValue(); for (int j = 0; j < 10; j++) { assertEquals(2 * j, values.get(j), 0.01); } } }
### Question: AggregatedMetricValues { public void subtract(AggregatedMetricValues other) { for (Map.Entry<Short, MetricValues> entry : other.metricValues().entrySet()) { short metricId = entry.getKey(); MetricValues otherValuesForMetric = entry.getValue(); MetricValues valuesForMetric = valuesFor(metricId); if (valuesForMetric == null) { throw new IllegalStateException("Cannot subtract a values from a non-existing MetricValues"); } if (valuesForMetric.length() != otherValuesForMetric.length()) { throw new IllegalStateException("The two values arrays have different lengths " + valuesForMetric.length() + " and " + otherValuesForMetric.length()); } valuesForMetric.subtract(otherValuesForMetric); } } AggregatedMetricValues(); AggregatedMetricValues(Map<Short, MetricValues> valuesByMetricId); MetricValues valuesFor(short metricId); AggregatedMetricValues valuesFor(Collection<Short> metricIds, boolean shareValueArray); MetricValues valuesForGroup(String group, MetricDef metricDef, boolean shareValueArray); int length(); boolean isEmpty(); Set<Short> metricIds(); void add(short metricId, MetricValues metricValuesToAdd); void add(AggregatedMetricValues other); void subtract(AggregatedMetricValues other); void clear(); void writeTo(OutputStream out); @Override String toString(); }### Answer: @Test public void testDeduct() { Map<Short, MetricValues> valuesByMetricId = getValuesByMetricId(); AggregatedMetricValues aggregatedMetricValues = new AggregatedMetricValues(valuesByMetricId); aggregatedMetricValues.subtract(aggregatedMetricValues); for (Map.Entry<Short, MetricValues> entry : valuesByMetricId.entrySet()) { MetricValues values = entry.getValue(); for (int j = 0; j < 10; j++) { assertEquals(0, values.get(j), 0.01); } } }
### Question: RawMetricValues extends WindowIndexedArrays { public synchronized ValuesAndExtrapolations aggregate(SortedSet<Long> windowIndices, MetricDef metricDef) { return aggregate(windowIndices, metricDef, true); } RawMetricValues(int numWindowsToKeep, byte minSamplesPerWindow, int numMetricTypesInSample); synchronized void addSample(MetricSample<?, ?> sample, long windowIndex, MetricDef metricDef); synchronized void updateOldestWindowIndex(long newOldestWindowIndex); synchronized boolean isValid(int maxAllowedWindowsWithExtrapolation); synchronized int numWindowsWithExtrapolation(); synchronized boolean isValidAtWindowIndex(long windowIndex); synchronized boolean isExtrapolatedAtWindowIndex(long windowIndex); synchronized byte sampleCountsAtWindowIndex(long windowIndex); synchronized void sanityCheckWindowIndex(long windowIndex); synchronized void sanityCheckWindowRangeReset(long startingWindowIndex, int numWindowIndicesToReset); synchronized int resetWindowIndices(long startingWindowIndex, int numWindowIndicesToReset); synchronized ValuesAndExtrapolations aggregate(SortedSet<Long> windowIndices, MetricDef metricDef); synchronized ValuesAndExtrapolations peekCurrentWindow(long currentWindowIndex, MetricDef metricDef); synchronized int numSamples(); }### Answer: @Test public void testExtrapolationAdjacentAvgAtMiddle() { RawMetricValues rawValues = new RawMetricValues(NUM_WINDOWS_TO_KEEP, MIN_SAMPLES_PER_WINDOW, NUM_RAW_METRICS); prepareWindowMissingAtIndex(rawValues, 1); ValuesAndExtrapolations valuesAndExtrapolations = aggregate(rawValues, allWindowIndices(0)); assertEquals(11.5, valuesAndExtrapolations.metricValues().valuesFor((short) 0).get(1), EPSILON); assertEquals(13.0, valuesAndExtrapolations.metricValues().valuesFor((short) 1).get(1), EPSILON); assertEquals(13.0, valuesAndExtrapolations.metricValues().valuesFor((short) 2).get(1), EPSILON); assertEquals(1, valuesAndExtrapolations.extrapolations().size()); Assert.assertEquals(Extrapolation.AVG_ADJACENT, valuesAndExtrapolations.extrapolations().get(1)); } @Test public void testExtrapolationAdjacentAvgAtLeftEdge() { RawMetricValues rawValues = new RawMetricValues(NUM_WINDOWS_TO_KEEP, MIN_SAMPLES_PER_WINDOW, NUM_RAW_METRICS); prepareWindowMissingAtIndex(rawValues, 0); ValuesAndExtrapolations valuesAndExtrapolations = aggregate(rawValues, allWindowIndices(0)); assertEquals(0, valuesAndExtrapolations.metricValues().valuesFor((short) 0).get(0), EPSILON); assertEquals(0, valuesAndExtrapolations.metricValues().valuesFor((short) 1).get(0), EPSILON); assertEquals(0, valuesAndExtrapolations.metricValues().valuesFor((short) 2).get(0), EPSILON); assertEquals(1, valuesAndExtrapolations.extrapolations().size()); Assert.assertEquals(Extrapolation.NO_VALID_EXTRAPOLATION, valuesAndExtrapolations.extrapolations().get(0)); }
### Question: RawMetricValues extends WindowIndexedArrays { public synchronized boolean isValid(int maxAllowedWindowsWithExtrapolation) { int currentArrayIndex = arrayIndex(currentWindowIndex()); int numValidIndicesAdjustment = _validity.get(currentArrayIndex) ? 1 : 0; boolean allIndicesValid = _validity.cardinality() - numValidIndicesAdjustment == _counts.length - 1; return allIndicesValid && numWindowsWithExtrapolation() <= maxAllowedWindowsWithExtrapolation; } RawMetricValues(int numWindowsToKeep, byte minSamplesPerWindow, int numMetricTypesInSample); synchronized void addSample(MetricSample<?, ?> sample, long windowIndex, MetricDef metricDef); synchronized void updateOldestWindowIndex(long newOldestWindowIndex); synchronized boolean isValid(int maxAllowedWindowsWithExtrapolation); synchronized int numWindowsWithExtrapolation(); synchronized boolean isValidAtWindowIndex(long windowIndex); synchronized boolean isExtrapolatedAtWindowIndex(long windowIndex); synchronized byte sampleCountsAtWindowIndex(long windowIndex); synchronized void sanityCheckWindowIndex(long windowIndex); synchronized void sanityCheckWindowRangeReset(long startingWindowIndex, int numWindowIndicesToReset); synchronized int resetWindowIndices(long startingWindowIndex, int numWindowIndicesToReset); synchronized ValuesAndExtrapolations aggregate(SortedSet<Long> windowIndices, MetricDef metricDef); synchronized ValuesAndExtrapolations peekCurrentWindow(long currentWindowIndex, MetricDef metricDef); synchronized int numSamples(); }### Answer: @Test public void testIsValid() { RawMetricValues rawValues = new RawMetricValues(NUM_WINDOWS_TO_KEEP, MIN_SAMPLES_PER_WINDOW, NUM_RAW_METRICS); rawValues.updateOldestWindowIndex(0); MetricSample<String, IntegerEntity> m = getMetricSample(10, 10, 10); for (int i = 0; i < NUM_WINDOWS_TO_KEEP; i++) { for (int j = 0; j < MIN_SAMPLES_PER_WINDOW - 1; j++) { addSample(rawValues, m, i); } } assertTrue(rawValues.isValid(5)); assertFalse(rawValues.isValid(4)); addSample(rawValues, m, 0); assertTrue(rawValues.isValid(4)); }
### Question: ReplicationThrottleHelper { static String removeReplicasFromConfig(String throttleConfig, Set<String> replicas) { ArrayList<String> throttles = new ArrayList<>(Arrays.asList(throttleConfig.split(","))); throttles.removeIf(replicas::contains); return String.join(",", throttles); } ReplicationThrottleHelper(KafkaZkClient kafkaZkClient, Long throttleRate); }### Answer: @Test public void testRemoveReplicasFromConfigTest() { Set<String> replicas = new LinkedHashSet<>(); replicas.add("foo"); replicas.add("bar"); replicas.add("baz"); String throttleConfig = "foo,bar,qux,qaz,baz"; String result = ReplicationThrottleHelper.removeReplicasFromConfig(throttleConfig, replicas); assertEquals(result, "qux,qaz"); }
### Question: MetricSampleAggregator extends LongGenerationed { public List<Long> allWindows() { return getWindowList(_oldestWindowIndex, _currentWindowIndex); } MetricSampleAggregator(int numWindows, long windowMs, byte minSamplesPerWindow, int completenessCacheSize, MetricDef metricDef); boolean addSample(MetricSample<G, E> sample); MetricSampleAggregationResult<G, E> aggregate(long from, long to, AggregationOptions<G, E> options); Map<E, ValuesAndExtrapolations> peekCurrentWindow(); MetricSampleCompleteness<G, E> completeness(long from, long to, AggregationOptions<G, E> options); List<Long> availableWindows(); int numAvailableWindows(); int numAvailableWindows(long from, long to); List<Long> allWindows(); Long earliestWindow(); int numSamples(); void retainEntities(Set<E> entities); void removeEntities(Set<E> entities); void retainEntityGroup(Set<G> entityGroups); void removeEntityGroup(Set<G> entityGroups); void clear(); long monitoringPeriodMs(); }### Answer: @Test public void testAllWindows() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); assertTrue(aggregator.allWindows().isEmpty()); CruiseControlUnitTestUtils.populateSampleAggregator(NUM_WINDOWS + 1, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY1, 0, WINDOW_MS, _metricDef); List<Long> allStWindows = aggregator.allWindows(); assertEquals(NUM_WINDOWS + 1, allStWindows.size()); for (int i = 0; i < NUM_WINDOWS + 1; i++) { assertEquals((i + 1) * WINDOW_MS, allStWindows.get(i).longValue()); } }
### Question: ExecutionProposal { public Map<Integer, ReplicaPlacementInfo> replicasToMoveBetweenDisksByBroker() { return _replicasToMoveBetweenDisksByBroker; } ExecutionProposal(TopicPartition tp, long partitionSize, ReplicaPlacementInfo oldLeader, List<ReplicaPlacementInfo> oldReplicas, List<ReplicaPlacementInfo> newReplicas); boolean isInterBrokerMovementCompleted(PartitionInfo partitionInfo); boolean isInterBrokerMovementAborted(PartitionInfo partitionInfo); String topic(); int partitionId(); TopicPartition topicPartition(); ReplicaPlacementInfo oldLeader(); ReplicaPlacementInfo newLeader(); List<ReplicaPlacementInfo> oldReplicas(); List<ReplicaPlacementInfo> newReplicas(); Set<ReplicaPlacementInfo> replicasToAdd(); Set<ReplicaPlacementInfo> replicasToRemove(); Map<Integer, ReplicaPlacementInfo> replicasToMoveBetweenDisksByBroker(); boolean hasReplicaAction(); boolean hasLeaderAction(); long interBrokerDataToMoveInMB(); long intraBrokerDataToMoveInMB(); long dataToMoveInMB(); Map<String, Object> getJsonStructure(); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void testIntraBrokerReplicaMovements() { ExecutionProposal p = new ExecutionProposal(TP, 0, _r0d0, Arrays.asList(_r0d0, _r1d1), Arrays.asList(_r0d1, _r1d1)); Assert.assertEquals(1, p.replicasToMoveBetweenDisksByBroker().size()); }
### Question: ExecutionTaskPlanner { public void clear() { _intraPartMoveTaskByBrokerId.clear(); _interPartMoveTaskByBrokerId.clear(); _remainingLeadershipMovements.clear(); _remainingInterBrokerReplicaMovements.clear(); _remainingIntraBrokerReplicaMovements.clear(); } ExecutionTaskPlanner(AdminClient adminClient, KafkaCruiseControlConfig config); void addExecutionProposals(Collection<ExecutionProposal> proposals, Cluster cluster, ReplicaMovementStrategy replicaMovementStrategy); Set<ExecutionTask> remainingInterBrokerReplicaMovements(); Set<ExecutionTask> remainingIntraBrokerReplicaMovements(); Collection<ExecutionTask> remainingLeadershipMovements(); List<ExecutionTask> getLeadershipMovementTasks(int numTasks); List<ExecutionTask> getInterBrokerReplicaMovementTasks(Map<Integer, Integer> readyBrokers, Set<TopicPartition> inProgressPartitions); List<ExecutionTask> getIntraBrokerReplicaMovementTasks(Map<Integer, Integer> readyBrokers); void clear(); }### Answer: @Test public void testClear() { List<ExecutionProposal> proposals = new ArrayList<>(); proposals.add(_leaderMovement1); proposals.add(_partitionMovement1); ExecutionTaskPlanner planner = new ExecutionTaskPlanner(null, new KafkaCruiseControlConfig(KafkaCruiseControlUnitTestUtils.getKafkaCruiseControlProperties())); Set<PartitionInfo> partitions = new HashSet<>(); partitions.add(generatePartitionInfo(_leaderMovement1, false)); partitions.add(generatePartitionInfo(_partitionMovement1, false)); Cluster expectedCluster = new Cluster(null, _expectedNodes, partitions, Collections.<String>emptySet(), Collections.<String>emptySet()); planner.addExecutionProposals(proposals, expectedCluster, null); assertEquals(2, planner.remainingLeadershipMovements().size()); assertEquals(2, planner.remainingInterBrokerReplicaMovements().size()); planner.clear(); assertEquals(0, planner.remainingLeadershipMovements().size()); assertEquals(0, planner.remainingInterBrokerReplicaMovements().size()); }
### Question: SortedReplicas { SortedReplicas(Broker broker, Set<Function<Replica, Boolean>> selectionFuncs, List<Function<Replica, Integer>> priorityFuncs, Function<Replica, Double> scoreFunction) { this(broker, null, selectionFuncs, priorityFuncs, scoreFunction, true); } SortedReplicas(Broker broker, Set<Function<Replica, Boolean>> selectionFuncs, List<Function<Replica, Integer>> priorityFuncs, Function<Replica, Double> scoreFunction); SortedReplicas(Broker broker, Disk disk, Set<Function<Replica, Boolean>> selectionFuncs, List<Function<Replica, Integer>> priorityFuncs, Function<Replica, Double> scoreFunc, boolean initialize); SortedSet<Replica> sortedReplicas(boolean clone); Set<Function<Replica, Boolean>> selectionFunctions(); List<Function<Replica, Integer>> priorityFunctions(); Function<Replica, Double> scoreFunction(); void add(Replica replica); }### Answer: @Test public void testScoreFunctionOnly() { Broker broker = generateBroker(NUM_REPLICAS); broker.trackSortedReplicas(SORT_NAME, null, null, SCORE_FUNC); SortedReplicas sr = broker.trackedSortedReplicas(SORT_NAME); double lastScore = Double.NEGATIVE_INFINITY; for (Replica r : sr.sortedReplicas(false)) { assertTrue(SCORE_FUNC.apply(r) >= lastScore); } } @Test public void testPriorityFunction() { Broker broker = generateBroker(NUM_REPLICAS); new SortedReplicasHelper().addPriorityFunc(PRIORITY_FUNC) .setScoreFunc(SCORE_FUNC) .trackSortedReplicasFor(SORT_NAME, broker); SortedReplicas sr = broker.trackedSortedReplicas(SORT_NAME); assertEquals(NUM_REPLICAS, sr.sortedReplicas(false).size()); verifySortedReplicas(sr); } @Test public void testSelectionFunction() { Broker broker = generateBroker(NUM_REPLICAS); new SortedReplicasHelper().addSelectionFunc(SELECTION_FUNC) .addPriorityFunc(PRIORITY_FUNC) .setScoreFunc(SCORE_FUNC) .trackSortedReplicasFor(SORT_NAME, broker); SortedReplicas sr = broker.trackedSortedReplicas(SORT_NAME); assertEquals(broker.leaderReplicas().size(), sr.sortedReplicas(false).size()); verifySortedReplicas(sr); }
### Question: MetricSampleAggregator extends LongGenerationed { public List<Long> availableWindows() { return getWindowList(_oldestWindowIndex, _currentWindowIndex - 1); } MetricSampleAggregator(int numWindows, long windowMs, byte minSamplesPerWindow, int completenessCacheSize, MetricDef metricDef); boolean addSample(MetricSample<G, E> sample); MetricSampleAggregationResult<G, E> aggregate(long from, long to, AggregationOptions<G, E> options); Map<E, ValuesAndExtrapolations> peekCurrentWindow(); MetricSampleCompleteness<G, E> completeness(long from, long to, AggregationOptions<G, E> options); List<Long> availableWindows(); int numAvailableWindows(); int numAvailableWindows(long from, long to); List<Long> allWindows(); Long earliestWindow(); int numSamples(); void retainEntities(Set<E> entities); void removeEntities(Set<E> entities); void retainEntityGroup(Set<G> entityGroups); void removeEntityGroup(Set<G> entityGroups); void clear(); long monitoringPeriodMs(); }### Answer: @Test public void testAvailableWindows() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); assertTrue(aggregator.availableWindows().isEmpty()); CruiseControlUnitTestUtils.populateSampleAggregator(1, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY1, 0, WINDOW_MS, _metricDef); assertTrue(aggregator.availableWindows().isEmpty()); CruiseControlUnitTestUtils.populateSampleAggregator(NUM_WINDOWS - 2, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY1, 1, WINDOW_MS, _metricDef); List<Long> availableWindows = aggregator.availableWindows(); assertEquals(NUM_WINDOWS - 2, availableWindows.size()); for (int i = 0; i < NUM_WINDOWS - 2; i++) { assertEquals((i + 1) * WINDOW_MS, availableWindows.get(i).longValue()); } } @Test public void testAddSamplesWithLargeInterval() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); CruiseControlUnitTestUtils.populateSampleAggregator(NUM_WINDOWS + 1, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY1, 0, WINDOW_MS, _metricDef); CruiseControlUnitTestUtils.populateSampleAggregator(NUM_WINDOWS, MIN_SAMPLES_PER_WINDOW, aggregator, ENTITY1, 4 * NUM_WINDOWS, WINDOW_MS, _metricDef); List<Long> availableWindows = aggregator.availableWindows(); assertEquals(NUM_WINDOWS, availableWindows.size()); for (int i = 0; i < NUM_WINDOWS; i++) { assertEquals((i + 4 * NUM_WINDOWS) * WINDOW_MS, availableWindows.get(i).longValue()); } }
### Question: KafkaPartitionMetricSampleAggregator extends MetricSampleAggregator<String, PartitionEntity> { public SortedSet<Long> validWindows(Cluster cluster, double minMonitoredPartitionsPercentage) { AggregationOptions<String, PartitionEntity> options = new AggregationOptions<>(minMonitoredPartitionsPercentage, 0.0, 1, _maxAllowedExtrapolationsPerPartition, allPartitions(cluster), AggregationOptions.Granularity.ENTITY, true); MetricSampleCompleteness<String, PartitionEntity> completeness = completeness(-1, Long.MAX_VALUE, options); return windowIndicesToWindows(completeness.validWindowIndices(), _windowMs); } KafkaPartitionMetricSampleAggregator(KafkaCruiseControlConfig config, Metadata metadata); boolean addSample(PartitionMetricSample sample); boolean addSample(PartitionMetricSample sample, boolean leaderValidation); MetricSampleAggregationResult<String, PartitionEntity> aggregate(Cluster cluster, long now, OperationProgress operationProgress); MetricSampleAggregationResult<String, PartitionEntity> aggregate(Cluster cluster, long from, long to, ModelCompletenessRequirements requirements, OperationProgress operationProgress); MetricSampleCompleteness<String, PartitionEntity> completeness(Cluster cluster, long from, long to, ModelCompletenessRequirements requirements); SortedSet<Long> validWindows(Cluster cluster, double minMonitoredPartitionsPercentage); double monitoredPercentage(Cluster cluster); SortedMap<Long, Float> validPartitionRatioByWindows(Cluster cluster); }### Answer: @Test public void testValidWindows() { TestContext ctx = setupScenario1(); KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator(); MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0); SortedSet<Long> validWindows = aggregator.validWindows(clusterAndGeneration.cluster(), 1.0); assertEquals(NUM_WINDOWS, validWindows.size()); assertValidWindows(validWindows, NUM_WINDOWS, Collections.emptySet()); } @Test public void testValidWindowsWithInvalidPartitions() { TestContext ctx = setupScenario2(); KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator(); MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0); SortedSet<Long> validWindows = aggregator.validWindows(clusterAndGeneration.cluster(), 1.0); assertEquals("Should have three invalid windows.", NUM_WINDOWS - 3, validWindows.size()); assertValidWindows(validWindows, NUM_WINDOWS - 1, Arrays.asList(6, 7)); assertEquals(NUM_WINDOWS, aggregator.validWindows(clusterAndGeneration.cluster(), 0.5).size()); } @Test public void testValidWindowWithDifferentInvalidPartitions() { TestContext ctx = setupScenario3(); KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator(); MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0); SortedSet<Long> validWindows = aggregator.validWindows(clusterAndGeneration.cluster(), 0.75); assertEquals("Should have two invalid windows.", NUM_WINDOWS - 2, validWindows.size()); assertValidWindows(validWindows, NUM_WINDOWS, Arrays.asList(6, 7)); } @Test public void testValidWindowsWithTooManyExtrapolations() { TestContext ctx = setupScenario4(); KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator(); MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0); SortedSet<Long> validWindows = aggregator.validWindows(clusterAndGeneration.cluster(), 0.75); assertEquals("Should have two invalid windows.", NUM_WINDOWS - 2, validWindows.size()); assertValidWindows(validWindows, NUM_WINDOWS, Arrays.asList(6, 7)); }
### Question: KafkaPartitionMetricSampleAggregator extends MetricSampleAggregator<String, PartitionEntity> { public double monitoredPercentage(Cluster cluster) { AggregationOptions<String, PartitionEntity> options = new AggregationOptions<>(0.0, 0.0, 1, _maxAllowedExtrapolationsPerPartition, allPartitions(cluster), AggregationOptions.Granularity.ENTITY, true); MetricSampleCompleteness<String, PartitionEntity> completeness = completeness(-1, Long.MAX_VALUE, options); return completeness.validEntityRatio(); } KafkaPartitionMetricSampleAggregator(KafkaCruiseControlConfig config, Metadata metadata); boolean addSample(PartitionMetricSample sample); boolean addSample(PartitionMetricSample sample, boolean leaderValidation); MetricSampleAggregationResult<String, PartitionEntity> aggregate(Cluster cluster, long now, OperationProgress operationProgress); MetricSampleAggregationResult<String, PartitionEntity> aggregate(Cluster cluster, long from, long to, ModelCompletenessRequirements requirements, OperationProgress operationProgress); MetricSampleCompleteness<String, PartitionEntity> completeness(Cluster cluster, long from, long to, ModelCompletenessRequirements requirements); SortedSet<Long> validWindows(Cluster cluster, double minMonitoredPartitionsPercentage); double monitoredPercentage(Cluster cluster); SortedMap<Long, Float> validPartitionRatioByWindows(Cluster cluster); }### Answer: @Test public void testMonitoredPercentage() { TestContext ctx = setupScenario1(); KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator(); MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals(1.0, aggregator.monitoredPercentage(clusterAndGeneration.cluster()), 0.01); ctx = setupScenario2(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals(0.75, aggregator.monitoredPercentage(clusterAndGeneration.cluster()), 0.01); ctx = setupScenario3(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals((double) 4 / 6, aggregator.monitoredPercentage(clusterAndGeneration.cluster()), 0.01); ctx = setupScenario4(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); assertEquals((double) 4 / 6, aggregator.monitoredPercentage(clusterAndGeneration.cluster()), 0.01); }
### Question: KafkaPartitionMetricSampleAggregator extends MetricSampleAggregator<String, PartitionEntity> { public SortedMap<Long, Float> validPartitionRatioByWindows(Cluster cluster) { AggregationOptions<String, PartitionEntity> options = new AggregationOptions<>(0.0, 0.0, 1, _maxAllowedExtrapolationsPerPartition, allPartitions(cluster), AggregationOptions.Granularity.ENTITY, true); MetricSampleCompleteness<String, PartitionEntity> completeness = completeness(-1, Long.MAX_VALUE, options); return windowIndicesToWindows(completeness.validEntityRatioWithGroupGranularityByWindowIndex(), _windowMs); } KafkaPartitionMetricSampleAggregator(KafkaCruiseControlConfig config, Metadata metadata); boolean addSample(PartitionMetricSample sample); boolean addSample(PartitionMetricSample sample, boolean leaderValidation); MetricSampleAggregationResult<String, PartitionEntity> aggregate(Cluster cluster, long now, OperationProgress operationProgress); MetricSampleAggregationResult<String, PartitionEntity> aggregate(Cluster cluster, long from, long to, ModelCompletenessRequirements requirements, OperationProgress operationProgress); MetricSampleCompleteness<String, PartitionEntity> completeness(Cluster cluster, long from, long to, ModelCompletenessRequirements requirements); SortedSet<Long> validWindows(Cluster cluster, double minMonitoredPartitionsPercentage); double monitoredPercentage(Cluster cluster); SortedMap<Long, Float> validPartitionRatioByWindows(Cluster cluster); }### Answer: @Test public void testMonitoredPercentagesByWindows() { TestContext ctx = setupScenario1(); KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator(); MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0); Map<Long, Float> percentages = aggregator.validPartitionRatioByWindows(clusterAndGeneration.cluster()); assertEquals(NUM_WINDOWS, percentages.size()); for (Map.Entry<Long, Float> entry : percentages.entrySet()) { assertEquals(1.0, entry.getValue(), 0.01); } ctx = setupScenario2(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); percentages = aggregator.validPartitionRatioByWindows(clusterAndGeneration.cluster()); assertEquals(NUM_WINDOWS, percentages.size()); for (Map.Entry<Long, Float> entry : percentages.entrySet()) { long window = entry.getKey(); if (window == 6000 || window == 7000 || window == 20000) { assertEquals(0.5, entry.getValue(), 0.01); } else { assertEquals(1.0, entry.getValue(), 0.01); } } ctx = setupScenario3(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); percentages = aggregator.validPartitionRatioByWindows(clusterAndGeneration.cluster()); assertEquals(NUM_WINDOWS, percentages.size()); for (Map.Entry<Long, Float> entry : percentages.entrySet()) { long window = entry.getKey(); if (window == 6000 || window == 7000 || window == 18000 || window == 19000) { assertEquals((double) 4 / 6, entry.getValue(), 0.01); } else { assertEquals(1.0, entry.getValue(), 0.01); } } ctx = setupScenario4(); aggregator = ctx.aggregator(); clusterAndGeneration = ctx.clusterAndGeneration(0); percentages = aggregator.validPartitionRatioByWindows(clusterAndGeneration.cluster()); assertEquals(NUM_WINDOWS, percentages.size()); for (Map.Entry<Long, Float> entry : percentages.entrySet()) { long window = entry.getKey(); if (window == 6000 || window == 7000) { assertEquals((double) 2 / 6, entry.getValue(), 0.01); } else { assertEquals((double) 4 / 6, entry.getValue(), 0.01); } } }
### Question: OperationProgress { public void refer(OperationProgress other) { List<OperationStep> steps; List<Long> startTimes; synchronized (other) { steps = other._steps; startTimes = other._startTimes; } synchronized (this) { ensureMutable(); this._steps = steps; this._startTimes = startTimes; this._mutable = false; } } OperationProgress(); OperationProgress(String operation); synchronized void addStep(OperationStep step); void refer(OperationProgress other); synchronized List<OperationStep> progress(); synchronized void clear(); @Override synchronized String toString(); Map<String, Object> getJsonStructure(); }### Answer: @Test public void testRefer() { OperationProgress progress1 = new OperationProgress(); progress1.addStep(new Pending()); OperationProgress progress2 = new OperationProgress(); progress2.addStep(new WaitingForClusterModel()); assertTrue(progress1.progress().get(0) instanceof Pending); progress1.refer(progress2); assertTrue(progress1.progress().get(0) instanceof WaitingForClusterModel); assertEquals(progress1.progress(), progress2.progress()); }
### Question: JwtLoginService extends AbstractLifeCycle implements LoginService { @Override public UserIdentity login(String username, Object credentials, ServletRequest request) { if (!(credentials instanceof SignedJWT)) { return null; } if (!(request instanceof HttpServletRequest)) { return null; } SignedJWT jwtToken = (SignedJWT) credentials; JWTClaimsSet claimsSet; boolean valid; try { claimsSet = jwtToken.getJWTClaimsSet(); valid = validateToken(jwtToken, claimsSet, username); } catch (ParseException e) { JWT_LOGGER.warn(String.format("%s: Couldn't parse a JWT token", username), e); return null; } if (valid) { String serializedToken = (String) request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE); UserIdentity rolesDelegate = _authorizationService.getUserIdentity((HttpServletRequest) request, username); if (rolesDelegate == null) { return null; } else { return getUserIdentity(jwtToken, claimsSet, serializedToken, username, rolesDelegate); } } else { return null; } } JwtLoginService(AuthorizationService authorizationService, String publicKeyLocation, List<String> audiences); JwtLoginService(AuthorizationService authorizationService, RSAPublicKey publicKey, List<String> audiences); JwtLoginService(AuthorizationService authorizationService, RSAPublicKey publicKey, List<String> audiences, Clock clock); @Override String getName(); @Override UserIdentity login(String username, Object credentials, ServletRequest request); @Override boolean validate(UserIdentity user); @Override IdentityService getIdentityService(); @Override void setIdentityService(IdentityService service); @Override void logout(UserIdentity user); static final String X_509_CERT_TYPE; }### Answer: @Test public void testFailSignatureValidation() throws Exception { UserStore testUserStore = new UserStore(); testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"}); TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER); TokenGenerator.TokenAndKeys tokenAndKeys2 = TokenGenerator.generateToken(TEST_USER); JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys2.publicKey(), null); SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token()); HttpServletRequest request = mock(HttpServletRequest.class); UserIdentity identity = loginService.login(TEST_USER, jwtToken, request); assertNull(identity); } @Test public void testFailAudienceValidation() throws Exception { UserStore testUserStore = new UserStore(); testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"}); TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER, Arrays.asList("A", "B")); JwtLoginService loginService = new JwtLoginService( new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), Arrays.asList("C", "D")); SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token()); HttpServletRequest request = mock(HttpServletRequest.class); UserIdentity identity = loginService.login(TEST_USER, jwtToken, request); assertNull(identity); } @Test public void testFailExpirationValidation() throws Exception { UserStore testUserStore = new UserStore(); testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"}); TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER, 1L); JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null); SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token()); HttpServletRequest request = mock(HttpServletRequest.class); UserIdentity identity = loginService.login(TEST_USER, jwtToken, request); assertNull(identity); }
### Question: JwtAuthenticator extends LoginAuthenticator { String getJwtFromBearerAuthorization(HttpServletRequest req) { String authorizationHeader = req.getHeader(HttpHeader.AUTHORIZATION.asString()); if (authorizationHeader == null || !authorizationHeader.startsWith(BEARER)) { return null; } else { return authorizationHeader.substring(BEARER.length()).trim(); } } JwtAuthenticator(String authenticationProviderUrl, String cookieName); @Override String getAuthMethod(); @Override void prepareRequest(ServletRequest request); @Override Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory); @Override boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory, Authentication.User validatedUser); static final String JWT_TOKEN_REQUEST_ATTRIBUTE; }### Answer: @Test public void testParseTokenFromAuthHeader() { JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN); HttpServletRequest request = mock(HttpServletRequest.class); expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(JwtAuthenticator.BEARER + " " + EXPECTED_TOKEN); replay(request); String actualToken = authenticator.getJwtFromBearerAuthorization(request); verify(request); assertEquals(EXPECTED_TOKEN, actualToken); } @Test public void testParseTokenFromAuthHeaderNoBearer() { JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN); HttpServletRequest request = mock(HttpServletRequest.class); expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(BASIC_SCHEME + " " + EXPECTED_TOKEN); replay(request); String actualToken = authenticator.getJwtFromBearerAuthorization(request); verify(request); assertNull(actualToken); }
### Question: JwtAuthenticator extends LoginAuthenticator { String getJwtFromCookie(HttpServletRequest req) { String serializedJWT = null; Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (_cookieName != null && _cookieName.equals(cookie.getName())) { JWT_LOGGER.trace(_cookieName + " cookie has been found and is being processed"); serializedJWT = cookie.getValue(); break; } } } return serializedJWT; } JwtAuthenticator(String authenticationProviderUrl, String cookieName); @Override String getAuthMethod(); @Override void prepareRequest(ServletRequest request); @Override Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory); @Override boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory, Authentication.User validatedUser); static final String JWT_TOKEN_REQUEST_ATTRIBUTE; }### Answer: @Test public void testParseTokenFromCookie() { JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN); HttpServletRequest request = mock(HttpServletRequest.class); expect(request.getCookies()).andReturn(new Cookie[] {new Cookie(JWT_TOKEN, EXPECTED_TOKEN)}); replay(request); String actualToken = authenticator.getJwtFromCookie(request); verify(request); assertEquals(EXPECTED_TOKEN, actualToken); } @Test public void testParseTokenFromCookieNoJwtCookie() { JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN); HttpServletRequest request = mock(HttpServletRequest.class); expect(request.getCookies()).andReturn(new Cookie[] {new Cookie(RANDOM_COOKIE_NAME, "")}); replay(request); String actualToken = authenticator.getJwtFromCookie(request); verify(request); assertNull(actualToken); }
### Question: TrustedProxyAuthorizationService extends AbstractLifeCycle implements AuthorizationService { @Override public UserIdentity getUserIdentity(HttpServletRequest request, String name) { int nameHostSeparatorIndex = name.indexOf('/'); String serviceName = nameHostSeparatorIndex > 0 ? name.substring(0, nameHostSeparatorIndex) : name; UserIdentity serviceIdentity = _adminUserStore.getUserIdentity(serviceName); if (_trustedProxyIpPattern != null) { return _trustedProxyIpPattern.matcher(request.getRemoteAddr()).matches() ? serviceIdentity : null; } else { return serviceIdentity; } } TrustedProxyAuthorizationService(List<String> userNames, String trustedProxyIpPattern); @Override UserIdentity getUserIdentity(HttpServletRequest request, String name); }### Answer: @Test public void testSuccessfulLoginWithIpFiltering() throws Exception { TrustedProxyAuthorizationService srv = new TrustedProxyAuthorizationService(Collections.singletonList(AUTH_SERVICE_NAME), IP_FILTER); HttpServletRequest mockRequest = mock(HttpServletRequest.class); expect(mockRequest.getRemoteAddr()).andReturn("192.168.0.1"); replay(mockRequest); srv.start(); try { UserIdentity result = srv.getUserIdentity(mockRequest, AUTH_SERVICE_NAME); assertNotNull(result); assertEquals(AUTH_SERVICE_NAME, result.getUserPrincipal().getName()); } finally { srv.stop(); } } @Test public void testUnsuccessfulLoginWithIpFiltering() throws Exception { TrustedProxyAuthorizationService srv = new TrustedProxyAuthorizationService(Collections.singletonList(AUTH_SERVICE_NAME), IP_FILTER); HttpServletRequest mockRequest = mock(HttpServletRequest.class); expect(mockRequest.getRemoteAddr()).andReturn("192.167.0.1"); replay(mockRequest); srv.start(); try { UserIdentity result = srv.getUserIdentity(mockRequest, AUTH_SERVICE_NAME); assertNull(result); } finally { srv.stop(); } } @Test public void testSuccessfulLoginWithoutIpFiltering() throws Exception { TrustedProxyAuthorizationService srv = new TrustedProxyAuthorizationService(Collections.singletonList(AUTH_SERVICE_NAME), null); HttpServletRequest mockRequest = mock(HttpServletRequest.class); srv.start(); try { UserIdentity result = srv.getUserIdentity(mockRequest, AUTH_SERVICE_NAME); assertNotNull(result); assertEquals(AUTH_SERVICE_NAME, result.getUserPrincipal().getName()); } finally { srv.stop(); } }
### Question: TrustedProxyLoginService extends ContainerLifeCycle implements LoginService { @Override public UserIdentity login(String username, Object credentials, ServletRequest request) { if (!(request instanceof HttpServletRequest)) { return null; } SpnegoUserIdentity serviceIdentity = (SpnegoUserIdentity) _delegateSpnegoLoginService.login(username, credentials, request); SpnegoUserPrincipal servicePrincipal = (SpnegoUserPrincipal) serviceIdentity.getUserPrincipal(); String doAsUser = request.getParameter(DO_AS); LOG.info("Authorizing proxy user {} from {} service", doAsUser, servicePrincipal.getName()); UserIdentity doAsIdentity = null; if (doAsUser != null && !doAsUser.isEmpty()) { doAsIdentity = _endUserAuthorizer.getUserIdentity((HttpServletRequest) request, doAsUser); } Principal principal = new TrustedProxyPrincipal(doAsUser, servicePrincipal); Subject subject = new Subject(READ_ONLY_SUBJECT, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet()); if (!serviceIdentity.isEstablished()) { LOG.info("Service user {} isn't authorized as a trusted proxy", servicePrincipal.getName()); return new SpnegoUserIdentity(subject, principal, null); } else { if (doAsIdentity == null) { LOG.info("Couldn't authorize user {}", doAsUser); } return new SpnegoUserIdentity(subject, principal, doAsIdentity); } } TrustedProxyLoginService(String realm, AuthorizationService userAuthorizer, List<String> trustedProxies, String trustedProxyIpPattern); TrustedProxyLoginService(ConfigurableSpnegoLoginService delegateSpnegoLoginService, AuthorizationService userAuthorizer); void setServiceName(String serviceName); void setHostName(String hostName); void setKeyTabPath(Path path); @Override String getName(); @Override UserIdentity login(String username, Object credentials, ServletRequest request); @Override boolean validate(UserIdentity user); @Override IdentityService getIdentityService(); @Override void setIdentityService(IdentityService service); @Override void logout(UserIdentity user); static final boolean READ_ONLY_SUBJECT; }### Answer: @Test public void testInvalidAuthServiceUser() { ConfigurableSpnegoLoginService mockSpnegoLoginService = mock(ConfigurableSpnegoLoginService.class); SpnegoUserPrincipal servicePrincipal = new SpnegoUserPrincipal(TEST_SERVICE_USER, ENCODED_TOKEN); Subject subject = new Subject(true, Collections.singleton(servicePrincipal), Collections.emptySet(), Collections.emptySet()); SpnegoUserIdentity result = new SpnegoUserIdentity(subject, servicePrincipal, null); expect(mockSpnegoLoginService.login(anyString(), anyObject(), anyObject())).andReturn(result); TestAuthorizer userAuthorizer = new TestAuthorizer(TEST_USER); HttpServletRequest mockRequest = mock(HttpServletRequest.class); expect(mockRequest.getParameter(DO_AS)).andReturn(TEST_USER); replay(mockSpnegoLoginService); TrustedProxyLoginService trustedProxyLoginService = new TrustedProxyLoginService(mockSpnegoLoginService, userAuthorizer); UserIdentity doAsIdentity = trustedProxyLoginService.login(null, ENCODED_TOKEN, mockRequest); assertNotNull(doAsIdentity); assertFalse(((SpnegoUserIdentity) doAsIdentity).isEstablished()); }
### Question: SpnegoUserStoreAuthorizationService extends UserStoreAuthorizationService { @Override public UserIdentity getUserIdentity(HttpServletRequest request, String name) { int hostSeparator = name.indexOf('/'); String shortName = hostSeparator > 0 ? name.substring(0, hostSeparator) : name; int realmSeparator = shortName.indexOf('@'); shortName = realmSeparator > 0 ? shortName.substring(0, realmSeparator) : shortName; return super.getUserIdentity(request, shortName); } SpnegoUserStoreAuthorizationService(String privilegesFilePath); SpnegoUserStoreAuthorizationService(UserStore userStore); @Override UserIdentity getUserIdentity(HttpServletRequest request, String name); }### Answer: @Test public void testPrincipalNames() { UserStore users = new UserStore(); users.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] { DefaultRoleSecurityProvider.ADMIN }); UserStoreAuthorizationService usas = new SpnegoUserStoreAuthorizationService(users); UserIdentity result = usas.getUserIdentity(null, TEST_USER + "/host@REALM"); assertNotNull(result); assertEquals(TEST_USER, result.getUserPrincipal().getName()); result = usas.getUserIdentity(null, TEST_USER + "@REALM"); assertNotNull(result); assertEquals(TEST_USER, result.getUserPrincipal().getName()); result = usas.getUserIdentity(null, TEST_USER + "/host"); assertNotNull(result); assertEquals(TEST_USER, result.getUserPrincipal().getName()); result = usas.getUserIdentity(null, TEST_USER); assertNotNull(result); assertEquals(TEST_USER, result.getUserPrincipal().getName()); }
### Question: OperationFuture extends CompletableFuture<CruiseControlResponse> { public synchronized boolean setExecutionThread(Thread t) { if (isCancelled() && t != null) { return false; } else { _executionThread = t; return true; } } OperationFuture(String operation); @Override synchronized boolean cancel(boolean mayInterruptIfRunning); @Override CruiseControlResponse get(); String operation(); synchronized boolean setExecutionThread(Thread t); String progressString(); Map<String, Object> getJsonStructure(); OperationProgress operationProgress(); void setFinishTimeNs(long finishTimeNs); long finishTimeNs(); }### Answer: @Test public void testSetExecutionThread() { OperationFuture future = new OperationFuture("testSetExecutionThread"); assertTrue(future.setExecutionThread(new Thread())); future.cancel(true); assertTrue("Should be able to set the execution thread of canceled future to null", future.setExecutionThread(null)); assertFalse("Should failed to set execution thread for the canceled future.", future.setExecutionThread(new Thread())); }
### Question: SessionManager { synchronized OperationFuture getAndCreateSessionIfNotExist(HttpServletRequest request, Supplier<OperationFuture> operation, int step) { HttpSession session = request.getSession(); SessionInfo info = _inProgressSessions.get(session); String requestString = toRequestString(request); if (info != null) { LOG.info("Found existing session {}", session); info.ensureSameRequest(requestString, request.getParameterMap()); if (step < info.numFutures()) { return info.future(step); } else if (step == info.numFutures()) { LOG.info("Adding new future to existing session {}.", session); OperationFuture future = operation.get(); info.addFuture(future); return future; } else { throw new IllegalArgumentException(String.format("There are %d steps in the session. Cannot add step %d.", info.numFutures(), step)); } } else { if (step > 0) { throw new IllegalArgumentException(String.format("There are no step in the session. Cannot add step %d.", step)); } if (_inProgressSessions.size() >= _capacity) { _sessionCreationFailureMeter.mark(); throw new RuntimeException("There are already " + _inProgressSessions.size() + " active sessions, which " + "has reached the servlet capacity."); } LOG.info("Created session for {}", session); info = new SessionInfo(requestString, request.getParameterMap(), ParameterUtils.endPoint(request)); OperationFuture future = operation.get(); info.addFuture(future); _inProgressSessions.put(session, info); return future; } } SessionManager(int capacity, long sessionExpiryMs, Time time, MetricRegistry dropwizardMetricRegistry, Map<EndPoint, Timer> successfulRequestExecutionTimer); void close(); }### Answer: @Test public void testMultipleOperationRequest() { TestContext context = prepareRequests(false, 1); SessionManager sessionManager = new SessionManager(1, 1000, context.time(), new MetricRegistry(), null); HttpServletRequest request = context.request(0); OperationFuture future1 = new OperationFuture("future1"); OperationFuture future2 = new OperationFuture("future2"); for (int i = 0; i < 2; i++) { OperationFuture firstFuture = sessionManager.getAndCreateSessionIfNotExist(request, () -> future1, 0); assertSame(firstFuture, future1); future1.complete(new PauseSamplingResult(null)); OperationFuture secondFuture = sessionManager.getAndCreateSessionIfNotExist(request, () -> future2, 1); assertSame(secondFuture, future2); future2.complete(new ResumeSamplingResult(null)); } } @Test (expected = IllegalArgumentException.class) public void testSkipStep() { TestContext context = prepareRequests(false, 1); SessionManager sessionManager = new SessionManager(1, 1000, context.time(), new MetricRegistry(), null); HttpServletRequest request = context.request(0); sessionManager.getAndCreateSessionIfNotExist(request, () -> null, 1); }
### Question: BrokerFailures extends KafkaAnomaly { @Override public String toString() { StringBuilder sb = new StringBuilder().append("{"); sb.append(_fixable ? "Fixable " : " Unfixable "); sb.append("broker failures detected: {"); if (_failedBrokers != null) { _failedBrokers.forEach((key, value) -> { sb.append("Broker ").append(key).append(" failed at ").append(toDateString(value)).append(",\t"); }); sb.setLength(sb.length() - 2); } sb.append("}}"); return sb.toString(); } BrokerFailures(); Map<Integer, Long> failedBrokers(); boolean fixable(); @Override boolean fix(); @Override AnomalyType anomalyType(); @Override Supplier<String> reasonSupplier(); @Override String toString(); @SuppressWarnings("unchecked") @Override void configure(Map<String, ?> configs); }### Answer: @Test public void testToString() { assertNotNull(new BrokerFailures().toString()); }
### Question: SlackSelfHealingNotifier extends SelfHealingNotifier { @Override public void alert(Object anomaly, boolean autoFixTriggered, long selfHealingStartTime, AnomalyType anomalyType) { super.alert(anomaly, autoFixTriggered, selfHealingStartTime, anomalyType); if (_slackWebhook == null) { LOG.warn("Slack webhook is null, can't send Slack self healing notification"); return; } if (_slackChannel == null) { LOG.warn("Slack channel name is null, can't send Slack self healing notification"); return; } String text = String.format("%s detected %s. Self healing %s.%s", anomalyType, anomaly, _selfHealingEnabled.get(anomalyType) ? String.format("start time %s", toDateString(selfHealingStartTime)) : "is disabled", autoFixTriggered ? "%nSelf-healing has been triggered." : ""); try { sendSlackMessage(new SlackMessage(_slackUser, text, _slackIcon, _slackChannel), _slackWebhook); } catch (IOException e) { LOG.warn("ERROR sending alert to Slack", e); } } SlackSelfHealingNotifier(); SlackSelfHealingNotifier(Time time); @Override void configure(Map<String, ?> config); @Override void alert(Object anomaly, boolean autoFixTriggered, long selfHealingStartTime, AnomalyType anomalyType); static final String SLACK_SELF_HEALING_NOTIFIER_WEBHOOK; static final String SLACK_SELF_HEALING_NOTIFIER_ICON; static final String SLACK_SELF_HEALING_NOTIFIER_USER; static final String SLACK_SELF_HEALING_NOTIFIER_CHANNEL; static final String DEFAULT_SLACK_SELF_HEALING_NOTIFIER_ICON; static final String DEFAULT_SLACK_SELF_HEALING_NOTIFIER_USER; }### Answer: @Test public void testSlackAlertWithNoWebhook() { _notifier = new MockSlackSelfHealingNotifier(MOCK_TIME); _notifier.alert(FAILURES, false, 1L, KafkaAnomalyType.BROKER_FAILURE); assertEquals(0, _notifier.getSlackMessageList().size()); } @Test public void testSlackAlertWithNoChannel() { _notifier = new MockSlackSelfHealingNotifier(MOCK_TIME); _notifier._slackWebhook = "http: _notifier.alert(FAILURES, false, 1L, KafkaAnomalyType.BROKER_FAILURE); assertEquals(0, _notifier.getSlackMessageList().size()); } @Test public void testSlackAlertWithDefaultOptions() { _notifier = new MockSlackSelfHealingNotifier(MOCK_TIME); _notifier._slackWebhook = "http: _notifier._slackChannel = "#dummy-channel"; _notifier.alert(FAILURES, false, 1L, KafkaAnomalyType.BROKER_FAILURE); assertEquals(1, _notifier.getSlackMessageList().size()); SlackMessage message = _notifier.getSlackMessageList().get(0); assertEquals("#dummy-channel", message.getChannel()); }
### Question: SlackMessage implements Serializable { @Override public String toString() { return "{\"username\" : " + (_username == null ? null : "\"" + _username + "\"") + ",\"text\" : " + (_text == null ? null : "\"" + _text + "\"") + ",\"icon_emoji\" : " + (_iconEmoji == null ? null : "\"" + _iconEmoji + "\"") + ",\"channel\" : " + (_channel == null ? null : "\"" + _channel + "\"") + "}"; } SlackMessage(String username, String text, String iconEmoji, String channel); String getUsername(); String getText(); String getIconEmoji(); String getChannel(); @Override String toString(); }### Answer: @Test public void testSlackMessageJsonFormat() { String expectedJson = "{\"username\" : \"userA\",\"text\" : \"cc alert\",\"icon_emoji\" : \":information_source:" + "\",\"channel\" : \"#cc-alerts\"}"; assertEquals(expectedJson, new SlackMessage("userA", "cc alert", ":information_source:", "#cc-alerts").toString()); }
### Question: TopicReplicationFactorAnomalyFinder implements TopicAnomalyFinder { @Override public Set<TopicAnomaly> topicAnomalies() { LOG.info("Start to detect topic replication factor anomaly."); Cluster cluster = _kafkaCruiseControl.kafkaCluster(); Set<String> topicsToCheck = new HashSet<>(); for (String topic : cluster.topics()) { if (_topicExcludedFromCheck.matcher(topic).matches()) { continue; } for (PartitionInfo partition : cluster.partitionsForTopic(topic)) { if (partition.replicas().length != _targetReplicationFactor) { topicsToCheck.add(topic); break; } } } refreshTopicMinISRCache(); if (!topicsToCheck.isEmpty()) { maybeRetrieveAndCacheTopicMinISR(topicsToCheck); Map<Short, Set<TopicReplicationFactorAnomalyEntry>> badTopicsByReplicationFactor = populateBadTopicsByReplicationFactor(topicsToCheck, cluster); if (!badTopicsByReplicationFactor.isEmpty()) { return Collections.singleton(createTopicReplicationFactorAnomaly(badTopicsByReplicationFactor, _targetReplicationFactor)); } } return Collections.emptySet(); } TopicReplicationFactorAnomalyFinder(); TopicReplicationFactorAnomalyFinder(KafkaCruiseControl kafkaCruiseControl, short targetReplicationFactor, AdminClient adminClient); @Override Set<TopicAnomaly> topicAnomalies(); @Override void configure(Map<String, ?> configs); static final String SELF_HEALING_TARGET_TOPIC_REPLICATION_FACTOR_CONFIG; static final String TOPIC_EXCLUDED_FROM_REPLICATION_FACTOR_CHECK; static final String DEFAULT_TOPIC_EXCLUDED_FROM_REPLICATION_FACTOR_CHECK; static final String TOPIC_REPLICATION_FACTOR_ANOMALY_CLASS_CONFIG; static final Class<?> DEFAULT_TOPIC_REPLICATION_FACTOR_ANOMALY_CLASS; static final String BAD_TOPICS_BY_REPLICATION_FACTOR_CONFIG; static final String TOPIC_REPLICATION_FACTOR_MARGIN_CONFIG; static final short DEFAULT_TOPIC_REPLICATION_FACTOR_MARGIN; static final String TOPIC_MIN_ISR_RECORD_RETENTION_TIME_MS_CONFIG; static final long DEFAULT_TOPIC_MIN_ISR_RECORD_RETENTION_TIME_MS; static final long DESCRIBE_TOPIC_CONFIG_TIMEOUT_MS; }### Answer: @Test public void testAnomalyDetection() throws InterruptedException, ExecutionException, TimeoutException { KafkaCruiseControl mockKafkaCruiseControl = mockKafkaCruiseControl(); AdminClient mockAdminClient = mockAdminClient((short) 1); TopicReplicationFactorAnomalyFinder anomalyFinder = new TopicReplicationFactorAnomalyFinder(mockKafkaCruiseControl, TARGET_TOPIC_REPLICATION_FACTOR, mockAdminClient); Set<TopicAnomaly> topicAnomalies = anomalyFinder.topicAnomalies(); assertEquals(1, topicAnomalies.size()); EasyMock.verify(mockKafkaCruiseControl, mockAdminClient); } @Test public void testSkipTopicWithLargeMinISR() throws InterruptedException, ExecutionException, TimeoutException { KafkaCruiseControl mockKafkaCruiseControl = mockKafkaCruiseControl(); AdminClient mockAdminClient = mockAdminClient((short) 2); TopicReplicationFactorAnomalyFinder anomalyFinder = new TopicReplicationFactorAnomalyFinder(mockKafkaCruiseControl, TARGET_TOPIC_REPLICATION_FACTOR, mockAdminClient); Set<TopicAnomaly> topicAnomalies = anomalyFinder.topicAnomalies(); assertTrue(topicAnomalies.isEmpty()); EasyMock.verify(mockKafkaCruiseControl, mockAdminClient); }
### Question: MaintenanceEvent extends KafkaAnomaly { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("{Handling %s", _maintenanceEventType)); if (_topicsWithRFUpdate != null) { sb.append(String.format(" by desired RF: [%s]", _topicsWithRFUpdate)); } else if (_brokers != null) { sb.append(String.format(" for brokers: [%s]", _brokers)); } sb.append("}"); return sb.toString(); } @Override Supplier<String> reasonSupplier(); @Override AnomalyType anomalyType(); MaintenanceEventType maintenanceEventType(); @Override boolean fix(); @Override String toString(); @Override void configure(Map<String, ?> configs); static final String MAINTENANCE_EVENT_TYPE_CONFIG; static final String BROKERS_OBJECT_CONFIG; static final String TOPICS_WITH_RF_UPDATE_CONFIG; }### Answer: @Test public void testToStringBeforeConfiguration() { assertNotNull(new MaintenanceEvent().toString()); }
### Question: AnomalyUtils { public static Pattern buildTopicRegex(Set<String> stringsToMatch) { StringJoiner sj = new StringJoiner("|"); stringsToMatch.forEach(sj::add); return Pattern.compile(sj.toString()); } private AnomalyUtils(); static KafkaCruiseControl extractKafkaCruiseControlObjectFromConfig(Map<String, ?> configs, AnomalyType anomalyType); static boolean isLoadMonitorReady(LoadMonitorTaskRunner.LoadMonitorTaskRunnerState loadMonitorTaskRunnerState); static Pattern buildTopicRegex(Set<String> stringsToMatch); static int parseAndGetConfig(Map<String, Object> config, String key, int defaultValue, Predicate<Integer> illegalValueCheck); static double parseAndGetConfig(Map<String, Object> config, String key, double defaultValue, Predicate<Double> illegalValueCheck); }### Answer: @Test public void testBuildTopicRegex() { Set<String> topicsToMatch = new HashSet<>(2); topicsToMatch.add(TOPIC1); topicsToMatch.add(TOPIC2); Pattern pattern = buildTopicRegex(topicsToMatch); assertTrue(pattern.matcher(TOPIC1).matches()); assertTrue(pattern.matcher(TOPIC2).matches()); assertFalse(pattern.matcher(TOPIC3).matches()); }
### Question: KafkaAssignerDiskUsageDistributionGoal implements Goal { boolean canSwap(Replica r1, Replica r2, ClusterModel clusterModel) { boolean inSameRack = r1.broker().rack() == r2.broker().rack() && r1.broker() != r2.broker(); boolean rackAware = !clusterModel.partition(r1.topicPartition()).partitionRacks().contains(r2.broker().rack()) && !clusterModel.partition(r2.topicPartition()).partitionRacks().contains(r1.broker().rack()); boolean sameRole = r1.isLeader() == r2.isLeader(); return (inSameRack || rackAware) && sameRole; } KafkaAssignerDiskUsageDistributionGoal(); KafkaAssignerDiskUsageDistributionGoal(BalancingConstraint constraint); @Override ClusterModelStatsComparator clusterModelStatsComparator(); @Override void configure(Map<String, ?> configs); @Override ModelCompletenessRequirements clusterModelCompletenessRequirements(); @Override boolean optimize(ClusterModel clusterModel, Set<Goal> optimizedGoals, OptimizationOptions optimizationOptions); @Override ActionAcceptance actionAcceptance(BalancingAction action, ClusterModel clusterModel); @Override String name(); @Override void finish(); @Override boolean isHardGoal(); }### Answer: @Test public void testCanSwap() { KafkaAssignerDiskUsageDistributionGoal goal = new KafkaAssignerDiskUsageDistributionGoal(); ClusterModel clusterModel = createClusterModel(); Replica r1 = clusterModel.broker(0).replica(T0P0); Replica r2 = clusterModel.broker(1).replica(T2P0); assertTrue("Replicas in the same rack should be good to swap", goal.canSwap(r1, r2, clusterModel)); assertTrue("Replicas in the same rack should be good to swap", goal.canSwap(r2, r1, clusterModel)); r2 = clusterModel.broker(1).replica(T1P0); assertFalse("Should not be able to swap replica with different roles.", goal.canSwap(r1, r2, clusterModel)); assertFalse("Should not be able to swap replica with different roles.", goal.canSwap(r2, r1, clusterModel)); r2 = clusterModel.broker(2).replica(T2P1); assertFalse("Should not be able to put two replicas in the same broker", goal.canSwap(r1, r2, clusterModel)); assertFalse("Should not be able to put two replicas in the same broker", goal.canSwap(r2, r1, clusterModel)); r2 = clusterModel.broker(3).replica(T2P2); assertFalse("Should not be able to put two replicas in the same rack", goal.canSwap(r1, r2, clusterModel)); assertFalse("Should not be able to put two replicas in the same rack", goal.canSwap(r2, r1, clusterModel)); r1 = clusterModel.broker(3).replica(T0P2); r2 = clusterModel.broker(4).replica(T1P2); assertTrue("Should be able to swap", goal.canSwap(r1, r2, clusterModel)); assertTrue("Should be able to swap", goal.canSwap(r2, r1, clusterModel)); }
### Question: GoalOptimizer implements Runnable { @Override public void run() { _proposalPrecomputingSchedulerThread = Thread.currentThread(); LOG.info("Starting proposal candidate computation."); while (!_shutdown && _numPrecomputingThreads > 0) { LoadMonitorTaskRunner.LoadMonitorTaskRunnerState loadMonitorTaskRunnerState = _loadMonitor.taskRunnerState(); long sleepTime = _proposalExpirationMs; if (loadMonitorTaskRunnerState == LOADING || loadMonitorTaskRunnerState == BOOTSTRAPPING) { LOG.info("Skipping proposal precomputing because load monitor is in " + loadMonitorTaskRunnerState + " state."); sleepTime = 30000L; } else if (!_loadMonitor.meetCompletenessRequirements(_requirementsWithAvailableValidWindows)) { LOG.info("Skipping proposal precomputing because load monitor does not have enough snapshots."); sleepTime = 30000L; } else { try { if (!validCachedProposal()) { if (LOG.isDebugEnabled()) { LOG.debug("Invalidated cache. Model generation (cached: {}, current: {}).{}", _cachedProposals == null ? null : _cachedProposals.modelGeneration(), _loadMonitor.clusterModelGeneration(), _cachedProposals == null ? "" : String.format(" Cached was excluding default topics: %s.", _cachedProposals.excludedTopics())); } clearCachedProposal(); long start = System.nanoTime(); computeCachedProposal(_allowCapacityEstimationOnProposalPrecompute); _proposalComputationTimer.update(System.nanoTime() - start, TimeUnit.NANOSECONDS); } else { LOG.debug("Skipping proposal precomputing because the cached proposal result is still valid. " + "Cached generation: {}", _cachedProposals.modelGeneration()); } } catch (KafkaCruiseControlException e) { sleepTime = 30000L; LOG.debug("Skipping proposal precomputing because there is an ongoing execution.", e); } } long deadline = _time.milliseconds() + sleepTime; if (!_shutdown && _time.milliseconds() < deadline) { try { Thread.sleep(deadline - _time.milliseconds()); } catch (InterruptedException e) { } } } } GoalOptimizer(KafkaCruiseControlConfig config, LoadMonitor loadMonitor, Time time, MetricRegistry dropwizardMetricRegistry, Executor executor); @Override void run(); void shutdown(); ModelCompletenessRequirements defaultModelCompletenessRequirements(); ModelCompletenessRequirements modelCompletenessRequirementsForPrecomputing(); AnalyzerState state(Cluster cluster); OptimizerResult optimizations(OperationProgress operationProgress, boolean allowCapacityEstimation); OptimizerResult optimizations(ClusterModel clusterModel, OperationProgress operationProgress); OptimizerResult optimizations(ClusterModel clusterModel, List<Goal> goalsByPriority, OperationProgress operationProgress); OptimizerResult optimizations(ClusterModel clusterModel, List<Goal> goalsByPriority, OperationProgress operationProgress, Map<TopicPartition, List<ReplicaPlacementInfo>> initReplicaDistributionForProposalGeneration, OptimizationOptions optimizationOptions); Set<String> excludedTopics(ClusterModel clusterModel, Pattern requestedExcludedTopics); }### Answer: @Test public void testNoPreComputingThread() { Properties props = new Properties(); props.setProperty(MonitorConfig.BOOTSTRAP_SERVERS_CONFIG, "bootstrap.servers"); props.setProperty(ExecutorConfig.ZOOKEEPER_CONNECT_CONFIG, "connect:1234"); props.setProperty(AnalyzerConfig.NUM_PROPOSAL_PRECOMPUTE_THREADS_CONFIG, "0"); props.setProperty(AnalyzerConfig.DEFAULT_GOALS_CONFIG, TestConstants.DEFAULT_GOALS_VALUES); KafkaCruiseControlConfig config = new KafkaCruiseControlConfig(props); GoalOptimizer goalOptimizer = new GoalOptimizer(config, EasyMock.mock(LoadMonitor.class), new SystemTime(), new MetricRegistry(), EasyMock.mock(Executor.class)); goalOptimizer.run(); }
### Question: ContainerMetricUtils { public static double getContainerProcessCpuLoad(double cpuUtil) throws IOException { int logicalProcessorsOfNode = getAvailableProcessors(); double cpuQuota = getCpuQuota(); if (cpuQuota == NO_CPU_QUOTA) { return cpuUtil; } double cpuLimit = cpuQuota / getCpuPeriod(); double cpus = cpuUtil * logicalProcessorsOfNode; return cpus / cpuLimit; } private ContainerMetricUtils(); static double getContainerProcessCpuLoad(double cpuUtil); static final int NO_CPU_QUOTA; }### Answer: @Test public void testGetContainerProcessCpuLoad() throws Exception { mockGetContainerProcessCpuLoad(1, 100000.0, 100000.0, 1.0, 1.0); mockGetContainerProcessCpuLoad(1, 100000.0, 100000.0, 0.5, 0.5); mockGetContainerProcessCpuLoad(1, 50000.0, 100000.0, 0.5, 1.0); mockGetContainerProcessCpuLoad(1, 75000.0, 100000.0, 0.5, 0.66); mockGetContainerProcessCpuLoad(2, 100000.0, 100000.0, 0.5, 1.0); mockGetContainerProcessCpuLoad(2, 200000.0, 100000.0, 1.0, 1.0); mockGetContainerProcessCpuLoad(2, 25000.0, 100000.0, 0.125, 1.0); mockGetContainerProcessCpuLoad(2, 2500.0, 100000.0, 0.0125, 1.0); mockGetContainerProcessCpuLoad(2, ContainerMetricUtils.NO_CPU_QUOTA, 100000.0, 0.125, 0.125); }
### Question: DeliveryParameterBuilder { public DeliveryParameterBuilder projection(String... elements) { if (elements != null) { nameValuePairs.add(new NameValuePair(ELEMENTS, String.join(",", elements))); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer: @Test public void testProjection() { List<NameValuePair> params = DeliveryParameterBuilder.params().projection("foo", "bar").build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("elements", params.get(0).getName()); Assert.assertEquals("foo,bar", params.get(0).getValue()); }
### Question: DeliveryParameterBuilder { public DeliveryParameterBuilder linkedItemsDepth(Integer depth) { if (depth != null) { nameValuePairs.add(new NameValuePair(DEPTH, depth.toString())); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer: @Test public void testLinkedItemsDepth() { List<NameValuePair> params = DeliveryParameterBuilder.params().linkedItemsDepth(3).build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("depth", params.get(0).getName()); Assert.assertEquals("3", params.get(0).getValue()); }
### Question: DeliveryParameterBuilder { public DeliveryParameterBuilder excludeLinkedItems() { nameValuePairs.add(new NameValuePair(DEPTH, "0")); return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer: @Test public void testExcludeLinkedItems() { List<NameValuePair> params = DeliveryParameterBuilder.params().excludeLinkedItems().build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("depth", params.get(0).getName()); Assert.assertEquals("0", params.get(0).getValue()); }
### Question: DeliveryParameterBuilder { public DeliveryParameterBuilder language(String language) { if (language != null) { nameValuePairs.add(new NameValuePair(LANGUAGE, language)); } return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer: @Test public void testLanguage() { List<NameValuePair> params = DeliveryParameterBuilder.params().language(Locale.US.toLanguageTag()).build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("language", params.get(0).getName()); Assert.assertEquals("en-US", params.get(0).getValue()); }
### Question: DeliveryParameterBuilder { public DeliveryParameterBuilder includeTotalCount() { nameValuePairs.add(new NameValuePair(INCLUDE_TOTAL_COUNT, "true")); return this; } static DeliveryParameterBuilder params(); DeliveryParameterBuilder filterEquals(String attribute, String value); DeliveryParameterBuilder filterLessThan(String attribute, String value); DeliveryParameterBuilder filterLessThanEquals(String attribute, String value); DeliveryParameterBuilder filterGreaterThan(String attribute, String value); DeliveryParameterBuilder filterGreaterThanEquals(String attribute, String value); DeliveryParameterBuilder filterRange(String attribute, String lower, String upper); DeliveryParameterBuilder filterIn(String attribute, String... values); DeliveryParameterBuilder filterIn(String attribute, Collection<String> values); DeliveryParameterBuilder filterContains(String attribute, String value); DeliveryParameterBuilder filterAny(String attribute, String... values); DeliveryParameterBuilder filterAny(String attribute, Collection<String> values); DeliveryParameterBuilder filterAll(String attribute, String... values); DeliveryParameterBuilder filterAll(String attribute, Collection<String> values); DeliveryParameterBuilder orderByAsc(String attribute); DeliveryParameterBuilder orderByDesc(String attribute); DeliveryParameterBuilder page(Integer skip, Integer limit); DeliveryParameterBuilder projection(String... elements); DeliveryParameterBuilder linkedItemsDepth(Integer depth); DeliveryParameterBuilder excludeLinkedItems(); DeliveryParameterBuilder language(String language); DeliveryParameterBuilder language(Locale language); DeliveryParameterBuilder includeTotalCount(); List<NameValuePair> build(); }### Answer: @Test public void testIncludeTotalCount() { List<NameValuePair> params = DeliveryParameterBuilder.params().includeTotalCount().build(); Assert.assertEquals(1, params.size()); Assert.assertEquals("includeTotalCount", params.get(0).getName()); Assert.assertEquals("true", params.get(0).getValue()); }
### Question: ThymeleafTemplateEngine implements TemplateEngine { protected boolean supports(TemplateEngineModel data) { if (!configured) { return false; } String contentType = getContentTypeFromModel(data.getInlineContentItem()); if (contentType == null) { return false; } Set<ITemplateResolver> templateResolvers = templateEngine.getTemplateResolvers(); for (ITemplateResolver resolver : templateResolvers) { if (resolver instanceof AbstractTemplateResolver) { TemplateResolution templateResolution = resolver.resolveTemplate(templateEngine.getConfiguration(), null, contentType, null); if (templateResolution != null && templateResolution.getTemplateResource().exists()) { return true; } } } return false; } @Override void setViewResolverConfiguration(ViewResolverConfiguration viewResolverConfiguration); @Override String process(TemplateEngineModel data); }### Answer: @Test public void testIllegalStateException() throws RenderingEngineMissingException { ThymeleafInlineContentItemsResolver resolver = new ThymeleafInlineContentItemsResolver(); ArticleItem articleItem = new ArticleItem(); articleItem.setTitle("Test"); TemplateEngineModel templateEngineModel = new TemplateEngineModel(); templateEngineModel.setInlineContentItem(articleItem); Assert.assertFalse(resolver.supports(templateEngineModel)); try { resolver.resolve(templateEngineModel); Assert.fail("Expected IllegalStateException"); } catch (IllegalStateException e) { Assert.assertEquals("Engine not configured. Did you call setViewResolverConfiguration()?", e.getMessage()); } }
### Question: RegisterImageBackedByEbsOptions extends RegisterImageOptions { @Override public RegisterImageBackedByEbsOptions withDescription(String info) { return (RegisterImageBackedByEbsOptions) super.withDescription(info); } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); }### Answer: @Test public void testWithDescription() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withDescription("test"); assertEquals(options.buildFormParameters().get("Description"), ImmutableList.of("test")); } @Test public void testWithDescriptionStatic() { RegisterImageBackedByEbsOptions options = withDescription("test"); assertEquals(options.buildFormParameters().get("Description"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testWithDescriptionNPE() { withDescription(null); }
### Question: RegisterImageBackedByEbsOptions extends RegisterImageOptions { @Override public RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture) { return (RegisterImageBackedByEbsOptions) super.asArchitecture(architecture); } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); }### Answer: @Test public void testWithArchitecture() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.asArchitecture(Architecture.I386); assertEquals(options.buildFormParameters().get("Architecture"), ImmutableList.of("i386")); } @Test public void testWithArchitectureStatic() { RegisterImageBackedByEbsOptions options = asArchitecture(Architecture.I386); assertEquals(options.buildFormParameters().get("Architecture"), ImmutableList.of("i386")); } @Test(expectedExceptions = NullPointerException.class) public void testWithArchitectureNPE() { asArchitecture(null); }
### Question: DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled) { this.backupsEnabled = backupsEnabled; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer: @Test public void testBackupsEnabled() { TemplateOptions options = new DigitalOcean2TemplateOptions().backupsEnabled(true); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getBackupsEnabled(), true); }
### Question: RegisterImageBackedByEbsOptions extends RegisterImageOptions { @Override public RegisterImageBackedByEbsOptions withKernelId(String kernelId) { return (RegisterImageBackedByEbsOptions) super.withKernelId(kernelId); } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); }### Answer: @Test public void testWithKernelId() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test public void testWithKernelIdStatic() { RegisterImageBackedByEbsOptions options = withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testWithKernelIdNPE() { withKernelId(null); }
### Question: RegisterImageBackedByEbsOptions extends RegisterImageOptions { @Override public RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId) { return (RegisterImageBackedByEbsOptions) super.withRamdisk(ramDiskId); } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); }### Answer: @Test public void testWithRamdisk() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); } @Test public void testWithRamdiskStatic() { RegisterImageBackedByEbsOptions options = withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) public void testWithRamdiskNPE() { withRamdisk(null); }
### Question: DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair) { this.autoCreateKeyPair = autoCreateKeyPair; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer: @Test public void testAutoCreateKeyPair() { TemplateOptions options = new DigitalOcean2TemplateOptions().autoCreateKeyPair(false); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getAutoCreateKeyPair(), false); }
### Question: RegisterImageBackedByEbsOptions extends RegisterImageOptions { public RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId) { formParameters.put("BlockDeviceMapping." + deviceIndex + ".DeviceName", checkNotNull( deviceName, "deviceName")); if (virtualName != null) formParameters.put("BlockDeviceMapping." + deviceIndex + ".VirtualName", checkNotNull( virtualName, "virtualName")); formParameters.put("BlockDeviceMapping." + deviceIndex + ".Ebs.SnapshotId", checkNotNull( snapshotId, "snapshotId")); deviceIndex++; return this; } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); }### Answer: @Test public void testAddEphemeralBlockDeviceFromSnapshot() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addEphemeralBlockDeviceFromSnapshot("deviceName", "virtualName", "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); } @Test public void testAddEphemeralBlockDeviceFromSnapshotNullVirtualName() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addEphemeralBlockDeviceFromSnapshot("deviceName", null, "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); } @Test public void testAddEphemeralBlockDeviceFromSnapshotStatic() { RegisterImageBackedByEbsOptions options = addEphemeralBlockDeviceFromSnapshot("deviceName", "virtualName", "snapshotId"); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.SnapshotId", "snapshotId").entries()); } @Test(expectedExceptions = NullPointerException.class) public void testAddEphemeralBlockDeviceFromSnapshotNPE() { addEphemeralBlockDeviceFromSnapshot(null, null, null); }
### Question: DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions userData(byte[] userData) { this.userData = userData; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer: @Test public void testUserData() { byte[] userData = "Lorem ipsum".getBytes(); TemplateOptions options = new DigitalOcean2TemplateOptions().userData(userData); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getUserData(), userData); }
### Question: RegisterImageBackedByEbsOptions extends RegisterImageOptions { public RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize) { checkArgument(volumeSize > 0 && volumeSize < 1025, "volumeSize must be between 1 and 1024 gb"); formParameters.put("BlockDeviceMapping." + deviceIndex + ".DeviceName", checkNotNull( deviceName, "deviceName")); if (virtualName != null) formParameters.put("BlockDeviceMapping." + deviceIndex + ".VirtualName", checkNotNull( virtualName, "virtualName")); formParameters.put("BlockDeviceMapping." + deviceIndex + ".Ebs.VolumeSize", volumeSize + ""); deviceIndex++; return this; } RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize, boolean deleteOnTermination, @Nullable String volumeType, @Nullable Integer iops, boolean encrypted); RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName, @Nullable String virtualName, String snapshotId); RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName, @Nullable String virtualName, int volumeSize); @Override RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture); @Override RegisterImageBackedByEbsOptions withDescription(String info); @Override RegisterImageBackedByEbsOptions withKernelId(String kernelId); @Override RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId); }### Answer: @Test public void testAddNewEphemeralBlockDevice() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addNewEphemeralBlockDevice("deviceName", "virtualName", 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); } @Test public void testAddNewEphemeralBlockDeviceNullVirtualName() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.addNewEphemeralBlockDevice("deviceName", null, 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); } @Test public void testAddNewEphemeralBlockDeviceStatic() { RegisterImageBackedByEbsOptions options = addNewEphemeralBlockDevice("deviceName", "virtualName", 1); assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of( "BlockDeviceMapping.1.DeviceName", "deviceName", "BlockDeviceMapping.1.VirtualName", "virtualName", "BlockDeviceMapping.1.Ebs.VolumeSize", "1").entries()); } @Test(expectedExceptions = NullPointerException.class) public void testAddNewEphemeralBlockDeviceNPE() { addNewEphemeralBlockDevice(null, null, 1); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAddNewEphemeralBlockDeviceTooBig() { addNewEphemeralBlockDevice("deviceName", "virtualName", 1025); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAddNewEphemeralBlockDeviceTooSmall() { addNewEphemeralBlockDevice("deviceName", "virtualName", 0); }
### Question: DropletStatusToStatus implements Function<Droplet.Status, Status> { @Override public Status apply(final Droplet.Status input) { return toPortableStatus.apply(input); } @Override Status apply(final Droplet.Status input); }### Answer: @Test public void testAllStatesHaveMapping() { DropletStatusToStatus function = new DropletStatusToStatus(); for (Status status : Status.values()) { assertNotEquals(function.apply(status), UNRECOGNIZED); } }
### Question: SizeToHardware implements Function<Size, Hardware> { @Override public Hardware apply(Size input) { HardwareBuilder builder = new HardwareBuilder(); builder.id(input.slug()); builder.providerId(input.slug()); builder.name(input.slug()); builder.ram(input.memory()); builder.processor(new Processor(input.vcpus(), input.vcpus())); builder.volume(new VolumeBuilder() .size(Float.valueOf(input.disk())) .type(Type.LOCAL) .build()); ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("costPerHour", String.valueOf(input.priceHourly())); metadata.put("costPerMonth", String.valueOf(input.priceMonthly())); builder.userMetadata(metadata.build()); return builder.build(); } @Override Hardware apply(Size input); }### Answer: @Test public void testConvertSize() { Size size = Size.create("2gb", true, 1.0f, 10f, 0.05f, 2048, 1, 20, ImmutableList.<String> of()); Hardware expected = new HardwareBuilder().id("2gb").providerId("2gb").name("2gb") .processor(new Processor(1.0, 1.0)).ram(2048) .volume(new VolumeBuilder().size(20f).type(Type.LOCAL).build()) .userMetadata(ImmutableMap.of("costPerHour", "0.05", "costPerMonth", "10")).build(); SizeToHardware function = new SizeToHardware(); assertEquals(function.apply(size), expected); }
### Question: RegionToLocation implements Function<Region, Location> { @Override public Location apply(Region input) { LocationBuilder builder = new LocationBuilder(); builder.id(input.slug()); builder.description(input.name()); builder.scope(LocationScope.REGION); builder.parent(getOnlyElement(justProvider.get())); builder.iso3166Codes(ImmutableSet.<String> of()); builder.metadata(ImmutableMap.<String, Object> of("available", input.available(), "features", input.features())); return builder.build(); } @Inject RegionToLocation(JustProvider justProvider); @Override Location apply(Region input); }### Answer: @Test public void testConvertRegion() { DigitalOcean2ProviderMetadata metadata = new DigitalOcean2ProviderMetadata(); JustProvider locationsSupplier = new JustProvider(metadata.getId(), Suppliers.<URI> ofInstance(URI .create(metadata.getEndpoint())), ImmutableSet.<String> of()); Region region = Region.create("reg1", "Region1", ImmutableList.<String> of(), true, ImmutableList.<String> of("virtio", "metadata")); Location expected = new LocationBuilder().id("reg1").description("reg1/Region 1") .parent(getOnlyElement(locationsSupplier.get())).scope(LocationScope.REGION).build(); Location location = new RegionToLocation(locationsSupplier).apply(region); assertEquals(location, expected); assertEquals(location.getMetadata().get("available"), true); assertEquals(location.getMetadata().get("features"), ImmutableList.of("virtio", "metadata")); }
### Question: ECDSAKeys { public static String fingerprintPublicKey(String publicKeyOpenSSH) throws IOException { ECPublicKeySpec publicKeySpec = publicKeySpecFromOpenSSH(publicKeyOpenSSH); String fingerprint = null; try { ECPublicKey pk = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(publicKeySpec); fingerprint = fingerprint(pk); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return fingerprint; } static String encodeAsOpenSSH(ECPublicKey key); static ECPublicKeySpec publicKeySpecFromOpenSSH(String ecDsaPub); static ECPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(ECPublicKey publicKey); static byte[] encodeECPoint(ECPoint group, EllipticCurve curve); static ECPoint decodeECPoint(byte[] M, EllipticCurve curve); static final String ECDSA_SHA2_PREFIX; }### Answer: @Test public void testCanReadRsaAndCompareFingerprintOnPublicECDSAKey() throws IOException { String ecdsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-ecdsa.pub")); String fingerPrint = ECDSAKeys.fingerprintPublicKey(ecdsa); assertEquals(fingerPrint, expectedFingerPrint); }
### Question: BindS3UploadPolicyAndSignature implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { String encodedJson = base64().encode(checkNotNull(input, "json").toString().getBytes(UTF_8)); Builder<String, String> builder = ImmutableMultimap.builder(); builder.put("Storage.S3.UploadPolicy", encodedJson); String signature = signer.sign(encodedJson); builder.put("Storage.S3.UploadPolicySignature", signature); return (R) request.toBuilder().replaceFormParams(builder.build()).build(); } @Inject BindS3UploadPolicyAndSignature(FormSignerV2 signer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testNullIsBad() { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); }
### Question: ECDSAKeys { public static String encodeAsOpenSSH(ECPublicKey key) { String curveName = null; try { curveName = getCurveName(key.getParams()); } catch (IOException e) { propagate(e); } String keyFormat = ECDSA_SHA2_PREFIX + curveName; byte[] keyBlob = keyBlob(key); return keyFormat + " " + base64().encode(keyBlob); } static String encodeAsOpenSSH(ECPublicKey key); static ECPublicKeySpec publicKeySpecFromOpenSSH(String ecDsaPub); static ECPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static String fingerprintPublicKey(String publicKeyOpenSSH); static String fingerprint(ECPublicKey publicKey); static byte[] encodeECPoint(ECPoint group, EllipticCurve curve); static ECPoint decodeECPoint(byte[] M, EllipticCurve curve); static final String ECDSA_SHA2_PREFIX; }### Answer: @Test public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { String ecdsa = Strings2.toStringAndClose(getClass().getResourceAsStream("/ssh-ecdsa.pub")); ECPublicKeySpec spec = ECDSAKeys.publicKeySpecFromOpenSSH(ecdsa); ECPublicKey key = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(spec); assertTrue(ecdsa.startsWith(ECDSAKeys.encodeAsOpenSSH(key))); }
### Question: VolumeDetached implements Predicate<Attachment> { public boolean apply(Attachment attachment) { logger.trace("looking for volume %s", attachment.getVolumeId()); Volume volume = Iterables.getOnlyElement(client.describeVolumesInRegion(attachment .getRegion(), attachment.getVolumeId())); if (volume.getAttachments().isEmpty()) { return true; } Attachment lastAttachment = getLast(volume.getAttachments()); logger.trace("%s: looking for status %s: currently: %s", lastAttachment, Attachment.Status.DETACHED, lastAttachment.getStatus()); return lastAttachment.getStatus() == Attachment.Status.DETACHED; } @Inject VolumeDetached(ElasticBlockStoreApi client); boolean apply(Attachment attachment); }### Answer: @Test public void testVolumeWithEmptyListOfAttachments() { Attachment attachment = newAttachmentWithStatus(Status.ATTACHED); Set<Volume> volumes = newHashSet(newVolumeWithAttachments()); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertTrue(volumeDetached.apply(attachment)); verify(client); } @Test(dataProvider = "notDetachedStatuses") public void testWithDifferentStatus(Status attachmentStatus) { Attachment attachment = newAttachmentWithStatus(attachmentStatus); Set<Volume> volumes = newHashSet(newVolumeWithAttachments(attachment)); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertFalse(volumeDetached.apply(attachment)); verify(client); } @Test public void testWithStatusDetached() { Attachment attachment = newAttachmentWithStatus(Status.DETACHED); Set<Volume> volumes = newHashSet(newVolumeWithAttachments(attachment)); expect(client.describeVolumesInRegion(attachment.getRegion(), attachment.getVolumeId())).andReturn(volumes); replay(client); assertTrue(volumeDetached.apply(attachment)); verify(client); }
### Question: CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions { @VisibleForTesting public String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) { String keyPairName = null; boolean shouldAutomaticallyCreateKeyPair = true; if (options instanceof EC2TemplateOptions) { keyPairName = EC2TemplateOptions.class.cast(options).getKeyPair(); if (keyPairName == null) shouldAutomaticallyCreateKeyPair = EC2TemplateOptions.class.cast(options) .shouldAutomaticallyCreateKeyPair(); } if (keyPairName == null && shouldAutomaticallyCreateKeyPair) { keyPairName = createOrImportKeyPair(region, group, options); } else if (keyPairName != null) { if (options.getLoginPrivateKey() != null) { String pem = options.getLoginPrivateKey(); KeyPair keyPair = KeyPair.builder().region(region).keyName(keyPairName).fingerprint( fingerprintPrivateKey(pem)).sha1OfPrivateKey(sha1PrivateKey(pem)).keyMaterial(pem).build(); RegionAndName key = new RegionAndName(region, keyPairName); credentialsMap.put(key, keyPair); } } if (options.getRunScript() != null) { RegionAndName regionAndName = new RegionAndName(region, keyPairName); checkArgument( credentialsMap.containsKey(regionAndName), "no private key configured for: %s; please use options.overrideLoginCredentialWith(rsa_private_text)", regionAndName); } return keyPairName; } @Inject CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions(Function<RegionAndName, KeyPair> makeKeyPair, ConcurrentMap<RegionAndName, KeyPair> credentialsMap, @Named("SECURITY") LoadingCache<RegionAndName, String> securityGroupMap, Provider<RunInstancesOptions> optionsProvider, GroupNamingConvention.Factory namingConvention); RunInstancesOptions execute(String region, String group, Template template); @VisibleForTesting String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options); @VisibleForTesting Set<String> getSecurityGroupsForTagAndOptions(String region, @Nullable String group, @Nullable String vpcId, TemplateOptions options); @VisibleForTesting javax.inject.Provider<RunInstancesOptions> getOptionsProvider(); @VisibleForTesting public Function<RegionAndName, KeyPair> makeKeyPair; @VisibleForTesting final ConcurrentMap<RegionAndName, KeyPair> credentialsMap; @VisibleForTesting final LoadingCache<RegionAndName, String> securityGroupMap; @VisibleForTesting final Provider<RunInstancesOptions> optionsProvider; }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptButNoCredentials() { String region = Region.AP_SOUTHEAST_1; String group = "group"; String userSuppliedKeyPair = "myKeyPair"; CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy(); EC2TemplateOptions options = createMock(EC2TemplateOptions.class); KeyPair keyPair = createMock(KeyPair.class); expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); expect(options.getLoginUser()).andReturn(null); expect(options.getLoginPassword()).andReturn(null); expect(options.getLoginPrivateKey()).andReturn(null); expect(options.shouldAuthenticateSudo()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false); replay(options); replay(keyPair); replayStrategy(strategy); assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair); verify(options); verify(keyPair); verifyStrategy(strategy); }