method2testcases
stringlengths
118
6.63k
### Question: RequestAction extends Request { public static RequestActionSyntax actions() { return new Builder(); } private RequestAction(Builder builder); static RequestActionSyntax actions(); @Override Sc2Api.Request toSc2Api(); @Override ResponseType responseType(); List<Action> getActions(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenActionListIsEmpty() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ((RequestAction.Builder) actions()).build()) .withMessage("action list is required"); }
### Question: RequestSaveMap extends Request { public static Builder saveMap() { return new Builder(); } private RequestSaveMap(Builder builder); static Builder saveMap(); @Override Sc2Api.Request toSc2Api(); @Override ResponseType responseType(); LocalMap getMap(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenMapIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> saveMap().build()) .withMessage("map is required"); }
### Question: RequestDebug extends Request { public static RequestDebugSyntax debug() { return new Builder(); } private RequestDebug(Builder builder); static RequestDebugSyntax debug(); @Override Sc2Api.Request toSc2Api(); @Override ResponseType responseType(); List<DebugCommand> getCommands(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenMapIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ((RequestDebug.Builder) debug()).build()) .withMessage("command list is required"); }
### Question: RequestCreateGame extends Request { public static RequestCreateGameSyntax createGame() { return new Builder(); } private RequestCreateGame(Builder builder); static RequestCreateGameSyntax createGame(); @Override Sc2Api.Request toSc2Api(); @Override ResponseType responseType(); boolean isDisableFog(); boolean isRealTime(); Optional<Integer> getRandomSeed(); List<PlayerSetup> getPlayerSetups(); Optional<BattlenetMap> getBattlenetMap(); Optional<LocalMap> getLocalMap(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenMapDataIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(createGame()).build()) .withMessage("one of map data is required"); } @Test void throwsExceptionWhenPlayerSetupIsEmpty() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> createGame().onBattlenetMap(BattlenetMap.of(BATTLENET_MAP_NAME)).build()) .withMessage("player setup is required"); }
### 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: RequestStartReplay extends Request { @Override public Sc2Api.Request toSc2Api() { Sc2Api.RequestStartReplay.Builder aSc2ApiRequestStartReplay = Sc2Api.RequestStartReplay.newBuilder() .setOptions(interfaceOptions.toSc2Api()) .setObservedPlayerId(observedPlayerId) .setDisableFog(disableFog) .setRealtime(realtime); getReplayPath().map(Path::toString).ifPresent(aSc2ApiRequestStartReplay::setReplayPath); getReplayDataInBytes().map(ByteString::copyFrom).ifPresent(aSc2ApiRequestStartReplay::setReplayData); getMapDataInBytes().map(ByteString::copyFrom).ifPresent(aSc2ApiRequestStartReplay::setMapData); return Sc2Api.Request.newBuilder() .setStartReplay(aSc2ApiRequestStartReplay.build()) .build(); } 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 serializesDefaultDisableFogValueIfNotSet() { Sc2Api.RequestStartReplay aSc2ApiRequestStartReplay = aRequestStartReplay().build().toSc2Api().getStartReplay(); assertThat(aSc2ApiRequestStartReplay.hasDisableFog()).as("disable fog value is set").isTrue(); assertThat(aSc2ApiRequestStartReplay.getDisableFog()).as("default disable fog value is set").isFalse(); } @Test void serializesDefaultRealtimeValueIfNotSet() { Sc2Api.RequestStartReplay aSc2ApiRequestStartReplay = aRequestStartReplay().build().toSc2Api().getStartReplay(); assertThat(aSc2ApiRequestStartReplay.hasRealtime()).as("realtime value is set").isTrue(); assertThat(aSc2ApiRequestStartReplay.getRealtime()).as("default realtime value is set").isFalse(); }
### 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: ResponseGameInfo extends Response { public static ResponseGameInfo from(Sc2Api.Response sc2ApiResponse) { if (!hasGameInfoResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have game info response"); } return new ResponseGameInfo(sc2ApiResponse.getGameInfo(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseGameInfo(Sc2Api.ResponseGameInfo sc2ApiResponseGameInfo, Sc2Api.Status status, int id); static ResponseGameInfo from(Sc2Api.Response sc2ApiResponse); String getMapName(); Set<String> getModNames(); Optional<LocalMap> getLocalMap(); Set<PlayerInfo> getPlayersInfo(); Optional<StartRaw> getStartRaw(); InterfaceOptions getInterfaceOptions(); PointI convertWorldToMinimap(Point2d world); PointI convertWorldToCamera(Point2d cameraWorld, Point2d world); Point2d findRandomLocation(); Point2d findRandomLocation(Point2d min, Point2d max); PointI findCenterOfMap(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveGameInfo() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseGameInfo.from(nothing())) .withMessage("provided argument doesn't have game info response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseGameInfo.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have game info response"); } @Test void throwsExceptionWhenMapNameIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseGameInfo.from( sc2ApiGameInfoWithout(Sc2Api.ResponseGameInfo.Builder::clearMapName))) .withMessage("map name is required"); } @Test void throwsExceptionWhenInterfaceOptionsIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseGameInfo.from( sc2ApiGameInfoWithout(Sc2Api.ResponseGameInfo.Builder::clearOptions))) .withMessage("interface options is required"); } @Test void throwsExceptionWhenPlayersInfoIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseGameInfo.from( sc2ApiGameInfoWithout(Sc2Api.ResponseGameInfo.Builder::clearPlayerInfo))) .withMessage("players info is required"); } @Test void convertsSc2ApiResponseGameInfoToResponseGameInfo() { assertThatAllFieldsAreProperlyConverted(ResponseGameInfo.from(sc2ApiResponseWithGameInfo())); }
### 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: ResponseRestartGame extends Response { public static ResponseRestartGame from(Sc2Api.Response sc2ApiResponse) { if (!hasRestartGameResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have restart game response"); } return new ResponseRestartGame( sc2ApiResponse.getRestartGame(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseRestartGame( Sc2Api.ResponseRestartGame sc2ApiResponseRestartGame, Sc2Api.Status sc2ApiStatus, int id); static ResponseRestartGame from(Sc2Api.Response sc2ApiResponse); Optional<Error> getError(); Optional<String> getErrorDetails(); Optional<Boolean> getNeedHardReset(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveRestartGame() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseRestartGame.from(nothing())) .withMessage("provided argument doesn't have restart game response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseRestartGame.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have restart game response"); } @Test void convertsSc2ApiResponseRestartGameToResponseRestartGame() { ResponseRestartGame responseRestartGame = ResponseRestartGame.from(sc2ApiResponseWithRestartGame()); assertThatResponseDoesNotHaveError(responseRestartGame); assertThatResponseIsInValidState(responseRestartGame); } @Test void throwsExceptionWhenResponseRestartGameErrorIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseRestartGame.Error.from(nothing())) .withMessage("sc2api response restart game error is required"); } @Test void convertsSc2ApiResponseRestartGameWithErrorToResponseRestartGame() { ResponseRestartGame responseRestartGame = ResponseRestartGame.from(sc2ApiResponseWithRestartGameWithError()); assertThatResponseIsInValidState(responseRestartGame); assertThatErrorsAreMapped(responseRestartGame); }
### Question: ResponsePing extends Response { public static ResponsePing from(Sc2Api.Response sc2ApiResponse) { if (!hasPingResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have ping response"); } return new ResponsePing(sc2ApiResponse.getPing(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponsePing(Sc2Api.ResponsePing sc2ApiResponsePing, Sc2Api.Status sc2ApiStatus, int id); static ResponsePing from(Sc2Api.Response sc2ApiResponse); String getGameVersion(); String getDataVersion(); Integer getDataBuild(); Integer getBaseBuild(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHavePing() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponsePing.from(nothing())) .withMessage("provided argument doesn't have ping response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponsePing.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have ping response"); } @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveAllFieldsSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponsePing.from( sc2ApiResponsePingWithout(Sc2Api.ResponsePing.Builder::clearGameVersion))) .withMessage("game version is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponsePing.from( sc2ApiResponsePingWithout(Sc2Api.ResponsePing.Builder::clearDataVersion))) .withMessage("data version is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponsePing.from( sc2ApiResponsePingWithout(Sc2Api.ResponsePing.Builder::clearBaseBuild))) .withMessage("base build is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponsePing.from( sc2ApiResponsePingWithout(Sc2Api.ResponsePing.Builder::clearDataBuild))) .withMessage("data build is required"); } @Test void convertsSc2ApiResponsePingToResponsePing() { ResponsePing responsePing = ResponsePing.from(sc2ApiResponseWithPing()); assertThatAllFieldsAreProperlyConverted(responsePing); }
### 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: ResponseReplayInfo extends Response { public static ResponseReplayInfo from(Sc2Api.Response sc2ApiResponse) { if (!hasReplayInfoResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have replay info response"); } return new ResponseReplayInfo( sc2ApiResponse.getReplayInfo(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseReplayInfo( Sc2Api.ResponseReplayInfo sc2ApiResponseReplayInfo, Sc2Api.Status sc2ApiStatus, int id); static ResponseReplayInfo from(Sc2Api.Response sc2ApiResponse); Optional<ResponseReplayInfo.Error> getError(); Optional<String> getErrorDetails(); Optional<ReplayInfo> getReplayInfo(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveReplayInfo() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseReplayInfo.from(nothing())) .withMessage("provided argument doesn't have replay info response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseReplayInfo.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have replay info response"); } @Test void convertsSc2ApiResponseReplayInfoToResponseReplayInfo() { ResponseReplayInfo responseReplayInfo = ResponseReplayInfo.from(sc2ApiResponseWithReplayInfo()); assertThatResponseDoesNotHaveError(responseReplayInfo); assertThatResponseIsInValidState(responseReplayInfo); } @Test void throwsExceptionWhenMapInfoIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseReplayInfo.from(sc2ApiResponseReplayInfoWithoutMap())) .withMessage("map info (local or battlenet) is required"); } @Test void throwsExceptionWhenResponseReplayInfoErrorIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseReplayInfo.Error.from(nothing())) .withMessage("sc2api response replay info error is required"); } @Test void convertsSc2ApiResponseReplayInfoWithErrorToResponseReplayInfo() { ResponseReplayInfo responseReplayInfo = ResponseReplayInfo.from(sc2ApiResponseWithReplayInfoWithError()); assertThatResponseIsInValidState(responseReplayInfo); assertThatErrorsAreMapped(responseReplayInfo); }
### 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: ResponseObservation extends Response { public static ResponseObservation from(Sc2Api.Response sc2ApiResponse) { if (!hasObservationResponse(sc2ApiResponse)) { throw new IllegalArgumentException("provided argument doesn't have observation response"); } return new ResponseObservation( sc2ApiResponse.getObservation(), sc2ApiResponse.getStatus(), sc2ApiResponse.getId()); } private ResponseObservation(Sc2Api.ResponseObservation sc2ApiResponseObservation, Sc2Api.Status status, int id); static ResponseObservation from(Sc2Api.Response sc2ApiResponse); List<Action> getActions(); List<ActionError> getActionErrors(); Observation getObservation(); List<PlayerResult> getPlayerResults(); List<ChatReceived> getChat(); @Override boolean equals(Object o); @Override boolean canEqual(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiResponseDoesNotHaveObservation() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseObservation.from(nothing())) .withMessage("provided argument doesn't have observation response"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseObservation.from(aSc2ApiResponse().build())) .withMessage("provided argument doesn't have observation response"); } @Test void convertsSc2ApiResponseObservationToResponseObservation() { ResponseObservation responseObservation = ResponseObservation.from(sc2ApiResponseWithObservation()); assertThatResponseIsInValidState(responseObservation); assertThatAllFieldsAreConverted(responseObservation); } @Test void throwsExceptionWhenObservationDoesNotExist() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> ResponseObservation.from(emptySc2ApiResponseObservation())) .withMessage("observation is required"); } @Test void fulfillsEqualsContract() throws UnsupportedEncodingException { EqualsVerifier.forClass(ResponseObservation.class) .withIgnoredFields("nanoTime") .withNonnullFields("type", "status", "actions", "actionErrors", "observation", "playerResults", "chat") .withRedefinedSuperclass() .withPrefabValues(UnitInfo.class, UnitInfo.from(sc2ApiUnitInfoAddOn()), UnitInfo.from(sc2ApiUnitInfo())) .withPrefabValues( ByteString.class, ByteString.copyFrom("test", "UTF-8"), ByteString.copyFrom("test2", "UTF-8")) .verify(); }
### 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: PassengerUnit implements Serializable { public static PassengerUnit from(Raw.PassengerUnit sc2ApiPassengerUnit) { require("sc2api passenger unit", sc2ApiPassengerUnit); return new PassengerUnit(sc2ApiPassengerUnit); } private PassengerUnit(Raw.PassengerUnit sc2ApiPassengerUnit); static PassengerUnit from(Raw.PassengerUnit sc2ApiPassengerUnit); Tag getTag(); float getHealth(); float getHealthMax(); Optional<Float> getShield(); Optional<Float> getShieldMax(); Optional<Float> getEnergy(); Optional<Float> getEnergyMax(); UnitType getType(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiPassengerUnitIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> PassengerUnit.from(nothing())) .withMessage("sc2api passenger unit is required"); } @Test void convertsAllFieldsFromSc2ApiPassengerUnit() { assertThatAllFieldsAreConverted(PassengerUnit.from(sc2ApiPassengerUnit())); } @Test void throwsExceptionWhenTagIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> PassengerUnit.from( without(() -> sc2ApiPassengerUnit().toBuilder(), Raw.PassengerUnit.Builder::clearTag).build())) .withMessage("tag is required"); } @Test void throwsExceptionWhenHealthIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> PassengerUnit.from( without(() -> sc2ApiPassengerUnit().toBuilder(), Raw.PassengerUnit.Builder::clearHealth) .build())) .withMessage("health is required"); } @Test void throwsExceptionWhenHealthMaxIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> PassengerUnit.from( without(() -> sc2ApiPassengerUnit().toBuilder(), Raw.PassengerUnit.Builder::clearHealthMax) .build())) .withMessage("health max is required"); } @Test void throwsExceptionWhenTypeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> PassengerUnit.from( without(() -> sc2ApiPassengerUnit().toBuilder(), Raw.PassengerUnit.Builder::clearUnitType) .build())) .withMessage("unit type is required"); }
### Question: Unit extends UnitSnapshot { public static Unit from(Raw.Unit sc2ApiUnit) { require("sc2api unit", sc2ApiUnit); return new Unit(sc2ApiUnit); } private Unit(Raw.Unit sc2ApiUnit); private Unit(Unit original, UnaryOperator<Ability> generalize); static Unit from(Raw.Unit sc2ApiUnit); Tag getTag(); UnitType getType(); int getOwner(); float getFacing(); float getRadius(); float getBuildProgress(); @Override Unit generalizeAbility(UnaryOperator<Ability> generalize); @Override boolean canEqual(Object other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final int CLOAKED; }### Answer: @Test void throwsExceptionWhenSc2ApiUnitIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Unit.from(nothing())) .withMessage("sc2api unit is required"); } @Test void convertsAllFieldsFromSc2ApiUnit() { assertThatAllFieldsAreConverted(Unit.from(sc2ApiUnit())); } @Test void throwsExceptionWhenDisplayTypeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Unit.from( without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearDisplayType).build())) .withMessage("display type is required"); } @Test void throwsExceptionWhenAllianceIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Unit.from( without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearAlliance).build())) .withMessage("alliance is required"); } @Test void throwsExceptionWhenTagIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Unit.from( without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearTag).build())) .withMessage("tag is required"); } @Test void throwsExceptionWhenTypeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Unit.from( without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearUnitType).build())) .withMessage("unit type is required"); } @Test void throwsExceptionWhenPositionIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Unit.from( without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearPos).build())) .withMessage("position is required"); } @Test void hasDefaultValueForOnScreenFieldIfNotProvided() { Unit unit = Unit.from(without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearIsOnScreen).build()); assertThat(unit.isOnScreen()).as("unit: default on screen").isFalse(); } @Test void hasDefaultValueForBlipFieldIfNotProvided() { Unit unit = Unit.from(without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearIsBlip).build()); assertThat(unit.isBlip()).as("unit: default blip").isFalse(); } @Test void hasEmptyListOfOrdersWhenNotProvided() { assertThat(Unit.from( without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearOrders).build() ).getOrders()).as("unit: empty orders list").isEmpty(); } @Test void hasEmptyListOfPassengersWhenNotProvided() { assertThat(Unit.from( without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearPassengers).build() ).getPassengers()).as("unit: empty passengers list").isEmpty(); } @Test void hasEmptySetOfBuffsWhenNotProvided() { assertThat(Unit.from( without(() -> sc2ApiUnit().toBuilder(), Raw.Unit.Builder::clearBuffIds).build() ).getBuffs()).as("unit: empty buff set").isEmpty(); }
### Question: DebugText implements Sc2ApiSerializable<Debug.DebugText> { public static DebugTextSyntax text() { return new Builder(); } private DebugText(Builder builder); static DebugTextSyntax text(); @Override Debug.DebugText toSc2Api(); Color getColor(); Optional<Integer> getSize(); String getText(); Optional<Point> getPoint3d(); Optional<Point> getPoint2d(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenColorIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(text().of(DEBUG_TEXT)).withColor(nothing()).build()) .withMessage("color is required"); } @Test void throwsExceptionWhenTextIsNotSet() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> fullAccessTo(text()).withColor(SAMPLE_COLOR).build()) .withMessage("text is required"); } @Test void throwsExceptionWhenPointIsNotInValidRange() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> text().of(DEBUG_TEXT).on(Point.of(-1, 1)).build()) .withMessage("virtualized point 2d [x] has value -1.0 and is lower than 0.0"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> text().of(DEBUG_TEXT).on(Point.of(1.1f, 1)).build()) .withMessage("virtualized point 2d [x] has value 1.1 and is greater than 1.0"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> text().of(DEBUG_TEXT).on(Point.of(1.0f, -1)).build()) .withMessage("virtualized point 2d [y] has value -1.0 and is lower than 0.0"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> text().of(DEBUG_TEXT).on(Point.of(1.0f, 1.1f)).build()) .withMessage("virtualized point 2d [y] has value 1.1 and is greater than 1.0"); }
### 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: CategoryScoreDetails implements Serializable { public static CategoryScoreDetails from(ScoreOuterClass.CategoryScoreDetails sc2ApiCategoryScoreDetails) { require("sc2api category score details", sc2ApiCategoryScoreDetails); return new CategoryScoreDetails(sc2ApiCategoryScoreDetails); } private CategoryScoreDetails(ScoreOuterClass.CategoryScoreDetails sc2APiCategoryScoreDetails); static CategoryScoreDetails from(ScoreOuterClass.CategoryScoreDetails sc2ApiCategoryScoreDetails); float getNone(); float getArmy(); float getEconomy(); float getTechnology(); float getUpgrade(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiCategoryScoreDetailsIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> CategoryScoreDetails.from(nothing())) .withMessage("sc2api category score details is required"); } @Test void convertsAllFieldsFromSc2ApiCategoryScoreDetails() { assertThatAllFieldsAreConverted(CategoryScoreDetails.from(sc2ApiCategoryScoreDetails())); } @Test void throwsExceptionWhenNoneIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> CategoryScoreDetails.from(without( () -> sc2ApiCategoryScoreDetails().toBuilder(), ScoreOuterClass.CategoryScoreDetails.Builder::clearNone).build())) .withMessage("none is required"); } @Test void throwsExceptionWhenArmyIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> CategoryScoreDetails.from(without( () -> sc2ApiCategoryScoreDetails().toBuilder(), ScoreOuterClass.CategoryScoreDetails.Builder::clearArmy).build())) .withMessage("army is required"); } @Test void throwsExceptionWhenEconomyIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> CategoryScoreDetails.from(without( () -> sc2ApiCategoryScoreDetails().toBuilder(), ScoreOuterClass.CategoryScoreDetails.Builder::clearEconomy).build())) .withMessage("economy is required"); } @Test void throwsExceptionWhenTechnologyIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> CategoryScoreDetails.from(without( () -> sc2ApiCategoryScoreDetails().toBuilder(), ScoreOuterClass.CategoryScoreDetails.Builder::clearTechnology).build())) .withMessage("technology is required"); } @Test void throwsExceptionWhenUpgradeIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> CategoryScoreDetails.from(without( () -> sc2ApiCategoryScoreDetails().toBuilder(), ScoreOuterClass.CategoryScoreDetails.Builder::clearUpgrade).build())) .withMessage("upgrade is required"); }
### Question: DebugCommand implements Sc2ApiSerializable<Debug.DebugCommand> { public static Builder command() { return new Builder(); } private DebugCommand(DebugDraw draw); private DebugCommand(DebugGameState gameState); private DebugCommand(DebugCreateUnit createUnit); private DebugCommand(DebugKillUnit killUnit); private DebugCommand(DebugTestProcess testProcess); private DebugCommand(DebugSetScore setScore); private DebugCommand(DebugEndGame endGame); private DebugCommand(DebugSetUnitValue setUnitValue); static Builder command(); @Override Debug.DebugCommand toSc2Api(); Optional<DebugDraw> getDraw(); Optional<DebugGameState> getGameState(); Optional<DebugCreateUnit> getCreateUnit(); Optional<DebugKillUnit> getKillUnit(); Optional<DebugTestProcess> getTestProcess(); Optional<DebugSetScore> getSetScore(); Optional<DebugEndGame> getEndGame(); Optional<DebugSetUnitValue> getSetUnitValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenThereIsNoActionCase() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> command().of((DebugDraw) nothing())) .withMessage("draw is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> command().of((DebugGameState) nothing())) .withMessage("game state is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> command().of((DebugCreateUnit) nothing())) .withMessage("create unit is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> command().of((DebugKillUnit) nothing())) .withMessage("kill unit is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> command().of((DebugTestProcess) nothing())) .withMessage("test process is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> command().of((DebugSetScore) nothing())) .withMessage("set score is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> command().of((DebugEndGame) nothing())) .withMessage("end game is required"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> command().of((DebugSetUnitValue) nothing())) .withMessage("set unit value 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: Observation implements Serializable { public static Observation from(Sc2Api.Observation sc2ApiObservation) { require("sc2api observation", sc2ApiObservation); return new Observation(sc2ApiObservation); } private Observation(Sc2Api.Observation sc2ApiObservation); static Observation from(Sc2Api.Observation sc2ApiObservation); int getGameLoop(); PlayerCommon getPlayerCommon(); Set<Alert> getAlerts(); Set<AvailableAbility> getAvailableAbilities(); Optional<Score> getScore(); Optional<ObservationRaw> getRaw(); Optional<ObservationFeatureLayer> getFeatureLayer(); Optional<ObservationRender> getRender(); Optional<ObservationUi> getUi(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test void throwsExceptionWhenSc2ApiObservationIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Observation.from(nothing())) .withMessage("sc2api observation is required"); } @Test void convertsAllFieldsFromSc2ApiObservation() { assertThatAllFieldsAreConverted(Observation.from(sc2ApiObservation())); } @Test void throwsExceptionWhenGameLoopIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Observation.from(without( () -> sc2ApiObservation().toBuilder(), Sc2Api.Observation.Builder::clearGameLoop).build())) .withMessage("game loop is required"); } @Test void throwsExceptionWhenPlayerCommonIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Observation.from(without( () -> sc2ApiObservation().toBuilder(), Sc2Api.Observation.Builder::clearPlayerCommon).build())) .withMessage("player common is required"); } @Test void throwsExceptionWhenOneOfInterfacesNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Observation.from(without( () -> sc2ApiObservation().toBuilder(), Sc2Api.Observation.Builder::clearRawData, Sc2Api.Observation.Builder::clearFeatureLayerData, Sc2Api.Observation.Builder::clearRenderData).build())) .withMessage("one of interfaces is required"); } @Test void fulfillsEqualsContract() throws UnsupportedEncodingException { EqualsVerifier .forClass(Observation.class) .withNonnullFields("playerCommon", "alerts", "availableAbilities") .withPrefabValues(UnitInfo.class, UnitInfo.from(sc2ApiUnitInfoAddOn()), UnitInfo.from(sc2ApiUnitInfo())) .withPrefabValues( ByteString.class, ByteString.copyFrom("test", "UTF-8"), ByteString.copyFrom("test2", "UTF-8")) .verify(); }
### 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: TextAndPosition { public List<Integer> match(String toMatch) { toMatch = toMatch.toLowerCase(); ArrayList<Integer> result= new ArrayList<>(); if (toMatch.length() == 0) return result; int found = 0; while ((found = content.indexOf(toMatch, found)) != -1 ) { int actualPos = convertIndexToPos(found); result.add(actualPos); found++; } return result; } private TextAndPosition(int startPos, String content, List<Integer> limits); List<Integer> match(String toMatch); static Builder builder(int startPos); }### Answer: @Test public void testMatchFirst() { List<Integer> res = textAndPosition.match("bc"); assertEquals(Arrays.asList(10), res); } @Test public void testMatchSecondA() { List<Integer> res = textAndPosition.match("f"); assertEquals(Arrays.asList(11), res); } @Test public void testMatchSecondB() { List<Integer> res = textAndPosition.match("fg"); assertEquals(Arrays.asList(11), res); } @Test public void testMatchSecondC() { List<Integer> res = textAndPosition.match("g"); assertEquals(Arrays.asList(11), res); } @Test public void testMatchLastA() { List<Integer> res = textAndPosition.match("hi"); assertEquals(Arrays.asList(12), res); } @Test public void testMatchLastB() { List<Integer> res = textAndPosition.match("h"); assertEquals(Arrays.asList(12), res); } @Test public void testMatchLastC() { List<Integer> res = textAndPosition.match("i"); assertEquals(Arrays.asList(12), res); } @Test public void testMatchOverlap() { List<Integer> res = textAndPosition.match("ghi"); assertEquals(Arrays.asList(11), res); } @Test public void testMatchOverlapA() { List<Integer> res = textAndPosition.match("efghi"); assertEquals(Arrays.asList(10), res); } @Test public void testMatchOverlapAll() { List<Integer> res = textAndPosition.match("abcdefghi"); assertEquals(Arrays.asList(10), res); }
### 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: DynamicViewDAO { public ViewMapVO getViewMapForView(String register, String dataType, long version) throws SQLException { String sql = "SELECT idSKRSViewMapping,tableName,createdDate FROM SKRSViewMapping WHERE register=? AND " + "datatype=? AND version=?"; ArrayListHandler handler = new ArrayListHandler(); QueryRunner qr = new QueryRunner(); Connection conn = null; try { conn = connectionProvider.get(); List<Object[]> viewMaps = qr.query(conn, sql, handler, register, dataType, version); if (viewMaps.size() < 1) { throw new DynamicViewException("View not found for " + register + "/" + dataType + "/" + version); } else if (viewMaps.size() > 1) { throw new DynamicViewException("Multiple views found for " + register + "/" + dataType + "/" + version); } Long id = (Long) viewMaps.get(0)[0]; String tableName = (String) viewMaps.get(0)[1]; Timestamp createTime = (Timestamp) viewMaps.get(0)[2]; List<ColumnMapVO> columnMaps = getColumnMapsForView(conn, id); ViewMapVO viewMap = new ViewMapVO(); viewMap.setCreatedDate(createTime); viewMap.setDatatype(dataType); viewMap.setRegister(register); viewMap.setTableName(tableName); viewMap.setVersion(version); for (ColumnMapVO columnMap : columnMaps) { viewMap.addColumn(columnMap); } return viewMap; } finally { DbUtils.close(conn); } } @Inject DynamicViewDAO(Provider<Connection> connectionProvider); List<String> listAllViews(); ViewMapVO getViewMapForView(String register, String dataType, long version); }### Answer: @Test public void testGetViewMap() throws SQLException { ViewMapVO viewMapForView = dao.getViewMapForView(testRegister, testDatatype, 1); assertNotNull(viewMapForView); assertEquals(testRegister, viewMapForView.getRegister()); assertEquals(testDatatype, viewMapForView.getDatatype()); assertEquals(1, viewMapForView.getVersion()); assertEquals(testTableName, viewMapForView.getTableName()); assertNotNull(viewMapForView.getCreatedDate()); List<ColumnMapVO> columnMaps = viewMapForView.getColumnMaps(); assertEquals(1, columnMaps.size()); ColumnMapVO column1 = columnMaps.iterator().next(); assertEquals(-1, column1.getDataType()); assertEquals(1, column1.getFeedPosition()); assertEquals((Integer)100, column1.getMaxLength()); assertEquals("test_column", column1.getTableColumnName()); assertEquals("test_feed_column", column1.getFeedColumnName()); removeMapping(id); }
### 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: AvroSerDePartitionTransformation extends AbstractAvroSerDeTransformation implements PartitionTransformation { @Override public Partition transform(Partition partition) { if (avroTransformationSpecified()) { partition = apply(partition, avroDestination(getAvroSchemaDestinationFolder(), getEventId(), getTableLocation())); } return partition; } @Autowired AvroSerDePartitionTransformation(TransformOptions transformOptions, SchemaCopier copier); @Override Partition transform(Partition partition); }### Answer: @Test public void transformOverride() throws Exception { Map<String, Object> avroOverrideOptions = new HashMap<>(); avroOverrideOptions.put(AvroSerDeConfig.BASE_URL, "schemaOverride"); Map<String, Object> transformOptions = new HashMap<>(); transformOptions.put(AvroSerDeConfig.AVRO_SERDE_OPTIONS, avroOverrideOptions); when(tableReplicationEvent.getTransformOptions()).thenReturn(transformOptions); EventReplicaTable eventReplicaTable = new EventReplicaTable("db", "table", "location"); when(tableReplicationEvent.getReplicaTable()).thenReturn(eventReplicaTable); transformation.tableReplicationStart(tableReplicationEvent, "eventId"); HiveObjectUtils.updateSerDeUrl(partition, AVRO_SCHEMA_URL_PARAMETER, "avroSourceUrl"); when(schemaCopier.copy("avroSourceUrl", "schemaOverride/eventId/", tableReplicationEvent, "eventId")) .thenReturn(destinationPath); Partition result = transformation.transform(partition); assertThat(result.getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is(destinationPathString)); } @Test public void transformNoAvro() { transformation.transform(partition); verifyZeroInteractions(schemaCopier); assertThat(partition, is(newPartition())); } @Test public void missingEventId() { transformation.transform(partition); verifyZeroInteractions(schemaCopier); assertThat(partition, is(newPartition())); } @Test public void missingAvroDestinationFolder() { EventReplicaTable eventReplicaTable = new EventReplicaTable("db", "table", "location"); when(tableReplicationEvent.getReplicaTable()).thenReturn(eventReplicaTable); transformation.tableReplicationStart(tableReplicationEvent, "eventId"); transformation.transform(partition); verifyZeroInteractions(schemaCopier); assertThat(partition, is(newPartition())); } @Test public void transformNoSourceUrl() throws Exception { EventReplicaTable eventReplicaTable = new EventReplicaTable("db", "table", "location"); when(tableReplicationEvent.getReplicaTable()).thenReturn(eventReplicaTable); transformation.tableReplicationStart(tableReplicationEvent, "eventId"); Partition result = transformation.transform(partition); verifyZeroInteractions(schemaCopier); assertThat(result, is(newPartition())); } @Test public void transform() throws Exception { EventReplicaTable eventReplicaTable = new EventReplicaTable("db", "table", "location"); when(tableReplicationEvent.getReplicaTable()).thenReturn(eventReplicaTable); transformation.tableReplicationStart(tableReplicationEvent, "eventId"); HiveObjectUtils.updateSerDeUrl(partition, AVRO_SCHEMA_URL_PARAMETER, "avroSourceUrl"); when(schemaCopier.copy("avroSourceUrl", "schema/eventId/", tableReplicationEvent, "eventId")) .thenReturn(destinationPath); Partition result = transformation.transform(partition); assertThat(result.getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is(destinationPathString)); }
### Question: AvroSerDeTransformation { Table apply(Table table, String avroSchemaDestination, String eventId) throws Exception { if (avroSchemaDestination == null) { return table; } avroSchemaDestination = addTrailingSlash(avroSchemaDestination); avroSchemaDestination += eventId; String avroSchemaSource = table.getParameters().get(AVRO_SCHEMA_URL_PARAMETER); copy(avroSchemaSource, avroSchemaDestination); table.putToParameters(AVRO_SCHEMA_URL_PARAMETER, avroSchemaDestination + "/" + getAvroSchemaFileName(avroSchemaSource)); LOG.info("Avro SerDe transformation has been applied to table '{}'", table.getTableName()); return table; } @Autowired AvroSerDeTransformation(HiveConf sourceHiveConf, HiveConf replicaHiveConf); }### Answer: @Test public void applyTable() throws Exception { File srcSchemaFile = temporaryFolder.newFile(); File dstFolder = temporaryFolder.newFolder(); table.putToParameters("avro.schema.url", srcSchemaFile.toString()); table = avroSerDeTransformation.apply(table, dstFolder.toString(), "1"); String replicaBasePath = table.getParameters().get("avro.schema.url"); replicaBasePath = replicaBasePath.substring(0, replicaBasePath.lastIndexOf("/")); assertThat(replicaBasePath, startsWith(dstFolder.toString())); assertTrue(new File(replicaBasePath).exists()); } @Test public void applyPartition() throws Exception { File srcSchemaFile = temporaryFolder.newFile(); File dstFolder = temporaryFolder.newFolder(); partition.putToParameters("avro.schema.url", srcSchemaFile.toString()); partition = avroSerDeTransformation.apply(partition, dstFolder.toString(), "1"); String replicaBasePath = partition.getParameters().get("avro.schema.url"); replicaBasePath = replicaBasePath.substring(0, replicaBasePath.lastIndexOf("/")); assertThat(replicaBasePath, startsWith(dstFolder.toString())); assertTrue(new File(replicaBasePath).exists()); } @Test public void nullAvroDestinationFailsInTableApply() throws Exception { table.putToParameters("avro.schema.url", "/test/"); Table result = avroSerDeTransformation.apply(table, null, "1"); assertThat(result, is(table)); } @Test public void nullAvroDestinationFailsInPartitionApply() throws Exception { partition.putToParameters("avro.schema.url", "/test/"); Partition result = avroSerDeTransformation.apply(partition, null, "1"); assertThat(result, is(partition)); }
### 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: ViewTransformation implements TableTransformation { @Override public Table transform(Table table) { if (!MetaStoreUtils.isView(table)) { return table; } LOG.info("Translating HQL of view {}.{}", table.getDbName(), table.getTableName()); String tableQualifiedName = Warehouse.getQualifiedName(table); String hql = hqlTranslator.translate(tableQualifiedName, table.getViewOriginalText()); String expandedHql = hqlTranslator.translate(tableQualifiedName, table.getViewExpandedText()); Table transformedView = new Table(table); transformedView.setViewOriginalText(hql); transformedView.setViewExpandedText(expandedHql); if (!replicaHiveConf.getBoolean(SKIP_TABLE_EXIST_CHECKS, false)) { LOG .info("Validating that tables used by the view {}.{} exist in the replica catalog", table.getDbName(), table.getTableName()); validateReferencedTables(transformedView); } return transformedView; } @Autowired ViewTransformation( HiveConf replicaHiveConf, HqlTranslator hqlTranslator, Supplier<CloseableMetaStoreClient> replicaMetaStoreClientSupplier); @Override Table transform(Table table); }### Answer: @Test public void skipTables() { when(table.getTableType()).thenReturn(TableType.EXTERNAL_TABLE.name()); Table transformedTable = transformation.transform(table); assertThat(transformedTable, is(table)); } @Test public void transform() { Table transformedTable = transformation.transform(table); assertThat(transformedTable, is(not(table))); verify(translator).translate(QUALIFIED_NAME, ORIGINAL_HQL); verify(translator).translate(QUALIFIED_NAME, EXPANDED_HQL); assertThat(transformedTable.getViewOriginalText(), is(ORIGINAL_TRANSLATED_HQL)); assertThat(transformedTable.getViewExpandedText(), is(EXPANDED_TRANSLATED_HQL)); } @Test(expected = CircusTrainException.class) public void underlyingTableIsMissing() throws Exception { hiveConf.setBoolean(ViewTransformation.SKIP_TABLE_EXIST_CHECKS, false); when(metaStoreClient.getTable("replica", "tt")).thenThrow(new NoSuchObjectException()); transformation.transform(table); } @Test public void underlyingTablesExist() { hiveConf.setBoolean(ViewTransformation.SKIP_TABLE_EXIST_CHECKS, false); when(table.getTableType()).thenReturn(TableType.VIRTUAL_VIEW.name()); Table transformedTable = transformation.transform(table); assertThat(transformedTable, is(not(table))); verify(translator).translate(QUALIFIED_NAME, ORIGINAL_HQL); verify(translator).translate(QUALIFIED_NAME, EXPANDED_HQL); assertThat(transformedTable.getViewOriginalText(), is(ORIGINAL_TRANSLATED_HQL)); assertThat(transformedTable.getViewExpandedText(), is(EXPANDED_TRANSLATED_HQL)); }
### 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: HqlTranslator { public String translate(String viewQualifiedName, String hql) { List<TableTranslation> translations = mappings.get(viewQualifiedName); if (translations == null) { return hql; } return translate(hql, translations); } @Autowired HqlTranslator(TableReplications tableReplications); String translate(String viewQualifiedName, String hql); }### Answer: @Test public void unescapedStatement() { Map<String, String> replicationMappings = ImmutableMap .<String, String> builder() .put("db1.table_a", "r_db.a_table") .build(); when(tableReplication.getTableMappings()).thenReturn(replicationMappings); HqlTranslator translator = new HqlTranslator(tableReplications); String translatedStatement = translator.translate(VIEW_NAME, UNESCAPED_SELECT_STATEMENT); String expectedTranslatedStatement = new StringBuilder() .append("SELECT a_table.col1, b.col2 \n") .append(" FROM r_db.a_table \n") .append(" JOIN db2.table_b AS B ON B.key = a_table.key \n") .append(" WHERE a_table.cond = 'VAL' \n") .append(" AND a_table.cmp < b.cmp \n") .toString(); assertThat(translatedStatement, is(expectedTranslatedStatement)); } @Test public void escapedStatment() { Map<String, String> replicationMappings = ImmutableMap .<String, String> builder() .put("db1.table_a", "r_db.a_table") .put("db2.table_b", "r_db.b_table") .build(); when(tableReplication.getTableMappings()).thenReturn(replicationMappings); HqlTranslator translator = new HqlTranslator(tableReplications); String translatedStatement = translator.translate(VIEW_NAME, ESCAPED_SELECT_STATEMENT); String expectedTranslatedStatement = new StringBuilder() .append("SELECT `A`.`col1`, `b_table`.`col2` \n") .append(" FROM `r_db`.`a_table` AS `A` \n") .append(" JOIN `r_db`.`b_table` ON `b_table`.`key` = `A`.`key` \n") .append(" WHERE `A`.`cond` = 'VAL' \n") .append(" AND `A`.`cmp` < `b_table`.`cmp` \n") .toString(); assertThat(translatedStatement, is(expectedTranslatedStatement)); }
### 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: GraphiteMetricSender implements MetricSender { @Override public void send(String name, long value) { send(singletonMap(name, value)); } GraphiteMetricSender(GraphiteSender graphite, Clock clock, String prefix); static GraphiteMetricSender newInstance(String host, String prefix); @Override void send(String name, long value); @Override void send(Map<String, Long> metrics); }### Answer: @Test public void typical() throws IOException { when(graphite.isConnected()).thenReturn(false); sender.send("name", 2L); verify(graphite).connect(); verify(graphite).send("prefix.name", "2", 1L); verify(graphite).flush(); verify(graphite).close(); } @Test public void alreadyConnected() throws IOException { when(graphite.isConnected()).thenReturn(true); sender.send("name", 2L); verify(graphite, never()).connect(); verify(graphite).send("prefix.name", "2", 1L); verify(graphite).flush(); verify(graphite).close(); } @Test public void exceptionOnConnect() throws IOException { when(graphite.isConnected()).thenReturn(false); doThrow(IOException.class).when(graphite).connect(); try { sender.send("name", 2L); } catch (Exception e) { fail("Unexpected exception"); } verify(graphite, never()).send("prefix.name", "2", 1L); verify(graphite, never()).flush(); verify(graphite).close(); } @Test public void exceptionOnSend() throws IOException { when(graphite.isConnected()).thenReturn(true); doThrow(IOException.class).when(graphite).send(anyString(), anyString(), anyLong()); try { sender.send("name", 2L); } catch (Exception e) { fail("Unexpected exception"); } verify(graphite, never()).flush(); verify(graphite).close(); } @Test public void exceptionOnFlush() throws IOException { when(graphite.isConnected()).thenReturn(true); doThrow(IOException.class).when(graphite).flush(); try { sender.send("name", 2L); } catch (Exception e) { fail("Unexpected exception"); } verify(graphite).close(); } @Test public void exceptionOnClose() throws IOException { when(graphite.isConnected()).thenReturn(true); doThrow(IOException.class).when(graphite).close(); try { sender.send("name", 2L); } catch (Exception e) { fail("Unexpected exception"); } verify(graphite).close(); }
### 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)); }