method2testcases
stringlengths
118
3.08k
### Question: RequestStep extends Request { public int getCount() { return count; } private RequestStep(Builder builder); static RequestStepSyntax nextStep(); int getCount(); @Override Sc2Api.Request toSc2Api(); @Override ResponseType responseType(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void serializesDefaultValueForCountWhenNotSet() { assertThat(requestStepWithDefaultValues().getCount()).as("count default value") .isEqualTo(DEFAULT_GAME_LOOP_COUNT); }
### Question: UpgradeData implements Serializable { public static UpgradeData from(Data.UpgradeData sc2ApiUpgradeData) { require("sc2api upgrade data", sc2ApiUpgradeData); return new UpgradeData(sc2ApiUpgradeData); } private UpgradeData(Data.UpgradeData sc2ApiUpgradeData); static UpgradeData from(Data.UpgradeData sc2ApiUpgradeData); Upgrade getUpgrade(); String getName(); Optional<Integer> getMineralCost(); Optional<Integer> getVespeneCost(); Optional<Float> getResearchTime(); Optional<Ability> getAbility(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiUpgradeDataIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> UpgradeData.from(nothing())) .withMessage("sc2api upgrade data is required"); } @Test void convertsAllFieldsFromSc2ApiUnit() { assertThatAllFieldsAreConverted(UpgradeData.from(sc2ApiUpgradeData())); } @Test void throwsExceptionWhenUpgradeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> UpgradeData.from(without( () -> sc2ApiUpgradeData().toBuilder(), Data.UpgradeData.Builder::clearUpgradeId).build())) .withMessage("upgrade is required"); } @Test void throwsExceptionWhenNameIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> UpgradeData.from(without( () -> sc2ApiUpgradeData().toBuilder(), Data.UpgradeData.Builder::clearName).build())) .withMessage("name is required"); }
### Question: RequestStep extends Request { public static RequestStepSyntax nextStep() { return new Builder(); } private RequestStep(Builder builder); static RequestStepSyntax nextStep(); int getCount(); @Override Sc2Api.Request toSc2Api(); @Override ResponseType responseType(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenCountValueIsLowerThanOne() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> nextStep().withCount(0)) .withMessage("count must be greater than 0"); }
### Question: RequestStartReplay extends Request { public static RequestStartReplaySyntax startReplay() { return new Builder(); } private RequestStartReplay(Builder builder); static RequestStartReplaySyntax startReplay(); @Override Sc2Api.Request toSc2Api(); @Override ResponseType responseType(); Optional<Path> getReplayPath(); Optional<byte[]> getReplayDataInBytes(); Optional<byte[]> getMapDataInBytes(); InterfaceOptions getInterfaceOptions(); int getObservedPlayerId(); boolean isDisableFog(); boolean isRealtime(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenReplayCaseIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(startReplay()).build()) .withMessage("one of replay case is required"); } @Test void throwsExceptionWhenObservedPlayerIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy( () -> fullAccessTo(startReplay().from(Paths.get(REPLAY_PATH)).use(defaultInterfaces())).build()) .withMessage("observed player is required"); }
### Question: ResponseError extends Response { public static ResponseError from(Sc2Api.Response sc2ApiResponse) { if (!isSet(sc2ApiResponse) || sc2ApiResponse.getErrorCount() == 0) { throw new IllegalArgumentException("provided argument doesn't have error response"); } return new ResponseError(sc2ApiResponse.getErrorList(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseError(List<String> errors, Sc2Api.Status status, int id); static ResponseError from(Sc2Api.Response sc2ApiResponse); List<String> getErrors(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsIllegalArgumentExceptionForNullArgumentsOrEmptyErrorListInSc2ApiResponse() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseError.from(nothing())) .withMessage("provided argument doesn't have error response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseError.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have error response"); }
### Question: ResponseDebug extends Response { public static ResponseDebug from(Sc2Api.Response sc2ApiResponse) { if (!hasDebugResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have debug response"); } return new ResponseDebug(sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseDebug(Sc2Api.Status sc2ApiStatus, int id); static ResponseDebug from(Sc2Api.Response sc2ApiResponse); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveDebug() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseDebug.from(nothing())) .withMessage("provided argument doesn't have debug response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseDebug.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have debug response"); } @Test void convertsSc2ApiResponseDebugToResponseDebug() { ResponseDebug responseDebug = ResponseDebug.from(sc2ApiResponseWithDebug()); assertThat(responseDebug).as("converted response debug").isNotNull(); assertThat(responseDebug.getType()).as("type of debug response") .isEqualTo(ResponseType.DEBUG); assertThat(responseDebug.getStatus()).as("status of debug response").isEqualTo(GameStatus.IN_GAME); }
### Question: ResponseObserverAction extends Response { public static ResponseObserverAction from(Sc2Api.Response sc2ApiResponse) { if (!hasObserverActionResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have observer action response"); } return new ResponseObserverAction(sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseObserverAction(Sc2Api.Status sc2ApiStatus, int id); static ResponseObserverAction from(Sc2Api.Response sc2ApiResponse); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveObserverAction() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseObserverAction.from(nothing())) .withMessage("provided argument doesn't have observer action response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseObserverAction.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have observer action response"); } @Test void convertsSc2ApiResponseObserverActionToResponseObserverAction() { ResponseObserverAction responseObserverAction = ResponseObserverAction.from(sc2ApiResponseWithObserverAction()); assertThat(responseObserverAction).as("converted response observer action").isNotNull(); assertThat(responseObserverAction.getType()).as("type of observer action response") .isEqualTo(ResponseType.OBSERVER_ACTION); assertThat(responseObserverAction.getStatus()).as("status of observer action response") .isEqualTo(GameStatus.IN_GAME); }
### Question: ResponseCreateGame extends Response { public static ResponseCreateGame from(Sc2Api.Response sc2ApiResponse) { if (!hasCreateGameResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have create game response"); } return new ResponseCreateGame( sc2ApiResponse.getCreateGame(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseCreateGame(Sc2Api.ResponseCreateGame sc2ApiResponseCreateGame, Sc2Api.Status status, int id); static ResponseCreateGame from(Sc2Api.Response sc2ApiResponse); Optional<Error> getError(); Optional<String> getErrorDetails(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveCreateGame() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseCreateGame.from(nothing())) .withMessage("provided argument doesn't have create game response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseCreateGame.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have create game response"); } @Test void convertsSc2ApiResponseCreateGameToResponseCreateGame() { assertThatResponseCreateGameDoesNotHaveError(ResponseCreateGame.from(sc2ApiResponseWithCreateGame())); } @Test void throwsExceptionWhenResponseCreateGameErrorIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseCreateGame.Error.from(nothing())) .withMessage("sc2api response create game error is required"); } @Test void convertsSc2ApiResponseCreateGameWithErrorToResponseCreateGame() { ResponseCreateGame responseCreateGame = ResponseCreateGame.from(sc2ApiResponseWithCreateGameWithError()); assertThatResponseIsInValidState(responseCreateGame); assertThatErrorsAreMapped(responseCreateGame); }
### Question: ResponseQuitGame extends Response { public static ResponseQuitGame from(Sc2Api.Response sc2ApiResponse) { if (!hasQuitResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have quit response"); } return new ResponseQuitGame(sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseQuitGame(Sc2Api.Status sc2ApiStatus, int id); static ResponseQuitGame from(Sc2Api.Response sc2ApiResponse); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveQuitGame() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseQuitGame.from(nothing())) .withMessage("provided argument doesn't have quit response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseQuitGame.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have quit response"); } @Test void convertsSc2ApiResponseQuitGameToResponseQuitGame() { ResponseQuitGame responseQuitGame = ResponseQuitGame.from(sc2ApiResponseWithQuit()); assertThat(responseQuitGame).as("converted response quit game").isNotNull(); assertThat(responseQuitGame.getType()).as("type of quit game response") .isEqualTo(ResponseType.QUIT_GAME); assertThat(responseQuitGame.getStatus()).as("status of quit game response").isEqualTo(GameStatus.QUIT); }
### Question: ResponseAvailableMaps extends Response { public static ResponseAvailableMaps from(Sc2Api.Response sc2ApiResponse) { if (!hasAvailableMapsResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have available maps response"); } return new ResponseAvailableMaps( sc2ApiResponse.getAvailableMaps(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseAvailableMaps( Sc2Api.ResponseAvailableMaps sc2ApiResponseAvailableMaps, Sc2Api.Status sc2ApiStatus, int id); static ResponseAvailableMaps from(Sc2Api.Response sc2ApiResponse); Set<BattlenetMap> getBattlenetMaps(); Set<LocalMap> getLocalMaps(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveAvailableMaps() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseAvailableMaps.from(nothing())) .withMessage("provided argument doesn't have available maps response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseAvailableMaps.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have available maps response"); } @Test void hasEmptySetOfMapsForEmptySc2ApiResponseAvailableMaps() { ResponseAvailableMaps responseAvailableMaps = ResponseAvailableMaps.from(emptySc2ApiResponseWithAvailableMaps()); assertThatAllFieldsAreProperlyConverted( responseAvailableMaps, new ExpectedResponseData().withResponseStatus(GameStatus.QUIT)); } @Test void convertsSc2ApiResponseAvailableMapsToResponseAvailableMaps() { ResponseAvailableMaps responseAvailableMaps = ResponseAvailableMaps.from(sc2ApiResponseWithAvailableMaps()); assertThatAllFieldsAreProperlyConverted( responseAvailableMaps, new ExpectedResponseData() .withResponseStatus(GameStatus.IN_GAME) .withBattlenetMapNames(BATTLENET_MAPS) .withLocalMapPaths(LOCAL_MAP_PATHS)); }
### Question: ResponseSaveMap extends Response { public static ResponseSaveMap from(Sc2Api.Response sc2ApiResponse) { if (!hasSaveMapResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have save map response"); } return new ResponseSaveMap(sc2ApiResponse.getSaveMap(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseSaveMap(Sc2Api.ResponseSaveMap sc2ApiResponseSaveMap, Sc2Api.Status sc2ApiStatus, int id); static ResponseSaveMap from(Sc2Api.Response sc2ApiResponse); Optional<Error> getError(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveSaveMap() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseSaveMap.from(nothing())) .withMessage("provided argument doesn't have save map response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseSaveMap.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have save map response"); } @Test void convertsSc2ApiResponseSaveMapToResponseSaveMap() { ResponseSaveMap responseSaveMap = ResponseSaveMap.from(sc2ApiResponseWithSaveMap()); assertThatResponseDoesNotHaveError(responseSaveMap); assertThatResponseIsInValidState(responseSaveMap); } @Test void throwsExceptionWhenResponseSaveMapErrorIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseSaveMap.Error.from(nothing())) .withMessage("sc2api response save map error is required"); } @Test void convertsSc2ApiResponseSaveMapWithErrorToResponseSaveMap() { ResponseSaveMap responseSaveMap = ResponseSaveMap.from(sc2ApiResponseWithSaveMapWithError()); assertThatResponseIsInValidState(responseSaveMap); assertThatErrorIsMapped(responseSaveMap); }
### Question: ResponseQuery extends Response { public static ResponseQuery from(Sc2Api.Response sc2ApiResponse) { if (!hasQueryResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have query response"); } return new ResponseQuery(sc2ApiResponse.getQuery(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseQuery(Query.ResponseQuery sc2ApiResponseQuery, Sc2Api.Status status, int id); static ResponseQuery from(Sc2Api.Response sc2ApiResponse); List<Pathing> getPathing(); List<AvailableAbilities> getAbilities(); List<BuildingPlacement> getPlacements(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveQuery() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseQuery.from(nothing())) .withMessage("provided argument doesn't have query response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseQuery.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have query response"); } @Test void convertsSc2ApiResponseQueryToResponseQuery() { assertThatAllFieldsAreProperlyConverted(ResponseQuery.from(sc2ApiResponseWithQuery())); }
### Question: ResponseData extends Response { public static ResponseData from(Sc2Api.Response sc2ApiResponse) { if (!hasDataResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have data response"); } return new ResponseData(sc2ApiResponse.getData(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseData(Sc2Api.ResponseData sc2ApiResponseData, Sc2Api.Status status, int id); static ResponseData from(Sc2Api.Response sc2ApiResponse); Set<AbilityData> getAbilities(); Set<UnitTypeData> getUnitTypes(); Set<UpgradeData> getUpgrades(); Set<BuffData> getBuffs(); Set<EffectData> getEffects(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveData() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseData.from(nothing())) .withMessage("provided argument doesn't have data response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseData.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have data response"); } @Test void convertsSc2ApiResponseDataToResponseData() { assertThatAllFieldsAreProperlyConverted(ResponseData.from(sc2ApiResponseWithData())); }
### Question: ResponseSaveReplay extends Response { public static ResponseSaveReplay from(Sc2Api.Response sc2ApiResponse) { if (!hasSaveReplayResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have save replay response"); } return new ResponseSaveReplay( sc2ApiResponse.getSaveReplay(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseSaveReplay( Sc2Api.ResponseSaveReplay sc2ApiResponseSaveReplay, Sc2Api.Status sc2ApiStatus, int id); static ResponseSaveReplay from(Sc2Api.Response sc2ApiResponse); byte[] getData(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveSaveReplay() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseSaveReplay.from(nothing())) .withMessage("provided argument doesn't have save replay response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseSaveReplay.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have save replay response"); } @Test void throwsExceptionWhenDataIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseSaveReplay.from(sc2ApiResponseWithSaveReplayWithoutData())) .withMessage("data is required"); }
### Question: BuffData implements Serializable { public static BuffData from(Data.BuffData sc2ApiBuffData) { require("sc2api buff data", sc2ApiBuffData); return new BuffData(sc2ApiBuffData); } private BuffData(Data.BuffData sc2ApiBuffData); static BuffData from(Data.BuffData sc2ApiBuffData); Buff getBuff(); String getName(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiBuffDataIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> BuffData.from(nothing())) .withMessage("sc2api buff data is required"); } @Test void convertsAllFieldsFromSc2ApiUnit() { assertThatAllFieldsAreConverted(BuffData.from(sc2ApiBuffData())); } @Test void throwsExceptionWhenBuffIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> BuffData.from(without( () -> sc2ApiBuffData().toBuilder(), Data.BuffData.Builder::clearBuffId).build())) .withMessage("buff is required"); } @Test void throwsExceptionWhenNameIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> BuffData.from(without( () -> sc2ApiBuffData().toBuilder(), Data.BuffData.Builder::clearName).build())) .withMessage("name is required"); }
### Question: ResponseQuickSave extends Response { public static ResponseQuickSave from(Sc2Api.Response sc2ApiResponse) { if (!hasQuickSaveResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have quick save response"); } return new ResponseQuickSave(sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseQuickSave(Sc2Api.Status sc2ApiStatus, int id); static ResponseQuickSave from(Sc2Api.Response sc2ApiResponse); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveQuickSave() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseQuickSave.from(nothing())) .withMessage("provided argument doesn't have quick save response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseQuickSave.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have quick save response"); } @Test void convertsSc2ApiResponseQuickSaveToResponseQuickSave() { ResponseQuickSave responseQuickSave = ResponseQuickSave.from(sc2ApiResponseWithQuickSave()); assertThat(responseQuickSave).as("converted response quick save").isNotNull(); assertThat(responseQuickSave.getType()).as("type of quick save response").isEqualTo(ResponseType.QUICK_SAVE); assertThat(responseQuickSave.getStatus()).as("status of quick save response").isEqualTo(GameStatus.IN_GAME); }
### Question: ResponseStartReplay extends Response { public static ResponseStartReplay from(Sc2Api.Response sc2ApiResponse) { if (!hasStartReplayResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have start replay response"); } return new ResponseStartReplay( sc2ApiResponse.getStartReplay(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseStartReplay( Sc2Api.ResponseStartReplay sc2ApiResponseStartReplay, Sc2Api.Status sc2ApiStatus, int id); static ResponseStartReplay from(Sc2Api.Response sc2ApiResponse); Optional<ResponseStartReplay.Error> getError(); Optional<String> getErrorDetails(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveStartReplay() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseStartReplay.from(nothing())) .withMessage("provided argument doesn't have start replay response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseStartReplay.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have start replay response"); } @Test void convertsSc2ApiResponseStartReplayToResponseStartReplay() { ResponseStartReplay responseStartReplay = ResponseStartReplay.from(sc2ApiResponseWithStartReplay()); assertThatResponseDoesNotHaveError(responseStartReplay); assertThatResponseIsInValidState(responseStartReplay); } @Test void throwsExceptionWhenResponseStartReplayErrorIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseStartReplay.Error.from(nothing())) .withMessage("sc2api response start replay error is required"); }
### Question: ResponseLeaveGame extends Response { public static ResponseLeaveGame from(Sc2Api.Response sc2ApiResponse) { if (!hasLeaveGameResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have leave game response"); } return new ResponseLeaveGame(sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseLeaveGame(Sc2Api.Status sc2ApiStatus, int id); static ResponseLeaveGame from(Sc2Api.Response sc2ApiResponse); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveLeaveGame() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseLeaveGame.from(nothing())) .withMessage("provided argument doesn't have leave game response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseLeaveGame.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have leave game response"); } @Test void convertsSc2ApiResponseLeaveGameToResponseLeaveGame() { ResponseLeaveGame responseLeaveGame = ResponseLeaveGame.from(sc2ApiResponseWithLeaveGame()); assertThat(responseLeaveGame).as("converted response leave game").isNotNull(); assertThat(responseLeaveGame.getType()).as("type of leave game response").isEqualTo(ResponseType.LEAVE_GAME); assertThat(responseLeaveGame.getStatus()).as("status of leave game response").isEqualTo(GameStatus.LAUNCHED); }
### Question: ResponseJoinGame extends Response { public static ResponseJoinGame from(Sc2Api.Response sc2ApiResponse) { if (!hasJoinGameResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have join game response"); } return new ResponseJoinGame(sc2ApiResponse.getJoinGame(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseJoinGame(Sc2Api.ResponseJoinGame sc2ApiResponseJoinGame, Sc2Api.Status sc2ApiStatus, int id); static ResponseJoinGame from(Sc2Api.Response sc2ApiResponse); Optional<Error> getError(); Optional<String> getErrorDetails(); Integer getPlayerId(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveJoinGame() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseJoinGame.from(nothing())) .withMessage("provided argument doesn't have join game response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseJoinGame.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have join game response"); } @Test void convertsSc2ApiResponseJoinGameToResponseJoinGame() { assertThatResponseJoinGameDoesNotHaveError(ResponseJoinGame.from(sc2ApiResponseWithJoinGame())); } @Test void throwsExceptionWhenResponseJoinGameErrorIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseJoinGame.Error.from(nothing())) .withMessage("sc2api response join game error is required"); } @Test void convertsSc2ApiResponseJoinGameWithErrorToResponseJoinGame() { ResponseJoinGame responseJoinGame = ResponseJoinGame.from(sc2ApiResponseWithJoinGameWithError()); assertThatResponseIsInValidState(responseJoinGame); assertThatErrorsAreMapped(responseJoinGame); }
### Question: ResponseStep extends Response { public static ResponseStep from(Sc2Api.Response sc2ApiResponse) { if (!hasStepResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have step response"); } return new ResponseStep(sc2ApiResponse.getStep(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseStep(Sc2Api.ResponseStep responseStep, Sc2Api.Status sc2ApiStatus, int id); static ResponseStep from(Sc2Api.Response sc2ApiResponse); Optional<Integer> getSimulationLoop(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveStep() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseStep.from(nothing())) .withMessage("provided argument doesn't have step response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseStep.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have step response"); }
### Question: DebugKillUnit implements Sc2ApiSerializable<Debug.DebugKillUnit> { public static DebugKillUnitSyntax killUnit() { return new Builder(); } private DebugKillUnit(Builder builder); static DebugKillUnitSyntax killUnit(); @Override Debug.DebugKillUnit toSc2Api(); Set<Tag> getUnitTags(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenUnitTagSetIsEmpty() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ((DebugKillUnit.Builder) killUnit()).build()) .withMessage("unit tag set is required"); }
### Question: ResponseAction extends Response { public static ResponseAction from(Sc2Api.Response sc2ApiResponse) { if (!hasActionResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have action response"); } return new ResponseAction(sc2ApiResponse.getAction(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseAction(Sc2Api.ResponseAction sc2ApiResponseAction, Sc2Api.Status status, int id); static ResponseAction from(Sc2Api.Response sc2ApiResponse); List<ActionResult> getResults(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveAction() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseAction.from(nothing())) .withMessage("provided argument doesn't have action response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseAction.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have action response"); } @Test void convertsSc2ApiResponseActionToResponseAction() { assertThatAllFieldsAreProperlyConverted(ResponseAction.from(sc2ApiResponseWithAction())); }
### Question: ResponseQuickLoad extends Response { public static ResponseQuickLoad from(Sc2Api.Response sc2ApiResponse) { if (!hasQuickLoadResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have quick load response"); } return new ResponseQuickLoad(sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseQuickLoad(Sc2Api.Status sc2ApiStatus, int id); static ResponseQuickLoad from(Sc2Api.Response sc2ApiResponse); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveQuickLoad() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseQuickLoad.from(nothing())) .withMessage("provided argument doesn't have quick load response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseQuickLoad.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have quick load response"); } @Test void convertsSc2ApiResponseQuickLoadToResponseQuickLoad() { ResponseQuickLoad responseQuickLoad = ResponseQuickLoad.from(sc2ApiResponseWithQuickLoad()); assertThat(responseQuickLoad).as("converted response quick load").isNotNull(); assertThat(responseQuickLoad.getType()).as("type of quick load response").isEqualTo(ResponseType.QUICK_LOAD); assertThat(responseQuickLoad.getStatus()).as("status of quick load response").isEqualTo(GameStatus.IN_GAME); }
### Question: DebugLine implements Sc2ApiSerializable<Debug.DebugLine> { public static DebugLineSyntax line() { return new Builder(); } private DebugLine(Builder builder); static DebugLineSyntax line(); @Override Debug.DebugLine toSc2Api(); Color getColor(); Line getLine(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenColorIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(line().of(P0, P1).withColor(nothing())).build()) .withMessage("color is required"); } @Test void throwsExceptionWhenLineIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(line()).withColor(SAMPLE_COLOR).build()) .withMessage("line is required"); }
### Question: UnitInfo implements Serializable { public static UnitInfo from(Ui.UnitInfo sc2ApiUnitInfo) { require("sc2api unit info", sc2ApiUnitInfo); return new UnitInfo(sc2ApiUnitInfo); } private UnitInfo(Ui.UnitInfo sc2ApiUnitInfo); static UnitInfo from(Ui.UnitInfo sc2ApiUnitInfo); UnitType getUnitType(); Optional<Alliance> getPlayerRelative(); Optional<Integer> getHealth(); Optional<Integer> getShields(); Optional<Integer> getEnergy(); Optional<Integer> getTransportSlotsTaken(); Optional<Float> getBuildProgress(); Optional<UnitInfo> getAddOn(); Optional<Integer> getMaxHealth(); Optional<Integer> getMaxShields(); Optional<Integer> getMaxEnergy(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiUnitInfoIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> UnitInfo.from(nothing())) .withMessage("sc2api unit info is required"); } @Test void convertsAllFieldsFromSc2ApiUnitInfo() { assertThatAllFieldsAreConverted(UnitInfo.from(sc2ApiUnitInfo())); } @Test void throwsExceptionWhenUnitTypeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> UnitInfo.from( without(() -> sc2ApiUnitInfo().toBuilder(), Ui.UnitInfo.Builder::clearUnitType).build())) .withMessage("unit type is required"); } @Test void fulfillsEqualsContract() { EqualsVerifier .forClass(UnitInfo.class) .withNonnullFields("unitType") .withPrefabValues(UnitInfo.class, UnitInfo.from(sc2ApiUnitInfoAddOn()), UnitInfo.from(sc2ApiUnitInfo())) .verify(); }
### Question: Tag implements Sc2ApiSerializable<Long> { public static Tag from(Long sc2apiTag) { require("sc2api unit tag", sc2apiTag); return new Tag(sc2apiTag); } private Tag(Long sc2apiTag); static Tag from(Long sc2apiTag); static Tag of(Long sc2apiTag); static Tag tag(Long sc2apiTag); @Override Long toSc2Api(); @JsonValue Long getValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiUnitTagIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Tag.from(nothing())) .withMessage("sc2api unit tag is required"); }
### Question: UnitOrder implements Serializable, GeneralizableAbility<UnitOrder> { public static UnitOrder from(Raw.UnitOrder sc2ApiUnitOrder) { require("sc2api unit order", sc2ApiUnitOrder); return new UnitOrder(sc2ApiUnitOrder); } private UnitOrder(Raw.UnitOrder sc2ApiUnitOrder); private UnitOrder(Ability ability, Tag targetedUnitTag, Point targetedWorldSpacePosition, Float progress); static UnitOrder from(Raw.UnitOrder sc2ApiUnitOrder); Ability getAbility(); Optional<Tag> getTargetedUnitTag(); Optional<Point> getTargetedWorldSpacePosition(); Optional<Float> getProgress(); @Override UnitOrder generalizeAbility(UnaryOperator<Ability> generalize); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiUnitOrderIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> UnitOrder.from(nothing())) .withMessage("sc2api unit order is required"); } @Test void convertsAllFieldsFromSc2ApiUnitOrder() { assertThatAllFieldsAreConverted(UnitOrder.from(sc2ApiUnitOrder())); assertThatWorldSpacePositionInConvertedIfProvided( UnitOrder.from(sc2ApiUnitOrderWithTargetedWorldSpacePosition())); } @Test void throwsExceptionWhenAbilityIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> UnitOrder.from( without(() -> sc2ApiUnitOrder().toBuilder(), Raw.UnitOrder.Builder::clearAbilityId).build())) .withMessage("ability is required"); }
### Question: Score implements Serializable { public static Score from(ScoreOuterClass.Score sc2ApiScore) { require("sc2api score", sc2ApiScore); return new Score(sc2ApiScore); } private Score(ScoreOuterClass.Score sc2ApiScore); static Score from(ScoreOuterClass.Score sc2ApiScore); Type getType(); int getScore(); ScoreDetails getDetails(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiScoreIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Score.from(nothing())) .withMessage("sc2api score is required"); } @Test void convertsAllFieldsFromSc2ApiScore() { assertThatAllFieldsAreConverted(Score.from(sc2ApiScore())); } @Test void throwsExceptionWhenTypeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Score.from(without( () -> sc2ApiScore().toBuilder(), ScoreOuterClass.Score.Builder::clearScoreType).build())) .withMessage("type is required"); } @Test void throwsExceptionWhenScoreIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Score.from(without( () -> sc2ApiScore().toBuilder(), ScoreOuterClass.Score.Builder::clearScore).build())) .withMessage("score is required"); } @Test void throwsExceptionWhenDetailsAreNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Score.from(without( () -> sc2ApiScore().toBuilder(), ScoreOuterClass.Score.Builder::clearScoreDetails).build())) .withMessage("details is required"); } @Test void throwsExceptionWhenSc2ApiScoreTypeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Score.Type.from(nothing())) .withMessage("sc2api score type is required"); }
### Question: VitalScoreDetails implements Serializable { public static VitalScoreDetails from(ScoreOuterClass.VitalScoreDetails sc2ApiVitalScoreDetails) { require("sc2api vital score details", sc2ApiVitalScoreDetails); return new VitalScoreDetails(sc2ApiVitalScoreDetails); } private VitalScoreDetails(ScoreOuterClass.VitalScoreDetails sc2ApiVitalScoreDetails); static VitalScoreDetails from(ScoreOuterClass.VitalScoreDetails sc2ApiVitalScoreDetails); float getLife(); float getShields(); float getEnergy(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiVitalScoreDetailsIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> VitalScoreDetails.from(nothing())) .withMessage("sc2api vital score details is required"); } @Test void convertsAllFieldsFromSc2ApiVitalScoreDetails() { assertThatAllFieldsAreConverted(VitalScoreDetails.from(sc2ApiVitalScoreDetails())); } @Test void throwsExceptionWhenLifeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> VitalScoreDetails.from(without( () -> sc2ApiVitalScoreDetails().toBuilder(), ScoreOuterClass.VitalScoreDetails.Builder::clearLife).build())) .withMessage("life is required"); } @Test void throwsExceptionWhenShieldsIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> VitalScoreDetails.from(without( () -> sc2ApiVitalScoreDetails().toBuilder(), ScoreOuterClass.VitalScoreDetails.Builder::clearShields).build())) .withMessage("shields is required"); } @Test void throwsExceptionWhenEnergyIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> VitalScoreDetails.from(without( () -> sc2ApiVitalScoreDetails().toBuilder(), ScoreOuterClass.VitalScoreDetails.Builder::clearEnergy).build())) .withMessage("energy is required"); }
### Question: DebugSetUnitValue implements Sc2ApiSerializable<Debug.DebugSetUnitValue> { public static DebugSetUnitValueSyntax setUnitValue() { return new DebugSetUnitValue.Builder(); } private DebugSetUnitValue(DebugSetUnitValue.Builder builder); static DebugSetUnitValueSyntax setUnitValue(); @Override Debug.DebugSetUnitValue toSc2Api(); UnitValue getUnitValue(); Tag getUnitTag(); float getValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenUnitValueIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(setUnitValue().forUnit(Tag.from(UNIT_TAG))) .to(VITAL_SCORE_ENERGY).build()) .withMessage("unit value is required"); } @Test void throwsExceptionWhenUnitTagIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(setUnitValue()) .set(DebugSetUnitValue.UnitValue.ENERGY).to(VITAL_SCORE_ENERGY).build()) .withMessage("unit tag is required"); } @Test void throwsExceptionWhenValueIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(setUnitValue().forUnit(Tag.from(UNIT_TAG)) .set(DebugSetUnitValue.UnitValue.ENERGY)).build()) .withMessage("value is required"); }
### Question: S2Client extends DefaultSubscriber<Response> { public <T extends Request> void request(T requestData) { if (!done.get()) { require("request", requestData); if (traced) tracer.fire(requestData); channelProvider.getChannel().input(new RequestSerializer().apply(requestData)); } else { throw new IllegalStateException("Client is already stopped."); } } private S2Client(Builder builder); static S2ClientSyntax starcraft2Client(); Flowable<Response> responseStream(); void request(T requestData); void request(BuilderSyntax<T> requestDataBuilder); Response requestSync(T requestData); Maybe<Response> waitForResponse(ResponseType responseType); Response requestSync(BuilderSyntax<T> requestDataBuilder); S requestSync(T requestData, Class<S> responseClass); S requestSync( BuilderSyntax<T> requestDataBuilder, Class<S> responseClass); boolean isDone(); boolean stop(); boolean fullStop(); boolean await(); @Override void onNext(Response response); @Override void onError(Throwable throwable); @Override void onComplete(); String getConnectToIp(); Integer getConnectToPort(); int getRequestTimeoutInMillis(); int getConnectTimeoutInMillis(); boolean isTraced(); S2Client untilReady(); S2Client untilReady(Runnable onPull); @Override String toString(); }### Answer: @Test void throwsExceptionForNullRequest() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> aSampleS2Client().start().request((Request) nothing())) .withMessage("request is required"); } @Test void doesNotUseTracingIfDisabled() { DataFlowTracer tracer = mock(DataFlowTracer.class); S2Client client = aSampleS2Client().traced(false).withTracer(tracer).start(); client.request(ping()); verifyNoMoreInteractions(tracer); }
### Question: UnitPool { UnitInPool createUnit(Tag tag) { Optional<UnitInPool> existing = getUnit(tag); if (existing.isPresent()) { UnitInPool unitInPool = existing.get(); existingPool.put(tag, unitInPool); return unitInPool; } UnitInPool newUnitInPool = new UnitInPool(tag); pool.put(tag, newUnitInPool); existingPool.put(tag, newUnitInPool); return newUnitInPool; } }### Answer: @Test void addsUnitToPools() { UnitPool unitPool = new UnitPool(); UnitInPool unitInPool = unitPool.createUnit(TAG); assertThatUnitInPoolIsAddedCorrectly(unitPool, unitInPool); } @Test void addsUnitToExistingPoolIfIsPresentInPool() { UnitPool unitPool = new UnitPool(); unitPool.createUnit(TAG); UnitInPool unitInPool = unitPool.createUnit(TAG); assertThatUnitInPoolIsAddedCorrectly(unitPool, unitInPool); }
### Question: ProtoInterfaceImpl implements ProtoInterface { void setOnError(BiConsumer<ClientError, List<String>> onError) { require("onError callback", onError); this.onError = onError; } @Override boolean connectToGame( S2Controller theGame, Integer connectionTimeoutInMillis, Integer requestTimeoutInMillis, Boolean traced); @Override boolean connectToGame( String address, Integer port, Integer connectionTimeoutInMillis, Integer requestTimeoutInMillis, Boolean traced); @Override Maybe<Response> sendRequest(T requestData); @Override Maybe<Response> sendRequest(BuilderSyntax<T> requestDataBuilder); @Override Optional<Response> waitForResponse(Maybe<Response> waitFor); @Override void quit(); @Override boolean pollResponse(ResponseType type); @Override boolean hasResponsePending(ResponseType type); @Override boolean hasResponsePending(); @Override Maybe<Response> getResponsePending(ResponseType type); @Override GameStatus lastStatus(); @Override String getConnectToIp(); @Override Integer getConnectToPort(); @Override String getDataVersion(); @Override Integer getBaseBuild(); @Override Map<ResponseType, Integer> getCountUses(); @Override String toString(); }### Answer: @Test void throwsExceptionIfOnErrorCallbackIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new ProtoInterfaceImpl().setOnError(null)) .withMessage("onError callback is required"); }
### Question: ProtoInterfaceImpl implements ProtoInterface { @Override public GameStatus lastStatus() { return latestStatus; } @Override boolean connectToGame( S2Controller theGame, Integer connectionTimeoutInMillis, Integer requestTimeoutInMillis, Boolean traced); @Override boolean connectToGame( String address, Integer port, Integer connectionTimeoutInMillis, Integer requestTimeoutInMillis, Boolean traced); @Override Maybe<Response> sendRequest(T requestData); @Override Maybe<Response> sendRequest(BuilderSyntax<T> requestDataBuilder); @Override Optional<Response> waitForResponse(Maybe<Response> waitFor); @Override void quit(); @Override boolean pollResponse(ResponseType type); @Override boolean hasResponsePending(ResponseType type); @Override boolean hasResponsePending(); @Override Maybe<Response> getResponsePending(ResponseType type); @Override GameStatus lastStatus(); @Override String getConnectToIp(); @Override Integer getConnectToPort(); @Override String getDataVersion(); @Override Integer getBaseBuild(); @Override Map<ResponseType, Integer> getCountUses(); @Override String toString(); }### Answer: @Test void startsWithUnknownGameStatus() { assertThat(new ProtoInterfaceImpl().lastStatus()).isEqualTo(GameStatus.UNKNOWN); }
### Question: ProtoInterfaceImpl implements ProtoInterface { @Override public <T extends Request> Maybe<Response> sendRequest(T requestData) { require("request", requestData); if (!requestData.responseType().equals(ResponseType.PING) && responseQueue.peek(requestData.responseType())) { onError.accept(ClientError.RESPONSE_NOT_CONSUMED, Collections.emptyList()); return Maybe.empty(); } Maybe<Response> responseMaybe = s2Client.waitForResponse(requestData.responseType()); s2Client.request(requestData); countUses.compute(requestData.responseType(), (responseType, count) -> count != null ? ++count : 1); responseQueue.offer(requestData.responseType(), responseMaybe); return responseMaybe; } @Override boolean connectToGame( S2Controller theGame, Integer connectionTimeoutInMillis, Integer requestTimeoutInMillis, Boolean traced); @Override boolean connectToGame( String address, Integer port, Integer connectionTimeoutInMillis, Integer requestTimeoutInMillis, Boolean traced); @Override Maybe<Response> sendRequest(T requestData); @Override Maybe<Response> sendRequest(BuilderSyntax<T> requestDataBuilder); @Override Optional<Response> waitForResponse(Maybe<Response> waitFor); @Override void quit(); @Override boolean pollResponse(ResponseType type); @Override boolean hasResponsePending(ResponseType type); @Override boolean hasResponsePending(); @Override Maybe<Response> getResponsePending(ResponseType type); @Override GameStatus lastStatus(); @Override String getConnectToIp(); @Override Integer getConnectToPort(); @Override String getDataVersion(); @Override Integer getBaseBuild(); @Override Map<ResponseType, Integer> getCountUses(); @Override String toString(); }### Answer: @Test void throwsExceptionIfRequestIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new ProtoInterfaceImpl().sendRequest((Request) null)) .withMessage("request is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new ProtoInterfaceImpl().sendRequest((BuilderSyntax<Request>) null)) .withMessage("request is required"); }
### Question: ResponseQueue { boolean offer(ResponseType type, Maybe<Response> waitFor) { if (!pending.containsKey(type)) { if (waitFor instanceof MaybeSubject) { pending.put(type, (MaybeSubject<Response>) waitFor); return true; } else { return false; } } else { return false; } } }### Answer: @Test void allowsToStoreOnePendingResponseTypeAtTime() { ResponseQueue responseQueue = new ResponseQueue(); assertThat(responseQueue.offer(ResponseType.ACTION, MaybeSubject.create())).isTrue(); assertThat(responseQueue.offer(ResponseType.ACTION, MaybeSubject.create())).isFalse(); }
### Question: ReplaySettings { public ReplaySettings setReplayPath(Path replayPath) throws IOException { require("replay path", replayPath); replayFiles.clear(); if (replayPath.toFile().isDirectory()) { try (Stream<Path> files = Files.walk(replayPath)) { replayFiles.addAll(files.filter(p -> !Files.isDirectory(p)).collect(Collectors.toList())); } } else if (replayPath.toString().endsWith(SC2_REPLAY_EXTENSION)) { replayFiles.add(replayPath.toAbsolutePath()); } return this; } ReplaySettings setReplayRecovery(boolean replayRecovery); boolean isReplayRecovery(); ReplaySettings setReplayPath(Path replayPath); ReplaySettings loadReplayList(Path path); List<Path> getReplayFiles(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionIfEmptyPathIsProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new ReplaySettings().setReplayPath(null)) .withMessage("replay path is required"); }
### Question: ReplaySettings { public ReplaySettings loadReplayList(Path path) throws IOException { require("file with replay list", path); replayFiles.clear(); try (Stream<String> lines = Files.lines(path)) { replayFiles.addAll(lines.map(Paths::get).collect(Collectors.toList())); } return this; } ReplaySettings setReplayRecovery(boolean replayRecovery); boolean isReplayRecovery(); ReplaySettings setReplayPath(Path replayPath); ReplaySettings loadReplayList(Path path); List<Path> getReplayFiles(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionIfEmptyFileIsProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new ReplaySettings().loadReplayList(null)) .withMessage("file with replay list is required"); }
### Question: S2Coordinator { public static SettingsSyntax setup() { return new Builder(); } private S2Coordinator(Builder builder); void setupPorts(int numberOfAgents, Supplier<Integer> portStart, boolean checkSingle); static SettingsSyntax setup(); S2Coordinator startGame(); S2Coordinator startGame(LocalMap localMap); S2Coordinator startGame(BattlenetMap battlenetMap); S2Coordinator createGame(); S2Coordinator createGame(LocalMap localMap); S2Coordinator createGame(BattlenetMap battlenetMap); S2Coordinator joinGame(); boolean update(); void leaveGame(); boolean allGamesEnded(); S2Coordinator saveReplayList(Path path); boolean hasReplays(); boolean remoteSaveMap(byte[] data, Path path); Path getExePath(); void quit(); static PlayerSettings createParticipant(Race race, S2Agent bot); static PlayerSettings createComputer(Race race, Difficulty difficulty); static PlayerSettings createParticipant(Race race, S2Agent bot, String playerName); static PlayerSettings createComputer(Race race, Difficulty difficulty, String playerName); static PlayerSettings createComputer(Race race, Difficulty difficulty, AiBuild aiBuild); static PlayerSettings createComputer(Race race, Difficulty difficulty, String playerName, AiBuild aiBuild); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenAgentListIsEmpty() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> S2Coordinator.setup().setParticipants().launchStarcraft()) .withMessage("one of agents or replay observers is required"); }
### Question: DebugDraw implements Sc2ApiSerializable<Debug.DebugDraw> { public static DebugDrawSyntax draw() { return new Builder(); } private DebugDraw(Builder builder); static DebugDrawSyntax draw(); @Override Debug.DebugDraw toSc2Api(); List<DebugText> getTexts(); List<DebugLine> getLines(); List<DebugBox> getBoxes(); List<DebugSphere> getSpheres(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenOneOfDrawElementsIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ((DebugDraw.Builder) draw()).build()) .withMessage("one of draw elements is required"); }
### Question: DebugSetScore implements Sc2ApiSerializable<Debug.DebugSetScore> { public static DebugSetScoreSyntax setScore() { return new Builder(); } private DebugSetScore(Builder builder); static DebugSetScoreSyntax setScore(); @Override Debug.DebugSetScore toSc2Api(); float getScore(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenUnitTagSetIsEmpty() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ((DebugSetScore.Builder) setScore()).build()) .withMessage("score is required"); }
### Question: DebugEndGame implements Sc2ApiSerializable<Debug.DebugEndGame> { public static DebugEndGameSyntax endGame() { return new Builder(); } private DebugEndGame(Builder builder); static DebugEndGameSyntax endGame(); @Override Debug.DebugEndGame toSc2Api(); EndResult getResult(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenResultIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ((DebugEndGame.Builder) endGame()).build()) .withMessage("result is required"); }
### Question: DebugCreateUnit implements Sc2ApiSerializable<Debug.DebugCreateUnit> { public static DebugCreateUnitSyntax createUnit() { return new Builder(); } private DebugCreateUnit(Builder builder); static DebugCreateUnitSyntax createUnit(); @Override Debug.DebugCreateUnit toSc2Api(); UnitType getType(); int getOwner(); Point2d getPosition(); int getQuantity(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenTypeIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(createUnit()).forPlayer(PLAYER_ID).on(POS).build()) .withMessage("type is required"); } @Test void throwsExceptionWhenOwnerIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(createUnit().ofType(Units.PROTOSS_STALKER)).on(POS).build()) .withMessage("owner is required"); } @Test void throwsExceptionWhenPositionIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(createUnit().ofType(Units.PROTOSS_STALKER).forPlayer(PLAYER_ID)).build()) .withMessage("position is required"); } @Test void throwsExceptionWhenQuantityIsLowerThanOne() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> createUnit() .ofType(Units.PROTOSS_STALKER).forPlayer(PLAYER_ID).on(POS).withQuantity(0).build()) .withMessage("quantity has value 0 and is lower than 1"); }
### Question: DebugCreateUnit implements Sc2ApiSerializable<Debug.DebugCreateUnit> { public int getQuantity() { return quantity; } private DebugCreateUnit(Builder builder); static DebugCreateUnitSyntax createUnit(); @Override Debug.DebugCreateUnit toSc2Api(); UnitType getType(); int getOwner(); Point2d getPosition(); int getQuantity(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void serializesDefaultValueForQuantityIfNotProvided() { assertThat(defaultCreateUnit().getQuantity()).as("sc2api debug create unit: default quantity").isEqualTo(1); }
### Question: DebugSphere implements Sc2ApiSerializable<Debug.DebugSphere> { public static DebugSphereSyntax sphere() { return new Builder(); } private DebugSphere(Builder builder); static DebugSphereSyntax sphere(); @Override Debug.DebugSphere toSc2Api(); Color getColor(); Point getCenter(); float getRadius(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenColorIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(sphere().on(P0).withRadius(RADIUS)).withColor(nothing()).build()) .withMessage("color is required"); } @Test void throwsExceptionWhenCenterIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(sphere()).withRadius(RADIUS).withColor(SAMPLE_COLOR).build()) .withMessage("center is required"); } @Test void throwsExceptionWhenRadiusIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(sphere().on(P0)).withColor(SAMPLE_COLOR).build()) .withMessage("radius is required"); } @Test void throwsExceptionWhenRadiusIsNotGreaterThanZero() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> sphere().on(P0).withRadius(0).build()) .withMessage("radius has value 0.0 and is not greater than 0.0"); }
### Question: Color implements Sc2ApiSerializable<Debug.Color> { public static Color of(int r, int g, int b) { return new Color(r, g, b); } private Color(int r, int g, int b); static Color of(int r, int g, int b); @Override Debug.Color toSc2Api(); int getR(); int getG(); int getB(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final Color WHITE; static final Color RED; static final Color GREEN; static final Color YELLOW; static final Color BLUE; static final Color TEAL; static final Color PURPLE; static final Color BLACK; static final Color GRAY; }### Answer: @Test void throwsExceptionWhenColorIsNotInValidRange() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Color.of(-1, 1, 1)) .withMessage("color [r] has value -1 and is lower than 0"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Color.of(256, 1, 1)) .withMessage("color [r] has value 256 and is greater than 255"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Color.of(1, -1, 1)) .withMessage("color [g] has value -1 and is lower than 0"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Color.of(1, 256, 1)) .withMessage("color [g] has value 256 and is greater than 255"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Color.of(1, 1, -1)) .withMessage("color [b] has value -1 and is lower than 0"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Color.of(1, 1, 256)) .withMessage("color [b] has value 256 and is greater than 255"); }
### Question: Line implements Sc2ApiSerializable<Debug.Line> { public static Line of(Point p0, Point p1) { require("p0", p0); require("p1", p1); return new Line(p0, p1); } private Line(Point p0, Point p1); static Line of(Point p0, Point p1); @Override Debug.Line toSc2Api(); Point getP0(); Point getP1(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenPointsAreNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Line.of(nothing(), P1)) .withMessage("p0 is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Line.of(P0, nothing())) .withMessage("p1 is required"); }
### Question: DebugBox implements Sc2ApiSerializable<Debug.DebugBox> { public static DebugBoxSyntax box() { return new Builder(); } private DebugBox(Builder builder); static DebugBoxSyntax box(); @Override Debug.DebugBox toSc2Api(); Color getColor(); Point getMin(); Point getMax(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenColorIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> box().of(P0, P1).withColor(nothing()).build()) .withMessage("color is required"); } @Test void throwsExceptionWhenMinimumIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> box().of(nothing(), P1).withColor(SAMPLE_COLOR).build()) .withMessage("min is required"); } @Test void throwsExceptionWhenMaximumIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> box().of(P0, nothing()).withColor(SAMPLE_COLOR).build()) .withMessage("max is required"); }
### Question: QueryAvailableAbilities implements Sc2ApiSerializable<Query.RequestQueryAvailableAbilities> { public static QueryAvailableAbilitiesSyntax availableAbilities() { return new Builder(); } private QueryAvailableAbilities(Builder builder); static QueryAvailableAbilitiesSyntax availableAbilities(); @Override Query.RequestQueryAvailableAbilities toSc2Api(); Tag getUnitTag(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenUnitTagIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ((QueryAvailableAbilities.Builder) availableAbilities()).build()) .withMessage("unit tag is required"); }
### Question: QueryBuildingPlacement implements Sc2ApiSerializable<Query.RequestQueryBuildingPlacement> { public static QueryBuildingPlacementSyntax placeBuilding() { return new Builder(); } private QueryBuildingPlacement(Builder builder); static QueryBuildingPlacementSyntax placeBuilding(); @Override Query.RequestQueryBuildingPlacement toSc2Api(); Ability getAbility(); Point2d getTarget(); Optional<Tag> getPlacingUnitTag(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenAbilityIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(placeBuilding().withUnit(Tag.from(UNIT_TAG))).on(START).build()) .withMessage("ability is required"); } @Test void throwsExceptionWhenTargetIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(placeBuilding().withUnit(Tag.from(UNIT_TAG)) .useAbility(Abilities.BUILD_ARMORY)).build()) .withMessage("target is required"); }
### Question: QueryPathing implements Sc2ApiSerializable<Query.RequestQueryPathing> { public static QueryPathingSyntax path() { return new QueryPathing.Builder(); } private QueryPathing(QueryPathing.Builder builder); static QueryPathingSyntax path(); @Override Query.RequestQueryPathing toSc2Api(); Optional<Point2d> getStart(); Optional<Tag> getUnitTag(); Point2d getEnd(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenEndIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(path().from(START)).build()) .withMessage("end is required"); } @Test void throwsExceptionWhenOneOfStartCaseIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(path()).to(END).build()) .withMessage("one of start case is required"); }
### Question: BuildingPlacement implements Serializable { public static BuildingPlacement from(Query.ResponseQueryBuildingPlacement sc2ApiResponseQueryBuildingPlacement) { require("sc2api response query building placement", sc2ApiResponseQueryBuildingPlacement); return new BuildingPlacement(sc2ApiResponseQueryBuildingPlacement); } private BuildingPlacement(Query.ResponseQueryBuildingPlacement sc2ApiResponseQueryBuildingPlacement); static BuildingPlacement from(Query.ResponseQueryBuildingPlacement sc2ApiResponseQueryBuildingPlacement); ActionResult getResult(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiBuildingPlacementIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> BuildingPlacement.from(nothing())) .withMessage("sc2api response query building placement is required"); } @Test void convertsAllFieldsFromSc2ApiBuildingPlacement() { assertThatAllFieldsAreConverted(BuildingPlacement.from(sc2ApiBuildingPlacement())); } @Test void throwsExceptionWhenTagIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> BuildingPlacement.from(without( () -> sc2ApiBuildingPlacement().toBuilder(), Query.ResponseQueryBuildingPlacement.Builder::clearResult).build())) .withMessage("result is required"); }
### Question: AvailableAbilities implements Serializable, GeneralizableAbility<AvailableAbilities> { public static AvailableAbilities from(Query.ResponseQueryAvailableAbilities sc2ApiResponseQueryAvailableAbilities) { require("sc2api response query available abilities", sc2ApiResponseQueryAvailableAbilities); return new AvailableAbilities(sc2ApiResponseQueryAvailableAbilities); } private AvailableAbilities(Query.ResponseQueryAvailableAbilities sc2ApiResponseQueryAvailableAbilities); private AvailableAbilities(Set<AvailableAbility> abilities, Tag unitTag, UnitType unitType); static AvailableAbilities from(Query.ResponseQueryAvailableAbilities sc2ApiResponseQueryAvailableAbilities); Set<AvailableAbility> getAbilities(); Tag getUnitTag(); UnitType getUnitType(); @Override AvailableAbilities generalizeAbility(UnaryOperator<Ability> generalize); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiAvailableAbilitiesIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> AvailableAbilities.from(nothing())) .withMessage("sc2api response query available abilities is required"); } @Test void convertsAllFieldsFromSc2ApiAvailableAbilities() { assertThatAllFieldsAreConverted(AvailableAbilities.from(sc2ApiAvailableAbilities())); } @Test void throwsExceptionWhenUnitTagIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> AvailableAbilities.from(without( () -> sc2ApiAvailableAbilities().toBuilder(), Query.ResponseQueryAvailableAbilities.Builder::clearUnitTag).build())) .withMessage("unit tag is required"); } @Test void throwsExceptionWhenUnitTypeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> AvailableAbilities.from(without( () -> sc2ApiAvailableAbilities().toBuilder(), Query.ResponseQueryAvailableAbilities.Builder::clearUnitTypeId).build())) .withMessage("unit type is required"); }
### Question: Pathing implements Serializable { public static Pathing from(Query.ResponseQueryPathing sc2ApiResponseQueryPathing) { require("sc2api response query pathing", sc2ApiResponseQueryPathing); return new Pathing(sc2ApiResponseQueryPathing); } private Pathing(Query.ResponseQueryPathing sc2ApiResponseQueryPathing); static Pathing from(Query.ResponseQueryPathing sc2ApiResponseQueryPathing); Optional<Float> getDistance(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiPathingIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Pathing.from(nothing())) .withMessage("sc2api response query pathing is required"); } @Test void convertsAllFieldsFromSc2ApiPathing() { assertThatAllFieldsAreConverted(Pathing.from(sc2ApiPathing())); }
### Question: Versions { public static Optional<GameVersion> versionFor(int baseBuild) { return Optional.ofNullable(gameVersions.get(baseBuild)); } private Versions(); static Optional<GameVersion> versionFor(int baseBuild); static final String API_VERSION; }### Answer: @Test void providesInformationAboutGameVersions() { assertThat(Versions.versionFor(BASE_BUILD)).isNotEmpty(); }
### Question: AvailableAbility implements Serializable, GeneralizableAbility<AvailableAbility> { public static AvailableAbility from(Common.AvailableAbility sc2ApiAvailableAbility) { require("sc2api available ability", sc2ApiAvailableAbility); return new AvailableAbility(sc2ApiAvailableAbility); } private AvailableAbility(Common.AvailableAbility sc2ApiAvailableAbility); private AvailableAbility(Ability ability, boolean requiresPoint); static AvailableAbility from(Common.AvailableAbility sc2ApiAvailableAbility); Ability getAbility(); boolean isRequiresPoint(); @Override AvailableAbility generalizeAbility(UnaryOperator<Ability> generalize); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiAvailableAbilityIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> AvailableAbility.from(nothing())) .withMessage("sc2api available ability is required"); } @Test void convertsAllFieldsFromSc2ApiAvailableAbility() { assertThatAllFieldsAreConverted(AvailableAbility.from(sc2ApiAvailableAbility())); } @Test void throwsExceptionWhenAbilityIdIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> AvailableAbility.from(without( () -> sc2ApiAvailableAbility().toBuilder(), Common.AvailableAbility.Builder::clearAbilityId).build())) .withMessage("ability is required"); }
### Question: RecommendationVerticle extends AbstractVerticle { static String parseContainerIdFromHostname(String hostname) { return hostname.replaceAll("recommendation-v\\d+-", ""); } @Override void start(); static void main(String[] args); }### Answer: @Test public void parseContainerIdFromHostname() { assertThat(RecommendationVerticle.parseContainerIdFromHostname("recommendation-v1-abcdef"), equalTo("abcdef")); assertThat(RecommendationVerticle.parseContainerIdFromHostname("recommendation-v2-abcdef"), equalTo("abcdef")); assertThat(RecommendationVerticle.parseContainerIdFromHostname("recommendation-v10-abcdef"), equalTo("abcdef")); assertThat(RecommendationVerticle.parseContainerIdFromHostname("unknown"), equalTo("unknown")); assertThat(RecommendationVerticle.parseContainerIdFromHostname("localhost"), equalTo("localhost")); }
### Question: MDCCodeExtractor { public List<String> getCodesAsList(String manuelDeCodageText) throws MDCSyntaxError { SignListBuilder builder = new SignListBuilder(); MDCParserFacade parser = new MDCParserFacade(builder); parser.parse(new StringReader(manuelDeCodageText)); return builder.result; } String[] getCodes(String manuelDeCodageText); List<String> getCodesAsList(String manuelDeCodageText); boolean isNormalize(); void setNormalize(boolean normalize); boolean isSuppressNonGlyphs(); void setSuppressNonGlyphs(boolean suppressNonGlyphs); static void main(String[] args); }### Answer: @Test public void testSimple() throws MDCSyntaxError { String mdc = "i-w-r:a-C1-m-pt:p*t"; MDCCodeExtractor extractor= new MDCCodeExtractor(); List<String> codeList = extractor.getCodesAsList(mdc); assertEquals(Arrays.asList("M17","G43","D21","D36","C1", "G17", "N1", "Q3", "X1"), codeList); } @Test public void test3() throws MDCSyntaxError { String mdc = "3"; MDCCodeExtractor extractor= new MDCCodeExtractor(); List<String> codeList = extractor.getCodesAsList(mdc); assertEquals(Arrays.asList("3"), codeList); }
### Question: CprAbbsResponseParser { public List<String> extractCprNumbersWithoutHeaders(String soapResponse) throws CprAbbsException { try { Document document = createDomTree(soapResponse); NodeList nodeList = extractChangedCprsNodes(document); return convertNodeListToCprStrings(nodeList); } catch (Exception e) { throw new CprAbbsException(e); } } List<String> extractCprNumbers(String soapResponse); List<String> extractCprNumbersWithoutHeaders(String soapResponse); }### Answer: @Test public void testBasicParserWithoutHeaders() throws CprAbbsException { CprAbbsResponseParser parser = new CprAbbsResponseParser(); List<String> extractCprNumbers = parser.extractCprNumbersWithoutHeaders(exampleSoapResponse); assertEquals(2, extractCprNumbers.size()); assertEquals("0101822231", extractCprNumbers.get(0)); assertEquals("0101821234", extractCprNumbers.get(1)); }
### Question: CprAbbsResponseParser { public List<String> extractCprNumbers(String soapResponse) throws CprAbbsException { int start = soapResponse.indexOf("<?xml"); if(start == -1) { throw new CprAbbsException("Invalid message body on call to CPR Abbs"); } String soapResponseWithoutHeader = soapResponse.substring(start); return extractCprNumbersWithoutHeaders(soapResponseWithoutHeader); } List<String> extractCprNumbers(String soapResponse); List<String> extractCprNumbersWithoutHeaders(String soapResponse); }### Answer: @Test public void testBasicParser() throws CprAbbsException { CprAbbsResponseParser parser = new CprAbbsResponseParser(); List<String> extractCprNumbers = parser.extractCprNumbers(exampleResponseWithHeaders); assertEquals(2, extractCprNumbers.size()); assertEquals("0101822231", extractCprNumbers.get(0)); assertEquals("0101821234", extractCprNumbers.get(1)); }
### Question: ReplicaHiveEndpoint extends HiveEndpoint { @Override public TableAndStatistics getTableAndStatistics(TableReplication tableReplication) { return super.getTableAndStatistics(tableReplication.getReplicaDatabaseName(), tableReplication.getReplicaTableName()); } ReplicaHiveEndpoint( String name, HiveConf hiveConf, Supplier<CloseableMetaStoreClient> metaStoreClientSupplier); @Override TableAndStatistics getTableAndStatistics(TableReplication tableReplication); }### Answer: @Test public void useCorrectReplicaTableName() throws Exception { ReplicaHiveEndpoint replicaDiffEndpoint = new ReplicaHiveEndpoint("name", hiveConf, metastoreSupplier); when(metastoreSupplier.get()).thenReturn(metastoreClient); when(metastoreClient.getTable("dbname", "tableName")).thenReturn(table); when(table.getSd()).thenReturn(sd); when(tableReplication.getReplicaDatabaseName()).thenReturn("dbname"); when(tableReplication.getReplicaTableName()).thenReturn("tableName"); TableAndStatistics tableAndStats = replicaDiffEndpoint.getTableAndStatistics(tableReplication); assertThat(tableAndStats.getTable(), is(table)); }
### Question: AvroSerDeTransformation { @VisibleForTesting String getAvroSchemaFileName(String avroSchemaSource) { if (avroSchemaSource == null) { return ""; } return avroSchemaSource.substring(avroSchemaSource.lastIndexOf("/") + 1, avroSchemaSource.length()); } @Autowired AvroSerDeTransformation(HiveConf sourceHiveConf, HiveConf replicaHiveConf); }### Answer: @Test public void getAvroSchemaFileName() throws Exception { String dummyUri = "testing/avro.avsc"; assertThat(avroSerDeTransformation.getAvroSchemaFileName(dummyUri), is("avro.avsc")); }
### Question: AvroSerDeTransformation { @VisibleForTesting String addTrailingSlash(String str) { if (str != null && str.charAt(str.length() - 1) != '/') { str += "/"; } return str; } @Autowired AvroSerDeTransformation(HiveConf sourceHiveConf, HiveConf replicaHiveConf); }### Answer: @Test public void addTrailingSlash() throws Exception { String dummyUri = "testing/avro"; dummyUri = avroSerDeTransformation.addTrailingSlash(dummyUri); assertThat(dummyUri, is("testing/avro/")); } @Test public void addTrailingSlashOnlyAddsOne() throws Exception { String dummyUri = "testing/avro/"; dummyUri = avroSerDeTransformation.addTrailingSlash(dummyUri); assertThat(dummyUri, is("testing/avro/")); }
### Question: TableProcessor implements NodeProcessor { @Override public Object process(Node node, Stack<Node> stack, NodeProcessorCtx procCtx, Object... nodeOutputs) throws SemanticException { ASTNode astNode = (ASTNode) node; if (astNode.getToken() != null && astNode.getToken().getText() != null) { if ("TOK_TABNAME".equals(astNode.getToken().getText())) { tables.add(extractTableName(astNode)); } } return null; } @Override Object process(Node node, Stack<Node> stack, NodeProcessorCtx procCtx, Object... nodeOutputs); List<String> getTables(); }### Answer: @Test(expected = NullPointerException.class) public void unqualifiedTableNameFailsIsSessionIsNotSet() throws Exception { ArrayList<Node> children = new ArrayList<>(); children.add(tableNode); when(node.getChildren()).thenReturn(children); when(node.getChildCount()).thenReturn(children.size()); when(node.getChild(0)).thenReturn(tableNode); when(node.getType()).thenReturn(HiveParser.TOK_TABNAME); when(token.getText()).thenReturn("TOK_TABNAME"); processor.process(node, null, null); }
### Question: TableTranslation { String toUnescapedQualifiedOriginalName() { return toUnescapedQualifiedName(originalDatabaseName, originalTableName); } TableTranslation( String originalDatabaseName, String originalTableName, String replicaDatabaseName, String replicaTableName); @Override boolean equals(Object obj); }### Answer: @Test public void unescapedOriginalName() { assertThat(tableTranslation.toUnescapedQualifiedOriginalName(), is("odb.o_table")); }
### Question: S3S3CopierOptions { public CannedAccessControlList getCannedAcl() { String cannedAcl = MapUtils.getString(copierOptions, Keys.CANNED_ACL.keyName(), null); if (cannedAcl != null) { return CannedAclUtils.toCannedAccessControlList(cannedAcl); } return null; } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer: @Test public void getCannedAcl() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.CANNED_ACL.keyName(), CannedAccessControlList.BucketOwnerFullControl.toString()); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getCannedAcl(), is(CannedAccessControlList.BucketOwnerFullControl)); } @Test public void getCannedAclDefaultIsNull() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertNull(options.getCannedAcl()); }
### Question: TableTranslation { String toEscapedQualifiedOriginalName() { return toEscapedQualifiedName(originalDatabaseName, originalTableName); } TableTranslation( String originalDatabaseName, String originalTableName, String replicaDatabaseName, String replicaTableName); @Override boolean equals(Object obj); }### Answer: @Test public void escapedOriginalName() { assertThat(tableTranslation.toEscapedQualifiedOriginalName(), is("`odb`.`o_table`")); }
### Question: TableTranslation { String toUnescapedQualifiedReplicaName() { return toUnescapedQualifiedName(replicaDatabaseName, replicaTableName); } TableTranslation( String originalDatabaseName, String originalTableName, String replicaDatabaseName, String replicaTableName); @Override boolean equals(Object obj); }### Answer: @Test public void unescapedReplicaName() { assertThat(tableTranslation.toUnescapedQualifiedReplicaName(), is("rdb.r_table")); }
### Question: TableTranslation { String toEscapedQualifiedReplicaName() { return toEscapedQualifiedName(replicaDatabaseName, replicaTableName); } TableTranslation( String originalDatabaseName, String originalTableName, String replicaDatabaseName, String replicaTableName); @Override boolean equals(Object obj); }### Answer: @Test public void escapedReplicaName() { assertThat(tableTranslation.toEscapedQualifiedReplicaName(), is("`rdb`.`r_table`")); }
### Question: TableTranslation { String toUnescapedOriginalTableReference() { return unescapedTableReference(originalTableName); } TableTranslation( String originalDatabaseName, String originalTableName, String replicaDatabaseName, String replicaTableName); @Override boolean equals(Object obj); }### Answer: @Test public void unescapedOriginalTableReference() { assertThat(tableTranslation.toUnescapedOriginalTableReference(), is("o_table.")); }
### Question: TableTranslation { String toEscapedOriginalTableReference() { return escapedTableReference(originalTableName); } TableTranslation( String originalDatabaseName, String originalTableName, String replicaDatabaseName, String replicaTableName); @Override boolean equals(Object obj); }### Answer: @Test public void escapedOriginalTableReference() { assertThat(tableTranslation.toEscapedOriginalTableReference(), is("`o_table`.")); }
### Question: TableTranslation { String toUnescapedReplicaTableReference() { return unescapedTableReference(replicaTableName); } TableTranslation( String originalDatabaseName, String originalTableName, String replicaDatabaseName, String replicaTableName); @Override boolean equals(Object obj); }### Answer: @Test public void unescapedReplicaTableReference() { assertThat(tableTranslation.toUnescapedReplicaTableReference(), is("r_table.")); }
### Question: TableTranslation { String toEscapedReplicaTableReference() { return escapedTableReference(replicaTableName); } TableTranslation( String originalDatabaseName, String originalTableName, String replicaDatabaseName, String replicaTableName); @Override boolean equals(Object obj); }### Answer: @Test public void escapedReplicaTableReference() { assertThat(tableTranslation.toEscapedReplicaTableReference(), is("`r_table`.")); }
### Question: HqlTranslator { Map<String, List<TableTranslation>> getMappings() { return mappings; } @Autowired HqlTranslator(TableReplications tableReplications); String translate(String viewQualifiedName, String hql); }### Answer: @Test public void mappings() { Map<String, String> replicationMappings = ImmutableMap .<String, String> builder() .put("db1.table_a", "r_db.a_table") .put("odb.o_table", "r_db.r_table") .build(); when(tableReplication.getTableMappings()).thenReturn(replicationMappings); HqlTranslator translator = new HqlTranslator(tableReplications); assertThat(translator.getMappings().size(), is(1)); List<TableTranslation> translations = translator.getMappings().get(VIEW_NAME); assertThat(translations.size(), is(2)); assertThat(translations.contains(new TableTranslation("db1", "table_a", "r_db", "a_table")), is(true)); assertThat(translations.contains(new TableTranslation("odb", "o_table", "r_db", "r_table")), is(true)); }
### Question: InetSocketAddressFactory { public InetSocketAddress newInstance(String host) { int index = host.indexOf(':'); if (index == -1) { throw new IllegalArgumentException("No port found in host:" + host); } String hostname = host.substring(0, index); int port = Integer.parseInt(host.substring(index + 1)); return new InetSocketAddress(hostname, port); } InetSocketAddress newInstance(String host); }### Answer: @Test(expected = IllegalArgumentException.class) public void noPort() { factory.newInstance("localhost"); } @Test public void typical() { InetSocketAddress address = factory.newInstance("localhost:1234"); assertThat(address.getHostName(), is("localhost")); assertThat(address.getPort(), is(1234)); }
### Question: S3S3CopierOptions { public int getMaxCopyAttempts() { Integer maxCopyAttempts = MapUtils.getInteger(copierOptions, Keys.MAX_COPY_ATTEMPTS.keyName(), 3); return maxCopyAttempts < 1 ? 3 : maxCopyAttempts; } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer: @Test public void getMaxCopyAttempts() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.MAX_COPY_ATTEMPTS.keyName(), 3); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getMaxCopyAttempts(), is(3)); } @Test public void getMaxCopyAttemptsDefaultIsThree() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getMaxCopyAttempts(), is(3)); } @Test public void getMaxCopyAttemptsDefaultIfLessThanOne() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.MAX_COPY_ATTEMPTS.keyName(), -1); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getMaxCopyAttempts(), is(3)); }
### Question: JobCounterGauge implements Gauge<Long> { @Override public Long getValue() { try { if (groupName != null) { return job.getCounters().findCounter(groupName, counterName).getValue(); } else { return job.getCounters().findCounter(counter).getValue(); } } catch (IOException e) { LOG.warn("Could not get value for counter " + counter, e); } return 0L; } JobCounterGauge(Job job, String groupName, String counterName); JobCounterGauge(Job job, Enum<?> counter); private JobCounterGauge(Job job, Enum<?> counter, String groupName, String counterName); @Override Long getValue(); }### Answer: @Test public void getValue() { jobCounterGauge = new JobCounterGauge(job, key); Long result = jobCounterGauge.getValue(); assertThat(result, is(expectedResult)); } @Test public void getValueGroupName() { jobCounterGauge = new JobCounterGauge(job, groupName, counterName); Long result = jobCounterGauge.getValue(); assertThat(result, is(expectedResult)); } @Test public void getValueCannotGetCounters() throws IOException { when(job.getCounters()).thenThrow(new IOException()); jobCounterGauge = new JobCounterGauge(job, key); Long result = jobCounterGauge.getValue(); assertThat(result, is(0L)); }
### Question: MetricsConf { @Bean MetricSender metricSender(ValidatedGraphite validatedGraphite) { if (validatedGraphite.isEnabled()) { return GraphiteMetricSender.newInstance(validatedGraphite.getHost(), validatedGraphite.getFormattedPrefix()); } return MetricSender.DEFAULT_LOG_ONLY; } }### Answer: @Test public void graphiteMetricSender() { when(validatedGraphite.getHost()).thenReturn("localhost:123"); when(validatedGraphite.getFormattedPrefix()).thenReturn("prefix.namespace"); when(validatedGraphite.isEnabled()).thenReturn(true); MetricSender sender = new MetricsConf().metricSender(validatedGraphite); assertTrue(sender instanceof GraphiteMetricSender); } @Test public void defaultMetricSender() { when(validatedGraphite.isEnabled()).thenReturn(false); MetricSender sender = new MetricsConf().metricSender(validatedGraphite); assertTrue(sender == MetricSender.DEFAULT_LOG_ONLY); }
### Question: MetricsConf { @Bean ScheduledReporterFactory runningScheduledReporterFactory( MetricRegistry runningMetricRegistry, ValidatedGraphite validatedGraphite) { if (validatedGraphite.isEnabled()) { return new GraphiteScheduledReporterFactory(runningMetricRegistry, validatedGraphite.getHost(), validatedGraphite.getFormattedPrefix()); } return new LoggingScheduledReporterFactory(runningMetricRegistry); } }### Answer: @Test public void graphiteReporter() { when(validatedGraphite.isEnabled()).thenReturn(true); ScheduledReporterFactory reporterFactory = new MetricsConf().runningScheduledReporterFactory(new MetricRegistry(), validatedGraphite); assertTrue(reporterFactory instanceof GraphiteScheduledReporterFactory); } @Test public void defaultReporter() { when(validatedGraphite.isEnabled()).thenReturn(false); ScheduledReporterFactory reporterFactory = new MetricsConf().runningScheduledReporterFactory(new MetricRegistry(), validatedGraphite); assertTrue(reporterFactory instanceof LoggingScheduledReporterFactory); }
### Question: GraphiteLoader { Graphite load(Path path) { Graphite graphite = new Graphite(); if (path != null) { graphite.setConfig(path); Properties properties = loadProperties(path); graphite.setHost(properties.getProperty("graphite.host")); graphite.setPrefix(properties.getProperty("graphite.prefix")); graphite.setNamespace(properties.getProperty("graphite.namespace")); } return graphite; } GraphiteLoader(Configuration conf); }### Answer: @Test public void readAllProps() throws IOException { Properties properties = new Properties(); properties.put("graphite.host", "h"); properties.put("graphite.prefix", "p"); properties.put("graphite.namespace", "n"); try (OutputStream outputStream = new FileOutputStream(clusterProperties)) { properties.store(outputStream, null); } Graphite graphite = loader.load(path); assertThat(graphite.getConfig(), is(path)); assertThat(graphite.getHost(), is("h")); assertThat(graphite.getPrefix(), is("p")); assertThat(graphite.getNamespace(), is("n")); } @Test public void nullPath() throws IOException { Graphite graphite = loader.load(null); assertThat(graphite.getConfig(), is(nullValue())); assertThat(graphite.getHost(), is(nullValue())); assertThat(graphite.getPrefix(), is(nullValue())); assertThat(graphite.getNamespace(), is(nullValue())); } @Test(expected = CircusTrainException.class) public void pathDoesNotExist() throws IOException { loader.load(new Path(new File(temp.getRoot(), "dummy.properties").toURI())); } @SuppressWarnings("unchecked") @Test(expected = CircusTrainException.class) public void ioException() throws IOException { Path mockPath = mock(Path.class); when(mockPath.getFileSystem(conf)).thenThrow(IOException.class); loader.load(mockPath); }
### Question: Graphite { public void setHost(String host) { this.host = host; } boolean isEnabled(); Path getConfig(); void setConfig(Path config); String getHost(); void setHost(String host); String getPrefix(); void setPrefix(String prefix); String getNamespace(); void setNamespace(String namespace); }### Answer: @Test public void validHostAndPort() { graphite.setHost("foo.com:1234"); Set<ConstraintViolation<Graphite>> violations = validator.validate(graphite); assertThat(violations.size(), is(0)); } @Test public void missingPort() { graphite.setHost("foo"); Set<ConstraintViolation<Graphite>> violations = validator.validate(graphite); assertThat(violations.size(), is(1)); } @Test public void nullHost() { graphite.setHost(null); Set<ConstraintViolation<Graphite>> violations = validator.validate(graphite); assertThat(violations.size(), is(0)); }
### Question: JobMetrics implements Metrics { @Override public Map<String, Long> getMetrics() { return metrics; } JobMetrics(Job job, String bytesReplicatedGroup, String bytesReplicatedCounter); JobMetrics(Job job, Enum<?> bytesReplicatedCounter); JobMetrics(Job job, String bytesReplicatedKey); @Override Map<String, Long> getMetrics(); @Override long getBytesReplicated(); }### Answer: @Test public void nullJob() throws Exception { Map<String, Long> metrics = new JobMetrics(null, GROUP, COUNTER).getMetrics(); assertThat(metrics.size(), is(0)); } @Test public void nullCounters() throws Exception { when(job.getCounters()).thenReturn(null); Map<String, Long> metrics = new JobMetrics(job, GROUP, COUNTER).getMetrics(); assertThat(metrics.size(), is(0)); }
### Question: BufferedPartitionFetcher implements PartitionFetcher { @Override public Partition fetch(String partitionName) { int partitionPosition = partitionNames.indexOf(partitionName); if (partitionPosition < 0) { throw new PartitionNotFoundException("Unknown partition " + partitionName); } if (!buffer.containsKey(partitionName)) { bufferPartitions(partitionPosition); } return buffer.get(partitionName); } BufferedPartitionFetcher(IMetaStoreClient metastore, Table table, short bufferSize); @Override Partition fetch(String partitionName); }### Answer: @Test(expected = PartitionNotFoundException.class) public void unknowPartition() throws Exception { when(metastore.getPartitionsByNames(DATABASE_NAME, TABLE_NAME, Arrays.asList("a=01", "a=02", "a=03"))) .thenReturn(Arrays.asList(p01, p02, p03)); BufferedPartitionFetcher fetcher = spy(new BufferedPartitionFetcher(metastore, table, (short) 10)); fetcher.fetch("a=10"); }
### Question: HiveLanguageParser { public void parse(String statement, NodeProcessor nodeProcessor) { Context parserContext; try { parserContext = new Context(hiveConf); } catch (IOException e) { throw new RuntimeException("Unable to create Context for parser", e); } ParseDriver parserDriver = new ParseDriver(); ASTNode tree; try { tree = parserDriver.parse(statement, parserContext); } catch (ParseException e) { throw new HiveParseException(e); } Map<Rule, NodeProcessor> rules = new LinkedHashMap<>(); Dispatcher dispatcher = new DefaultRuleDispatcher(nodeProcessor, rules, null); GraphWalker walker = new DefaultGraphWalker(dispatcher); List<Node> topNodes = new ArrayList<>(); topNodes.add(tree); try { walker.startWalking(topNodes, null); } catch (SemanticException e) { throw new HiveSemanticException(e); } } HiveLanguageParser(HiveConf hiveConfiguration); void parse(String statement, NodeProcessor nodeProcessor); }### Answer: @SuppressWarnings("unchecked") @Test public void typical() throws Exception { parser.parse(CREATE_TABLE_STATEMENT, nodeProcessor); verify(nodeProcessor, times(49)).process(any(Node.class), any(Stack.class), any(NodeProcessorCtx.class), anyVararg()); } @Test(expected = HiveParseException.class) public void invalidSyntax() throws Exception { parser.parse("CREATE TABLE abc () LOCATION 'path'", nodeProcessor); }
### Question: S3S3CopierOptions { public String getAssumedRole() { return MapUtils.getString(copierOptions, Keys.ASSUME_ROLE.keyName(), null); } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer: @Test public void getAssumedRole() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.ASSUME_ROLE.keyName(), "iam:role:1234:user"); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getAssumedRole(), is("iam:role:1234:user")); } @Test public void getAssumedRoleDefaultIsNull() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertNull(options.getAssumedRole()); }
### Question: BindGoogleHadoopFileSystem { public void bindFileSystem(Configuration configuration) { LOG.debug("Binding GoogleHadoopFileSystem"); configuration.set(GS_FS_IMPLEMENTATION, GoogleHadoopFileSystem.class.getName()); configuration.set(GS_ABSTRACT_FS, GoogleHadoopFS.class.getName()); configuration.set(GCP_SERVICE_ACCOUNT_ENABLE, "true"); configuration.set(GCP_PROJECT_ID, "_THIS_VALUE_DOESNT_MATTER"); loadGSFileSystem(configuration); } void bindFileSystem(Configuration configuration); }### Answer: @Test public void bindFileSystemTest() throws Exception { Configuration conf = new Configuration(); BindGoogleHadoopFileSystem binder = new BindGoogleHadoopFileSystem(); binder.bindFileSystem(conf); assertNotNull(conf.get(GCP_PROJECT_ID)); assertEquals("true", conf.get(GCP_SERVICE_ACCOUNT_ENABLE)); assertEquals(GoogleHadoopFileSystem.class.getName(), conf.get(GS_FS_IMPLEMENTATION)); assertEquals(GoogleHadoopFS.class.getName(), conf.get(GS_ABSTRACT_FS)); }
### Question: GCPCredentialPathProvider { public Path newPath() { String credentialProviderPath = security.getCredentialProvider(); if (isBlank(credentialProviderPath)) { return null; } java.nio.file.Path currentDirectory = Paths.get(System.getProperty("user.dir")); java.nio.file.Path pathToCredentialsFile = Paths.get(security.getCredentialProvider()); if (pathToCredentialsFile.isAbsolute()) { java.nio.file.Path pathRelative = currentDirectory.relativize(pathToCredentialsFile); return new Path(pathRelative.toString()); } else { return new Path(pathToCredentialsFile.toString()); } } @Autowired GCPCredentialPathProvider(GCPSecurity security); Path newPath(); }### Answer: @Test public void newInstanceWithRelativePath() { String relativePath = "../test.json"; security.setCredentialProvider(relativePath); String result = new GCPCredentialPathProvider(security).newPath().toString(); assertThat(result, is(relativePath)); } @Test public void newInstanceWithAbsolutePath() { security.setCredentialProvider("/test.json"); String result = new GCPCredentialPathProvider(security).newPath().toString(); assertFalse(new Path(result).isAbsolute()); assertThat(result, startsWith("../")); } @Test public void newInstanceWithBlankPath() { security.setCredentialProvider(""); Path result = new GCPCredentialPathProvider(security).newPath(); assertNull(result); }
### Question: GCPBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (CommonBeans.BEAN_BASE_CONF.equals(beanName)) { Configuration baseConf = (Configuration) bean; setHadoopConfiguration(baseConf); return baseConf; } return bean; } @Autowired GCPBeanPostProcessor( GCPCredentialPathProvider credentialPathProvider, DistributedFileSystemPathProvider dfsPathProvider, BindGoogleHadoopFileSystem bindGoogleHadoopFileSystem, FileSystemFactory fileSystemFactory, GCPCredentialCopier credentialCopier); @Override Object postProcessBeforeInitialization(Object bean, String beanName); @Override Object postProcessAfterInitialization(Object bean, String beanName); }### Answer: @Test public void postProcessAfterInitializationWithIncorrectBeanName() throws Exception { String beanName = "notBaseConf"; processor.postProcessAfterInitialization(configuration, beanName); verifyZeroInteractions(credentialPathProvider, bindGoogleHadoopFileSystem, credentialCopier); } @Test public void postProcessAfterInitializationWithConfigurationBeanProviderPathIsNotNull() throws Exception { String beanName = CommonBeans.BEAN_BASE_CONF; when(credentialPathProvider.newPath()).thenReturn(new Path("/test.json")); when(fileSystemFactory.getFileSystem(configuration)).thenReturn(fileSystem); processor.postProcessAfterInitialization(configuration, beanName); verify(bindGoogleHadoopFileSystem).bindFileSystem(configuration); verify(credentialCopier) .copyCredentials(fileSystem, configuration, credentialPathProvider, distributedFileSystemPathProvider); } @Test public void postProcessAfterInitializationWithConfigurationBeanProviderPathIsNull() throws Exception { String beanName = CommonBeans.BEAN_BASE_CONF; when(credentialPathProvider.newPath()).thenReturn(null); processor.postProcessAfterInitialization(configuration, beanName); verifyZeroInteractions(bindGoogleHadoopFileSystem, credentialCopier, fileSystemFactory); }
### Question: GCPCredentialCopier { public void copyCredentials( FileSystem fs, Configuration conf, GCPCredentialPathProvider credentialPathProvider, DistributedFileSystemPathProvider dfsPathProvider) { try { Path source = credentialPathProvider.newPath(); Path destination = dfsPathProvider.newPath(conf); copyCredentialIntoHdfs(fs, source, destination); linkRelativePathInDistributedCache(conf, source, destination); } catch (IOException | URISyntaxException e) { throw new CircusTrainException(e); } } void copyCredentials( FileSystem fs, Configuration conf, GCPCredentialPathProvider credentialPathProvider, DistributedFileSystemPathProvider dfsPathProvider); }### Answer: @Test public void copyCredentialsWithCredentialProviderSupplied() throws Exception { copier.copyCredentials(fileSystem, conf, credentialPathProvider, distributedFileSystemPathProvider); verify(fileSystem).copyFromLocalFile(credentialsFileRelativePath, dfsAbsolutePath); verify(fileSystem).deleteOnExit(dfsDirectory); assertNotNull(conf.get(DISTRIBUTED_CACHE_PROPERTY)); assertThat(conf.get(DISTRIBUTED_CACHE_PROPERTY), is(dfsAbsolutePath + SYMLINK_FLAG + credentialsFileRelativePath)); } @Test(expected = CircusTrainException.class) public void copyCredentialsWhenFileDoesntExistThrowsException() throws Exception { doThrow(new IOException("File does not exist")) .when(fileSystem) .copyFromLocalFile(any(Path.class), any(Path.class)); copier.copyCredentials(fileSystem, conf, credentialPathProvider, distributedFileSystemPathProvider); }
### Question: DistCpCopierFactory implements CopierFactory { @Override public boolean supportsSchemes(String sourceScheme, String replicaScheme) { return true; } @Autowired DistCpCopierFactory(@Value("#{sourceHiveConf}") Configuration conf, MetricRegistry runningMetricsRegistry); @Override boolean supportsSchemes(String sourceScheme, String replicaScheme); @Override Copier newInstance(CopierContext copierContext); @Override Copier newInstance( String eventId, Path sourceBaseLocation, Path replicaLocation, Map<String, Object> copierOptions); @Override Copier newInstance( String eventId, Path sourceBaseLocation, List<Path> sourceSubLocations, Path replicaLocation, Map<String, Object> copierOptions); }### Answer: @Test public void supportSchemes() { DistCpCopierFactory factory = new DistCpCopierFactory(conf, metricRegistry); assertThat(factory.supportsSchemes("hdfs", "s3a"), is(true)); assertThat(factory.supportsSchemes("hdfs", "s3"), is(true)); assertThat(factory.supportsSchemes("hdfs", "s3n"), is(true)); assertThat(factory.supportsSchemes("hdfs", "hdfs"), is(true)); assertThat(factory.supportsSchemes("hdfs", "file"), is(true)); assertThat(factory.supportsSchemes("hdfs", "other"), is(true)); }
### Question: HdfsDataManipulatorFactory implements DataManipulatorFactory { @Override public boolean supportsSchemes(String sourceScheme, String replicaScheme) { return true; } @Autowired HdfsDataManipulatorFactory(@Value("#{replicaHiveConf}") Configuration conf); @Override DataManipulator newInstance(Path path, Map<String, Object> copierOptions); @Override boolean supportsSchemes(String sourceScheme, String replicaScheme); }### Answer: @Test public void checkSupportsHdfs() { sourceLocation = hdfsPath; replicaLocation = hdfsPath; assertTrue(dataManipulatorFactory.supportsSchemes(sourceLocation, replicaLocation)); } @Test public void checkSupportsHdfsUpperCase() { sourceLocation = hdfsPath.toUpperCase(); replicaLocation = hdfsPath.toUpperCase(); assertTrue(dataManipulatorFactory.supportsSchemes(sourceLocation, replicaLocation)); } @Test public void checkSupportsS3ToHdfs() { sourceLocation = s3Path; replicaLocation = hdfsPath; assertTrue(dataManipulatorFactory.supportsSchemes(sourceLocation, replicaLocation)); } @Test public void checkSupportsS3() { sourceLocation = s3Path; replicaLocation = s3Path; assertTrue(dataManipulatorFactory.supportsSchemes(sourceLocation, replicaLocation)); } @Test public void checkSupportsHdfsToS3() { sourceLocation = hdfsPath; replicaLocation = s3Path; assertTrue(dataManipulatorFactory.supportsSchemes(sourceLocation, replicaLocation)); } @Test public void checkSupportsRandomPaths() { sourceLocation = "<path>"; replicaLocation = "<path>"; assertTrue(dataManipulatorFactory.supportsSchemes(sourceLocation, replicaLocation)); }
### Question: SourceHiveEndpoint extends HiveEndpoint { @Override public TableAndStatistics getTableAndStatistics(TableReplication tableReplication) { SourceTable sourceTable = tableReplication.getSourceTable(); return super.getTableAndStatistics(sourceTable.getDatabaseName(), sourceTable.getTableName()); } SourceHiveEndpoint( String name, HiveConf hiveConf, Supplier<CloseableMetaStoreClient> metaStoreClientSupplier); @Override TableAndStatistics getTableAndStatistics(TableReplication tableReplication); }### Answer: @Test public void useCorrectReplicaTableName() throws Exception { SourceHiveEndpoint replicaDiffEndpoint = new SourceHiveEndpoint("name", hiveConf, metastoreSupplier); when(metastoreSupplier.get()).thenReturn(metastoreClient); when(metastoreClient.getTable("dbname", "tableName")).thenReturn(table); when(table.getSd()).thenReturn(sd); when(tableReplication.getSourceTable()).thenReturn(sourceTable); when(sourceTable.getDatabaseName()).thenReturn("dbname"); when(sourceTable.getTableName()).thenReturn("tableName"); TableAndStatistics tableAndStats = replicaDiffEndpoint.getTableAndStatistics(tableReplication); assertThat(tableAndStats.getTable(), is(table)); }
### Question: RelativePathFunction implements Function<FileStatus, String> { @Override public String apply(@Nonnull FileStatus fileStatus) { return DistCpUtils.getRelativePath(sourceRootPath, fileStatus.getPath()); } RelativePathFunction(Path sourceRootPath); @Override String apply(@Nonnull FileStatus fileStatus); }### Answer: @Test public void typical() { Path sourceRootPath = new Path("/root/"); Path path = new Path("/root/foo/bar/"); when(fileStatus.getPath()).thenReturn(path); String relativePath = new RelativePathFunction(sourceRootPath).apply(fileStatus); assertThat(relativePath, is("/foo/bar")); }
### Question: CircusTrainCopyListing extends SimpleCopyListing { static void setAsCopyListingClass(Configuration conf) { conf.setClass(CONF_LABEL_COPY_LISTING_CLASS, CircusTrainCopyListing.class, CopyListing.class); } CircusTrainCopyListing(Configuration configuration, Credentials credentials); @Override void doBuildListing(Path pathToListFile, DistCpOptions options); }### Answer: @Test public void copyListingClass() { CircusTrainCopyListing.setAsCopyListingClass(conf); assertThat(conf.get(DistCpConstants.CONF_LABEL_COPY_LISTING_CLASS), is(CircusTrainCopyListing.class.getName())); }
### Question: CircusTrainCopyListing extends SimpleCopyListing { static Path getRootPath(Configuration conf) { String pathString = conf.get(CONF_ROOT_PATH); if (pathString == null) { throw new CircusTrainException("No root path was set."); } return new Path(pathString); } CircusTrainCopyListing(Configuration configuration, Credentials credentials); @Override void doBuildListing(Path pathToListFile, DistCpOptions options); }### Answer: @Test(expected = CircusTrainException.class) public void rootPathNotSet() { CircusTrainCopyListing.getRootPath(conf); }
### Question: IoUtil { public static void closeSilently(Closeable... closeables) { closeSilently(null, closeables); } private IoUtil(); static void closeSilently(Closeable... closeables); static void closeSilently(Logger log, Closeable... closeables); }### Answer: @Test public void closeSilentlyNoCloseable() { IoUtil.closeSilently(logger); verifyNoMoreInteractions(logger); } @Test public void closeSilentlyTypical() throws Exception { IoUtil.closeSilently(logger, closeable); verify(closeable).close(); verifyNoMoreInteractions(logger); } @Test public void closeSilentlyWhenCloseThrowsException() throws Exception { RuntimeException e = new RuntimeException(); doThrow(e).when(closeable).close(); IoUtil.closeSilently(logger, closeable); verify(closeable).close(); verify(logger).debug(anyString(), eq(closeable), eq(e)); }
### Question: ConfigurationUtil { public static <T> void publish(Configuration configuration, String label, T value) { configuration.set(label, String.valueOf(value)); } private ConfigurationUtil(); static void publish(Configuration configuration, String label, T value); static int getInt(Configuration configuration, String label); static long getLong(Configuration configuration, String label); static Class<? extends InputFormat> getStrategy(Configuration conf, S3MapReduceCpOptions options); }### Answer: @Test public void publish() { class T { @Override public String toString() { return "Hello world!"; } } ConfigurationUtil.publish(config, "a.b.c", new T()); assertThat(config.get("a.b.c"), is("Hello world!")); }
### Question: ConfigurationUtil { public static int getInt(Configuration configuration, String label) { int value = configuration.getInt(label, -1); assert value >= 0 : "Couldn't find " + label; return value; } private ConfigurationUtil(); static void publish(Configuration configuration, String label, T value); static int getInt(Configuration configuration, String label); static long getLong(Configuration configuration, String label); static Class<? extends InputFormat> getStrategy(Configuration conf, S3MapReduceCpOptions options); }### Answer: @Test(expected = AssertionError.class) public void getUnknownIntProperty() { ConfigurationUtil.getInt(config, "a.b.c"); } @Test public void getIntProperty() { config.set("a.b.c", "1024"); assertThat(ConfigurationUtil.getInt(config, "a.b.c"), is(1024)); }
### Question: ConfigurationUtil { public static long getLong(Configuration configuration, String label) { long value = configuration.getLong(label, -1); assert value >= 0 : "Couldn't find " + label; return value; } private ConfigurationUtil(); static void publish(Configuration configuration, String label, T value); static int getInt(Configuration configuration, String label); static long getLong(Configuration configuration, String label); static Class<? extends InputFormat> getStrategy(Configuration conf, S3MapReduceCpOptions options); }### Answer: @Test(expected = AssertionError.class) public void getUnknownLongProperty() { ConfigurationUtil.getLong(config, "a.b.c"); } @Test public void getLongProperty() { config.set("a.b.c", "1234567890"); assertThat(ConfigurationUtil.getLong(config, "a.b.c"), is(1234567890L)); }
### Question: ConfigurationUtil { public static Class<? extends InputFormat> getStrategy(Configuration conf, S3MapReduceCpOptions options) { String confLabel = "com.hotels.bdp.circustrain.s3mapreducecp." + options.getCopyStrategy().toLowerCase(Locale.getDefault()) + ".strategy.impl"; return conf.getClass(confLabel, UniformSizeInputFormat.class, InputFormat.class); } private ConfigurationUtil(); static void publish(Configuration configuration, String label, T value); static int getInt(Configuration configuration, String label); static long getLong(Configuration configuration, String label); static Class<? extends InputFormat> getStrategy(Configuration conf, S3MapReduceCpOptions options); }### Answer: @Test public void getDefaultStrategy() { S3MapReduceCpOptions options = new S3MapReduceCpOptions(); assertThat(ConfigurationUtil.getStrategy(config, options), is(CoreMatchers.<Class<?>> equalTo(UniformSizeInputFormat.class))); } @Test public void getCustomStrategy() { class CustomInputFormat extends InputFormat<Text, CopyListingFileStatus> { @Override public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException { return null; } @Override public RecordReader<Text, CopyListingFileStatus> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { return null; } } config.set("com.hotels.bdp.circustrain.s3mapreducecp.my-strategy.strategy.impl", CustomInputFormat.class.getName()); S3MapReduceCpOptions options = S3MapReduceCpOptions.builder(null, null).copyStrategy("my-strategy").build(); assertThat(ConfigurationUtil.getStrategy(config, options), is(CoreMatchers.<Class<?>> equalTo(CustomInputFormat.class))); }