method2testcases
stringlengths
118
3.08k
### Question: SOHWriteResponseBodyConsumer implements ResponseBodyConsumer { @Override public Map<String, String> consume(final int statusCode, final InputStream response) throws IOException { if (statusCode != 201) { return ImmutableMap.of(); } checkNotNull(response); final BufferedReader reader = new BufferedReader(new InputStreamReader(response, Charsets.UTF_8)); final String objectName = reader.readLine(); while ((reader.readLine()) != null) { } return ImmutableMap.of(Context.X_OG_OBJECT_NAME, objectName); } @Override Map<String, String> consume(final int statusCode, final InputStream response); @Override String toString(); }### Answer: @Test(expected = NullPointerException.class) public void nullInputStream() throws IOException { new SOHWriteResponseBodyConsumer().consume(201, null); } @Test public void invalidStatusCode() throws IOException { final SOHWriteResponseBodyConsumer consumer = new SOHWriteResponseBodyConsumer(); final InputStream in = mock(InputStream.class); final Map<String, String> m = consumer.consume(500, in); assertThat(m.size(), is(0)); } @Test public void consume() throws IOException { final SOHWriteResponseBodyConsumer consumer = new SOHWriteResponseBodyConsumer(); final StringBuilder s = new StringBuilder(); for (int i = 0; i < 10000; i++) { s.append("objectName").append(i).append("\n"); } final InputStream in = new ByteArrayInputStream(s.toString().getBytes(Charsets.UTF_8)); final Map<String, String> m = consumer.consume(201, in); assertThat(m.size(), is(1)); final Entry<String, String> e = m.entrySet().iterator().next(); assertThat(e.getKey(), Matchers.is(Context.X_OG_OBJECT_NAME)); assertThat(e.getValue(), is("objectName0")); assertThat(in.available(), is(0)); }
### Question: ObjectFile { public static InputStream getInputStream(final File input) throws FileNotFoundException { InputStream in = System.in; if (input != null) { in = new FileInputStream(input); } return new BufferedInputStream(in); } private ObjectFile(); static void main(final String[] args); static InputStream getInputStream(final File input); static OutputStream getOutputStream(final boolean split, final int splitSize, final String output); static OutputStream getOutputStream(final String output); static void write(final InputStream in, final OutputStream out, boolean writeVersionHeader); static void read(final InputStream in, final OutputStream out, boolean writeVersionHeader); static void filter(final InputStream in, final OutputStream out, final long minFilesize, final long maxFilesize, final int minContainerSuffix, final int maxContainerSuffix, final Set<Integer> containerSuffixes, final int minLegalholds, final int maxLegalHolds, final long minRetention, final long maxRetention, boolean writeVersionHeader); static void split(final InputStream in, final OutputStream out); static void upgrade(final InputStream in, final OutputStream out); static boolean readFully(final InputStream in, final byte[] b); static void compactObjectFiles(final HashMap<File, Integer> objectFiles, final int maxcount); static void combineFiles(File f1, File f2); static void randomShuffleObjects(final InputStream in, final OutputStream out); static void shuffle(String prefix, String directory, int maxObjects); }### Answer: @Test public void getInputStreamNullInput() throws FileNotFoundException { final InputStream in = ObjectFile.getInputStream(null); assertThat(in, is(notNullValue())); } @Test(expected = FileNotFoundException.class) public void getInputStreamMissingInput() throws FileNotFoundException { ObjectFile.getInputStream(this.nonExistent); } @Test public void getInputStream() throws FileNotFoundException { final InputStream in = ObjectFile.getInputStream(this.exists); assertThat(in, is(not(System.in))); }
### Question: ObjectFile { public static OutputStream getOutputStream(final boolean split, final int splitSize, final String output) throws FileNotFoundException, IOException { if (split) { int maxObjects; if (splitSize > 0) maxObjects = splitSize/ RandomObjectPopulator.OBJECT_SIZE; else maxObjects = RandomObjectPopulator.MAX_OBJECT_ARG; return new ObjectFileOutputStream(output, maxObjects, RandomObjectPopulator.SUFFIX); } else { return new BufferedOutputStream(getOutputStream(output)); } } private ObjectFile(); static void main(final String[] args); static InputStream getInputStream(final File input); static OutputStream getOutputStream(final boolean split, final int splitSize, final String output); static OutputStream getOutputStream(final String output); static void write(final InputStream in, final OutputStream out, boolean writeVersionHeader); static void read(final InputStream in, final OutputStream out, boolean writeVersionHeader); static void filter(final InputStream in, final OutputStream out, final long minFilesize, final long maxFilesize, final int minContainerSuffix, final int maxContainerSuffix, final Set<Integer> containerSuffixes, final int minLegalholds, final int maxLegalHolds, final long minRetention, final long maxRetention, boolean writeVersionHeader); static void split(final InputStream in, final OutputStream out); static void upgrade(final InputStream in, final OutputStream out); static boolean readFully(final InputStream in, final byte[] b); static void compactObjectFiles(final HashMap<File, Integer> objectFiles, final int maxcount); static void combineFiles(File f1, File f2); static void randomShuffleObjects(final InputStream in, final OutputStream out); static void shuffle(String prefix, String directory, int maxObjects); }### Answer: @Test public void getOutputStreamNullOutput() throws FileNotFoundException { final OutputStream out = ObjectFile.getOutputStream(null); assertThat(out, is((OutputStream) System.out)); } @Test public void getOutputStream() throws FileNotFoundException { final OutputStream out = ObjectFile.getOutputStream(this.exists.toString()); assertThat(out, is(not((OutputStream) System.out))); }
### Question: Streams { public static InputStream throttle(final InputStream in, final long bytesPerSecond) { return new ThrottledInputStream(in, bytesPerSecond); } private Streams(); static InputStream create(final Body body); static InputStream throttle(final InputStream in, final long bytesPerSecond); static OutputStream throttle(final OutputStream out, final long bytesPerSecond); static final int REPEAT_LENGTH; }### Answer: @Test public void throttleInputStream() { Streams.throttle(mock(InputStream.class), 1); } @Test public void throttleOutputStream() { Streams.throttle(mock(OutputStream.class), 1); }
### Question: OGLog4jShutdownCallbackRegistry extends DefaultShutdownCallbackRegistry { public static void setOGShutdownHook(final Runnable ogShutdownHook) { setLogger(); _logger.debug("Setting ogShutdownHook to [{}]", ogShutdownHook); OG_SHUTDOWN_HOOK = checkNotNull(ogShutdownHook); } OGLog4jShutdownCallbackRegistry(); @Override void run(); static void waitForGzCompressActionCompletion(); static void setOGShutdownHook(final Runnable ogShutdownHook); }### Answer: @Test(expected = NullPointerException.class) public void nullSetOGShutdownHook() { OGLog4jShutdownCallbackRegistry.setOGShutdownHook(null); } @Test public void setOGShutdownHook() { OGLog4jShutdownCallbackRegistry.setOGShutdownHook(new Runnable() { @Override public void run() {} }); }
### Question: Application { public static URI getResource(final String resourceName) { checkNotNull(resourceName); try { final URL url = ClassLoader.getSystemResource(resourceName); checkArgument(url != null, "Could not find configuration file on classpath [%s]", resourceName); return url.toURI(); } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } } private Application(); static Cli cli(final String name, final GetOpt getopt, final String[] args); static URI getResource(final String resourceName); static T fromJson(final File json, final Class<T> cls, final Gson gson); static void exit(final int exitCode); static final int TEST_SUCCESS; static final int TEST_ERROR; static final int TEST_CONFIG_ERROR; static final int TEST_SHUTDOWN_ERROR; static final String TEST_SUCCESS_MSG; }### Answer: @Test(expected = NullPointerException.class) public void getResourceNullResource() { Application.getResource(null); } @Test(expected = IllegalArgumentException.class) public void getResourceMissingResource() { Application.getResource("nonexistent.jsap"); } @Test public void getResource() { assertThat(Application.getResource(APPLICATION_JSAP), notNullValue()); }
### Question: Application { public static <T> T fromJson(final File json, final Class<T> cls, final Gson gson) throws FileNotFoundException { checkNotNull(json); checkNotNull(cls); checkNotNull(gson); final Reader reader = new InputStreamReader(new FileInputStream(json), Charsets.UTF_8); return gson.fromJson(reader, cls); } private Application(); static Cli cli(final String name, final GetOpt getopt, final String[] args); static URI getResource(final String resourceName); static T fromJson(final File json, final Class<T> cls, final Gson gson); static void exit(final int exitCode); static final int TEST_SUCCESS; static final int TEST_ERROR; static final int TEST_CONFIG_ERROR; static final int TEST_SHUTDOWN_ERROR; static final String TEST_SUCCESS_MSG; }### Answer: @Test @UseDataProvider("provideInvalidFromJson") public void invalidFromJson(final File json, final Class<?> cls, final Gson gson, final Class<Exception> expectedException) throws FileNotFoundException { this.thrown.expect(expectedException); Application.fromJson(json, cls, gson); } @Test public void fromJson() throws FileNotFoundException { final File json = new File(Application.getResource(APPLICATION_JSON)); final Item item = Application.fromJson(json, Item.class, this.gson); assertThat(item.key, is(VALUE)); }
### Question: InfiniteInputStream extends InputStream { @Override public int read() { return this.buf[updateCursor(1)]; } InfiniteInputStream(final byte[] buf); @Override int read(); @Override int read(final byte[] b); @Override int read(final byte[] b, final int off, final int len); @Override int available(); @Override void mark(final int readlimit); @Override void reset(); @Override boolean markSupported(); @Override String toString(); }### Answer: @Test(expected = NullPointerException.class) public void readNullBuffer() { this.in.read(null); } @Test @UseDataProvider("provideInvalidRead") public void invalidRead(final byte[] buf, final int off, final int len, final Class<Exception> expectedException) { this.thrown.expect(expectedException); this.in.read(buf, off, len); } @Test @UseDataProvider("provideRead") public void read(final byte[] readBuffer) { assertThat(this.in.read(readBuffer), is(readBuffer.length)); for (int i = 0; i < readBuffer.length; i++) { assertThat(readBuffer[i], is(this.buf[i % this.buf.length])); assertThat(this.in.available(), is(Integer.MAX_VALUE)); } } @Test public void readZeroLength() { assertThat(this.in.read(new byte[1], 0, 0), is(0)); } @Test public void readPositiveLength() { assertThat(this.in.read(new byte[1], 0, 1), is(1)); }
### Question: SizeUnitTypeAdapter extends TypeAdapter<SizeUnit> { @Override public SizeUnit read(final JsonReader in) throws IOException { return Units.size(in.nextString()); } @Override void write(final JsonWriter out, final SizeUnit value); @Override SizeUnit read(final JsonReader in); }### Answer: @Test public void read() throws IOException { final JsonReader reader = mock(JsonReader.class); when(reader.nextString()).thenReturn("b"); assertThat(this.typeAdapter.read(reader), is(SizeUnit.BYTES)); }
### Question: Statistics { public long get(final Operation operation, final Counter counter) { checkNotNull(operation); checkNotNull(counter); return this.counters.get(operation).get(counter); } @Inject Statistics(); @Subscribe void update(final TestState state); @Subscribe void update(final Request request); @Subscribe void update(final Pair<Request, Response> result); void setOperation(final Operation operation); long get(final Operation operation, final Counter counter); long getStatusCode(final Operation operation, final int statusCode); Map<Integer, Long> statusCodes(final Operation operation); @Override String toString(); }### Answer: @Test(expected = NullPointerException.class) public void getNullOperation() { this.stats.get(null, Counter.OPERATIONS); } @Test(expected = NullPointerException.class) public void getNullCounter() { this.stats.get(Operation.WRITE, null); }
### Question: Statistics { public long getStatusCode(final Operation operation, final int statusCode) { checkNotNull(operation); checkArgument(HttpUtil.VALID_STATUS_CODES.contains(statusCode), "statusCode must be a valid status code [%s]", statusCode); return this.scCounters.get(operation).get(statusCode); } @Inject Statistics(); @Subscribe void update(final TestState state); @Subscribe void update(final Request request); @Subscribe void update(final Pair<Request, Response> result); void setOperation(final Operation operation); long get(final Operation operation, final Counter counter); long getStatusCode(final Operation operation, final int statusCode); Map<Integer, Long> statusCodes(final Operation operation); @Override String toString(); }### Answer: @Test @UseDataProvider("provideInvalidStatusCode") public void invalidStatusCode(final Operation operation, final int statusCode, final Class<Exception> expectedException) { this.thrown.expect(expectedException); this.stats.getStatusCode(operation, statusCode); }
### Question: InfiniteInputStream extends InputStream { @Override public void reset() { this.cursor = this.markLocation; } InfiniteInputStream(final byte[] buf); @Override int read(); @Override int read(final byte[] b); @Override int read(final byte[] b, final int off, final int len); @Override int available(); @Override void mark(final int readlimit); @Override void reset(); @Override boolean markSupported(); @Override String toString(); }### Answer: @Test public void reset() { this.in.read(); this.in.mark(Integer.MAX_VALUE); final int r1 = this.in.read(); this.in.reset(); assertThat(this.in.read(), is(r1)); }
### Question: Units { public static TimeUnit time(final String time) { checkNotNull(time); final TimeUnit unit = TIME_UNITS.get(time.toUpperCase()); checkArgument(unit != null, "Could not parse time [%s]", time); return unit; } private Units(); static TimeUnit time(final String time); static SizeUnit size(final String size); }### Answer: @Test @UseDataProvider("provideInvalidTime") public void invalidTime(final String invalidTime, final Class<Exception> expectedException) { this.thrown.expect(expectedException); Units.time(invalidTime); } @Test @UseDataProvider("provideTime") public void time(final List<String> units, final TimeUnit unit) { for (final String u : units) { assertThat(Units.time(u), is(unit)); } } @Test public void caseInsensitiveTime() { assertThat(Units.time("seconds"), is(Units.time("sECONds"))); }
### Question: Units { public static SizeUnit size(final String size) { checkNotNull(size); final SizeUnit unit = SIZE_UNITS.get(size.toUpperCase()); checkArgument(unit != null, "Could not parse size [%s]", size); return unit; } private Units(); static TimeUnit time(final String time); static SizeUnit size(final String size); }### Answer: @Test @UseDataProvider("provideInvalidSize") public void invalidSize(final String invalidSize, final Class<Exception> expectedException) { this.thrown.expect(expectedException); Units.size(invalidSize); } @Test @UseDataProvider("provideSize") public void size(final List<String> units, final SizeUnit unit) { for (final String u : units) { assertThat(Units.size(u), is(unit)); } } @Test public void caseInsensitiveSize() { assertThat(Units.size("bytes"), is(Units.size("bYTEs"))); }
### Question: TimeUnitTypeAdapter extends TypeAdapter<TimeUnit> { @Override public void write(final JsonWriter out, final TimeUnit value) throws IOException { out.value(value.toString().toLowerCase(Locale.US)); } @Override void write(final JsonWriter out, final TimeUnit value); @Override TimeUnit read(final JsonReader in); }### Answer: @Test public void write() throws IOException { final JsonWriter writer = mock(JsonWriter.class); this.typeAdapter.write(writer, TimeUnit.SECONDS); verify(writer).value("seconds"); }
### Question: Pair { public static <K, V> Pair<K, V> of(final K key, final V value) { return new Pair<K, V>(key, value); } private Pair(final K key, final V value); static Pair<K, V> of(final K key, final V value); K getKey(); V getValue(); @Override String toString(); }### Answer: @Test(expected = NullPointerException.class) public void nullKey() { Pair.of(null, "value"); } @Test(expected = NullPointerException.class) public void nullValue() { Pair.of("key", null); }
### Question: Pair { private Pair(final K key, final V value) { this.key = checkNotNull(key); this.value = checkNotNull(value); } private Pair(final K key, final V value); static Pair<K, V> of(final K key, final V value); K getKey(); V getValue(); @Override String toString(); }### Answer: @Test public void pair() { final Pair<String, String> p = Pair.of("key", "value"); assertThat(p.getKey(), is("key")); assertThat(p.getValue(), is("value")); }
### Question: Distributions { public static Distribution uniform(final double average, final double spread) { checkArgument(average >= 0.0, "average must be >= 0.0 [%s]", average); checkArgument(spread >= 0.0, "spread must be >= 0.0 [%s]", spread); if (DoubleMath.fuzzyEquals(spread, 0.0, Distributions.ERR)) { return constant(average); } final double lower = average - spread; final double upper = average + spread; checkArgument(lower >= 0.0, "average - spread must be >= 0.0 [%s]", lower); final String s = String.format("UniformDistribution [average=%s, spread=%s]", average, spread); return new RealDistributionAdapter(new UniformRealDistribution(lower, upper), s); } private Distributions(); static Distribution uniform(final double average, final double spread); static Distribution normal(final double average, final double spread); static Distribution lognormal(final double average, final double spread); static Distribution poisson(final double average); }### Answer: @Test @UseDataProvider("provideInvalidReal") public void invalidUniform(final double average, final double spread) { this.thrown.expect(IllegalArgumentException.class); Distributions.uniform(average, spread); } @Test public void uniform() { validate(Distributions.uniform(10, 1)); }
### Question: Distributions { public static Distribution normal(final double average, final double spread) { checkArgument(average >= 0.0, "average must be >= 0.0 [%s]", average); checkArgument(spread >= 0.0, "spread must be >= 0.0 [%s]", spread); if (DoubleMath.fuzzyEquals(spread, 0.0, Distributions.ERR)) { return constant(average); } final double min = average - (3 * spread); checkArgument(min >= 0.0, "three standard deviations must be >= 0.0 [%s]", min); final String s = String.format("NormalDistribution [average=%s, spread=%s]", average, spread); return new RealDistributionAdapter(new NormalDistribution(average, spread), s); } private Distributions(); static Distribution uniform(final double average, final double spread); static Distribution normal(final double average, final double spread); static Distribution lognormal(final double average, final double spread); static Distribution poisson(final double average); }### Answer: @Test @UseDataProvider("provideInvalidReal") public void invalidNormal(final double average, final double spread) { this.thrown.expect(IllegalArgumentException.class); Distributions.normal(average, spread); } @Test public void normal() { validate(Distributions.normal(10, 1)); }
### Question: Distributions { public static Distribution lognormal(final double average, final double spread) { checkArgument(average >= 0.0, "average must be >= 0.0 [%s]", average); checkArgument(spread >= 0.0, "spread must be >= 0.0 [%s]", spread); if (DoubleMath.fuzzyEquals(spread, 0.0, Distributions.ERR)) { return constant(average); } final double min = average - (3 * spread); checkArgument(min >= 0.0, "three standard deviations must be >= 0.0 [%s]", min); final String s = String.format("LogNormalDistribution [average=%s, spread=%s]", average, spread); return new RealDistributionAdapter(new LogNormalDistribution(average, spread), s); } private Distributions(); static Distribution uniform(final double average, final double spread); static Distribution normal(final double average, final double spread); static Distribution lognormal(final double average, final double spread); static Distribution poisson(final double average); }### Answer: @Test @UseDataProvider("provideInvalidReal") public void invalidLogNormal(final double average, final double spread) { this.thrown.expect(IllegalArgumentException.class); Distributions.lognormal(average, spread); } @Test public void lognormal() { validate(Distributions.lognormal(10, 1)); }
### Question: Distributions { public static Distribution poisson(final double average) { checkArgument(average >= 0.0, "average must be >= 0.0 [%s]", average); final String s = String.format("PoissonDistribution [average=%s]", average); return new IntegerDistributionAdapter(new PoissonDistribution(average), s); } private Distributions(); static Distribution uniform(final double average, final double spread); static Distribution normal(final double average, final double spread); static Distribution lognormal(final double average, final double spread); static Distribution poisson(final double average); }### Answer: @Test(expected = IllegalArgumentException.class) public void invalidPoisson() { Distributions.poisson(-1); } @Test public void poisson() { validate(Distributions.poisson(10)); }
### Question: TimeUnitTypeAdapter extends TypeAdapter<TimeUnit> { @Override public TimeUnit read(final JsonReader in) throws IOException { return Units.time(in.nextString()); } @Override void write(final JsonWriter out, final TimeUnit value); @Override TimeUnit read(final JsonReader in); }### Answer: @Test public void read() throws IOException { final JsonReader reader = mock(JsonReader.class); when(reader.nextString()).thenReturn("s"); assertThat(this.typeAdapter.read(reader), is(TimeUnit.SECONDS)); }
### Question: MD5DigestLoader extends CacheLoader<Long, byte[]> { @Override public byte[] load(final Long key) throws Exception { checkNotNull(key); _logger.debug("Loading md5 digest for size [{}]", key); final HashingInputStream hashStream = new HashingInputStream(Hashing.md5(), Streams.create(Bodies.zeroes(key))); final byte[] buffer = new byte[4096]; while (hashStream.read(buffer) != -1) { } hashStream.close(); return hashStream.hash().asBytes(); } @Override byte[] load(final Long key); }### Answer: @Test public void checkMD5() throws Exception { byte[] expected = {(byte)0xA6, 0x3C, (byte)0x90, (byte)0xCC, 0x36, (byte)0x84, (byte)0xAD, (byte)0x8B, 0x0A, 0x21, (byte)0x76, (byte)0xA6, (byte)0xA8, (byte)0xFE, (byte)0x90, (byte)0x05}; byte[] md5 = this.cache.load(10L); assertArrayEquals("MD5 mismatch", expected, md5); } @Test public void checkMD5_1000() throws Exception { byte[] expected = {(byte)0x6B, (byte)0xF9, (byte)0x5A, (byte)0x48, (byte)0xF3, (byte)0x66, (byte)0xBD, (byte)0xF8, (byte)0XAF, 0x3A, (byte)0x19, (byte)0x8C, (byte)0x7B, (byte)0x72, (byte)0x3C, (byte)0x77}; byte[] md5 = this.cache.load(5000L); assertArrayEquals("MD5 mismatch", expected, md5); }
### Question: AuthenticatedHttpRequest implements AuthenticatedRequest { public void addQueryParameter(final String key, final String value) { List<String> parameterValues = this.queryParameters.get(checkNotNull(key)); if (parameterValues == null) { parameterValues = Lists.newArrayList(); this.queryParameters.put(key, parameterValues); } parameterValues.add(value); } AuthenticatedHttpRequest(final Request request); @Override Method getMethod(); @Override URI getUri(); @Override Map<String, List<String>> getQueryParameters(); void addQueryParameter(final String key, final String value); @Override Map<String, String> headers(); void addHeader(final String key, final String value); @Override Body getBody(); @Override Map<String, String> getContext(); @Override InputStream getContent(); void setContent(final InputStream content); @Override long getContentLength(); void setContentLength(final long length); @Override String toString(); @Override Operation getOperation(); }### Answer: @Test(expected = NullPointerException.class) public void addQueryParameterNullKey() { final AuthenticatedHttpRequest authenticatedRequest = new AuthenticatedHttpRequest(this.request); authenticatedRequest.addQueryParameter(null, "value"); } @Test public void addQueryParameterNullValue() { final AuthenticatedHttpRequest authenticatedRequest = new AuthenticatedHttpRequest(this.request); authenticatedRequest.addQueryParameter("key", null); }
### Question: AuthenticatedHttpRequest implements AuthenticatedRequest { public void addHeader(final String key, final String value) { this.requestHeaders.put(checkNotNull(key), checkNotNull(value)); } AuthenticatedHttpRequest(final Request request); @Override Method getMethod(); @Override URI getUri(); @Override Map<String, List<String>> getQueryParameters(); void addQueryParameter(final String key, final String value); @Override Map<String, String> headers(); void addHeader(final String key, final String value); @Override Body getBody(); @Override Map<String, String> getContext(); @Override InputStream getContent(); void setContent(final InputStream content); @Override long getContentLength(); void setContentLength(final long length); @Override String toString(); @Override Operation getOperation(); }### Answer: @Test(expected = NullPointerException.class) public void addHeaderNullKey() { final AuthenticatedHttpRequest authenticatedRequest = new AuthenticatedHttpRequest(this.request); authenticatedRequest.addHeader(null, "value"); } @Test(expected = NullPointerException.class) public void addHeaderNullValue() { final AuthenticatedHttpRequest authenticatedRequest = new AuthenticatedHttpRequest(this.request); authenticatedRequest.addHeader("key", null); }
### Question: HttpRequest implements Request { @Override public Method getMethod() { return this.method; } private HttpRequest(final Builder builder); @Override Method getMethod(); @Override URI getUri(); @Override Map<String, List<String>> getQueryParameters(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override Operation getOperation(); @Override String toString(); }### Answer: @Test public void method() { final Method method = new HttpRequest.Builder(Method.HEAD, this.uri, this.operation).build().getMethod(); assertThat(method, is(Method.HEAD)); }
### Question: HttpRequest implements Request { @Override public URI getUri() { return this.uri; } private HttpRequest(final Builder builder); @Override Method getMethod(); @Override URI getUri(); @Override Map<String, List<String>> getQueryParameters(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override Operation getOperation(); @Override String toString(); }### Answer: @Test public void uri() { final URI uri = new HttpRequest.Builder(this.method, this.uri, this.operation).build().getUri(); assertThat(uri, is(this.uri)); }
### Question: CaseInsensitiveEnumTypeAdapterFactory implements TypeAdapterFactory { @Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { @SuppressWarnings("unchecked") final Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isEnum()) { return null; } return new TypeAdapter<T>() { @Override public void write(final JsonWriter out, final T value) throws IOException { out.value(value.toString().toLowerCase(Locale.US)); } @Override @SuppressWarnings("unchecked") public T read(final JsonReader in) throws IOException { final String s = in.nextString().toUpperCase(Locale.US); for (final Object enumEntry : rawType.getEnumConstants()) { if (enumEntry.toString().equals(s)) { return (T) enumEntry; } } throw new JsonSyntaxException(String.format("Could not parse into enum [%s]", s)); } }.nullSafe(); } @Override TypeAdapter<T> create(final Gson gson, final TypeToken<T> type); }### Answer: @Test public void nonEnumCreate() { assertThat(this.typeAdapterFactory.create(this.gson, TypeToken.get(String.class)), nullValue()); } @Test public void isEnum() throws IOException { final TypeAdapter<DistributionType> typeAdapter = this.typeAdapterFactory.create(this.gson, TypeToken.get(DistributionType.class)); assertThat(typeAdapter, notNullValue()); typeAdapter.write(this.writer, DistributionType.NORMAL); verify(this.writer).value("normal"); when(this.reader.nextString()).thenReturn("NormAL"); assertThat(typeAdapter.read(this.reader), is(DistributionType.NORMAL)); } @Test(expected = JsonSyntaxException.class) public void nonEnumRead() throws IOException { final TypeAdapter<DistributionType> typeAdapter = this.typeAdapterFactory.create(this.gson, TypeToken.get(DistributionType.class)); when(this.reader.nextString()).thenReturn("fakeDistribution"); typeAdapter.read(this.reader); }
### Question: HttpRequest implements Request { @Override public Operation getOperation() { return this.operation; } private HttpRequest(final Builder builder); @Override Method getMethod(); @Override URI getUri(); @Override Map<String, List<String>> getQueryParameters(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override Operation getOperation(); @Override String toString(); }### Answer: @Test public void operation() { final Operation operation = new HttpRequest.Builder(this.method, this.uri, this.operation).build().getOperation(); assertThat(operation, is(this.operation)); }
### Question: HttpRequest implements Request { @Override public Map<String, String> getContext() { return this.context; } private HttpRequest(final Builder builder); @Override Method getMethod(); @Override URI getUri(); @Override Map<String, List<String>> getQueryParameters(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override Operation getOperation(); @Override String toString(); }### Answer: @Test public void noContext() { final HttpRequest request = new HttpRequest.Builder(this.method, this.uri, Operation.WRITE).build(); assertThat(request.getContext().size(), is(0)); } @Test public void oneContext() { final HttpRequest request = new HttpRequest.Builder(this.method, this.uri, Operation.WRITE) .withContext("key", "value").build(); assertThat(request.getContext().size(), is(1)); assertThat(request.getContext(), hasEntry("key", "value")); } @Test public void multipleContext() { final HttpRequest request = new HttpRequest.Builder(this.method, this.uri, Operation.WRITE) .withContext("key1", "value1").withContext("key2", "value2").build(); assertThat(request.getContext().size(), is(2)); assertThat(request.getContext(), hasEntry("key1", "value1")); assertThat(request.getContext(), hasEntry("key2", "value2")); } @Test public void contextModification() { final HttpRequest.Builder b = new HttpRequest.Builder(this.method, this.uri, Operation.WRITE) .withContext("key1", "value1"); final HttpRequest request = b.build(); b.withContext("key2", "value2"); assertThat(request.getContext(), hasEntry("key1", "value1")); assertThat(request.getContext(), not(hasEntry("key2", "value2"))); } @Test(expected = UnsupportedOperationException.class) public void contextRemove() { new HttpRequest.Builder(this.method, this.uri, Operation.WRITE).withContext("key", "value") .build().getContext().remove("key"); }
### Question: HttpRequest implements Request { @Override public Map<String, String> headers() { return this.requestHeaders; } private HttpRequest(final Builder builder); @Override Method getMethod(); @Override URI getUri(); @Override Map<String, List<String>> getQueryParameters(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override Operation getOperation(); @Override String toString(); }### Answer: @Test public void noHeaders() { final HttpRequest request = new HttpRequest.Builder(this.method, this.uri, this.operation).build(); assertThat(request.headers().size(), is(0)); } @Test public void oneHeader() { final HttpRequest request = new HttpRequest.Builder(this.method, this.uri, this.operation) .withHeader("key", "value").build(); assertThat(request.headers().size(), is(1)); assertThat(request.headers(), hasEntry("key", "value")); } @Test public void multipleHeaders() { final HttpRequest.Builder b = new HttpRequest.Builder(this.method, this.uri, this.operation); for (int i = 0; i < 10; i++) { b.withHeader("key" + (10 - i), "value"); } final HttpRequest request = b.build(); assertThat(request.headers().size(), is(10)); for (int i = 0; i < 10; i++) { assertThat(request.headers(), hasEntry("key" + (10 - i), "value")); } } @Test public void headerModification() { final HttpRequest.Builder b = new HttpRequest.Builder(this.method, this.uri, this.operation).withHeader("key1", "value1"); final HttpRequest request = b.build(); b.withHeader("key2", "value2"); assertThat(request.headers(), hasEntry("key1", "value1")); assertThat(request.headers(), not(hasEntry("key2", "value2"))); } @Test(expected = UnsupportedOperationException.class) public void headerRemove() { new HttpRequest.Builder(this.method, this.uri, this.operation).withHeader("key", "value") .build().headers().remove("key"); }
### Question: HttpRequest implements Request { @Override public Body getBody() { return this.body; } private HttpRequest(final Builder builder); @Override Method getMethod(); @Override URI getUri(); @Override Map<String, List<String>> getQueryParameters(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override Operation getOperation(); @Override String toString(); }### Answer: @Test public void defaultBody() { final Body body = new HttpRequest.Builder(this.method, this.uri, this.operation).build().getBody(); assertThat(body.getDataType(), is(DataType.NONE)); assertThat(body.getSize(), is(0L)); } @Test public void body() { final Body body = new HttpRequest.Builder(this.method, this.uri, this.operation) .withBody(Bodies.zeroes(12345)).build().getBody(); assertThat(body.getDataType(), is(DataType.ZEROES)); assertThat(body.getSize(), is(12345L)); }
### Question: HttpResponse implements Response { @Override public int getStatusCode() { return this.statusCode; } private HttpResponse(final Builder builder); @Override int getStatusCode(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override RequestTimestamps getRequestTimestamps(); @Override String toString(); }### Answer: @Test public void statusCode() { final HttpResponse response = new HttpResponse.Builder().withStatusCode(404).build(); assertThat(response.getStatusCode(), is(404)); }
### Question: HttpResponse implements Response { @Override public Map<String, String> headers() { return this.responseHeaders; } private HttpResponse(final Builder builder); @Override int getStatusCode(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override RequestTimestamps getRequestTimestamps(); @Override String toString(); }### Answer: @Test public void noHeaders() { final HttpResponse response = new HttpResponse.Builder().withStatusCode(this.statusCode).build(); assertThat(response.headers().size(), is(0)); } @Test public void oneHeader() { final HttpResponse response = new HttpResponse.Builder().withStatusCode(this.statusCode) .withHeader("key", "value").build(); assertThat(response.headers().size(), is(1)); assertThat(response.headers(), hasEntry("key", "value")); } @Test public void multipleHeaders() { final HttpResponse.Builder b = new HttpResponse.Builder().withStatusCode(this.statusCode); for (int i = 0; i < 10; i++) { b.withHeader("key" + (10 - i), "value"); } final HttpResponse response = b.build(); assertThat(response.headers().size(), is(10)); for (int i = 0; i < 10; i++) { assertThat(response.headers(), hasEntry("key" + (10 - i), "value")); } } @Test public void headerModification() { final HttpResponse.Builder b = new HttpResponse.Builder().withStatusCode(this.statusCode).withHeader("key1", "value1"); final HttpResponse response = b.build(); b.withHeader("key2", "value2"); assertThat(response.headers(), hasEntry("key1", "value1")); assertThat(response.headers(), not(hasEntry("key2", "value2"))); } @Test(expected = UnsupportedOperationException.class) public void testHeaderIteratorRemove() { new HttpResponse.Builder().withStatusCode(this.statusCode).withHeader("key", "value").build() .headers().remove("key"); }
### Question: HttpResponse implements Response { @Override public Body getBody() { return this.body; } private HttpResponse(final Builder builder); @Override int getStatusCode(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override RequestTimestamps getRequestTimestamps(); @Override String toString(); }### Answer: @Test public void defaultBody() { final Body body = new HttpResponse.Builder().withStatusCode(this.statusCode).build().getBody(); assertThat(body.getDataType(), is(DataType.NONE)); assertThat(body.getSize(), is(0L)); } @Test public void body() { final Body body = new HttpResponse.Builder().withStatusCode(this.statusCode) .withBody(Bodies.zeroes(12345)).build().getBody(); assertThat(body.getDataType(), is(DataType.ZEROES)); assertThat(body.getSize(), is(12345L)); }
### Question: HttpResponse implements Response { @Override public Map<String, String> getContext() { return this.context; } private HttpResponse(final Builder builder); @Override int getStatusCode(); @Override Map<String, String> headers(); @Override Body getBody(); @Override Map<String, String> getContext(); @Override RequestTimestamps getRequestTimestamps(); @Override String toString(); }### Answer: @Test public void noContext() { final HttpResponse response = new HttpResponse.Builder().withStatusCode(200).build(); assertThat(response.getContext().size(), is(0)); } @Test public void oneContext() { final HttpResponse response = new HttpResponse.Builder().withStatusCode(200).withContext("key", "value").build(); assertThat(response.getContext().size(), is(1)); assertThat(response.getContext(), hasEntry("key", "value")); } @Test public void multipleContext() { final HttpResponse response = new HttpResponse.Builder().withStatusCode(200) .withContext("key1", "value1").withContext("key2", "value2").build(); assertThat(response.getContext().size(), is(2)); assertThat(response.getContext(), hasEntry("key1", "value1")); assertThat(response.getContext(), hasEntry("key2", "value2")); } @Test public void contextModification() { final HttpResponse.Builder b = new HttpResponse.Builder().withStatusCode(200).withContext("key1", "value1"); final HttpResponse response = b.build(); b.withContext("key2", "value2"); assertThat(response.getContext(), hasEntry("key1", "value1")); assertThat(response.getContext(), not(hasEntry("key2", "value2"))); } @Test(expected = UnsupportedOperationException.class) public void contextRemove() { new HttpResponse.Builder().withStatusCode(200).withContext("key", "value").build().getContext() .remove("key"); }
### Question: ThrottledOutputStream extends FilterOutputStream { private void throttle(final int bytes) { if (bytes == 1) { this.rateLimiter.acquire(); } else if (bytes > 1) { this.rateLimiter.acquire(bytes - 1); this.rateLimiter.acquire(); } } ThrottledOutputStream(final OutputStream out, final long bytesPerSecond); @Override void write(final int b); @Override void write(final byte[] b); @Override void write(final byte[] b, final int off, final int len); @Override String toString(); }### Answer: @Test @UseDataProvider("provideInvalidThrottleOutputStream") public void invalidOutputStream(final OutputStream out, final long bytesPerSecond, final Class<Exception> expectedException) { this.thrown.expect(expectedException); Streams.throttle(out, bytesPerSecond); }
### Question: BasicAuth implements HttpAuth { @Override public AuthenticatedRequest authenticate(final Request request) { final String username = checkNotNull(request.getContext().get(Context.X_OG_USERNAME)); final String password = checkNotNull(request.getContext().get(Context.X_OG_PASSWORD)); final String credentials = username + ":" + password; final AuthenticatedHttpRequest authenticatedRequest = new AuthenticatedHttpRequest(request); authenticatedRequest.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + BaseEncoding.base64().encode(credentials.getBytes(Charsets.UTF_8))); return authenticatedRequest; } BasicAuth(); @Override AuthenticatedRequest authenticate(final Request request); @Override String toString(); }### Answer: @Test(expected = NullPointerException.class) public void noUsername() { final Request badRequest = new HttpRequest.Builder(Method.PUT, this.uri, Operation.WRITE) .withContext(Context.X_OG_PASSWORD, this.password).build(); this.basicAuth.authenticate(badRequest); } @Test(expected = NullPointerException.class) public void noPassword() { final Request badRequest = new HttpRequest.Builder(Method.PUT, this.uri, Operation.WRITE) .withHeader(Context.X_OG_USERNAME, this.username).build(); this.basicAuth.authenticate(badRequest); }
### Question: Bodies { public static Body none() { return NONE_BODY; } private Bodies(); static Body none(); static Body random(final long size); static Body zeroes(final long size); static Body custom(final long size, String content); }### Answer: @Test public void none() { final Body body = Bodies.none(); assertThat(body.getDataType(), is(DataType.NONE)); assertThat(body.getSize(), is(0L)); }
### Question: Bodies { public static Body random(final long size) { return create(DataType.RANDOM, size); } private Bodies(); static Body none(); static Body random(final long size); static Body zeroes(final long size); static Body custom(final long size, String content); }### Answer: @Test(expected = IllegalArgumentException.class) public void randomNegativeSize() { Bodies.random(-1); } @Test public void random() { final Body body = Bodies.random(1); assertThat(body.getDataType(), is(DataType.RANDOM)); assertThat(body.getSize(), is(1L)); }
### Question: Bodies { public static Body zeroes(final long size) { return create(DataType.ZEROES, size); } private Bodies(); static Body none(); static Body random(final long size); static Body zeroes(final long size); static Body custom(final long size, String content); }### Answer: @Test(expected = IllegalArgumentException.class) public void zeroesNegativeSize() { Bodies.zeroes(-1); } @Test public void zeroes() { final Body body = Bodies.zeroes(1); assertThat(body.getDataType(), is(DataType.ZEROES)); assertThat(body.getSize(), is(1L)); }
### Question: ThrottledOutputStream extends FilterOutputStream { @Override public void write(final int b) throws IOException { super.write(b); throttle(1); } ThrottledOutputStream(final OutputStream out, final long bytesPerSecond); @Override void write(final int b); @Override void write(final byte[] b); @Override void write(final byte[] b, final int off, final int len); @Override String toString(); }### Answer: @Test public void writeOneByteAtATime() throws IOException { final OutputStream throttled = new ThrottledOutputStream(this.out, 1000); final long timestampStart = System.nanoTime(); for (int i = 0; i < 100; i++) { throttled.write(1); } final long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestampStart); final long delta = Math.abs(duration - 100); assertThat(delta, lessThan(10L)); } @Test public void write() throws IOException { final OutputStream throttled = new ThrottledOutputStream(this.out, 1000); final byte[] buf = new byte[100]; final long timestampStart = System.nanoTime(); throttled.write(buf); final long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestampStart); final long delta = Math.abs(duration - 100); assertThat(delta, lessThan(10L)); }
### Question: SourceReadObjectNameFunction implements Function<Map<String, String>, String> { @Override public String apply(final Map<String, String> context) { final ObjectMetadata objectMetadata = this.objectManager.get(); context.put(Context.X_OG_SSE_SOURCE_OBJECT_NAME, objectMetadata.getName()); context.put(Context.X_OG_SSE_SOURCE_OBJECT_SIZE, String.valueOf(objectMetadata.getSize())); context.put(Context.X_OG_SSE_SOURCE_OBJECT_CONTAINER_SUFFIX, String.valueOf(objectMetadata.getContainerSuffix())); context.put(Context.X_OG_OBJECT_SIZE, String.valueOf(objectMetadata.getSize())); return objectMetadata.getName(); } SourceReadObjectNameFunction(final ObjectManager objectManager); @Override String apply(final Map<String, String> context); @Override String toString(); }### Answer: @Test public void readObjectNameSupplier() { final String object = "objectName"; final ObjectMetadata objectName = mock(ObjectMetadata.class); when(objectName.getName()).thenReturn(object); when(objectName.getSize()).thenReturn(50000L); when(objectName.getContainerSuffix()).thenReturn(-1); when(this.objectManager.get()).thenReturn(objectName); final Map<String, String> context = Maps.newHashMap(); assertThat(new SourceReadObjectNameFunction(this.objectManager).apply(context), is(object)); assertThat(context.get(Context.X_OG_SSE_SOURCE_OBJECT_NAME), is(object)); assertThat(context.get(Context.X_OG_SSE_SOURCE_OBJECT_SIZE), is("50000")); assertThat(context.get(Context.X_OG_SSE_SOURCE_OBJECT_CONTAINER_SUFFIX), is("-1")); assertThat(context.get(Context.X_OG_OBJECT_SIZE), is("50000")); } @Test(expected = ObjectManagerException.class) public void supplierException() { when(this.objectManager.get()).thenThrow(new ObjectManagerException()); new ReadObjectNameFunction(this.objectManager).apply(Maps.<String, String>newHashMap()); }
### Question: ObjectRetentionExtensionFunction implements Function<Map<String, String>, String> { @Override public String apply(final Map<String, String> context) { final ObjectMetadata objectMetadata = this.objectManager.removeForUpdate(); context.put(Context.X_OG_OBJECT_NAME, objectMetadata.getName()); context.put(Context.X_OG_OBJECT_SIZE, String.valueOf(objectMetadata.getSize())); context.put(Context.X_OG_CONTAINER_SUFFIX, String.valueOf(objectMetadata.getContainerSuffix())); context.put(Context.X_OG_LEGAL_HOLD_SUFFIX, String.valueOf(objectMetadata.getNumberOfLegalHolds())); context.put(Context.X_OG_OBJECT_RETENTION, String.valueOf(objectMetadata.getRetention())); return objectMetadata.getName(); } ObjectRetentionExtensionFunction(final ObjectManager objectManager); @Override String apply(final Map<String, String> context); @Override String toString(); }### Answer: @Test(expected = ObjectManagerException.class) public void supplierException() { when(this.objectManager.removeForUpdate()).thenThrow(new ObjectManagerException()); new ObjectRetentionExtensionFunction(this.objectManager).apply(Maps.<String, String>newHashMap()); }
### Question: RandomSupplier implements Supplier<T> { @Override public T get() { final double totalWeight = getCurrentWeights(); final double rnd = this.random.nextDouble() * totalWeight; double previousWeights = 0.0; for (final Choice<T> choice : this.choices) { if (rnd < previousWeights + choice.currentWeight) { return choice.value; } previousWeights += choice.currentWeight; } throw new IllegalStateException("Incorrect weight calculation"); } private RandomSupplier(final Builder<T> builder); @Override T get(); @Override String toString(); }### Answer: @Test public void oneChoice() { final Supplier<Integer> s = new RandomSupplier.Builder<Integer>().withChoice(1).build(); for (int i = 0; i < 10; i++) { assertThat(s.get(), is(1)); } } @Test public void multipleChoices() { final Supplier<Integer> s = new RandomSupplier.Builder<Integer>().withChoice(1, 33).withChoice(2, Suppliers.of(33.5)) .withChoice(3, Suppliers.of(33)).withRandom(new Random()).build(); final Map<Integer, Integer> counts = Maps.newHashMap(); counts.put(1, 0); counts.put(2, 0); counts.put(3, 0); for (int i = 0; i < 100; i++) { final int value = s.get(); counts.put(value, counts.get(value) + 1); } for (final int count : counts.values()) { assertThat(count, greaterThan(0)); } }
### Question: UUIDObjectNameFunction implements Function<Map<String, String>, String> { @Override public String apply(final Map<String, String> context) { if (!this.octalNamingMode) { final String objectName = UUID.randomUUID().toString().replace("-", "") + "0000"; context.put(Context.X_OG_OBJECT_NAME, objectName); return objectName; } else { UUID uuid = UUID.randomUUID(); long msl = uuid.getMostSignificantBits(); long lsl = uuid.getLeastSignificantBits(); msl = msl & 0x7777777777777777L; lsl = lsl & 0x7777777777777777L; UUID uuid2 = new UUID(msl, lsl); final String objectName = uuid2.toString().replace("-", "") + "0000"; context.put(Context.X_OG_OBJECT_NAME, objectName); return objectName; } } UUIDObjectNameFunction(boolean octalNamingMode); @Override String apply(final Map<String, String> context); @Override String toString(); }### Answer: @Test public void uuidObjectNameSupplier() { final Function<Map<String, String>, String> s = new UUIDObjectNameFunction(false); final Map<String, String> context = Maps.newHashMap(); assertThat(s.apply(context), is(not(s.apply(context)))); }
### Question: RFXColorPicker extends RFXComponent { @Override public void focusLost(RFXComponent next) { String currentColor = getColorCode(((ColorPicker) node).getValue()); if (!currentColor.equals(prevColor)) { recorder.recordSelect(this, currentColor); } } RFXColorPicker(Node source, JSONOMapConfig omapConfig, Point2D point, IJSONRecorder recorder); @Override void focusGained(RFXComponent prev); @Override void focusLost(RFXComponent next); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void selectColor() { ColorPicker colorPicker = (ColorPicker) getPrimaryStage().getScene().getRoot().lookup(".color-picker"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(() -> { RFXColorPicker rfxColorPicker = new RFXColorPicker(colorPicker, null, null, lr); colorPicker.setValue(Color.rgb(234, 156, 44)); rfxColorPicker.focusLost(null); }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording recording = recordings.get(0); AssertJUnit.assertEquals("recordSelect", recording.getCall()); AssertJUnit.assertEquals("#ea9c2c", recording.getParameters()[0]); } @Test public void colorChooserWithColorName() { ColorPicker colorPicker = (ColorPicker) getPrimaryStage().getScene().getRoot().lookup(".color-picker"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(() -> { RFXColorPicker rfxColorPicker = new RFXColorPicker(colorPicker, null, null, lr); colorPicker.setValue(Color.RED); rfxColorPicker.focusLost(null); }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording recording = recordings.get(0); AssertJUnit.assertEquals("recordSelect", recording.getCall()); AssertJUnit.assertEquals("#ff0000", recording.getParameters()[0]); }
### Question: RFXCheckBox extends RFXComponent { @Override protected void mouseClicked(MouseEvent me) { int selection = getSelection((CheckBox) node); if (prevSelection == null || selection != prevSelection) { recorder.recordSelect(this, JavaFXCheckBoxElement.states[selection]); } prevSelection = selection; } RFXCheckBox(Node source, JSONOMapConfig omapConfig, Point2D point, IJSONRecorder recorder); @Override String _getValue(); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void selectCheckBoxSelected() throws Throwable { CheckBox checkBox = findCheckbox("Simple checkbox"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(new Runnable() { @Override public void run() { checkBox.setSelected(true); RFXCheckBox rfxCheckBox = new RFXCheckBox(checkBox, null, null, lr); rfxCheckBox.mouseClicked(null); } }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording select = recordings.get(0); AssertJUnit.assertEquals("recordSelect", select.getCall()); AssertJUnit.assertEquals("checked", select.getParameters()[0]); } @Test public void selectCheckBoxSelectedTriState() throws Throwable { CheckBox checkBox = findCheckbox("Three state checkbox"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(new Runnable() { @Override public void run() { checkBox.setIndeterminate(true); checkBox.setSelected(true); RFXCheckBox rfxCheckBox = new RFXCheckBox(checkBox, null, null, lr); rfxCheckBox.mouseClicked(null); } }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording select = recordings.get(0); AssertJUnit.assertEquals("recordSelect", select.getCall()); AssertJUnit.assertEquals("indeterminate", select.getParameters()[0]); }
### Question: RFXToggleButton extends RFXComponent { @Override protected void mouseClicked(MouseEvent me) { boolean selected = ((ToggleButton) node).isSelected(); if (prevSelection == null || selected != prevSelection.booleanValue()) { recorder.recordSelect(this, Boolean.toString(selected)); } prevSelection = selected; } RFXToggleButton(Node source, JSONOMapConfig omapConfig, Point2D point, IJSONRecorder recorder); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void selectRadioButtonSelected() { RadioButton radioButton = (RadioButton) getPrimaryStage().getScene().getRoot().lookup(".radio-button"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(new Runnable() { @Override public void run() { RFXToggleButton rfxToggleButton = new RFXToggleButton(radioButton, null, null, lr); radioButton.setSelected(true); rfxToggleButton.mouseClicked(null); } }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording select = recordings.get(0); AssertJUnit.assertEquals("recordSelect", select.getCall()); AssertJUnit.assertEquals("true", select.getParameters()[0]); }
### Question: RFXSplitPane extends RFXComponent { @Override protected void mouseReleased(MouseEvent me) { SplitPane splitPane = (SplitPane) node; String currentDividerLoctions = getDividerLocations(splitPane); if (!currentDividerLoctions.equals(prevLocations)) { recorder.recordSelect(this, currentDividerLoctions); } } RFXSplitPane(Node source, JSONOMapConfig omapConfig, Point2D point, IJSONRecorder recorder); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void selectSplitPane() { SplitPane splitPane = (SplitPane) getPrimaryStage().getScene().getRoot().lookup(".split-pane"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(() -> { RFXSplitPane rfxSplitPane = new RFXSplitPane(splitPane, null, null, lr); splitPane.setDividerPosition(0, 0.6); rfxSplitPane.mouseReleased(null); }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording recording = recordings.get(0); AssertJUnit.assertEquals("recordSelect", recording.getCall()); AssertJUnit.assertEquals(0.6, new JSONArray((String) recording.getParameters()[0]).getDouble(0)); } @Test public void getText() { SplitPane splitPane = (SplitPane) getPrimaryStage().getScene().getRoot().lookup(".split-pane"); LoggingRecorder lr = new LoggingRecorder(); List<String> text = new ArrayList<>(); Platform.runLater(() -> { RFXSplitPane rfxSplitPane = new RFXSplitPane(splitPane, null, null, lr); splitPane.setDividerPosition(0, 0.6); rfxSplitPane.mouseReleased(null); text.add(rfxSplitPane.getAttribute("text")); }); new Wait("Waiting for split pane text.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals("[0.6,0.6008064516129032]", text.get(0)); }
### Question: RFXProgressBar extends RFXComponent { @Override protected void mouseReleased(MouseEvent me) { ProgressBar progressBar = (ProgressBar) node; String currentValue = getProgressText(progressBar); if (currentValue != null && !currentValue.equals("-1")) { recorder.recordSelect(this, currentValue); } } RFXProgressBar(Node source, JSONOMapConfig omapConfig, Point2D point, IJSONRecorder recorder); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void select() { ProgressBar progressBar = (ProgressBar) getPrimaryStage().getScene().getRoot().lookup(".progress-bar"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(() -> { RFXProgressBar rfxProgressBar = new RFXProgressBar(progressBar, null, null, lr); progressBar.setProgress(0.56); rfxProgressBar.mouseReleased(null); }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording recording = recordings.get(0); AssertJUnit.assertEquals("recordSelect", recording.getCall()); AssertJUnit.assertEquals("0.56", recording.getParameters()[0]); } @Test public void getText() { ProgressBar progressBar = (ProgressBar) getPrimaryStage().getScene().getRoot().lookup(".progress-bar"); LoggingRecorder lr = new LoggingRecorder(); List<String> text = new ArrayList<>(); Platform.runLater(() -> { RFXProgressBar rfxProgressBar = new RFXProgressBar(progressBar, null, null, lr); progressBar.setProgress(0.56); rfxProgressBar.mouseReleased(null); text.add(rfxProgressBar.getAttribute("text")); }); new Wait("Waiting for progress bar text.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals("0.56", text.get(0)); }
### Question: RFXDatePicker extends RFXComponent { @Override public String _getText() { return getDatePickerText((DatePicker) node, ((DatePicker) node).getValue()); } RFXDatePicker(Node source, JSONOMapConfig omapConfig, Point2D point, IJSONRecorder recorder); @Override void focusGained(RFXComponent prev); @Override void focusLost(RFXComponent next); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void getText() { DatePicker datePicker = (DatePicker) getPrimaryStage().getScene().getRoot().lookup(".date-picker"); LoggingRecorder lr = new LoggingRecorder(); List<String> text = new ArrayList<>(); RFXDatePicker rfxDatePicker = new RFXDatePicker(datePicker, null, null, lr); Platform.runLater(() -> { datePicker.setValue(LocalDate.now()); text.add(rfxDatePicker._getText()); }); new Wait("Waiting for date picker text.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals(datePicker.getConverter().toString(LocalDate.now()), text.get(0)); }
### Question: RFXSlider extends RFXComponent { @Override public void focusLost(RFXComponent next) { double current = ((Slider) node).getValue(); if (current != prevValue) { recorder.recordSelect(this, "" + current); } } RFXSlider(Node source, JSONOMapConfig omapConfig, Point2D point, IJSONRecorder recorder); @Override void focusGained(RFXComponent prev); @Override void focusLost(RFXComponent next); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void slider() throws Throwable { Slider slider = (Slider) getPrimaryStage().getScene().getRoot().lookup(".slider"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(new Runnable() { @Override public void run() { slider.setValue(25.0); RFXSlider rfxSlider = new RFXSlider(slider, null, null, lr); rfxSlider.focusLost(null); } }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording recording = recordings.get(0); AssertJUnit.assertEquals("recordSelect", recording.getCall()); AssertJUnit.assertEquals("25.0", recording.getParameters()[0]); } @Test public void getText() throws Throwable { Slider slider = (Slider) getPrimaryStage().getScene().getRoot().lookup(".slider"); LoggingRecorder lr = new LoggingRecorder(); List<String> text = new ArrayList<>(); Platform.runLater(new Runnable() { @Override public void run() { slider.setValue(25.0); RFXSlider rfxSlider = new RFXSlider(slider, null, null, lr); rfxSlider.focusLost(null); text.add(rfxSlider.getAttribute("text")); } }); new Wait("Waiting for slider text.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals("25.0", text.get(0)); }
### Question: RFXTitledPane extends RFXComponent { @Override protected void mouseButton1Pressed(MouseEvent me) { recorder.recordClick(this, me); } RFXTitledPane(Node source, JSONOMapConfig omapConfig, Point2D point, IJSONRecorder recorder); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void click() { TitledPane titledPane = (TitledPane) getPrimaryStage().getScene().getRoot().lookup(".titled-pane"); LoggingRecorder lr = new LoggingRecorder(); Platform.runLater(() -> { RFXTitledPane rfxTitledPane = new RFXTitledPane(titledPane, null, null, lr); titledPane.setExpanded(true); rfxTitledPane.mouseButton1Pressed(null); }); List<Recording> recordings = lr.waitAndGetRecordings(1); Recording recording = recordings.get(0); AssertJUnit.assertEquals("click", recording.getCall()); } @Test public void getText() { TitledPane titledPane = (TitledPane) getPrimaryStage().getScene().getRoot().lookup(".titled-pane"); LoggingRecorder lr = new LoggingRecorder(); List<String> text = new ArrayList<>(); Platform.runLater(() -> { RFXTitledPane rfxTitledPane = new RFXTitledPane(titledPane, null, null, lr); titledPane.setExpanded(true); rfxTitledPane.mouseButton1Pressed(null); text.add(rfxTitledPane.getAttribute("text")); }); new Wait("Waiting for titled pane text.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals("Node 1", text.get(0)); }
### Question: JSliderJavaElement extends AbstractJavaElement { @Override public boolean marathon_select(String value) { ((JSlider) component).setValue(Integer.valueOf(Integer.parseInt(value))); return true; } JSliderJavaElement(Component component, IJavaAgent driver, JWindow window); @Override String _getText(); static String getCurrentValue(JSlider slider); @Override boolean marathon_select(String value); static final Logger LOGGER; }### Answer: @Test(expectedExceptions = NumberFormatException.class) public void illegalArgumentException() { IJavaElement slider = driver.findElementByTagName("slider"); marathon_select(slider, "ten"); AssertJUnit.assertEquals("", slider.getAttribute("value")); }
### Question: JavaFXChoiceBoxElement extends JavaFXElement { @Override public boolean marathon_select(String value) { ChoiceBox<?> choiceBox = (ChoiceBox<?>) getComponent(); String text = stripHTMLTags(value); int selectedItem = getChoiceBoxItemIndex(choiceBox, text); if (selectedItem == -1) { return false; } choiceBox.getSelectionModel().select(selectedItem); return true; } JavaFXChoiceBoxElement(Node component, IJavaFXAgent driver, JFXWindow window); @Override List<IJavaFXElement> getByPseudoElement(String selector, Object[] params); @Override boolean marathon_select(String value); String getContent(); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void select() { ChoiceBox<?> choiceBoxNode = (ChoiceBox<?>) getPrimaryStage().getScene().getRoot().lookup(".choice-box"); Platform.runLater(() -> { choiceBox.marathon_select("Cat"); }); new Wait("Waiting for choice box option to be set.") { @Override public boolean until() { return choiceBoxNode.getSelectionModel().getSelectedIndex() == 1; } }; } @Test public void getText() { List<String> text = new ArrayList<>(); Platform.runLater(() -> { choiceBox.marathon_select("Horse"); text.add(choiceBox.getAttribute("text")); }); new Wait("Waiting for choice box text.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals("Horse", text.get(0)); }
### Question: JColorChooserJavaElement extends AbstractJavaElement { @Override public boolean marathon_select(String value) { if (!value.equals("")) { try { ((JColorChooser) component).setColor(Color.decode(value)); return true; } catch (Throwable t) { throw new NumberFormatException("Invalid value for '" + value + "' for color-chooser '"); } } return false; } JColorChooserJavaElement(Component component, IJavaAgent driver, JWindow window); @Override boolean marathon_select(String value); static final Logger LOGGER; }### Answer: @Test(expectedExceptions = NumberFormatException.class) public void colorChooserWithInvalidColorCode() { IJavaElement colorChooser = driver.findElementByTagName("color-chooser"); marathon_select(colorChooser, "#87436278"); }
### Question: JavaFXProgressBarElement extends JavaFXElement { @Override public boolean marathon_select(String value) { ProgressBar progressBar = (ProgressBar) getComponent(); progressBar.setProgress(Double.parseDouble(value)); return true; } JavaFXProgressBarElement(Node component, IJavaFXAgent driver, JFXWindow window); @Override boolean marathon_select(String value); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void select() { ProgressBar progressBarNode = (ProgressBar) getPrimaryStage().getScene().getRoot().lookup(".progress-bar"); Platform.runLater(() -> { progressBar.marathon_select("0.20"); }); new Wait("Wating for progress bar progress to be set.") { @Override public boolean until() { return progressBarNode.getProgress() == 0.2; } }; } @Test public void getText() { List<String> value = new ArrayList<>(); Platform.runLater(() -> { progressBar.marathon_select("0.20"); value.add(progressBar.getAttribute("text")); }); new Wait("Wating for progress bar value") { @Override public boolean until() { return value.size() > 0; } }; AssertJUnit.assertEquals("0.2", value.get(0)); }
### Question: JTabbedPaneJavaElement extends AbstractJavaElement { @Override public boolean marathon_select(String tab) { int tabIndex = findTabIndex((JTabbedPane) component, tab); if (tabIndex != -1) { ((JTabbedPane) component).setSelectedIndex(tabIndex); } return tabIndex != -1; } JTabbedPaneJavaElement(Component component, IJavaAgent driver, JWindow window); @Override String _getText(); static String getSelectedItemText(JTabbedPane component); @Override List<IJavaElement> getByPseudoElement(String selector, Object[] params); @Override boolean marathon_select(String tab); String getContent(); static String[][] getContent(JTabbedPane component); static final Logger LOGGER; }### Answer: @Test(expectedExceptions = { RuntimeException.class }) public void selectAnInvalidTab() throws Throwable { IJavaElement tabbedPane = driver.findElementByTagName("tabbed-pane"); AssertJUnit.assertEquals("0", tabbedPane.getAttribute("selectedIndex")); marathon_select(tabbedPane, "Tab 21"); AssertJUnit.assertEquals("1", tabbedPane.getAttribute("selectedIndex")); }
### Question: JavaFXHTMLEditor extends JavaFXElement { @Override public boolean marathon_select(String value) { HTMLEditor htmlEditor = (HTMLEditor) getComponent(); htmlEditor.setHtmlText(value); return true; } JavaFXHTMLEditor(Node component, IJavaFXAgent driver, JFXWindow window); @Override boolean marathon_select(String value); @Override String getTagName(); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void select() { HTMLEditor htmlEditorNode = (HTMLEditor) getPrimaryStage().getScene().getRoot().lookup(".html-editor"); Platform.runLater(() -> { htmlEditor.marathon_select("This html editor test"); }); try { new Wait("Waiting for html text to be set.") { @Override public boolean until() { String htmlText = htmlEditorNode.getHtmlText(); return htmlText.equals( "<html dir=\"ltr\"><head></head><body contenteditable=\"true\">This html editor test</body></html>"); } }; } catch (Throwable t) { } AssertJUnit.assertEquals( "<html dir=\"ltr\"><head></head><body contenteditable=\"true\">This html editor test</body></html>", htmlEditor.getText()); AssertJUnit.assertEquals( "<html dir=\"ltr\"><head></head><body contenteditable=\"true\">This html editor test</body></html>", htmlEditorNode.getHtmlText()); } @Test public void getText() { List<String> text = new ArrayList<>(); Platform.runLater(() -> { htmlEditor.marathon_select("This html editor test"); text.add(htmlEditor.getAttribute("text")); }); try { new Wait("Waiting for html text to be set.") { @Override public boolean until() { return htmlEditor.getAttribute("text").equals( "<html dir=\"ltr\"><head></head><body contenteditable=\"true\">This html editor test</body></html>"); } }; } catch (Throwable t) { } AssertJUnit.assertEquals( "<html dir=\"ltr\"><head></head><body contenteditable=\"true\">This html editor test</body></html>", htmlEditor.getAttribute("text")); }
### Question: JavaFXTabPaneElement extends JavaFXElement { @Override public boolean marathon_select(String tab) { Matcher matcher = CLOSE_PATTERN.matcher(tab); boolean isCloseTab = matcher.matches(); tab = isCloseTab ? matcher.group(1) : tab; TabPane tp = (TabPane) node; ObservableList<Tab> tabs = tp.getTabs(); for (int index = 0; index < tabs.size(); index++) { String current = getTextForTab(tp, tabs.get(index)); if (tab.equals(current)) { if (isCloseTab) { closeTab(tabs.get(index)); return true; } tp.getSelectionModel().select(index); return true; } } return false; } JavaFXTabPaneElement(Node component, IJavaFXAgent driver, JFXWindow window); @Override List<IJavaFXElement> getByPseudoElement(String selector, Object[] params); @Override boolean marathon_select(String tab); @Override String _getText(); String getContent(); static final Logger LOGGER; }### Answer: @Test public void selectTab() { TabPane tabPaneNode = (TabPane) getPrimaryStage().getScene().getRoot().lookup(".tab-pane"); tabPane.marathon_select("Tab 2"); new Wait("Waiting for the tab selection.") { @Override public boolean until() { return 1 == tabPaneNode.getSelectionModel().getSelectedIndex(); } }; } @Test public void getText() { List<String> text = new ArrayList<>(); Platform.runLater(() -> { tabPane.marathon_select("Tab 2"); text.add(tabPane.getAttribute("text")); }); new Wait("Waiting for the tab selection.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals("Tab 2", text.get(0)); } @Test public void selectAnInvalidTab() { AssertJUnit.assertEquals("0", tabPane.getAttribute("selectionModel.getSelectedIndex")); tabPane.marathon_select("Tab 21"); AssertJUnit.assertEquals(false, tabPane.marathon_select("Tab 21")); }
### Question: JavaFXColorPickerElement extends JavaFXElement { @Override public boolean marathon_select(String value) { ColorPicker colorPicker = (ColorPicker) getComponent(); if (!value.equals("")) { try { colorPicker.setValue(Color.valueOf(value)); Event.fireEvent(colorPicker, new ActionEvent()); return true; } catch (Throwable t) { throw new IllegalArgumentException("Invalid value for '" + value + "' for color-picker '"); } } return false; } JavaFXColorPickerElement(Node component, IJavaFXAgent driver, JFXWindow window); @Override boolean marathon_select(String value); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void selectColor() { ColorPicker colorPickerNode = (ColorPicker) getPrimaryStage().getScene().getRoot().lookup(".color-picker"); Platform.runLater(() -> colorpicker.marathon_select("#ff0000")); new Wait("Waiting for color to be set.") { @Override public boolean until() { return colorPickerNode.getValue().toString().equals("0xff0000ff"); } }; } @Test public void getText() { List<String> text = new ArrayList<>(); Platform.runLater(() -> { colorpicker.marathon_select("#ff0000"); text.add(colorpicker.getAttribute("text")); }); new Wait("Waiting for color picker text.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals("#ff0000", text.get(0)); } @Test(expectedExceptions = IllegalArgumentException.class) public void colorPickerWithInvalidColorCode() { colorpicker.marathon_select("#67899"); }
### Question: JavaFXSliderElement extends JavaFXElement { @Override public boolean marathon_select(String value) { ((Slider) node).setValue(Double.valueOf(Double.parseDouble(value))); return true; } JavaFXSliderElement(Node component, IJavaFXAgent driver, JFXWindow window); @Override boolean marathon_select(String value); @Override String _getText(); static final Logger LOGGER; }### Answer: @Test public void setSliderValue() { Slider sliderNode = (Slider) getPrimaryStage().getScene().getRoot().lookup(".slider"); slider.marathon_select("25.0"); new Wait("Waiting for slider value to be set.") { @Override public boolean until() { return 25.0 == sliderNode.getValue(); } }; } @Test public void getText() { List<String> text = new ArrayList<>(); Platform.runLater(() -> { slider.marathon_select("25.0"); text.add(slider.getAttribute("text")); }); new Wait("Waiting for the slider text.") { @Override public boolean until() { return text.size() > 0; } }; AssertJUnit.assertEquals("25.0", text.get(0)); } @Test(expectedExceptions = NumberFormatException.class) public void illegalArgumentException() { Slider sliderNode = (Slider) getPrimaryStage().getScene().getRoot().lookup(".slider"); slider.marathon_select("ten"); new Wait("Waiting for slider value to be set.") { @Override public boolean until() { return 25.0 == sliderNode.getValue(); } }; }
### Question: PokeDataSource { public Observable<String> getPokemonStringObservable(String id) { return pokemonService.getPokemon(id) .map(new Function<Pokemon, String>() { @Override public String apply(@NonNull Pokemon pokemon) throws Exception { return constructPokemon(pokemon); } }); } @Inject PokeDataSource(PokemonService pokemonService); Observable<String> getPokemonStringObservable(String id); Observable<String> getPokemonAbilityStringObservable(String id); }### Answer: @Test public void testOnAddedHeader() throws InterruptedException { PokeDataSource dataSource = new PokeDataSource(pokemonService); TestObserver<String> observer = new TestObserver<>(); dataSource.getPokemonStringObservable("12").subscribe(observer); RecordedRequest recordedRequest = getMockWebServer().takeRequest(); assertEquals("application/json", recordedRequest.getHeader("Content-Type")); } @Test public void testGetPokemonStringObservable() { PokeDataSource dataSource = new PokeDataSource(pokemonService); TestObserver observer = new TestObserver(); dataSource.getPokemonStringObservable("12") .subscribe(observer); observer.assertNoErrors(); observer.awaitTerminalEvent(); observer.assertComplete(); observer.assertValue("Id: 12\n" + "Name: butterfree"); }
### Question: PokeDataSource { public Observable<String> getPokemonAbilityStringObservable(String id) { return pokemonService.getPokemon(id) .map(new Function<Pokemon, String>() { @Override public String apply(@NonNull Pokemon pokemon) throws Exception { return constructAbility(pokemon); } }); } @Inject PokeDataSource(PokemonService pokemonService); Observable<String> getPokemonStringObservable(String id); Observable<String> getPokemonAbilityStringObservable(String id); }### Answer: @Test public void testGetPokemonAbilityStringObservable() { PokeDataSource dataSource = new PokeDataSource(pokemonService); TestObserver observer = new TestObserver(); dataSource.getPokemonAbilityStringObservable("12") .subscribe(observer); observer.assertNoErrors(); observer.awaitTerminalEvent(); observer.assertComplete(); observer.assertValue("Id: 12\n" + "Name: butterfreeAbility Name : tinted-lens\n" + " Is Hidden : true"); }
### Question: ScrambleMove { public static ScrambleMove parse(String move) { ScrambleMoves sm = ScrambleMoves.determineMove(move); String sanitizedMove = move.replaceAll("\\s", ""); sanitizedMove = sanitizedMove.substring(sanitizedMove.lastIndexOf(":") + 1, sanitizedMove.length() - 1); String[] moveParts = sanitizedMove.split("(" + ARG_SEP + "|" + COORD_SEP + "|" + COORD_SEP_CAP + ")"); long[] args = new long[moveParts.length]; for (int i = 0; i < moveParts.length; i++) { args[i] = Long.parseLong(moveParts[i]); } return new ScrambleMove(sm, args); } ScrambleMove(ScrambleMoves move, long ... args); long getArg(int argIndex); void toReverse(); String toKeyString(StringBuilder sbIn, boolean reverse); String toKeyString(); static ScrambleMove parse(String move); static LongLinkedList<ScrambleMove> parseMulti(String moves); static synchronized boolean isUsingOpCode(); static synchronized void useOpCode(boolean use); @Override boolean equals(Object o); @Override int hashCode(); final ScrambleMoves move; }### Answer: @Test public void testParse(){ assertEquals(this.testMove, ScrambleMove.parse(this.expectedString)); }
### Question: UserFactory { public User create(String username, String password, String salt, String role) { return new User(username, password, salt, role); } User create(String username, String password, String salt, String role); }### Answer: @Test public void testCreate() { UserFactory userFactory = new UserFactory(); assertNotNull(userFactory.create("username", "pass", "salt", "USER")); }
### Question: AuthProviderService implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String login = authentication.getName(); String password = authentication.getCredentials().toString(); LOGGER.info("Doing login " + login); User u = userService.isLoginValid(login, password); if(u != null) { LOGGER.info("Login successful. User: " + login); return usernamePasswordAuthenticationTokenFactory.create(u); } throw new UsernameNotFoundException("Not valid login/password"); } @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> aClass); }### Answer: @Test public void testAuthenticateSuccess() { User user = new User("username", "pass", "salt", "role"); Authentication authentication = mock(UsernamePasswordAuthenticationToken.class); when(authentication.getName()).thenReturn("username"); when(authentication.getCredentials()).thenReturn("pass"); when(userService.isLoginValid("username", "pass")).thenReturn(user); when(usernamePasswordAuthenticationTokenFactory.create(user)).thenReturn((UsernamePasswordAuthenticationToken) authentication); try { Authentication a = authProviderService.authenticate(authentication); assertEquals("username", a.getName()); assertEquals("pass", a.getCredentials().toString()); } catch (UsernameNotFoundException e) { fail("This code should not be executed"); } } @Test public void testAuthenticateInvalid() { when(userService.isLoginValid(anyString(), anyString())).thenReturn(null); Authentication authentication = mock(Authentication.class); when(authentication.getName()).thenReturn("username"); when(authentication.getCredentials()).thenReturn("pass"); try { authProviderService.authenticate(authentication); fail("This code should not be executed"); } catch (UsernameNotFoundException e) { assertNotNull(e); } }
### Question: JwtService { public String createToken(String username, String secret, Date expireAt) { if(StringUtils.hasText(username) && StringUtils.hasText(secret) && expireAt != null && expireAt.after(new Date()) ) { String secret2 = new String(Base64.encodeBase64(secret.getBytes())); String compactJws = Jwts.builder() .setSubject(username) .signWith(SignatureAlgorithm.HS512, secret2) .setExpiration(expireAt) .compact(); return compactJws; } return null; } String createToken(String username, String secret, Date expireAt); boolean isValid(String token, String secret); String getUsername(String token, String secret); }### Answer: @Test public void testCreateTokenEmptyUsername() { assertNull(jwtService.createToken(null, SECRET, generateValidDate())); assertNull(jwtService.createToken("", SECRET, generateValidDate())); assertNull(jwtService.createToken(" ", SECRET, generateValidDate())); } @Test public void testCreateTokenEmptySecret() { assertNull(jwtService.createToken(USERNAME, null, generateValidDate())); assertNull(jwtService.createToken(USERNAME, "", generateValidDate())); assertNull(jwtService.createToken(USERNAME, " ", generateValidDate())); } @Test public void testCreateTokenInvalidDate() { assertNull(jwtService.createToken(USERNAME, SECRET, null)); assertNull(jwtService.createToken(USERNAME, SECRET, generateInValidDate())); } @Test public void testCreateTokenSuccess() { Date d = generateValidDate(); String s = jwtService.createToken(USERNAME, SECRET, d); String secret2 = new String(Base64.encodeBase64(SECRET.getBytes())); String compactJws = Jwts.builder() .setSubject(USERNAME) .signWith(SignatureAlgorithm.HS512, secret2) .setExpiration(d) .compact(); assertEquals(compactJws, s); }
### Question: UserService { public void create(String username, String password, String role) { String salt = stringSupport.generate(); User u = userFactory.create(username, shaPasswordEncoder.encodePassword(password, salt), salt, role); userRepository.save(u); } void create(String username, String password, String role); User isLoginValid(String username, String pass); User findByUsername(String username); User createUserToken(String username, String secret); User validateUser(String token, String secret); }### Answer: @Test public void testCreate() { userService.create(USERNAME, PASS, ROLE); verify(userRepository).save(user); }
### Question: UsernamePasswordAuthenticationTokenFactory { public UsernamePasswordAuthenticationToken create(User u) { SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(u.getRole()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(u.getUsername(), u.getPassword(), Arrays.asList(simpleGrantedAuthority)); return authentication; } UsernamePasswordAuthenticationToken create(User u); }### Answer: @Test public void testCreate() { UsernamePasswordAuthenticationTokenFactory factory = new UsernamePasswordAuthenticationTokenFactory(); User u = new User("username", "pass", "salt", "role"); UsernamePasswordAuthenticationToken auth = factory.create(u); assertNotNull(auth); assertEquals(u.getUsername(), auth.getPrincipal().toString()); assertEquals(u.getPassword(), auth.getCredentials().toString()); assertEquals(u.getRole(), auth.getAuthorities().toArray()[0].toString()); }
### Question: UserService { public User isLoginValid(String username, String pass) { if(!StringUtils.hasText(username) || !StringUtils.hasText(pass)) { return null; } String password = new String(Base64.decodeBase64(pass.getBytes())); User u = userRepository.findByUsername(username); if(u == null) { return null; } if(!u.getPassword().equals(shaPasswordEncoder.encodePassword(password, u.getSalt()))) { return null; } return u; } void create(String username, String password, String role); User isLoginValid(String username, String pass); User findByUsername(String username); User createUserToken(String username, String secret); User validateUser(String token, String secret); }### Answer: @Test public void testIsLoginValidEmptyParams() { assertNull(userService.isLoginValid(null, null) ); assertNull(userService.isLoginValid("", null)); assertNull(userService.isLoginValid(null, "")); verifyZeroInteractions(userRepository, shaPasswordEncoder); }
### Question: AjaxAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { logger.debug("Authentication Successful"); User u = userService.createUserToken(authentication.getName(), request.getRemoteAddr()); response.getWriter().print("{ \"token\" : \"" + u.getToken() + "\"}"); response.setStatus(HttpServletResponse.SC_OK); headerHandler.process(request, response); } @Override void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication); }### Answer: @Test public void testOnAuthenticationSuccess() throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); Authentication authentication = mock(Authentication.class); when(authentication.getName()).thenReturn("name"); when(request.getRemoteAddr()).thenReturn("localhost"); PrintWriter printWriter = mock(PrintWriter.class); when(response.getWriter()).thenReturn(printWriter); String token = "token"; User u = new User("usernma", "pass", "salt", "role"); u.setToken("token"); when(userService.createUserToken(authentication.getName(), request.getRemoteAddr())).thenReturn(u); ajaxAuthenticationSuccessHandler.onAuthenticationSuccess(request, response, authentication); verify(response).setStatus(HttpServletResponse.SC_OK); verify(headerHandler).process(request, response); verify(userService).createUserToken(authentication.getName(), request.getRemoteAddr()) ; verify(printWriter).print("{ \"token\" : \"" + u.getToken() + "\"}"); }
### Question: HeaderHandler { public void process(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setHeader(ALLOW_ORIGIN, STAR); response.setHeader(ALLOW_CREDENTIALS, TRUE); response.setHeader(ALLOW_HEADERS, request.getHeader(REQUEST_HEADERS)); if (request.getMethod().equals(OPTIONS)) { response.getWriter().print(OK); response.getWriter().flush(); } } void process(HttpServletRequest request, HttpServletResponse response); }### Answer: @Test public void testProcess() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getMethod()).thenReturn(OPTIONS); PrintWriter printWriter = mock(PrintWriter.class); when(response.getWriter()).thenReturn(printWriter); headerHandler.process(request, response); verify(response).setHeader(ALLOW_ORIGIN, STAR); verify(response).setHeader(ALLOW_CREDENTIALS, TRUE); verify(response).setHeader(ALLOW_HEADERS, request.getHeader(REQUEST_HEADERS)); verify(printWriter).print(OK); verify(printWriter).flush(); } @Test public void testProcessMethodGet() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getMethod()).thenReturn("GET"); PrintWriter printWriter = mock(PrintWriter.class); when(response.getWriter()).thenReturn(printWriter); headerHandler.process(request, response); verify(response).setHeader(ALLOW_ORIGIN, STAR); verify(response).setHeader(ALLOW_CREDENTIALS, TRUE); verify(response).setHeader(ALLOW_HEADERS, request.getHeader(REQUEST_HEADERS)); verify(printWriter, never()).print(OK); verify(printWriter, never()).flush(); }
### Question: Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint { public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,ServletException { LOGGER.debug("Pre-authenticated entry point called. Rejecting access:" + request.getRequestURL()); headerHandler.process(request, response); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied"); } void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2); }### Answer: @Test public void testCommence() throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); AuthenticationException authenticationException = mock(AuthenticationException.class); http401UnauthorizedEntryPoint.commence(request, response, authenticationException); verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied"); verify(headerHandler).process(request, response); }
### Question: AjaxAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { headerHandler.process(request, response); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed"); } @Override void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception); }### Answer: @Test public void testOnAuthenticationFailure() throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); AuthenticationException exception = mock(AuthenticationException.class); ajaxAuthenticationFailureHandler.onAuthenticationFailure(request, response, exception); verifyZeroInteractions(request, exception); verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed"); verify(headerHandler).process(request, response); }
### Question: UserService { public User findByUsername(String username) { return userRepository.findByUsername(username); } void create(String username, String password, String role); User isLoginValid(String username, String pass); User findByUsername(String username); User createUserToken(String username, String secret); User validateUser(String token, String secret); }### Answer: @Test public void testFindByUsername() { User u = new User(USERNAME, PASS, SALT, ROLE); when(userRepository.findByUsername(USERNAME)).thenReturn(u); assertEquals(u, userService.findByUsername(USERNAME)); }
### Question: SecurityAppContext { public SecurityContext getContext() { return SecurityContextHolder.getContext(); } SecurityContext getContext(); }### Answer: @Test public void testContext() { assertNotNull(securityAppContext.getContext()); }
### Question: HelloController { @RequestMapping("/") public String index() { return "It is working!"; } @RequestMapping("/") String index(); }### Answer: @Test public void index() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("It is working!"))); }
### Question: StringSupport { public String generate() { return UUID.randomUUID().toString(); } String generate(); }### Answer: @Test public void testGenerate() { StringSupport stringSupport = new StringSupport(); assertNotNull(stringSupport.generate()); assertTrue(stringSupport.generate().length() > 0); }
### Question: DateGenerator { public Date getExpirationDate() { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_WEEK, 1); return c.getTime(); } Date getExpirationDate(); }### Answer: @Test public void testExpirationDate() { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_WEEK, 1); DateGenerator dateGenerator = new DateGenerator(); Calendar c2 = Calendar.getInstance(); c2.setTime(dateGenerator.getExpirationDate()); assertEquals(c.get(Calendar.DAY_OF_WEEK), c2.get(Calendar.DAY_OF_WEEK)); assertEquals(c.get(Calendar.DAY_OF_MONTH), c2.get(Calendar.DAY_OF_MONTH)); assertEquals(c.get(Calendar.MONTH), c2.get(Calendar.MONTH)); assertEquals(c.get(Calendar.YEAR), c2.get(Calendar.YEAR)); assertEquals(c.get(Calendar.HOUR_OF_DAY), c2.get(Calendar.HOUR_OF_DAY)); }
### Question: UserService { public User createUserToken(String username, String secret) { String token = jwtService.createToken(username, secret, dateGenerator.getExpirationDate()); User u = userRepository.findByUsername(username); u.setToken(token); return userRepository.save(u); } void create(String username, String password, String role); User isLoginValid(String username, String pass); User findByUsername(String username); User createUserToken(String username, String secret); User validateUser(String token, String secret); }### Answer: @Test public void testCreateUserToken() { User u = new User(USERNAME, ENCODED_PASS, SALT, ROLE); when(jwtService.createToken(USERNAME, SECRET, date)).thenReturn(TOKEN); when(userRepository.findByUsername(USERNAME)).thenReturn(u); when(userRepository.save(u)).thenReturn(u); User u2 = userService.createUserToken(USERNAME, SECRET); verify(userRepository).save(u); assertEquals(TOKEN, u2.getToken()); }
### Question: UserService { public User validateUser(String token, String secret) { String username = jwtService.getUsername(token, secret); if (username != null ) { User user = userRepository.findByUsername(username); if (user != null && token.equals(user.getToken()) && jwtService.isValid(token, secret)) { return user; } } return null; } void create(String username, String password, String role); User isLoginValid(String username, String pass); User findByUsername(String username); User createUserToken(String username, String secret); User validateUser(String token, String secret); }### Answer: @Test public void testValidateUserNullUsername() { when(jwtService.getUsername(TOKEN, SECRET)).thenReturn(null); assertNull(userService.validateUser(TOKEN, SECRET)); }
### Question: WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authProvider); } @Bean ShaPasswordEncoder sha(); }### Answer: @Test public void testConfigure() throws Exception { AuthenticationManagerBuilder auth = mock(AuthenticationManagerBuilder.class); webSecurityConfig.configure(auth); verify(auth).authenticationProvider(authProvider); }
### Question: WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public ShaPasswordEncoder sha() { ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder(256); return shaPasswordEncoder; } @Bean ShaPasswordEncoder sha(); }### Answer: @Test public void testPasswordEncoder() { assertNotNull(webSecurityConfig.sha()); assertEquals("SHA-256", webSecurityConfig.sha().getAlgorithm()); }
### Question: AuthProviderService implements AuthenticationProvider { @Override public boolean supports(Class<?> aClass) { return aClass.equals(UsernamePasswordAuthenticationToken.class); } @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> aClass); }### Answer: @Test public void testSupports() { assertFalse(authProviderService.supports(String.class)); assertTrue(authProviderService.supports(UsernamePasswordAuthenticationToken.class)); }
### Question: FirstPresenter { public void attach(FirstFragment fragment) { firstFragment = fragment; firstFragment.initialize(text); } void attach(FirstFragment fragment); boolean hasView(); void detach(FirstFragment fragment); void updateText(String text); void restore(StateBundle stateBundle); StateBundle persist(); }### Answer: @Test public void attach() throws Exception { firstPresenter.updateText(TEST_VALUE); firstPresenter.attach(firstFragment); Mockito.verify(firstFragment, Mockito.only()).initialize(TEST_VALUE); }
### Question: FirstPresenter { public void detach(FirstFragment fragment) { this.firstFragment = null; } void attach(FirstFragment fragment); boolean hasView(); void detach(FirstFragment fragment); void updateText(String text); void restore(StateBundle stateBundle); StateBundle persist(); }### Answer: @Test public void detach() throws Exception { firstPresenter.updateText(TEST_VALUE); firstPresenter.attach(firstFragment); Mockito.verify(firstFragment, Mockito.only()).initialize(TEST_VALUE); assertThat(firstPresenter.hasView()).isTrue(); firstPresenter.detach(firstFragment); firstPresenter.updateText("BLAH"); Mockito.verify(firstFragment, Mockito.only()).initialize(TEST_VALUE); assertThat(firstPresenter.hasView()).isFalse(); }
### Question: FirstPresenter { public StateBundle persist() { StateBundle stateBundle = new StateBundle(); stateBundle.putString(TEXT, text); return stateBundle; } void attach(FirstFragment fragment); boolean hasView(); void detach(FirstFragment fragment); void updateText(String text); void restore(StateBundle stateBundle); StateBundle persist(); }### Answer: @Test public void persist() throws Exception { firstPresenter.updateText(TEST_VALUE); StateBundle stateBundle = firstPresenter.persist(); assertThat(stateBundle.getString(FirstPresenter.TEXT)).isEqualTo(TEST_VALUE); }
### Question: FirstPresenter { public void restore(StateBundle stateBundle) { this.text = stateBundle.getString(TEXT); } void attach(FirstFragment fragment); boolean hasView(); void detach(FirstFragment fragment); void updateText(String text); void restore(StateBundle stateBundle); StateBundle persist(); }### Answer: @Test public void restore() throws Exception { firstPresenter.updateText(""); StateBundle stateBundle = new StateBundle(); stateBundle.putString(FirstPresenter.TEXT, TEST_VALUE); firstPresenter.restore(stateBundle); firstPresenter.attach(firstFragment); Mockito.verify(firstFragment).initialize(TEST_VALUE); }
### Question: And extends BinaryProp { @Override public Boolean eval(Context m) { Boolean r1 = p1.eval(m); Boolean r2 = p2.eval(m); if (r1 == null || r2 == null) { return null; } if (!r1) { return false; } return r2; } And(Proposition p1, Proposition p2); @Override String operator(); @Override Or not(); @Override Boolean eval(Context m); @Override String toString(); }### Answer: @Test(dataProvider = "input") public void testTruthTable(Proposition a, Proposition b, Boolean r) { And p = new And(a, b); Assert.assertEquals(p.eval(new Context()), r); }
### Question: Ban extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Ban ban = (Ban) o; return isContinuous() == ban.isContinuous() && Objects.equals(vm, ban.vm) && nodes.size() == ban.nodes.size() && nodes.containsAll(ban.nodes) && ban.nodes.containsAll(nodes); } Ban(VM vm, Collection<Node> nodes); Ban(VM vm, Collection<Node> nodes, boolean continuous); Ban(VM vm, final Node node); @Override Collection<Node> getInvolvedNodes(); @Override Collection<VM> getInvolvedVMs(); @Override String toString(); @Override BanChecker getChecker(); static List<Ban> newBan(Collection<VM> vms, Collection<Node> nodes); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testEquals() { Model m = new DefaultModel(); VM v = m.newVM(); List<Node> ns = Util.newNodes(m, 10); Set<Node> nodes = new HashSet<>(Arrays.asList(ns.get(0), ns.get(1))); Ban b = new Ban(v, nodes); Assert.assertTrue(b.equals(b)); Assert.assertTrue(new Ban(v, nodes).equals(b)); Assert.assertEquals(new Ban(v, nodes).hashCode(), b.hashCode()); Assert.assertNotEquals(new Ban(m.newVM(), nodes), b); }
### Question: DefaultModel implements Model { @Override public void clearViews() { this.resources.clear(); } DefaultModel(); DefaultModel(ElementBuilder eb); @Override ModelView getView(String id); @Override boolean attach(ModelView v); @Override Collection<ModelView> getViews(); @Override Mapping getMapping(); @Override boolean equals(Object o); @Override int hashCode(); @Override boolean detach(ModelView v); @Override void clearViews(); @Override Attributes getAttributes(); @Override void setAttributes(Attributes a); @Override Model copy(); @Override String toString(); @Override VM newVM(); @Override VM newVM(int id); @Override Node newNode(); @Override Node newNode(int id); @Override boolean contains(VM v); @Override boolean contains(Node n); }### Answer: @Test(dependsOnMethods = {"testAttachView", "testInstantiate"}) public void testClearViews() { Model i = new DefaultModel(); ModelView v1 = mock(ModelView.class); when(v1.getIdentifier()).thenReturn("cpu"); ModelView v2 = mock(ModelView.class); when(v2.getIdentifier()).thenReturn("mem"); i.attach(v1); i.attach(v2); i.clearViews(); Assert.assertTrue(i.getViews().isEmpty()); }
### Question: SynchronizedElementBuilder implements ElementBuilder { @Override public VM newVM() { synchronized (vmLock) { return base.newVM(); } } SynchronizedElementBuilder(ElementBuilder b); @Override VM newVM(); @Override VM newVM(int id); @Override Node newNode(); @Override Node newNode(int id); @Override boolean contains(VM v); @Override boolean contains(Node n); @Override ElementBuilder copy(); }### Answer: @Test public void testMultipleIDDemand() { final ElementBuilder eb = new SynchronizedElementBuilder(new DefaultElementBuilder()); int nbThreads = 10; final int nbAllocs = 1000; final int[] used = new int[nbThreads * nbAllocs]; Thread[] ths = new Thread[nbThreads]; for (int i = 0; i < nbThreads; i++) { Thread t = new Thread(() -> { for (int x = 0; x < nbAllocs; x++) { VM v = eb.newVM(); used[v.id()]++; } }); ths[i] = t; t.start(); } try { for (int i = 0; i < nbThreads; i++) { ths[i].join(); } } catch (InterruptedException ex) { Assert.fail(ex.getMessage(), ex); } for (int i = 0; i < used.length; i++) { if (used[i] != 1) { Assert.fail("ID '" + i + "' used " + used[i] + " times"); } } }
### Question: ShareableResource implements ModelView { public static ShareableResource get(Model mo, String id) { return (ShareableResource) mo.getView(VIEW_ID_BASE + id); } ShareableResource(String r); ShareableResource(String id, int defCapacity, int defConsumption); int getConsumption(VM vm); int getCapacity(Node n); Set<VM> getDefinedVMs(); Set<Node> getDefinedNodes(); ShareableResource setConsumption(VM vm, int val); ShareableResource setConsumption(int val, VM... vms); ShareableResource setCapacity(Node n, int val); ShareableResource setCapacity(int val, Node... nodes); void unset(VM vm); void unset(Node n); void unset(VM... vms); void unset(Node... nodes); boolean consumptionDefined(VM vm); boolean capacityDefined(Node n); @Override String getIdentifier(); static String getIdentifier(String rcId); String getResourceIdentifier(); int getDefaultConsumption(); int getDefaultCapacity(); @Override boolean equals(Object o); @Override int hashCode(); @Override ShareableResource copy(); @Override String toString(); @Override boolean substituteVM(VM oldRef, VM newRef); int sumConsumptions(Collection<VM> ids, boolean undef); int sumCapacities(Collection<Node> ids, boolean undef); static ShareableResource get(Model mo, String id); static final String VIEW_ID_BASE; static final int DEFAULT_NO_VALUE; }### Answer: @Test public void testGet() { Model mo = new DefaultModel(); Assert.assertNull(ShareableResource.get(mo, "cpu")); ShareableResource cpu = new ShareableResource("cpu"); ShareableResource mem = new ShareableResource("mem"); mo.attach(cpu); Assert.assertEquals(ShareableResource.get(mo, "cpu"), cpu); Assert.assertNull(ShareableResource.get(mo, "mem")); mo.attach(mem); Assert.assertEquals(ShareableResource.get(mo, "cpu"), cpu); Assert.assertEquals(ShareableResource.get(mo, "mem"), mem); }
### Question: ShareableResource implements ModelView { @Override public int hashCode() { return Objects.hash(rcId, vmsConsumption, nodesCapacity); } ShareableResource(String r); ShareableResource(String id, int defCapacity, int defConsumption); int getConsumption(VM vm); int getCapacity(Node n); Set<VM> getDefinedVMs(); Set<Node> getDefinedNodes(); ShareableResource setConsumption(VM vm, int val); ShareableResource setConsumption(int val, VM... vms); ShareableResource setCapacity(Node n, int val); ShareableResource setCapacity(int val, Node... nodes); void unset(VM vm); void unset(Node n); void unset(VM... vms); void unset(Node... nodes); boolean consumptionDefined(VM vm); boolean capacityDefined(Node n); @Override String getIdentifier(); static String getIdentifier(String rcId); String getResourceIdentifier(); int getDefaultConsumption(); int getDefaultCapacity(); @Override boolean equals(Object o); @Override int hashCode(); @Override ShareableResource copy(); @Override String toString(); @Override boolean substituteVM(VM oldRef, VM newRef); int sumConsumptions(Collection<VM> ids, boolean undef); int sumCapacities(Collection<Node> ids, boolean undef); static ShareableResource get(Model mo, String id); static final String VIEW_ID_BASE; static final int DEFAULT_NO_VALUE; }### Answer: @Test(dependsOnMethods = {"testInstantiation"}) public void testEqualsAndHashCode() { ShareableResource rc1 = new ShareableResource("foo"); ShareableResource rc2 = new ShareableResource("foo"); ShareableResource rc3 = new ShareableResource("bar"); Assert.assertEquals(rc1, rc2); Assert.assertEquals(rc2, rc2); Assert.assertEquals(rc1.hashCode(), rc2.hashCode()); Assert.assertNotEquals(rc1, rc3); Assert.assertNotEquals(rc3, rc2); Assert.assertNotEquals(rc1.hashCode(), rc3.hashCode()); Assert.assertNotEquals(rc1, "foo"); }
### Question: BanConverter implements ConstraintConverter<Ban> { @Override public String getJSONId() { return "ban"; } @Override Class<Ban> getSupportedConstraint(); @Override String getJSONId(); @Override Ban fromJSON(Model mo, JSONObject o); @Override JSONObject toJSON(Ban o); }### Answer: @Test public void testBundle() { Assert.assertTrue(ConstraintsConverter.newBundle().getSupportedJavaConstraints().contains(Ban.class)); Assert.assertTrue(ConstraintsConverter.newBundle().getSupportedJSONConstraints().contains(new BanConverter().getJSONId())); }
### Question: TimeBasedPlanApplier extends DefaultPlanApplier { @Override public Model apply(ReconfigurationPlan p) { Model res = p.getOrigin().copy(); List<Action> actions = new ArrayList<>(p.getActions()); actions.sort(startFirstComparator); for (Action a : actions) { if (!a.apply(res)) { return null; } fireAction(a); } return res; } @Override Model apply(ReconfigurationPlan p); @Override String toString(ReconfigurationPlan p); }### Answer: @Test public void testApply() { Model mo = new DefaultModel(); List<VM> vms = Util.newVMs(mo, 10); List<Node> ns = Util.newNodes(mo, 10); ReconfigurationPlan plan = makePlan(mo, ns, vms); Model res = new DependencyBasedPlanApplier().apply(plan); Mapping resMapping = res.getMapping(); Assert.assertTrue(resMapping.isOffline(ns.get(0))); Assert.assertTrue(resMapping.isOnline(ns.get(3))); ShareableResource rc = ShareableResource.get(res, "cpu"); Assert.assertEquals(rc.getConsumption(vms.get(2)), 7); Assert.assertEquals(resMapping.getVMLocation(vms.get(0)), ns.get(3)); Assert.assertEquals(resMapping.getVMLocation(vms.get(1)), ns.get(1)); Assert.assertEquals(resMapping.getVMLocation(vms.get(3)), ns.get(2)); }
### Question: TimeBasedPlanApplier extends DefaultPlanApplier { @Override public String toString(ReconfigurationPlan p) { Set<Action> sorted = new TreeSet<>(new TimedBasedActionComparator(true, true)); sorted.addAll(p.getActions()); StringBuilder b = new StringBuilder(); for (Action a : sorted) { b.append(a.getStart()).append(':').append(a.getEnd()).append(' ').append(a.toString()).append('\n'); } return b.toString(); } @Override Model apply(ReconfigurationPlan p); @Override String toString(ReconfigurationPlan p); }### Answer: @Test public void testToString() { Model mo = new DefaultModel(); List<VM> vms = Util.newVMs(mo, 10); List<Node> ns = Util.newNodes(mo, 10); ReconfigurationPlan plan = makePlan(mo, ns, vms); Assert.assertFalse(new DependencyBasedPlanApplier().toString(plan).contains("null")); }
### Question: DefaultReconfigurationPlanMonitor implements ReconfigurationPlanMonitor { @Override public Set<Action> commit(Action a) { Set<Action> s = new HashSet<>(); synchronized (lock) { boolean ret = a.apply(curModel); if (!ret) { throw new InfeasibleActionException(curModel, a); } nbCommitted++; Set<Dependency> deps = pre.get(a); if (deps != null) { for (Dependency dep : deps) { Set<Action> actions = dep.getDependencies(); actions.remove(a); if (actions.isEmpty()) { Action x = dep.getAction(); s.add(x); } } } } return s; } DefaultReconfigurationPlanMonitor(ReconfigurationPlan p); @Override Model getCurrentModel(); @Override Set<Action> commit(Action a); @Override int getNbCommitted(); @Override boolean isBlocked(Action a); @Override ReconfigurationPlan getReconfigurationPlan(); }### Answer: @Test(dependsOnMethods = {"testInit", "testGoodCommits"}, expectedExceptions = InfeasibleActionException.class) public void testCommitBlocked() { ReconfigurationPlan plan = makePlan(); ReconfigurationPlanMonitor exec = new DefaultReconfigurationPlanMonitor(plan); exec.commit(a3); } @Test(dependsOnMethods = {"testInit", "testGoodCommits"}, expectedExceptions = InfeasibleActionException.class) public void testDoubleCommit() { ReconfigurationPlan plan = makePlan(); ReconfigurationPlanMonitor exec = new DefaultReconfigurationPlanMonitor(plan); Assert.assertNotNull(exec.commit(a1)); exec.commit(a1); }