method2testcases stringlengths 118 3.08k |
|---|
### Question:
GroovyResponseHttpMessageConverter implements HttpMessageConverter<GroovyResponse> { @Override public GroovyResponse read(Class<? extends GroovyResponse> clazz, HttpInputMessage inputMessage) throws IOException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); Streams.copy(inputMessage.getBody(), output); return new GroovyResponse() { @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(output.toByteArray()); } }; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override GroovyResponse read(Class<? extends GroovyResponse> clazz, HttpInputMessage inputMessage); @Override void write(GroovyResponse t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void read() throws Exception { MockHttpInputMessage inputMessage = new MockHttpInputMessage("print 'hello'"); GroovyResponse response = converter.read(GroovyResponse.class, inputMessage); assertEquals("print 'hello'", Streams.toString(response.getInputStream())); } |
### Question:
GroovyResponseHttpMessageConverter implements HttpMessageConverter<GroovyResponse> { @Override public void write(GroovyResponse t, String contentType, HttpOutputMessage outputMessage) throws IOException { throw new UnsupportedOperationException(); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override GroovyResponse read(Class<? extends GroovyResponse> clazz, HttpInputMessage inputMessage); @Override void write(GroovyResponse t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void write() throws Exception { converter.write(null, null, null); } |
### Question:
JobArrayHttpMessageConverter implements HttpMessageConverter<Job[]> { @Override public boolean canRead(Class<?> clazz) { return Job[].class.equals(clazz); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Job[] read(Class<? extends Job[]> clazz, HttpInputMessage inputMessage); @Override void write(Job[] t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canRead() throws Exception { assertTrue(converter.canRead(Job[].class)); assertFalse(converter.canRead(Job.class)); assertFalse(converter.canRead(Object.class)); } |
### Question:
JobArrayHttpMessageConverter implements HttpMessageConverter<Job[]> { @Override public boolean canWrite(Class<?> clazz) { return false; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Job[] read(Class<? extends Job[]> clazz, HttpInputMessage inputMessage); @Override void write(Job[] t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canWrite() throws Exception { assertFalse(converter.canWrite(Job[].class)); assertFalse(converter.canWrite(Job.class)); assertFalse(converter.canWrite(Object.class)); } |
### Question:
JobArrayHttpMessageConverter implements HttpMessageConverter<Job[]> { @Override public void write(Job[] t, String contentType, HttpOutputMessage outputMessage) throws IOException { throw new UnsupportedOperationException(); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Job[] read(Class<? extends Job[]> clazz, HttpInputMessage inputMessage); @Override void write(Job[] t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void write() throws Exception { converter.write(new Job[] {}, null, null); } |
### Question:
JobHttpMessageConverter implements HttpMessageConverter<Job> { @Override public boolean canRead(Class<?> clazz) { return Job.class.equals(clazz); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Job read(Class<? extends Job> clazz, HttpInputMessage inputMessage); @Override void write(Job t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canRead() throws Exception { Assert.assertTrue(converter.canRead(Job.class)); Assert.assertFalse(converter.canRead(String.class)); Assert.assertFalse(converter.canRead(Object.class)); Assert.assertFalse(converter.canRead(Job[].class)); } |
### Question:
DefaultResponseErrorHandler implements ResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = response.getStatusCode(); switch (statusCode.series()) { case CLIENT_ERROR: throw new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response)); case SERVER_ERROR: throw new HttpServerErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response)); default: throw new JenkinsClientException("Unknown status code [" + statusCode + "]"); } } @Override boolean hasError(ClientHttpResponse response); @Override void handleError(ClientHttpResponse response); }### Answer:
@Test public void handleError() throws Exception { thrown.expect(JenkinsClientException.class); errorHandler.handleError(new MockClientHttpResponse(HttpStatus.INTERNAL_SERVER_ERROR)); } |
### Question:
JobHttpMessageConverter implements HttpMessageConverter<Job> { @Override public boolean canWrite(Class<?> clazz) { return false; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Job read(Class<? extends Job> clazz, HttpInputMessage inputMessage); @Override void write(Job t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canWrite() throws Exception { Assert.assertFalse(converter.canWrite(Job.class)); Assert.assertFalse(converter.canWrite(Job[].class)); Assert.assertFalse(converter.canWrite(Object.class)); } |
### Question:
JobHttpMessageConverter implements HttpMessageConverter<Job> { @Override public void write(Job t, String contentType, HttpOutputMessage outputMessage) throws IOException { throw new UnsupportedOperationException(); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Job read(Class<? extends Job> clazz, HttpInputMessage inputMessage); @Override void write(Job t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void write() throws Exception { converter.write(new Job(), null, null); } |
### Question:
JobConfigurationHttpMessageConverter implements HttpMessageConverter<JobConfiguration> { @Override public boolean canRead(Class<?> clazz) { return JobConfiguration.class.equals(clazz); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override JobConfiguration read(Class<? extends JobConfiguration> clazz, HttpInputMessage inputMessage); @Override void write(JobConfiguration t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canRead() throws Exception { assertTrue(converter.canRead(JobConfiguration.class)); assertFalse(converter.canRead(JobConfiguration[].class)); assertFalse(converter.canRead(Object.class)); } |
### Question:
JobConfigurationHttpMessageConverter implements HttpMessageConverter<JobConfiguration> { @Override public boolean canWrite(Class<?> clazz) { return JobConfiguration.class.isAssignableFrom(clazz); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override JobConfiguration read(Class<? extends JobConfiguration> clazz, HttpInputMessage inputMessage); @Override void write(JobConfiguration t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canWrite() throws Exception { assertTrue(converter.canWrite(JobConfiguration.class)); assertTrue(converter.canWrite(ClassPathJobConfiguration.class)); assertFalse(converter.canWrite(Object.class)); } |
### Question:
JobConfigurationHttpMessageConverter implements HttpMessageConverter<JobConfiguration> { @Override public JobConfiguration read(Class<? extends JobConfiguration> clazz, HttpInputMessage inputMessage) throws IOException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); Streams.copy(inputMessage.getBody(), output); return new JobConfiguration() { @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(output.toByteArray()); } }; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override JobConfiguration read(Class<? extends JobConfiguration> clazz, HttpInputMessage inputMessage); @Override void write(JobConfiguration t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void read() throws Exception { HttpInputMessage inputMessage = new MockHttpInputMessage("<freeStyleProject></freeStyleProject>"); JobConfiguration jobConfiguration = converter.read(JobConfiguration.class, inputMessage); Assert.assertEquals("<freeStyleProject></freeStyleProject>", Streams.toString(jobConfiguration.getInputStream())); } |
### Question:
GroovyScriptHttpMessageConverter implements HttpMessageConverter<GroovyScript> { @Override public boolean canRead(Class<?> clazz) { return false; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override void write(GroovyScript t, String contentType, HttpOutputMessage outputMessage); @Override GroovyScript read(Class<? extends GroovyScript> clazz, HttpInputMessage inputMessage); }### Answer:
@Test public void canRead() throws Exception { assertFalse(converter.canRead(GroovyScript.class)); assertFalse(converter.canRead(Object.class)); } |
### Question:
GroovyScriptHttpMessageConverter implements HttpMessageConverter<GroovyScript> { @Override public boolean canWrite(Class<?> clazz) { return GroovyScript.class.isAssignableFrom(clazz); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override void write(GroovyScript t, String contentType, HttpOutputMessage outputMessage); @Override GroovyScript read(Class<? extends GroovyScript> clazz, HttpInputMessage inputMessage); }### Answer:
@Test public void canWrite() throws Exception { assertTrue(converter.canWrite(GroovyScript.class)); assertTrue(converter.canWrite(StringGroovyScript.class)); assertFalse(converter.canWrite(Object.class)); } |
### Question:
BuildHttpMessageConverter implements HttpMessageConverter<Build> { @Override public boolean canRead(Class<?> clazz) { return Build.class.equals(clazz); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Build read(Class<? extends Build> clazz, HttpInputMessage inputMessage); @Override void write(Build t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canRead() throws Exception { assertTrue(converter.canRead(Build.class)); assertFalse(converter.canRead(Build[].class)); assertFalse(converter.canRead(Object.class)); } |
### Question:
GroovyScriptHttpMessageConverter implements HttpMessageConverter<GroovyScript> { @Override public void write(GroovyScript t, String contentType, HttpOutputMessage outputMessage) throws IOException { String payload = "script=" + Streams.toString(t.getInputStream()); Streams.copy(payload, outputMessage.getBody()); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override void write(GroovyScript t, String contentType, HttpOutputMessage outputMessage); @Override GroovyScript read(Class<? extends GroovyScript> clazz, HttpInputMessage inputMessage); }### Answer:
@Test public void write() throws Exception { GroovyScript script = new StringGroovyScript("print 'Hello, Jenkins!'"); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(script, null, outputMessage); assertEquals("script=print 'Hello, Jenkins!'", outputMessage.getBodyAsString()); } |
### Question:
GroovyScriptHttpMessageConverter implements HttpMessageConverter<GroovyScript> { @Override public GroovyScript read(Class<? extends GroovyScript> clazz, HttpInputMessage inputMessage) throws IOException { throw new UnsupportedOperationException(); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override void write(GroovyScript t, String contentType, HttpOutputMessage outputMessage); @Override GroovyScript read(Class<? extends GroovyScript> clazz, HttpInputMessage inputMessage); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void read() throws Exception { converter.read(GroovyScript.class, null); } |
### Question:
PluginArrayHttpMessageConverter implements HttpMessageConverter<Plugin[]> { @Override public boolean canRead(Class<?> clazz) { return Plugin[].class.equals(clazz); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Plugin[] read(Class<? extends Plugin[]> clazz, HttpInputMessage inputMessage); @Override void write(Plugin[] t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canRead() throws Exception { assertTrue(converter.canRead(Plugin[].class)); assertFalse(converter.canRead(Plugin.class)); assertFalse(converter.canRead(Object.class)); } |
### Question:
PluginArrayHttpMessageConverter implements HttpMessageConverter<Plugin[]> { @Override public boolean canWrite(Class<?> clazz) { return false; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Plugin[] read(Class<? extends Plugin[]> clazz, HttpInputMessage inputMessage); @Override void write(Plugin[] t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canWrite() throws Exception { assertFalse(converter.canWrite(Plugin[].class)); assertFalse(converter.canWrite(Plugin.class)); assertFalse(converter.canWrite(Object.class)); } |
### Question:
PluginArrayHttpMessageConverter implements HttpMessageConverter<Plugin[]> { @Override public void write(Plugin[] t, String contentType, HttpOutputMessage outputMessage) throws IOException { throw new UnsupportedOperationException(); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Plugin[] read(Class<? extends Plugin[]> clazz, HttpInputMessage inputMessage); @Override void write(Plugin[] t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void write() throws Exception { converter.write(new Plugin[] {}, null, null); } |
### Question:
StringGroovyScript implements GroovyScript { @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(script.getBytes()); } StringGroovyScript(String script); @Override InputStream getInputStream(); }### Answer:
@Test public void init() throws Exception { StringGroovyScript script = new StringGroovyScript("print 'Hello, Jenkins!'"); assertEquals("print 'Hello, Jenkins!'", Streams.toString(script.getInputStream())); } |
### Question:
Job implements Serializable { public Long getLastBuildNumber() { return lastBuildNumber; } String getName(); Job setName(String name); String getDisplayName(); Job setDisplayName(String displayName); String getUrl(); Job setUrl(String url); Boolean getBuildable(); Job setBuildable(Boolean buildable); Boolean getInQueue(); Job setInQueue(Boolean inQueue); Long getNextBuildNumber(); Job setNextBuildNumber(Long nextBuildNumber); Long getLastBuildNumber(); Job setLastBuildNumber(Long lastBuildNumber); }### Answer:
@Test public void lastBuildNumber_byDefault_isNull() { assertNull(job.getLastBuildNumber()); } |
### Question:
ScriptingService extends AbstractService { public GroovyResponse runScript(GroovyScript script) { checkArgumentNotNull(script, "Script cannot be null"); return client().postForObject(SEGMENT_SCRIPT_TEXT, script, GroovyResponse.class); } ScriptingService(); ScriptingService(JenkinsClient client); GroovyResponse runScript(GroovyScript script); }### Answer:
@Test(expected = IllegalArgumentException.class) public void runScript_WithNullScript_ThrowsException() throws Exception { service.runScript(null); }
@Test public void runScript() throws Exception { GroovyScript script = new StringGroovyScript("print 'hello'"); when(client.postForObject("/scriptText", script, GroovyResponse.class)).thenReturn(response); assertEquals(response, service.runScript(script)); } |
### Question:
BuildHttpMessageConverter implements HttpMessageConverter<Build> { @Override public boolean canWrite(Class<?> clazz) { return false; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Build read(Class<? extends Build> clazz, HttpInputMessage inputMessage); @Override void write(Build t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canWrite() throws Exception { assertFalse(converter.canWrite(Build.class)); assertFalse(converter.canWrite(Build[].class)); assertFalse(converter.canWrite(Object.class)); } |
### Question:
JobService extends AbstractService { public Job createJob(String name, JobConfiguration configuration) { checkArgumentNotNull(name, "Name cannot be null"); checkArgumentNotNull(configuration, "JobConfiguration cannot be null"); client().postForLocation(SEGMENT_CREATE_ITEM + "?name=" + name, configuration); return getJob(name); } JobService(); JobService(JenkinsClient client); List<Job> getJobs(); Job createJob(String name, JobConfiguration configuration); Job updateJob(String name, JobConfiguration configuration); Job updateJob(Job job, JobConfiguration configuration); void deleteJob(String name); void deleteJob(Job job); Job getJob(String name); JobConfiguration getJobConfiguration(Job job); JobConfiguration getJobConfiguration(String name); Long triggerBuild(Job job); Long triggerBuild(Job job, Map<String, Object> parameters); Build getBuild(Job job, Long buildNumber); Build getBuild(String name, Long buildNumber); Build triggerBuildAndWait(Job job); Build triggerBuildAndWait(Job job, Map<String, Object> parameters); }### Answer:
@Test(expected = IllegalArgumentException.class) public void createJob_WithNullName_ThrowsException() throws Exception { service.createJob(null, jobConfiguration); }
@Test(expected = IllegalArgumentException.class) public void createJob_WithNullJobConfiguration_ThrowsException() throws Exception { service.createJob("vacuum.my.room", null); }
@Test public void createJob() throws Exception { service.createJob("vacuum.my.room", jobConfiguration); verify(client).postForLocation("/createItem?name=vacuum.my.room", jobConfiguration); } |
### Question:
JobService extends AbstractService { public void deleteJob(String name) { checkArgumentNotNull(name, "Name cannot be null"); client().postForLocation(SEGMENT_JOB + "/" + name + SEGMENT_DO_DELETE, null); } JobService(); JobService(JenkinsClient client); List<Job> getJobs(); Job createJob(String name, JobConfiguration configuration); Job updateJob(String name, JobConfiguration configuration); Job updateJob(Job job, JobConfiguration configuration); void deleteJob(String name); void deleteJob(Job job); Job getJob(String name); JobConfiguration getJobConfiguration(Job job); JobConfiguration getJobConfiguration(String name); Long triggerBuild(Job job); Long triggerBuild(Job job, Map<String, Object> parameters); Build getBuild(Job job, Long buildNumber); Build getBuild(String name, Long buildNumber); Build triggerBuildAndWait(Job job); Build triggerBuildAndWait(Job job, Map<String, Object> parameters); }### Answer:
@Test(expected = IllegalArgumentException.class) public void deleteJob_WithNullJob_ThrowsException() throws Exception { service.deleteJob((Job) null); }
@Test(expected = IllegalArgumentException.class) public void deleteJob_WithNullJobName_ThrowsException() throws Exception { service.deleteJob(new Job()); }
@Test public void deleteJob() throws Exception { Job job = new Job().setName("j"); service.deleteJob(job); verify(client).postForLocation("/job/j/doDelete", null); } |
### Question:
JobService extends AbstractService { public List<Job> getJobs() { return asList(client().getForObject(SEGMENT_API_XML + "?depth=2", Job[].class)); } JobService(); JobService(JenkinsClient client); List<Job> getJobs(); Job createJob(String name, JobConfiguration configuration); Job updateJob(String name, JobConfiguration configuration); Job updateJob(Job job, JobConfiguration configuration); void deleteJob(String name); void deleteJob(Job job); Job getJob(String name); JobConfiguration getJobConfiguration(Job job); JobConfiguration getJobConfiguration(String name); Long triggerBuild(Job job); Long triggerBuild(Job job, Map<String, Object> parameters); Build getBuild(Job job, Long buildNumber); Build getBuild(String name, Long buildNumber); Build triggerBuildAndWait(Job job); Build triggerBuildAndWait(Job job, Map<String, Object> parameters); }### Answer:
@Test public void getJobs() throws Exception { Job[] someJobs = new Job[] {}; when(client.getForObject("/api/xml?depth=2", Job[].class)).thenReturn(someJobs); assertEquals(Arrays.asList(someJobs), service.getJobs()); } |
### Question:
JobService extends AbstractService { public JobConfiguration getJobConfiguration(Job job) { checkArgumentNotNull(job, "Job cannot be null"); return getJobConfiguration(job.getName()); } JobService(); JobService(JenkinsClient client); List<Job> getJobs(); Job createJob(String name, JobConfiguration configuration); Job updateJob(String name, JobConfiguration configuration); Job updateJob(Job job, JobConfiguration configuration); void deleteJob(String name); void deleteJob(Job job); Job getJob(String name); JobConfiguration getJobConfiguration(Job job); JobConfiguration getJobConfiguration(String name); Long triggerBuild(Job job); Long triggerBuild(Job job, Map<String, Object> parameters); Build getBuild(Job job, Long buildNumber); Build getBuild(String name, Long buildNumber); Build triggerBuildAndWait(Job job); Build triggerBuildAndWait(Job job, Map<String, Object> parameters); }### Answer:
@Test(expected = IllegalArgumentException.class) public void getJobConfiguration_WithNullJob_ThrowsException() throws Exception { service.getJobConfiguration((Job) null); }
@Test(expected = IllegalArgumentException.class) public void getJobConfiguration_WithNullJobName_ThrowsException() throws Exception { service.getJobConfiguration(new Job()); }
@Test public void getJobConfiguration() throws Exception { Job job = new Job().setName("vacuum.my.room"); when(client.getForObject("/job/vacuum.my.room/config.xml", JobConfiguration.class)).thenReturn(jobConfiguration); assertEquals(jobConfiguration, service.getJobConfiguration(job)); } |
### Question:
BuildHttpMessageConverter implements HttpMessageConverter<Build> { @Override public Build read(Class<? extends Build> clazz, HttpInputMessage inputMessage) throws IOException { XmlResponse xml = new XmlResponse(inputMessage.getBody()); Build build = new Build(); build.setNumber(xml.evaluateAsLong("url")); build.setDuration(xml.evaluateAsLong("building"); if (building) { build.setStatus(Build.Status.PENDING); } else { build.setStatus(Build.Status.valueOf(xml.evaluateAsString("/*/result"))); } return build; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Build read(Class<? extends Build> clazz, HttpInputMessage inputMessage); @Override void write(Build t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void read_WithSuccessfulBuild() throws Exception { HttpInputMessage inputMessage = new MockHttpInputMessage("" + "<freeStyleBuild>" + "<building>false</building>" + "<duration>1450</duration>" + "<number>6</number>" + "<result>SUCCESS</result>" + "<url>http: + "</freeStyleBuild>" ); Build build = converter.read(Build.class, inputMessage); assertEquals(new Long(6), build.getNumber()); assertEquals(Build.Status.SUCCESS, build.getStatus()); assertEquals(new Long(1450), build.getDuration()); assertEquals("http: }
@Test public void read_WithPendingBuild() throws Exception { HttpInputMessage inputMessage = new MockHttpInputMessage("" + "<freeStyleBuild>" + "<building>true</building>" + "<duration>150</duration>" + "<number>45</number>" + "<url>http: + "</freeStyleBuild>" ); Build build = converter.read(Build.class, inputMessage); assertEquals(new Long(45), build.getNumber()); assertEquals(Build.Status.PENDING, build.getStatus()); assertEquals(new Long(150), build.getDuration()); assertEquals("http: } |
### Question:
JobService extends AbstractService { public Job updateJob(String name, JobConfiguration configuration) { checkArgumentNotNull(name, "Name cannot be null"); checkArgumentNotNull(configuration, "JobConfiguration cannot be null"); client().postForLocation(SEGMENT_JOB + "/" + name + SEGMENT_CONFIG_XML, configuration); return getJob(name); } JobService(); JobService(JenkinsClient client); List<Job> getJobs(); Job createJob(String name, JobConfiguration configuration); Job updateJob(String name, JobConfiguration configuration); Job updateJob(Job job, JobConfiguration configuration); void deleteJob(String name); void deleteJob(Job job); Job getJob(String name); JobConfiguration getJobConfiguration(Job job); JobConfiguration getJobConfiguration(String name); Long triggerBuild(Job job); Long triggerBuild(Job job, Map<String, Object> parameters); Build getBuild(Job job, Long buildNumber); Build getBuild(String name, Long buildNumber); Build triggerBuildAndWait(Job job); Build triggerBuildAndWait(Job job, Map<String, Object> parameters); }### Answer:
@Test(expected = IllegalArgumentException.class) public void updateJob_WithNullName_ThrowsException() throws Exception { service.updateJob((String) null, jobConfiguration); }
@Test(expected = IllegalArgumentException.class) public void updateJob_WithNullJobName_ThrowsException() throws Exception { service.updateJob(new Job(), jobConfiguration); }
@Test(expected = IllegalArgumentException.class) public void updateJob_WithNullJobConfiguration_ThrowsException() throws Exception { service.updateJob("my.job", null); }
@Test public void updateJob() throws Exception { service.updateJob("my.job", jobConfiguration); verify(client).postForLocation("/job/my.job/config.xml", jobConfiguration); } |
### Question:
BuildHttpMessageConverter implements HttpMessageConverter<Build> { @Override public void write(Build t, String contentType, HttpOutputMessage outputMessage) throws IOException { throw new UnsupportedOperationException(); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Build read(Class<? extends Build> clazz, HttpInputMessage inputMessage); @Override void write(Build t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void write() throws Exception { converter.write(new Build(), null, null); } |
### Question:
JenkinsService extends AbstractService { public Jenkins getJenkins() { return client().getForObject(SEGMENT_API_XML, Jenkins.class); } JenkinsService(); JenkinsService(JenkinsClient client); Jenkins getJenkins(); }### Answer:
@Test public void getJenkins() throws Exception { Jenkins jenkins = new Jenkins(); when(client.getForObject("/api/xml", Jenkins.class)).thenReturn(jenkins); assertEquals(jenkins, service.getJenkins()); } |
### Question:
PluginService extends AbstractService { public List<Plugin> getPlugins() { return asList(client().getForObject("/pluginManager/api/xml?depth=1", Plugin[].class)); } PluginService(); PluginService(JenkinsClient client); List<Plugin> getPlugins(); }### Answer:
@Test public void getPlugins() throws Exception { Plugin[] somePlugins = new Plugin[] {}; when(client.getForObject("/pluginManager/api/xml?depth=1", Plugin[].class)).thenReturn(somePlugins); assertEquals(Arrays.asList(somePlugins), service.getPlugins()); } |
### Question:
ClassPathJobConfiguration implements JobConfiguration { @Override public InputStream getInputStream() { return getClass().getResourceAsStream("/" + path); } ClassPathJobConfiguration(String path); @Override InputStream getInputStream(); }### Answer:
@Test public void getInputStream() throws Exception { ClassPathJobConfiguration jobConfiguration = new ClassPathJobConfiguration("job/config/empty.xml"); assertEquals("<project></project>", Streams.toString(jobConfiguration.getInputStream())); } |
### Question:
JenkinsClient { public JenkinsClient setCredentials(String user, String password) { checkArgumentNotNull(user, "User cannot be null"); checkArgumentNotNull(password, "Password cannot be null"); getClientHttpRequestFactory().setCredentials(user, password); return this; } JenkinsClient(); JenkinsClient(String host, Integer port); JenkinsClient(String scheme, String host, Integer port, String prefix); T getForObject(String uri, Class<T> responseType); URI postForLocation(String uri, Object request); T postForObject(String uri, Object request, Class<T> responseType); JenkinsClient setCredentials(String user, String password); JenkinsClient setUserAgent(String identifier); ClientHttpRequestFactory getClientHttpRequestFactory(); void setClientHttpRequestFactory(ClientHttpRequestFactory clientHttpRequestFactory); ResponseErrorHandler getResponseErrorHandler(); JenkinsClient setResponseErrorHandler(ResponseErrorHandler responseErrorHandler); List<HttpMessageConverter<?>> getMessageConverters(); void setMessageConverters(List<HttpMessageConverter<?>> messageConverters); static final String DEFAULT_URL_HOST; static final int DEFAULT_URL_PORT; static final String SEGMENT_JOB; static final String SEGMENT_CREATE_ITEM; static final String SEGMENT_DO_DELETE; static final String SEGMENT_API_XML; static final String SEGMENT_CONFIG_XML; static final String SEGMENT_SCRIPT_TEXT; static final String DEFAULT_USER_AGENT; }### Answer:
@Test(expected = IllegalArgumentException.class) public void setCredentials_WithNullUser_ThrowsException() throws Exception { client.setCredentials(null, "passw0rd"); }
@Test(expected = IllegalArgumentException.class) public void setCredentials_WithNullPassword_ThrowsException() throws Exception { client.setCredentials("dpacak", null); }
@Test public void setCredentials() throws Exception { client.setCredentials("dpacak", "passw0rd"); verify(httpRequestFactory).setCredentials("dpacak", "passw0rd"); } |
### Question:
JenkinsClient { public JenkinsClient setUserAgent(String identifier) { checkArgumentNotNull(identifier, "Identifier cannot be null"); getClientHttpRequestFactory().setUserAgent(identifier); return this; } JenkinsClient(); JenkinsClient(String host, Integer port); JenkinsClient(String scheme, String host, Integer port, String prefix); T getForObject(String uri, Class<T> responseType); URI postForLocation(String uri, Object request); T postForObject(String uri, Object request, Class<T> responseType); JenkinsClient setCredentials(String user, String password); JenkinsClient setUserAgent(String identifier); ClientHttpRequestFactory getClientHttpRequestFactory(); void setClientHttpRequestFactory(ClientHttpRequestFactory clientHttpRequestFactory); ResponseErrorHandler getResponseErrorHandler(); JenkinsClient setResponseErrorHandler(ResponseErrorHandler responseErrorHandler); List<HttpMessageConverter<?>> getMessageConverters(); void setMessageConverters(List<HttpMessageConverter<?>> messageConverters); static final String DEFAULT_URL_HOST; static final int DEFAULT_URL_PORT; static final String SEGMENT_JOB; static final String SEGMENT_CREATE_ITEM; static final String SEGMENT_DO_DELETE; static final String SEGMENT_API_XML; static final String SEGMENT_CONFIG_XML; static final String SEGMENT_SCRIPT_TEXT; static final String DEFAULT_USER_AGENT; }### Answer:
@Test(expected = IllegalArgumentException.class) public void setUserAgent_WithNullIdentifier_ThrowsException() throws Exception { client.setUserAgent(null); }
@Test public void setUserAgent() throws Exception { client.setUserAgent("JenkinsJavaAPI"); verify(httpRequestFactory).setUserAgent("JenkinsJavaAPI"); } |
### Question:
JenkinsHttpMessageConverter implements HttpMessageConverter<Jenkins> { @Override public boolean canRead(Class<?> clazz) { return Jenkins.class.equals(clazz); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Jenkins read(Class<? extends Jenkins> clazz, HttpInputMessage inputMessage); @Override void write(Jenkins t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canRead() throws Exception { assertTrue(converter.canRead(Jenkins.class)); assertFalse(converter.canRead(String.class)); } |
### Question:
JenkinsClient { public URI postForLocation(String uri, Object request) { RequestCallback requestCallback = new HttpMessageCoverterRequestCallback(request, messageConverters); HttpHeadersResponseExtractor responseExtractor = new HttpHeadersResponseExtractor(); return execute(newURI(baseUri + uri), HttpMethod.POST, requestCallback, responseExtractor).getLocation(); } JenkinsClient(); JenkinsClient(String host, Integer port); JenkinsClient(String scheme, String host, Integer port, String prefix); T getForObject(String uri, Class<T> responseType); URI postForLocation(String uri, Object request); T postForObject(String uri, Object request, Class<T> responseType); JenkinsClient setCredentials(String user, String password); JenkinsClient setUserAgent(String identifier); ClientHttpRequestFactory getClientHttpRequestFactory(); void setClientHttpRequestFactory(ClientHttpRequestFactory clientHttpRequestFactory); ResponseErrorHandler getResponseErrorHandler(); JenkinsClient setResponseErrorHandler(ResponseErrorHandler responseErrorHandler); List<HttpMessageConverter<?>> getMessageConverters(); void setMessageConverters(List<HttpMessageConverter<?>> messageConverters); static final String DEFAULT_URL_HOST; static final int DEFAULT_URL_PORT; static final String SEGMENT_JOB; static final String SEGMENT_CREATE_ITEM; static final String SEGMENT_DO_DELETE; static final String SEGMENT_API_XML; static final String SEGMENT_CONFIG_XML; static final String SEGMENT_SCRIPT_TEXT; static final String DEFAULT_USER_AGENT; }### Answer:
@SuppressWarnings("unchecked") @Test public void postForLocation() throws Exception { given(converter.canWrite(String.class)).willReturn(true); given(errorHandler.hasError(httpResponse)).willReturn(false); given(httpRequestFactory.createRequest(new URI("http: given(httpRequest.execute()).willReturn(httpResponse); HttpHeaders responseHeaders = new HttpHeaders().setLocation(new URI("http: given(httpResponse.getHeaders()).willReturn(responseHeaders); assertEquals(new URI("http: verify(converter).write("Post payload", null, httpRequest); verify(httpResponse).close(); } |
### Question:
JenkinsHttpMessageConverter implements HttpMessageConverter<Jenkins> { @Override public boolean canWrite(Class<?> clazz) { return false; } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Jenkins read(Class<? extends Jenkins> clazz, HttpInputMessage inputMessage); @Override void write(Jenkins t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void canWrite() throws Exception { assertFalse(converter.canWrite(Jenkins.class)); assertFalse(converter.canWrite(String.class)); } |
### Question:
JenkinsHttpMessageConverter implements HttpMessageConverter<Jenkins> { @Override public Jenkins read(Class<? extends Jenkins> clazz, HttpInputMessage inputMessage) throws IOException { XmlResponse xml = new XmlResponse(inputMessage.getBody()); return new Jenkins() .setMode(Jenkins.MODE.valueOf(xml.evaluateAsString("nodeDescription")) .setNodeName(xml.evaluateAsString("numExecutors")) .setUseSecurity(xml.evaluateAsBoolean("/*/useSecurity")); } @Override boolean canRead(Class<?> clazz); @Override boolean canWrite(Class<?> clazz); @Override Jenkins read(Class<? extends Jenkins> clazz, HttpInputMessage inputMessage); @Override void write(Jenkins t, String contentType, HttpOutputMessage outputMessage); }### Answer:
@Test public void read() throws Exception { HttpInputMessage inputMessage = new MockHttpInputMessage("" + "<hudson>" + "<mode>NORMAL</mode>" + "<nodeDescription>Node description</nodeDescription>" + "<nodeName/>" + "<numExecutors>2</numExecutors>" + "<useSecurity>false</useSecurity>" + "</hudson>" ); Jenkins jenkins = converter.read(Jenkins.class, inputMessage); assertEquals(Jenkins.MODE.NORMAL, jenkins.getMode()); assertEquals("Node description", jenkins.getNodeDescription()); assertNull(jenkins.getNodeName()); assertEquals(new Integer(2), jenkins.getNumExecutors()); assertFalse(jenkins.getUseSecurity()); } |
### Question:
Classes { @SuppressWarnings("unchecked") public static <T> T from(Object implementor) { try { return (T) implementor; } catch (ClassCastException e) { throw new DeveloperError(implementor.toString() + " does not inherit / implement the wanted interface", e); } } private Classes(); @SuppressWarnings("unchecked") static T from(Object implementor); }### Answer:
@Test public void testCastingIsWorking() { Object object = new Integer(0); Integer integer = Classes.from(object); assertThat(integer, instanceOf(Integer.class)); }
@Test(expected = ClassCastException.class) public void testThatAWrongCastingThrowsAnException() { Object object = new Object(); Integer integer = Classes.from(object); } |
### Question:
StringUtils { public static String truncateIfLengthMoreThan(final int maximumLengthAllowed, String string) { if (string.length() > maximumLengthAllowed) { return string.substring(0, maximumLengthAllowed - THREE_DOTS.length()).concat(THREE_DOTS); } else { return string; } } static String join(Collection<?> collection, String delimiter); static String truncateIfLengthMoreThan(final int maximumLengthAllowed, String string); static String[] toStringArray(Object[] objects); }### Answer:
@Test public void testLongStringLengthIsTruncatedAtMaximum() throws Exception { String string = StringUtils.truncateIfLengthMoreThan(SHORT_STRING_LENGTH, RANDOM_STRING); assertEquals(string.length(), SHORT_STRING_LENGTH); }
@Test public void testStringLengthUnchangedIfStringLengthIsLessThanMaximum() throws Exception { String truncatedString = StringUtils.truncateIfLengthMoreThan(LONG_STRING_LENGTH, RANDOM_STRING); assertEquals(truncatedString.length(), RANDOM_STRING.length()); }
@Test public void testLongStringHasThreeDotsWhenLengthIsMoreThanMaximum() throws Exception { String truncatedString = StringUtils.truncateIfLengthMoreThan(SHORT_STRING_LENGTH, RANDOM_STRING); assertEquals(String.valueOf(truncatedString.charAt(SHORT_STRING_LENGTH - 1)), THREE_DOTS); }
@Test public void testStringIsUntouchedWhenLengthIsLessThanMaximum() throws Exception { String truncatedString = StringUtils.truncateIfLengthMoreThan(LONG_STRING_LENGTH, RANDOM_STRING); assertEquals(RANDOM_STRING, truncatedString); } |
### Question:
AndroidUtils { public static int convertToPix(float density, int sizeInDips) { float size = sizeInDips * density; return (int) size; } private AndroidUtils(); static void toggleKeyboard(Context context); static void requestHideKeyboard(Context context, View v); static int convertToDip(DisplayMetrics displayMetrics, int sizeInPixels); static int convertToPix(float density, int sizeInDips); static String getVersionName(Context context); static int deviceDPI(Context c); static String deviceResolution(Context c); static boolean isServiceRunning(Class<? extends Service> service, Context context); }### Answer:
@Test public void testConvertToPix() { int sizeInPix = AndroidUtils.convertToPix(DENSITY, SIZE_IN_DIPS); assertEquals(sizeInPix, SIZE_IN_PIX); } |
### Question:
QueryUtils { public static String createSelectionPlaceholdersOfSize(int size) { if (size == 0) { return ""; } int sizeOfResult = size * 3 - 2; char[] result = new char[sizeOfResult]; for (int i = 0; i < sizeOfResult - 1; i += 3) { result[i] = '?'; result[i + 1] = ','; result[i + 2] = ' '; } result[sizeOfResult - 1] = '?'; return new String(result); } static String createSelectionPlaceholdersOfSize(int size); }### Answer:
@Test public void testSizeOfZeroReturnsEmptyString() { String expected = ""; assertEquals(expected, QueryUtils.createSelectionPlaceholdersOfSize(0)); }
@Test public void testSizeOfOneReturnsJustQuestionMark() { String expected = "?"; assertEquals(expected, QueryUtils.createSelectionPlaceholdersOfSize(1)); }
@Test public void testSizeBiggerThanOneReturnsSameNumberOfQuestionMarkSeparatedByCommas() { String expected = "?, ?, ?, ?, ?, ?, ?, ?, ?, ?"; assertEquals(expected, QueryUtils.createSelectionPlaceholdersOfSize(10)); } |
### Question:
ArrayBag implements Iterable<T> { @SuppressWarnings("unchecked") ArrayBag() { items = (T[]) new Object[2]; last = 0; } @SuppressWarnings("unchecked") ArrayBag(); int size(); void add(T e); ArrayBagIterator iterator(); T item(); boolean isEmpty(); }### Answer:
@Test public void testArrayBag() { ArrayBag<Integer> bag = new ArrayBag<Integer>(); bag.add(1); assertEquals(1, bag.size()); Iterator<Integer> it = bag.iterator(); assertTrue(it.hasNext()); int j = it.next(); assertEquals(1, j); assertFalse(it.hasNext()); it.remove(); assertEquals(0, bag.size()); assertFalse(it.hasNext()); bag.add(1); bag.add(2); assertEquals(2, bag.size()); it = bag.iterator(); assertTrue(it.hasNext()); j = it.next(); assertEquals(1, j); assertTrue(it.hasNext()); it.remove(); assertEquals(1, bag.size()); assertTrue(it.hasNext()); j = it.next(); assertEquals(2, j); assertFalse(it.hasNext()); bag = new ArrayBag<Integer>(); bag.add(1); bag.add(2); bag.add(3); it = bag.iterator(); assertTrue(it.hasNext()); j = it.next(); j = it.next(); it.remove(); j = it.next(); assertEquals(3, j); it.remove(); assertFalse(it.hasNext()); } |
### Question:
OSMWithTags { public static boolean isTrue(String tagValue) { return ("yes".equals(tagValue) || "1".equals(tagValue) || "true".equals(tagValue)); } long getId(); void setId(long id); void addTag(OSMTag tag); void addTag(String key, String value); Map<String, String> getTags(); boolean hasTag(String tag); boolean isTagFalse(String tag); boolean isTagTrue(String tag); boolean doesTagAllowAccess(String tag); String getTag(String tag); Boolean isTag(String tag, String value); String getAssumedName(); Map<String, String> getTagsByPrefix(String prefix); static boolean isFalse(String tagValue); static boolean isTrue(String tagValue); boolean isUnderConstruction(); boolean isGeneralAccessDenied(); boolean isMotorcarExplicitlyDenied(); boolean isMotorcarExplicitlyAllowed(); boolean isBicycleExplicitlyDenied(); boolean isBicycleExplicitlyAllowed(); boolean isPedestrianExplicitlyDenied(); boolean isPedestrianExplicitlyAllowed(); boolean isThroughTrafficExplicitlyDisallowed(); }### Answer:
@Test public void testIsTrue() { assertTrue(OSMWithTags.isTrue("yes")); assertTrue(OSMWithTags.isTrue("1")); assertTrue(OSMWithTags.isTrue("true")); assertFalse(OSMWithTags.isTrue("no")); assertFalse(OSMWithTags.isTrue("0")); assertFalse(OSMWithTags.isTrue("false")); assertFalse(OSMWithTags.isTrue("foo")); assertFalse(OSMWithTags.isTrue("bar")); assertFalse(OSMWithTags.isTrue("baz")); } |
### Question:
OSMWithTags { public boolean isGeneralAccessDenied() { return isTagDeniedAccess("access"); } long getId(); void setId(long id); void addTag(OSMTag tag); void addTag(String key, String value); Map<String, String> getTags(); boolean hasTag(String tag); boolean isTagFalse(String tag); boolean isTagTrue(String tag); boolean doesTagAllowAccess(String tag); String getTag(String tag); Boolean isTag(String tag, String value); String getAssumedName(); Map<String, String> getTagsByPrefix(String prefix); static boolean isFalse(String tagValue); static boolean isTrue(String tagValue); boolean isUnderConstruction(); boolean isGeneralAccessDenied(); boolean isMotorcarExplicitlyDenied(); boolean isMotorcarExplicitlyAllowed(); boolean isBicycleExplicitlyDenied(); boolean isBicycleExplicitlyAllowed(); boolean isPedestrianExplicitlyDenied(); boolean isPedestrianExplicitlyAllowed(); boolean isThroughTrafficExplicitlyDisallowed(); }### Answer:
@Test public void testIsGeneralAccessDenied() { OSMWithTags o = new OSMWithTags(); assertFalse(o.isGeneralAccessDenied()); o.addTag("access", "something"); assertFalse(o.isGeneralAccessDenied()); o.addTag("access", "license"); assertTrue(o.isGeneralAccessDenied()); o.addTag("access", "no"); assertTrue(o.isGeneralAccessDenied()); } |
### Question:
OSMWithTags { public boolean isThroughTrafficExplicitlyDisallowed() { String access = getTag("access"); boolean noThruTraffic = "destination".equals(access) || "private".equals(access) || "customers".equals(access) || "delivery".equals(access) || "forestry".equals(access) || "agricultural".equals(access); return noThruTraffic; } long getId(); void setId(long id); void addTag(OSMTag tag); void addTag(String key, String value); Map<String, String> getTags(); boolean hasTag(String tag); boolean isTagFalse(String tag); boolean isTagTrue(String tag); boolean doesTagAllowAccess(String tag); String getTag(String tag); Boolean isTag(String tag, String value); String getAssumedName(); Map<String, String> getTagsByPrefix(String prefix); static boolean isFalse(String tagValue); static boolean isTrue(String tagValue); boolean isUnderConstruction(); boolean isGeneralAccessDenied(); boolean isMotorcarExplicitlyDenied(); boolean isMotorcarExplicitlyAllowed(); boolean isBicycleExplicitlyDenied(); boolean isBicycleExplicitlyAllowed(); boolean isPedestrianExplicitlyDenied(); boolean isPedestrianExplicitlyAllowed(); boolean isThroughTrafficExplicitlyDisallowed(); }### Answer:
@Test public void testIsThroughTrafficExplicitlyDisallowed() { OSMWithTags o = new OSMWithTags(); assertFalse(o.isThroughTrafficExplicitlyDisallowed()); o.addTag("access", "something"); assertFalse(o.isThroughTrafficExplicitlyDisallowed()); o.addTag("access", "destination"); assertTrue(o.isThroughTrafficExplicitlyDisallowed()); o.addTag("access", "forestry"); assertTrue(o.isThroughTrafficExplicitlyDisallowed()); o.addTag("access", "private"); assertTrue(o.isThroughTrafficExplicitlyDisallowed()); } |
### Question:
OSMWay extends OSMWithTags { public boolean isBicycleDismountForced() { String bicycle = getTag("bicycle"); return isTag("cycleway", "dismount") || "dismount".equals(bicycle); } void addNodeRef(OSMNodeRef nodeRef); void addNodeRef(long nodeRef); List<Long> getNodeRefs(); String toString(); boolean isBicycleDismountForced(); boolean isSteps(); boolean isRoundabout(); boolean isOneWayForwardDriving(); boolean isOneWayReverseDriving(); boolean isOneWayForwardBicycle(); boolean isOneWayReverseBicycle(); boolean isOpposableCycleway(); }### Answer:
@Test public void testIsBicycleDismountForced() { OSMWay way = new OSMWay(); assertFalse(way.isBicycleDismountForced()); way.addTag("bicycle", "dismount"); assertTrue(way.isBicycleDismountForced()); } |
### Question:
OSMWay extends OSMWithTags { public boolean isSteps() { return "steps".equals(getTag("highway")); } void addNodeRef(OSMNodeRef nodeRef); void addNodeRef(long nodeRef); List<Long> getNodeRefs(); String toString(); boolean isBicycleDismountForced(); boolean isSteps(); boolean isRoundabout(); boolean isOneWayForwardDriving(); boolean isOneWayReverseDriving(); boolean isOneWayForwardBicycle(); boolean isOneWayReverseBicycle(); boolean isOpposableCycleway(); }### Answer:
@Test public void testIsSteps() { OSMWay way = new OSMWay(); assertFalse(way.isSteps()); way.addTag("highway", "primary"); assertFalse(way.isSteps()); way.addTag("highway", "steps"); assertTrue(way.isSteps()); } |
### Question:
OSMWay extends OSMWithTags { public boolean isRoundabout() { return "roundabout".equals(getTag("junction")); } void addNodeRef(OSMNodeRef nodeRef); void addNodeRef(long nodeRef); List<Long> getNodeRefs(); String toString(); boolean isBicycleDismountForced(); boolean isSteps(); boolean isRoundabout(); boolean isOneWayForwardDriving(); boolean isOneWayReverseDriving(); boolean isOneWayForwardBicycle(); boolean isOneWayReverseBicycle(); boolean isOpposableCycleway(); }### Answer:
@Test public void testIsRoundabout() { OSMWay way = new OSMWay(); assertFalse(way.isRoundabout()); way.addTag("junction", "dovetail"); assertFalse(way.isRoundabout()); way.addTag("junction", "roundabout"); assertTrue(way.isRoundabout()); } |
### Question:
OSMWay extends OSMWithTags { public boolean isOpposableCycleway() { String cycleway = getTag("cycleway"); String cyclewayLeft = getTag("cycleway:left"); String cyclewayRight = getTag("cycleway:right"); return (cycleway != null && cycleway.startsWith("opposite")) || (cyclewayLeft != null && cyclewayLeft.startsWith("opposite")) || (cyclewayRight != null && cyclewayRight.startsWith("opposite")); } void addNodeRef(OSMNodeRef nodeRef); void addNodeRef(long nodeRef); List<Long> getNodeRefs(); String toString(); boolean isBicycleDismountForced(); boolean isSteps(); boolean isRoundabout(); boolean isOneWayForwardDriving(); boolean isOneWayReverseDriving(); boolean isOneWayForwardBicycle(); boolean isOneWayReverseBicycle(); boolean isOpposableCycleway(); }### Answer:
@Test public void testIsOpposableCycleway() { OSMWay way = new OSMWay(); assertFalse(way.isOpposableCycleway()); way.addTag("cycleway", "notatagvalue"); assertFalse(way.isOpposableCycleway()); way.addTag("cycleway", "oppo"); assertFalse(way.isOpposableCycleway()); way.addTag("cycleway", "opposite"); assertTrue(way.isOpposableCycleway()); way.addTag("cycleway", "nope"); way.addTag("cycleway:left", "opposite_side"); assertTrue(way.isOpposableCycleway()); } |
### Question:
IntersectionVertex extends StreetVertex { public boolean inferredFreeFlowing() { if (this.freeFlowing) { return true; } return getDegreeIn() == 1 && getDegreeOut() == 1 && !this.trafficLight; } IntersectionVertex(Graph g, String label, double x, double y, String name); IntersectionVertex(Graph g, String label, double x, double y); boolean inferredFreeFlowing(); }### Answer:
@Test public void testInferredFreeFlowing() { IntersectionVertex iv = new IntersectionVertex(_graph, "vertex", 1.0, 2.0); assertFalse(iv.isTrafficLight()); assertFalse(iv.inferredFreeFlowing()); assertEquals(0, iv.getDegreeIn()); assertEquals(0, iv.getDegreeOut()); iv.setTrafficLight(true); assertTrue(iv.isTrafficLight()); assertFalse(iv.inferredFreeFlowing()); iv.addIncoming(fromEdge); assertEquals(1, iv.getDegreeIn()); assertEquals(0, iv.getDegreeOut()); assertFalse(iv.inferredFreeFlowing()); iv.addOutgoing(straightAheadEdge); assertEquals(1, iv.getDegreeIn()); assertEquals(1, iv.getDegreeOut()); assertFalse(iv.inferredFreeFlowing()); iv.setTrafficLight(false); assertFalse(iv.isTrafficLight()); assertTrue(iv.inferredFreeFlowing()); iv.setFreeFlowing(false); assertFalse(iv.isFreeFlowing()); } |
### Question:
IncrementingIdGenerator implements UniqueIdGenerator<T> { public int getId(T elem) { return next++; } IncrementingIdGenerator(); IncrementingIdGenerator(int start); int getId(T elem); }### Answer:
@Test public void testConstruct() { UniqueIdGenerator<String> gen = new IncrementingIdGenerator<String>(); assertEquals(0, gen.getId("")); assertEquals(1, gen.getId("fake")); assertEquals(2, gen.getId("foo")); }
@Test public void testConstructWithStart() { int start = 102; UniqueIdGenerator<String> gen = new IncrementingIdGenerator<String>(start); assertEquals(start, gen.getId("")); assertEquals(start + 1, gen.getId("fake")); assertEquals(start + 2, gen.getId("foo")); } |
### Question:
RoutingRequestBuilder { public RoutingRequestBuilder setNumItineraries(int n) { routingRequest.setNumItineraries(n); return this; } RoutingRequestBuilder(); RoutingRequestBuilder(TripParameters tripParams); RoutingRequestBuilder(RoutingRequest prototypeRequest); RoutingRequestBuilder setStartTime(long startTime); RoutingRequestBuilder setArriveBy(long arriveBy); RoutingRequestBuilder addTripParameters(TripParameters tripParams); RoutingRequestBuilder setTravelModes(TravelModeSet modes); RoutingRequestBuilder setTravelModes(Collection<TravelMode> modes); RoutingRequestBuilder setOrigin(Location origin); RoutingRequestBuilder setOrigin(LatLng origin); RoutingRequestBuilder setDestination(Location dest); RoutingRequestBuilder setDestination(LatLng dest); RoutingRequestBuilder setBatch(boolean batch); RoutingRequestBuilder setGraph(Graph g); RoutingRequestBuilder setNumItineraries(int n); RoutingRequest build(); }### Answer:
@Test public void testSetNumItineraries() { int n = 3; RoutingRequest rr = (new RoutingRequestBuilder()).setNumItineraries(n).build(); assertEquals(n, rr.getNumItineraries()); } |
### Question:
RoutingRequestBuilder { public RoutingRequestBuilder setStartTime(long startTime) { routingRequest.dateTime = startTime; routingRequest.setArriveBy(false); return this; } RoutingRequestBuilder(); RoutingRequestBuilder(TripParameters tripParams); RoutingRequestBuilder(RoutingRequest prototypeRequest); RoutingRequestBuilder setStartTime(long startTime); RoutingRequestBuilder setArriveBy(long arriveBy); RoutingRequestBuilder addTripParameters(TripParameters tripParams); RoutingRequestBuilder setTravelModes(TravelModeSet modes); RoutingRequestBuilder setTravelModes(Collection<TravelMode> modes); RoutingRequestBuilder setOrigin(Location origin); RoutingRequestBuilder setOrigin(LatLng origin); RoutingRequestBuilder setDestination(Location dest); RoutingRequestBuilder setDestination(LatLng dest); RoutingRequestBuilder setBatch(boolean batch); RoutingRequestBuilder setGraph(Graph g); RoutingRequestBuilder setNumItineraries(int n); RoutingRequest build(); }### Answer:
@Test public void testSetStartTime() { long now = this.getTimeSeconds(); RoutingRequest rr = (new RoutingRequestBuilder()).setStartTime(now).build(); assertEquals(now, rr.dateTime); assertFalse(rr.arriveBy); } |
### Question:
RoutingRequestBuilder { public RoutingRequestBuilder setArriveBy(long arriveBy) { routingRequest.dateTime = arriveBy; routingRequest.setArriveBy(true); return this; } RoutingRequestBuilder(); RoutingRequestBuilder(TripParameters tripParams); RoutingRequestBuilder(RoutingRequest prototypeRequest); RoutingRequestBuilder setStartTime(long startTime); RoutingRequestBuilder setArriveBy(long arriveBy); RoutingRequestBuilder addTripParameters(TripParameters tripParams); RoutingRequestBuilder setTravelModes(TravelModeSet modes); RoutingRequestBuilder setTravelModes(Collection<TravelMode> modes); RoutingRequestBuilder setOrigin(Location origin); RoutingRequestBuilder setOrigin(LatLng origin); RoutingRequestBuilder setDestination(Location dest); RoutingRequestBuilder setDestination(LatLng dest); RoutingRequestBuilder setBatch(boolean batch); RoutingRequestBuilder setGraph(Graph g); RoutingRequestBuilder setNumItineraries(int n); RoutingRequest build(); }### Answer:
@Test public void testSetArriveBy() { long t = this.getTimeSeconds() + 30 * 60; RoutingRequest rr = (new RoutingRequestBuilder()).setArriveBy(t).build(); assertEquals(t, rr.dateTime); assertTrue(rr.arriveBy); } |
### Question:
TravelModeSet extends HashSet<TravelMode> { public TraverseModeSet toTraverseModeSet() { TraverseModeSet modeSet = new TraverseModeSet(); for (TravelMode travelMode : this) { TraverseMode traverseMode = (new TravelModeWrapper(travelMode)).toTraverseMode(); modeSet.setMode(traverseMode, true); } return modeSet; } TravelModeSet(); TravelModeSet(Collection<TravelMode> modes); TraverseModeSet toTraverseModeSet(); }### Answer:
@Test public void testAdd() { TravelModeSet modeSet = new TravelModeSet(); modeSet.add(TravelMode.WALK); modeSet.add(TravelMode.ANY_TRAIN); TraverseModeSet traverseModes = modeSet.toTraverseModeSet(); assertTrue(traverseModes.getWalk()); assertTrue(traverseModes.getTrainish()); assertFalse(traverseModes.getBicycle()); }
@Test public void testConstructFromSet() { Set<TravelMode> modes = new HashSet<TravelMode>(3); modes.add(TravelMode.WALK); modes.add(TravelMode.ANY_TRAIN); TravelModeSet modeSet = new TravelModeSet(modes); TraverseModeSet traverseModes = modeSet.toTraverseModeSet(); assertTrue(traverseModes.getWalk()); assertTrue(traverseModes.getTrainish()); assertFalse(traverseModes.getBicycle()); } |
### Question:
TravelModeWrapper { public TraverseMode toTraverseMode() { switch (travelMode) { case BICYCLE: return TraverseMode.BICYCLE; case WALK: return TraverseMode.WALK; case CAR: return TraverseMode.CAR; case CUSTOM_MOTOR_VEHICLE: return TraverseMode.CUSTOM_MOTOR_VEHICLE; case TRAM: return TraverseMode.TRAM; case SUBWAY: return TraverseMode.SUBWAY; case RAIL: return TraverseMode.RAIL; case ANY_TRAIN: return TraverseMode.TRAINISH; case ANY_TRANSIT: return TraverseMode.TRANSIT; default: return null; } } TraverseMode toTraverseMode(); }### Answer:
@Test public void testToTraverseMode() { Map<TravelMode, TraverseMode> modeMap = new HashMap<TravelMode, TraverseMode>(); modeMap.put(TravelMode.BICYCLE, TraverseMode.BICYCLE); modeMap.put(TravelMode.CAR, TraverseMode.CAR); modeMap.put(TravelMode.CUSTOM_MOTOR_VEHICLE, TraverseMode.CUSTOM_MOTOR_VEHICLE); modeMap.put(TravelMode.WALK, TraverseMode.WALK); modeMap.put(TravelMode.ANY_TRAIN, TraverseMode.TRAINISH); modeMap.put(TravelMode.ANY_TRANSIT, TraverseMode.TRANSIT); for (TravelMode travelMode : modeMap.keySet()) { TraverseMode expectedTraverseMode = modeMap.get(travelMode); TraverseMode actualTraverseMode = (new TravelModeWrapper(travelMode)).toTraverseMode(); assertEquals(expectedTraverseMode, actualTraverseMode); } } |
### Question:
OTPServiceImpl implements OTPService.Iface { @Override public GraphEdgesResponse GetEdges(GraphEdgesRequest req) throws TException { LOG.debug("GetEdges called"); long startTime = System.currentTimeMillis(); GraphEdgesResponse res = new GraphEdgesResponse(); Graph g = graphService.getGraph(); res.setEdges(makeGraphEdges(g, req)); res.setCompute_time_millis(System.currentTimeMillis() - startTime); return res; } @Override GraphVerticesResponse GetVertices(GraphVerticesRequest req); @Override GraphEdgesResponse GetEdges(GraphEdgesRequest req); @Override FindNearestVertexResponse FindNearestVertex(FindNearestVertexRequest req); @Override BulkFindNearestVertexResponse BulkFindNearestVertex(BulkFindNearestVertexRequest req); @Override FindNearestEdgesResponse FindNearestEdges(FindNearestEdgesRequest req); @Override BulkFindNearestEdgesResponse BulkFindNearestEdges(BulkFindNearestEdgesRequest req); @Override FindPathsResponse FindPaths(FindPathsRequest req); @Override BulkPathsResponse BulkFindPaths(BulkPathsRequest req); }### Answer:
@Test public void testGetGraphEdges() throws TException { GraphEdgesRequest req = new GraphEdgesRequest(); req.validate(); req.setStreet_edges_only(true); GraphEdgesResponse res = serviceImpl.GetEdges(req); Set<Integer> expectedEdgeIds = new HashSet<Integer>(); for (Edge e : graph.getStreetEdges()) { expectedEdgeIds.add(e.getId()); } Set<Integer> actualEdgeIds = new HashSet<Integer>(res.getEdgesSize()); for (GraphEdge ge : res.getEdges()) { actualEdgeIds.add(ge.getId()); } assertTrue(expectedEdgeIds.equals(actualEdgeIds)); } |
### Question:
OTPServiceImpl implements OTPService.Iface { @Override public GraphVerticesResponse GetVertices(GraphVerticesRequest req) throws TException { LOG.debug("GetVertices called"); long startTime = System.currentTimeMillis(); GraphVerticesResponse res = new GraphVerticesResponse(); Graph g = graphService.getGraph(); res.setVertices(makeGraphVertices(g)); res.setCompute_time_millis(System.currentTimeMillis() - startTime); return res; } @Override GraphVerticesResponse GetVertices(GraphVerticesRequest req); @Override GraphEdgesResponse GetEdges(GraphEdgesRequest req); @Override FindNearestVertexResponse FindNearestVertex(FindNearestVertexRequest req); @Override BulkFindNearestVertexResponse BulkFindNearestVertex(BulkFindNearestVertexRequest req); @Override FindNearestEdgesResponse FindNearestEdges(FindNearestEdgesRequest req); @Override BulkFindNearestEdgesResponse BulkFindNearestEdges(BulkFindNearestEdgesRequest req); @Override FindPathsResponse FindPaths(FindPathsRequest req); @Override BulkPathsResponse BulkFindPaths(BulkPathsRequest req); }### Answer:
@Test public void testGetGraphVertices() throws TException { GraphVerticesRequest req = new GraphVerticesRequest(); req.validate(); GraphVerticesResponse res = serviceImpl.GetVertices(req); Set<Integer> expectedVertexIds = new HashSet<Integer>(); for (Vertex v : graph.getVertices()) { expectedVertexIds.add(v.getIndex()); } Set<Integer> actualVertexIds = new HashSet<Integer>(res.getVerticesSize()); for (GraphVertex gv : res.getVertices()) { actualVertexIds.add(gv.getId()); } assertTrue(expectedVertexIds.equals(actualVertexIds)); } |
### Question:
OTPServiceImpl implements OTPService.Iface { @Override public FindNearestVertexResponse FindNearestVertex(FindNearestVertexRequest req) throws TException { LOG.debug("FindNearestVertex called"); long startTime = System.currentTimeMillis(); VertexQuery q = req.getQuery(); VertexResult result = findNearbyVertex(q); FindNearestVertexResponse res = new FindNearestVertexResponse(); res.setResult(result); res.setCompute_time_millis(System.currentTimeMillis() - startTime); return res; } @Override GraphVerticesResponse GetVertices(GraphVerticesRequest req); @Override GraphEdgesResponse GetEdges(GraphEdgesRequest req); @Override FindNearestVertexResponse FindNearestVertex(FindNearestVertexRequest req); @Override BulkFindNearestVertexResponse BulkFindNearestVertex(BulkFindNearestVertexRequest req); @Override FindNearestEdgesResponse FindNearestEdges(FindNearestEdgesRequest req); @Override BulkFindNearestEdgesResponse BulkFindNearestEdges(BulkFindNearestEdgesRequest req); @Override FindPathsResponse FindPaths(FindPathsRequest req); @Override BulkPathsResponse BulkFindPaths(BulkPathsRequest req); }### Answer:
@Test public void testFindNearestVertex() throws TException { for (Vertex v : graph.getVertices()) { FindNearestVertexRequest req = new FindNearestVertexRequest(); VertexQuery q = new VertexQuery(); q.setLocation(getLocationForVertex(v)); req.setQuery(q); FindNearestVertexResponse res = serviceImpl.FindNearestVertex(req); GraphVertex gv = res.getResult().getNearest_vertex(); int expectedId = v.getIndex(); int actualId = gv.getId(); if (expectedId != actualId) { LatLng ll = gv.getLat_lng(); Coordinate outCoord = new Coordinate(ll.getLng(), ll.getLat()); assertTrue(v.getCoordinate().distance(outCoord) < 0.00001); } } } |
### Question:
GeocoderServer { @GET @Produces({MediaType.APPLICATION_XML + "; charset=UTF-8", MediaType.APPLICATION_JSON + "; charset=UTF-8"}) public GeocoderResults geocode( @QueryParam("address") String address, @QueryParam("bbox") String bbox) { if (address == null) { error("no address"); } if (bbox != null) { String[] elem = bbox.split(","); if (elem.length == 4) { try { double x1 = Double.parseDouble(elem[0]); double y1 = Double.parseDouble(elem[1]); double x2 = Double.parseDouble(elem[2]); double y2 = Double.parseDouble(elem[3]); Envelope envelope = new Envelope(new Coordinate(x1, y1), new Coordinate(x2, y2)); return geocoder.geocode(address, envelope); } catch (NumberFormatException e) { error("bad bounding box: use left,top,right,bottom"); } } else { error("bad bounding box: use left,top,right,bottom"); } } return geocoder.geocode(address, null); } void setGeocoder(Geocoder geocoder); @GET @Produces({MediaType.APPLICATION_XML + "; charset=UTF-8", MediaType.APPLICATION_JSON + "; charset=UTF-8"}) GeocoderResults geocode(
@QueryParam("address") String address,
@QueryParam("bbox") String bbox); }### Answer:
@Test(expected = WebApplicationException.class) public void testGeocodeNoAddress() { geocoderServer.geocode(null, null); fail("Should have thrown an error"); } |
### Question:
GeocoderNullImpl implements Geocoder { @Override public GeocoderResults geocode(String address, Envelope bbox) { return new GeocoderResults(ERROR_MSG); } @Override GeocoderResults geocode(String address, Envelope bbox); }### Answer:
@Test public void testGeocode() { Geocoder nullGeocoder = new GeocoderNullImpl(); GeocoderResults result = nullGeocoder.geocode("121 elm street", null); assertEquals("stub response", GeocoderNullImpl.ERROR_MSG, result.getError()); } |
### Question:
GenericLocation implements Cloneable { @Override public String toString() { if (this.place != null && !this.place.isEmpty()) { if (this.name == null || this.name.isEmpty()) { return this.place; } else { return String.format("%s::%s", this.name, this.place); } } return String.format("%s,%s", this.lat, this.lng); } GenericLocation(); GenericLocation(double lat, double lng); GenericLocation(Coordinate coord); GenericLocation(double lat, double lng, double heading); GenericLocation(String name, String place); GenericLocation(NamedPlace np); static GenericLocation fromOldStyleString(String input); boolean hasHeading(); boolean hasName(); boolean hasPlace(); boolean hasCoordinate(); boolean hasEdgeId(); NamedPlace getNamedPlace(); Coordinate getCoordinate(); @Override String toString(); String toDescriptiveString(); @Override GenericLocation clone(); }### Answer:
@Test public void testToString() { String input = "name::1.0,2.5"; GenericLocation loc = GenericLocation.fromOldStyleString(input); assertEquals(input, loc.toString()); assertTrue(loc.hasCoordinate()); assertFalse(loc.hasHeading()); input = "name::12345"; loc = GenericLocation.fromOldStyleString(input); assertEquals(input, loc.toString()); assertFalse(loc.hasCoordinate()); assertFalse(loc.hasHeading()); input = "name"; loc = GenericLocation.fromOldStyleString(input); assertEquals(input, loc.toString()); assertFalse(loc.hasCoordinate()); assertFalse(loc.hasHeading()); } |
### Question:
OSMNode extends OSMWithTags { public boolean isMultiLevel() { return hasTag("highway") && "elevator".equals(getTag("highway")); } String toString(); int getCapacity(); boolean isMultiLevel(); boolean hasTrafficLight(); }### Answer:
@Test public void testIsMultiLevel() { OSMNode node = new OSMNode(); assertFalse(node.isMultiLevel()); node.addTag("highway", "var"); assertFalse(node.isMultiLevel()); node.addTag("highway", "elevator"); assertTrue(node.isMultiLevel()); } |
### Question:
OSMNode extends OSMWithTags { public int getCapacity() throws NumberFormatException { String capacity = getTag("capacity"); if (capacity == null) { return 0; } return Integer.parseInt(getTag("capacity")); } String toString(); int getCapacity(); boolean isMultiLevel(); boolean hasTrafficLight(); }### Answer:
@Test public void testGetCapacity() { OSMNode node = new OSMNode(); assertFalse(node.hasTag("capacity")); assertEquals(0, node.getCapacity()); try { node.addTag("capacity", "foobie"); node.getCapacity(); assertFalse(true); } catch (NumberFormatException e) {} node.addTag("capacity", "10"); assertTrue(node.hasTag("capacity")); assertEquals(10, node.getCapacity()); } |
### Question:
OSMWithTags { public boolean hasTag(String tag) { tag = tag.toLowerCase(); return _tags != null && _tags.containsKey(tag); } long getId(); void setId(long id); void addTag(OSMTag tag); void addTag(String key, String value); Map<String, String> getTags(); boolean hasTag(String tag); boolean isTagFalse(String tag); boolean isTagTrue(String tag); boolean doesTagAllowAccess(String tag); String getTag(String tag); Boolean isTag(String tag, String value); String getAssumedName(); Map<String, String> getTagsByPrefix(String prefix); static boolean isFalse(String tagValue); static boolean isTrue(String tagValue); boolean isUnderConstruction(); boolean isGeneralAccessDenied(); boolean isMotorcarExplicitlyDenied(); boolean isMotorcarExplicitlyAllowed(); boolean isBicycleExplicitlyDenied(); boolean isBicycleExplicitlyAllowed(); boolean isPedestrianExplicitlyDenied(); boolean isPedestrianExplicitlyAllowed(); boolean isThroughTrafficExplicitlyDisallowed(); }### Answer:
@Test public void testHasTag() { OSMWithTags o = new OSMWithTags(); assertFalse(o.hasTag("foo")); assertFalse(o.hasTag("FOO")); o.addTag("foo", "bar"); assertTrue(o.hasTag("foo")); assertTrue(o.hasTag("FOO")); } |
### Question:
OSMWithTags { public String getTag(String tag) { tag = tag.toLowerCase(); if (_tags != null && _tags.containsKey(tag)) return _tags.get(tag); return null; } long getId(); void setId(long id); void addTag(OSMTag tag); void addTag(String key, String value); Map<String, String> getTags(); boolean hasTag(String tag); boolean isTagFalse(String tag); boolean isTagTrue(String tag); boolean doesTagAllowAccess(String tag); String getTag(String tag); Boolean isTag(String tag, String value); String getAssumedName(); Map<String, String> getTagsByPrefix(String prefix); static boolean isFalse(String tagValue); static boolean isTrue(String tagValue); boolean isUnderConstruction(); boolean isGeneralAccessDenied(); boolean isMotorcarExplicitlyDenied(); boolean isMotorcarExplicitlyAllowed(); boolean isBicycleExplicitlyDenied(); boolean isBicycleExplicitlyAllowed(); boolean isPedestrianExplicitlyDenied(); boolean isPedestrianExplicitlyAllowed(); boolean isThroughTrafficExplicitlyDisallowed(); }### Answer:
@Test public void testGetTag() { OSMWithTags o = new OSMWithTags(); assertNull(o.getTag("foo")); assertNull(o.getTag("FOO")); o.addTag("foo", "bar"); assertEquals("bar", o.getTag("foo")); assertEquals("bar", o.getTag("FOO")); } |
### Question:
OSMWithTags { public static boolean isFalse(String tagValue) { return ("no".equals(tagValue) || "0".equals(tagValue) || "false".equals(tagValue)); } long getId(); void setId(long id); void addTag(OSMTag tag); void addTag(String key, String value); Map<String, String> getTags(); boolean hasTag(String tag); boolean isTagFalse(String tag); boolean isTagTrue(String tag); boolean doesTagAllowAccess(String tag); String getTag(String tag); Boolean isTag(String tag, String value); String getAssumedName(); Map<String, String> getTagsByPrefix(String prefix); static boolean isFalse(String tagValue); static boolean isTrue(String tagValue); boolean isUnderConstruction(); boolean isGeneralAccessDenied(); boolean isMotorcarExplicitlyDenied(); boolean isMotorcarExplicitlyAllowed(); boolean isBicycleExplicitlyDenied(); boolean isBicycleExplicitlyAllowed(); boolean isPedestrianExplicitlyDenied(); boolean isPedestrianExplicitlyAllowed(); boolean isThroughTrafficExplicitlyDisallowed(); }### Answer:
@Test public void testIsFalse() { assertTrue(OSMWithTags.isFalse("no")); assertTrue(OSMWithTags.isFalse("0")); assertTrue(OSMWithTags.isFalse("false")); assertFalse(OSMWithTags.isFalse("yes")); assertFalse(OSMWithTags.isFalse("1")); assertFalse(OSMWithTags.isFalse("true")); assertFalse(OSMWithTags.isFalse("foo")); assertFalse(OSMWithTags.isFalse("bar")); assertFalse(OSMWithTags.isFalse("baz")); } |
### Question:
MainActivity extends RoboFragmentActivity { @Override public void onBackPressed() { if (mChronoFragment.isBackPressReset) { mChronoFragment.isBackPressReset = false; mBackPressedOnce = false; } if (mBackPressedOnce) { super.onBackPressed(); } else { mBackPressedOnce = true; Toast toast = Toast.makeText(this, R.string.press_back_again, Toast.LENGTH_SHORT); toast.show(); } } MainActivity(); @Override void onBackPressed(); void endMeeting(); void restartMeeting(); }### Answer:
@Test public void whenTwoBackPressesThenExit() { out.onBackPressed(); assertEquals(out.getString(R.string.press_back_again), ShadowToast.getTextOfLatestToast()); assertFalse(out.isFinishing()); out.onBackPressed(); assertTrue(out.isFinishing()); }
@Test public void whenTwoBackPressesInResultsThenExit() { mPagerListener.onPageSelected(1); out.onBackPressed(); assertEquals(out.getString(R.string.press_back_again), ShadowToast.getTextOfLatestToast()); assertFalse(out.isFinishing()); out.onBackPressed(); assertTrue(out.isFinishing()); assertNull(shadowOut.getNextStartedActivity()); } |
### Question:
ChronoFragment extends RoboFragment implements ChronoInterface { public int getNumberOfParticipants() { return mNumberOfParticipants; } @Override View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); @Override void onStart(); @Override void onResume(); int getNumberOfParticipants(); @Override void setTime(int time); void pauseTickSound(); @Override void setDailyTimer(final String string); @Override void timeOut(); @Override void setCountDown(final String string); void resetBackground(); @Override void onStop(); int getNumberOfTimeouts(); String getPreparationTime(); static final String TOTAL_TIME; static final String TIMEOUTS; static final String WARMUP_TIME; static final String PREFS_NAME; static final String TIME_SLOT_LENGTH; }### Answer:
@Test public void whenInPauseDoNotGoToNextParticipant() { wholeLayout.performClick(); wholeLayout.performLongClick(); when(mockTimer.isCountDownPaused()).thenReturn(true); wholeLayout.performClick(); assertEquals(1, out.getNumberOfParticipants()); } |
### Question:
SlotSeekBarController { OnSeekBarChangeListener getListener() { return mListener; } @Inject SlotSeekBarController(); void configure(SeekBar seekBar, ChronoInterface chronoInterface); static final int MINIMUM_INTERVAL; static final int DEFAULT_VALUE; }### Answer:
@Test public void whenSeekBarIsSetThenAssignListener() { verify(mockSeekBar).setOnSeekBarChangeListener(out.getListener()); } |
### Question:
EndMeetingPageTransformer implements PageTransformer { @Override public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position < 0) { view.setAlpha(1 + position * 2); } else { view.setAlpha(1); view.setTranslationX((int) (pageWidth * -position * 0.7)); view.setScaleX(1 - position / 8); view.setScaleY(1 - position / 8); } } @Override void transformPage(View view, float position); }### Answer:
@Test public void whenStillThenShowsProperly() { out.transformPage(mockView, 0); verify(mockView).setAlpha(1f); verify(mockView).setTranslationX(0.0f); verify(mockView).setScaleX(1f); verify(mockView).setScaleY(1f); }
@Test public void whenDissapearingToTheLeft() { out.transformPage(mockView, -0.25f); verify(mockView).setAlpha(0.5f); }
@Test public void whenAppearingFromTheRight() { out.transformPage(mockView, 0.5f); verify(mockView).setAlpha(1f); verify(mockView).setTranslationX(-35f); verify(mockView).setScaleX((float) (1 - 0.5 / 8)); verify(mockView).setScaleY((float) (1 - 0.5 / 8)); } |
### Question:
ChronoFragment extends RoboFragment implements ChronoInterface { @Override public void timeOut() { mNumberOfTimeouts++; if (mAlarmPlayer != null) { mAlarmPlayer.start(); } new Thread(new Runnable() { @Override public void run() { if (mTickPlayer != null) { mTickPlayer.start(); } } }).start(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mWholeLayout.setBackgroundResource(R.drawable.timeout_background_gradient); } }); } @Override View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); @Override void onStart(); @Override void onResume(); int getNumberOfParticipants(); @Override void setTime(int time); void pauseTickSound(); @Override void setDailyTimer(final String string); @Override void timeOut(); @Override void setCountDown(final String string); void resetBackground(); @Override void onStop(); int getNumberOfTimeouts(); String getPreparationTime(); static final String TOTAL_TIME; static final String TIMEOUTS; static final String WARMUP_TIME; static final String PREFS_NAME; static final String TIME_SLOT_LENGTH; }### Answer:
@Test public void whenResetCountDownThenUndoTimeout() { when(mockTickPlayer.isPlaying()).thenReturn(true); wholeLayout.performClick(); assertEquals("Participant:1", mParticipantTextView.getText().toString()); out.timeOut(); wholeLayout.performClick(); verify(mockTickPlayer).isPlaying(); verify(mockTickPlayer).pause(); assertFalse(0xFFFF0000 == Robolectric.shadowOf(wholeLayout).getBackgroundColor()); } |
### Question:
ChronoFragment extends RoboFragment implements ChronoInterface { @Override public void onResume() { super.onResume(); int timeSlotLength = getSharedPreferences().getInt(TIME_SLOT_LENGTH, -1); if (timeSlotLength == -1) { timeSlotLength = SlotSeekBarController.DEFAULT_VALUE; } mScrumTimer.setTimeSlotLength(timeSlotLength); mSeekBar.setVisibility(View.VISIBLE); mParticipantTextView.setVisibility(View.GONE); mSeekBar.setProgress(timeSlotLength); setTime(timeSlotLength); } @Override View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); @Override void onStart(); @Override void onResume(); int getNumberOfParticipants(); @Override void setTime(int time); void pauseTickSound(); @Override void setDailyTimer(final String string); @Override void timeOut(); @Override void setCountDown(final String string); void resetBackground(); @Override void onStop(); int getNumberOfTimeouts(); String getPreparationTime(); static final String TOTAL_TIME; static final String TIMEOUTS; static final String WARMUP_TIME; static final String PREFS_NAME; static final String TIME_SLOT_LENGTH; }### Answer:
@Test public void whenTimeSlotLengthNotSetThenDefaultValue() { when(mockPreferences.getInt(ChronoFragment.TIME_SLOT_LENGTH, -1)).thenReturn(-1); when(mockTimer.getPrettyTime(60)).thenReturn("01:00"); out.onResume(); assertEquals(SlotSeekBarController.DEFAULT_VALUE, mSeekBar.getProgress()); assertEquals("01:00", mCountDownTextView.getText()); } |
### Question:
ChronoFragment extends RoboFragment implements ChronoInterface { @Override public void setTime(int time) { mCountDownTextView.setText(mScrumTimer.getPrettyTime(time)); } @Override View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); @Override void onStart(); @Override void onResume(); int getNumberOfParticipants(); @Override void setTime(int time); void pauseTickSound(); @Override void setDailyTimer(final String string); @Override void timeOut(); @Override void setCountDown(final String string); void resetBackground(); @Override void onStop(); int getNumberOfTimeouts(); String getPreparationTime(); static final String TOTAL_TIME; static final String TIMEOUTS; static final String WARMUP_TIME; static final String PREFS_NAME; static final String TIME_SLOT_LENGTH; }### Answer:
@Test public void whenSeekBarValueChangesThenUpdateChrono() { when(mockTimer.getPrettyTime(40)).thenReturn("00:30"); out.setTime(40); assertEquals("00:30", mCountDownTextView.getText()); } |
### Question:
ChronoFragment extends RoboFragment implements ChronoInterface { @Override public void onStop() { super.onStop(); mScrumTimer.stopCountDown(); mScrumTimer.stopTimer(); if (mTickPlayer != null) { mTickPlayer.release(); mTickPlayer = null; } if (mAlarmPlayer != null) { mAlarmPlayer.release(); mAlarmPlayer = null; } storeSlotTime(); } @Override View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); @Override void onStart(); @Override void onResume(); int getNumberOfParticipants(); @Override void setTime(int time); void pauseTickSound(); @Override void setDailyTimer(final String string); @Override void timeOut(); @Override void setCountDown(final String string); void resetBackground(); @Override void onStop(); int getNumberOfTimeouts(); String getPreparationTime(); static final String TOTAL_TIME; static final String TIMEOUTS; static final String WARMUP_TIME; static final String PREFS_NAME; static final String TIME_SLOT_LENGTH; }### Answer:
@Test public void whenPauseThenStoreValueFromSeekBar() { mSeekBar.setProgress(90); out.onStop(); verify(mockEditor).putInt(ChronoFragment.TIME_SLOT_LENGTH, 90); verify(mockEditor).commit(); } |
### Question:
Socket { public Observable<Object> connection() { return connection; } Socket(@Nonnull SocketConnection socketConnection, @Nonnull Scheduler scheduler); Observable<RxObjectEvent> events(); Observable<RxObjectEventConn> connectedAndRegistered(); Observable<Object> connection(); void sendPingWhenConnected(); void sendPingEvery5seconds(); @Nonnull Observable<String> nextId(); @Nonnull Observable<DataMessage> sendMessageOnceWhenConnected(final Func1<String, Observable<Object>> createMessage); static final Logger LOGGER; }### Answer:
@Test public void testConnection_registerIsSent() throws Exception { final Subscription subscribe = socket.connection().subscribe(observer); try { connection.onNext(new RxObjectEventConnected(sender), 0); testScheduler.triggerActions(); verify(sender).sendObjectMessage(new RegisterMessage("asdf")); } finally { subscribe.unsubscribe(); } }
@Test public void testAfterConnection_registerSuccess() throws Exception { final Subscription subscribe = socket.connection().subscribe(observer); try { register(); } finally { subscribe.unsubscribe(); } }
@Test public void testConnectionSuccessAfterAWhile_registerSuccess() throws Exception { final Subscription subscribe = socket.connection().subscribe(observer); try { testScheduler.advanceTimeBy(30, TimeUnit.SECONDS); register(); } finally { subscribe.unsubscribe(); } } |
### Question:
MeterPool { public Meter getMeter(String scope) { if (scope == null) { throw new IllegalArgumentException("scope cannot be null"); } Meter meter = meters.get(scope); if (meter == null) { meter = Metrics.newMeter(clazz, name, scope, name, TimeUnit.SECONDS); Meter existing = meters.putIfAbsent(scope, meter); if (existing != null) { meter = existing; } } return meter; } MeterPool(Class<?> clazz, String name); Meter getMeter(String scope); }### Answer:
@Test(expected = IllegalArgumentException.class) public void getMeterNullScope() { new MeterPool(Object.class, "name").getMeter(null); }
@Test public void getMeterSameScope() { MeterPool pool = new MeterPool(Object.class, "name"); Meter meter1 = pool.getMeter("scope"); Meter meter2 = pool.getMeter("scope"); assertSame(meter1, meter2); }
@Test public void getMeterDifferentScope() { MeterPool pool = new MeterPool(Object.class, "name"); Meter meter1 = pool.getMeter("scope1"); Meter meter2 = pool.getMeter("scope2"); assertThat(meter1, is(not(equalTo(meter2)))); } |
### Question:
KafkaSinkTask extends SinkTask { @Override public void flush(Map<TopicPartition, OffsetAndMetadata> offsets) { LOGGER.debug("Flushing kafka sink"); try { producer.flush(); } catch (IOException e) { LOGGER.debug("IOException on flush, re-throwing as retriable", e); throw new RetriableException(e); } super.flush(offsets); } @Override String version(); @Override void start(Map<String, String> taskConfig); @Override void put(Collection<SinkRecord> collection); @Override void flush(Map<TopicPartition, OffsetAndMetadata> offsets); @Override void stop(); }### Answer:
@Test public void flush() { task.put(Collections.singletonList(sinkRecord)); task.flush(Collections.emptyMap()); verify(kafkaProducer).flush(); } |
### Question:
Version { public static String getVersion() { return version; } static String getVersion(); }### Answer:
@Test public void getVersion() { assertThat(Version.getVersion(), is(not("unknown"))); assertThat(Version.getVersion(), is(not(nullValue()))); assertThat(Version.getVersion(), is(not(""))); } |
### Question:
KafkaAdminClient implements Closeable { public Set<TopicAndPartition> getPartitions() { LOG.debug("Retrieving all partitions"); return getPartitions(getTopics()); } KafkaAdminClient(Properties properties); Set<String> getTopics(); Set<TopicAndPartition> getPartitions(); Set<TopicAndPartition> getPartitions(String topic); Authorizer getAuthorizer(); Map<Resource, Set<Acl>> getAcls(); Map<Resource, Set<Acl>> getAcls(KafkaPrincipal principal); Set<Acl> getAcls(Resource resource); void addAcls(Set<Acl> acls, Resource resource); void removeAcls(Set<Acl> acls, Resource resource); void createTopic(String topic, int partitions, int replicationFactor); void createTopic(String topic, int partitions, int replicationFactor, Properties topicConfig); void deleteTopic(String topic); Properties getTopicConfig(String topic); void updateTopicConfig(String topic, Properties properties); int getTopicReplicationFactor(String topic); int getTopicPartitions(String topic); void addTopicPartitions(String topic, int partitions); AdminClient.ConsumerGroupSummary getConsumerGroupSummary(String consumerGroup); Collection<AdminClient.ConsumerSummary> getConsumerGroupSummaries(String consumerGroup); Map<TopicPartition, String> getConsumerGroupAssignments(String consumerGroup); @Override void close(); static final String ZOOKEEPER_SECURE; static final String DEFAULT_ZOOKEEPER_SECURE; static final String OPERATION_TIMEOUT_MS; static final String DEFAULT_OPERATION_TIMEOUT_MS; static final String OPERATION_SLEEP_MS; static final String DEFAULT_OPERATION_SLEEP_MS; }### Answer:
@Test public void getPartitions() { String topic1 = topic + "-1"; String topic2 = topic + "-2"; client.createTopic(topic1, 1, 1); client.createTopic(topic2, 1, 1); assertThat(client.getPartitions(), hasItems(new TopicAndPartition(topic1, 0), new TopicAndPartition(topic2, 0))); } |
### Question:
ProcessingPartition implements Closeable { public void committedOffset(long committedOffset) { LOGGER.debug("Offset [{}] has been committed for partition [{}]. Removing all completed offsets below commit value", committedOffset, topicPartition); lastCommittedOffset = committedOffset; committableOffset = null; completedOffsets.removeIf(o -> o < committedOffset); PARTITION_COMMITTED_OFFSETS.update(committedOffset - lastCommittedOffset); } ProcessingPartition(TopicPartition topicPartition, ProcessingConfig config, Consumer<K, V> consumer); boolean ack(long offset); boolean fail(long offset); void maybeUnpause(long currentTime); OffsetAndMetadata getCommittableOffset(); long getCommittableOffsetsSize(); void committedOffset(long committedOffset); void load(List<ConsumerRecord<K, V>> records); ConsumerRecord<K, V> nextRecord(); boolean hasNextRecord(); TopicPartition getTopicPartition(); @Override void close(); }### Answer:
@Test public void committedOffset() { long previousCommittedOffsets = ProcessingPartition.PARTITION_COMMITTED_OFFSETS.count(); partition.lastCommittedOffset = 0L; partition.committedOffset(123L); assertThat(ProcessingPartition.PARTITION_COMMITTED_OFFSETS.count(), is(previousCommittedOffsets + 1L)); } |
### Question:
ProcessingConfig { public double getFailThreshold() { return failThreshold; } ProcessingConfig(Properties properties); boolean getCommitInitialOffset(); long getCommitTimeThreshold(); long getCommitSizeThreshold(); OffsetResetStrategy getOffsetResetStrategy(); double getFailThreshold(); int getFailSampleSize(); long getFailPauseTime(); long getMaxPollInterval(); Properties getProperties(); String getGroupId(); @Override String toString(); static final String COMMIT_INITIAL_OFFSET_PROPERTY; static final String COMMIT_INITIAL_OFFSET_DEFAULT; static final String COMMIT_TIME_THRESHOLD_PROPERTY; static final String COMMIT_TIME_THRESHOLD_DEFAULT; static final String COMMIT_SIZE_THRESHOLD_PROPERTY; static final String COMMIT_SIZE_THRESHOLD_DEFAULT; static final String FAIL_THRESHOLD_PROPERTY; static final String FAIL_THRESHOLD_DEFAULT; static final String FAIL_SAMPLE_SIZE_PROPERTY; static final String FAIL_SAMPLE_SIZE_DEFAULT; static final String FAIL_PAUSE_TIME_PROPERTY; static final String FAIL_PAUSE_TIME_DEFAULT; }### Answer:
@Test public void constructor_pauseThresholdEqualsZero() throws IOException { properties.setProperty(ProcessingConfig.FAIL_THRESHOLD_PROPERTY, "0"); config = new ProcessingConfig(properties); assertThat(config.getFailThreshold(), is(0.0)); }
@Test public void constructor_pauseThresholdEqualsOne() throws IOException { properties.setProperty(ProcessingConfig.FAIL_THRESHOLD_PROPERTY, "1"); config = new ProcessingConfig(properties); assertThat(config.getFailThreshold(), is(1.0)); } |
### Question:
ProcessingKafkaConsumer implements Closeable { public Consumer<K, V> getConsumer() { return consumer; } ProcessingKafkaConsumer(ProcessingConfig config); ProcessingKafkaConsumer(ProcessingConfig config, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer); ProcessingKafkaConsumer(ProcessingConfig config, Consumer<K, V> consumer); Optional<ConsumerRecord<K, V>> nextRecord(final long timeout); boolean ack(ConsumerRecord<K, V> record); boolean ack(TopicPartition topicPartition, long offset); boolean fail(ConsumerRecord<K, V> record); boolean fail(TopicPartition topicPartition, long offset); synchronized void resetOffsets(Map<TopicPartition, Long> offsets); synchronized void commitOffsets(); void subscribe(Collection<String> topics); Consumer<K, V> getConsumer(); @Override void close(); }### Answer:
@Test public void constructorWithoutConsumer() throws IOException { try (ProcessingKafkaConsumer<String, String> processingKafkaConsumer = new ProcessingKafkaConsumer<>(config)) { assertThat(processingKafkaConsumer.getConsumer(), is(instanceOf(KafkaConsumer.class))); } }
@Test public void constructorWithConsumer() { assertThat(processingConsumer.getConsumer(), is(consumer)); }
@Test public void constructorWithDeserializers() throws IOException { Deserializer<String> keyDeserializer = new StringDeserializer(); Deserializer<String> valueDeserializer = new StringDeserializer(); try (ProcessingKafkaConsumer<String, String> processingKafkaConsumer = new ProcessingKafkaConsumer<>(config, keyDeserializer, valueDeserializer)) { assertThat(processingKafkaConsumer.getConsumer(), is(instanceOf(KafkaConsumer.class))); } } |
### Question:
ProcessingPartition implements Closeable { public void load(List<ConsumerRecord<K, V>> records) { List<ConsumerRecord<K, V>> recordsToAdd = new ArrayList<>(); LOGGER.debug("Loading records for partition [{}]", topicPartition); if (hasNextRecord()) { LOGGER.debug("Combining existing records with added records for partition [{}]", topicPartition); this.records.forEachRemaining(recordsToAdd::add); } recordsToAdd.addAll(records); this.records = recordsToAdd.iterator(); } ProcessingPartition(TopicPartition topicPartition, ProcessingConfig config, Consumer<K, V> consumer); boolean ack(long offset); boolean fail(long offset); void maybeUnpause(long currentTime); OffsetAndMetadata getCommittableOffset(); long getCommittableOffsetsSize(); void committedOffset(long committedOffset); void load(List<ConsumerRecord<K, V>> records); ConsumerRecord<K, V> nextRecord(); boolean hasNextRecord(); TopicPartition getTopicPartition(); @Override void close(); }### Answer:
@Test public void load() { partition.load(Arrays.asList(record(1L), record(2L), record(3L))); assertThat(partition.records.hasNext(), is(true)); assertRecordsAreEqual(partition.records.next(), record(1L)); assertThat(partition.records.hasNext(), is(true)); assertRecordsAreEqual(partition.records.next(), record(2L)); assertThat(partition.records.hasNext(), is(true)); assertRecordsAreEqual(partition.records.next(), record(3L)); assertThat(partition.records.hasNext(), is(false)); }
@Test public void load_withExistingRecords() { partition.load(Arrays.asList(record(1L))); partition.load(Arrays.asList(record(2L))); assertThat(partition.records.hasNext(), is(true)); assertRecordsAreEqual(partition.records.next(), record(1L)); assertThat(partition.records.hasNext(), is(true)); assertRecordsAreEqual(partition.records.next(), record(2L)); assertThat(partition.records.hasNext(), is(false)); } |
### Question:
ProcessingKafkaConsumer implements Closeable { public void subscribe(Collection<String> topics) { consumer.subscribe(topics, rebalanceListener); } ProcessingKafkaConsumer(ProcessingConfig config); ProcessingKafkaConsumer(ProcessingConfig config, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer); ProcessingKafkaConsumer(ProcessingConfig config, Consumer<K, V> consumer); Optional<ConsumerRecord<K, V>> nextRecord(final long timeout); boolean ack(ConsumerRecord<K, V> record); boolean ack(TopicPartition topicPartition, long offset); boolean fail(ConsumerRecord<K, V> record); boolean fail(TopicPartition topicPartition, long offset); synchronized void resetOffsets(Map<TopicPartition, Long> offsets); synchronized void commitOffsets(); void subscribe(Collection<String> topics); Consumer<K, V> getConsumer(); @Override void close(); }### Answer:
@Test public void subscribe() { List<String> topics = Arrays.asList("topic1", "topic2"); processingConsumer.subscribe(topics); verify(consumer).subscribe(topics, processingConsumer.rebalanceListener); } |
### Question:
ProcessingPartition implements Closeable { public boolean ack(long offset) { Long messageReadTime = pendingOffsets.remove(offset); if (messageReadTime == null) { LOGGER.debug("Ack for record on topic partition [{}] with offset [{}] is invalid as that offset is not " + "pending. Not committing", topicPartition, offset); return false; } PROCESSING_LATENCY.update(System.currentTimeMillis() - messageReadTime); LOGGER.debug("Acking record with offset [{}] for partition [{}]", offset, topicPartition); completedOffsets.add(offset); maybeUpdateCommitableOffset(offset); addResult(true); return true; } ProcessingPartition(TopicPartition topicPartition, ProcessingConfig config, Consumer<K, V> consumer); boolean ack(long offset); boolean fail(long offset); void maybeUnpause(long currentTime); OffsetAndMetadata getCommittableOffset(); long getCommittableOffsetsSize(); void committedOffset(long committedOffset); void load(List<ConsumerRecord<K, V>> records); ConsumerRecord<K, V> nextRecord(); boolean hasNextRecord(); TopicPartition getTopicPartition(); @Override void close(); }### Answer:
@Test public void ack_recordNotPending() { long previousProcessingLatencyCount = ProcessingPartition.PROCESSING_LATENCY.count(); assertThat(partition.ack(1L), is(false)); assertThat(ProcessingPartition.PROCESSING_LATENCY.count(), is(previousProcessingLatencyCount)); } |
### Question:
ConsumerOffsetClient implements Closeable { public long getCommittedOffset(TopicPartition topicPartition) { if (topicPartition == null) throw new IllegalArgumentException("topicPartition cannot be null"); OffsetAndMetadata offsetAndMetadata = consumer.committed(topicPartition); return offsetAndMetadata == null ? -1L : offsetAndMetadata.offset(); } ConsumerOffsetClient(Properties properties); ConsumerOffsetClient(Consumer<Object, Object> consumer); ConsumerOffsetClient(Consumer<Object, Object> consumer, boolean providedByUser); Map<TopicPartition, Long> getEndOffsets(Collection<String> topics); Map<TopicPartition, Long> getBeginningOffsets(Collection<String> topics); Map<TopicPartition, Long> getOffsetsForTimes(Collection<String> topics, long time); Map<TopicPartition, Long> getCommittedOffsets(Collection<String> topics); void commitOffsets(Map<TopicPartition, Long> offsets); long getCommittedOffset(TopicPartition topicPartition); Collection<TopicPartition> getPartitionsFor(Collection<String> topics); @Override void close(); }### Answer:
@Test public void getCommittedOffset() { when(consumer.committed(new TopicPartition("topic", 0))).thenReturn(new OffsetAndMetadata(123L)); assertThat(client.getCommittedOffset(new TopicPartition("topic", 0)), is(123L)); }
@Test public void getCommittedOffset_noOffset() { assertThat(client.getCommittedOffset(new TopicPartition("topic", 0)), is(-1L)); }
@Test (expected = IllegalArgumentException.class) public void getCommittedOffset_nullTopicPartition() { client.getCommittedOffset(null); } |
### Question:
ConsumerOffsetClient implements Closeable { @Override public void close() { if (!providedByUser) IOUtils.closeQuietly(consumer); } ConsumerOffsetClient(Properties properties); ConsumerOffsetClient(Consumer<Object, Object> consumer); ConsumerOffsetClient(Consumer<Object, Object> consumer, boolean providedByUser); Map<TopicPartition, Long> getEndOffsets(Collection<String> topics); Map<TopicPartition, Long> getBeginningOffsets(Collection<String> topics); Map<TopicPartition, Long> getOffsetsForTimes(Collection<String> topics, long time); Map<TopicPartition, Long> getCommittedOffsets(Collection<String> topics); void commitOffsets(Map<TopicPartition, Long> offsets); long getCommittedOffset(TopicPartition topicPartition); Collection<TopicPartition> getPartitionsFor(Collection<String> topics); @Override void close(); }### Answer:
@Test public void close_providedByConsumer() throws IOException { client.close(); verify(consumer, never()).close(); }
@Test public void close_notProvidedByConsumer() throws IOException { client = new ConsumerOffsetClient(consumer, false); client.close(); verify(consumer).close(); } |
### Question:
ProcessingPartition implements Closeable { @Override public void close() throws IOException { if (consumer.paused().contains(topicPartition)) PAUSED_PARTITIONS.dec(); } ProcessingPartition(TopicPartition topicPartition, ProcessingConfig config, Consumer<K, V> consumer); boolean ack(long offset); boolean fail(long offset); void maybeUnpause(long currentTime); OffsetAndMetadata getCommittableOffset(); long getCommittableOffsetsSize(); void committedOffset(long committedOffset); void load(List<ConsumerRecord<K, V>> records); ConsumerRecord<K, V> nextRecord(); boolean hasNextRecord(); TopicPartition getTopicPartition(); @Override void close(); }### Answer:
@Test public void pause_thenClosePartition() throws IOException { when(consumer.paused()).thenReturn(Collections.singleton(topicPartition)); long previousPausedPartitions = ProcessingPartition.PAUSED_PARTITIONS.count(); pause_thresholdMet(); assertThat(ProcessingPartition.PAUSED_PARTITIONS.count(), is(previousPausedPartitions + 1)); partition.close(); assertThat(ProcessingPartition.PAUSED_PARTITIONS.count(), is(previousPausedPartitions)); } |
### Question:
KafkaProducerPool implements Closeable { @Override public void close() throws IOException { writeLock.lock(); try { if (!shutdown) { shutdown = true; final Stream<Exception> exceptions = pool.values().stream() .flatMap(Collection::stream) .flatMap(producer -> { try { producer.close(); } catch (Exception e) { LOGGER.error("Could not close producer", e); return Stream.of(e); } return Stream.empty(); }); final Optional<Exception> exception = exceptions.findFirst(); if (exception.isPresent()) { throw new IOException(exception.get()); } } } finally { writeLock.unlock(); } } KafkaProducerPool(); Producer<K, V> getProducer(Properties properties); @Override void close(); static final String KAFKA_PRODUCER_CONCURRENCY; static final int DEFAULT_KAFKA_PRODUCER_CONCURRENCY_INT; static final String DEFAULT_KAFKA_PRODUCER_CONCURRENCY; }### Answer:
@Test public void closeEmptyPool() throws IOException { pool.close(); } |
### Question:
KafkaProducerWrapper implements Closeable, Flushable { public void send(ProducerRecord<K, T> record){ if(record == null){ throw new IllegalArgumentException("The 'record' cannot be 'null'."); } TimerContext context = SEND_TIMER.time(); try { pendingWrites.add(kafkaProducer.send(record)); } finally { context.stop(); } } KafkaProducerWrapper(Producer<K, T> kafkaProducer); void send(ProducerRecord<K, T> record); void sendSynchronously(ProducerRecord<K, T> record); void sendSynchronously(List<ProducerRecord<K, T>> records); @Override void flush(); @Override void close(); }### Answer:
@Test(expected=IllegalArgumentException.class) public void test_sendNullRecord() throws IOException, ExecutionException, InterruptedException { KafkaProducerWrapper<String, String> producer = new KafkaProducerWrapper<>(mockedProducer); producer.send(null); } |
### Question:
KafkaProducerWrapper implements Closeable, Flushable { @Override public void close() throws IOException { LOGGER.debug("Closing the producer wrapper and flushing outstanding writes."); flush(); } KafkaProducerWrapper(Producer<K, T> kafkaProducer); void send(ProducerRecord<K, T> record); void sendSynchronously(ProducerRecord<K, T> record); void sendSynchronously(List<ProducerRecord<K, T>> records); @Override void flush(); @Override void close(); }### Answer:
@Test public void test_WrapperNotCloseProducer() throws IOException, ExecutionException, InterruptedException { KafkaProducerWrapper<String, String> producer = new KafkaProducerWrapper<>(mockedProducer); producer.close(); verify(mockedProducer, never()).close(); } |
### Question:
KafkaProducerWrapper implements Closeable, Flushable { public void sendSynchronously(ProducerRecord<K, T> record) throws IOException { sendSynchronously(Collections.singletonList(record)); } KafkaProducerWrapper(Producer<K, T> kafkaProducer); void send(ProducerRecord<K, T> record); void sendSynchronously(ProducerRecord<K, T> record); void sendSynchronously(List<ProducerRecord<K, T>> records); @Override void flush(); @Override void close(); }### Answer:
@Test public void testSynchronous_messageTooLarge() throws IOException { kafkaAdminClient.createTopic(topic, 4, 1, new Properties()); Properties props = KafkaTests.getProps(); props.setProperty(KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.setProperty(VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.setProperty(ProducerConfig.BATCH_SIZE_CONFIG, "10000"); props.setProperty(ProducerConfig.LINGER_MS_CONFIG, "60000"); StringBuilder bldr = new StringBuilder(); for(int i = 0; i < 100000; i++) { bldr.append(i); } List<ProducerRecord<String, String>> records = new ArrayList<>(2); records.add(new ProducerRecord<>(topic, "key", bldr.toString())); records.add(new ProducerRecord<>(topic, "key2", "small")); boolean caughtRecordTooLargeException = false; try (KafkaProducerWrapper<String, String> producer = new KafkaProducerWrapper<>(new KafkaProducer<>(props))) { producer.sendSynchronously(records); } catch (KafkaExecutionException e) { Throwable cause = e.getCause(); assertThat(cause, instanceOf(ExecutionException.class)); Throwable cause2 = cause.getCause(); assertThat(cause2, instanceOf(RecordTooLargeException.class)); caughtRecordTooLargeException = true; } assertThat(caughtRecordTooLargeException, is(true)); } |
### Question:
KafkaSinkConnector extends SinkConnector { @Override public void start(Map<String, String> taskConfig) { config = new HashMap<>(); taskConfig.forEach((key, value) -> { if (key.startsWith(PRODUCER_PREFIX)) { config.put(key.substring(PRODUCER_PREFIX.length()), value); } }); config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, taskConfig.get(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)); config = Collections.unmodifiableMap(config); LOGGER.debug("Using {} for config", config); } @Override String version(); @Override void start(Map<String, String> taskConfig); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int totalConfigs); @Override void stop(); @Override ConfigDef config(); static final String PRODUCER_PREFIX; }### Answer:
@Test public void start() { connector.start(startConfig); assertThat(connector.config, is(taskConfig)); } |
### Question:
KafkaSinkConnector extends SinkConnector { @Override public List<Map<String, String>> taskConfigs(int totalConfigs) { return IntStream.range(0, totalConfigs).mapToObj(i -> config).collect(Collectors.toList()); } @Override String version(); @Override void start(Map<String, String> taskConfig); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int totalConfigs); @Override void stop(); @Override ConfigDef config(); static final String PRODUCER_PREFIX; }### Answer:
@Test public void taskConfigs() { connector.start(startConfig); assertThat(connector.taskConfigs(3), is(Arrays.asList(taskConfig, taskConfig, taskConfig))); } |
### Question:
CamelConsumerEndpoint extends ConsumerEndpoint implements AsyncProcessor { public void process(final MessageExchange messageExchange) throws Exception { final ContinuationData data = continuations.remove(messageExchange.getExchangeId()); if (data == null) { logger.error("Unexpected MessageExchange received: {}", messageExchange); } else { binding.runWithCamelContextClassLoader(new Callable<Object>() { public Object call() throws Exception { processReponse(messageExchange, data.exchange); data.callback.done(false); return null; } }); } } CamelConsumerEndpoint(JbiBinding binding, JbiEndpoint jbiEndpoint); void process(final MessageExchange messageExchange); void process(Exchange exchange); boolean process(Exchange exchange, AsyncCallback asyncCallback); @Override void validate(); static final QName SERVICE_NAME; }### Answer:
@Test public void testInvalidMessageExchangeDoesNotThrowException() throws Exception { client.sendBody("direct:a", "<hello>world</hello>"); String endpointName = jbiContainer.getRegistry().getExternalEndpointsForService(CamelConsumerEndpoint.SERVICE_NAME)[0].getEndpointName(); CamelConsumerEndpoint endpoint = (CamelConsumerEndpoint) component.getRegistry().getEndpoint(CamelConsumerEndpoint.SERVICE_NAME + ":" + endpointName); try { endpoint.process(new MockMessageExchange() { @Override public String getExchangeId() { return "a-fake-exchange-id"; } }); } catch (Exception e) { fail("Should not throw " + e); } } |
### Question:
MBeanServerHelper { public static ObjectName register(MBeanServer server, ObjectName name, Object object) throws JBIException { if (server == null) { throw new JBIException("MBeanServer is null when registering MBean " + name); } try { doUnregister(server, name); LOGGER.debug("Registering MBean {}", name); ObjectInstance instance = doRegister(server, name, object); ObjectName result = instance.getObjectName(); LOGGER.debug("Successfully registered MBean {}", result); return result; } catch (JMException e) { throw new JBIException("Exception occured while registering JMX MBean " + name, e); } } static ObjectName register(MBeanServer server, ObjectName name, Object object); static void unregister(MBeanServer server, ObjectName name); }### Answer:
@Test(expected = JBIException.class) public void testRegisterNullServerThrowsJBIException() throws NotCompliantMBeanException, MalformedObjectNameException, JBIException { SampleMBean mbean = new SampleMBeanImpl(); Object object = new StandardMBean(mbean, SampleMBean.class); MBeanServerHelper.register(null, defaultObjectName, object); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.