method2testcases
stringlengths 118
3.08k
|
---|
### Question:
AbstractBFEmptinessOracle extends AbstractBFOracle<A, I, D> implements EmptinessOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { return super.findCounterExample(hypothesis, inputs); } protected AbstractBFEmptinessOracle(MembershipOracle<I, D> membershipOracle, double multiplier); @Override boolean isCounterExample(A hypothesis, Iterable<? extends I> inputs, @Nullable D output); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); }### Answer:
@Test public void testFindCounterExample() { final DefaultQuery<Character, D> cex = bfeo.findCounterExample(automaton, ALPHABET); Assert.assertEquals(cex, query); } |
### Question:
AbstractBFEmptinessOracle extends AbstractBFOracle<A, I, D> implements EmptinessOracle<A, I, D> { @Override public boolean isCounterExample(A hypothesis, Iterable<? extends I> inputs, @Nullable D output) { return EmptinessOracle.super.isCounterExample(hypothesis, inputs, output); } protected AbstractBFEmptinessOracle(MembershipOracle<I, D> membershipOracle, double multiplier); @Override boolean isCounterExample(A hypothesis, Iterable<? extends I> inputs, @Nullable D output); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); }### Answer:
@Test public void testIsCounterExample() { bfeo.isCounterExample(automaton, query.getInput(), query.getOutput()); } |
### Question:
DisproveFirstOracle implements BlackBoxOracle<A, I, D> { @Override public List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles() { return propertyOracles; } DisproveFirstOracle(); DisproveFirstOracle(PropertyOracle<I, ? super A, ?, D> propertyOracle); DisproveFirstOracle(Collection<? extends PropertyOracle<I, ? super A, ?, D>> propertyOracles); @Override List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles(); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); }### Answer:
@Test public void testGetPropertyOracles() { Assert.assertEquals(oracle.getPropertyOracles().size(), 2); } |
### Question:
DisproveFirstOracle implements BlackBoxOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { for (PropertyOracle<I, ? super A, ?, D> po : propertyOracles) { if (!po.isDisproved()) { po.disprove(hypothesis, inputs); } } for (PropertyOracle<I, ? super A, ?, D> po : propertyOracles) { if (!po.isDisproved()) { final DefaultQuery<I, D> ce = po.doFindCounterExample(hypothesis, inputs); if (ce != null) { assert isCounterExample(hypothesis, ce.getInput(), ce.getOutput()); return ce; } } } return null; } DisproveFirstOracle(); DisproveFirstOracle(PropertyOracle<I, ? super A, ?, D> propertyOracle); DisproveFirstOracle(Collection<? extends PropertyOracle<I, ? super A, ?, D>> propertyOracles); @Override List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles(); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); }### Answer:
@Test public void testFindCounterExample() { final DefaultQuery<Boolean, Boolean> ce = oracle.findCounterExample(automaton, inputs); Assert.assertEquals(ce, query); Mockito.verify(po1, Mockito.times(1)).disprove(automaton, inputs); Mockito.verify(po2).disprove(automaton, inputs); Mockito.verify(po2, Mockito.never()).doFindCounterExample(automaton, inputs); } |
### Question:
AbstractBFInclusionOracle extends AbstractBFOracle<A, I, D> implements InclusionOracle<A, I, D> { @Override public boolean isCounterExample(A hypothesis, Iterable<? extends I> inputs, D output) { return InclusionOracle.super.isCounterExample(hypothesis, inputs, output); } AbstractBFInclusionOracle(MembershipOracle<I, D> membershipOracle, double multiplier); @Override boolean isCounterExample(A hypothesis, Iterable<? extends I> inputs, D output); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); }### Answer:
@Test public void testIsCounterExample() { Assert.assertTrue(bfio.isCounterExample(automaton, query.getInput(), query.getOutput())); } |
### Question:
TagUtil { static String byteHexDirName(int majorRevision) { if (majorRevision <= 0) { throw new IllegalArgumentException("invalid majorRevision " + majorRevision + " (expected: > 0)"); } final StringBuilder sb = new StringBuilder(16); final int shift = 8; do { sb.append(TABLE[majorRevision & 0xFF]); majorRevision >>>= shift; } while (majorRevision != 0); return sb.toString(); } private TagUtil(); }### Answer:
@Test void testByteHexDirName() { assertThat(TagUtil.byteHexDirName(0x00000001)).isEqualTo("01/"); assertThat(TagUtil.byteHexDirName(0x00000b0a)).isEqualTo("0a/0b/"); assertThat(TagUtil.byteHexDirName(0x000c0b0a)).isEqualTo("0a/0b/0c/"); assertThat(TagUtil.byteHexDirName(0x0d0c0b0a)).isEqualTo("0a/0b/0c/0d/"); }
@Test void testByteHexDirNameException() { assertThatIllegalArgumentException() .isThrownBy(() -> TagUtil.byteHexDirName(0)); assertThatIllegalArgumentException() .isThrownBy(() -> TagUtil.byteHexDirName(-1)); } |
### Question:
JsonPatch implements JsonSerializable { public JsonNode apply(final JsonNode node) { requireNonNull(node, "node"); JsonNode ret = node.deepCopy(); for (final JsonPatchOperation operation : operations) { ret = operation.apply(ret); } return ret; } @JsonCreator JsonPatch(final List<JsonPatchOperation> operations); static JsonPatch fromJson(final JsonNode node); static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode); boolean isEmpty(); List<JsonPatchOperation> operations(); JsonNode apply(final JsonNode node); ArrayNode toJson(); @Override String toString(); @Override void serialize(final JsonGenerator jgen, final SerializerProvider provider); @Override void serializeWithType(final JsonGenerator jgen,
final SerializerProvider provider, final TypeSerializer typeSer); }### Answer:
@Test void cannotPatchNull() { final JsonPatch patch = new JsonPatch(ImmutableList.of(op1, op2)); assertThatNullPointerException() .isThrownBy(() -> patch.apply(null)); }
@Test void operationsAreCalledInOrder() { final JsonNode node1 = FACTORY.textNode("hello"); final JsonNode node2 = FACTORY.textNode("world"); when(op1.apply(node1)).thenReturn(node2); final JsonPatch patch = new JsonPatch(ImmutableList.of(op1, op2)); final ArgumentCaptor<JsonNode> captor = ArgumentCaptor.forClass(JsonNode.class); patch.apply(node1); verify(op1, only()).apply(same(node1)); verify(op2, only()).apply(captor.capture()); assertThat(captor.getValue()).isSameAs(node2); }
@Test void whenOneOperationFailsNextOperationIsNotCalled() { final String message = "foo"; when(op1.apply(any(JsonNode.class))) .thenThrow(new JsonPatchException(message)); final JsonPatch patch = new JsonPatch(ImmutableList.of(op1, op2)); assertThatThrownBy(() -> patch.apply(FACTORY.nullNode())) .isInstanceOf(JsonPatchException.class) .hasMessage(message); verifyNoMoreInteractions(op2); } |
### Question:
PublicKeyMirrorCredential extends AbstractMirrorCredential { @Nullable public byte[] passphrase() { if (passphrase == null) { return null; } else { return passphrase.clone(); } } @JsonCreator PublicKeyMirrorCredential(@JsonProperty("id") @Nullable String id,
@JsonProperty("hostnamePatterns") @Nullable
@JsonDeserialize(contentAs = Pattern.class)
Iterable<Pattern> hostnamePatterns,
@JsonProperty("username") String username,
@JsonProperty("publicKey") String publicKey,
@JsonProperty("privateKey") String privateKey,
@JsonProperty("passphrase") @Nullable String passphrase); PublicKeyMirrorCredential(@Nullable String id,
@Nullable Iterable<Pattern> hostnamePatterns,
String username, byte[] publicKey, byte[] privateKey,
@Nullable byte[] passphrase); String username(); byte[] publicKey(); byte[] privateKey(); @Nullable byte[] passphrase(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test void testBase64Passphrase() { final PublicKeyMirrorCredential c = new PublicKeyMirrorCredential( null, null, USERNAME, PUBLIC_KEY, PRIVATE_KEY, PASSPHRASE_BASE64); assertThat(c.passphrase()).isEqualTo(PASSPHRASE.getBytes(StandardCharsets.UTF_8)); } |
### Question:
ExpiredSessionDeletingSessionManager extends ForwardingSessionManager { @Override public CompletableFuture<Session> get(String sessionId) { return super.get(sessionId).thenApply(session -> { if (session != null) { if (Instant.now().isBefore(session.expirationTime())) { return session; } delete(sessionId); } return null; }); } ExpiredSessionDeletingSessionManager(SessionManager delegate); @Override CompletableFuture<Session> get(String sessionId); }### Answer:
@Test void shouldReturnNonNull() { final Session expiredAfterOneHour = createSession(Instant.now().plus(1, ChronoUnit.HOURS)); final SessionManager delegate = mock(SessionManager.class); when(delegate.get(any())).thenReturn(CompletableFuture.completedFuture(expiredAfterOneHour)); final ExpiredSessionDeletingSessionManager manager = new ExpiredSessionDeletingSessionManager(delegate); assertThat(manager.get("id").join()).isEqualTo(expiredAfterOneHour); }
@Test void shouldReturnNull() { final Session expiredSession = createSession(Instant.EPOCH); final SessionManager delegate = mock(SessionManager.class); when(delegate.get(any())).thenReturn(CompletableFuture.completedFuture(expiredSession)); final ExpiredSessionDeletingSessionManager manager = new ExpiredSessionDeletingSessionManager(delegate); assertThat(manager.get("id").join()).isNull(); } |
### Question:
WatchTimeout { public static long availableTimeout(long expectedTimeoutMillis) { return availableTimeout(expectedTimeoutMillis, 0); } private WatchTimeout(); static long availableTimeout(long expectedTimeoutMillis); static long availableTimeout(long expectedTimeoutMillis, long currentTimeoutMillis); static final long MAX_MILLIS; }### Answer:
@Test void testMakeReasonable() { assertThat(availableTimeout(1_000, 0)).isEqualTo(1_000); assertThat(availableTimeout(1_000, 1_000)).isEqualTo(1_000); assertThat(availableTimeout(MAX_MILLIS, 1_000)).isEqualTo(MAX_MILLIS - 1_000); assertThat(availableTimeout(MAX_MILLIS + 1_000, 0)).isEqualTo(MAX_MILLIS); assertThat(availableTimeout(MAX_MILLIS - 1_000, 500)).isEqualTo(MAX_MILLIS - 1000); assertThatThrownBy(() -> availableTimeout(0, 1_000)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> availableTimeout(-1, 1_000)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> availableTimeout(1_000, -1)) .isInstanceOf(IllegalArgumentException.class); } |
### Question:
JsonEndpointListDecoder implements EndpointListDecoder<JsonNode> { @Override public List<Endpoint> decode(JsonNode node) { final List<String> endpoints; try { endpoints = objectMapper.readValue(node.traverse(), new TypeReference<List<String>>() {}); } catch (IOException e) { throw new IllegalArgumentException("invalid format: " + node); } return convertToEndpointList(endpoints); } @Override List<Endpoint> decode(JsonNode node); }### Answer:
@Test void decode() throws Exception { final EndpointListDecoder<JsonNode> decoder = EndpointListDecoder.JSON; final List<Endpoint> decoded = decoder.decode( objectMapper.readTree(objectMapper.writeValueAsString(HOST_AND_PORT_LIST))); assertThat(decoded).hasSize(4); assertThat(decoded).isEqualTo(ENDPOINT_LIST); } |
### Question:
TextEndpointListDecoder implements EndpointListDecoder<String> { @Override public List<Endpoint> decode(String object) { return convertToEndpointList(NEWLINE_SPLITTER.splitToList(object)); } @Override List<Endpoint> decode(String object); }### Answer:
@Test void decode() { final EndpointListDecoder<String> decoder = EndpointListDecoder.TEXT; final List<Endpoint> decoded = decoder.decode(String.join("\n", HOST_AND_PORT_LIST)); assertThat(decoded).hasSize(4); assertThat(decoded).isEqualTo(ENDPOINT_LIST); } |
### Question:
ArmeriaCentralDogmaBuilder extends AbstractArmeriaCentralDogmaBuilder<ArmeriaCentralDogmaBuilder> { public CentralDogma build() throws UnknownHostException { final EndpointGroup endpointGroup = endpointGroup(); final String scheme = "none+" + (isUseTls() ? "https" : "http"); final ClientBuilder builder = newClientBuilder(scheme, endpointGroup, cb -> cb.decorator(DecodingClient.newDecorator()), "/"); final EventLoopGroup executor = clientFactory().eventLoopGroup(); final int maxRetriesOnReplicationLag = maxNumRetriesOnReplicationLag(); final CentralDogma dogma = new ArmeriaCentralDogma(executor, builder.build(WebClient.class), accessToken()); if (maxRetriesOnReplicationLag <= 0) { return dogma; } else { return new ReplicationLagTolerantCentralDogma( executor, dogma, maxRetriesOnReplicationLag, retryIntervalOnReplicationLagMillis(), () -> { final ClientRequestContext ctx = ClientRequestContext.currentOrNull(); return ctx != null ? ctx.remoteAddress() : null; }); } } CentralDogma build(); }### Answer:
@Test void newClientBuilderCustomizationOrder() { final ClientFactory cf1 = mock(ClientFactory.class); final ClientFactory cf2 = mock(ClientFactory.class); final ClientFactory cf3 = mock(ClientFactory.class); final ArmeriaCentralDogmaBuilder b = new ArmeriaCentralDogmaBuilder(); final StringBuilder buf = new StringBuilder(); b.clientFactory(cf1); b.clientConfigurator(cb -> { buf.append('2'); cb.factory(cf2); }); final ClientBuilder cb = b.newClientBuilder("none+http", Endpoint.of("127.0.0.1"), cb2 -> { cb2.factory(cf3); buf.append('1'); }, "/"); assertThat(buf.toString()).isEqualTo("12"); cb.build(HttpClient.class); verify(cf1, times(1)).newClient(any()); verify(cf2, never()).newClient(any()); verify(cf3, never()).newClient(any()); } |
### Question:
LegacyCentralDogmaTimeoutScheduler extends SimpleDecoratingRpcClient { @Override public RpcResponse execute(ClientRequestContext ctx, RpcRequest req) throws Exception { final long responseTimeoutMillis = ctx.responseTimeoutMillis(); if (responseTimeoutMillis > 0) { final String method = req.method(); if ("watchFile".equals(method) || "watchRepository".equals(method)) { final List<Object> params = req.params(); final long timeout = (Long) params.get(params.size() - 1); if (timeout > 0) { ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, WatchTimeout.availableTimeout(timeout, responseTimeoutMillis)); } } } return unwrap().execute(ctx, req); } LegacyCentralDogmaTimeoutScheduler(RpcClient delegate); @Override RpcResponse execute(ClientRequestContext ctx, RpcRequest req); }### Answer:
@Test void execute() throws Exception { check("listProjects", 1000L, 1L, 1L); } |
### Question:
Entry implements ContentHolder<T> { public static <T> Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content) { return new Entry<>(revision, path, type, content); } private Entry(Revision revision, String path, EntryType type, @Nullable T content); static Entry<Void> ofDirectory(Revision revision, String path); static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content); static Entry<JsonNode> ofJson(Revision revision, String path, String content); static Entry<String> ofText(Revision revision, String path, String content); static Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content); Revision revision(); String path(); boolean hasContent(); void ifHasContent(Consumer<? super T> consumer); @Override EntryType type(); @Override T content(); @Override String contentAsText(); @Override String contentAsPrettyText(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); }### Answer:
@Test void of() { assertThatThrownBy(() -> Entry.of(null, "/1.txt", EntryType.TEXT, "1")) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> Entry.of(new Revision(1), null, EntryType.TEXT, "1")) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> Entry.of(new Revision(1), "/1.txt", null, "1")) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> Entry.of(new Revision(1), "/1.txt", EntryType.TEXT, null)) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> Entry.of(new Revision(1), "/1.txt", EntryType.TEXT, new Object())) .isInstanceOf(ClassCastException.class); Entry.of(new Revision(1), "/a", EntryType.DIRECTORY, null); assertThatThrownBy(() -> Entry.of(new Revision(1), "/a", EntryType.DIRECTORY, "foo")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("expected: null"); } |
### Question:
Entry implements ContentHolder<T> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Entry)) { return false; } @SuppressWarnings("unchecked") final Entry<T> that = (Entry<T>) o; return type == that.type && revision.equals(that.revision) && path.equals(that.path) && Objects.equals(content, that.content); } private Entry(Revision revision, String path, EntryType type, @Nullable T content); static Entry<Void> ofDirectory(Revision revision, String path); static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content); static Entry<JsonNode> ofJson(Revision revision, String path, String content); static Entry<String> ofText(Revision revision, String path, String content); static Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content); Revision revision(); String path(); boolean hasContent(); void ifHasContent(Consumer<? super T> consumer); @Override EntryType type(); @Override T content(); @Override String contentAsText(); @Override String contentAsPrettyText(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); }### Answer:
@Test void testEquals() { final Entry<Void> e = Entry.ofDirectory(new Revision(1), "/foo"); assertThat(e).isNotEqualTo(null); assertThat(e).isNotEqualTo(new Object()); assertThat(e).isEqualTo(e); } |
### Question:
Entry implements ContentHolder<T> { @Override public String toString() { return MoreObjects.toStringHelper(this).omitNullValues() .add("revision", revision.text()) .add("path", path) .add("type", type) .add("content", hasContent() ? contentAsText() : null) .toString(); } private Entry(Revision revision, String path, EntryType type, @Nullable T content); static Entry<Void> ofDirectory(Revision revision, String path); static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content); static Entry<JsonNode> ofJson(Revision revision, String path, String content); static Entry<String> ofText(Revision revision, String path, String content); static Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content); Revision revision(); String path(); boolean hasContent(); void ifHasContent(Consumer<? super T> consumer); @Override EntryType type(); @Override T content(); @Override String contentAsText(); @Override String contentAsPrettyText(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); }### Answer:
@Test void testToString() { assertThat(Entry.ofText(new Revision(1), "/a.txt", "a").toString()).isNotEmpty(); } |
### Question:
CreateProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator CreateProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName); @JsonProperty String projectName(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test void backwardCompatibility() throws Exception { final CreateProjectCommand c = (CreateProjectCommand) Jackson.readValue( '{' + " \"type\": \"CREATE_PROJECT\"," + " \"projectName\": \"foo\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); } |
### Question:
PurgeProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator PurgeProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName); @JsonProperty String projectName(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test void backwardCompatibility() throws Exception { final PurgeProjectCommand c = (PurgeProjectCommand) Jackson.readValue( '{' + " \"type\": \"PURGE_PROJECT\"," + " \"projectName\": \"foo\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); } |
### Question:
RemoveProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator RemoveProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName); @JsonProperty String projectName(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test void backwardCompatibility() throws Exception { final RemoveProjectCommand c = (RemoveProjectCommand) Jackson.readValue( '{' + " \"type\": \"REMOVE_PROJECT\"," + " \"projectName\": \"foo\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); } |
### Question:
PurgeRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator PurgeRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName,
@JsonProperty("repositoryName") String repositoryName); @JsonProperty String repositoryName(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test void backwardCompatibility() throws Exception { final PurgeRepositoryCommand c = (PurgeRepositoryCommand) Jackson.readValue( '{' + " \"type\": \"PURGE_REPOSITORY\"," + " \"projectName\": \"foo\"," + " \"repositoryName\": \"bar\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); assertThat(c.repositoryName()).isEqualTo("bar"); } |
### Question:
RemoveRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator RemoveRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName,
@JsonProperty("repositoryName") String repositoryName); @JsonProperty String repositoryName(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test void backwardCompatibility() throws Exception { final RemoveRepositoryCommand c = (RemoveRepositoryCommand) Jackson.readValue( '{' + " \"type\": \"REMOVE_REPOSITORY\"," + " \"projectName\": \"foo\"," + " \"repositoryName\": \"bar\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); assertThat(c.repositoryName()).isEqualTo("bar"); } |
### Question:
CreateRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator CreateRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName,
@JsonProperty("repositoryName") String repositoryName); @JsonProperty String repositoryName(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test void backwardCompatibility() throws Exception { final CreateRepositoryCommand c = (CreateRepositoryCommand) Jackson.readValue( '{' + " \"type\": \"CREATE_REPOSITORY\"," + " \"projectName\": \"foo\"," + " \"repositoryName\": \"bar\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); assertThat(c.repositoryName()).isEqualTo("bar"); } |
### Question:
UnremoveRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator UnremoveRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName,
@JsonProperty("repositoryName") String repositoryName); @JsonProperty String repositoryName(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test void backwardCompatibility() throws Exception { final UnremoveRepositoryCommand c = (UnremoveRepositoryCommand) Jackson.readValue( '{' + " \"type\": \"UNREMOVE_REPOSITORY\"," + " \"projectName\": \"foo\"," + " \"repositoryName\": \"bar\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); assertThat(c.repositoryName()).isEqualTo("bar"); } |
### Question:
UnremoveProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator UnremoveProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName); @JsonProperty String projectName(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test void backwardCompatibility() throws Exception { final UnremoveProjectCommand c = (UnremoveProjectCommand) Jackson.readValue( '{' + " \"type\": \"UNREMOVE_PROJECT\"," + " \"projectName\": \"foo\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); } |
### Question:
ProjectServiceV1 extends AbstractService { @Delete("/projects/{projectName}") @RequiresRole(roles = ProjectRole.OWNER) public CompletableFuture<Void> removeProject(Project project, Author author) { return mds.removeProject(author, project.name()) .thenCompose(unused -> execute(Command.removeProject(author, project.name()))) .handle(HttpApiUtil::throwUnsafelyIfNonNull); } ProjectServiceV1(ProjectManager projectManager, CommandExecutor executor, MetadataService mds); @Get("/projects") CompletableFuture<List<ProjectDto>> listProjects(@Param @Nullable String status); @Post("/projects") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) CompletableFuture<ProjectDto> createProject(CreateProjectRequest request, Author author); @Get("/projects/{projectName}") @RequiresRole(roles = { ProjectRole.OWNER, ProjectRole.MEMBER }) CompletableFuture<ProjectMetadata> getProjectMetadata(
@Param String projectName,
@Param("checkPermissionOnly") @Default("false") boolean isCheckPermissionOnly); @Delete("/projects/{projectName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> removeProject(Project project, Author author); @Delete("/projects/{projectName}/removed") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> purgeProject(@Param String projectName, Author author); @Consumes("application/json-patch+json") @Patch("/projects/{projectName}") @RequiresAdministrator CompletableFuture<ProjectDto> patchProject(@Param String projectName, JsonNode node, Author author); }### Answer:
@Test void removeProject() { final WebClient client = dogma.httpClient(); createProject(client, "foo"); final AggregatedHttpResponse aRes = client.delete(PROJECTS_PREFIX + "/foo") .aggregate().join(); final ResponseHeaders headers = ResponseHeaders.of(aRes.headers()); assertThat(ResponseHeaders.of(headers).status()).isEqualTo(HttpStatus.NO_CONTENT); } |
### Question:
ProjectServiceV1 extends AbstractService { @Delete("/projects/{projectName}/removed") @RequiresRole(roles = ProjectRole.OWNER) public CompletableFuture<Void> purgeProject(@Param String projectName, Author author) { return execute(Command.purgeProject(author, projectName)) .handle(HttpApiUtil::throwUnsafelyIfNonNull); } ProjectServiceV1(ProjectManager projectManager, CommandExecutor executor, MetadataService mds); @Get("/projects") CompletableFuture<List<ProjectDto>> listProjects(@Param @Nullable String status); @Post("/projects") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) CompletableFuture<ProjectDto> createProject(CreateProjectRequest request, Author author); @Get("/projects/{projectName}") @RequiresRole(roles = { ProjectRole.OWNER, ProjectRole.MEMBER }) CompletableFuture<ProjectMetadata> getProjectMetadata(
@Param String projectName,
@Param("checkPermissionOnly") @Default("false") boolean isCheckPermissionOnly); @Delete("/projects/{projectName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> removeProject(Project project, Author author); @Delete("/projects/{projectName}/removed") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> purgeProject(@Param String projectName, Author author); @Consumes("application/json-patch+json") @Patch("/projects/{projectName}") @RequiresAdministrator CompletableFuture<ProjectDto> patchProject(@Param String projectName, JsonNode node, Author author); }### Answer:
@Test void purgeProject() { removeProject(); final WebClient client = dogma.httpClient(); final AggregatedHttpResponse aRes = client.delete(PROJECTS_PREFIX + "/foo/removed") .aggregate().join(); final ResponseHeaders headers = ResponseHeaders.of(aRes.headers()); assertThat(ResponseHeaders.of(headers).status()).isEqualTo(HttpStatus.NO_CONTENT); } |
### Question:
RemoveOperation extends JsonPatchOperation { @Override JsonNode apply(final JsonNode node) { if (path.toString().isEmpty()) { return MissingNode.getInstance(); } ensureExistence(node); final JsonNode parentNode = node.at(path.head()); final String raw = path.last().getMatchingProperty(); if (parentNode.isObject()) { ((ObjectNode) parentNode).remove(raw); } else { ((ArrayNode) parentNode).remove(Integer.parseInt(raw)); } return node; } @JsonCreator RemoveOperation(@JsonProperty("path") final JsonPointer path); @Override void serialize(final JsonGenerator jgen,
final SerializerProvider provider); @Override void serializeWithType(final JsonGenerator jgen,
final SerializerProvider provider, final TypeSerializer typeSer); @Override String toString(); }### Answer:
@Test void removingRootReturnsMissingNode() { final JsonNode node = JsonNodeFactory.instance.nullNode(); final JsonPatchOperation op = new RemoveOperation(EMPTY_JSON_POINTER); final JsonNode ret = op.apply(node); assertThat(ret.isMissingNode()).isTrue(); } |
### Question:
RemoveIfExistsOperation extends JsonPatchOperation { @Override JsonNode apply(final JsonNode node) { if (path.toString().isEmpty()) { return MissingNode.getInstance(); } final JsonNode found = node.at(path); if (found.isMissingNode()) { return node; } final JsonNode parentNode = node.at(path.head()); final String raw = path.last().getMatchingProperty(); if (parentNode.isObject()) { ((ObjectNode) parentNode).remove(raw); } else if (parentNode.isArray()) { ((ArrayNode) parentNode).remove(Integer.parseInt(raw)); } return node; } @JsonCreator RemoveIfExistsOperation(@JsonProperty("path") final JsonPointer path); @Override void serialize(final JsonGenerator jgen,
final SerializerProvider provider); @Override void serializeWithType(final JsonGenerator jgen,
final SerializerProvider provider, final TypeSerializer typeSer); @Override String toString(); }### Answer:
@Test void removingRootReturnsMissingNode() { final JsonNode node = JsonNodeFactory.instance.nullNode(); final JsonPatchOperation op = new RemoveIfExistsOperation(EMPTY_JSON_POINTER); final JsonNode ret = op.apply(node); assertThat(ret.isMissingNode()).isTrue(); } |
### Question:
PurgeSchedulingService { @VisibleForTesting void purgeProjectAndRepository(CommandExecutor commandExecutor, MetadataService metadataService) { final long minAllowedTimestamp = System.currentTimeMillis() - maxRemovedRepositoryAgeMillis; final Predicate<Instant> olderThanMinAllowed = removedAt -> removedAt.toEpochMilli() < minAllowedTimestamp; purgeProject(commandExecutor, olderThanMinAllowed); purgeRepository(commandExecutor, metadataService, olderThanMinAllowed); } PurgeSchedulingService(ProjectManager projectManager, ScheduledExecutorService purgeWorker,
long maxRemovedRepositoryAgeMillis); void start(CommandExecutor commandExecutor,
MetadataService metadataService); boolean isStarted(); void stop(); }### Answer:
@Test void testSchedule() throws InterruptedException { Thread.sleep(10); service.purgeProjectAndRepository(manager.executor(), metadataService); verify(manager.executor()).execute(isA(PurgeProjectCommand.class)); verify(manager.executor()).execute(isA(PurgeRepositoryCommand.class)); } |
### Question:
RepositoryManagerWrapper implements RepositoryManager { @Override public Repository create(String name, long creationTimeMillis, Author author) { return repos.compute( name, (n, v) -> repoWrapper.apply(delegate.create(name, creationTimeMillis, author))); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); }### Answer:
@Test void create(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); final Repository repo = m.create(name, Author.SYSTEM); assertThat(repo).isInstanceOf(RepositoryWrapper.class); assertThatThrownBy(() -> m.create(name, Author.SYSTEM)).isInstanceOf(RepositoryExistsException.class); } |
### Question:
RepositoryManagerWrapper implements RepositoryManager { @Override public Repository get(String name) { ensureOpen(); final Repository r = repos.get(name); if (r == null) { throw new RepositoryNotFoundException(name); } return r; } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); }### Answer:
@Test void get(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); final Repository repo = m.create(name, Author.SYSTEM); final Repository repo2 = m.get(name); assertThat(repo).isSameAs(repo2); } |
### Question:
RepositoryManagerWrapper implements RepositoryManager { @Override public void remove(String name) { repos.compute(name, (n, v) -> { delegate.remove(n); return null; }); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); }### Answer:
@Test void remove(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); m.create(name, Author.SYSTEM); m.remove(name); assertThat(m.exists(name)).isFalse(); }
@Test void remove_failure(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); assertThatThrownBy(() -> m.remove(name)).isInstanceOf(RepositoryNotFoundException.class); } |
### Question:
RepositoryManagerWrapper implements RepositoryManager { @Override public Repository unremove(String name) { ensureOpen(); return repos.computeIfAbsent(name, n -> repoWrapper.apply(delegate.unremove(n))); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); }### Answer:
@Test void unremove_failure(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); assertThatThrownBy(() -> m.unremove(name)).isInstanceOf(RepositoryNotFoundException.class); } |
### Question:
RepositoryManagerWrapper implements RepositoryManager { @Override public Map<String, Repository> list() { ensureOpen(); final int estimatedSize = repos.size(); final String[] names = repos.keySet().toArray(new String[estimatedSize]); Arrays.sort(names); final Map<String, Repository> ret = new LinkedHashMap<>(names.length); for (String name : names) { final Repository repo = repos.get(name); if (repo != null) { ret.put(name, repo); } } return Collections.unmodifiableMap(ret); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); }### Answer:
@Test void list(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); final int numNames = 10; for (int i = 0; i < numNames; i++) { m.create(name + i, Author.SYSTEM); } final List<String> names = new ArrayList<>(m.list().keySet()); for (int i = 0; i < numNames - 1; i++) { if (names.get(i).compareTo(names.get(i + 1)) > 0) { fail("names is not in ascending order"); } } } |
### Question:
RepositoryManagerWrapper implements RepositoryManager { @Override public void markForPurge(String name) { repos.compute(name, (n, v) -> { delegate.markForPurge(name); return null; }); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); }### Answer:
@Test void markForPurge(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); m.create(name, Author.SYSTEM); m.remove(name); m.markForPurge(name); verify(purgeWorker).execute(any()); assertThat(m.listRemoved().keySet()).doesNotContain(name); } |
### Question:
RepositoryManagerWrapper implements RepositoryManager { @Override public void purgeMarked() { delegate.purgeMarked(); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); }### Answer:
@Test void purgeMarked(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); final int numNames = 10; for (int i = 0; i < numNames; i++) { final String targetName = name + i; m.create(targetName, Author.SYSTEM); m.remove(targetName); m.markForPurge(targetName); } m.purgeMarked(); for (int i = 0; i < numNames; i++) { final String targetName = name + i; assertThatThrownBy(() -> m.get(targetName)).isInstanceOf(RepositoryNotFoundException.class); } } |
### Question:
RepositoryManagerWrapper implements RepositoryManager { @Override public void close(Supplier<CentralDogmaException> failureCauseSupplier) { delegate.close(failureCauseSupplier); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); }### Answer:
@Test void close(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); m.create(name, Author.SYSTEM); assertThat(m.exists(name)).isTrue(); m.close(ShuttingDownException::new); assertThatThrownBy(() -> m.get(name)).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.exists(name)).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.remove(name)).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.unremove(name)).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.list()).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.listRemoved()).isInstanceOf(ShuttingDownException.class); } |
### Question:
JsonPatch implements JsonSerializable { public static JsonPatch fromJson(final JsonNode node) throws IOException { requireNonNull(node, "node"); try { return Jackson.treeToValue(node, JsonPatch.class); } catch (JsonMappingException e) { throw new JsonPatchException("invalid JSON patch", e); } } @JsonCreator JsonPatch(final List<JsonPatchOperation> operations); static JsonPatch fromJson(final JsonNode node); static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode); boolean isEmpty(); List<JsonPatchOperation> operations(); JsonNode apply(final JsonNode node); ArrayNode toJson(); @Override String toString(); @Override void serialize(final JsonGenerator jgen, final SerializerProvider provider); @Override void serializeWithType(final JsonGenerator jgen,
final SerializerProvider provider, final TypeSerializer typeSer); }### Answer:
@Test void nullInputsDuringBuildAreRejected() { assertThatNullPointerException() .isThrownBy(() -> JsonPatch.fromJson(null)); } |
### Question:
AbstractCommunicator implements Communicator { @Override public void start() { queue.clear(); try { mainThread.start(); } catch (IllegalThreadStateException e) { if (!mainThread.isAlive()) { mainThread = new Thread(this, getClass().getSimpleName()); mainThread.start(); } else { log("Thread " + mainThread.getName() + " is already running."); } } } protected AbstractCommunicator(int port); @Override void run(); @Override void setState(MopedState state); @Override void setValue(MopedDataType type, int value); @Override void addListener(CommunicationListener cl); @Override void start(); @Override void stop(); boolean isRunning(); boolean isLoggingEnabled(); void enableLogging(); void disableLogging(); }### Answer:
@Test public void testMultipleStarts() { try { Communicator server = new ServerCommunicator(45756); Communicator client = new ClientCommunicator("0.0.0.0", 45756); server.start(); server.start(); Thread.sleep(100); client.start(); client.start(); server.start(); client.start(); } catch (InterruptedException e) { e.printStackTrace(); } } |
### Question:
CarControlImpl implements CarControl { @Override public synchronized void addThrottle(int value) { setThrottle(currentThrottleValue + value); } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); }### Answer:
@Test void addThrottle() { carControl.addThrottle(1); assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE + 1); } |
### Question:
CarControlImpl implements CarControl { @Override public synchronized void addSteer(int value) { setSteerValue(currentSteerValue + value); } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); }### Answer:
@Test void addSteer() { carControl.addSteer(1); assertEquals(carControl.getLastSteer(), STEER_VALUE + 1); } |
### Question:
StreamReader extends Thread { void setOnInputRead(Consumer<String> consumer) { this.onInputRead = consumer; } StreamReader(InputStream inputStream); @Override void run(); }### Answer:
@Test void testOnDataRead() { final String data = "A"; List<String> receivedData = new ArrayList<>(); Consumer c = new Consumer(receivedData); InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); StreamReader reader = new StreamReader(stream); reader.setOnInputRead(c::stringRecieved); reader.start(); try { reader.join(); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals(receivedData.get(0), data); assertEquals(receivedData.get(1), String.valueOf((char) -1)); } |
### Question:
DistanceSensorImpl implements DistanceSensor { @Override public double getDistance() { return currentSensorValue; } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); }### Answer:
@Test void getDistance(){ sensorInstance.receivedString("1.0\n",new StringBuilder()); assertEquals(0.7,sensorInstance.getDistance(), 0.01); }
@Test void testRecieveData() { CommunicationsMediator cm = new CommunicationsMediator() { private DataReceiver distanceSensor; @Override public void transmitData(String data, Direction direction) { distanceSensor.dataReceived(data); } @Override public void subscribe(Direction direction, DataReceiver receiver) { distanceSensor = receiver; } @Override public void unsubscribe(Direction direction, DataReceiver receiver) { } }; DistanceSensor ds = new DistanceSensorImpl(cm, ardMock, new LowPassFilter(LP_WEIGHT)); cm.transmitData(CAM_TGT_DIST + ",1.0\n", Direction.INTERNAL); assertEquals(0.7, ds.getDistance(),0.01); } |
### Question:
DistanceSensorImpl implements DistanceSensor { @Override public double getValue() { return getDistance(); } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); }### Answer:
@Test void getValue(){ sensorInstance.receivedString("1.0\n",new StringBuilder()); assertEquals(0.7,sensorInstance.getValue(), 0.01); } |
### Question:
DistanceSensorImpl implements DistanceSensor { @Override public void subscribe(Consumer<Double> dataConsumer) { dataConsumers.add(dataConsumer); } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); }### Answer:
@Test @DisplayName("should subscribe a consumer") void subscribe() { Consumer<Double> consumer = new ConsumerImpl(); Consumer<Double> consumerSpy = spy(consumer); StringBuilder sb = new StringBuilder(); sensorInstance.subscribe(consumerSpy); sensorInstance.receivedString("0.3\n", sb); verify(consumerSpy, times(1)).accept(any()); } |
### Question:
DistanceSensorImpl implements DistanceSensor { @Override public void unsubscribe(Consumer<Double> dataConsumer) { dataConsumers.remove(dataConsumer); } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); }### Answer:
@Test @DisplayName("should unsubscribe a consumer") void unsubscribe() { Consumer<Double> consumer = new ConsumerImpl(); Consumer<Double> consumerSpy = spy(consumer); StringBuilder sb = new StringBuilder(); sensorInstance.subscribe(consumerSpy); sensorInstance.receivedString("0.3\n", sb); verify(consumerSpy, times(1)).accept(any()); sensorInstance.unsubscribe(consumerSpy); sensorInstance.receivedString("0.3\n", sb); verify(consumerSpy, times(1)).accept(any()); } |
### Question:
CommunicationsMediatorImpl implements CommunicationsMediator { @Override public void transmitData(String data, Direction direction) { for (DataReceiver dataReceiver : this.subscribers.get(direction)) { dataReceiver.dataReceived(data); } } CommunicationsMediatorImpl(); @Override void transmitData(String data, Direction direction); @Override void subscribe(Direction direction, DataReceiver receiver); @Override void unsubscribe(Direction direction, DataReceiver receiver); }### Answer:
@Test @DisplayName("should transmit data to receivers") void transmitData() { final int[] called = new int[1]; called[0] = 0; DataReceiver receiver1 = new DataReceiver() { int[] call = called; @Override public void dataReceived(String data) { call[0]++; } }; DataReceiver receiver2 = new DataReceiver() { int[] call = called; @Override public void dataReceived(String data) { call[0]++; } }; DataReceiver receiver3 = new DataReceiver() { int[] call = called; @Override public void dataReceived(String data) { call[0]++; } }; comInstance.subscribe(Direction.INTERNAL, receiver1); comInstance.subscribe(Direction.INTERNAL, receiver2); comInstance.subscribe(Direction.INTERNAL, receiver3); comInstance.transmitData(value, Direction.INTERNAL); assertEquals(3, called[0]); } |
### Question:
DistanceSensorImpl implements DistanceSensor { synchronized void receivedString(String string, StringBuilder sb) { for (char c : string.toCharArray()) { if (c != 10 && c != 13) { sb.append(c); } else { setCurrentSensorValue(sb.toString()); sb.delete(0, sb.length()); } } } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); }### Answer:
@Test @DisplayName("should build string from input") void receivedString() { StringBuilder sb = new StringBuilder(); sensorInstance.receivedString("100", sb); assertEquals("100", sb.toString()); }
@Test @DisplayName("should reset the StringBuilder on new line") void receivedString2() { StringBuilder sb = new StringBuilder(); sensorInstance.receivedString("100\n", sb); assertEquals("", sb.toString()); } |
### Question:
CommunicationsMediatorImpl implements CommunicationsMediator { @Override public void subscribe(Direction direction, DataReceiver receiver) { List<DataReceiver> dataReceivers = this.subscribers.get(direction); if (!dataReceivers.contains(receiver)) { dataReceivers.add(receiver); } } CommunicationsMediatorImpl(); @Override void transmitData(String data, Direction direction); @Override void subscribe(Direction direction, DataReceiver receiver); @Override void unsubscribe(Direction direction, DataReceiver receiver); }### Answer:
@Test @DisplayName("should add DataReceiver as a subscriber") void subscribe() { DataReceiver receiver = new DataReceiver() { @Override public void dataReceived(String data) { assertEquals(value, data); } }; comInstance.subscribe(Direction.INTERNAL, receiver); comInstance.transmitData(value, Direction.INTERNAL); } |
### Question:
CommunicationsMediatorImpl implements CommunicationsMediator { @Override public void unsubscribe(Direction direction, DataReceiver receiver) { int index = -1; List<DataReceiver> receivers = this.subscribers.get(direction); for (int i = 0; i < receivers.size(); i++) { DataReceiver dataReceiver = receivers.get(i); if (dataReceiver == receiver) { index = i; } } if (index != -1) { receivers.remove(index); } } CommunicationsMediatorImpl(); @Override void transmitData(String data, Direction direction); @Override void subscribe(Direction direction, DataReceiver receiver); @Override void unsubscribe(Direction direction, DataReceiver receiver); }### Answer:
@Test @DisplayName("should unsubscribe a subscribing receiver") void unsubscribe() { DataReceiver receiver = new DataReceiver() { @Override public void dataReceived(String data) { assert false; } }; comInstance.subscribe(Direction.INTERNAL, receiver); comInstance.unsubscribe(Direction.INTERNAL, receiver); comInstance.transmitData(value, Direction.INTERNAL); } |
### Question:
StrToDoubleConverter { public double convertStringToDouble(String input) { if (input.matches("[0-9.-]+")) { double convertedDistance = Double.valueOf(input); return convertedDistance; } else { return NaN; } } double convertStringToDouble(String input); }### Answer:
@Test public void convertDistanceTest(){ StrToDoubleConverter strToDoubleConverter = new StrToDoubleConverter(); assertEquals(Double.NaN, strToDoubleConverter.convertStringToDouble("ASD"),0.01); assertEquals(-1, strToDoubleConverter.convertStringToDouble("-1"), 0.01); assertEquals(23.3, strToDoubleConverter.convertStringToDouble("23.3"),0.01); } |
### Question:
EngineDataConverter { public int convertToMotorValue( double throttle){ double smallestDifference = Double.POSITIVE_INFINITY; int r = 0; for (int i: validMotorValues) { System.out.println(i); double difference = Math.abs(i - throttle); if (smallestDifference > difference){ smallestDifference = difference; r = i; }else if (smallestDifference == difference && throttle < i){ r = i; } } return r; } EngineDataConverter(int[] validMotorValues); int convertToMotorValue( double throttle); }### Answer:
@Test void convertToMotorValue(){ int [] motorValues = {1,2,3,4,5,6,7,8,9,10}; EngineDataConverter EDC = new EngineDataConverter(motorValues); assertEquals(1,EDC.convertToMotorValue(1.2)); assertEquals(1,EDC.convertToMotorValue(-5)); assertEquals(5,EDC.convertToMotorValue(5.4)); assertEquals(7, EDC.convertToMotorValue(6.5)); } |
### Question:
CarControlImpl implements CarControl { @Override public int getLastThrottle() { return currentThrottleValue; } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); }### Answer:
@Test void getLastThrottle() { assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE); } |
### Question:
CarControlImpl implements CarControl { @Override public int getLastSteer() { return currentSteerValue; } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); }### Answer:
@Test void getLastSteer() { assertEquals(carControl.getLastSteer(), STEER_VALUE); } |
### Question:
CarControlImpl implements CarControl { @Override public synchronized void setThrottle(int value) { if (value != currentThrottleValue) { currentThrottleValue = constrainInRange(value, MIN_SPEED, MAX_SPEED); } } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); }### Answer:
@Test void setThrottle() { carControl.setThrottle(THROTTLE_VALUE + 1); assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE + 1); } |
### Question:
CarControlImpl implements CarControl { @Override public synchronized void setSteerValue(int value) { if (value != currentSteerValue) { currentSteerValue = constrainInRange(value,MIN_STEER,MAX_STEER); } } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); }### Answer:
@Test void setSteerValue() { carControl.setSteerValue(STEER_VALUE + 1); assertEquals(carControl.getLastSteer(), STEER_VALUE + 1); } |
### Question:
PathSet implements Set<Path> { public boolean containsAncestor(Path path) { for (Path p : this) { if (p.isAncestorOf(path)) { return true; } } return false; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); }### Answer:
@Test public void containsAncestor() { assertTrue(data.remove(new Path("/"))); assertTrue(data.containsAncestor(new Path("/foo/baz"))); assertTrue(data.containsAncestor(new Path("/bar/baz"))); assertTrue(!data.containsAncestor(new Path("/foo"))); assertTrue(!data.containsAncestor(new Path("/baz"))); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isDescendantOf(Path other) { if (other.isRoot()) { if (isRoot()) { return false; } else if (isAbsolute()) { return true; } else { return false; } } else { return path.startsWith(other.path + SEPARATOR) && path.length() > other.path.length(); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isDescendantOf() { assertDescendant(new Path("/"), new Path("/foo")); assertDescendant(new Path("/"), new Path("/foo/bar")); assertDescendant(new Path("/foo"), new Path("/foo/bar")); assertNotDescendant(new Path("/foo"), new Path("/bar/foo")); assertNotDescendant(new Path("/foo"), new Path("/")); assertNotDescendant(new Path("/"), new Path("relative")); assertDescendant(new Path("foo/bar"), new Path("foo/bar/baz")); assertNotDescendant(new Path("foo/bar"), new Path("bar")); assertNotDescendant(new Path("/"), new Path("/")); assertNotDescendant(new Path("/foo"), new Path("/foo")); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isRoot() { return path.equals(SEPARATOR); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isRoot() { assertTrue(new Path("/").isRoot()); assertTrue(!new Path("foo").isRoot()); assertTrue(!new Path("/foo").isRoot()); } |
### Question:
Path implements Iterable<String>, Serializable { public Iterator<String> iterator() { return new Iterator<String>() { int idx = 0; public boolean hasNext() { return idx < size(); } public String next() { return part(idx++); } public void remove() { throw new UnsupportedOperationException("Path parts iterator is read only"); } }; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test @SuppressWarnings("unused") public void iterator() { Path path = new Path("/foo/bar/baz"); Set<String> parts = new HashSet<String>(Arrays.asList(new String[]{"foo", "bar", "baz"})); for (String part : path) { assertTrue(parts.remove(part)); } assertTrue(parts.isEmpty()); for (String part : new Path("/")) { fail(); } } |
### Question:
Path implements Iterable<String>, Serializable { public Path parent() { if (isRoot()) { return null; } else { return new Path(path + "/.."); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void parent() { assertTrue(new Path("/").parent() == null); assertEquals(new Path("/foo").parent(), new Path("/")); assertEquals(new Path("/foo/bar").parent(), new Path("/foo")); assertEquals(new Path("foo").parent(), new Path(".")); assertEquals(new Path("foo/bar").parent(), new Path("foo")); assertEquals(new Path(".").parent(), new Path("..")); assertEquals(new Path("../foo").parent(), new Path("..")); assertEquals(new Path("..").parent(), new Path("../..")); } |
### Question:
Path implements Iterable<String>, Serializable { public String part(int index) { if (index < 0) { throw new IndexOutOfBoundsException(); } int start = isAbsolute() ? 1 : 0; for (int i = 0; i < index; i++) { start = path.indexOf(SEPARATOR, start); if (start < 0) { throw new IndexOutOfBoundsException(); } start++; } int end = path.indexOf(SEPARATOR, start); if (end < 0) { end = path.length(); } return path.substring(start, end); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void part() { Path path = new Path("/foo/bar/baz"); assertEquals("foo", path.part(0)); assertEquals("bar", path.part(1)); assertEquals("baz", path.part(2)); path = new Path("foo/bar/baz"); assertEquals("foo", path.part(0)); assertEquals("bar", path.part(1)); assertEquals("baz", path.part(2)); } |
### Question:
Path implements Iterable<String>, Serializable { public int size() { if (isRoot()) { return 0; } int size = 0; int pos = 0; while (pos >= 0) { size++; pos = path.indexOf(SEPARATOR, pos + 1); } return size; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void size() { assertEquals(new Path("/").size(), 0); assertEquals(new Path("/foo").size(), 1); assertEquals(new Path("/foo/bar").size(), 2); assertEquals(new Path("/foo/bar/baz").size(), 3); } |
### Question:
Path implements Iterable<String>, Serializable { public Path toRelative(Path ancestor) { if (isRoot()) { throw new IllegalStateException("Cannot make root path relative"); } if (!isDescendantOf(ancestor)) { throw new IllegalArgumentException("Cannot create relative path because this path: " + this + " is not descendant of ancestor argument: " + ancestor); } Path fragment = new Path(path.substring(ancestor.path.length()), false); if (fragment.isAbsolute()) { fragment = fragment.toRelative(new Path("/")); } return fragment; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void toRelative() { try { new Path("/").toRelative(new Path("/")); fail(); } catch (IllegalStateException e) { } try { new Path("/foo/bar").toRelative(new Path("/bar")); fail(); } catch (IllegalArgumentException e) { } assertEquals(new Path("foo"), new Path("/foo").toRelative(new Path("/"))); assertEquals(new Path("bar"), new Path("/foo/bar").toRelative(new Path("/foo"))); assertEquals(new Path("bar"), new Path("foo/bar").toRelative(new Path("foo"))); } |
### Question:
PathSet implements Set<Path> { public boolean containsParent(Path path) { for (Path p : this) { if (p.isParentOf(path)) { return true; } } return false; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); }### Answer:
@Test public void containsParent() { assertTrue(!data.containsParent(new Path("/"))); assertTrue(data.containsParent(new Path("/foo"))); assertTrue(data.containsParent(new Path("/foo/baz"))); assertTrue(data.containsParent(new Path("/foo/bar/baz"))); assertTrue(data.containsParent(new Path("/foo/bar/baz/boz"))); assertTrue(!data.containsParent(new Path("/foo/baz/bar"))); } |
### Question:
PathSet implements Set<Path> { public void removeDescendants(Path path) { Iterator<Path> i = iterator(); while (i.hasNext()) { Path p = i.next(); if (p.isDescendantOf(path)) { i.remove(); } } } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); }### Answer:
@Test public void removeDescendants() { data.removeDescendants(new Path("/foo")); assertTrue(data.size() == 3); assertTrue(data.contains(new Path("/"))); assertTrue(data.contains(new Path("/bar"))); assertTrue(data.contains(new Path("/foo"))); data.removeDescendants(new Path("/")); assertTrue(data.size() == 1); assertTrue(data.contains(new Path("/"))); } |
### Question:
PathSet implements Set<Path> { public boolean removeWithDescendants(Path path) { boolean ret = remove(path); removeDescendants(path); return ret; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); }### Answer:
@Test public void removeWithDescendants() { data.removeWithDescendants(new Path("/foo")); assertTrue(data.size() == 2); assertTrue(data.contains(new Path("/"))); assertTrue(data.contains(new Path("/bar"))); data.removeWithDescendants(new Path("/")); assertTrue(data.isEmpty()); } |
### Question:
Path implements Iterable<String>, Serializable { @Override public String toString() { return path; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void construction() { assertEquals(new Path("/").toString(), "/"); assertEquals(new Path("/foo").toString(), "/foo"); assertEquals(new Path("/foo/").toString(), "/foo"); assertEquals(new Path("/foo/bar").toString(), "/foo/bar"); assertEquals(new Path("/foo/bar/").toString(), "/foo/bar"); assertEquals(new Path("foo").toString(), "foo"); assertEquals(new Path("foo/").toString(), "foo"); assertEquals(new Path("foo/bar").toString(), "foo/bar"); assertEquals(new Path("foo/bar/").toString(), "foo/bar"); try { new Path(""); fail(); } catch (IllegalArgumentException e) { } try { new Path(null); fail(); } catch (IllegalArgumentException e) { } } |
### Question:
Path implements Iterable<String>, Serializable { public String getName() { if (path.equals(SEPARATOR)) { return path; } else { int last = path.lastIndexOf(SEPARATOR); return path.substring(last + 1); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void getName() { assertEquals(new Path("/").getName(), "/"); assertEquals(new Path("/foo").getName(), "foo"); assertEquals(new Path("/foo/bar").getName(), "bar"); assertEquals(new Path("foo").getName(), "foo"); assertEquals(new Path("foo/bar").getName(), "bar"); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isAbsolute() { return path.startsWith("/"); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isAbsolute() { assertTrue(new Path("/").isAbsolute()); assertTrue(new Path("/foo").isAbsolute()); assertTrue(new Path("/foo/bar").isAbsolute()); assertTrue(!new Path("foo").isAbsolute()); assertTrue(!new Path("foo/bar").isAbsolute()); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isChildOf(Path other) { return isDescendantOf(other) && size() == other.size() + 1; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isChildOf() { assertChild(new Path("/"), new Path("/foo")); assertNotChild(new Path("/"), new Path("/foo/bar")); assertChild(new Path("/foo/bar"), new Path("/foo/bar/baz")); assertNotChild(new Path("/foo/bar"), new Path("/foo/baz/bar")); assertNotChild(new Path("/"), new Path("/")); assertNotChild(new Path("/foo"), new Path("/")); } |
### Question:
PoiList { public List<OsmObject> createAlternateList() { return poiList.subList(1, poiList.size()); } private PoiList(); static synchronized PoiList getInstance(); List<OsmObject> getPoiList(); void setPoiList(List<OsmObject> poiList); List<OsmObject> createAlternateList(); void clearPoiList(); void sortList(final double queryLatitude, final double queryLongitude); String serializePoiList(); void decodePoiList(String json); }### Answer:
@Test public void createAlternateList() { List<OsmObject> alternateList = PoiList.getInstance().createAlternateList(); assertEquals(0, alternateList.size()); } |
### Question:
QuestionsPresenter implements QuestionsActivityContract.Presenter { @Override public void assessIntentData(URI uri) { if (uri != null) { try { Map<String, List<String>> list = Utilities.splitQuery(uri); String verifier = list.get(PreferenceList.OAUTH_VERIFIER).get(0); String token = list.get(PreferenceList.OAUTH_TOKEN).get(0); preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, verifier); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, token); view.startOAuth(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } QuestionsPresenter(QuestionsActivityContract.View view, SourceContract.Preferences preferences); @Override void addPoiNameToTextview(); @Override void assessIntentData(URI uri); @Override void savePoiList(); @Override void restorePoiList(); }### Answer:
@Test public void assessIntentData() { URI uri = null; try { uri = new URI("http: } catch (URISyntaxException e) { e.printStackTrace(); } questionsPresenter.assessIntentData(uri); verify(preferences).setStringPreference("oauth_verifier", "1"); verify(preferences).setStringPreference("oauth_token", "1"); verify(view).startOAuth(); } |
### Question:
IntroPresenter implements IntroFragmentContract.Presenter { @Override public void getDetails() { String address = getAddress(); view.showDetails(poi.getName(), address, poi.getDrawable()); } IntroPresenter(IntroFragmentContract.View view); @Override void getDetails(); }### Answer:
@Test public void addPoiToTextview() { introPresenter.getDetails(); verify(view).showDetails("Kitchen", " ", R.drawable.ic_restaurant); } |
### Question:
OsmLoginPresenter implements OsmLoginFragmentContract.Presenter { @Override public void clickedOsmLoginButton() { preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, ""); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, ""); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN_SECRET, ""); view.startOAuth(); } OsmLoginPresenter(OsmLoginFragmentContract.View view, SourceContract.Preferences preferences); @Override void clickedOsmLoginButton(); }### Answer:
@Test public void checkPreferencesAreCleared() { presenter.clickedOsmLoginButton(); verify(view).startOAuth(); } |
### Question:
QuestionPresenter implements QuestionFragmentContract.Presenter { @Override public void getQuestion() { List<QuestionsContract> questions = this.listOfQuestions.getQuestion(); QuestionsContract questionsContract = questions.get(position); int question = questionsContract.getQuestion(); int color = questionsContract.getColor(); int drawable = questionsContract.getIcon(); view.showQuestion(question, poi.getName(), color, drawable); String key = questionsContract.getTag(); String answer = poi.getTag(key); if (answer != null) { view.setPreviousAnswer(answer); } else { view.setPreviousAnswer(""); } } QuestionPresenter(QuestionFragmentContract.View view, int position, SourceContract.Preferences preferences); @Override void getQuestion(); @Override void onAnswerSelected(int id); }### Answer:
@Test public void getQuestionTest() { questionPresenter.getQuestion(); verify(view).showQuestion(anyInt(), anyString(), anyInt(), anyInt()); }
@Test public void getPreviousAnswerTest() { questionPresenter.getQuestion(); verify(view).setPreviousAnswer(anyString()); } |
### Question:
MainActivityPresenter implements MainActivityContract.Presenter { @Override public void checkIfOauth(URI uri) { if (uri != null) { try { Map<String, List<String>> list = Utilities.splitQuery(uri); String verifier = list.get(PreferenceList.OAUTH_VERIFIER).get(0); String token = list.get(PreferenceList.OAUTH_TOKEN).get(0); preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, verifier); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, token); view.startOAuth(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } MainActivityPresenter(MainActivityContract.View view, SourceContract.Preferences preferences); @Override void showIfLoggedIn(); @Override void checkIfOauth(URI uri); void onButtonClicked(); @Override void toggleDebugMode(); @Override String getUserName(); @Override void savePoiList(); @Override void restorePoiList(); }### Answer:
@Test public void checkIfInOAuthFlow() { URI url = null; try { url = new URI("http: } catch (URISyntaxException e) { e.printStackTrace(); } presenter.checkIfOauth(url); verify(view).startOAuth(); } |
### Question:
MainActivityPresenter implements MainActivityContract.Presenter { @Override public void showIfLoggedIn() { boolean loggedIn = preferences.getBooleanPreference(PreferenceList.LOGGED_IN_TO_OSM); int message; int button; String userName = getUserName(); if (loggedIn) { if ("".equals(userName)) { message = R.string.logged_in; } else { message = R.string.logged_in_as; } button = R.string.log_out; } else { message = R.string.not_logged_in; button = R.string.authorise_openstreetmap; } view.showIfLoggedIn(message, button, userName); } MainActivityPresenter(MainActivityContract.View view, SourceContract.Preferences preferences); @Override void showIfLoggedIn(); @Override void checkIfOauth(URI uri); void onButtonClicked(); @Override void toggleDebugMode(); @Override String getUserName(); @Override void savePoiList(); @Override void restorePoiList(); }### Answer:
@Test public void checkIfUsernameIsSetCorrectly() { presenter.showIfLoggedIn(); verify(view).showIfLoggedIn(anyInt(), anyInt(), (String) any()); } |
### Question:
QueryOverpass implements SourceContract.Overpass { @Override public String getOverpassUri(double latitude, double longitude, float accuracy) { float measuredAccuracy; if (accuracy < 20) { measuredAccuracy = 20; } else if (accuracy > 100) { measuredAccuracy = 100; } else { measuredAccuracy = accuracy; } String overpassLocation = String.format("around:%s,%s,%s", measuredAccuracy, latitude, longitude); String nwr = "%1$s[~\"^(%2$s)$\"~\".\"](%3$s);"; String types = "shop|amenity|leisure|tourism"; String node = String.format(nwr, "node", types, overpassLocation); String way = String.format(nwr, "way", types, overpassLocation); String relation = String.format(nwr, "relation", types, overpassLocation); return String.format("https: } QueryOverpass(Context context); QueryOverpass(); @Override String getOverpassUri(double latitude, double longitude, float accuracy); @Override String queryOverpassApi(String urlString); @Override void processResult(String result); @Override void queryOverpass(double latitude, double longitude, float accuracy); String getType(JSONObject tags); }### Answer:
@Test public void testGenerateOverpassUri() { double latitude = 53; double longitude = -7; float accuracy = 50; String expected_uri = "https: String uri = queryOverpass.getOverpassUri(latitude, longitude, accuracy); assertEquals(expected_uri, uri); } |
### Question:
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void findVersion() { String version = BuildConfig.VERSION_NAME; view.setVersion(version); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); }### Answer:
@Test public void checkVersionNameIsSet() { aboutPresenter.findVersion(); verify(view).setVersion(BuildConfig.VERSION_NAME); } |
### Question:
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void getLicence() { String uri = "http: view.visitUri(uri); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); }### Answer:
@Test public void checkLicenceDetailsAreSet() { aboutPresenter.getLicence(); verify(view).visitUri("http: } |
### Question:
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void getGitHub() { String uri = "https: view.visitUri(uri); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); }### Answer:
@Test public void checkSourceDetailsAreSet() { aboutPresenter.getGitHub(); verify(view).visitUri("https: } |
### Question:
Utilities { public static Map<String, List<String>> splitQuery(URI url) throws UnsupportedEncodingException { final Map<String, List<String>> query_pairs = new LinkedHashMap<>(); final String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<String>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } static Map<String, List<String>> splitQuery(URI url); static float computeDistance(double latitude1, double longitude1, double latitude2, double longitude2); }### Answer:
@Test public void splitqueryValidUrl() throws URISyntaxException, UnsupportedEncodingException { String uri = "http: URI url = new URI(uri); Map<String, List<String>> map = Utilities.splitQuery(url); assertEquals("[out:json]", map.get("data").get(0)); } |
### Question:
QueryOverpass implements SourceContract.Overpass { public String getType(JSONObject tags) throws JSONException { String type = ""; if (tags.has("amenity")) { type = tags.getString("amenity"); } if (tags.has("shop")) { type = tags.getString("shop"); } if (tags.has("tourism")) { type = tags.getString("tourism"); } if (tags.has("leisure")) { type = tags.getString("leisure"); } return type; } QueryOverpass(Context context); QueryOverpass(); @Override String getOverpassUri(double latitude, double longitude, float accuracy); @Override String queryOverpassApi(String urlString); @Override void processResult(String result); @Override void queryOverpass(double latitude, double longitude, float accuracy); String getType(JSONObject tags); }### Answer:
@Test public void testGetOverpassResultPoiType() throws JSONException { String expected_result = "hairdresser"; JSONObject json = new JSONObject().put("amenity", expected_result); String result = queryOverpass.getType(json); assertEquals(expected_result, result); } |
### Question:
Answers { public static Map<String, String> getAnswerMap() { getInstance(); return answerMap; } private Answers(); static Map<String, String> getAnswerMap(); static void addAnswer(String question, String answer); static void clearAnswerList(); static void setPoiDetails(OsmObject osmObject); static long getPoiId(); static String getPoiName(); static String getPoiType(); static Map<String, String> getChangesetTags(); static void setChangesetTags(Map<String, String> changesetTags); }### Answer:
@Test public void getKeyFromTag() { String tag = this.questionObject.getTag(); String expectedValue = this.questionObject.getAnswerYes(); String actualValue = Answers.getAnswerMap().get(tag); assertEquals(expectedValue, actualValue); } |
### Question:
Answers { public static Map<String, String> getChangesetTags() { getInstance(); return changesetTags; } private Answers(); static Map<String, String> getAnswerMap(); static void addAnswer(String question, String answer); static void clearAnswerList(); static void setPoiDetails(OsmObject osmObject); static long getPoiId(); static String getPoiName(); static String getPoiType(); static Map<String, String> getChangesetTags(); static void setChangesetTags(Map<String, String> changesetTags); }### Answer:
@Test public void checkChangesetTagsAreSet() { Map<String, String> actualTags = Answers.getChangesetTags(); Map<String, String> expectedTags = new HashMap<>(); expectedTags.put("", ""); assertEquals(expectedTags, actualTags); } |
### Question:
NotHerePresenter implements NotHereFragmentContract.Presenter { @Override public void getPoiDetails() { String name = poiList.get(0).getName(); view.setTextview(name); view.setAdapter(alternateList); } NotHerePresenter(NotHereFragmentContract.View view); @Override void getPoiDetails(); @Override void onItemClicked(int i); }### Answer:
@Test public void addPoiToTextview() { notHerePresenter.getPoiDetails(); verify(view).setTextview("Kitchen"); } |
### Question:
NotHerePresenter implements NotHereFragmentContract.Presenter { @Override public void onItemClicked(int i) { ArrayList<OsmObject> intentList = new ArrayList<>(); intentList.add(0, this.alternateList.get(i)); PoiList.getInstance().setPoiList(intentList); view.startActivity(); } NotHerePresenter(NotHereFragmentContract.View view); @Override void getPoiDetails(); @Override void onItemClicked(int i); }### Answer:
@Test public void onClick() { notHerePresenter.onItemClicked(0); verify(view).startActivity(); } |
### Question:
MigrationRouter { public List<MigrationPair> getMigrationPairOfPNode(int pNodeNo) { return allNodeMigrationPairs.get(pNodeNo); } MigrationRouter(int vNodes, int oldPNodeCount, int newPNodeCount); int getNewPNodeCount(); int getOldPNodeCount(); List<MigrationPair> getMigrationPairOfPNode(int pNodeNo); List<List<MigrationPair>> getAllNodeMigrationPairs(); }### Answer:
@Test public void testGetMigrationPairOfPNode() { MigrationRouter migrationRouter = new MigrationRouter(10000, 3, 4); System.out.println(migrationRouter.getMigrationPairOfPNode(0)); List<List<MigrationPair>> allNodeMigrationPairs = migrationRouter.getAllNodeMigrationPairs(); Assert.assertTrue( allNodeMigrationPairs.size() == 3); List<MigrationPair> pairs = allNodeMigrationPairs.get( 0 ); for (MigrationPair pair : pairs) { if(pair.getVnode() == 3) { Assert.assertEquals(0, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } if(pair.getVnode() == 9) { Assert.assertEquals(1, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } if(pair.getVnode() == 11) { Assert.assertEquals(2, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } } } |
### Question:
ConsistentReportServiceImpl implements ConsistentReportService { public List<ConsistentReportDO> queryConsistentReport(Map params) { return consistentReportDao.queryConsistentReport(params); } void setConsistentReportDao(ConsistentReportDao consistentReportDao); Integer saveConsistentReport(ConsistentReportDO consistentReportDO); List<ConsistentReportDO> queryConsistentReport(Map params); int countConsistentReport(Map params); Integer deleteByIds(List<Integer> ids); Integer deleteByGmtCreate(String gmtCreateFrom, String gmtCreateTo); }### Answer:
@Test public void testQueryConsistentReport() { } |
### Question:
PNode2VNodeMapping { public List<Integer> getVNodes(int pNode) { return vpmMapping.get( pNode ); } PNode2VNodeMapping(int vNodes, int pNodeCount); List<Integer> getVNodes(int pNode); int getPNodeCount(); List<List<Integer>> getVpmMapping(); }### Answer:
@Test public void testGetVNodes() { PNode2VNodeMapping mapping = new PNode2VNodeMapping(12, 3); System.out.println( "vNodes: of (12,3): " + mapping); List<Integer> vNodes = mapping.getVNodes(1); System.out.println( "vNodes: of (12,3:1): " + vNodes ); Assert.assertEquals(6, vNodes.get(0).intValue()); Assert.assertEquals(7, vNodes.get(1).intValue()); Assert.assertEquals(8, vNodes.get(2).intValue()); Assert.assertEquals(9, vNodes.get(3).intValue()); } |
### Question:
PropertiesLoadUtil { public static Properties loadProperties(String propLocation) { Properties properties = null; properties = loadAsFile(propLocation); if( properties != null) return properties; properties = loadAsResource(propLocation); return properties; } static Properties loadProperties(String propLocation); }### Answer:
@Test public void testProperty() { Properties properties = PropertiesLoadUtil.loadProperties("./test/test/test/testp.properties"); assertEquals("value1", properties.get("key1")); } |
### Question:
JavaObjectSerializer implements Serializer { public byte[] serialize(Object o, Object arg) { byte[] bvalue = null; if( o == null ) { bvalue = new byte[]{ Byte.valueOf( (byte) 0 )}; return bvalue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject( o ); bvalue = baos.toByteArray(); return bvalue; } catch (IOException e) { throw new RuntimeException("Fail to serialize object: " + o +", cause: " + e, e); }finally { try { baos.close(); } catch (IOException e) { } } } Object deserialize(byte[] bvalue, Object deserializeTarget); byte[] serialize(Object o, Object arg); }### Answer:
@Test public void testSerializeNull() { Serializer serializer = new JavaObjectSerializer(); byte[] bvalue = serializer.serialize(null, null); char c = (char) Byte.valueOf( (byte)0 ).byteValue(); byte s = "0".getBytes()[0] ; System.out.println("asc 0: " + s +", c: " + c); }
@Test public void testSerialize() { Serializer serializer = new JavaObjectSerializer(); String stringObj = "key001"; byte[] bvalue = serializer.serialize(stringObj, null); Assert.assertTrue("string serialize result", bvalue != null); } |
### Question:
JavaObjectSerializer implements Serializer { public Object deserialize(byte[] bvalue, Object deserializeTarget) { if( bvalue == null) return null; ByteArrayInputStream bais = new ByteArrayInputStream( bvalue ); try { ObjectInputStream ois = new ObjectInputStream(bais); Object obj = ois.readObject(); return obj; } catch (Exception e) { throw new RuntimeException("Fail to deserialize object, byte value:" + bvalue +", cause: " + e, e); }finally { try { bais.close(); } catch (IOException e) { } } } Object deserialize(byte[] bvalue, Object deserializeTarget); byte[] serialize(Object o, Object arg); }### Answer:
@Test public void testDeserialize() { Serializer serializer = new JavaObjectSerializer(); String stringObj = "key001"; byte[] bvalue = serializer.serialize(stringObj, null); String result = (String) serializer.deserialize(bvalue, null); Assert.assertEquals("string serialize result",stringObj, result); } |
### Question:
StorageManager { protected void loadStorage(StorageConfig config) { driver.init(config); storage = driver.createStorage(); } StorageManager(); Storage getStorage(); StorageType getStorageType(); void registStorage(Class<?> storageDriverClass); }### Answer:
@Test public void testLoadStorage() { StorageManager manager = new StorageManager(); } |
### Question:
MigrationVirtualNodeFinder { public String getTargetNodeOfVirtualNode(int vnode) { return index.get( vnode ); } MigrationVirtualNodeFinder(List<MigrationRoutePair> migrationRoutePairs); String getTargetNodeOfVirtualNode(int vnode); }### Answer:
@Test public void testGetTargetNodeOfVirtualNode() { List<MigrationRoutePair> migrationRoutePairs = new ArrayList<MigrationRoutePair>(); for (int i = 0; i < 1000 ; i++) { MigrationRoutePair pair = new MigrationRoutePair(); pair.setVnode( i ); pair.setTargetPhysicalId("127.0.0.1"); migrationRoutePairs.add( pair ); } MigrationVirtualNodeFinder finder = new MigrationVirtualNodeFinder(migrationRoutePairs); String targetNode1 = finder.getTargetNodeOfVirtualNode( 100 ); assertNotNull("targetNode1 found", targetNode1); String targetNode2 = finder.getTargetNodeOfVirtualNode( 1000 + 1 ); assertNull("targetNode2 not found ", targetNode2); } |
### Question:
ProgressComputer { public int getGrossProgress() { reentrantLock.lock(); try { return grossProgress; }finally { reentrantLock.unlock(); } } ProgressComputer(List<MigrationRoutePair> migrationRoutePairs); synchronized boolean completeOneVNode(String targetNodeId, Integer vnodeId); int getGrossProgress(); int getFinishCount(); int getProgressOfTarget(String tNodeId); }### Answer:
@Test public void testGetGrossProgress() { List<MigrationRoutePair> migrationRoutePairs = new ArrayList<MigrationRoutePair>(); int t = 1, v = 10000 ; for (int i = 0; i < t; i++) { for (int j = 0; j < v; j++) { MigrationRoutePair pair = new MigrationRoutePair(j , "t"+i ); migrationRoutePairs.add( pair ); } } ProgressComputer progressComputer = new ProgressComputer(migrationRoutePairs); int lastProgress = -1; for (int i = 0; i < v ; i++) { boolean need = progressComputer.completeOneVNode( "t0", 0); int progress = progressComputer.getGrossProgress(); lastProgress = progress; } assertEquals("Progress=100", 100,lastProgress); } |
### Question:
ConsistentReportServiceImpl implements ConsistentReportService { public Integer saveConsistentReport(ConsistentReportDO consistentReportDO) { return consistentReportDao.insert(consistentReportDO); } void setConsistentReportDao(ConsistentReportDao consistentReportDao); Integer saveConsistentReport(ConsistentReportDO consistentReportDO); List<ConsistentReportDO> queryConsistentReport(Map params); int countConsistentReport(Map params); Integer deleteByIds(List<Integer> ids); Integer deleteByGmtCreate(String gmtCreateFrom, String gmtCreateTo); }### Answer:
@Test public void testSaveConsistentReport() { } |
### Question:
BPMNParser extends AbstractXMLParser { public static BPMNProcess generateProcessFromXML(String filePath) { Document doc = readXMLDocument(filePath); return generateBPMNProcess(doc); } static BPMNProcess generateProcessFromXML(String filePath); }### Answer:
@Test public void testComplexProcess() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{ BPMNProcess BPMNProcess = BPMNParser.generateProcessFromXML(complexfilePath); assertNotNull(BPMNProcess); assertTrue(BPMNProcess.getBPMNElementsWithOutSequenceFlows().size() == 21); assertTrue(BPMNProcess.getStartEvent().getId().equals("sid-EC585815-8EAC-411C-89C2-553ACA85CF5A")); }
@Test public void testSubProcessImport() { BPMNProcess BPMNProcess = BPMNParser.generateProcessFromXML(subProcessfilePath); assertNotNull(BPMNProcess); assertTrue(BPMNProcess.getBPMNElementsWithOutSequenceFlows().size() == 7); assertTrue(BPMNProcess.hasSubProcesses()); BPMNSubProcess subProcess = BPMNProcess.getSubProcesses().get(0); assertNotNull(subProcess); assertFalse(subProcess.getStartEvent().getSuccessors().isEmpty()); } |
Subsets and Splits