method2testcases
stringlengths 118
6.63k
|
---|
### Question:
PositionData { public PositionData avgEntryPrice(BigDecimal avgEntryPrice) { this.avgEntryPrice = avgEntryPrice; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbolIdExchange); PositionData symbolIdCoinapi(String symbolIdCoinapi); @javax.annotation.Nullable @ApiModelProperty(example = "BITMEX_PERP_BTC_USD", value = "CoinAPI symbol.") String getSymbolIdCoinapi(); void setSymbolIdCoinapi(String symbolIdCoinapi); PositionData avgEntryPrice(BigDecimal avgEntryPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.00134444", value = "Calculated average price of all fills on this position.") BigDecimal getAvgEntryPrice(); void setAvgEntryPrice(BigDecimal avgEntryPrice); PositionData quantity(BigDecimal quantity); @javax.annotation.Nullable @ApiModelProperty(example = "7", value = "The current position quantity.") BigDecimal getQuantity(); void setQuantity(BigDecimal quantity); PositionData side(OrdSide side); @javax.annotation.Nullable @ApiModelProperty(value = "") OrdSide getSide(); void setSide(OrdSide side); PositionData unrealizedPnl(BigDecimal unrealizedPnl); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Unrealised profit or loss (PNL) of this position.") BigDecimal getUnrealizedPnl(); void setUnrealizedPnl(BigDecimal unrealizedPnl); PositionData leverage(BigDecimal leverage); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Leverage for this position reported by the exchange.") BigDecimal getLeverage(); void setLeverage(BigDecimal leverage); PositionData crossMargin(Boolean crossMargin); @javax.annotation.Nullable @ApiModelProperty(example = "true", value = "Is cross margin mode enable for this position?") Boolean getCrossMargin(); void setCrossMargin(Boolean crossMargin); PositionData liquidationPrice(BigDecimal liquidationPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.072323", value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") BigDecimal getLiquidationPrice(); void setLiquidationPrice(BigDecimal liquidationPrice); PositionData rawData(Object rawData); @javax.annotation.Nullable @ApiModelProperty(example = "Other information provided by the exchange on this position.", value = "") Object getRawData(); void setRawData(Object rawData); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_SYMBOL_ID_EXCHANGE; static final String SERIALIZED_NAME_SYMBOL_ID_COINAPI; static final String SERIALIZED_NAME_AVG_ENTRY_PRICE; static final String SERIALIZED_NAME_QUANTITY; static final String SERIALIZED_NAME_SIDE; static final String SERIALIZED_NAME_UNREALIZED_PNL; static final String SERIALIZED_NAME_LEVERAGE; static final String SERIALIZED_NAME_CROSS_MARGIN; static final String SERIALIZED_NAME_LIQUIDATION_PRICE; static final String SERIALIZED_NAME_RAW_DATA; }### Answer:
@Test public void avgEntryPriceTest() { }
|
### Question:
ValidationError { public ValidationError type(String type) { this.type = type; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer:
@Test public void typeTest() { }
|
### Question:
PositionData { public PositionData quantity(BigDecimal quantity) { this.quantity = quantity; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbolIdExchange); PositionData symbolIdCoinapi(String symbolIdCoinapi); @javax.annotation.Nullable @ApiModelProperty(example = "BITMEX_PERP_BTC_USD", value = "CoinAPI symbol.") String getSymbolIdCoinapi(); void setSymbolIdCoinapi(String symbolIdCoinapi); PositionData avgEntryPrice(BigDecimal avgEntryPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.00134444", value = "Calculated average price of all fills on this position.") BigDecimal getAvgEntryPrice(); void setAvgEntryPrice(BigDecimal avgEntryPrice); PositionData quantity(BigDecimal quantity); @javax.annotation.Nullable @ApiModelProperty(example = "7", value = "The current position quantity.") BigDecimal getQuantity(); void setQuantity(BigDecimal quantity); PositionData side(OrdSide side); @javax.annotation.Nullable @ApiModelProperty(value = "") OrdSide getSide(); void setSide(OrdSide side); PositionData unrealizedPnl(BigDecimal unrealizedPnl); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Unrealised profit or loss (PNL) of this position.") BigDecimal getUnrealizedPnl(); void setUnrealizedPnl(BigDecimal unrealizedPnl); PositionData leverage(BigDecimal leverage); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Leverage for this position reported by the exchange.") BigDecimal getLeverage(); void setLeverage(BigDecimal leverage); PositionData crossMargin(Boolean crossMargin); @javax.annotation.Nullable @ApiModelProperty(example = "true", value = "Is cross margin mode enable for this position?") Boolean getCrossMargin(); void setCrossMargin(Boolean crossMargin); PositionData liquidationPrice(BigDecimal liquidationPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.072323", value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") BigDecimal getLiquidationPrice(); void setLiquidationPrice(BigDecimal liquidationPrice); PositionData rawData(Object rawData); @javax.annotation.Nullable @ApiModelProperty(example = "Other information provided by the exchange on this position.", value = "") Object getRawData(); void setRawData(Object rawData); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_SYMBOL_ID_EXCHANGE; static final String SERIALIZED_NAME_SYMBOL_ID_COINAPI; static final String SERIALIZED_NAME_AVG_ENTRY_PRICE; static final String SERIALIZED_NAME_QUANTITY; static final String SERIALIZED_NAME_SIDE; static final String SERIALIZED_NAME_UNREALIZED_PNL; static final String SERIALIZED_NAME_LEVERAGE; static final String SERIALIZED_NAME_CROSS_MARGIN; static final String SERIALIZED_NAME_LIQUIDATION_PRICE; static final String SERIALIZED_NAME_RAW_DATA; }### Answer:
@Test public void quantityTest() { }
|
### Question:
PositionData { public PositionData side(OrdSide side) { this.side = side; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbolIdExchange); PositionData symbolIdCoinapi(String symbolIdCoinapi); @javax.annotation.Nullable @ApiModelProperty(example = "BITMEX_PERP_BTC_USD", value = "CoinAPI symbol.") String getSymbolIdCoinapi(); void setSymbolIdCoinapi(String symbolIdCoinapi); PositionData avgEntryPrice(BigDecimal avgEntryPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.00134444", value = "Calculated average price of all fills on this position.") BigDecimal getAvgEntryPrice(); void setAvgEntryPrice(BigDecimal avgEntryPrice); PositionData quantity(BigDecimal quantity); @javax.annotation.Nullable @ApiModelProperty(example = "7", value = "The current position quantity.") BigDecimal getQuantity(); void setQuantity(BigDecimal quantity); PositionData side(OrdSide side); @javax.annotation.Nullable @ApiModelProperty(value = "") OrdSide getSide(); void setSide(OrdSide side); PositionData unrealizedPnl(BigDecimal unrealizedPnl); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Unrealised profit or loss (PNL) of this position.") BigDecimal getUnrealizedPnl(); void setUnrealizedPnl(BigDecimal unrealizedPnl); PositionData leverage(BigDecimal leverage); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Leverage for this position reported by the exchange.") BigDecimal getLeverage(); void setLeverage(BigDecimal leverage); PositionData crossMargin(Boolean crossMargin); @javax.annotation.Nullable @ApiModelProperty(example = "true", value = "Is cross margin mode enable for this position?") Boolean getCrossMargin(); void setCrossMargin(Boolean crossMargin); PositionData liquidationPrice(BigDecimal liquidationPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.072323", value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") BigDecimal getLiquidationPrice(); void setLiquidationPrice(BigDecimal liquidationPrice); PositionData rawData(Object rawData); @javax.annotation.Nullable @ApiModelProperty(example = "Other information provided by the exchange on this position.", value = "") Object getRawData(); void setRawData(Object rawData); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_SYMBOL_ID_EXCHANGE; static final String SERIALIZED_NAME_SYMBOL_ID_COINAPI; static final String SERIALIZED_NAME_AVG_ENTRY_PRICE; static final String SERIALIZED_NAME_QUANTITY; static final String SERIALIZED_NAME_SIDE; static final String SERIALIZED_NAME_UNREALIZED_PNL; static final String SERIALIZED_NAME_LEVERAGE; static final String SERIALIZED_NAME_CROSS_MARGIN; static final String SERIALIZED_NAME_LIQUIDATION_PRICE; static final String SERIALIZED_NAME_RAW_DATA; }### Answer:
@Test public void sideTest() { }
|
### Question:
PositionData { public PositionData unrealizedPnl(BigDecimal unrealizedPnl) { this.unrealizedPnl = unrealizedPnl; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbolIdExchange); PositionData symbolIdCoinapi(String symbolIdCoinapi); @javax.annotation.Nullable @ApiModelProperty(example = "BITMEX_PERP_BTC_USD", value = "CoinAPI symbol.") String getSymbolIdCoinapi(); void setSymbolIdCoinapi(String symbolIdCoinapi); PositionData avgEntryPrice(BigDecimal avgEntryPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.00134444", value = "Calculated average price of all fills on this position.") BigDecimal getAvgEntryPrice(); void setAvgEntryPrice(BigDecimal avgEntryPrice); PositionData quantity(BigDecimal quantity); @javax.annotation.Nullable @ApiModelProperty(example = "7", value = "The current position quantity.") BigDecimal getQuantity(); void setQuantity(BigDecimal quantity); PositionData side(OrdSide side); @javax.annotation.Nullable @ApiModelProperty(value = "") OrdSide getSide(); void setSide(OrdSide side); PositionData unrealizedPnl(BigDecimal unrealizedPnl); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Unrealised profit or loss (PNL) of this position.") BigDecimal getUnrealizedPnl(); void setUnrealizedPnl(BigDecimal unrealizedPnl); PositionData leverage(BigDecimal leverage); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Leverage for this position reported by the exchange.") BigDecimal getLeverage(); void setLeverage(BigDecimal leverage); PositionData crossMargin(Boolean crossMargin); @javax.annotation.Nullable @ApiModelProperty(example = "true", value = "Is cross margin mode enable for this position?") Boolean getCrossMargin(); void setCrossMargin(Boolean crossMargin); PositionData liquidationPrice(BigDecimal liquidationPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.072323", value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") BigDecimal getLiquidationPrice(); void setLiquidationPrice(BigDecimal liquidationPrice); PositionData rawData(Object rawData); @javax.annotation.Nullable @ApiModelProperty(example = "Other information provided by the exchange on this position.", value = "") Object getRawData(); void setRawData(Object rawData); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_SYMBOL_ID_EXCHANGE; static final String SERIALIZED_NAME_SYMBOL_ID_COINAPI; static final String SERIALIZED_NAME_AVG_ENTRY_PRICE; static final String SERIALIZED_NAME_QUANTITY; static final String SERIALIZED_NAME_SIDE; static final String SERIALIZED_NAME_UNREALIZED_PNL; static final String SERIALIZED_NAME_LEVERAGE; static final String SERIALIZED_NAME_CROSS_MARGIN; static final String SERIALIZED_NAME_LIQUIDATION_PRICE; static final String SERIALIZED_NAME_RAW_DATA; }### Answer:
@Test public void unrealizedPnlTest() { }
|
### Question:
PositionData { public PositionData leverage(BigDecimal leverage) { this.leverage = leverage; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbolIdExchange); PositionData symbolIdCoinapi(String symbolIdCoinapi); @javax.annotation.Nullable @ApiModelProperty(example = "BITMEX_PERP_BTC_USD", value = "CoinAPI symbol.") String getSymbolIdCoinapi(); void setSymbolIdCoinapi(String symbolIdCoinapi); PositionData avgEntryPrice(BigDecimal avgEntryPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.00134444", value = "Calculated average price of all fills on this position.") BigDecimal getAvgEntryPrice(); void setAvgEntryPrice(BigDecimal avgEntryPrice); PositionData quantity(BigDecimal quantity); @javax.annotation.Nullable @ApiModelProperty(example = "7", value = "The current position quantity.") BigDecimal getQuantity(); void setQuantity(BigDecimal quantity); PositionData side(OrdSide side); @javax.annotation.Nullable @ApiModelProperty(value = "") OrdSide getSide(); void setSide(OrdSide side); PositionData unrealizedPnl(BigDecimal unrealizedPnl); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Unrealised profit or loss (PNL) of this position.") BigDecimal getUnrealizedPnl(); void setUnrealizedPnl(BigDecimal unrealizedPnl); PositionData leverage(BigDecimal leverage); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Leverage for this position reported by the exchange.") BigDecimal getLeverage(); void setLeverage(BigDecimal leverage); PositionData crossMargin(Boolean crossMargin); @javax.annotation.Nullable @ApiModelProperty(example = "true", value = "Is cross margin mode enable for this position?") Boolean getCrossMargin(); void setCrossMargin(Boolean crossMargin); PositionData liquidationPrice(BigDecimal liquidationPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.072323", value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") BigDecimal getLiquidationPrice(); void setLiquidationPrice(BigDecimal liquidationPrice); PositionData rawData(Object rawData); @javax.annotation.Nullable @ApiModelProperty(example = "Other information provided by the exchange on this position.", value = "") Object getRawData(); void setRawData(Object rawData); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_SYMBOL_ID_EXCHANGE; static final String SERIALIZED_NAME_SYMBOL_ID_COINAPI; static final String SERIALIZED_NAME_AVG_ENTRY_PRICE; static final String SERIALIZED_NAME_QUANTITY; static final String SERIALIZED_NAME_SIDE; static final String SERIALIZED_NAME_UNREALIZED_PNL; static final String SERIALIZED_NAME_LEVERAGE; static final String SERIALIZED_NAME_CROSS_MARGIN; static final String SERIALIZED_NAME_LIQUIDATION_PRICE; static final String SERIALIZED_NAME_RAW_DATA; }### Answer:
@Test public void leverageTest() { }
|
### Question:
PositionData { public PositionData crossMargin(Boolean crossMargin) { this.crossMargin = crossMargin; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbolIdExchange); PositionData symbolIdCoinapi(String symbolIdCoinapi); @javax.annotation.Nullable @ApiModelProperty(example = "BITMEX_PERP_BTC_USD", value = "CoinAPI symbol.") String getSymbolIdCoinapi(); void setSymbolIdCoinapi(String symbolIdCoinapi); PositionData avgEntryPrice(BigDecimal avgEntryPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.00134444", value = "Calculated average price of all fills on this position.") BigDecimal getAvgEntryPrice(); void setAvgEntryPrice(BigDecimal avgEntryPrice); PositionData quantity(BigDecimal quantity); @javax.annotation.Nullable @ApiModelProperty(example = "7", value = "The current position quantity.") BigDecimal getQuantity(); void setQuantity(BigDecimal quantity); PositionData side(OrdSide side); @javax.annotation.Nullable @ApiModelProperty(value = "") OrdSide getSide(); void setSide(OrdSide side); PositionData unrealizedPnl(BigDecimal unrealizedPnl); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Unrealised profit or loss (PNL) of this position.") BigDecimal getUnrealizedPnl(); void setUnrealizedPnl(BigDecimal unrealizedPnl); PositionData leverage(BigDecimal leverage); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Leverage for this position reported by the exchange.") BigDecimal getLeverage(); void setLeverage(BigDecimal leverage); PositionData crossMargin(Boolean crossMargin); @javax.annotation.Nullable @ApiModelProperty(example = "true", value = "Is cross margin mode enable for this position?") Boolean getCrossMargin(); void setCrossMargin(Boolean crossMargin); PositionData liquidationPrice(BigDecimal liquidationPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.072323", value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") BigDecimal getLiquidationPrice(); void setLiquidationPrice(BigDecimal liquidationPrice); PositionData rawData(Object rawData); @javax.annotation.Nullable @ApiModelProperty(example = "Other information provided by the exchange on this position.", value = "") Object getRawData(); void setRawData(Object rawData); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_SYMBOL_ID_EXCHANGE; static final String SERIALIZED_NAME_SYMBOL_ID_COINAPI; static final String SERIALIZED_NAME_AVG_ENTRY_PRICE; static final String SERIALIZED_NAME_QUANTITY; static final String SERIALIZED_NAME_SIDE; static final String SERIALIZED_NAME_UNREALIZED_PNL; static final String SERIALIZED_NAME_LEVERAGE; static final String SERIALIZED_NAME_CROSS_MARGIN; static final String SERIALIZED_NAME_LIQUIDATION_PRICE; static final String SERIALIZED_NAME_RAW_DATA; }### Answer:
@Test public void crossMarginTest() { }
|
### Question:
PositionData { public PositionData liquidationPrice(BigDecimal liquidationPrice) { this.liquidationPrice = liquidationPrice; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbolIdExchange); PositionData symbolIdCoinapi(String symbolIdCoinapi); @javax.annotation.Nullable @ApiModelProperty(example = "BITMEX_PERP_BTC_USD", value = "CoinAPI symbol.") String getSymbolIdCoinapi(); void setSymbolIdCoinapi(String symbolIdCoinapi); PositionData avgEntryPrice(BigDecimal avgEntryPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.00134444", value = "Calculated average price of all fills on this position.") BigDecimal getAvgEntryPrice(); void setAvgEntryPrice(BigDecimal avgEntryPrice); PositionData quantity(BigDecimal quantity); @javax.annotation.Nullable @ApiModelProperty(example = "7", value = "The current position quantity.") BigDecimal getQuantity(); void setQuantity(BigDecimal quantity); PositionData side(OrdSide side); @javax.annotation.Nullable @ApiModelProperty(value = "") OrdSide getSide(); void setSide(OrdSide side); PositionData unrealizedPnl(BigDecimal unrealizedPnl); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Unrealised profit or loss (PNL) of this position.") BigDecimal getUnrealizedPnl(); void setUnrealizedPnl(BigDecimal unrealizedPnl); PositionData leverage(BigDecimal leverage); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Leverage for this position reported by the exchange.") BigDecimal getLeverage(); void setLeverage(BigDecimal leverage); PositionData crossMargin(Boolean crossMargin); @javax.annotation.Nullable @ApiModelProperty(example = "true", value = "Is cross margin mode enable for this position?") Boolean getCrossMargin(); void setCrossMargin(Boolean crossMargin); PositionData liquidationPrice(BigDecimal liquidationPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.072323", value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") BigDecimal getLiquidationPrice(); void setLiquidationPrice(BigDecimal liquidationPrice); PositionData rawData(Object rawData); @javax.annotation.Nullable @ApiModelProperty(example = "Other information provided by the exchange on this position.", value = "") Object getRawData(); void setRawData(Object rawData); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_SYMBOL_ID_EXCHANGE; static final String SERIALIZED_NAME_SYMBOL_ID_COINAPI; static final String SERIALIZED_NAME_AVG_ENTRY_PRICE; static final String SERIALIZED_NAME_QUANTITY; static final String SERIALIZED_NAME_SIDE; static final String SERIALIZED_NAME_UNREALIZED_PNL; static final String SERIALIZED_NAME_LEVERAGE; static final String SERIALIZED_NAME_CROSS_MARGIN; static final String SERIALIZED_NAME_LIQUIDATION_PRICE; static final String SERIALIZED_NAME_RAW_DATA; }### Answer:
@Test public void liquidationPriceTest() { }
|
### Question:
PositionData { public PositionData rawData(Object rawData) { this.rawData = rawData; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbolIdExchange); PositionData symbolIdCoinapi(String symbolIdCoinapi); @javax.annotation.Nullable @ApiModelProperty(example = "BITMEX_PERP_BTC_USD", value = "CoinAPI symbol.") String getSymbolIdCoinapi(); void setSymbolIdCoinapi(String symbolIdCoinapi); PositionData avgEntryPrice(BigDecimal avgEntryPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.00134444", value = "Calculated average price of all fills on this position.") BigDecimal getAvgEntryPrice(); void setAvgEntryPrice(BigDecimal avgEntryPrice); PositionData quantity(BigDecimal quantity); @javax.annotation.Nullable @ApiModelProperty(example = "7", value = "The current position quantity.") BigDecimal getQuantity(); void setQuantity(BigDecimal quantity); PositionData side(OrdSide side); @javax.annotation.Nullable @ApiModelProperty(value = "") OrdSide getSide(); void setSide(OrdSide side); PositionData unrealizedPnl(BigDecimal unrealizedPnl); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Unrealised profit or loss (PNL) of this position.") BigDecimal getUnrealizedPnl(); void setUnrealizedPnl(BigDecimal unrealizedPnl); PositionData leverage(BigDecimal leverage); @javax.annotation.Nullable @ApiModelProperty(example = "0.0", value = "Leverage for this position reported by the exchange.") BigDecimal getLeverage(); void setLeverage(BigDecimal leverage); PositionData crossMargin(Boolean crossMargin); @javax.annotation.Nullable @ApiModelProperty(example = "true", value = "Is cross margin mode enable for this position?") Boolean getCrossMargin(); void setCrossMargin(Boolean crossMargin); PositionData liquidationPrice(BigDecimal liquidationPrice); @javax.annotation.Nullable @ApiModelProperty(example = "0.072323", value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") BigDecimal getLiquidationPrice(); void setLiquidationPrice(BigDecimal liquidationPrice); PositionData rawData(Object rawData); @javax.annotation.Nullable @ApiModelProperty(example = "Other information provided by the exchange on this position.", value = "") Object getRawData(); void setRawData(Object rawData); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_SYMBOL_ID_EXCHANGE; static final String SERIALIZED_NAME_SYMBOL_ID_COINAPI; static final String SERIALIZED_NAME_AVG_ENTRY_PRICE; static final String SERIALIZED_NAME_QUANTITY; static final String SERIALIZED_NAME_SIDE; static final String SERIALIZED_NAME_UNREALIZED_PNL; static final String SERIALIZED_NAME_LEVERAGE; static final String SERIALIZED_NAME_CROSS_MARGIN; static final String SERIALIZED_NAME_LIQUIDATION_PRICE; static final String SERIALIZED_NAME_RAW_DATA; }### Answer:
@Test public void rawDataTest() { }
|
### Question:
Position { public Position exchangeId(String exchangeId) { this.exchangeId = exchangeId; return this; } Position exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); Position data(List<PositionData> data); Position addDataItem(PositionData dataItem); @javax.annotation.Nullable @ApiModelProperty(value = "") List<PositionData> getData(); void setData(List<PositionData> data); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_DATA; }### Answer:
@Test public void exchangeIdTest() { }
|
### Question:
Position { public Position data(List<PositionData> data) { this.data = data; return this; } Position exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExchangeId(String exchangeId); Position data(List<PositionData> data); Position addDataItem(PositionData dataItem); @javax.annotation.Nullable @ApiModelProperty(value = "") List<PositionData> getData(); void setData(List<PositionData> data); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_EXCHANGE_ID; static final String SERIALIZED_NAME_DATA; }### Answer:
@Test public void dataTest() { }
|
### Question:
OrdersApi { public Message v1OrdersCancelAllPost(OrderCancelAllRequest orderCancelAllRequest) throws ApiException { ApiResponse<Message> localVarResp = v1OrdersCancelAllPostWithHttpInfo(orderCancelAllRequest); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1OrdersCancelAllPostCall(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback _callback); Message v1OrdersCancelAllPost(OrderCancelAllRequest orderCancelAllRequest); ApiResponse<Message> v1OrdersCancelAllPostWithHttpInfo(OrderCancelAllRequest orderCancelAllRequest); okhttp3.Call v1OrdersCancelAllPostAsync(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback<Message> _callback); okhttp3.Call v1OrdersCancelPostCall(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersCancelPost(OrderCancelSingleRequest orderCancelSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersCancelPostWithHttpInfo(OrderCancelSingleRequest orderCancelSingleRequest); okhttp3.Call v1OrdersCancelPostAsync(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersGetCall(String exchangeId, final ApiCallback _callback); List<OrderExecutionReport> v1OrdersGet(String exchangeId); ApiResponse<List<OrderExecutionReport>> v1OrdersGetWithHttpInfo(String exchangeId); okhttp3.Call v1OrdersGetAsync(String exchangeId, final ApiCallback<List<OrderExecutionReport>> _callback); okhttp3.Call v1OrdersPostCall(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersPost(OrderNewSingleRequest orderNewSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersPostWithHttpInfo(OrderNewSingleRequest orderNewSingleRequest); okhttp3.Call v1OrdersPostAsync(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersStatusClientOrderIdGetCall(String clientOrderId, final ApiCallback _callback); OrderExecutionReport v1OrdersStatusClientOrderIdGet(String clientOrderId); ApiResponse<OrderExecutionReport> v1OrdersStatusClientOrderIdGetWithHttpInfo(String clientOrderId); okhttp3.Call v1OrdersStatusClientOrderIdGetAsync(String clientOrderId, final ApiCallback<OrderExecutionReport> _callback); }### Answer:
@Test public void v1OrdersCancelAllPostTest() throws ApiException { OrderCancelAllRequest orderCancelAllRequest = null; Message response = api.v1OrdersCancelAllPost(orderCancelAllRequest); }
|
### Question:
ValidationError { public ValidationError title(String title) { this.title = title; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer:
@Test public void titleTest() { }
|
### Question:
OrdersApi { public OrderExecutionReport v1OrdersCancelPost(OrderCancelSingleRequest orderCancelSingleRequest) throws ApiException { ApiResponse<OrderExecutionReport> localVarResp = v1OrdersCancelPostWithHttpInfo(orderCancelSingleRequest); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1OrdersCancelAllPostCall(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback _callback); Message v1OrdersCancelAllPost(OrderCancelAllRequest orderCancelAllRequest); ApiResponse<Message> v1OrdersCancelAllPostWithHttpInfo(OrderCancelAllRequest orderCancelAllRequest); okhttp3.Call v1OrdersCancelAllPostAsync(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback<Message> _callback); okhttp3.Call v1OrdersCancelPostCall(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersCancelPost(OrderCancelSingleRequest orderCancelSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersCancelPostWithHttpInfo(OrderCancelSingleRequest orderCancelSingleRequest); okhttp3.Call v1OrdersCancelPostAsync(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersGetCall(String exchangeId, final ApiCallback _callback); List<OrderExecutionReport> v1OrdersGet(String exchangeId); ApiResponse<List<OrderExecutionReport>> v1OrdersGetWithHttpInfo(String exchangeId); okhttp3.Call v1OrdersGetAsync(String exchangeId, final ApiCallback<List<OrderExecutionReport>> _callback); okhttp3.Call v1OrdersPostCall(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersPost(OrderNewSingleRequest orderNewSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersPostWithHttpInfo(OrderNewSingleRequest orderNewSingleRequest); okhttp3.Call v1OrdersPostAsync(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersStatusClientOrderIdGetCall(String clientOrderId, final ApiCallback _callback); OrderExecutionReport v1OrdersStatusClientOrderIdGet(String clientOrderId); ApiResponse<OrderExecutionReport> v1OrdersStatusClientOrderIdGetWithHttpInfo(String clientOrderId); okhttp3.Call v1OrdersStatusClientOrderIdGetAsync(String clientOrderId, final ApiCallback<OrderExecutionReport> _callback); }### Answer:
@Test public void v1OrdersCancelPostTest() throws ApiException { OrderCancelSingleRequest orderCancelSingleRequest = null; OrderExecutionReport response = api.v1OrdersCancelPost(orderCancelSingleRequest); }
|
### Question:
OrdersApi { public List<OrderExecutionReport> v1OrdersGet(String exchangeId) throws ApiException { ApiResponse<List<OrderExecutionReport>> localVarResp = v1OrdersGetWithHttpInfo(exchangeId); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1OrdersCancelAllPostCall(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback _callback); Message v1OrdersCancelAllPost(OrderCancelAllRequest orderCancelAllRequest); ApiResponse<Message> v1OrdersCancelAllPostWithHttpInfo(OrderCancelAllRequest orderCancelAllRequest); okhttp3.Call v1OrdersCancelAllPostAsync(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback<Message> _callback); okhttp3.Call v1OrdersCancelPostCall(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersCancelPost(OrderCancelSingleRequest orderCancelSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersCancelPostWithHttpInfo(OrderCancelSingleRequest orderCancelSingleRequest); okhttp3.Call v1OrdersCancelPostAsync(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersGetCall(String exchangeId, final ApiCallback _callback); List<OrderExecutionReport> v1OrdersGet(String exchangeId); ApiResponse<List<OrderExecutionReport>> v1OrdersGetWithHttpInfo(String exchangeId); okhttp3.Call v1OrdersGetAsync(String exchangeId, final ApiCallback<List<OrderExecutionReport>> _callback); okhttp3.Call v1OrdersPostCall(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersPost(OrderNewSingleRequest orderNewSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersPostWithHttpInfo(OrderNewSingleRequest orderNewSingleRequest); okhttp3.Call v1OrdersPostAsync(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersStatusClientOrderIdGetCall(String clientOrderId, final ApiCallback _callback); OrderExecutionReport v1OrdersStatusClientOrderIdGet(String clientOrderId); ApiResponse<OrderExecutionReport> v1OrdersStatusClientOrderIdGetWithHttpInfo(String clientOrderId); okhttp3.Call v1OrdersStatusClientOrderIdGetAsync(String clientOrderId, final ApiCallback<OrderExecutionReport> _callback); }### Answer:
@Test public void v1OrdersGetTest() throws ApiException { String exchangeId = null; List<OrderExecutionReport> response = api.v1OrdersGet(exchangeId); }
|
### Question:
OrdersApi { public OrderExecutionReport v1OrdersPost(OrderNewSingleRequest orderNewSingleRequest) throws ApiException { ApiResponse<OrderExecutionReport> localVarResp = v1OrdersPostWithHttpInfo(orderNewSingleRequest); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1OrdersCancelAllPostCall(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback _callback); Message v1OrdersCancelAllPost(OrderCancelAllRequest orderCancelAllRequest); ApiResponse<Message> v1OrdersCancelAllPostWithHttpInfo(OrderCancelAllRequest orderCancelAllRequest); okhttp3.Call v1OrdersCancelAllPostAsync(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback<Message> _callback); okhttp3.Call v1OrdersCancelPostCall(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersCancelPost(OrderCancelSingleRequest orderCancelSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersCancelPostWithHttpInfo(OrderCancelSingleRequest orderCancelSingleRequest); okhttp3.Call v1OrdersCancelPostAsync(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersGetCall(String exchangeId, final ApiCallback _callback); List<OrderExecutionReport> v1OrdersGet(String exchangeId); ApiResponse<List<OrderExecutionReport>> v1OrdersGetWithHttpInfo(String exchangeId); okhttp3.Call v1OrdersGetAsync(String exchangeId, final ApiCallback<List<OrderExecutionReport>> _callback); okhttp3.Call v1OrdersPostCall(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersPost(OrderNewSingleRequest orderNewSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersPostWithHttpInfo(OrderNewSingleRequest orderNewSingleRequest); okhttp3.Call v1OrdersPostAsync(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersStatusClientOrderIdGetCall(String clientOrderId, final ApiCallback _callback); OrderExecutionReport v1OrdersStatusClientOrderIdGet(String clientOrderId); ApiResponse<OrderExecutionReport> v1OrdersStatusClientOrderIdGetWithHttpInfo(String clientOrderId); okhttp3.Call v1OrdersStatusClientOrderIdGetAsync(String clientOrderId, final ApiCallback<OrderExecutionReport> _callback); }### Answer:
@Test public void v1OrdersPostTest() throws ApiException { OrderNewSingleRequest orderNewSingleRequest = null; OrderExecutionReport response = api.v1OrdersPost(orderNewSingleRequest); }
|
### Question:
OrdersApi { public OrderExecutionReport v1OrdersStatusClientOrderIdGet(String clientOrderId) throws ApiException { ApiResponse<OrderExecutionReport> localVarResp = v1OrdersStatusClientOrderIdGetWithHttpInfo(clientOrderId); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1OrdersCancelAllPostCall(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback _callback); Message v1OrdersCancelAllPost(OrderCancelAllRequest orderCancelAllRequest); ApiResponse<Message> v1OrdersCancelAllPostWithHttpInfo(OrderCancelAllRequest orderCancelAllRequest); okhttp3.Call v1OrdersCancelAllPostAsync(OrderCancelAllRequest orderCancelAllRequest, final ApiCallback<Message> _callback); okhttp3.Call v1OrdersCancelPostCall(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersCancelPost(OrderCancelSingleRequest orderCancelSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersCancelPostWithHttpInfo(OrderCancelSingleRequest orderCancelSingleRequest); okhttp3.Call v1OrdersCancelPostAsync(OrderCancelSingleRequest orderCancelSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersGetCall(String exchangeId, final ApiCallback _callback); List<OrderExecutionReport> v1OrdersGet(String exchangeId); ApiResponse<List<OrderExecutionReport>> v1OrdersGetWithHttpInfo(String exchangeId); okhttp3.Call v1OrdersGetAsync(String exchangeId, final ApiCallback<List<OrderExecutionReport>> _callback); okhttp3.Call v1OrdersPostCall(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback _callback); OrderExecutionReport v1OrdersPost(OrderNewSingleRequest orderNewSingleRequest); ApiResponse<OrderExecutionReport> v1OrdersPostWithHttpInfo(OrderNewSingleRequest orderNewSingleRequest); okhttp3.Call v1OrdersPostAsync(OrderNewSingleRequest orderNewSingleRequest, final ApiCallback<OrderExecutionReport> _callback); okhttp3.Call v1OrdersStatusClientOrderIdGetCall(String clientOrderId, final ApiCallback _callback); OrderExecutionReport v1OrdersStatusClientOrderIdGet(String clientOrderId); ApiResponse<OrderExecutionReport> v1OrdersStatusClientOrderIdGetWithHttpInfo(String clientOrderId); okhttp3.Call v1OrdersStatusClientOrderIdGetAsync(String clientOrderId, final ApiCallback<OrderExecutionReport> _callback); }### Answer:
@Test public void v1OrdersStatusClientOrderIdGetTest() throws ApiException { String clientOrderId = null; OrderExecutionReport response = api.v1OrdersStatusClientOrderIdGet(clientOrderId); }
|
### Question:
BalancesApi { public List<Balance> v1BalancesGet(String exchangeId) throws ApiException { ApiResponse<List<Balance>> localVarResp = v1BalancesGetWithHttpInfo(exchangeId); return localVarResp.getData(); } BalancesApi(); BalancesApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1BalancesGetCall(String exchangeId, final ApiCallback _callback); List<Balance> v1BalancesGet(String exchangeId); ApiResponse<List<Balance>> v1BalancesGetWithHttpInfo(String exchangeId); okhttp3.Call v1BalancesGetAsync(String exchangeId, final ApiCallback<List<Balance>> _callback); }### Answer:
@Test public void v1BalancesGetTest() throws ApiException { String exchangeId = null; List<Balance> response = api.v1BalancesGet(exchangeId); }
|
### Question:
PositionsApi { public List<Position> v1PositionsGet(String exchangeId) throws ApiException { ApiResponse<List<Position>> localVarResp = v1PositionsGetWithHttpInfo(exchangeId); return localVarResp.getData(); } PositionsApi(); PositionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); okhttp3.Call v1PositionsGetCall(String exchangeId, final ApiCallback _callback); List<Position> v1PositionsGet(String exchangeId); ApiResponse<List<Position>> v1PositionsGetWithHttpInfo(String exchangeId); okhttp3.Call v1PositionsGetAsync(String exchangeId, final ApiCallback<List<Position>> _callback); }### Answer:
@Test public void v1PositionsGetTest() throws ApiException { String exchangeId = null; List<Position> response = api.v1PositionsGet(exchangeId); }
|
### Question:
ValidationError { public ValidationError status(BigDecimal status) { this.status = status; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer:
@Test public void statusTest() { }
|
### Question:
ValidationError { public ValidationError traceId(String traceId) { this.traceId = traceId; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationError title(String title); @javax.annotation.Nullable @ApiModelProperty(example = "One or more validation errors occurred.", value = "") String getTitle(); void setTitle(String title); ValidationError status(BigDecimal status); @javax.annotation.Nullable @ApiModelProperty(example = "400", value = "") BigDecimal getStatus(); void setStatus(BigDecimal status); ValidationError traceId(String traceId); @javax.annotation.Nullable @ApiModelProperty(example = "d200e8b5-4271a5461ce5342f", value = "") String getTraceId(); void setTraceId(String traceId); ValidationError errors(String errors); @javax.annotation.Nullable @ApiModelProperty(value = "") String getErrors(); void setErrors(String errors); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String SERIALIZED_NAME_TYPE; static final String SERIALIZED_NAME_TITLE; static final String SERIALIZED_NAME_STATUS; static final String SERIALIZED_NAME_TRACE_ID; static final String SERIALIZED_NAME_ERRORS; }### Answer:
@Test public void traceIdTest() { }
|
### Question:
RunListBuilder { public List<String> build() { return ImmutableList.copyOf(list); } RunListBuilder addRecipe(String recipe); RunListBuilder addRecipes(String... recipes); RunListBuilder addRole(String role); RunListBuilder addRoles(String... roles); List<String> build(); }### Answer:
@Test public void testNoneRecipe() { RunListBuilder options = new RunListBuilder(); assertEquals(options.build(), ImmutableList.<String> of()); }
|
### Question:
ChefApiErrorRetryHandler implements HttpRetryHandler { public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { if (command.getFailureCount() > retryCountLimit) return false; if (response.getStatusCode() == 400 && command.getCurrentRequest().getMethod().equals("PUT") && command.getCurrentRequest().getEndpoint().getPath().indexOf("sandboxes") != -1) { if (response.getPayload() != null) { String error = new String(closeClientButKeepContentStream(response)); if (error != null && error.indexOf("was not uploaded") != -1) { return backoffLimitedRetryHandler.shouldRetryRequest(command, response); } } } return false; } @Inject ChefApiErrorRetryHandler(BackoffLimitedRetryHandler backoffLimitedRetryHandler); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); }### Answer:
@Test public void test401DoesNotRetry() { HttpCommand command = createMock(HttpCommand.class); HttpResponse response = createMock(HttpResponse.class); BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class); expect(command.getFailureCount()).andReturn(0); expect(response.getStatusCode()).andReturn(401).atLeastOnce(); replay(response); replay(retry); replay(command); ChefApiErrorRetryHandler handler = new ChefApiErrorRetryHandler(retry); assert !handler.shouldRetryRequest(command, response); verify(retry); verify(command); verify(response); }
@Test public void test400DoesNotRetry() { HttpCommand command = createMock(HttpCommand.class); HttpResponse response = createMock(HttpResponse.class); BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class); expect(command.getFailureCount()).andReturn(0); expect(response.getStatusCode()).andReturn(401).atLeastOnce(); replay(response); replay(retry); replay(command); ChefApiErrorRetryHandler handler = new ChefApiErrorRetryHandler(retry); assert !handler.shouldRetryRequest(command, response); verify(retry); verify(command); verify(response); }
@Test public void testRetryOn400PutSandbox() { HttpCommand command = createMock(HttpCommand.class); BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class); HttpRequest request = HttpRequest.builder().method("PUT") .endpoint("https: .build(); HttpResponse response = HttpResponse .builder() .statusCode(400) .message("400 Bad Request") .payload( "{\"error\":[\"Cannot update sandbox bfd68d4052f44053b2e593a33b5e1cd5: checksum 9b7c23369f4b576451216c39f214af6c was not uploaded\"]}") .build(); expect(command.getFailureCount()).andReturn(0); expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); expect(retry.shouldRetryRequest(command, response)).andReturn(true); replay(retry); replay(command); ChefApiErrorRetryHandler handler = new ChefApiErrorRetryHandler(retry); assert handler.shouldRetryRequest(command, response); verify(retry); verify(command); }
|
### Question:
BaseChefService implements ChefService { @VisibleForTesting String buildBootstrapConfiguration(Iterable<String> runList, Optional<JsonBall> jsonAttributes) { checkNotNull(runList, "runList must not be null"); checkNotNull(jsonAttributes, "jsonAttributes must not be null"); Map<String, Object> bootstrapConfig = Maps.newHashMap(); bootstrapConfig.put("run_list", Lists.newArrayList(runList)); if (jsonAttributes.isPresent()) { Map<String, Object> attributes = json.fromJson(jsonAttributes.get().toString(), BootstrapConfigForGroup.BOOTSTRAP_CONFIG_TYPE); bootstrapConfig.putAll(attributes); } return json.toJson(bootstrapConfig); } @Inject protected BaseChefService(ChefContext chefContext, ChefApi api,
CleanupStaleNodesAndClients cleanupStaleNodesAndClients,
CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes,
DeleteAllNodesInList deleteAllNodesInList, ListNodes listNodes, DeleteAllClientsInList deleteAllClientsInList,
ListClients listClients, ListCookbookVersions listCookbookVersions,
UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode, Supplier<PrivateKey> privateKey,
@Named(CHEF_BOOTSTRAP_DATABAG) String databag, GroupToBootScript groupToBootScript,
BootstrapConfigForGroup bootstrapConfigForGroup, RunListForGroup runListForGroup,
ListEnvironments listEnvironments, Json json); @Override void cleanupStaleNodesAndClients(String prefix, int secondsStale); @Override Node createNodeAndPopulateAutomaticAttributes(String nodeName, Iterable<String> runList); @Override void deleteAllNodesInList(Iterable<String> names); @Override Iterable<? extends Node> listNodes(); @Override Iterable<? extends Node> listNodesMatching(Predicate<String> nodeNameSelector); @Override Iterable<? extends Node> listNodesNamed(Iterable<String> names); @Override void deleteAllClientsInList(Iterable<String> names); @Override Iterable<? extends Client> listClientsDetails(); @Override Iterable<? extends Client> listClientsDetailsMatching(Predicate<String> clientNameSelector); @Override Iterable<? extends Client> listClientsNamed(Iterable<String> names); @Override Iterable<? extends CookbookVersion> listCookbookVersions(); @Override Iterable<? extends CookbookVersion> listCookbookVersionsMatching(Predicate<String> cookbookNameSelector); @Override Iterable<? extends CookbookVersion> listCookbookVersionsNamed(Iterable<String> names); @Override void updateAutomaticAttributesOnNode(String nodeName); @Override ChefContext getContext(); @Override Statement createBootstrapScriptForGroup(String group); @Override @Deprecated void updateRunListForGroup(Iterable<String> runList, String group); @Override void updateBootstrapConfigForGroup(Iterable<String> runList, String group); @Override void updateBootstrapConfigForGroup(Iterable<String> runList, @Nullable JsonBall jsonAttributes, String group); @Override List<String> getRunListForGroup(String group); @Override JsonBall getBootstrapConfigForGroup(String group); @Override byte[] decrypt(InputSupplier<? extends InputStream> supplier); @Override byte[] encrypt(InputSupplier<? extends InputStream> supplier); @Override Iterable<? extends Environment> listEnvironments(); @Override Iterable<? extends Environment> listEnvironmentsMatching(Predicate<String> environmentNameSelector); @Override Iterable<? extends Environment> listEnvironmentsNamed(Iterable<String> names); }### Answer:
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "runList must not be null") public void testBuildBootstrapConfigurationWithNullRunlist() { chefService.buildBootstrapConfiguration(null, null); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "jsonAttributes must not be null") public void testBuildBootstrapConfigurationWithNullJsonAttributes() { chefService.buildBootstrapConfiguration(ImmutableList.<String> of(), null); }
|
### Question:
GroupToBootScript implements Function<String, Statement> { public Statement apply(String group) { checkNotNull(group, "group"); String validatorClientName = validatorName.get(); PrivateKey validatorKey = validatorCredential.get(); JsonBall bootstrapConfig = null; try { bootstrapConfig = bootstrapConfigForGroup.load(group); } catch (Exception e) { throw propagate(e); } String chefConfigDir = "{root}etc{fs}chef"; Statement createChefConfigDir = exec("{md} " + chefConfigDir); Statement createClientRb = appendFile(chefConfigDir + "{fs}client.rb", ImmutableList.of("require 'rubygems'", "require 'ohai'", "o = Ohai::System.new", "o.all_plugins", String.format("node_name \"%s-\" + o[:ipaddress]", group), "log_level :info", "log_location STDOUT", String.format("validation_client_name \"%s\"", validatorClientName), String.format("chef_server_url \"%s\"", endpoint.get()))); Statement createValidationPem = appendFile(chefConfigDir + "{fs}validation.pem", Splitter.on('\n').split(Pems.pem(validatorKey))); String chefBootFile = chefConfigDir + "{fs}first-boot.json"; Statement createFirstBoot = appendFile(chefBootFile, Collections.singleton(json.toJson(bootstrapConfig))); Statement runChef = exec("chef-client -j " + chefBootFile); return newStatementList(installChefGems, createChefConfigDir, createClientRb, createValidationPem, createFirstBoot, runChef); } @Inject GroupToBootScript(@Provider Supplier<URI> endpoint, Json json,
CacheLoader<String, ? extends JsonBall> bootstrapConfigForGroup,
@Named("installChefGems") Statement installChefGems, @Validator Optional<String> validatorName,
@Validator Optional<PrivateKey> validatorCredential); Statement apply(String group); }### Answer:
@Test(expectedExceptions = IllegalStateException.class) public void testMustHaveValidatorName() { GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create("http: CacheLoader.from(Functions.forMap(ImmutableMap.<String, DatabagItem> of())), installChefGems, Optional.<String> absent(), validatorCredential); fn.apply("foo"); }
@Test(expectedExceptions = IllegalStateException.class) public void testMustHaveValidatorCredential() { GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create("http: CacheLoader.from(Functions.forMap(ImmutableMap.<String, DatabagItem> of())), installChefGems, validatorName, Optional.<PrivateKey> absent()); fn.apply("foo"); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Key 'foo' not present in map") public void testMustHaveRunScriptsName() { GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create("http: CacheLoader.from(Functions.forMap(ImmutableMap.<String, DatabagItem> of())), installChefGems, validatorName, validatorCredential); fn.apply("foo"); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "null value in entry: foo=null") public void testMustHaveRunScriptsValue() { GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create("http: CacheLoader.from(Functions.forMap(ImmutableMap.<String, DatabagItem> of("foo", (DatabagItem) null))), installChefGems, validatorName, validatorCredential); fn.apply("foo"); }
|
### Question:
ParseErrorFromJsonOrReturnBody implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String content = returnStringIf200.apply(response); if (content == null) return null; return parse(content); } @Inject ParseErrorFromJsonOrReturnBody(ReturnStringIf2xx returnStringIf200); @Override String apply(HttpResponse response); String parse(String in); }### Answer:
@Test public void testApplyInputStreamDetails() throws UnknownHostException { InputStream is = Strings2 .toInputStream("{\"error\":[\"invalid tarball: tarball root must contain java-bytearray\"]}"); ParseErrorFromJsonOrReturnBody parser = new ParseErrorFromJsonOrReturnBody(new ReturnStringIf2xx()); String response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build()); assertEquals(response, "invalid tarball: tarball root must contain java-bytearray"); }
|
### Question:
BootstrapConfigForGroup implements Function<String, DatabagItem> { @Override public DatabagItem apply(String from) { DatabagItem bootstrapConfig = api.getDatabagItem(databag, from); checkState(bootstrapConfig != null, "databag item %s/%s not found", databag, from); return bootstrapConfig; } @Inject BootstrapConfigForGroup(@Named(CHEF_BOOTSTRAP_DATABAG) String databag, ChefApi api); @Override DatabagItem apply(String from); static final Type BOOTSTRAP_CONFIG_TYPE; }### Answer:
@Test(expectedExceptions = IllegalStateException.class) public void testWhenNoDatabagItem() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Client client = createMock(Client.class); BootstrapConfigForGroup fn = new BootstrapConfigForGroup("jclouds", chefApi); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(null); replay(client); replay(chefApi); fn.apply("foo"); verify(client); verify(chefApi); }
@Test public void testReturnsItem() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Api api = createMock(Api.class); BootstrapConfigForGroup fn = new BootstrapConfigForGroup("jclouds", chefApi); DatabagItem config = new DatabagItem("foo", "{\"tomcat6\":{\"ssl_port\":8433},\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}"); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(config); replay(api); replay(chefApi); assertEquals(fn.apply("foo"), config); verify(api); verify(chefApi); }
|
### Question:
RunListForGroup implements Function<String, List<String>> { @Override public List<String> apply(String from) { DatabagItem bootstrapConfig = bootstrapConfigForGroup.apply(from); Map<String, JsonBall> config = json.fromJson(bootstrapConfig.toString(), BootstrapConfigForGroup.BOOTSTRAP_CONFIG_TYPE); JsonBall runlist = config.get("run_list"); return json.fromJson(runlist.toString(), RUN_LIST_TYPE); } @Inject RunListForGroup(BootstrapConfigForGroup bootstrapConfigForGroup, Json json); @Override List<String> apply(String from); static final Type RUN_LIST_TYPE; }### Answer:
@Test(expectedExceptions = IllegalStateException.class) public void testWhenNoDatabagItem() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Client client = createMock(Client.class); RunListForGroup fn = new RunListForGroup(new BootstrapConfigForGroup("jclouds", chefApi), json); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(null); replay(client); replay(chefApi); fn.apply("foo"); verify(client); verify(chefApi); }
@Test public void testReadRunList() throws IOException { ChefApi chefApi = createMock(ChefApi.class); Api api = createMock(Api.class); RunListForGroup fn = new RunListForGroup(new BootstrapConfigForGroup("jclouds", chefApi), json); DatabagItem config = new DatabagItem("foo", "{\"tomcat6\":{\"ssl_port\":8433},\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}"); expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(config); replay(api); replay(chefApi); assertEquals(fn.apply("foo"), ImmutableList.of("recipe[apache2]", "role[webserver]")); verify(api); verify(chefApi); }
|
### Question:
SignedHeaderAuth implements HttpRequestFilter { @VisibleForTesting String canonicalPath(String path) { path = path.replaceAll("\\/+", "/"); return path.endsWith("/") && path.length() > 1 ? path.substring(0, path.length() - 1) : path; } @Inject SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils); HttpRequest filter(HttpRequest input); String createStringToSign(String request, String hashedPath, String contentHash, String timestamp); String sign(String toSign); static final String SIGNING_DESCRIPTION; }### Answer:
@Test void canonicalizedPathRemovesMultipleSlashes() { assertEquals(signing_obj.canonicalPath(" }
@Test void canonicalizedPathRemovesTrailingSlash() { assertEquals(signing_obj.canonicalPath("/path/"), "/path"); }
|
### Question:
SignedHeaderAuth implements HttpRequestFilter { public HttpRequest filter(HttpRequest input) throws HttpException { HttpRequest request = input.toBuilder().endpoint(input.getEndpoint().toString().replace("%3F", "?")).build(); String contentHash = hashBody(request.getPayload()); Multimap<String, String> headers = ArrayListMultimap.create(); headers.put("X-Ops-Content-Hash", contentHash); String timestamp = timeStampProvider.get(); String toSign = createStringToSign(request.getMethod(), hashPath(request.getEndpoint().getPath()), contentHash, timestamp); headers.put("X-Ops-Userid", creds.get().identity); headers.put("X-Ops-Sign", SIGNING_DESCRIPTION); request = calculateAndReplaceAuthorizationHeaders(request, toSign); headers.put("X-Ops-Timestamp", timestamp); utils.logRequest(signatureLog, request, "<<"); return request.toBuilder().replaceHeaders(headers).build(); } @Inject SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils); HttpRequest filter(HttpRequest input); String createStringToSign(String request, String hashedPath, String contentHash, String timestamp); String sign(String toSign); static final String SIGNING_DESCRIPTION; }### Answer:
@Test void shouldGenerateTheCorrectStringToSignAndSignatureWithNoBody() { HttpRequest request = HttpRequest.builder().method(HttpMethod.DELETE).endpoint("http: .build(); request = signing_obj.filter(request); Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders()); assertEqualsNoOrder(headersWithoutContentLength.entries().toArray(), EXPECTED_SIGN_RESULT_EMPTY.entries() .toArray()); }
@Test void shouldNotChokeWhenSigningARequestForAResourceWithALongName() { StringBuilder path = new StringBuilder("nodes/"); for (int i = 0; i < 100; i++) path.append('A'); HttpRequest request = HttpRequest.builder().method(HttpMethod.PUT) .endpoint("http: signing_obj.filter(request); }
@Test void shouldReplacePercentage3FWithQuestionMarkAtUrl() { StringBuilder path = new StringBuilder("nodes/"); path.append("test/cookbooks/myCookBook%3Fnum_versions=5"); HttpRequest request = HttpRequest.builder().method(HttpMethod.GET) .endpoint("http: request = signing_obj.filter(request); assertTrue(request.getRequestLine().contains("?num_versions=5")); }
|
### Question:
BindGroupToUpdateRequestJsonPayload extends BindToJsonPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { checkArgument(checkNotNull(payload, "payload") instanceof Group, "this binder is only valid for Group objects"); GroupUpdateRequest updateGroup = new GroupUpdateRequest((Group) payload); return super.bindToRequest(request, updateGroup); } @Inject BindGroupToUpdateRequestJsonPayload(Json jsonBinder); @Override R bindToRequest(R request, Object payload); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http: binder.bindToRequest(request, null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidTypeInput() { HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http: binder.bindToRequest(request, new Object()); }
|
### Question:
BindGroupNameToJsonPayload extends BindToStringPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { super.bindToRequest(request, String.format("{\"groupname\":\"%s\"}", checkNotNull(payload, "payload"))); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); return request; } @Override R bindToRequest(R request, Object payload); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { BindGroupNameToJsonPayload binder = new BindGroupNameToJsonPayload(); HttpRequest request = HttpRequest.builder().method("POST").endpoint(URI.create("http: binder.bindToRequest(request, null); }
|
### Question:
GroupName implements Function<Object, String> { @Override public String apply(Object from) { return ((Group) checkNotNull(from, "from")).getGroupname(); } @Override String apply(Object from); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { new GroupName().apply(null); }
|
### Question:
CreateNodeAndPopulateAutomaticAttributesImpl implements CreateNodeAndPopulateAutomaticAttributes { @Override public Node execute(Node node) { logger.trace("creating node %s", node.getName()); node.getAutomatic().putAll(automaticSupplier.get()); chef.createNode(node); logger.debug("created node %s", node.getName()); return node; } @Inject CreateNodeAndPopulateAutomaticAttributesImpl(ChefApi chef,
@Automatic Supplier<Map<String, JsonBall>> automaticSupplier); @Override Node execute(Node node); @Override Node execute(String nodeName, Iterable<String> runList); }### Answer:
@Test public void testWithNoRunlist() { ChefApi chef = createMock(ChefApi.class); Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of(); Node node = new Node("name", ImmutableSet.<String> of(), "_default"); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); Node nodeWithAutomatic = new Node("name", ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), automatic, ImmutableSet.<String> of(), "_default"); node.getAutomatic().putAll(automaticSupplier.get()); chef.createNode(nodeWithAutomatic); replay(chef); CreateNodeAndPopulateAutomaticAttributesImpl updater = new CreateNodeAndPopulateAutomaticAttributesImpl(chef, automaticSupplier); updater.execute("name", ImmutableSet.<String> of()); verify(chef); }
|
### Question:
UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttributesOnNode { @Override public void execute(String nodeName) { logger.trace("updating node %s", nodeName); Node node = chef.getNode(nodeName); Node mutable = new Node(node.getName(), node.getNormal(), node.getOverride(), node.getDefault(), automaticSupplier.get(), node.getRunList(), node.getChefEnvironment()); chef.updateNode(mutable); logger.debug("updated node %s", nodeName); } @Inject UpdateAutomaticAttributesOnNodeImpl(ChefApi chef, @Automatic Supplier<Map<String, JsonBall>> automaticSupplier); @Override void execute(String nodeName); }### Answer:
@Test public void test() { ChefApi chef = createMock(ChefApi.class); Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of(); Node node = new Node("name", ImmutableSet.<String> of(), "_default"); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); Node nodeWithAutomatic = new Node("name", ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), automatic, ImmutableSet.<String> of(), "_default"); expect(chef.getNode("name")).andReturn(node); node.getAutomatic().putAll(automaticSupplier.get()); expect(chef.updateNode(nodeWithAutomatic)).andReturn(null); replay(chef); UpdateAutomaticAttributesOnNodeImpl updater = new UpdateAutomaticAttributesOnNodeImpl(chef, automaticSupplier); updater.execute("name"); verify(chef); }
|
### Question:
ChefUtils { public static String findRoleInRunList(List<String> runList) { final Pattern pattern = Pattern.compile("^role\\[(.*)\\]$"); String roleToParse = Iterables.find(runList, new Predicate<String>() { @Override public boolean apply(String input) { return pattern.matcher(input).matches(); } }); Matcher matcher = pattern.matcher(roleToParse); matcher.find(); return matcher.group(1); } static Date fromOhaiTime(JsonBall ohaiDate); static JsonBall toOhaiTime(long millis); static MapBinder<String, Supplier<JsonBall>> ohaiAutomaticAttributeBinder(Binder binder); static String findRoleInRunList(List<String> runList); }### Answer:
@Test(expectedExceptions = NoSuchElementException.class) public void testFindRoleInRunListThrowsNoSuchElementOnRecipe() { ChefUtils.findRoleInRunList(ImmutableList.of("recipe[java]")); }
|
### Question:
Extension implements FREExtension { @Override public FREContext createContext(String extId) { Logger.log("Create Context"); return LocalNotificationsContext.getInstance(); } @Override FREContext createContext(String extId); @Override void initialize(); @Override void dispose(); }### Answer:
@Test public void extension_createContext_returnsContext() { PowerMockito.mockStatic(LocalNotificationsContext.class); when(LocalNotificationsContext.getInstance()).thenReturn(context); assertSame(context, getSubject().createContext("anyId")); }
|
### Question:
SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }### Answer:
@Test public void settings_getSoundUri_returnsNullIfBundleDoesNotPlaySoundAndDoesNotHaveSoundName() { assertNull(getSubject().getSoundUri()); }
@Test public void settings_getSoundUri_returnsUriIfBundlePlaysSoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); NotificationSoundProvider.CONTENT_URI = "content: assertNotNull(getSubject().getSoundUri()); verifyStatic(Uri.class); Uri.parse("content: }
@Test public void settings_getSoundUri_returnsNullIfBundlePlaysSoundAndDoesNotHaveSoundName() { when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertNull(getSubject().getSoundUri()); when(bundle.getString(Constants.SOUND_NAME)).thenReturn(""); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertNull(getSubject().getSoundUri()); }
@Test public void settings_getSoundUri_returnsNullIfBundleDoesNotPlaySoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); assertNull(getSubject().getSoundUri()); }
|
### Question:
SoundSettings { public int getSoundDefault() { return shouldPlayDefaultSound()? Notification.DEFAULT_SOUND : 0; } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }### Answer:
@Test public void settings_getSoundDefault_returnsZeroIfBundlePlaysSoundAndDoesNotHaveSoundName() { when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertEquals(Notification.DEFAULT_SOUND, getSubject().getSoundDefault()); }
@Test public void settings_getSoundDefault_returnsZeroIfBundlePlaysSoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(true); assertEquals(0, getSubject().getSoundDefault()); }
@Test public void settings_getSoundDefault_returnsZeroIfBundleDoesNotPlaySoundAndHasSoundName() { when(bundle.getString(Constants.SOUND_NAME)).thenReturn("sound.mp3"); when(bundle.getBoolean(Constants.PLAY_SOUND)).thenReturn(false); assertEquals(0, getSubject().getSoundDefault()); }
@Test public void settings_getSoundDefault_returnsZeroIfBundleDoesNotPlaySoundAndDoesNotHaveSoundName() { assertEquals(0, getSubject().getSoundDefault()); }
|
### Question:
Application extends android.app.Application { @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(new LifecycleCallbacks()); } @Override void onCreate(); }### Answer:
@Test public void application_addsCallbacks_onCreate() { getSubject().onCreate(); verify(getSubject()).registerActivityLifecycleCallbacks(callbacks); }
|
### Question:
LocalNotification implements ISerializable, IDeserializable { @SuppressWarnings("WeakerAccess") public long getRepeatIntervalMilliseconds() { return new LocalNotificationTimeInterval(repeatInterval) .toMilliseconds(); } LocalNotification(); LocalNotification(String activityClassName); @SuppressWarnings("WeakerAccess") long getRepeatIntervalMilliseconds(); boolean repeatsRecurrently(); JSONObject serialize(); void deserialize(JSONObject jsonObject); public String code; public String tickerText; public String title; public String body; public boolean isExact; public boolean allowWhileIdle; public boolean playSound; public boolean vibrate; public int iconResourceId; public int numberAnnotation; public boolean cancelOnSelect; public boolean ongoing; public String alertPolicy; public String soundName; public boolean hasAction; public byte[] actionData; public Date fireDate; public int repeatInterval; public int priority; public boolean showInForeground; public String activityClassName; public String category; }### Answer:
@Test public void notification_getRepeatIntervalMilliseconds_returnsTimeInMilliseconds() { LocalNotificationTimeInterval intervalMock = mock(LocalNotificationTimeInterval.class); try { PowerMockito.whenNew(LocalNotificationTimeInterval.class) .withArguments(10) .thenReturn(intervalMock); } catch (Throwable e) { e.printStackTrace(); } when(intervalMock.toMilliseconds()).thenReturn(20000L); getSubject().repeatInterval = 10; assertEquals(getSubject().getRepeatIntervalMilliseconds(), 20000L); }
|
### Question:
LocalNotification implements ISerializable, IDeserializable { public boolean repeatsRecurrently() { return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT || isExact) && repeatInterval != 0; } LocalNotification(); LocalNotification(String activityClassName); @SuppressWarnings("WeakerAccess") long getRepeatIntervalMilliseconds(); boolean repeatsRecurrently(); JSONObject serialize(); void deserialize(JSONObject jsonObject); public String code; public String tickerText; public String title; public String body; public boolean isExact; public boolean allowWhileIdle; public boolean playSound; public boolean vibrate; public int iconResourceId; public int numberAnnotation; public boolean cancelOnSelect; public boolean ongoing; public String alertPolicy; public String soundName; public boolean hasAction; public byte[] actionData; public Date fireDate; public int repeatInterval; public int priority; public boolean showInForeground; public String activityClassName; public String category; }### Answer:
@Test public void notification_repeatsRecurrently_returnsTrueIfHasRepeatInterval_afterKitKat() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT); getSubject().repeatInterval = 10; getSubject().isExact = false; assertTrue(getSubject().repeatsRecurrently()); }
@Test public void notification_repeatsRecurrently_returnsTrueIfHasRepeatIntervalAndIsExact() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT - 1); getSubject().repeatInterval = 10; getSubject().isExact = true; assertTrue(getSubject().repeatsRecurrently()); }
@Test public void notification_repeatsRecurrently_returnsFalseIfDoesNotHaveRepeatInterval() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT); getSubject().repeatInterval = 0; getSubject().isExact = true; assertFalse(getSubject().repeatsRecurrently()); }
@Test public void notification_repeatsRecurrently_returnsFalseIfNonExact_beforeKitKat() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT - 1); getSubject().repeatInterval = 10; getSubject().isExact = false; assertFalse(getSubject().repeatsRecurrently()); }
|
### Question:
LocalNotificationsContext extends FREContext { void dispatchNotificationSelectedEvent() { LocalNotificationCache.getInstance().reset(); dispatchStatusEventAsync(NOTIFICATION_SELECTED, STATUS); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_dispatchNotificationSelectedEvent_dispatchesEvent() { getSubject().dispatchNotificationSelectedEvent(); verify(getSubject()).dispatchStatusEventAsync("notificationSelected", "status"); }
|
### Question:
LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_functions_getSelectedNotificationData() { byte[] data = {}; PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(ExtensionUtils.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getNotificationData()).thenReturn(data); when(ExtensionUtils.getFreObject(data)).thenReturn(freObject); assertSame(freObject, callFunction("getSelectedNotificationData")); }
@Test public void context_functions_getSelectedNotificationCode() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getNotificationCode()).thenReturn("Code"); try { when(FREObject.newObject("Code")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationCode")); }
@Test public void context_functions_getSelectedActionId() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getActionId()).thenReturn("ActionId"); try { when(FREObject.newObject("ActionId")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationAction")); }
@Test public void context_functions_getSelectedUserResponse() { PowerMockito.mockStatic(LocalNotificationCache.class); PowerMockito.mockStatic(FREObject.class); when(LocalNotificationCache.getInstance()).thenReturn(cache); when(cache.getUserResponse()).thenReturn("User Response"); try { when(FREObject.newObject("User Response")).thenReturn(freObject); } catch (Throwable e) { e.printStackTrace(); } assertSame(freObject, callFunction("getSelectedNotificationUserResponse")); }
@Test public void context_functions_checkForNotificationAction_whenCacheWasUpdated() { byte data[] = {}; LocalNotificationCache.getInstance().reset(); LocalNotificationCache.getInstance().setData("MyCode", data, "actionId", "User Response"); callFunction("checkForNotificationAction"); verify(getSubject()).dispatchStatusEventAsync("notificationSelected", "status"); }
@Test public void context_functions_checkForNotificationAction_whenCacheWasNotUpdated() { LocalNotificationCache.getInstance().reset(); callFunction("checkForNotificationAction"); verify(getSubject(), never()).dispatchStatusEventAsync("notificationSelected", "status"); }
@Test public void context_functions_checkForNotificationAction_dispatchesOnlyOnce() { byte data[] = {}; LocalNotificationCache.getInstance().reset(); LocalNotificationCache.getInstance().setData("MyCode", data, "actionId", "User Response"); callFunction("checkForNotificationAction"); callFunction("checkForNotificationAction"); verify(getSubject(), times(1)).dispatchStatusEventAsync("notificationSelected", "status"); }
|
### Question:
LocalNotificationsContext extends FREContext { private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_functions_cancel() { try { when(arg1.getAsString()).thenReturn("MyID"); } catch (Throwable e) { e.printStackTrace(); } callFunction("cancel"); verify(manager).cancel("MyID"); verify(persistenceManager).removeNotification("MyID"); }
|
### Question:
LocalNotificationsContext extends FREContext { private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_functions_cancelAll() { callFunction("cancelAll"); verify(manager).cancelAll(); verify(persistenceManager).clearNotifications(); }
|
### Question:
LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SETTINGS_SUBSCRIBED; }### Answer:
@Test public void context_functions_activate_legacy() { when(activity.getApplication()).thenReturn(legacyApplication); ApplicationStatus.setInForeground(false); callFunction("activate"); assertTrue(ApplicationStatus.getInForeground()); }
@Test public void context_functions_deactivate_legacy() { when(activity.getApplication()).thenReturn(legacyApplication); ApplicationStatus.setInForeground(true); callFunction("deactivate"); assertFalse(ApplicationStatus.getInForeground()); }
@Test public void context_functions_activate() { ApplicationStatus.setInForeground(false); callFunction("activate"); assertFalse(ApplicationStatus.getInForeground()); }
@Test public void context_functions_deactivate() { ApplicationStatus.setInForeground(true); callFunction("deactivate"); assertTrue(ApplicationStatus.getInForeground()); }
|
### Question:
LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }### Answer:
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsNotActive() { getSubject().dispatchWhenInForeground(); assertCache(); }
@Test public void dispatcher_dispatchInForeground_doesNotDispatchesIfAppIsNotActive() { getSubject().dispatchWhenInForeground(); verify(context, never()).dispatchNotificationSelectedEvent(); }
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsInBackground() { ApplicationStatus.setInForeground(true); ApplicationStatus.setInForeground(false); getSubject().dispatchWhenInForeground(); assertCache(); }
@Test public void dispatcher_dispatchInForeground_doesNotDispatchesIfAppIsInBackground() { ApplicationStatus.reset(); getSubject().dispatchWhenInForeground(); verify(context, never()).dispatchNotificationSelectedEvent(); }
@Test public void dispatcher_dispatchInForeground_setsCacheIfAppIsInForeground() { ApplicationStatus.setInForeground(true); getSubject().dispatchWhenInForeground(); assertCache(); }
@Test public void dispatcher_dispatchInForeground_dispatchesIfAppIsInForeground() { ApplicationStatus.setInForeground(true); getSubject().dispatchWhenInForeground(); verify(context).dispatchNotificationSelectedEvent(); }
|
### Question:
LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static int DAY_CALENDAR_UNIT; final static int HOUR_CALENDAR_UNIT; final static int MINUTE_CALENDAR_UNIT; final static int SECOND_CALENDAR_UNIT; final static int MILLISECOND_CALENDAR_UNIT; final static int WEEK_CALENDAR_UNIT; final static int QUARTER_CALENDAR_UNIT; }### Answer:
@Test public void notificationTimeInterval_yearInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 365, getSubject(LocalNotificationTimeInterval.YEAR_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_monthInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 30, getSubject(LocalNotificationTimeInterval.MONTH_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_dayInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60 * 24, getSubject(LocalNotificationTimeInterval.DAY_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_hourInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60, getSubject(LocalNotificationTimeInterval.HOUR_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_minuteInterval_toMilliseconds() { assertEquals( 1000 * 60, getSubject(LocalNotificationTimeInterval.MINUTE_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_secondInterval_toMilliseconds() { assertEquals( 1000, getSubject(LocalNotificationTimeInterval.SECOND_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_weekInterval_toMilliseconds() { assertEquals( 1000 * 60 * 60 * 24 * 7, getSubject(LocalNotificationTimeInterval.WEEK_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_quarterInterval_toMilliseconds() { assertEquals( (long)1000 * 60 * 60 * 24 * 91, getSubject(LocalNotificationTimeInterval.QUARTER_CALENDAR_UNIT).toMilliseconds() ); }
@Test public void notificationTimeInterval_unkownIntervalInterval_returnsZeroMilliseconds() { assertEquals(0, getSubject(1 << 20).toMilliseconds()); }
@Test public void notificationTimeInterval_toMillisecondsWithParameter_multipliesIntervalByParameter() { assertEquals( 4000, getSubject(LocalNotificationTimeInterval.SECOND_CALENDAR_UNIT).toMilliseconds(4) ); }
|
### Question:
AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String> notificationIds = persistenceManager.readNotificationKeys(); final LocalNotificationManager manager = new LocalNotificationManager(context); Date now = new Date(); for (String notificationId : notificationIds) { try { LocalNotification notification = persistenceManager.readNotification(notificationId); if (notification == null) continue; long nextTime = new NextNotificationCalculator(notification).getTime(now); if (nextTime >= now.getTime()) { manager.notify(notification); } else { persistenceManager.removeNotification(notification.code); } } catch (Exception e) { Logger.log("AlarmRestoreOnBoot: Error while restoring alarm details after reboot: " + e.toString()); } Logger.log("AlarmRestoreOnBoot: Successfully restored alarms upon reboot"); } } @Override void onReceive(Context context, Intent intent); }### Answer:
@Test public void provider_onReceive_doesNothing_ifNotRightPermission() { when(intent.getAction()).thenReturn("any.other.permission"); getSubject().onReceive(context, intent); verify(persistenceManager, never()).readNotificationKeys(); }
@Test public void provider_onReceive_notifiesEventsInTheFuture() { initNotifications(); getSubject().onReceive(context, intent); verify(notificationManager).notify(notification1); }
@Test public void provider_onReceive_removesEventsInThePast() { initNotifications(); getSubject().onReceive(context, intent); verify(persistenceManager).removeNotification("NOTIF2"); }
|
### Question:
TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); LocalNotification localNotification = persistenceManager.readNotification(code); Intent notificationIntent = new NotificationRequestIntentFactory(context) .createIntent(localNotification) .setClass(context, LocalNotificationIntentService.class) .putExtra(Constants.VIBRATE, false) .putExtra(Constants.PLAY_SOUND, false) .putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT) .putExtras(intent.getExtras()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Bundle bundle = RemoteInput.getResultsFromIntent(intent); String userResponse = bundle.getString(Constants.USER_RESPONSE_KEY); notificationIntent.putExtra(Constants.USER_RESPONSE_KEY, userResponse); } context.startService(notificationIntent); } @SuppressWarnings("ConstantConditions") @Override void onReceive(Context context, Intent intent); }### Answer:
@Test public void service_onReceive_startsService() { getSubject().onReceive(context, intent); verify(notificationIntent).setClass(context, LocalNotificationIntentService.class); verify(context).startService(notificationIntent); }
@Test public void service_onReceive_tonesDownNotificationService() { getSubject().onReceive(context, intent); verify(notificationIntent).putExtra(Constants.VIBRATE, false); verify(notificationIntent).putExtra(Constants.PLAY_SOUND, false); verify(notificationIntent).putExtra(Constants.PRIORITY, Notification.PRIORITY_DEFAULT); }
@Test public void service_onReceive_mergesIntentIntoNotificationIntent() { getSubject().onReceive(context, intent); verify(notificationIntent).putExtras(bundle); }
@Test public void service_onReceive_onLessThanNougat_doesNotMergeIntentIntoNotificationIntent() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.N - 1); getSubject().onReceive(context, intent); verify(notificationIntent, never()).putExtra(eq(Constants.USER_RESPONSE_KEY), anyString()); }
@Test public void service_onReceive_noNougatOrHigher_mergesUserResponseIntoNotificationIntent() { Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.N); Bundle resultsBundle = mock(Bundle.class); PowerMockito.mockStatic(RemoteInput.class); when(RemoteInput.getResultsFromIntent(intent)).thenReturn(resultsBundle); when(resultsBundle.getString(Constants.USER_RESPONSE_KEY)).thenReturn("User Response"); getSubject().onReceive(context, intent); verify(notificationIntent).putExtra(Constants.USER_RESPONSE_KEY, "User Response"); }
|
### Question:
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }### Answer:
@Test public void callbacks_setAppInForeground_whenActivityStarted() { ApplicationStatus.setInForeground(false); getSubject().onActivityStarted(null); assertTrue(ApplicationStatus.getInForeground()); }
|
### Question:
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }### Answer:
@Test public void callbacks_setAppInForeground_whenActivityStopped() { ApplicationStatus.setInForeground(true); getSubject().onActivityStopped(null); assertFalse(ApplicationStatus.getInForeground()); }
|
### Question:
LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivitySaveInstanceState(Activity activity, Bundle bundle); @Override void onActivityDestroyed(Activity activity); }### Answer:
@Test public void callbacks_doesNothing_whenNullIntent() { when(activity.getIntent()).thenReturn(null); getSubject().onActivityCreated(activity, null); verify(activity, never()).moveTaskToBack(true); }
@Test public void callbacks_doesNothing_whenNotInBackgroundMode() { when(activity.getIntent()).thenReturn(intent); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(false); getSubject().onActivityCreated(activity, null); verify(activity, never()).moveTaskToBack(true); }
@Test public void callbacks_hideActivity_whenInBackgroundMode() { when(activity.getIntent()).thenReturn(intent); when(intent.getBooleanExtra(Constants.BACKGROUND_MODE_KEY, false)).thenReturn(true); getSubject().onActivityCreated(activity, null); verify(activity).moveTaskToBack(true); }
|
### Question:
LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCode(), intentFactory.createIntent(notification), PendingIntent.FLAG_CANCEL_CURRENT); long repeatInterval = notification.getRepeatIntervalMilliseconds(); if (repeatInterval != 0) { notifier.notifyRepeating(notificationTime, repeatInterval, pendingIntent, notification); } else { notifier.notify(notificationTime, pendingIntent, notification); } } LocalNotificationManager(Context context); }### Answer:
@Test public void manager_notify_notifiesOnce_whenIntervalIsZero() { setupIntervalCalculator(); when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); when(calculator.getTime(any(Date.class))).thenReturn(100L); notification.repeatInterval = 0; getSubject().notify(notification); verify(notifier).notify(100L, pendingIntent, notification); }
@Test public void manager_notify_notifiesRepeating_whenIntervalIsNonZero() { setupIntervalCalculator(); when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); when(calculator.getTime(any(Date.class))).thenReturn(100L); notification.repeatInterval = LocalNotificationTimeInterval.MINUTE_CALENDAR_UNIT; getSubject().notify(notification); verify(notifier).notifyRepeating(100L, notification.getRepeatIntervalMilliseconds(), pendingIntent, notification); }
@Test public void manager_notify_calculatesNextTriggerTimeBasedOnCurrentDate() { when(PendingIntent.getBroadcast(context, "MyCode".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); Date date = mock(Date.class); try { PowerMockito .whenNew(Date.class) .withNoArguments() .thenReturn(date); PowerMockito.whenNew(NextNotificationCalculator.class) .withArguments(notification) .thenReturn(calculator); } catch (Throwable e) { e.printStackTrace(); } LocalNotification notification = getNotification(); getSubject().notify(notification); verify(calculator).getTime(date); }
@Test public void manager_notify_setsUpIntent() { getSubject().notify(getNotification()); verify(intentFactory).createIntent(notification); }
|
### Question:
LocalNotificationManager { void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = getAlarmManager(); try { am.cancel(pi); } catch (Exception e) { Logger.log("LocalNotificationManager::cancel Exception: " + e.getMessage()); } finally { notificationManager.cancel(notificationCode, Constants.STANDARD_NOTIFICATION_ID); } } LocalNotificationManager(Context context); }### Answer:
@Test public void manager_cancel_cancelsAllStoredAlarms() { when(PendingIntent.getBroadcast(context, "notif1".hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT)) .thenReturn(pendingIntent); getSubject().cancel("notif1"); verify(intent).setAction("notif1"); verify(alarmManager).cancel(pendingIntent); }
|
### Question:
NotificationDispatcher { void dispatch() { dispatchNotification(); } NotificationDispatcher(Context context, Bundle bundle); }### Answer:
@Test public void dispatcher_dispatch_whenAppIsInForeground_andNormalNotification_doesNotDisplayNotification() { getSubject().dispatch(); verify(notificationManager).notify("testCode", Constants.STANDARD_NOTIFICATION_ID, notification); }
|
### Question:
AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); NotificationDispatcher dispatcher = new NotificationDispatcher(context, bundle); if (showInForeground) { dispatcher.dispatch(); return; } if (tryEventDispatch(bundle)) return; dispatcher.dispatch(); Logger.log("AlarmIntentService::onReceive Intent: " + intent.toString()); } @Override void onReceive(Context context, Intent intent); }### Answer:
@Test public void intentService_onReceiveWhenAppIsInForeground_andNormalNotification_doesNotDispatchNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(true); getSubject().onReceive(context, intent); verify(notificationDispatcher, never()).dispatch(); }
@Test public void intentService_onReceiveWhenAppIsNotInForeground_andNormalNotification_dispatchesNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(false); mockNotificationDispatch(); getSubject().onReceive(context, intent); verify(notificationDispatcher).dispatch(); }
@Test public void intentService_onReceiveWhenNotificationShowsInForeground_dispatchesNotification() { when(eventDispatcher.dispatchWhenInForeground()).thenReturn(true); when(bundle.getBoolean(Constants.SHOW_IN_FOREGROUND)).thenReturn(true); mockNotificationDispatch(); getSubject().onReceive(context, intent); verify(notificationDispatcher).dispatch(); verify(eventDispatcher, never()).dispatchWhenInForeground(); }
@Test public void intentService_onReceiveWhenNotification_doesNotTriggersNewNotification_whenIntervalNotSent() { mockNotificationDispatch(); try { PowerMockito.whenNew(LocalNotificationManager.class).withArguments(context) .thenReturn(notificationManager); } catch(Throwable e) { e.printStackTrace(); } getSubject().onReceive(context, intent); verify(notificationManager, never()).notify(any(LocalNotification.class)); }
@Test public void intentService_onReceiveWhenNotification_triggersNewNotification_whenIntervalSent() { when(bundle.getInt(Constants.REPEAT_INTERVAL, 0)).thenReturn(1); mockNotificationDispatch(); try { PowerMockito.whenNew(LocalNotificationManager.class).withArguments(context) .thenReturn(notificationManager); PowerMockito.whenNew(PersistenceManager.class).withArguments(context) .thenReturn(persistenceManager); } catch(Throwable e) { e.printStackTrace(); } LocalNotification notification = new LocalNotification(); when(persistenceManager.readNotification("KeyCode")).thenReturn(notification); getSubject().onReceive(context, intent); verify(notificationManager).notify(notification); }
|
### Question:
NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); static String AUTHORITY; static String CONTENT_URI; }### Answer:
@Test public void provider_attachInfo_updatesAuthority() { assertEquals("expected.authority", NotificationSoundProvider.AUTHORITY); getSubject().attachInfo(null, info); assertEquals("new.authority", NotificationSoundProvider.AUTHORITY); }
@Test public void provider_attachInfo_updatesUri() { assertEquals("content: getSubject().attachInfo(null, info); assertEquals("content: }
|
### Question:
NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return new AssetDecompressor(getContext()).decompress(uri.getLastPathSegment()); } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri uri, String selection, String[] selectionArgs); @Override String getType(Uri uri); @Override Uri insert(Uri uri, ContentValues values); @Override boolean onCreate(); @Override Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); @Override int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs); @Override void attachInfo(Context context, ProviderInfo info); @Override AssetFileDescriptor openAssetFile(Uri uri, String mode); static String AUTHORITY; static String CONTENT_URI; }### Answer:
@Test public void provider_openAssetFile_returnsNullIfNotMp3OrWav() { when(uri.getLastPathSegment()).thenReturn("sound.mp3"); try { assertSame(fileDescriptor, getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } when(uri.getLastPathSegment()).thenReturn("sound.wav"); try { assertSame(fileDescriptor, getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } when(uri.getLastPathSegment()).thenReturn("sound.any"); try { assertNull(getSubject().openAssetFile(uri, "")); } catch (FileNotFoundException e) { e.printStackTrace(); } }
@Test public void provider_openAssetFile_decompressesUriLastSegment() { when(uri.getLastPathSegment()).thenReturn("sound.mp3"); try { getSubject().openAssetFile(uri, ""); verify(decompressor).decompress("sound.mp3"); } catch (FileNotFoundException e) { e.printStackTrace(); } }
|
### Question:
WinOrLose { public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int winOrLose(long first, long second); }### Answer:
@Test public void testWinOrLose() { Map<Integer, Long[]> mapIO = new HashMap<Integer, Long[]>() {{ put(0, new Long[]{new Long("2"), new Long("3")}); put(1, new Long[]{new Long("5"), new Long("3")}); }}; for (Map.Entry<Integer, Long[]> io : mapIO.entrySet()) { Assert.assertEquals( io.getKey().intValue(), WinOrLose.winOrLose(io.getValue()[0], io.getValue()[1]) ); } }
|
### Question:
HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }### Answer:
@Test public void testHello() { String ret = helloBean.sayHello(); Assertions.assertNotNull(ret); System.out.println(ret); }
|
### Question:
HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }### Answer:
@Test public void testValue() { String ret = helloBean.osName; Assertions.assertNotNull(ret); System.out.println(String.format("osName:%s, resource: %s", helloBean.osName, helloBean.url.toString() )); }
|
### Question:
HelloController { @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Object>() {{ put("ip", ip); put("name", name); put("gender", gender); put("msg", helloBean.sayHello()); }}; } @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender); }### Answer:
@Test public void testHello() { Object ret = helloController.hello("test", null, null); Assertions.assertTrue(ret.toString().contains("test")); System.out.println(ret); }
|
### Question:
ServerConfig { public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: } void setDomain(String domain); void setPort(long port); String getServerUrl(); boolean isSkipInit(); void setSkipInit(boolean skipInit); boolean isTesting(); void setTesting(boolean testing); }### Answer:
@Test public void testServerUrl() { String ret = serverConfig.getServerUrl(); Assertions.assertTrue(ret.contains("http: System.out.println(ret); }
|
### Question:
MqService { public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); }### Answer:
@Test public void testSendQueue() { for (Object obj : msgArr) { mqService.sendQueue(obj); } }
|
### Question:
MqService { public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); }### Answer:
@Test public void testSendTopic() { for (Object obj : msgArr) { mqService.sendTopic(obj); } }
|
### Question:
App { public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } static void main(String[] args); }### Answer:
@Test public void testApp() { App.main(null); }
|
### Question:
Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } private Inst3(); static Inst3 getInst(); }### Answer:
@Test public void testGetInst() { Inst3 inst = Inst3.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
### Question:
Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } private Inst2(); static Inst2 getInst(); }### Answer:
@Test public void testGetInst() { Inst2 inst = Inst2.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
### Question:
Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } private Inst4(); static Inst4 getInst(); }### Answer:
@Test public void testGetInst() { Inst4 inst = Inst4.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
### Question:
MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 + i]; diff += tmp * tmp; } if (minDiff > diff) { minDiff = diff; } if (minDiff == 0) { break; } } if (minDiff == Integer.MAX_VALUE) { minDiff = 0; } return minDiff; } static void main(String[] args); static int getMinDifference(int[] arA, int n, int[] arB, int m); }### Answer:
@Test public void testGetMinDifference() { int n = 2, m = 4; int[] arA = {1, 2}, arB = {3, 1, 2, 4}; Assert.assertEquals(0, MinDifference.getMinDifference(arA, n, arB, m)); }
@Test public void testGetMinDifference2() { int n = 2, m = 4; int[] arA = {1, 2}, arB = {1, 4, 2, 3}; Assert.assertEquals(2, MinDifference.getMinDifference(arA, n, arB, m)); }
|
### Question:
Inst5 { public static Inst5 getInst() { return Holder.inst; } private Inst5(); static Inst5 getInst(); }### Answer:
@Test public void testGetInst() { Inst5 inst = Inst5.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
### Question:
Inst1 { public static Inst1 getInst() { return inst; } private Inst1(); static Inst1 getInst(); }### Answer:
@Test public void testGetInst() { Inst1 inst = Inst1.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
|
### Question:
FtpUtil { public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathname); ftpClient.changeWorkingDirectory(pathname); ftpClient.storeFile(fileName, inputStream); } catch (IOException e) { System.err.printf("Fail to upload: %s, %s\n", fileName, e.getMessage()); return false; } System.out.printf("Success upload: %s\n", fileName); return true; } static void close(); static boolean upload(String pathname, String fileName, InputStream inputStream); }### Answer:
@Test public void testUpload() throws IOException { String filePath = "readme.md"; InputStream fileStream = new FileInputStream(new File(filePath)); boolean ret = FtpUtil.upload("unit-testing", String.format("%d_%s", new Date().getHours(), filePath), fileStream); fileStream.close(); FtpUtil.close(); Assert.assertTrue(ret); }
|
### Question:
HttpService { public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler); }### Answer:
@Test public void testSendHttpGet() { String html = httpService.sendHttpGet("https: String ret = html.substring(100, 130); System.out.println(ret); Assertions.assertNotNull(ret); }
|
### Question:
HttpService { public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { System.out.printf("Error when setEntity in sendHttpForm: %s\n", e.getMessage()); } } return sendRequest(httpPost, handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler); }### Answer:
@Test public void testBaiduToken() throws UnsupportedEncodingException { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("grant_type", "client_credentials"); put("client_id", "kVcnfD9iW2XVZSMaLMrtLYIz"); put("client_secret", "O9o1O213UgG5LFn0bDGNtoRN3VWl2du6"); }}; JSONObject ret = httpService.sendHttpForm(url, headers, params, new RespJsonObj()); System.out.println(ret); Assertions.assertNotNull(ret); String token = ret.getString("access_token"); testBaiduTts(token); }
|
### Question:
AiController { @ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("tex", URLEncoder.encode(text)); put("tok", token()); put("cuid", "starter_api_http_service"); put("ctp", "1"); put("lan", "zh"); put("spd", "6"); put("pit", "5"); put("vol", "5"); put("per", "0"); put("aue", "6"); }}; RespData respData = new RespData(); httpService.sendHttpForm(url, headers, params, respData); try { OutputStream outputStream = response.getOutputStream(); outputStream.write(respData.getBytes()); } catch (IOException e) { System.out.printf("写入语音合成数据错误: %s\n", e.getMessage()); } response.setContentLength(respData.getContentLength()); response.setContentType(respData.getContentType()); return "ok"; } @ApiOperation("语音合成") @GetMapping("/tts") Object tts(HttpServletResponse response, @RequestParam("text") String text); }### Answer:
@Test public void testTts() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); Object ret = aiController.tts(response, "测试AiController"); System.out.println(ret); Assertions.assertEquals("ok", ret); }
|
### Question:
FileController { @ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e) { System.out.printf("保存文件失败: %s, %s\n", path.toString(), e.getMessage()); } return new HashMap<String, Object>() {{ put("code", "ok"); put("msg", path.toString()); }}; } @ApiOperation("上传文件") @PostMapping("/upload") Object upload(@RequestPart MultipartFile file); @ApiOperation("下载文件") @GetMapping("/{name}") void download(HttpServletResponse response, @PathVariable("name") String name); }### Answer:
@Test public void testUpload() throws IOException { File file = File.createTempFile("tmp", ".txt"); MockMultipartFile multipartFile = new MockMultipartFile( file.getName(), file.getName(), null, new FileInputStream(file) ); Object ret = fileController.upload(multipartFile); System.out.println(ret); String name = (String) ((Map<String, Object>) ret).get("msg"); Assertions.assertNotNull(name); testDownload(name); }
|
### Question:
DateUtil { public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); static Date getEndOfToday(); }### Answer:
@Test public void testGetYYMMDD() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Map<String, String> io = new HashMap<String, String>() {{ put("yy-MM-dd", "getYYMMDD"); put("yy-MM-dd:HH:mm:ss", "getYYMMDDHHmmSS"); put("HH:mm:ss", "getHHmmSS"); }}; for (Map.Entry<String, String> entry : io.entrySet()) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(entry.getKey()); String expected = sdf.format(date); Assert.assertEquals(expected, DateUtil.class.getMethod(entry.getValue()).invoke(DateUtil.class)); } }
|
### Question:
DateUtil { public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getStartOfToday(); static Date getEndOfToday(); }### Answer:
@Test public void testGetStringDate() { Date date = mock(Date.class); String[] io = {"yyyy-MM-dd:HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss"}; for (String i : io) { String format = i; SimpleDateFormat sdf = new SimpleDateFormat(format); String expected = sdf.format(date); Assert.assertEquals(expected, DateUtil.getStringDate(format, date)); } }
|
### Question:
App { public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); } static void main(String[] args); }### Answer:
@Test public void testApp() { new App().main(null); }
|
### Question:
App { public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBox(); panel.add(verticalBox); final long msDuration = 5000; final String title = "Record"; final JButton recordBtn = new JButton(title); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000)); final RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(new TimeListener() { @Override public void timeUpdated(long seconds) { recordBtn.setText(String.format("%s(%d)", title, msDuration / 1000 - seconds)); } @Override public void stopped(long seconds) { recordBtn.setText(title); recordHelper.play(); } }, msDuration); } }); verticalBox.add(recordBtn); frame.setContentPane(panel); frame.setVisible(true); } static void main(String[] args); }### Answer:
@Test public void testApp() { App.main(null); }
|
### Question:
Player implements Runnable { public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } executorService.execute(player); } private Player(); static void asyncPlay(byte[] audioBytes); static void asyncPlay(URL fileUrl); static void asyncPlay(ByteArrayOutputStream byteOutputStream); @Override void run(); static void play(AudioInputStream audioStream, AudioFormat audioFormat); }### Answer:
@Test public void testPlayUrl() throws Exception { URL fileUrl = new URL("http: Player.asyncPlay(fileUrl); Thread.sleep(3000); }
|
### Question:
RecordHelper { public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } private RecordHelper(); static RecordHelper getInst(); void record(TimeListener timeListener, Long msDuration); void stop(); void stop(long millis); void play(); T save(T fileOrStream); }### Answer:
@Test public void testRecord() throws Exception { RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(null, null); recordHelper.stop(5000); ByteArrayOutputStream ret = recordHelper.save(new ByteArrayOutputStream()); System.out.printf("data: %d\n", ret == null ? 0 : ret.size()); recordHelper.play(); Thread.sleep(3000); File file = recordHelper.save(new File("rec.wav")); System.out.println(file.getName()); }
|
### Question:
SplitNumbers { public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if (numbers.size() == 0 && i >= str.length() / 2) { break; } BigInteger tmp = new BigInteger(str.substring(index, i + 1)); if (numbers.size() == 0 || tmp.add(offset).equals(numbers.get(numbers.size() - 1))) { numbers.add(tmp); if (splitStr(str, i + 1, numbers)) { return true; } else { numbers.remove(numbers.size() - 1); } } else if (tmp.add(offset).compareTo(numbers.get(numbers.size() - 1)) >= 0) { break; } } return false; } static boolean splitStr(String str, int index, List<BigInteger> numbers); }### Answer:
@Test public void testSplitNumbers() { Map<String, String> ioMap = new HashMap<String, String>() {{ put("101112", "YES 10"); put("1234", "YES 1"); put("91011", "YES 9"); put("99100", "YES 99"); put("101103", "NO"); put("010203", "NO"); put("13", "NO"); put("1", "NO"); put("11111111111111111111111111111111", "NO"); }}; List<BigInteger> numbers = new ArrayList<BigInteger>(); for (Map.Entry<String, String> io : ioMap.entrySet()) { String str = io.getKey(); numbers.clear(); String ret = SplitNumbers.splitStr(str, 0, numbers) ? ("YES " + String.valueOf(numbers.get(0))) : "NO"; if (!ret.equals(io.getValue())) { System.out.printf("%s %s", io.getValue(), ret); } Assert.assertEquals(io.getValue(), ret); } }
|
### Question:
DayOfProgrammer { public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month]; month++; } } if ((year > 1918 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) || (year < 1918 && year % 4 == 0)) { day -= 1; if (day <= 0) { month--; day += DAYS_OF_MONTH[month]; } } return String.format("%02d.%02d.%04d", day, month + 1, year); } static String solve(int year); static int[] DAYS_OF_MONTH; static int DAY_OF_PROGRAMMER; }### Answer:
@Test public void testResolve() { Map<Integer, String> ioMap = new HashMap<Integer, String>() {{ put(2016, "12.09.2016"); }}; for (Map.Entry<Integer, String> io : ioMap.entrySet()) { String r = DayOfProgrammer.solve(io.getKey()); if (!io.getValue().equals(r)) { System.out.println(r); } Assert.assertEquals(io.getValue(), r); } }
|
### Question:
StringDecoder { static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } else if (c >= '1' && c <= '2') { boolean isDouble = false; if (i + 2 < count && s.charAt(i + 2) == SYMBOL) { String subStr = s.substring(i, i + 2); addFrequency(chars, Integer.valueOf(subStr) - 1); i += 3; } else { addFrequency(chars, c - '1'); i++; } } else { System.out.printf("Error in str, %c", c); i++; } } return chars; } static void main(String[] args); }### Answer:
@Test public void testFrequency() { String input = "1226#24#"; int[] output = StringDecoder.frequency(input); Assert.assertEquals(1, output[0]); Assert.assertEquals(1, output[1]); }
|
### Question:
SortHotel { static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] keywordArr = keywords.trim().toLowerCase() .replace("-", "") .split(" "); if (keywordArr == null || keywordArr.length <= 0) { return null; } Set<String> keywordSet = new HashSet<String>(keywordArr.length){{ addAll(Arrays.asList(keywordArr)); }}; Map<Integer, Hotel> hotelMap = new HashMap<Integer, Hotel>(); for (int i = 0; i < hotel_ids.length; i++) { int id = hotel_ids[i]; Hotel hotel = hotelMap.get(id); if (hotel == null) { hotel = new Hotel(id); hotelMap.put(id, hotel); } String review = reviews[i]; if (review == null || review.trim().length() <= 0) { continue; } review = review.trim().toLowerCase() .replace(",", " ") .replace(".", " ") .replace("!", " ") .replace("-", ""); String[] reviewArr = review.split(" "); if (reviewArr == null || reviewArr.length <= 0) { continue; } for (String tmp : reviewArr) { if (tmp != null && tmp.trim().length() > 0 && keywordSet.contains(tmp.trim())) { hotel.reviewCount++; } } } Hotel[] hotelArr = new Hotel[hotelMap.size()]; hotelMap.values().toArray(hotelArr); Arrays.sort(hotelArr); int[] idArr = new int[hotelArr.length]; for (int i = 0; i < hotelArr.length; i++) { idArr[i] = hotelArr[i].id; } return idArr; } }### Answer:
@Test public void testSortHotels() { int[] ret = SortHotel.sort_hotels( "breakfast beach citycenter location metro view staff price", new int[]{1, 2, 1, 1, 2}, new String[]{ "This hotel has a nice view of the citycenter. The location is perfect.", "The breakfast is ok. Regarding location, it is quite far from citycenter buth price is cheap so it is worth.", "Location is excellent, 5 minutes from citycenter. There is also a metro station very close to the hotel.", "They said I couldn't take my dog and there were other guests with dogs! That is not fair.", "Very friendly staff and good cost-benefit ratio. Its location is a bit far from citycenter." }); Assert.assertArrayEquals(new int[] {2, 1}, ret); }
|
### Question:
Triangle { public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); }### Answer:
@Test public void testTriangle() { Map<int[], Integer> mapIO = new HashMap<int[], Integer>() {{ put(new int[]{3, 3, 3}, 1); put(new int[]{3, 5, 4}, 2); }}; for (Map.Entry<int[], Integer> io : mapIO.entrySet()) { int[] i = io.getKey(); int ret = Triangle.triangle(i[0], i[1], i[2]); Assert.assertEquals(io.getValue().intValue(), ret); } }
|
### Question:
Triangle { public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i], c[i]) > 0) { results[i] = "Yes"; } else { results[i] = "No"; } } return results; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, int[] c); }### Answer:
@Test public void testTriangleOrNot() { int[] a = {7, 10, 7}; int[] b = {2, 3, 4}; int[] c = {2, 7, 4}; String[] results = Triangle.triangleOrNot(a, b, c); System.out.println(Arrays.asList(results)); }
|
### Question:
CustomerServiceCapacity { public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[i][1]); } Arrays.sort(calls); for (int i = 0; i < calls.length - 1; i++) { for (int j = i + 1; j < calls.length; j++) { if (calls[i].isOverlap(calls[j])) { calls[i].addCount(); } else { break; } } } int max = calls[0].count; for (int i = 1; i < calls.length; i++) { if (max < calls[i].count) { max = calls[i].count; } } if (max <= noOfCurrentAgents) { return 0; } return max - noOfCurrentAgents; } static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes); }### Answer:
@Test public void testHowManyAgentsToAdd() { Map<int[][], int[]> mapIO = new HashMap<int[][], int[]>(){{ put(new int[][] {{1481122000, 1481122020}, {1481122000, 1481122040}, {1481122030, 1481122035}}, new int[]{1, 1}); }}; for (Map.Entry<int[][], int[]> io : mapIO.entrySet()) { int ret = CustomerServiceCapacity.howManyAgentsToAdd(io.getValue()[0], io.getKey()); Assert.assertEquals(io.getValue()[1], ret); } }
|
### Question:
Coupon { public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] values = log.split(" "); if (values == null || values.length <= 0) { break; } if (values.length == 1) { if ("?".equals(values[0])) { freeErrors++; continue; } else { break; } } String value = values[0]; Long key = -1L; try { key = Long.valueOf(values[1]); } catch (Exception e) { e.printStackTrace(); break; } if (map.containsKey(key)) { if ("o".equalsIgnoreCase(value)) { map.remove(key); } else if (freeErrors-- <= 0) { break; } } else { if ("i".equalsIgnoreCase(value)) { map.put(key, value); } else if (freeErrors-- <= 0) { break; } } } if (index >= logs.size() && freeErrors >= 0) { index = -1; } return index; } static void main(String[] args); static long findValidLogs(List<String> logs); }### Answer:
@Test public void testFindValidLogs() { Map<String[], Long> mapIO = new HashMap<String[], Long>() {{ put(new String[]{}, -1L); put(new String[]{"o 1"}, 1L); put(new String[]{"?", "o 1"}, -1L); put(new String[]{"I 1", "?", "O 1"}, -1L); put(new String[]{"i 2", "o 1"}, 2L); put(new String[]{"?", "O 1", "?", "O 2"}, -1L); }}; for (Map.Entry<String[], Long> io : mapIO.entrySet()) { List<String> ar = new ArrayList<String>(); for (String str : io.getKey()) { ar.add(str); } Assert.assertEquals( io.getValue().longValue(), Coupon.findValidLogs(ar) ); } }
|
### Question:
ElectionWinner { public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.containsKey(tmp) ? voteCountMap.get(tmp) : 0); voteCountMap.put(tmp, count); if (maxCount < count) { maxCount = count; } } List<String> candidateList = new ArrayList<String>(); for (Map.Entry<String, Integer> voteCount : voteCountMap.entrySet()) { if (voteCount.getValue() == maxCount) { candidateList.add(voteCount.getKey()); } } if (candidateList.size() <= 0) { return null; } else if (candidateList.size() == 1) { return candidateList.get(0); } String[] candidatesArr = new String[candidateList.size()]; candidateList.toArray(candidatesArr); Arrays.sort(candidatesArr); return candidatesArr[candidatesArr.length - 1]; } static String electionWinner(String[] votes); }### Answer:
@Test public void testElectionWinner() { String ret = ElectionWinner.electionWinner(new String[] {"Alex", "Michael", "harry", "Dave", "Michael", "Victor", "Harry", "Alex", "Mary", "Mary"}); Assert.assertEquals("Michael", ret); }
|
### Question:
DeltaEncode { public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { encode.add(-128); } encode.add(diff); } int[] encodeArr = new int[encode.size()]; for (int i = 0; i < encode.size(); i++) { encodeArr[i] = encode.get(i); } return encodeArr; } static int[] delta_encode(final int[] array); }### Answer:
@Test public void testDeltaEncode() { Map<int[], int[]> mapIO = new HashMap<int[], int[]>(){{ put(new int[]{25626, 25757, 24367, 24267, 16, 100, 2, 7277}, new int[]{25626, -128, 131, -128, -1390, -100, -128, -24251, 84, -98, -128, 7275}); }}; for (Map.Entry<int[], int[]> io : mapIO.entrySet()) { int[] ret = DeltaEncode.delta_encode(io.getKey()); Assert.assertArrayEquals(io.getValue(), ret); } }
|
### Question:
ZombieCluster { static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][j++] = (c == '1'); } } markCluster(zombieMatric, len, 0); int count = 0; for (int i = 0; i < len; i++) { if (zombieMatric[i][i]) { count++; } } return count; } }### Answer:
@Test public void testZombieCluster() { Map<String[], Integer> mapIO = new HashMap<String[], Integer>() {{ put(new String[]{"10000", "01000", "00100", "00010", "00001"}, 5); put(new String[]{"1100", "1110", "0110", "0001"}, 2); }}; for (Map.Entry<String[], Integer> io : mapIO.entrySet()) { int ret = ZombieCluster.zombieCluster(io.getKey()); Assert.assertEquals(io.getValue().intValue(), ret); } }
|
### Question:
GetDay { public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayInt = cal.get(Calendar.DAY_OF_WEEK); return (new String[]{ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" })[dayInt - 1]; } static String getDay(String day, String month, String year); }### Answer:
@Test public void testGetDay() { Map<String[], String> mapIO = new HashMap<String[], String>() {{ put(new String[]{"05", "08", "2015"}, "WEDNESDAY"); put(new String[]{"04", "06", "2018"}, "MONDAY"); put(new String[]{"06", "06", "2018"}, "WEDNESDAY"); }}; for (Map.Entry<String[], String> io : mapIO.entrySet()) { String[] params = io.getKey(); String ret = GetDay.getDay(params[0], params[1], params[2]); Assert.assertEquals(io.getValue(), ret); } }
|
### Question:
LeaderBoard { public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } else if (players[i].getScore() == players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank()); } else if (players[i].getScore() < players[i - 1].getScore()) { players[i].setRank(players[i - 1].getRank() + 1); } } int[] ranks = new int[alice.length]; int j = players.length - 1; for (int i = 0; i < alice.length; i++) { int score = alice[i]; for (; j >= 0; j--) { if (score < players[j].getScore()) { ranks[i] = players[j].getRank() + 1; break; } else if (score == players[j].getScore()) { ranks[i] = players[j].getRank(); break; } } if (j < 0) { ranks[i] = 1; } } return ranks; } static int[] getRanks(int[] scores, int[] alice); static void main(String[] args); }### Answer:
@Test public void testGetRanks() { Map<List<int[]>, int[]> ioMap = new HashMap<List<int[]>, int[]>() {{ put(new ArrayList() {{ add(new int[] {100, 100, 50, 40, 40, 20, 10}); add(new int[] {5, 25, 50, 120}); }}, new int[] {6, 4, 2, 1}); }}; for (Map.Entry<List<int[]>, int[]> io : ioMap.entrySet()) { int[] ranks = LeaderBoard.getRanks(io.getKey().get(0), io.getKey().get(1)); Assert.assertArrayEquals(ranks, io.getValue()); } }
|
### Question:
WaitingTime { public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else { count += ticket; if (i > p) { count--; } } } return count; } static long waitingTime(int[] tickets, int p); }### Answer:
@Test public void testWaitingTime() { Map<int[], long[]> mapIO = new HashMap<int[], long[]>(){{ put(new int[]{2, 6, 3, 4, 5}, new long[]{2, 12}); put(new int[]{1, 1, 1, 1}, new long[]{0, 1}); put(new int[]{5, 5, 2, 3}, new long[]{3, 11}); }}; for(Map.Entry<int[], long[]> io : mapIO.entrySet()) { long ret = WaitingTime.waitingTime(io.getKey(), (int)io.getValue()[0]); Assert.assertEquals(io.getValue()[1], ret); } }
|
### Question:
Hello { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); } static void main(String[] args); }### Answer:
@Test public void testMain() { Hello.main(null); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.