method2testcases
stringlengths
118
3.08k
### Question: WGS84Util { public static double getLongitudeDelta(double latitude, double distance) { return Math.toDegrees(distance / getLatitutesCircleRadius(latitude)) % 360; } static double shortestDistanceBetween(Point a, Point b); static double getLongitudeDelta(double latitude, double distance); static double getLatitudeDelta(double distance); static double normalizeLongitude(double longitude); static double normalizeLatitude(double latitude); static final String EPSG_4326; }### Answer: @Test public void shouldGetLongitudeDelta() throws FactoryException { assertThat(getLongitudeDelta(toRadians(0), 2 * PI * EARTH_MEAN_RADIUS), closeTo(0, ERROR_DELTA)); assertThat(getLongitudeDelta(toRadians(0), PI * EARTH_MEAN_RADIUS), closeTo(180, ERROR_DELTA)); }
### Question: WGS84Util { public static double getLatitudeDelta(double distance) { return Math.toDegrees(distance / EARTH_MEAN_RADIUS) % 180; } static double shortestDistanceBetween(Point a, Point b); static double getLongitudeDelta(double latitude, double distance); static double getLatitudeDelta(double distance); static double normalizeLongitude(double longitude); static double normalizeLatitude(double latitude); static final String EPSG_4326; }### Answer: @Test public void shouldGetLatitudeDelta() throws FactoryException { assertThat(getLatitudeDelta(0d), closeTo(0, ERROR_DELTA)); }
### Question: HelgolandConfiguration { protected String checkForApi(String url) { return url.endsWith(UrlSettings.BASE) ? url : url.endsWith("/api") ? url.concat("/") : url.endsWith("/") ? url.substring(0, url.lastIndexOf("/")).concat(UrlSettings.BASE) : url.concat(UrlSettings.BASE); } String getExternalUrl(); void setExternalUrl(String externalUrl); @Setting(EXTERNAL_URL_KEY) void setExternalHelgolandUri(URI externalHelgolandUri); String getRequestIntervalRestriction(); @Setting(REQUEST_INTERVAL_RESTRICTION_KEY) void setRequestIntervalRestriction(String requestIntervalRestriction); static final String DEFAULT_URL; static final String DEFAULT_REQUEST_INTERVAL_RESTRICTION; }### Answer: @Test public void when_UrlEndsBase() { String url = "http: String validated = config.checkForApi(url); assertEquals(EXPECTED_URL, validated); } @Test public void when_UrlEndsBaseMissingSlash() { String url = "http: String validated = config.checkForApi(url); assertEquals(EXPECTED_URL, validated); } @Test public void when_UrlSlash() { String url = "http: String validated = config.checkForApi(url); assertEquals(EXPECTED_URL, validated); } @Test public void when_UrlOnly() { String url = "http: String validated = config.checkForApi(url); assertEquals(EXPECTED_URL, validated); }
### Question: WGS84Util { static double getLatitutesCircleRadius(double latitude) { return EARTH_MEAN_RADIUS * Math.sin(Math.PI / 2 - latitude); } static double shortestDistanceBetween(Point a, Point b); static double getLongitudeDelta(double latitude, double distance); static double getLatitudeDelta(double distance); static double normalizeLongitude(double longitude); static double normalizeLatitude(double latitude); static final String EPSG_4326; }### Answer: @Test public void shouldReturnNearZeroDistanceAtPoles() throws FactoryException { assertThat(getLatitutesCircleRadius(toRadians(90)), closeTo(0.0, ERROR_DELTA)); assertThat(getLatitutesCircleRadius(toRadians(-90d)), closeTo(0.0, ERROR_DELTA)); assertThat(getLatitutesCircleRadius(toRadians(270d)), closeTo(0.0, ERROR_DELTA)); }
### Question: WGS84Util { public static double normalizeLatitude(double latitude) { double asRad = Math.toRadians(latitude); if (asRad > Math.PI / 2) { return Math.toDegrees(2 * Math.PI - asRad) % 90; } else if (-Math.PI / 2 > asRad) { return Math.toDegrees(-2 * Math.PI - asRad) % 90; } return latitude; } static double shortestDistanceBetween(Point a, Point b); static double getLongitudeDelta(double latitude, double distance); static double getLatitudeDelta(double distance); static double normalizeLongitude(double longitude); static double normalizeLatitude(double latitude); static final String EPSG_4326; }### Answer: @Test public void shouldNormlizeLatitudesBiggerThan90Degrees() { double toNormalize = 91.4; double normalized = WGS84Util.normalizeLatitude(toNormalize); assertThat(normalized, closeTo(88.6, ERROR_DELTA)); } @Test public void shouldNormlizeLatitudesSmallerThanMinus90Degrees() { double toNormalize = -91.4; double normalized = WGS84Util.normalizeLatitude(toNormalize); assertThat(normalized, closeTo(-88.6, ERROR_DELTA)); } @Test public void shouldNotChangeZeroLatitudeDegrees() { double toNormalize = 0; double normalized = WGS84Util.normalizeLatitude(toNormalize); assertThat(normalized, closeTo(0, ERROR_DELTA)); }
### Question: WGS84Util { public static double normalizeLongitude(double longitude) { double asRad = Math.toRadians(longitude); if (asRad > Math.PI) { return Math.toDegrees(-2 * Math.PI + asRad) % 180; } else if (-Math.PI > asRad) { return Math.toDegrees(2 * Math.PI + asRad) % 180; } return longitude; } static double shortestDistanceBetween(Point a, Point b); static double getLongitudeDelta(double latitude, double distance); static double getLatitudeDelta(double distance); static double normalizeLongitude(double longitude); static double normalizeLatitude(double latitude); static final String EPSG_4326; }### Answer: @Test public void shouldNormlizeLongitudesBiggerThan180Degrees() { double toNormalize = 182.3; double normalized = WGS84Util.normalizeLongitude(toNormalize); assertThat(normalized, closeTo(-177.7, ERROR_DELTA)); } @Test public void shouldNormlizeLongitudesSmallerThan180Degrees() { double toNormalize = -182.3; double normalized = WGS84Util.normalizeLongitude(toNormalize); assertThat(normalized, closeTo(177.7, ERROR_DELTA)); } @Test public void shouldNotChangeZeroLongitudeDegrees() { double toNormalize = 0; double normalized = WGS84Util.normalizeLongitude(toNormalize); assertThat(normalized, closeTo(0, ERROR_DELTA)); }
### Question: BoundingBox implements Serializable { public boolean contains(Geometry geometry) { return geometry.getDimension() > 2 ? !(geometry.contains(ll) || geometry.contains(ur)) : asEnvelop().contains(geometry.getEnvelopeInternal()); } @SuppressWarnings("unused") private BoundingBox(); BoundingBox(Point ll, Point ur, String srs); boolean contains(Geometry geometry); Envelope asEnvelop(); void extendBy(Point point); void setLl(Point ll); void setUr(Point ur); Point getLowerLeft(); Point getUpperRight(); String getSrs(); @Override String toString(); }### Answer: @Test public void testContainingGeometryIsContained() throws ParseException { Point ll = (Point) createGeometry("POINT (0 0)"); Point ur = (Point) createGeometry("POINT (10 10)"); BoundingBox bbox = new BoundingBox(ll, ur, "EPSG:4326"); Geometry overlappingPolygon = createGeometry("POLYGON ((0 1, 9 0, 3 3, 0 1))"); assertTrue(bbox.contains(overlappingPolygon), "geometry is not contained by bbox"); } @Test public void testOverlappingGeometryIsNotContained() throws ParseException { Point ll = (Point) createGeometry("POINT (0 0)"); Point ur = (Point) createGeometry("POINT (10 10)"); BoundingBox bbox = new BoundingBox(ll, ur, "EPSG:4326"); Geometry overlappingPolygon = createGeometry("POLYGON ((0 1, 11 0, 3 3, 0 1))"); assertFalse(bbox.contains(overlappingPolygon), "geometry is contained by bbox"); }
### Question: IntervalWithTimeZone { public Interval toInterval() { return Interval.parse(timespan); } IntervalWithTimeZone(String timespan); DateTimeZone getTimezone(); Interval toInterval(); @Override String toString(); }### Answer: @Test public void shouldParseToJodaInterval() { IntervalWithTimeZone interval = new IntervalWithTimeZone(VALID_ISO8601_RELATIVE_START); assertThat(interval.toInterval(), is(equalTo(new Interval(VALID_ISO8601_RELATIVE_START)))); }
### Question: RequestParameterSet { public final String getAsString(String parameterName) { return getAsString(parameterName, null); } protected RequestParameterSet(); String getOutputTimezone(); void setOutputTimezone(String timezone); boolean isGeneralize(); void setGeneralize(boolean generalize); @JsonProperty String getTimespan(); void setTimespan(String timespan); boolean isBase64(); void setBase64(boolean base64); boolean isExpanded(); void setExpanded(boolean expanded); String getLocale(); void setLocale(String locale); String getResultTime(); void setResultTime(String resultTime); Set<String> availableParameterNames(); final boolean containsParameter(String parameter); void removeParameter(String parameterName); final void setParameters(Map<String, JsonNode> parameters); final void setParameter(String parameter, Object value); final void setParameter(String parameterName, JsonNode value); final T getAs(Class<T> clazz, String parameterName, T defaultValue); final T getAs(Class<T> clazz, String parameterName); final JsonNode getParameterValue(String parameterName); final String[] getAsStringArray(String parameterName); final String[] getAsStringArray(String parameterName, String[] defaultValue); final String getAsString(String parameterName); final String getAsString(String parameterName, String defaultValue); final Integer getAsInt(String parameterName); final Integer getAsInt(String parameterName, Integer defaultValue); final Boolean getAsBoolean(String parameterName); final Boolean getAsBoolean(String parameterName, Boolean defaultValue); abstract String[] getDatasets(); IoParameters toParameters(); @Override String toString(); }### Answer: @Test public void when_stringParameterNotPresent_then_returnNullInsteadOfExceptions() { RequestParameterSet parameterset = createDummyParameterSet(); assertThat(parameterset.getAsString("notthere"), nullValue(String.class)); } @Test public void when_stringParameterNotPresent_then_returnDefault() { RequestParameterSet parameterset = createDummyParameterSet(); assertThat(parameterset.getAsString("notthere", "value"), is("value")); }
### Question: RequestParameterSet { public final Boolean getAsBoolean(String parameterName) { return getAsBoolean(parameterName, null); } protected RequestParameterSet(); String getOutputTimezone(); void setOutputTimezone(String timezone); boolean isGeneralize(); void setGeneralize(boolean generalize); @JsonProperty String getTimespan(); void setTimespan(String timespan); boolean isBase64(); void setBase64(boolean base64); boolean isExpanded(); void setExpanded(boolean expanded); String getLocale(); void setLocale(String locale); String getResultTime(); void setResultTime(String resultTime); Set<String> availableParameterNames(); final boolean containsParameter(String parameter); void removeParameter(String parameterName); final void setParameters(Map<String, JsonNode> parameters); final void setParameter(String parameter, Object value); final void setParameter(String parameterName, JsonNode value); final T getAs(Class<T> clazz, String parameterName, T defaultValue); final T getAs(Class<T> clazz, String parameterName); final JsonNode getParameterValue(String parameterName); final String[] getAsStringArray(String parameterName); final String[] getAsStringArray(String parameterName, String[] defaultValue); final String getAsString(String parameterName); final String getAsString(String parameterName, String defaultValue); final Integer getAsInt(String parameterName); final Integer getAsInt(String parameterName, Integer defaultValue); final Boolean getAsBoolean(String parameterName); final Boolean getAsBoolean(String parameterName, Boolean defaultValue); abstract String[] getDatasets(); IoParameters toParameters(); @Override String toString(); }### Answer: @Test public void when_booleanParameterNotPresent_then_returnNullInsteadOfExceptions() { RequestParameterSet parameterset = createDummyParameterSet(); assertThat(parameterset.getAsBoolean("notthere"), nullValue(Boolean.class)); } @Test public void when_booleanParameterNotPresent_then_returnDefault() { RequestParameterSet parameterset = createDummyParameterSet(); assertThat(parameterset.getAsBoolean("notthere", false), is(false)); }
### Question: RequestParameterSet { public final Integer getAsInt(String parameterName) { return getAsInt(parameterName, null); } protected RequestParameterSet(); String getOutputTimezone(); void setOutputTimezone(String timezone); boolean isGeneralize(); void setGeneralize(boolean generalize); @JsonProperty String getTimespan(); void setTimespan(String timespan); boolean isBase64(); void setBase64(boolean base64); boolean isExpanded(); void setExpanded(boolean expanded); String getLocale(); void setLocale(String locale); String getResultTime(); void setResultTime(String resultTime); Set<String> availableParameterNames(); final boolean containsParameter(String parameter); void removeParameter(String parameterName); final void setParameters(Map<String, JsonNode> parameters); final void setParameter(String parameter, Object value); final void setParameter(String parameterName, JsonNode value); final T getAs(Class<T> clazz, String parameterName, T defaultValue); final T getAs(Class<T> clazz, String parameterName); final JsonNode getParameterValue(String parameterName); final String[] getAsStringArray(String parameterName); final String[] getAsStringArray(String parameterName, String[] defaultValue); final String getAsString(String parameterName); final String getAsString(String parameterName, String defaultValue); final Integer getAsInt(String parameterName); final Integer getAsInt(String parameterName, Integer defaultValue); final Boolean getAsBoolean(String parameterName); final Boolean getAsBoolean(String parameterName, Boolean defaultValue); abstract String[] getDatasets(); IoParameters toParameters(); @Override String toString(); }### Answer: @Test public void when_intParameterNotPresent_then_returnDefault() { RequestParameterSet parameterset = createDummyParameterSet(); assertThat(parameterset.getAsInt("notthere", -99), is(-99)); } @Test public void when_intParameterNotPresent_then_returnNullInsteadOfExceptions() { RequestParameterSet parameterset = createDummyParameterSet(); assertThat(parameterset.getAsInt("notthere"), nullValue(Integer.class)); }
### Question: FilterResolver { public boolean hasInsituFilter() { return parameters.getInsitu() != null; } FilterResolver(IoParameters parameters); boolean hasMobileFilter(); boolean hasInsituFilter(); boolean isMobileFilter(); boolean isInsituFilter(); boolean shallIncludeAllDatasets(); boolean isSetPlatformTypeFilter(); boolean shallIncludeAllDatasetTypes(); boolean shallIncludeDatasetType(String datasetType); boolean shallIncludeAllObservationTypes(); boolean shallIncludeObservationType(String observationType); boolean shallIncludeAllValueTypes(); boolean shallIncludeValueType(String valueType); }### Answer: @Test public void when_defaults_then_insituFilterActive() { FilterResolver resolver = createResolver(createDefaults()); Assertions.assertFalse(resolver.hasInsituFilter()); } @Test public void when_defaults_then_remoteFilterActive() { FilterResolver resolver = createResolver(createDefaults()); Assertions.assertFalse(resolver.hasInsituFilter()); } @Test public void when_setAllDatasets_then_insituFilterActive() { IoParameters parameters = createDefaults(); FilterResolver resolver = createResolver(parameters); Assertions.assertFalse(resolver.hasInsituFilter()); } @Test public void when_setAllDatasets_then_remoteFilterActive() { IoParameters parameters = createDefaults(); FilterResolver resolver = createResolver(parameters); Assertions.assertFalse(resolver.hasInsituFilter()); }
### Question: FilterResolver { public boolean hasMobileFilter() { return parameters.getMobile() != null; } FilterResolver(IoParameters parameters); boolean hasMobileFilter(); boolean hasInsituFilter(); boolean isMobileFilter(); boolean isInsituFilter(); boolean shallIncludeAllDatasets(); boolean isSetPlatformTypeFilter(); boolean shallIncludeAllDatasetTypes(); boolean shallIncludeDatasetType(String datasetType); boolean shallIncludeAllObservationTypes(); boolean shallIncludeObservationType(String observationType); boolean shallIncludeAllValueTypes(); boolean shallIncludeValueType(String valueType); }### Answer: @Test public void when_defaults_then_stationaryFilterActive() { FilterResolver resolver = createResolver(createDefaults()); Assertions.assertFalse(resolver.hasMobileFilter()); } @Test public void when_defaults_then_mobileFilterActive() { FilterResolver resolver = createResolver(createDefaults()); Assertions.assertFalse(resolver.hasMobileFilter()); } @Test public void when_setAllDatasets_then_stationaryFilterActive() { IoParameters parameters = createDefaults(); FilterResolver resolver = createResolver(parameters); Assertions.assertFalse(resolver.hasMobileFilter()); } @Test public void when_setAllDatasets_then_mobileFilterActive() { IoParameters parameters = createDefaults(); FilterResolver resolver = createResolver(parameters); Assertions.assertFalse(resolver.hasMobileFilter()); }
### Question: FilterResolver { public boolean shallIncludeAllDatasetTypes() { Set<String> types = parameters.getDatasetTypes(); return (!isSetDatasetTypeFilter() && !isSetObservationTypeFilter() && !isSetValueTypeFilter()) || types.contains(ALL); } FilterResolver(IoParameters parameters); boolean hasMobileFilter(); boolean hasInsituFilter(); boolean isMobileFilter(); boolean isInsituFilter(); boolean shallIncludeAllDatasets(); boolean isSetPlatformTypeFilter(); boolean shallIncludeAllDatasetTypes(); boolean shallIncludeDatasetType(String datasetType); boolean shallIncludeAllObservationTypes(); boolean shallIncludeObservationType(String observationType); boolean shallIncludeAllValueTypes(); boolean shallIncludeValueType(String valueType); }### Answer: @Test public void when_setAllDatasetTypes_then_noFilterActive() { IoParameters parameters = createDefaults().extendWith(Parameters.FILTER_DATASET_TYPES, "all"); FilterResolver resolver = createResolver(parameters); Assertions.assertTrue(resolver.shallIncludeAllDatasetTypes()); }
### Question: ProfileDataItem implements Comparable<ProfileDataItem<T>> { @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) public BigDecimal getVerticalTo() { return isSetVerticalFrom() ? this.vertical : null; } ProfileDataItem(); ProfileDataItem(BigDecimal vertical, T value); ProfileDataItem(BigDecimal verticalFrom, BigDecimal verticalTo, T value); BigDecimal getVerticalFrom(); @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) void setVerticalFrom(BigDecimal verticalFrom); @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) BigDecimal getVerticalTo(); @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) BigDecimal getVertical(); void setVertical(BigDecimal vertical); @JsonInclude(content = Include.ALWAYS) T getValue(); void setValue(T value); @JsonIgnore void setValueFormatter(ValueFormatter<T> valueFormatter); @JsonIgnore String getFormattedValue(); DetectionLimitOutput getDetectionLimit(); void setDetectionLimit(DetectionLimitOutput detectionLimit); @Override int compareTo(ProfileDataItem<T> o); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void getVerticalTo_when_verticalFromIsNull() { ProfileDataItem<Object> value = new ProfileDataItem<>(BigDecimal.valueOf(1L), null); MatcherAssert.assertThat("verticalTo is null", value.getVerticalTo(), IsNull.nullValue()); } @Test public void getVerticalTo_when_verticalFromIsNotNull() { ProfileDataItem<Object> value = new ProfileDataItem<>(BigDecimal.valueOf(1L), BigDecimal.valueOf(2L), null); MatcherAssert.assertThat("verticalTo is null", value.getVerticalTo(), IsNull.notNullValue()); MatcherAssert.assertThat("verticalTo is not of value 2L", value.getVerticalTo(), is(BigDecimal.valueOf(2L))); }
### Question: ProfileDataItem implements Comparable<ProfileDataItem<T>> { @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) public BigDecimal getVertical() { return !isSetVerticalFrom() ? this.vertical : null; } ProfileDataItem(); ProfileDataItem(BigDecimal vertical, T value); ProfileDataItem(BigDecimal verticalFrom, BigDecimal verticalTo, T value); BigDecimal getVerticalFrom(); @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) void setVerticalFrom(BigDecimal verticalFrom); @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) BigDecimal getVerticalTo(); @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) BigDecimal getVertical(); void setVertical(BigDecimal vertical); @JsonInclude(content = Include.ALWAYS) T getValue(); void setValue(T value); @JsonIgnore void setValueFormatter(ValueFormatter<T> valueFormatter); @JsonIgnore String getFormattedValue(); DetectionLimitOutput getDetectionLimit(); void setDetectionLimit(DetectionLimitOutput detectionLimit); @Override int compareTo(ProfileDataItem<T> o); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void getVertical_when_verticalFromIsNull() { ProfileDataItem<Object> value = new ProfileDataItem<>(BigDecimal.valueOf(1L), null); MatcherAssert.assertThat("vertical is null", value.getVertical(), IsNull.notNullValue()); MatcherAssert.assertThat("vertical is not of value 1L", value.getVertical(), is(BigDecimal.valueOf(1L))); }
### Question: Sample3Controller { @PostMapping("/sample3") public String save(@RequestBody PointDto requestDto){ messagingTemplate.convertAndSend("sample3", requestDto); return "success"; } @PostMapping("/sample3") String save(@RequestBody PointDto requestDto); }### Answer: @Test public void Ack_fails_Go_to_the_dlq() throws Exception { PointDto requestDto = PointDto.builder() .userId(1L) .savePoint(1000L) .description("buy laptop") .build(); given(pointRepository.save(any())) .willThrow(new IllegalArgumentException("fail")); pointListener.setCountDownLatch(new CountDownLatch(1)); messagingTemplate.convertAndSend("sample3", requestDto); assertTrue(this.pointListener.getCountDownLatch().await(15, TimeUnit.SECONDS)); }
### Question: RandomPortFinder { public static int findAvailablePort() { for (int i=0; i<1000; i++) { try { int port = getRandomPort(); if(!isRunning(executeGrepProcessCommand(port))){ return port; } } catch (IOException ex) { } } String message = "Not Found Available port: 10000 ~ 65535"; log.error(message); throw new SqsMockException(message); } static int findAvailablePort(); static int getRandomPort(); }### Answer: @Test public void get_available_port() throws Exception { int usePort = 10000; ServerSocket serverSocket = new ServerSocket(usePort); int availablePort = RandomPortFinder.findAvailablePort(); assertTrue(availablePort != usePort); serverSocket.close(); }
### Question: Kelly { private void reloadCacheEntry(CacheEntry cacheEntry) throws ExecutionException, InterruptedException { LoaderCallable<T> loaderCallable = new LoaderCallable<T>(this, cacheProvider, cacheLoader, cacheEntry); executorService.submit(loaderCallable); } @Deprecated Kelly(CacheProvider<T> cacheProvider, CacheLoader<T> cacheLoader, int executorPoolSize); Kelly(CacheProvider<T> cacheProvider, CacheLoader<T> cacheLoader, int threadPoolSize, int queueSize); T get(String key); boolean put(String key, CacheEntry<T> value); void expire(String key); }### Answer: @Test public void reloadCacheEntryTest() throws CacheProviderException, KellyException, InterruptedException, CacheLoaderException { CacheProvider<String> cacheProvider = Mockito.mock(CacheProvider.class); CacheLoader<String> cacheLoader = Mockito.mock(CacheLoader.class); CacheEntry<String> cacheEntry = new CacheEntry<String>("dude", "suman karthik", 1); CacheEntry<String> cacheEntry1 = new CacheEntry<String>("dude", "suman", 1); Kelly<String> kelly = new Kelly<String>(cacheProvider, cacheLoader, 1); Mockito.when(cacheProvider.get("dude")).thenReturn(cacheEntry); Mockito.when(cacheLoader.reload("dude", "suman karthik")).thenReturn(cacheEntry1); assert kelly.get("dude").equals("suman karthik"); Thread.sleep(3000); assert kelly.get("dude").equals("suman karthik"); Thread.sleep(1000); Mockito.verify(cacheLoader).reload("dude","suman karthik"); Mockito.verify(cacheProvider).put("dude", cacheEntry1); }
### Question: Kelly { public boolean put(String key, CacheEntry<T> value) throws KellyException { try { return cacheProvider.put(key,value); } catch (CacheProviderException e) { throw new KellyException(e); } } @Deprecated Kelly(CacheProvider<T> cacheProvider, CacheLoader<T> cacheLoader, int executorPoolSize); Kelly(CacheProvider<T> cacheProvider, CacheLoader<T> cacheLoader, int threadPoolSize, int queueSize); T get(String key); boolean put(String key, CacheEntry<T> value); void expire(String key); }### Answer: @Test public void kellyPutTest() throws CacheProviderException, KellyException { CacheProvider<String> cacheProvider = Mockito.mock(CacheProvider.class); CacheLoader<String> cacheLoader = Mockito.mock(CacheLoader.class); CacheEntry<String> cacheEntry = new CacheEntry<String>("dude","suman",1); Mockito.when(cacheProvider.put("dude",cacheEntry)).thenReturn(true); Kelly<String> kelly = new Kelly<String>(cacheProvider,cacheLoader,1); assert kelly.put("dude",cacheEntry); Mockito.verify(cacheProvider).put("dude", cacheEntry); }
### Question: Kelly { public void expire(String key) throws KellyException { T value = get(key); CacheEntry<T> cacheEntry = new CacheEntry<T>(key,value,-10); put(key,cacheEntry); get(key); } @Deprecated Kelly(CacheProvider<T> cacheProvider, CacheLoader<T> cacheLoader, int executorPoolSize); Kelly(CacheProvider<T> cacheProvider, CacheLoader<T> cacheLoader, int threadPoolSize, int queueSize); T get(String key); boolean put(String key, CacheEntry<T> value); void expire(String key); }### Answer: @Test(dependsOnMethods = {"requestsInFlightTest"}) public void expireTest() throws KellyException, CacheProviderException, InterruptedException { CacheEntry<String> cacheEntry = new CacheEntry<String>("dude","suman",300); CacheProvider<String> cacheProvider = new DummyCacheProvider(); CacheLoader<String> cacheLoader = new DummyCacheLoader(); Kelly<String> kelly = new Kelly<String>(cacheProvider,cacheLoader,10); kelly.put("dude",cacheEntry); kelly.expire("dude"); assert cacheProvider.get("dude").getTtl()==-10; Thread.sleep(4000); assert kelly.get("dude").equals("suman karthik"); }
### Question: RedisCacheProvider implements CacheProvider<String> { @Override public CacheEntry<String> get(String key) throws CacheProviderException { assert pool != null; try (Jedis jedis = pool.getResource()) { try { String valueFromCache = jedis.get(key); if (StringUtils.isNotBlank(valueFromCache)) { return mapper.readValue(valueFromCache, new TypeReference<CacheEntry<String>>() {}); } else { return null; } } catch (Exception e) { throw new CacheProviderException(e); } } } RedisCacheProvider(JedisSentinelPool pool, ObjectMapper mapper); @Override CacheEntry<String> get(String key); @Override Boolean put(String key, CacheEntry<String> cacheEntry); }### Answer: @Test public void shouldDeserialize() throws Exception { String key = "TEST-KEY"; when(jedis.get(key)).thenReturn(cacheEntryAsString); assertEquals(cacheEntryAsString, mapper.writeValueAsString(cacheProvider.get(key))); }
### Question: RedisCacheProvider implements CacheProvider<String> { @Override public Boolean put(String key, CacheEntry<String> cacheEntry) throws CacheProviderException { assert pool != null; try (Jedis jedis = pool.getResource()) { jedis.set(key, mapper.writeValueAsString(cacheEntry)); return true; } catch (Exception e) { throw new CacheProviderException(e); } } RedisCacheProvider(JedisSentinelPool pool, ObjectMapper mapper); @Override CacheEntry<String> get(String key); @Override Boolean put(String key, CacheEntry<String> cacheEntry); }### Answer: @Test public void shouldSerialize() throws Exception { String key = "TEST-KEY"; cacheProvider.put(key, cacheEntry); verify(jedis).set(key, cacheEntryAsString); }
### Question: FunctionApp { public static JsonObject main(JsonObject args) { JsonObject response = new JsonObject(); response.addProperty("greetings", "Hello! Welcome to OpenWhisk on OpenShift"); return response; } static JsonObject main(JsonObject args); }### Answer: @Test public void testFunction() { JsonObject args = new JsonObject(); JsonObject response = FunctionApp.main(args); assertNotNull(response); String greetings = response.getAsJsonPrimitive("greetings").getAsString(); assertNotNull(greetings); assertEquals("Hello! Welcome to OpenWhisk on OpenShift", greetings); }
### Question: FunctionApp { public static JsonObject main(JsonObject args) { JsonObject response = new JsonObject(); String text = null; if (args.has("text")) { text = args.getAsJsonPrimitive("text").getAsString(); } String[] results = new String[] { text }; if (text != null && text.indexOf(",") != -1) { results = text.split(","); } JsonArray splitStrings = new JsonArray(); for (String var : results) { splitStrings.add(var); } response.add("result", splitStrings); return response; } static JsonObject main(JsonObject args); }### Answer: @Test public void testFunction() { JsonObject args = new JsonObject(); args.addProperty("text", "apple,orange,banana"); JsonObject response = FunctionApp.main(args); assertNotNull(response); JsonArray results = response.getAsJsonArray("result"); assertNotNull(results); assertEquals(3, results.size()); List<String> actuals = new ArrayList<>(); results.forEach(j -> actuals.add(j.getAsString())); assertTrue(actuals.contains("apple")); assertTrue(actuals.contains("orange")); assertTrue(actuals.contains("banana")); }
### Question: FunctionApp { public static JsonObject main(JsonObject args) { JsonObject response = new JsonObject(); JsonArray upperArray = new JsonArray(); if (args.has("result")) { args.getAsJsonArray("result").forEach(e -> upperArray.add(e.getAsString().toUpperCase())); } response.add("result", upperArray); return response; } static JsonObject main(JsonObject args); }### Answer: @Test public void testFunction() { JsonObject args = new JsonObject(); JsonArray splitStrings = new JsonArray(); splitStrings.add("apple"); splitStrings.add("orange"); splitStrings.add("banana"); args.add("result", splitStrings); JsonObject response = FunctionApp.main(args); assertNotNull(response); JsonArray results = response.getAsJsonArray("result"); assertNotNull(results); assertEquals(3, results.size()); List<String> actuals = new ArrayList<>(); results.forEach(j -> actuals.add(j.getAsString())); assertTrue(actuals.contains("APPLE")); assertTrue(actuals.contains("ORANGE")); assertTrue(actuals.contains("BANANA")); }
### Question: FunctionApp { public static JsonObject main(JsonObject args) { JsonObject response = new JsonObject(); List<String> upperStrings = new ArrayList<>(); if (args.has("result")) { args.getAsJsonArray("result").forEach(e -> upperStrings.add(e.getAsString())); } JsonArray sortedArray = new JsonArray(); upperStrings.stream().sorted(Comparator.naturalOrder()).forEach(s -> sortedArray.add(s)); response.add("result", sortedArray); return response; } static JsonObject main(JsonObject args); }### Answer: @Test public void testFunction() { JsonObject args = new JsonObject(); JsonArray splitStrings = new JsonArray(); splitStrings.add("APPLE"); splitStrings.add("ORANGE"); splitStrings.add("BANANA"); args.add("result", splitStrings); JsonObject response = FunctionApp.main(args); assertNotNull(response); JsonArray results = response.getAsJsonArray("result"); assertNotNull(results); assertEquals(3, results.size()); List<String> actuals = new ArrayList<>(); results.forEach(j -> actuals.add(j.getAsString())); assertTrue(actuals.get(0).equals("APPLE")); assertTrue(actuals.get(1).equals("BANANA")); assertTrue(actuals.get(2).equals("ORANGE")); }
### Question: FunctionApp { public static JsonObject main(JsonObject args) { JsonObject response = new JsonObject(); response.add("response", args); return response; } static JsonObject main(JsonObject args); }### Answer: @Test public void testFunction() { JsonObject args = new JsonObject(); args.addProperty("name", "test"); JsonObject response = FunctionApp.main(args); assertNotNull(response); String actual = response.get("response").getAsJsonObject().get("name").getAsString(); assertEquals("test", actual); }
### Question: JssdkUtils { public static Map<String, String> sign (final String jsapiTicket) { return sign(jsapiTicket, ""); } private JssdkUtils(); static Map<String, String> sign(final String jsapiTicket); static Map<String, String> sign(final String jsapiTicket, final String url); static String getAccessToken(final String appId, final String appSecret); static String getJsapiTicket(final String appId, final String appSecret); static String getJsapiTicket(final String accessToken); }### Answer: @Test public void testSign () { final String jsapiTicket = JssdkUtils.getJsapiTicket(appId, appSecret); final Map<String, String> map = JssdkUtils.sign(jsapiTicket, url); for (Map.Entry<String, String> entry : map.entrySet()) { LOG.info(entry.getKey() + ":" + entry.getValue()); } }
### Question: ReflectUtils { public static <T> T map2Object (final Map<String, Object> map, final Class<T> valueType) throws IllegalAccessException, InstantiationException { final T obj = valueType.newInstance(); final String METHOD_PREFIX = "set"; map.forEach((fieldName, fieldValue) -> { final StringBuilder sb = new StringBuilder(); try { final Method method = ReflectUtils.getMethod(valueType, sb.append(METHOD_PREFIX).append(StringUtils.capitalize(fieldName)).toString()); method.invoke(obj, fieldValue); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { LOG.error(e.getMessage()); } }); return obj; } private ReflectUtils(); static Field getField(final Class clazz, final String fieldName); static Method getMethod(final Class clazz, final String methodName); static T map2Object(final Map<String, Object> map, final Class<T> valueType); }### Answer: @Test public void testMap2Object () throws InstantiationException, IllegalAccessException { final Map<String, Object> map = new HashMap<>(); map.put("name", "bascker"); map.put("age", 24); map.put("sex", Sex.MALE); Assert.assertEquals("Person{mName='bascker', mAge=24, mSex=MALE}", ReflectUtils.map2Object(map, Person.class).toString()); }
### Question: ImageProcess { public static boolean isEmpty (final File imageFile) throws IOException { return isEmpty(ImageIO.read(imageFile)); } private ImageProcess(); static File download(final String imgUrl); static List<File> dowloads(final Set<String> urls); static boolean isEmpty(final File imageFile); static boolean isEmpty(final String imageUrl); static boolean isEmpty(final BufferedImage image); }### Answer: @Test public void testIsEmpty () { try { Assert.assertFalse(ImageProcess.isEmpty("http: } catch (IOException e) { e.printStackTrace(); } }
### Question: CollectionHelper { public static <T> T[] toArray (final Collection<T> collection) throws NoSuchMethodException { if (!isValid(collection)) { return null; } return (T[]) collection.toArray(); } private CollectionHelper(); static void sortDesc(final List<Integer> numbers); static boolean isValid(final Collection collection); static String toString(final Collection collection); static T[] toArray(final Collection<T> collection); static boolean isEmpty(final Collection<?> collection); static boolean isEmpty(final Map<?, ?> map); }### Answer: @Test public void testToArray () throws NoSuchMethodException { final List<String> namse = Arrays.asList("bascker", "johnnie", "lisa", "an"); final String[] names = CollectionHelper.toArray(namse); LOG.info(Arrays.toString(names)); final String[] rs = CollectionHelper.toArray(Collections.emptyList()); LOG.info(Arrays.toString(rs)); }
### Question: GamePlayerProxy implements InvocationHandler { public Object getProxy () { return Proxy.newProxyInstance(mClass.getClassLoader(), mClass.getInterfaces(), this); } GamePlayerProxy(final Object object); Object getProxy(); @Override Object invoke(final Object proxy, final Method method, final Object[] args); }### Answer: @Test public void test () { final GamePlayer player = new DnfGamePlayer("bascker", "123456"); final GamePlayerProxy handler = new GamePlayerProxy(player); final GamePlayer proxy = (GamePlayer) handler.getProxy(); proxy.login(); proxy.killBoss(); proxy.upgrade(); }
### Question: Genericity { public void wildcard(final List<?> list) { LOG.info(CollectionHelper.toString(list)); } void wildcard(final List<?> list); void up(final List<? extends Number> numbers); void down(final List<? super String> list); }### Answer: @Test public void testWildcard() { sample.wildcard(nums); final List<?> list = Arrays.asList(1, "bascker", '?'); sample.wildcard(list); }
### Question: Genericity { public void up(final List<? extends Number> numbers) { LOG.info(CollectionHelper.toString(numbers)); numbers.add(null); final Number n = numbers.get(0); LOG.info("numbers.get(0): " + n); } void wildcard(final List<?> list); void up(final List<? extends Number> numbers); void down(final List<? super String> list); }### Answer: @Test public void testUp() { sample.up(nums); final List<Long> ls = LongStream.range(10, 20).boxed().collect(Collectors.toList()); sample.up(ls); }
### Question: Genericity { public void down(final List<? super String> list) { LOG.info(CollectionHelper.toString(list)); final Object obj = list.get(0); LOG.info("list.get(0): " + obj); list.add("ha ha ha"); } void wildcard(final List<?> list); void up(final List<? extends Number> numbers); void down(final List<? super String> list); }### Answer: @Test public void testDown() { final List<String> strs = new ArrayList<>(); strs.addAll(Arrays.asList("my", "name", "is", "bascker")); sample.down(strs); final List<Object> objects = new ArrayList<>(); objects.addAll(Arrays.asList(new Object(), new Object())); sample.down(objects); }
### Question: ObjFileLoader extends Applet { public void create () { setLayout(new BorderLayout()); final Canvas3D canvas3D = new Canvas3D(SimpleUniverse.getPreferredConfiguration()); add("Center",canvas3D); final SimpleUniverse simpleUniverse = new SimpleUniverse(canvas3D); simpleUniverse.getViewingPlatform().setNominalViewingTransform(); final BranchGroup branchGroup = createSceneGraph(); branchGroup.compile(); simpleUniverse.addBranchGraph(branchGroup); new MainFrame(this, 360, 360); } ObjFileLoader(final String objFile); void create(); DirectionalLight createLight(); Background createBackground(); String getObjFile(); void setObjFile(final String objFile); }### Answer: @Test public void test () { final ObjFileLoader objFileLoader = new ObjFileLoader("D:\\文档\\Obj文件\\布迪加双座敞篷跑车3D图纸.obj"); objFileLoader.create(); }
### Question: Sphere3d { public void create () { final SimpleUniverse simpleUniverse = new SimpleUniverse(); final BranchGroup branchGroup = new BranchGroup(); final Sphere sphere = new Sphere(mRadius); branchGroup.addChild(sphere); final DirectionalLight lightDirection = J3DUtils.createDefaultLight(); branchGroup.addChild(lightDirection); simpleUniverse.getViewingPlatform().setNominalViewingTransform(); simpleUniverse.addBranchGraph(branchGroup); } Sphere3d(final float radius); void create(); float getRadius(); void setRadius(final float radius); public float mRadius; }### Answer: @Test public void test () { final Sphere3d sphere3d = new Sphere3d(.5f); sphere3d.create(); }
### Question: LineShape extends Shape3D { public LineShape(final float lineWidth, final float[] verts, final float[] colors) { mLineWidth = lineWidth; mVerts = verts; mColors = colors; } LineShape(final float lineWidth, final float[] verts, final float[] colors); void create(); float getLineWidth(); void setLineWidth(final float lineWidth); float[] getVerts(); void setVerts(final float[] verts); float[] getColors(); void setColors(final float[] colors); }### Answer: @Test public void testLineShape () { final LineShape lineShape = new LineShape(10.0f, verts, colors); lineShape.create(); }
### Question: LineShape extends Shape3D { public void create () { final LineArray lineArray = createLineArray(); final LineAttributes lineAttributes = createLineAttributes(); final Appearance appearance = new Appearance(); appearance.setLineAttributes(lineAttributes); this.setGeometry(lineArray); this.setAppearance(appearance); } LineShape(final float lineWidth, final float[] verts, final float[] colors); void create(); float getLineWidth(); void setLineWidth(final float lineWidth); float[] getVerts(); void setVerts(final float[] verts); float[] getColors(); void setColors(final float[] colors); }### Answer: @Test public void testLine3dShape () { final Line3dShape line3dShape = new Line3dShape(10.0f, verts, colors); line3dShape.create(); }
### Question: Cylinder3d extends Applet { public void create () { final SimpleUniverse universe = new SimpleUniverse(); final BranchGroup branchGroup = new BranchGroup(); final Cylinder cylinder = new Cylinder(mRadius, mCylinderHeight); branchGroup.addChild(cylinder); final DirectionalLight light = J3DUtils.createDefaultLight(); branchGroup.addChild(light); universe.getViewingPlatform().setNominalViewingTransform(); universe.addBranchGraph(branchGroup); } Cylinder3d(final float radius, final float cylinderHeight); void create(); float getRadius(); void setRadius(final float radius); float getCylinderHeight(); void setCylinderHeight(final float cylinderHeight); }### Answer: @Test public void test () { final Cylinder3d cylinder3d = new Cylinder3d(.5f, 1.0f); cylinder3d.create(); }
### Question: Conus3d extends Applet { public void create () { final SimpleUniverse simpleUniverse = new SimpleUniverse(); final BranchGroup branchGroup = new BranchGroup(); final Cone cone = new Cone(mRadius, mConusHeight); branchGroup.addChild(cone); final DirectionalLight lightDirection = J3DUtils.createDefaultLight(); branchGroup.addChild(lightDirection); simpleUniverse.getViewingPlatform().setNominalViewingTransform(); simpleUniverse.addBranchGraph(branchGroup); } Conus3d(final float radius, final float conusHeight); void create(); float getRadius(); void setRadius(final float radius); float getConusHeight(); void setConusHeight(final float conusHeight); }### Answer: @Test public void test () { final Conus3d conus3d = new Conus3d(0.5f, 1.0f); conus3d.create(); }
### Question: DateUtils { public static String now (final String pattern) { final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); return dateFormat.format(calendar.getTime()); } private DateUtils(); static String now(final String pattern); static String now(); }### Answer: @Test public void testNow () { LOG.info(DateUtils.now()); }
### Question: ReflectUtils { public static Method getMethod (final Class clazz, final String methodName) throws NoSuchMethodException { final List<Method> methods = Arrays.stream(clazz.getDeclaredMethods()) .filter(method -> methodName.equals(method.getName())) .collect(Collectors.toList()); return methods.get(0); } private ReflectUtils(); static Field getField(final Class clazz, final String fieldName); static Method getMethod(final Class clazz, final String methodName); static T map2Object(final Map<String, Object> map, final Class<T> valueType); }### Answer: @Test public void testGetMethod () throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final Method method = ReflectUtils.getMethod(ReflectUtilsTest.class, "hello"); final ReflectUtilsTest test = new ReflectUtilsTest(); method.invoke(test); final Method setName = ReflectUtils.getMethod(Person.class, "setName"); final Person person = new Person(); setName.invoke(person, "bascker"); LOG.info(person.toString()); }
### Question: ComponentLifeRegistry { public void register(String name, ComponentLife componentLife) { componentLifeTreeSet.add(componentLife); if (!name.equals(ComponentLife.class.getCanonicalName())) { componentApplicationHashMap.put(name, componentLife); } componentApplicationHashMap.put(componentLife.getClass().getCanonicalName(), componentLife); } ComponentLifeRegistry(); void registerFromManifest(Application application); void register(String name, ComponentLife componentLife); T search(Class<T> clasz); Iterable<ComponentLife> getAll(); }### Answer: @Test public void lifeCycleInvoke() { aApplication = Mockito.mock(MockComponentALife.class); bApplication = Mockito.mock(MockComponentBLife.class); componentLifeRegistry.register("aApplication", aApplication); componentLifeRegistry.register("bApplication", bApplication); }
### Question: Router { public static List<Long> shortestPath(GraphDB g, double stlon, double stlat, double destlon, double destlat) { return null; } static List<Long> shortestPath(GraphDB g, double stlon, double stlat, double destlon, double destlat); static List<NavigationDirection> routeDirections(GraphDB g, List<Long> route); }### Answer: @Test public void testShortestPath() throws Exception { List<Map<String, Double>> testParams = paramsFromFile(); List<List<Long>> expectedResults = resultsFromFile(); for (int i = 0; i < NUM_TESTS; i++) { System.out.println(String.format("Running test: %d", i)); Map<String, Double> params = testParams.get(i); List<Long> actual = Router.shortestPath(graph, params.get("start_lon"), params.get("start_lat"), params.get("end_lon"), params.get("end_lat")); List<Long> expected = expectedResults.get(i); assertEquals("Your results did not match the expected results", expected, actual); } }
### Question: OffByN implements CharacterComparator { @Override public boolean equalChars(char x, char y) { return (Math.abs((int) x - (int) y) == N); } OffByN(int N); @Override boolean equalChars(char x, char y); }### Answer: @Test public void testequalChars1() { CharacterComparator OffByN = new OffByN(5); assertFalse(OffByN.equalChars('a', 'b')); } @Test public void testequalChars2() { CharacterComparator OffByN = new OffByN(5); assertTrue(OffByN.equalChars('a', 'f')); }
### Question: Rasterer { public Map<String, Object> getMapRaster(Map<String, Double> params) { Map<String, Object> results = new HashMap<>(); System.out.println("Since you haven't implemented getMapRaster, nothing is displayed in " + "your browser."); double lrlon = params.get(lrlon); double ullon = params.get(ullon); double width = params.get(w); double height = params.get(h); double ullat = params.get(ullat); double lrlat = params.get(lrlat); String[][] render_grid; double raster_ul_lon; double raster_ul_lat; double raster_lr_lon; double raster_lr_lat; int depth; boolean query_success; } Rasterer(); Map<String, Object> getMapRaster(Map<String, Double> params); }### Answer: @Test public void testGetMapRaster() throws Exception { List<Map<String, Double>> testParams = paramsFromFile(); List<Map<String, Object>> expectedResults = resultsFromFile(); for (int i = 0; i < NUM_TESTS; i++) { System.out.println(String.format("Running test: %d", i)); Map<String, Double> params = testParams.get(i); Map<String, Object> actual = rasterer.getMapRaster(params); Map<String, Object> expected = expectedResults.get(i); String msg = "Your results did not match the expected results for input " + mapToString(params) + ".\n"; checkParamsMap(msg, expected, actual); } }
### Question: OffByOne implements CharacterComparator { @Override public boolean equalChars(char x, char y) { return (Math.abs((int) x - (int) y) == 1); } @Override boolean equalChars(char x, char y); }### Answer: @Test public void testequalChars1() { assertTrue(offByOne.equalChars('a', 'b')); } @Test public void testequalChars2() { assertFalse(offByOne.equalChars('a', 'c')); } @Test public void testequalChars3() { assertTrue(offByOne.equalChars('&', '%')); } @Test public void testequalChars4() { assertFalse(offByOne.equalChars('a', 'B')); }
### Question: Plip extends Creature { public Plip replicate() { this.energy *= 0.5; Plip replica = new Plip(this.energy); return replica; } Plip(double e); Plip(); Color color(); void attack(Creature c); void move(); void stay(); Plip replicate(); Action chooseAction(Map<Direction, Occupant> neighbors); }### Answer: @Test public void testReplicate() { Plip p1 = new Plip(1.5); Plip p2 = p1.replicate(); assertNotSame(p1, p2); }
### Question: IntList { public static IntList of(Integer... args) { IntList result, p; if (args.length > 0) { result = new IntList(args[0], null); } else { return null; } int k; for (k = 1, p = result; k < args.length; k += 1, p = p.rest) { p.rest = new IntList(args[k], null); } return result; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer: @Test public void testList() { IntList one = new IntList(1, null); IntList twoOne = new IntList(2, one); IntList threeTwoOne = new IntList(3, twoOne); IntList x = IntList.of(3, 2, 1); assertEquals(threeTwoOne, x); }
### Question: IntList { public static void dSquareList(IntList L) { while (L != null) { L.first = L.first * L.first; L = L.rest; } } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer: @Test public void testdSquareList() { IntList L = IntList.of(1, 2, 3); IntList.dSquareList(L); assertEquals(IntList.of(1, 4, 9), L); }
### Question: ArrayDeque { public boolean isEmpty() { return size == 0; } ArrayDeque(); void addFirst(PlaceholderType item); void addLast(PlaceholderType item); boolean isEmpty(); int size(); void printDeque(); PlaceholderType removeFirst(); PlaceholderType removeLast(); PlaceholderType get(int index); }### Answer: @Test public void IsEmptyTest1() { System.out.println("Perform IsEmptyTest1"); ArrayDeque<Integer> array = new ArrayDeque<>(); assertEquals(array.isEmpty(), true); }
### Question: IntList { public static IntList squareListRecursive(IntList L) { if (L == null) { return null; } return new IntList(L.first * L.first, squareListRecursive(L.rest)); } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer: @Test public void testSquareListRecursive() { IntList L = IntList.of(1, 2, 3); IntList res = IntList.squareListRecursive(L); assertEquals(IntList.of(1, 2, 3), L); assertEquals(IntList.of(1, 4, 9), res); }
### Question: IntList { public static IntList dcatenate(IntList A, IntList B) { if (A == null) { return B; } IntList p = A; while (p.rest != null) { p = p.rest; } p.rest = B; return A; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer: @Test public void testDcatenate() { IntList A = IntList.of(1, 2, 3); IntList B = IntList.of(4, 5, 6); IntList exp = IntList.of(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.dcatenate(A, B)); assertEquals(IntList.of(1, 2, 3, 4, 5, 6), A); }
### Question: IntList { public static IntList catenate(IntList A, IntList B) { if (A == null) { return B; } IntList returnList = new IntList (A.first , null); IntList q = returnList; A = A.rest; while (A != null) { q.rest = new IntList(A.first, null); A = A.rest; q = q.rest; } q.rest = B; return returnList; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; }### Answer: @Test public void testCatenate() { IntList A = IntList.of(1, 2, 3); IntList B = IntList.of(4, 5, 6); IntList exp = IntList.of(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.catenate(A, B)); assertEquals(IntList.of(1, 2, 3), A); }
### Question: IntList { public static IntList of(Integer... args) { IntList result, p; if (args.length > 0) { result = new IntList(args[0], null); } else { return null; } int k; for (k = 1, p = result; k < args.length; k += 1, p = p.rest) { p.rest = new IntList(args[k], null); } return result; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); static IntList reverse(IntList A); IntList dereverse(); public int first; public IntList rest; }### Answer: @Test public void testList() { IntList one = new IntList(1, null); IntList twoOne = new IntList(2, one); IntList threeTwoOne = new IntList(3, twoOne); IntList x = IntList.of(3, 2, 1); assertEquals(threeTwoOne, x); }
### Question: IntList { public static void dSquareList(IntList L) { while (L != null) { L.first = L.first * L.first; L = L.rest; } } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); static IntList reverse(IntList A); IntList dereverse(); public int first; public IntList rest; }### Answer: @Test public void testdSquareList() { IntList L = IntList.of(1, 2, 3); IntList.dSquareList(L); assertEquals(IntList.of(1, 4, 9), L); }
### Question: IntList { public static IntList squareListRecursive(IntList L) { if (L == null) { return null; } return new IntList(L.first * L.first, squareListRecursive(L.rest)); } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); static IntList reverse(IntList A); IntList dereverse(); public int first; public IntList rest; }### Answer: @Test public void testSquareListRecursive() { IntList L = IntList.of(1, 2, 3); IntList res = IntList.squareListRecursive(L); assertEquals(IntList.of(1, 2, 3), L); assertEquals(IntList.of(1, 4, 9), res); }
### Question: IntList { public static IntList dcatenate(IntList A, IntList B) { if (A == null) { return B; } IntList p = A; while (p.rest != null) { p = p.rest; } p.rest = B; return A; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); static IntList reverse(IntList A); IntList dereverse(); public int first; public IntList rest; }### Answer: @Test public void testDcatenate() { IntList A = IntList.of(1, 2, 3); IntList B = IntList.of(4, 5, 6); IntList exp = IntList.of(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.dcatenate(A, B)); assertEquals(IntList.of(1, 2, 3, 4, 5, 6), A); }
### Question: IntList { public static IntList catenate(IntList A, IntList B) { if (A == null) { return B; } IntList returnList = new IntList (A.first , null); IntList q = returnList; A = A.rest; while (A != null) { q.rest = new IntList(A.first, null); A = A.rest; q = q.rest; } q.rest = B; return returnList; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); static IntList reverse(IntList A); IntList dereverse(); public int first; public IntList rest; }### Answer: @Test public void testCatenate() { IntList A = IntList.of(1, 2, 3); IntList B = IntList.of(4, 5, 6); IntList exp = IntList.of(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.catenate(A, B)); assertEquals(IntList.of(1, 2, 3), A); }
### Question: IntList { public static IntList reverse(IntList A) { if (A == null) { return null; } IntList returnList = new IntList(A.first, null); while (A.rest != null) { A = A.rest; IntList tmp = new IntList(A.first, returnList); returnList = tmp; } return returnList; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); static IntList reverse(IntList A); IntList dereverse(); public int first; public IntList rest; }### Answer: @Test(timeout = 1000) public void testReverse() { IntList A = IntList.of(1, 2, 3); IntList exp = IntList.of(3, 2, 1); IntList A2 = IntList.of(3, 4, 5, 6, 3); IntList exp2 = IntList.of(3, 6, 5, 4, 3); IntList A3 = IntList.of(3); IntList exp3 = IntList.of(3); assertEquals(exp, IntList.reverse(A)); assertEquals(exp2, IntList.reverse(A2)); assertEquals(exp3, IntList.reverse(A3)); assertNull(IntList.reverse(null)); }
### Question: IntList { public IntList dereverse() { if (this.rest == null) { return this; } IntList tmp = this.rest; this.rest = null; while (tmp != null) { IntList tmp2 = new IntList(this.first, this.rest); this.first = tmp.first; this.rest = tmp2; tmp = tmp.rest; } return this; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList of(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); static IntList reverse(IntList A); IntList dereverse(); public int first; public IntList rest; }### Answer: @Test(timeout = 1000) public void testDereverse() { IntList A = IntList.of(1, 2, 3); IntList Ap = IntList.of(1, 2, 3); IntList exp = IntList.of(3, 2, 1); IntList A2 = IntList.of(3, 4, 5, 6, 3); IntList exp2 = IntList.of(3, 6, 5, 4, 3); assertEquals(exp, A.dereverse()); assertNotEquals(Ap, A); assertEquals(exp2, A2.dereverse()); }
### Question: ArrayDeque { public void printDeque() { for (PlaceholderType p : Array) { System.out.print(p + " "); } System.out.print("\n"); } ArrayDeque(); void addFirst(PlaceholderType item); void addLast(PlaceholderType item); boolean isEmpty(); int size(); void printDeque(); PlaceholderType removeFirst(); PlaceholderType removeLast(); PlaceholderType get(int index); }### Answer: @Test public void printDequeTest() { System.out.println("Perform printDequeTest1"); ArrayDeque<Integer> array = new ArrayDeque<>(); array.addFirst(123); array.addLast(234); array.addFirst(345); array.addLast(456); array.printDeque(); }
### Question: RadixSort { public static String[] sort(String[] asciis) { String[] sorted = new String[asciis.length]; System.arraycopy(asciis, 0, sorted, 0, asciis.length); int max = 0; for (String asc : asciis) { max = max > asc.length() ? max : asc.length(); } int index = 0; while (index < max) { sorted = sortHelperLSD(sorted, index); index += 1; } return sorted; } static String[] sort(String[] asciis); static void main(String[] args); }### Answer: @Test public void LSDSortTest() { String[] testArr1 = {"alatn", "hello", "succe", "donld", "hcdlo","heleh", "12321", "!*^&!"}; String[] result1 = RadixSort.sort(testArr1); System.out.println(Arrays.toString(result1)); String[] expected1 = {"alatn", "hello", "succe", "donld", "hcdlo","heleh", "12321", "!*^&!"}; assertArrayEquals(testArr1, expected1); }
### Question: AList { public int size() { return size; } AList(); void addLast(Item x); Item getLast(); Item get(int i); int size(); Item removeLast(); }### Answer: @Test public void testEmptySize() { AList L = new AList(); assertEquals(0, L.size()); }
### Question: AList { public Item get(int i) { return items[i]; } AList(); void addLast(Item x); Item getLast(); Item get(int i); int size(); Item removeLast(); }### Answer: @Test public void testGet() { AList L = new AList(); L.addLast(99); assertEquals(99, L.get(0)); L.addLast(36); assertEquals(99, L.get(0)); assertEquals(36, L.get(1)); }
### Question: AList { public int size() { return 0; } AList(); void addLast(int x); int getLast(); int get(int i); int size(); int removeLast(); }### Answer: @Test public void testEmptySize() { AList L = new AList(); assertEquals(0, L.size()); }
### Question: AList { public int get(int i) { return 0; } AList(); void addLast(int x); int getLast(); int get(int i); int size(); int removeLast(); }### Answer: @Test public void testGet() { AList L = new AList(); L.addLast(99); assertEquals(99, L.get(0)); L.addLast(36); assertEquals(99, L.get(0)); assertEquals(36, L.get(1)); }
### Question: GuitarString { public void tic() { double firstItem = buffer.dequeue(); double secondItem = buffer.peek(); double newItem = (firstItem + secondItem) * 0.5 * DECAY; buffer.enqueue(newItem); } GuitarString(double frequency); void pluck(); void tic(); double sample(); }### Answer: @Test public void testTic() { GuitarString s = new GuitarString(11025); s.pluck(); double s1 = s.sample(); s.tic(); double s2 = s.sample(); s.tic(); double s3 = s.sample(); s.tic(); double s4 = s.sample(); s.tic(); double s5 = s.sample(); double expected = 0.996 * 0.5 * (s1 + s2); assertEquals(expected, s5, 0.001); }
### Question: ArrayRingBuffer extends AbstractBoundedQueue<T> implements Iterable<T> { @Override public T peek() throws RuntimeException { if (isEmpty()) { throw new RuntimeException("Ring buffer underflow"); } else { return rb[first]; } } ArrayRingBuffer(int capacity); @Override Iterator<T> iterator(); @Override void enqueue(T x); @Override T dequeue(); @Override T peek(); }### Answer: @Test public void testPeek() { BoundedQueue<Integer> arb = new ArrayRingBuffer<>(10); for (int i = 0; i < arb.capacity(); i += 1) { arb.enqueue(i); } for (int i = 0; i < 5; i += 1) { arb.dequeue(); } assertEquals((int) arb.peek(), 5); }
### Question: ArrayRingBuffer extends AbstractBoundedQueue<T> implements Iterable<T> { @Override public void enqueue(T x) { if (isFull()) { throw new RuntimeException("Ring buffer overflow"); } else { rb[last] = x; last += 1; if (last >= this.capacity) { last = 0; } } fillCount += 1; } ArrayRingBuffer(int capacity); @Override Iterator<T> iterator(); @Override void enqueue(T x); @Override T dequeue(); @Override T peek(); }### Answer: @Test public void testIsFull() { ArrayRingBuffer<Integer> arb = new ArrayRingBuffer<>(10); for (int i = 0; i < arb.capacity(); i += 1) { arb.enqueue(i); } assertTrue(arb.isFull()); }
### Question: ArrayDeque { public PlaceholderType get(int index) { if (index >= this.Array.length) { return null; } else { return this.Array[index]; } } ArrayDeque(); void addFirst(PlaceholderType item); void addLast(PlaceholderType item); boolean isEmpty(); int size(); void printDeque(); PlaceholderType removeFirst(); PlaceholderType removeLast(); PlaceholderType get(int index); }### Answer: @Test public void getTest() { System.out.println("Perform getTest"); ArrayDeque<Integer> array = new ArrayDeque<>(); array.addFirst(123); array.addLast(234); array.addFirst(345); array.addLast(456); System.out.println(array.get(3)); }
### Question: ArrayRingBuffer extends AbstractBoundedQueue<T> implements Iterable<T> { @Override public Iterator<T> iterator() { return new BufferIterator(); } ArrayRingBuffer(int capacity); @Override Iterator<T> iterator(); @Override void enqueue(T x); @Override T dequeue(); @Override T peek(); }### Answer: @Test public void testIterator() { BoundedQueue<Integer> arb = new ArrayRingBuffer<>(10); for (int i = 0; i < arb.capacity(); i += 1) { arb.enqueue(i * 2); } for (int x : arb) { for (int y : arb) { System.out.println("x: " + x + "; y: " + y); } } }
### Question: Board implements WorldState { public int tileAt(int i, int j) throws IndexOutOfBoundsException { if ( !validate(i) || !validate(j) ) throw new IndexOutOfBoundsException("i: " + i + " or j: " + j + " is out of bounds! Please check!\n"); return board.get(i * N + j); } Board(int[][] tiles); int tileAt(int i, int j); int size(); @Override Iterable<WorldState> neighbors(); int hamming(); int manhattan(); int estimatedDistanceToGoal(); boolean equals(Object y); String toString(); }### Answer: @Test public void verifyImmutability() { int r = 2; int c = 2; int[][] x = new int[r][c]; int cnt = 0; for (int i = 0; i < r; i += 1) { for (int j = 0; j < c; j += 1) { x[i][j] = cnt; cnt += 1; } } Board b = new Board(x); assertEquals("Your Board class is not being initialized with the right values.", 0, b.tileAt(0, 0)); assertEquals("Your Board class is not being initialized with the right values.", 1, b.tileAt(0, 1)); assertEquals("Your Board class is not being initialized with the right values.", 2, b.tileAt(1, 0)); assertEquals("Your Board class is not being initialized with the right values.", 3, b.tileAt(1, 1)); x[1][1] = 1000; assertEquals("Your Board class is mutable and you should be making a copy of the values in the passed tiles array. Please see the FAQ!", 3, b.tileAt(1, 1)); }
### Question: SimpleOomage implements Oomage { @Override public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (this.getClass() != o.getClass()) return false; SimpleOomage y = (SimpleOomage) o; return (this.red == y.red && this.green == y.green && this.blue == y.blue); } SimpleOomage(int r, int g, int b); @Override boolean equals(Object o); @Override int hashCode(); @Override void draw(double x, double y, double scalingFactor); static SimpleOomage randomSimpleOomage(); static void main(String[] args); String toString(); }### Answer: @Test public void testEquals() { SimpleOomage ooA = new SimpleOomage(5, 10, 20); SimpleOomage ooA2 = new SimpleOomage(5, 10, 20); SimpleOomage ooB = new SimpleOomage(50, 50, 50); assertEquals(ooA, ooA2); assertNotEquals(ooA, ooB); assertNotEquals(ooA2, ooB); assertNotEquals(ooA, "ketchup"); }
### Question: Palindrome { public Deque<Character> wordToDeque(String word) { Deque<Character> worddeque = new LinkedListDeque<>(); for (int i = 0; i < word.length(); i++) { worddeque.addLast(word.charAt(i)); } return worddeque; } Deque<Character> wordToDeque(String word); boolean isPalindrome(String word); boolean isPalindrome(String word, CharacterComparator cc); }### Answer: @Test public void testWordToDeque() { Deque d = palindrome.wordToDeque("persiflage"); String actual = ""; for (int i = 0; i < "persiflage".length(); i++) { actual += d.removeFirst(); } assertEquals("persiflage", actual); }
### Question: ComplexOomage implements Oomage { public static ComplexOomage randomComplexOomage() { int N = StdRandom.uniform(1, 10); ArrayList<Integer> params = new ArrayList<>(N); for (int i = 0; i < N; i += 1) { params.add(StdRandom.uniform(0, 255)); } return new ComplexOomage(params); } ComplexOomage(List<Integer> params); @Override int hashCode(); @Override boolean equals(Object o); @Override void draw(double x, double y, double scalingFactor); static ComplexOomage randomComplexOomage(); static void main(String[] args); }### Answer: @Test public void testWithDeadlyParams() { List<Oomage> deadlyList = new ArrayList<>(); for (int i = 0; i < 167772; i++) { deadlyList.add(ComplexOomage.randomComplexOomage()); } assertTrue(OomageTestUtility.haveNiceHashCodeSpread(deadlyList, 256)); } @Test public void testRandomOomagesHashCodeSpread() { List<Oomage> oomages = new ArrayList<>(); int N = 10000; for (int i = 0; i < N; i += 1) { oomages.add(ComplexOomage.randomComplexOomage()); } assertTrue(OomageTestUtility.haveNiceHashCodeSpread(oomages, 10)); }
### Question: BinaryTrie implements Serializable { public Map<Character, BitSequence> buildLookupTable() { buildLookupTable(ref, bt, ""); return ref; } BinaryTrie(Map<Character, Integer> frequencyTable); Match longestPrefixMatch(BitSequence querySequence); Map<Character, BitSequence> buildLookupTable(); }### Answer: @Test public void testYourLookupTable() { System.out.println("Testing that your code outputs the right lookup table."); Map<Character, Integer> frequencyTable = new HashMap<Character, Integer>(); frequencyTable.put('a', 1); frequencyTable.put('b', 2); frequencyTable.put('c', 4); frequencyTable.put('d', 5); frequencyTable.put('e', 6); BinaryTrie trie = new BinaryTrie(frequencyTable); Map<Character, BitSequence> yourTable = trie.buildLookupTable(); HashMap<Character, BitSequence> expected = new HashMap<Character, BitSequence>(); expected.put('a', new BitSequence("000")); expected.put('b', new BitSequence("001")); expected.put('c', new BitSequence("01")); expected.put('d', new BitSequence("10")); expected.put('e', new BitSequence("11")); assertEquals(expected, yourTable); }
### Question: CurrentPlayerSwitch extends AbstractGameRules { public void switchCurrentPlayer(Game game) { if (game.isFinished()) { return; } int iterations = 0; Player player = game.getCurrentPlayer(); boolean isMoveFeasible; do { player = getNextPlayer(game, player.getId()); isMoveFeasible = moveFeasibilityChecker .isAnyMoveFeasible(game.getBoard().getCells(), player.getId()); if (!isMoveFeasible) { switchPlayerCells(game, player.getId()); } iterations++; if (iterations > game.getPlayers().size()) { throw new IllegalStateException(THERE_IS_DEAD_LOOP_ERR); } } while (!isMoveFeasible); game.setCurrentPlayer(player); } void switchCurrentPlayer(Game game); }### Answer: @Test(expected = IllegalStateException.class) public void exception_whenNobodyHasFeasibleMove() { currentPlayerSwitch.switchCurrentPlayer(game); } @Test public void notSwitchPlayer_whenGameFinished() { game.setFinished(true); currentPlayerSwitch.switchCurrentPlayer(game); assertThat(game.getCurrentPlayer().getId()).isEqualTo(FIRST_PLAYER_ID); }
### Question: GameEndingByMoving extends GameEnding { public void checkGameEndingByMoving(Game game) { BooleanContext isAllCellsOwned = new BooleanContext(); Map<Long, Integer> playersCellsCount = preparePlayersCellsCount(game); fillPlayersCellsCount(game, playersCellsCount, isAllCellsOwned); if (!isAllCellsOwned.isBool) { return; } Player winner = findMostConqueredCellsPlayer(playersCellsCount, game); finishGame(game, winner); } void checkGameEndingByMoving(Game game); }### Answer: @Test public void whenThereisEmptyCell() { game.getBoard().getCells()[0][1].setOwner(EMPTY_CELL_PLAYER_ID); gameEndingByMoving.checkGameEndingByMoving(game); assertFalse(game.isFinished()); assertThat(game.getWinner()).isNull(); } @Test public void whenSecondPlayerHasMoreCells() { gameEndingByMoving.checkGameEndingByMoving(game); assertTrue(game.isFinished()); assertThat(game.getWinner()).isEqualTo(secondPlayer); } @Test public void whenPlayersHasEqualsCellsCount() { game.getBoard().getCells()[0][1].setOwner(FIRST_PLAYER_ID); gameEndingByMoving.checkGameEndingByMoving(game); assertTrue(game.isFinished()); assertThat(game.getWinner()).isNull(); } @Test(expected = UnsupportedOperationException.class) public void when3Players() { game.getPlayers().add( createPlayer(99)); gameEndingByMoving.checkGameEndingByMoving(game); }
### Question: MoveFeasibilityChecker extends AbstractGameRules { public boolean isAnyMoveFeasible(Cell[][] cells, long playerId) { Collection<Integer> busyCellTypes = findBusyCellTypes(cells, playerId); for (int x = 0; x < cells.length; x++) { for (int y = 0; y < cells[x].length; y++) { Cell cell = cells[x][y]; List<Long> neighborCellsTypes = getNeighborCells(cells, x, y) .stream() .map(Cell::getOwner) .collect(Collectors.toList()); if (cell.getOwner() == 0 && !busyCellTypes.contains(cell.getType()) && neighborCellsTypes.contains(playerId)) { return true; } } } return false; } boolean isAnyMoveFeasible(Cell[][] cells, long playerId); }### Answer: @Test public void whenNoAnyFeasibleMove() { boolean actual = moveFeasibilityChecker.isAnyMoveFeasible(cells, FIRST_PLAYER_ID); assertFalse(actual); } @Test public void whenThereIsFeasibleMove() { List<Integer> otherPlayers = Arrays.asList(SECOND_PLAYER_ID, THIRD_PLAYER_ID); for (Integer otherPlayer : otherPlayers) { boolean actual = moveFeasibilityChecker.isAnyMoveFeasible(cells, otherPlayer); assertTrue(actual); } }
### Question: CapturableCellsFinder extends AbstractGameRules { public List<Cell> findCapturableCells(GameAction gameAction) { int x = gameAction.getX(); int y = gameAction.getY(); Cell[][] cells = gameAction.getGame().getBoard().getCells(); int initType = cells[x][y].getType(); List<Cell> capturedCells = new ArrayList<>(); deepTargetCell(capturedCells, cells, initType, x, y); deepOwnedCells(capturedCells, cells, initType, gameAction); return capturedCells; } List<Cell> findCapturableCells(GameAction gameAction); }### Answer: @Test public void testFindCapturedCells() { GameAction gameAction = new GameAction(); gameAction.setGame(generateGame()); gameAction.setX(TARGET_X); gameAction.setY(TARGET_Y); gameAction.setActionedPlayerId(PLAYER_ID); List<Cell> capturedCells = gameRules.findCapturableCells(gameAction); assertThat(capturedCells.size()).isEqualTo(7); assertThat(capturedCells).containsAll(markToCapturedCells); }
### Question: SkippedPlayerCellTypesFinder extends AbstractGameRules { public List<Integer> findPossibleCellTypes(Game game, long playerId) { validPlayersCount(game); List<Integer> possibleCellTypes = new ArrayList<>(GameOptions.ALL_CELL_TYPES); removePlayersCellTypes(game, possibleCellTypes); Set<Integer> opponentPossibleConquerTypes = getOpponentPossibleConquerTypes(game, playerId); if (opponentPossibleConquerTypes.size() == 1) { possibleCellTypes.removeAll(opponentPossibleConquerTypes); } return possibleCellTypes; } List<Integer> findPossibleCellTypes(Game game, long playerId); }### Answer: @Test public void whenOpponentHasOnlyOnePossibleMove() { List<Integer> possibleCellTypes = skippedPlayerCellTypesFinder .findPossibleCellTypes(game, FIRST_PLAYER_ID); assertThat(possibleCellTypes.size()).isEqualTo(GameOptions.CELL_TYPES_COUNT - 3); assertThat(possibleCellTypes).doesNotContain(1, 2, 5); } @Test public void whenOpponentHasTwoPossibleMoves() { freeAnotherElseCell(); List<Integer> possibleCellTypes = skippedPlayerCellTypesFinder .findPossibleCellTypes(game, FIRST_PLAYER_ID); assertThat(possibleCellTypes.size()).isEqualTo(GameOptions.CELL_TYPES_COUNT - 2); assertThat(possibleCellTypes).doesNotContain(1, 2); } @Test(expected = UnsupportedOperationException.class) public void whenThereAreMoreThenTwoPlayers() { game.getPlayers().add(new Player()); skippedPlayerCellTypesFinder.findPossibleCellTypes(game, FIRST_PLAYER_ID); }
### Question: FastDFSRepository { public String uploadFile(File file, String fileName, long fileLength) { try { String fileExtName = null; if (fileName.contains(".")) { fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1); } FastDFSClient client = fastDFSPool.getClient(); System.out.println(client); NameValuePair[] metaList = new NameValuePair[3]; metaList[0] = new NameValuePair("fileName", fileName); metaList[1] = new NameValuePair("fileExtName", fileExtName); metaList[2] = new NameValuePair("fileLength", String.valueOf(fileLength)); String path = client.upload_file1(FileUtils.getFileByte(file), fileExtName, metaList); client.close(); return path; } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } return null; } String uploadFile(File file, String fileName, long fileLength); byte[] downloadFile(String fileId); FileInfo getFileInfo(String fileId); Map<String, String> getFileMetadata(String fileId); int deleteFile(String fileId); }### Answer: @Test public void testUploadFile() { File file = new File("E: String path = fastDFSRepository.uploadFile(file, file.getName(), file.length()); System.out.println(path); }
### Question: FastDFSRepository { public FileInfo getFileInfo(String fileId) { try { FastDFSClient client = fastDFSPool.getClient(); FileInfo info = client.get_file_info1(fileId); client.close(); return info; } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } return null; } String uploadFile(File file, String fileName, long fileLength); byte[] downloadFile(String fileId); FileInfo getFileInfo(String fileId); Map<String, String> getFileMetadata(String fileId); int deleteFile(String fileId); }### Answer: @Test public void testGetFileInfo() { FileInfo fileInfo = fastDFSRepository.getFileInfo("group1/M00/00/00/wKgBLVrvch6ASeV5AAAAAAAAAAA014.txt"); System.out.println(fileInfo); }
### Question: FastDFSRepository { public Map<String, String> getFileMetadata(String fileId) { try { FastDFSClient client = fastDFSPool.getClient(); NameValuePair[] metaList = client.get_metadata1(fileId); if (metaList != null) { HashMap<String, String> map = new HashMap<String, String>(); for (NameValuePair metaItem : metaList) { map.put(metaItem.getName(), metaItem.getValue()); } client.close(); return map; } } catch (IOException | MyException e) { e.printStackTrace(); } return null; } String uploadFile(File file, String fileName, long fileLength); byte[] downloadFile(String fileId); FileInfo getFileInfo(String fileId); Map<String, String> getFileMetadata(String fileId); int deleteFile(String fileId); }### Answer: @Test public void getFileMetadata() { Map<String, String> fileMetadata = fastDFSRepository .getFileMetadata("group1/M00/00/00/wKgBLVrvch6ASeV5AAAAAAAAAAA014.txt"); for (String key : fileMetadata.keySet()) { System.out.println(key); System.out.println(fileMetadata.get(key)); System.out.println("------------------------------"); } }
### Question: FastDFSRepository { public int deleteFile(String fileId) { try { FastDFSClient client = fastDFSPool.getClient(); int result = client.delete_file1(fileId); client.close(); return result; } catch (IOException | MyException e) { e.printStackTrace(); } return 500; } String uploadFile(File file, String fileName, long fileLength); byte[] downloadFile(String fileId); FileInfo getFileInfo(String fileId); Map<String, String> getFileMetadata(String fileId); int deleteFile(String fileId); }### Answer: @Test public void deleteFile() { int status = fastDFSRepository.deleteFile("group1/M00/00/00/wKgBLVrvch6ASeV5AAAAAAAAAAA014.txt"); System.out.println(status); }
### Question: ParseAnalyticsController { public Task<Void> trackEventInBackground(final String name, Map<String, String> dimensions, String sessionToken) { ParseRESTCommand command = ParseRESTAnalyticsCommand.trackEventCommand(name, dimensions, sessionToken); Task<JSONObject> eventuallyTask = eventuallyQueue.enqueueEventuallyAsync(command, null); return eventuallyTask.makeVoid(); } ParseAnalyticsController(ParseEventuallyQueue eventuallyQueue); Task<Void> trackEventInBackground(final String name, Map<String, String> dimensions, String sessionToken); Task<Void> trackAppOpenedInBackground(String pushHash, String sessionToken); }### Answer: @Test public void testTrackEvent() throws Exception { ParseEventuallyQueue queue = mock(ParseEventuallyQueue.class); when(queue.enqueueEventuallyAsync(any(ParseRESTCommand.class), any(ParseObject.class))) .thenReturn(Task.forResult(new JSONObject())); ParseAnalyticsController controller = new ParseAnalyticsController(queue); Map<String, String> dimensions = new HashMap<>(); dimensions.put("event", "close"); ParseTaskUtils.wait(controller.trackEventInBackground("name", dimensions, "sessionToken")); ArgumentCaptor<ParseRESTCommand> command = ArgumentCaptor.forClass(ParseRESTCommand.class); ArgumentCaptor<ParseObject> object = ArgumentCaptor.forClass(ParseObject.class); verify(queue, times(1)).enqueueEventuallyAsync(command.capture(), object.capture()); assertNull(object.getValue()); assertTrue(command.getValue() instanceof ParseRESTAnalyticsCommand); assertTrue(command.getValue().httpPath.contains("name")); assertEquals("sessionToken", command.getValue().getSessionToken()); JSONObject jsonDimensions = command.getValue().jsonParameters.getJSONObject("dimensions"); assertEquals("close", jsonDimensions.get("event")); assertEquals(1, jsonDimensions.length()); }
### Question: OfflineQueryLogic { static <T extends ParseObject> boolean hasWriteAccess(ParseUser user, T object) { if (user == object) { return true; } ParseACL acl = object.getACL(); if (acl == null) { return true; } if (acl.getPublicWriteAccess()) { return true; } if (user != null && acl.getWriteAccess(user)) { return true; } return false; } OfflineQueryLogic(OfflineStore store); }### Answer: @Test public void testHasWriteAccessWithSameObject() { ParseUser user = mock(ParseUser.class); assertTrue(OfflineQueryLogic.hasWriteAccess(user, user)); verify(user, never()).getACL(); } @Test public void testHasWriteAccessWithNoACL() { ParseObject object = mock(ParseObject.class); when(object.getACL()).thenReturn(null); assertTrue(OfflineQueryLogic.hasWriteAccess(null, object)); } @Test public void testHasWriteAccessWithPublicWriteAccess() { ParseACL acl = mock(ParseACL.class); when(acl.getPublicWriteAccess()).thenReturn(true); ParseObject object = mock(ParseObject.class); when(object.getACL()).thenReturn(acl); assertTrue(OfflineQueryLogic.hasWriteAccess(null, object)); } @Test public void testHasWriteAccessWithWriteAccess() { ParseUser user = mock(ParseUser.class); ParseACL acl = mock(ParseACL.class); when(acl.getWriteAccess(user)).thenReturn(true); ParseObject object = mock(ParseObject.class); when(object.getACL()).thenReturn(acl); assertTrue(OfflineQueryLogic.hasWriteAccess(user, object)); } @Test public void testHasWriteAccessWithNoWriteAccess() { ParseACL acl = mock(ParseACL.class); when(acl.getPublicReadAccess()).thenReturn(false); ParseObject object = mock(ParseObject.class); when(object.getACL()).thenReturn(acl); assertFalse(OfflineQueryLogic.hasWriteAccess(null, object)); }
### Question: ParseCloud { static ParseCloudCodeController getCloudCodeController() { return ParseCorePlugins.getInstance().getCloudCodeController(); } private ParseCloud(); static Task<T> callFunctionInBackground(final String name, final Map<String, ?> params); static T callFunction(String name, Map<String, ?> params); static void callFunctionInBackground(String name, Map<String, ?> params, FunctionCallback<T> callback); }### Answer: @Test public void testGetCloudCodeController() { ParseCloudCodeController controller = mock(ParseCloudCodeController.class); ParseCorePlugins.getInstance().registerCloudCodeController(controller); assertSame(controller, ParseCloud.getCloudCodeController()); }
### Question: NetworkSessionController implements ParseSessionController { @Override public Task<ParseObject.State> getSessionAsync(String sessionToken) { ParseRESTSessionCommand command = ParseRESTSessionCommand.getCurrentSessionCommand(sessionToken); return command.executeAsync(client).onSuccess(new Continuation<JSONObject, ParseObject.State>() { @Override public ParseObject.State then(Task<JSONObject> task) throws Exception { JSONObject result = task.getResult(); return coder.decode(new ParseObject.State.Builder("_Session"), result, ParseDecoder.get()) .isComplete(true) .build(); } }); } NetworkSessionController(ParseHttpClient client); @Override Task<ParseObject.State> getSessionAsync(String sessionToken); @Override Task<Void> revokeAsync(String sessionToken); @Override Task<ParseObject.State> upgradeToRevocable(String sessionToken); }### Answer: @Test public void testGetSessionAsync() throws Exception { JSONObject mockResponse = generateBasicMockResponse(); mockResponse.put("installationId", "39c8e8a4-6dd0-4c39-ac85-7fd61425083b"); ParseHttpClient restClient = ParseTestUtils.mockParseHttpClientWithResponse(mockResponse, 200, "OK"); NetworkSessionController controller = new NetworkSessionController(restClient); ParseObject.State newState = ParseTaskUtils.wait(controller.getSessionAsync("sessionToken")); verifyBasicSessionState(mockResponse, newState); assertEquals("39c8e8a4-6dd0-4c39-ac85-7fd61425083b", newState.get("installationId")); assertTrue(newState.isComplete()); }
### Question: NetworkSessionController implements ParseSessionController { @Override public Task<ParseObject.State> upgradeToRevocable(String sessionToken) { ParseRESTSessionCommand command = ParseRESTSessionCommand.upgradeToRevocableSessionCommand(sessionToken); return command.executeAsync(client).onSuccess(new Continuation<JSONObject, ParseObject.State>() { @Override public ParseObject.State then(Task<JSONObject> task) throws Exception { JSONObject result = task.getResult(); return coder.decode(new ParseObject.State.Builder("_Session"), result, ParseDecoder.get()) .isComplete(true) .build(); } }); } NetworkSessionController(ParseHttpClient client); @Override Task<ParseObject.State> getSessionAsync(String sessionToken); @Override Task<Void> revokeAsync(String sessionToken); @Override Task<ParseObject.State> upgradeToRevocable(String sessionToken); }### Answer: @Test public void testUpgradeToRevocable() throws Exception { JSONObject mockResponse = generateBasicMockResponse(); ParseHttpClient restClient = ParseTestUtils.mockParseHttpClientWithResponse(mockResponse, 200, "OK"); NetworkSessionController controller = new NetworkSessionController(restClient); ParseObject.State newState = ParseTaskUtils.wait(controller.upgradeToRevocable("sessionToken")); verifyBasicSessionState(mockResponse, newState); assertTrue(newState.isComplete()); }
### Question: ParsePolygon implements Parcelable { public List<ParseGeoPoint> getCoordinates() { return coordinates; } ParsePolygon(List<ParseGeoPoint> coords); ParsePolygon(ParsePolygon polygon); protected ParsePolygon(Parcel source); ParsePolygon(Parcel source, ParseParcelDecoder decoder); void setCoordinates(List<ParseGeoPoint> coords); List<ParseGeoPoint> getCoordinates(); boolean containsPoint(ParseGeoPoint point); @Override boolean equals(Object obj); @Override String toString(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); final static Creator<ParsePolygon> CREATOR; }### Answer: @Test public void testConstructors() { List<ParseGeoPoint> arrayPoints = Arrays.asList( new ParseGeoPoint(0,0), new ParseGeoPoint(0,1), new ParseGeoPoint(1,1), new ParseGeoPoint(1,0) ); List<ParseGeoPoint> listPoints = new ArrayList<ParseGeoPoint>(); listPoints.add(new ParseGeoPoint(0,0)); listPoints.add(new ParseGeoPoint(0,1)); listPoints.add(new ParseGeoPoint(1,1)); listPoints.add(new ParseGeoPoint(1,0)); ParsePolygon polygonList = new ParsePolygon(listPoints); assertEquals(listPoints, polygonList.getCoordinates()); ParsePolygon polygonArray = new ParsePolygon(arrayPoints); assertEquals(arrayPoints, polygonArray.getCoordinates()); ParsePolygon copyList = new ParsePolygon(polygonList); assertEquals(polygonList.getCoordinates(), copyList.getCoordinates()); ParsePolygon copyArray = new ParsePolygon(polygonArray); assertEquals(polygonArray.getCoordinates(), copyArray.getCoordinates()); }
### Question: ParseRole extends ParseObject { public String getName() { return this.getString("name"); } ParseRole(); ParseRole(String name); ParseRole(String name, ParseACL acl); void setName(String name); String getName(); ParseRelation<ParseUser> getUsers(); ParseRelation<ParseRole> getRoles(); @Override void put(String key, Object value); static ParseQuery<ParseRole> getQuery(); }### Answer: @Test public void testConstructorWithName() { ParseRole role = new ParseRole("Test"); assertEquals("Test", role.getName()); } @Test public void testConstructorWithNameAndACL() { ParseACL acl = new ParseACL(); ParseRole role = new ParseRole("Test", acl); assertEquals("Test", role.getName()); assertSame(acl, role.getACL()); }
### Question: ParseRole extends ParseObject { public void setName(String name) { this.put("name", name); } ParseRole(); ParseRole(String name); ParseRole(String name, ParseACL acl); void setName(String name); String getName(); ParseRelation<ParseUser> getUsers(); ParseRelation<ParseRole> getRoles(); @Override void put(String key, Object value); static ParseQuery<ParseRole> getQuery(); }### Answer: @Test public void testSetName() { ParseRole role = new ParseRole(); role.setName("Test"); assertEquals("Test", role.getName()); }
### Question: ParseRole extends ParseObject { public ParseRelation<ParseUser> getUsers() { return getRelation("users"); } ParseRole(); ParseRole(String name); ParseRole(String name, ParseACL acl); void setName(String name); String getName(); ParseRelation<ParseUser> getUsers(); ParseRelation<ParseRole> getRoles(); @Override void put(String key, Object value); static ParseQuery<ParseRole> getQuery(); }### Answer: @Test public void testGetUsers() { ParseRole role = new ParseRole("Test"); assertThat(role.getUsers(), instanceOf(ParseRelation.class)); assertSame(role.getUsers(), role.getRelation("users")); }
### Question: ParseRole extends ParseObject { public ParseRelation<ParseRole> getRoles() { return getRelation("roles"); } ParseRole(); ParseRole(String name); ParseRole(String name, ParseACL acl); void setName(String name); String getName(); ParseRelation<ParseUser> getUsers(); ParseRelation<ParseRole> getRoles(); @Override void put(String key, Object value); static ParseQuery<ParseRole> getQuery(); }### Answer: @Test public void testGetRoles() { ParseRole role = new ParseRole("Test"); assertThat(role.getRoles(), instanceOf(ParseRelation.class)); assertSame(role.getRoles(), role.getRelation("roles")); }
### Question: ParseRole extends ParseObject { @Override void validateSave() { synchronized (mutex) { if (this.getObjectId() == null && getName() == null) { throw new IllegalStateException("New roles must specify a name."); } super.validateSave(); } } ParseRole(); ParseRole(String name); ParseRole(String name, ParseACL acl); void setName(String name); String getName(); ParseRelation<ParseUser> getUsers(); ParseRelation<ParseRole> getRoles(); @Override void put(String key, Object value); static ParseQuery<ParseRole> getQuery(); }### Answer: @Test public void testValidateSaveSuccess() { ParseRole role = new ParseRole("Test"); role.validateSave(); } @Test public void testValidateSaveSuccessWithNoName() { ParseRole role = new ParseRole("Test"); role.setObjectId("test"); role.validateSave(); } @Test(expected = IllegalStateException.class) public void testValidateSaveFailureWithNoObjectIdAndName() { ParseRole role = new ParseRole(); role.validateSave(); }
### Question: ParseRole extends ParseObject { @Override public void put(String key, Object value) { if ("name".equals(key)) { if (this.getObjectId() != null) { throw new IllegalArgumentException( "A role's name can only be set before it has been saved."); } if (!(value instanceof String)) { throw new IllegalArgumentException("A role's name must be a String."); } if (!NAME_PATTERN.matcher((String) value).matches()) { throw new IllegalArgumentException( "A role's name can only contain alphanumeric characters, _, -, and spaces."); } } super.put(key, value); } ParseRole(); ParseRole(String name); ParseRole(String name, ParseACL acl); void setName(String name); String getName(); ParseRelation<ParseUser> getUsers(); ParseRelation<ParseRole> getRoles(); @Override void put(String key, Object value); static ParseQuery<ParseRole> getQuery(); }### Answer: @Test public void testPutSuccess() { ParseRole role = new ParseRole("Test"); role.put("key", "value"); assertEquals("value", role.get("key")); } @Test(expected = IllegalArgumentException.class) public void testPutFailureWithNameAndObjectIdSet() { ParseRole role = new ParseRole("Test"); role.setObjectId("objectId"); role.put("name", "value"); } @Test(expected = IllegalArgumentException.class) public void testPutFailureWithInvalidNameTypeSet() { ParseRole role = new ParseRole("Test"); role.put("name", 1); } @Test(expected = IllegalArgumentException.class) public void testPutFailureWithInvalidNameValueSet() { ParseRole role = new ParseRole("Test"); role.put("name", "!!!!"); }