method2testcases
stringlengths 118
3.08k
|
---|
### Question:
MetricServiceImpl implements MetricService { @SuppressWarnings("rawtypes") @Override public ResponseEntity deleteMetricValues(String metricName) { try { return metricStore.deleteMetricValues(metricName); } catch (IOException e) { LOGGER.error("Failed to delete metric values named {}. {}", metricName, e.getMessage()); throw new GriffinException.ServiceException( "Failed to delete metric values.", e); } } @Override Map<String, List<Metric>> getAllMetrics(); @Override List<MetricValue> getMetricValues(String metricName, int offset,
int size, long tmst); @SuppressWarnings("rawtypes") @Override ResponseEntity addMetricValues(List<MetricValue> values); @SuppressWarnings("rawtypes") @Override ResponseEntity deleteMetricValues(String metricName); @Override MetricValue findMetric(Long id); }### Answer:
@Test public void testDeleteMetricValuesSuccess() throws IOException { given(metricStore.deleteMetricValues("metricName")) .willReturn(new ResponseEntity("{\"failures\": []}", HttpStatus.OK)); ResponseEntity response = service.deleteMetricValues("metricName"); Map body = JsonUtil.toEntity(response.getBody().toString(), Map.class); assertEquals(response.getStatusCode(), HttpStatus.OK); assertNotNull(body); assertEquals(body.get("failures"), Collections.emptyList()); }
@Test(expected = GriffinException.ServiceException.class) public void testDeleteMetricValuesFailureWithException() throws IOException { given(metricStore.deleteMetricValues("metricName")) .willThrow(new IOException()); service.deleteMetricValues("metricName"); } |
### Question:
HiveMetaStoreServiceJdbcImpl implements HiveMetaStoreService { @Override @Cacheable(unless = "#result==null") public Iterable<String> getAllTableNames(String dbName) { return queryHiveString(SHOW_TABLES_IN + dbName); } void setConn(Connection conn); void setHiveClassName(String hiveClassName); void setNeedKerberos(String needKerberos); void setKeytabUser(String keytabUser); void setKeytabPath(String keytabPath); @PostConstruct void init(); @Override @Cacheable(unless = "#result==null") Iterable<String> getAllDatabases(); @Override @Cacheable(unless = "#result==null") Iterable<String> getAllTableNames(String dbName); @Override @Cacheable(unless = "#result==null") Map<String, List<String>> getAllTableNames(); @Override List<Table> getAllTable(String db); @Override Map<String, List<Table>> getAllTable(); @Override @Cacheable(unless = "#result==null") Table getTable(String dbName, String tableName); @Scheduled(fixedRateString = "${cache.evict.hive.fixedRate.in.milliseconds}") @CacheEvict( cacheNames = "jdbcHive", allEntries = true, beforeInvocation = true) void evictHiveCache(); String getLocation(String tableMetadata); List<FieldSchema> getColums(String tableMetadata); String getComment(String colStr); }### Answer:
@Test public void testGetAllTableNames() throws SQLException { when(conn.createStatement()).thenReturn(stmt); when(stmt.executeQuery(anyString())).thenReturn(rs); when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false); when(rs.getString(anyInt())).thenReturn("session_data").thenReturn("session_summary"); Iterable<String> res = serviceJdbc.getAllTableNames("default"); StringBuilder sb = new StringBuilder(); for (String s : res) { sb.append(s).append(","); } Assert.assertEquals(sb.toString(), "session_data,session_summary,"); } |
### Question:
MeasureServiceImpl implements MeasureService { @Override public List<? extends Measure> getAllAliveMeasures(String type) { if (type.equals(GRIFFIN)) { return griffinMeasureRepo.findByDeleted(false); } else if (type.equals(EXTERNAL)) { return externalMeasureRepo.findByDeleted(false); } return measureRepo.findByDeleted(false); } @Override List<? extends Measure> getAllAliveMeasures(String type); @Override Measure getMeasureById(long id); @Override List<Measure> getAliveMeasuresByOwner(String owner); @Override Measure createMeasure(Measure measure); @Override Measure updateMeasure(Measure measure); @Override void deleteMeasureById(Long measureId); @Override void deleteMeasures(); }### Answer:
@Test public void testGetAllMeasures() throws Exception { Measure measure = createGriffinMeasure("view_item_hourly"); given(measureRepo.findByDeleted(false)).willReturn(Collections .singletonList(measure)); List<? extends Measure> measures = service.getAllAliveMeasures(""); assertEquals(measures.size(), 1); assertEquals(measures.get(0).getName(), "view_item_hourly"); } |
### Question:
MeasureServiceImpl implements MeasureService { @Override public Measure getMeasureById(long id) { Measure measure = measureRepo.findByIdAndDeleted(id, false); if (measure == null) { throw new GriffinException .NotFoundException(MEASURE_ID_DOES_NOT_EXIST); } return measure; } @Override List<? extends Measure> getAllAliveMeasures(String type); @Override Measure getMeasureById(long id); @Override List<Measure> getAliveMeasuresByOwner(String owner); @Override Measure createMeasure(Measure measure); @Override Measure updateMeasure(Measure measure); @Override void deleteMeasureById(Long measureId); @Override void deleteMeasures(); }### Answer:
@Test public void testGetMeasuresById() throws Exception { Measure measure = createGriffinMeasure("view_item_hourly"); given(measureRepo.findByIdAndDeleted(1L, false)).willReturn(measure); Measure m = service.getMeasureById(1); assertEquals(m.getName(), measure.getName()); }
@Test(expected = GriffinException.NotFoundException.class) public void testGetMeasuresByIdWithFileNotFoundException() { given(measureRepo.findByIdAndDeleted(1L, false)).willReturn(null); service.getMeasureById(1); } |
### Question:
MeasureServiceImpl implements MeasureService { @Override public List<Measure> getAliveMeasuresByOwner(String owner) { return measureRepo.findByOwnerAndDeleted(owner, false); } @Override List<? extends Measure> getAllAliveMeasures(String type); @Override Measure getMeasureById(long id); @Override List<Measure> getAliveMeasuresByOwner(String owner); @Override Measure createMeasure(Measure measure); @Override Measure updateMeasure(Measure measure); @Override void deleteMeasureById(Long measureId); @Override void deleteMeasures(); }### Answer:
@Test public void testGetAliveMeasuresByOwner() throws Exception { String owner = "test"; Measure measure = createGriffinMeasure("view_item_hourly"); given(measureRepo.findByOwnerAndDeleted(owner, false)) .willReturn(Collections.singletonList(measure)); List<Measure> measures = service.getAliveMeasuresByOwner(owner); assertEquals(measures.get(0).getName(), measure.getName()); } |
### Question:
MeasureServiceImpl implements MeasureService { @Override public void deleteMeasures() throws SchedulerException { List<Measure> measures = measureRepo.findByDeleted(false); for (Measure m : measures) { MeasureOperator op = getOperation(m); op.delete(m); } } @Override List<? extends Measure> getAllAliveMeasures(String type); @Override Measure getMeasureById(long id); @Override List<Measure> getAliveMeasuresByOwner(String owner); @Override Measure createMeasure(Measure measure); @Override Measure updateMeasure(Measure measure); @Override void deleteMeasureById(Long measureId); @Override void deleteMeasures(); }### Answer:
@Test public void testDeleteMeasuresForGriffinSuccess() throws Exception { GriffinMeasure measure = createGriffinMeasure("view_item_hourly"); measure.setId(1L); given(measureRepo.findByDeleted(false)).willReturn(Arrays .asList(measure)); doNothing().when(griffinOp).delete(measure); service.deleteMeasures(); }
@Test public void testDeleteMeasuresForExternalSuccess() throws SchedulerException { ExternalMeasure measure = createExternalMeasure("externalMeasure"); measure.setId(1L); given(measureRepo.findByDeleted(false)).willReturn(Arrays .asList(measure)); doNothing().when(externalOp).delete(measure); service.deleteMeasures(); }
@Test(expected = GriffinException.ServiceException.class) public void testDeleteMeasuresForGriffinFailureWithException() throws Exception { GriffinMeasure measure = createGriffinMeasure("externalMeasure"); measure.setId(1L); given(measureRepo.findByDeleted(false)).willReturn(Arrays .asList(measure)); doThrow(new GriffinException.ServiceException("Failed to delete job", new Exception())) .when(griffinOp).delete(measure); service.deleteMeasures(); } |
### Question:
MeasureOrgController { @RequestMapping(value = "/org", method = RequestMethod.GET) public List<String> getOrgs() { return measureOrgService.getOrgs(); } @RequestMapping(value = "/org", method = RequestMethod.GET) List<String> getOrgs(); @RequestMapping(value = "/org/{org}", method = RequestMethod.GET) List<String> getMetricNameListByOrg(@PathVariable("org") String org); @RequestMapping(value = "/org/measure/names", method = RequestMethod.GET) Map<String, List<String>> getMeasureNamesGroupByOrg(); }### Answer:
@Test public void testGetOrgs() throws Exception { String org = "orgName"; when(measureOrgService.getOrgs()).thenReturn(Arrays.asList(org)); mockMvc.perform(get(URLHelper.API_VERSION_PATH + "/org")) .andExpect(status().isOk()) .andExpect(jsonPath("$.[0]", is(org))); } |
### Question:
MeasureOrgController { @RequestMapping(value = "/org/{org}", method = RequestMethod.GET) public List<String> getMetricNameListByOrg(@PathVariable("org") String org) { return measureOrgService.getMetricNameListByOrg(org); } @RequestMapping(value = "/org", method = RequestMethod.GET) List<String> getOrgs(); @RequestMapping(value = "/org/{org}", method = RequestMethod.GET) List<String> getMetricNameListByOrg(@PathVariable("org") String org); @RequestMapping(value = "/org/measure/names", method = RequestMethod.GET) Map<String, List<String>> getMeasureNamesGroupByOrg(); }### Answer:
@Test public void testGetMetricNameListByOrg() throws Exception { String org = "hadoop"; when(measureOrgService.getMetricNameListByOrg(org)).thenReturn(Arrays .asList(org)); mockMvc.perform(get(URLHelper.API_VERSION_PATH + "/org/{org}", org)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[0]", is(org))); } |
### Question:
HiveMetaStoreController { @RequestMapping(value = "/dbs", method = RequestMethod.GET) public Iterable<String> getAllDatabases() { return hiveMetaStoreService.getAllDatabases(); } @RequestMapping(value = "/dbs", method = RequestMethod.GET) Iterable<String> getAllDatabases(); @RequestMapping(value = "/tables/names", method = RequestMethod.GET) Iterable<String> getAllTableNames(@RequestParam("db") String dbName); @RequestMapping(value = "/tables", method = RequestMethod.GET) List<Table> getAllTables(@RequestParam("db") String dbName); @RequestMapping(value = "/dbs/tables", method = RequestMethod.GET) Map<String, List<Table>> getAllTables(); @RequestMapping(value = "/dbs/tables/names", method = RequestMethod.GET) Map<String, List<String>> getAllTableNames(); @RequestMapping(value = "/table", method = RequestMethod.GET) Table getTable(@RequestParam("db") String dbName,
@RequestParam("table") String tableName); }### Answer:
@Test public void testGetAllDatabases() throws Exception { String dbName = "default"; given(hiveMetaStoreService.getAllDatabases()).willReturn(Arrays .asList(dbName)); mockMvc.perform(get(URLHelper.API_VERSION_PATH + "/metadata/hive/dbs")) .andExpect(status().isOk()) .andExpect(jsonPath("$.[0]", is(dbName))); } |
### Question:
MeasureOrgController { @RequestMapping(value = "/org/measure/names", method = RequestMethod.GET) public Map<String, List<String>> getMeasureNamesGroupByOrg() { return measureOrgService.getMeasureNamesGroupByOrg(); } @RequestMapping(value = "/org", method = RequestMethod.GET) List<String> getOrgs(); @RequestMapping(value = "/org/{org}", method = RequestMethod.GET) List<String> getMetricNameListByOrg(@PathVariable("org") String org); @RequestMapping(value = "/org/measure/names", method = RequestMethod.GET) Map<String, List<String>> getMeasureNamesGroupByOrg(); }### Answer:
@Test public void testGetMeasureNamesGroupByOrg() throws Exception { List<String> measures = Arrays.asList("measureName"); Map<String, List<String>> map = new HashMap<>(); map.put("orgName", measures); when(measureOrgService.getMeasureNamesGroupByOrg()).thenReturn(map); mockMvc.perform(get(URLHelper.API_VERSION_PATH + "/org/measure/names")) .andExpect(status().isOk()) .andExpect(jsonPath("$.orgName", hasSize(1))); } |
### Question:
MeasureController { @RequestMapping(value = "/measures", method = RequestMethod.GET) public List<? extends Measure> getAllAliveMeasures(@RequestParam(value = "type", defaultValue = "") String type) { return measureService.getAllAliveMeasures(type); } @RequestMapping(value = "/measures", method = RequestMethod.GET) List<? extends Measure> getAllAliveMeasures(@RequestParam(value =
"type", defaultValue = "") String type); @RequestMapping(value = "/measures/{id}", method = RequestMethod.GET) Measure getMeasureById(@PathVariable("id") long id); @RequestMapping(value = "/measures/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) void deleteMeasureById(@PathVariable("id") Long id); @RequestMapping(value = "/measures", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) void deleteMeasures(); @RequestMapping(value = "/measures", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) Measure updateMeasure(@RequestBody Measure measure); @RequestMapping(value = "/measures/owner/{owner}", method = RequestMethod.GET) List<Measure> getAliveMeasuresByOwner(@PathVariable("owner")
@Valid String owner); @RequestMapping(value = "/measures", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) Measure createMeasure(@RequestBody Measure measure); }### Answer:
@Test public void testGetAllMeasures() throws Exception { Measure measure = createGriffinMeasure("view_item_hourly"); Mockito.<List<? extends Measure>>when(service.getAllAliveMeasures("")) .thenReturn(Collections.singletonList(measure)); mvc.perform(get(URLHelper.API_VERSION_PATH + "/measures")) .andExpect(status().isOk()) .andExpect(jsonPath("$.[0].name", is("view_item_hourly"))); } |
### Question:
MeasureController { @RequestMapping(value = "/measures/{id}", method = RequestMethod.GET) public Measure getMeasureById(@PathVariable("id") long id) { return measureService.getMeasureById(id); } @RequestMapping(value = "/measures", method = RequestMethod.GET) List<? extends Measure> getAllAliveMeasures(@RequestParam(value =
"type", defaultValue = "") String type); @RequestMapping(value = "/measures/{id}", method = RequestMethod.GET) Measure getMeasureById(@PathVariable("id") long id); @RequestMapping(value = "/measures/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) void deleteMeasureById(@PathVariable("id") Long id); @RequestMapping(value = "/measures", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) void deleteMeasures(); @RequestMapping(value = "/measures", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) Measure updateMeasure(@RequestBody Measure measure); @RequestMapping(value = "/measures/owner/{owner}", method = RequestMethod.GET) List<Measure> getAliveMeasuresByOwner(@PathVariable("owner")
@Valid String owner); @RequestMapping(value = "/measures", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) Measure createMeasure(@RequestBody Measure measure); }### Answer:
@Test public void testGetMeasuresById() throws Exception { Measure measure = createGriffinMeasure("view_item_hourly"); given(service.getMeasureById(1L)).willReturn(measure); mvc.perform(get(URLHelper.API_VERSION_PATH + "/measures/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", is("view_item_hourly"))); } |
### Question:
HiveMetaStoreController { @RequestMapping(value = "/tables/names", method = RequestMethod.GET) public Iterable<String> getAllTableNames(@RequestParam("db") String dbName) { return hiveMetaStoreService.getAllTableNames(dbName); } @RequestMapping(value = "/dbs", method = RequestMethod.GET) Iterable<String> getAllDatabases(); @RequestMapping(value = "/tables/names", method = RequestMethod.GET) Iterable<String> getAllTableNames(@RequestParam("db") String dbName); @RequestMapping(value = "/tables", method = RequestMethod.GET) List<Table> getAllTables(@RequestParam("db") String dbName); @RequestMapping(value = "/dbs/tables", method = RequestMethod.GET) Map<String, List<Table>> getAllTables(); @RequestMapping(value = "/dbs/tables/names", method = RequestMethod.GET) Map<String, List<String>> getAllTableNames(); @RequestMapping(value = "/table", method = RequestMethod.GET) Table getTable(@RequestParam("db") String dbName,
@RequestParam("table") String tableName); }### Answer:
@Test public void testGetAllTableNames() throws Exception { String dbName = "default"; String tableName = "table"; given(hiveMetaStoreService.getAllTableNames(dbName)).willReturn(Arrays .asList(tableName)); mockMvc.perform(get(URLHelper.API_VERSION_PATH + "/metadata/hive/tables/names").param("db", dbName)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[0]", is(tableName))); } |
### Question:
EmptyContent extends Content { @Override public void draw(Graphics2D graphics) {} @Override void draw(Graphics2D graphics); @Override void setMinWidth(double minWidth); @Override void setMinHeight(double minHeight); }### Answer:
@Test public void testDraw() throws Exception { } |
### Question:
Content { public final double getY() { return 0; } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testGetY() throws Exception { Content content = new TestContent(); assertEquals(0, content.getY(), 0.01); } |
### Question:
Content { public final double getWidth() { return Math.max(width, minWidth); } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testGetWidth() throws Exception { Content content = new TestContent(); assertEquals(0, content.getWidth(), 0.01); content.setMinWidth(50); assertEquals(50, content.getWidth(), 0.01); } |
### Question:
Content { public final double getHeight() { return Math.max(height, minHeight); } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testGetHeight() throws Exception { Content content = new TestContent(); assertEquals(0, content.getHeight(), 0.01); content.setMinHeight(20); assertEquals(20, content.getHeight(), 0.01); } |
### Question:
Content { public void setMinWidth(double minWidth) { if(0 > minWidth) { throw new IllegalArgumentException("min width can only be a positive number"); } this.minWidth = minWidth; refreshUp(); } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testSetMinWidth() throws Exception { Content content = new TestContent(); content.setMinWidth(500); assertEquals(500, content.getWidth(), 0.01); } |
### Question:
Content { public void setMinHeight(double minHeight){ if(0 > minHeight) { throw new IllegalArgumentException("min height can only be a positive number"); } this.minHeight = minHeight; refreshUp(); } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testSetMinHeight() throws Exception { Content content = new TestContent(); content.setMinHeight(200); assertEquals(200, content.getHeight(), 0.01); } |
### Question:
Content { public final void refresh() { refreshUp(); refreshDown(); } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testRefreshParent() throws Exception { TestingRefreshContent testingRefreshContent = new TestingRefreshContent(); assertEquals(0, testingRefreshContent.refreshUpCount); assertEquals(0, testingRefreshContent.refreshDownCount); Content content = new TestContent(); testingRefreshContent.setAsParent(content); content.refresh(); assertEquals(1, testingRefreshContent.refreshUpCount); assertEquals(0, testingRefreshContent.refreshDownCount); }
@Test public void testRefreshChildren() throws Exception { TestingRefreshContent testingRefreshContent = new TestingRefreshContent(); assertEquals(0, testingRefreshContent.refreshUpCount); assertEquals(0, testingRefreshContent.refreshDownCount); Content content = new TestContent(); testingRefreshContent.setAsChildren(content); content.refresh(); assertEquals(0, testingRefreshContent.refreshUpCount); assertEquals(0, testingRefreshContent.refreshDownCount); } |
### Question:
Layout extends Content { public void add(Content content) { if(null == content) { throw new NullPointerException("Content can't be null"); } content.addParent(this); contents.add(content); refresh(); } void add(Content content); void remove(Content content); final Separator getSeparator(); final void setSeparator(Separator separator); boolean isEmpty(); void clear(); @Override final void draw(Graphics2D graphics); Point2D getLocation(Content content); }### Answer:
@Test public void testAdd() throws Exception { } |
### Question:
Layout extends Content { public void remove(Content content) { if(null == content) { throw new NullPointerException("Content can't be null"); } content.removeParent(this); contents.remove(content); refresh(); } void add(Content content); void remove(Content content); final Separator getSeparator(); final void setSeparator(Separator separator); boolean isEmpty(); void clear(); @Override final void draw(Graphics2D graphics); Point2D getLocation(Content content); }### Answer:
@Test public void testRemove() throws Exception { } |
### Question:
Layout extends Content { public final Separator getSeparator() { return separator; } void add(Content content); void remove(Content content); final Separator getSeparator(); final void setSeparator(Separator separator); boolean isEmpty(); void clear(); @Override final void draw(Graphics2D graphics); Point2D getLocation(Content content); }### Answer:
@Test public void testGetSeparator() throws Exception { } |
### Question:
Layout extends Content { public final void setSeparator(Separator separator) { if(null==separator) { separator = Separator.EMPTY; } this.separator = separator; } void add(Content content); void remove(Content content); final Separator getSeparator(); final void setSeparator(Separator separator); boolean isEmpty(); void clear(); @Override final void draw(Graphics2D graphics); Point2D getLocation(Content content); }### Answer:
@Test public void testSetSeparator() throws Exception { } |
### Question:
Layout extends Content { public Point2D getLocation(Content content) { int index = contents.indexOf(content); Point2D offset = new Point2D.Double(0,0); for(int i = 0; i < index; ++i) { offset = getNextOffset(offset, contents.get(i)); } return offset; } void add(Content content); void remove(Content content); final Separator getSeparator(); final void setSeparator(Separator separator); boolean isEmpty(); void clear(); @Override final void draw(Graphics2D graphics); Point2D getLocation(Content content); }### Answer:
@Test public void testGetLocation() throws Exception { } |
### Question:
TextContent extends Content implements LineText.ChangeListener { @Override public void onChange() { refresh(); } TextContent(LineText text); @Override void onChange(); @Override void draw(Graphics2D graphics); Rectangle2D getMinimalBounds(); }### Answer:
@Test public void testOnChange() throws Exception { SingleLineText singleLineText = new SingleLineText(); TextContent textContent = new TextContent(singleLineText); TestingRefreshContent testingRefreshContent = new TestingRefreshContent(); testingRefreshContent.setAsParent(textContent); assertEquals(0, testingRefreshContent.refreshUpCount); assertEquals(0, testingRefreshContent.refreshDownCount); singleLineText.setText("test"); assertEquals(1, testingRefreshContent.refreshUpCount); assertEquals(0, testingRefreshContent.refreshDownCount); } |
### Question:
Content { public boolean contains(Point2D point) { return getBounds().contains(point); } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testContains() throws Exception { Content content = new TestContent(); content.setMinWidth(50); content.setMinHeight(20); assertTrue(content.contains(new Point(0,0))); assertTrue(content.contains(new Point(49,19))); assertTrue(content.contains(new Point(30,10))); assertTrue(content.contains(new Point(1,1))); assertTrue(content.contains(new Point(49,0))); assertFalse(content.contains(new Point(50,20))); assertFalse(content.contains(new Point(-1,0))); assertFalse(content.contains(new Point(100,100))); } |
### Question:
Content { public final Rectangle2D getBounds() { return new Rectangle2D.Double(getX(),getY(),getWidth(),getHeight()); } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testGetBounds() throws Exception { Content content = new TestContent(); content.setMinWidth(50); content.setMinHeight(20); assertEquals(0, content.getBounds().getX(), 0.01); assertEquals(0, content.getBounds().getY(), 0.01); assertEquals(50, content.getBounds().getWidth(), 0.01); assertEquals(20, content.getBounds().getHeight(), 0.01); } |
### Question:
Content { public final double getX() { return 0; } boolean contains(Point2D point); abstract void draw(Graphics2D graphics); final void draw(Graphics2D graphics, Point2D offset); final Rectangle2D getBounds(); Rectangle2D getMinimalBounds(); final double getX(); final double getY(); final double getWidth(); final double getHeight(); void setMinWidth(double minWidth); void setMinHeight(double minHeight); final void refresh(); }### Answer:
@Test public void testGetX() throws Exception { Content content = new TestContent(); assertEquals(0, content.getX(), 0.01); } |
### Question:
ChainrFactory { public static Chainr fromClassPath( String chainrSpecClassPath ) { return fromClassPath( chainrSpecClassPath, null ); } static Chainr fromClassPath( String chainrSpecClassPath ); static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ); static Chainr fromFileSystem( String chainrSpecFilePath ); static Chainr fromFileSystem( String chainrSpecFilePath, ChainrInstantiator chainrInstantiator ); static Chainr fromFile( File chainrSpecFile ); static Chainr fromFile( File chainrSpecFile, ChainrInstantiator chainrInstantiator ); }### Answer:
@Test public void testGetChainrInstanceFromClassPath_success() throws Exception { Chainr result = ChainrFactory.fromClassPath( CLASSPATH + WELLFORMED_INPUT_FILENAME ); Assert.assertNotNull( result, "ChainrFactory did not return an instance of Chainr." ); }
@Test( expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Unable to load JSON.*" ) public void testGetChainrInstanceFromClassPath_error() throws Exception { ChainrFactory.fromClassPath( CLASSPATH + MALFORMED_INPUT_FILENAME ); }
@Test public void testGetChainrInstanceFromClassPathWithInstantiator_success() throws Exception { Chainr result = ChainrFactory.fromClassPath( CLASSPATH + WELLFORMED_INPUT_FILENAME, new DefaultChainrInstantiator() ); Assert.assertNotNull( result, "ChainrFactory did not return an instance of Chainr." ); }
@Test( expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Unable to load JSON.*" ) public void testGetChainrInstanceFromClassPathWithInstantiator_error() throws Exception { ChainrFactory.fromClassPath( CLASSPATH + MALFORMED_INPUT_FILENAME, new DefaultChainrInstantiator() ); } |
### Question:
ChainrFactory { public static Chainr fromFile( File chainrSpecFile ) { return fromFile( chainrSpecFile, null ); } static Chainr fromClassPath( String chainrSpecClassPath ); static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ); static Chainr fromFileSystem( String chainrSpecFilePath ); static Chainr fromFileSystem( String chainrSpecFilePath, ChainrInstantiator chainrInstantiator ); static Chainr fromFile( File chainrSpecFile ); static Chainr fromFile( File chainrSpecFile, ChainrInstantiator chainrInstantiator ); }### Answer:
@Test public void testGetChainrInstanceFromFileWithInstantiator_success() throws Exception { Chainr result = ChainrFactory.fromFile( wellformedFile, new DefaultChainrInstantiator() ); Assert.assertNotNull( result, "ChainrFactory did not return an instance of Chainr." ); }
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Unable to load chainr spec file.*") public void testGetChainrInstanceFromFileWithInstantiator_error() throws Exception { ChainrFactory.fromFile( malformedFile, new DefaultChainrInstantiator() ); }
@Test public void testGetChainrInstanceFromFile_success() throws Exception { Chainr result = ChainrFactory.fromFile( wellformedFile ); Assert.assertNotNull( result, "ChainrFactory did not return an instance of Chainr." ); }
@Test( expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Unable to load chainr spec file.*" ) public void testGetChainrInstanceFromFile_error() throws Exception { ChainrFactory.fromFile( malformedFile ); } |
### Question:
Removr implements SpecDriven, Transform { @Override public Object transform( Object input ) { Map<String,Object> wrappedMap = new HashMap<>(); wrappedMap.put(ROOT_KEY, input); rootSpec.applyToMap( wrappedMap ); return input; } @Inject Removr( Object spec ); @Override Object transform( Object input ); }### Answer:
@Test(dataProvider = "getTestCaseNames") public void runTestCases(String testCaseName) throws IOException { String testPath = "/json/removr/" + testCaseName; Map<String, Object> testUnit = JsonUtils.classpathToMap( testPath + ".json" ); Object input = testUnit.get( "input" ); Object spec = testUnit.get( "spec" ); Object expected = testUnit.get( "expected" ); Removr removr = new Removr( spec ); Object actual = removr.transform( input ); JoltTestUtil.runDiffy( "failed case " + testPath, expected, actual ); } |
### Question:
Chainr implements Transform, ContextualTransform { public static Chainr fromSpec( Object input ) { return new ChainrBuilder( input ).build(); } Chainr( List<JoltTransform> joltTransforms ); static Chainr fromSpec( Object input ); static Chainr fromSpec( Object input, ChainrInstantiator instantiator ); @Override Object transform( Object input, Map<String, Object> context ); @Override Object transform( Object input ); Object transform( int to, Object input ); Object transform( int to, Object input, Map<String, Object> context ); Object transform( int from, int to, Object input ); Object transform( int from, int to, Object input, Map<String, Object> context ); boolean hasContextualTransforms(); List<ContextualTransform> getContextualTransforms(); }### Answer:
@Test(dataProvider = "failureSpecCases", expectedExceptions = SpecException.class) public void process_itBlowsUp_fromSpec(Object spec) { Chainr.fromSpec( spec ); Assert.fail("Should have failed during spec initialization."); } |
### Question:
StarDoublePathElement extends BasePathElement implements StarPathElement { @Override public MatchedElement match(String dataKey, WalkedPath walkedPath) { if ( stringMatch( dataKey ) ) { List<String> subKeys = new ArrayList<>(2); int midStart = finMidIndex(dataKey); int midEnd = midStart + mid.length(); String firstStarPart = dataKey.substring( prefix.length(), midStart); subKeys.add( firstStarPart ); String secondStarPart = dataKey.substring( midEnd, dataKey.length() - suffix.length() ); subKeys.add( secondStarPart ); return new MatchedElement(dataKey, subKeys); } return null; } StarDoublePathElement(String key); @Override boolean stringMatch(String literal); @Override MatchedElement match(String dataKey, WalkedPath walkedPath); @Override String getCanonicalForm(); }### Answer:
@Test public void testStarsInMiddleNonGreedy() { StarPathElement star = new StarDoublePathElement( "a*b*c" ); MatchedElement lpe = star.match( "abbccbccc", null ); Assert.assertEquals( "abbccbccc", lpe.getSubKeyRef( 0 ) ); Assert.assertEquals( "b", lpe.getSubKeyRef( 1 ) ); Assert.assertEquals( "ccbcc", lpe.getSubKeyRef( 2 ) ); Assert.assertEquals( 3, lpe.getSubKeyCount() ); } |
### Question:
DeepCopy { public static Object simpleDeepCopy( Object object ) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); oos.flush(); oos.close(); bos.close(); byte [] byteData = bos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(byteData); return new ObjectInputStream(bais).readObject(); } catch ( IOException ioe ) { throw new RuntimeException( "DeepCopy IOException", ioe ); } catch ( ClassNotFoundException cnf ) { throw new RuntimeException( "DeepCopy ClassNotFoundException", cnf ); } } static Object simpleDeepCopy( Object object ); }### Answer:
@Test public void deepCopyTest() throws Exception { Object input = JsonUtils.classpathToObject( "/json/deepcopy/original.json" ); Map<String, Object> fiddle = (Map<String, Object>) DeepCopy.simpleDeepCopy( input ); JoltTestUtil.runDiffy( "Verify that the DeepCopy did in fact make a copy.", input, fiddle ); List array = (List) fiddle.get( "array" ); array.add( "c" ); array.set( 1, 3 ); Map<String,Object> subMap = (Map<String,Object>) fiddle.get( "map" ); subMap.put("c", "c"); subMap.put("b", 3 ); Object unmodified = JsonUtils.classpathToObject( "/json/deepcopy/original.json" ); JoltTestUtil.runDiffy( "Verify that the deepcopy was actually deep / input is unmodified", unmodified, input ); Object expectedModified = JsonUtils.classpathToObject( "/json/deepcopy/modifed.json" ); JoltTestUtil.runDiffy( "Verify fiddled post deepcopy object looks correct / was modifed.", expectedModified, fiddle ); } |
### Question:
JoltUtils { public static String toSimpleTraversrPath(Object[] paths) { StringBuilder pathBuilder = new StringBuilder(); for(int i=0; i<paths.length; i++) { Object path = paths[i]; if(path instanceof Integer) { pathBuilder.append("[").append(((Integer) path).intValue()).append("]"); } else if(path instanceof String) { pathBuilder.append(path.toString()); } else{ throw new UnsupportedOperationException("Only Strings and Integers are supported as path element"); } if(!(i+1 == paths.length)) { pathBuilder.append("."); } } return pathBuilder.toString(); } static void removeRecursive( Object json, String keyToRemove ); static T navigate( final Object source, final Object... paths ); static T navigateStrict( final Object source, final Object... paths ); static T navigateOrDefault( final T defaultValue, final Object source, final Object... paths ); @Deprecated static T navigateSafe(final T defaultValue, final Object source, final Object... paths); static boolean isVacantJson(final Object obj); static boolean isBlankJson(final Object obj); static List<Object[]> listKeyChains(final Object source); static List<Object[]> listKeyChains(final Object key, final Object value); static String toSimpleTraversrPath(Object[] paths); @SuppressWarnings("unchecked") static T cast(Object object); @SuppressWarnings("unchecked") static E[] cast(Object[] object); @SuppressWarnings("unchecked") static Object compactJson(Object source); @SuppressWarnings( "unchecked" ) static T store( Object source, T value, Object... paths ); @SuppressWarnings( "unchecked" ) static T remove( Object source, Object... paths ); }### Answer:
@Test(dataProvider = "pathProvider") public void testToSimpleTraversrPath(Object... paths) { String humanReadablePath = JoltUtils.toSimpleTraversrPath(paths); Assert.assertEquals(new SimpleTraversal<>(humanReadablePath).get(jsonSource).get(), navigate(jsonSource, paths)); } |
### Question:
StringTools { public static int countMatches(CharSequence sourceSequence, CharSequence subSequence) { if (isEmpty(sourceSequence) || isEmpty(subSequence) || sourceSequence.length() < subSequence.length()) { return 0; } int count = 0; int sourceSequenceIndex = 0; int subSequenceIndex = 0; while(sourceSequenceIndex < sourceSequence.length()) { if(sourceSequence.charAt(sourceSequenceIndex) == subSequence.charAt(subSequenceIndex)) { sourceSequenceIndex++; subSequenceIndex++; while(sourceSequenceIndex < sourceSequence.length() && subSequenceIndex < subSequence.length()) { if(sourceSequence.charAt(sourceSequenceIndex) != subSequence.charAt(subSequenceIndex)) { break; } sourceSequenceIndex++; subSequenceIndex++; } if(subSequenceIndex == subSequence.length()) { count++; } subSequenceIndex = 0; continue; } sourceSequenceIndex++; } return count; } static int countMatches(CharSequence sourceSequence, CharSequence subSequence); static boolean isNotBlank(CharSequence sourceSequence); static boolean isBlank(CharSequence sourceSequence); static boolean isEmpty(CharSequence sourceSequence); }### Answer:
@Test(dataProvider = "testCaseGenerator") public void testCountMatches(String str, String subStr) throws Exception { Assert.assertEquals( StringTools.countMatches(str, subStr), StringTools.countMatches(str, subStr), "test failed: \nstr=\"" + str + "\"\nsubStr=\"" + subStr + "\"" ); } |
### Question:
StringTools { public static boolean isNotBlank(CharSequence sourceSequence) { return !isBlank(sourceSequence); } static int countMatches(CharSequence sourceSequence, CharSequence subSequence); static boolean isNotBlank(CharSequence sourceSequence); static boolean isBlank(CharSequence sourceSequence); static boolean isEmpty(CharSequence sourceSequence); }### Answer:
@Test public void testIsNotBlank() throws Exception { Assert.assertTrue(StringTools.isNotBlank(" a a ")); Assert.assertTrue(StringTools.isNotBlank("a a")); Assert.assertTrue(StringTools.isNotBlank(" a ")); Assert.assertTrue(StringTools.isNotBlank("a")); Assert.assertFalse(StringTools.isNotBlank(" ")); Assert.assertFalse(StringTools.isNotBlank(" ")); Assert.assertFalse(StringTools.isNotBlank("")); Assert.assertFalse(StringTools.isNotBlank(null)); } |
### Question:
StringTools { public static boolean isBlank(CharSequence sourceSequence) { int sequenceLength; if (sourceSequence == null || (sequenceLength = sourceSequence.length()) == 0) { return true; } for (int i = 0; i < sequenceLength; i++) { if ((Character.isWhitespace(sourceSequence.charAt(i)) == false)) { return false; } } return true; } static int countMatches(CharSequence sourceSequence, CharSequence subSequence); static boolean isNotBlank(CharSequence sourceSequence); static boolean isBlank(CharSequence sourceSequence); static boolean isEmpty(CharSequence sourceSequence); }### Answer:
@Test public void testIsBlank() throws Exception { Assert.assertFalse(StringTools.isBlank(" a a ")); Assert.assertFalse(StringTools.isBlank("a a")); Assert.assertFalse(StringTools.isBlank(" a ")); Assert.assertFalse(StringTools.isBlank("a")); Assert.assertTrue(StringTools.isBlank(" ")); Assert.assertTrue(StringTools.isBlank(" ")); Assert.assertTrue(StringTools.isBlank("")); Assert.assertTrue(StringTools.isBlank(null)); } |
### Question:
StringTools { public static boolean isEmpty(CharSequence sourceSequence) { return sourceSequence == null || sourceSequence.length() == 0; } static int countMatches(CharSequence sourceSequence, CharSequence subSequence); static boolean isNotBlank(CharSequence sourceSequence); static boolean isBlank(CharSequence sourceSequence); static boolean isEmpty(CharSequence sourceSequence); }### Answer:
@Test public void testIsEmpty() throws Exception { Assert.assertTrue(StringTools.isEmpty("")); Assert.assertTrue(StringTools.isEmpty(null)); Assert.assertFalse(StringTools.isEmpty(" ")); } |
### Question:
Shiftr implements SpecDriven, Transform { @Override public Object transform( Object input ) { Map<String,Object> output = new HashMap<>(); MatchedElement rootLpe = new MatchedElement( ROOT_KEY ); WalkedPath walkedPath = new WalkedPath(); walkedPath.add( input, rootLpe ); rootSpec.apply( ROOT_KEY, Optional.of( input ), walkedPath, output, null ); return output.get( ROOT_KEY ); } @Inject Shiftr( Object spec ); @Override Object transform( Object input ); }### Answer:
@Test(dataProvider = "getTestCaseUnits") public void runTestUnits(String testCaseName) throws IOException { String testPath = "/json/shiftr/" + testCaseName; Map<String, Object> testUnit = JsonUtils.classpathToMap( testPath + ".json" ); Object input = testUnit.get( "input" ); Object spec = testUnit.get( "spec" ); Object expected = testUnit.get( "expected" ); Shiftr shiftr = new Shiftr( spec ); Object actual = shiftr.transform( input ); JoltTestUtil.runDiffy( "failed case " + testPath, expected, actual ); } |
### Question:
SimpleTraversal { public Optional<DataType> get( Object tree ) { return (Optional<DataType>) traversr.get( tree, keys ); } SimpleTraversal( String humanReadablePath ); static SimpleTraversal<T> newTraversal(String humanReadablePath); Optional<DataType> get( Object tree ); Optional<DataType> set( Object tree, DataType data ); Optional<DataType> remove( Object tree ); }### Answer:
@Test( dataProvider = "inAndOutTestCases") public void getTests( String testDescription, SimpleTraversal simpleTraversal, Object ignoredForTest, Object input, String expected ) throws IOException { Object original = JsonUtils.cloneJson( input ); Object tree = JsonUtils.cloneJson( input ); Optional actual = simpleTraversal.get( tree ); Assert.assertEquals( expected, actual.get() ); JoltTestUtil.runDiffy( "Get should not have modified the input", original, tree ); } |
### Question:
Sortr implements Transform { @Override public Object transform( Object input ) { return sortJson( input ); } @Override Object transform( Object input ); @SuppressWarnings( "unchecked" ) static Object sortJson( Object obj ); }### Answer:
@Test(dataProvider = "getTestCaseNames") public void runTestCases(String testCaseName) throws IOException { if ("".equals( testCaseName )) { return; } String testPath = "/json/sortr/"+testCaseName; Map<String, Object> input = JsonUtils.classpathToMap(testPath + "/input.json"); Map<String, Object> expected = JsonUtils.classpathToMap( testPath + "/output.json" ); Sortr sortr = new Sortr(); Map<String, Object> actual = (Map<String, Object>) sortr.transform( input ); JoltTestUtil.runDiffy( "Make sure it is still the same object : " + testPath, expected, actual ); String orderErrorMessage = verifyOrder( actual, expected ); Assert.assertNull( orderErrorMessage, orderErrorMessage ); } |
### Question:
Sortr implements Transform { @SuppressWarnings( "unchecked" ) public static Object sortJson( Object obj ) { if ( obj instanceof Map ) { return sortMap( (Map<String, Object>) obj ); } else if ( obj instanceof List ) { return ordered( (List<Object>) obj ); } else { return obj; } } @Override Object transform( Object input ); @SuppressWarnings( "unchecked" ) static Object sortJson( Object obj ); }### Answer:
@Test public void testDoesNotBlowUpOnUnmodifiableArray() { List<Object> hasNan = new ArrayList<>(); hasNan.add( 1 ); hasNan.add( Double.NaN ); hasNan.add( 2 ); Map<String,Object> map = new HashMap<>(); map.put("a", "shouldBeFirst"); map.put("hasNan", Collections.unmodifiableList( hasNan ) ); try { Sortr.sortJson( map ); } catch( UnsupportedOperationException uoe ) { Assert.fail( "Sort threw a UnsupportedOperationException" ); } } |
### Question:
Modifier implements SpecDriven, ContextualTransform { @Override public Object transform( final Object input, final Map<String, Object> context ) { Map<String, Object> contextWrapper = new HashMap<>( ); contextWrapper.put( ROOT_KEY, context ); MatchedElement rootLpe = new MatchedElement( ROOT_KEY ); WalkedPath walkedPath = new WalkedPath(); walkedPath.add( input, rootLpe ); rootSpec.apply( ROOT_KEY, Optional.of( input), walkedPath, null, contextWrapper ); return input; } @SuppressWarnings( "unchecked" ) private Modifier( Object spec, OpMode opMode, Map<String, Function> functionsMap ); @Override Object transform( final Object input, final Map<String, Object> context ); }### Answer:
@Test public void testModifierFirstElementArray() throws IOException { Map<String, Object> input = new HashMap<String, Object>() {{ put("input", new Integer[]{5, 4}); }}; Map<String, Object> spec = new HashMap<String, Object>() {{ put("first", "=firstElement(@(1,input))"); }}; Map<String, Object> expected = new HashMap<String, Object>() {{ put("input", new Integer[]{5, 4}); put("first", 5); }}; Modifier modifier = new Modifier.Overwritr( spec ); Object actual = modifier.transform( input, null ); JoltTestUtil.runArrayOrderObliviousDiffy( "failed modifierFirstElementArray", expected, actual ); } |
### Question:
ArrayOrderObliviousDiffy extends Diffy { public ArrayOrderObliviousDiffy(JsonUtil jsonUtil) { super(jsonUtil); } ArrayOrderObliviousDiffy(JsonUtil jsonUtil); ArrayOrderObliviousDiffy(); }### Answer:
@Test(dataProvider = "testCases") public void ArrayOrderObliviousDiffy(String testCase) throws Exception { Object expected = JsonUtils.classpathToObject("/jsonUtils/" + testCase + "/expected.json"); Object actual = JsonUtils.classpathToObject("/jsonUtils/" + testCase + "/actual.json"); Diffy.Result result = unit.diff(expected, actual); Assert.assertTrue(result.isEmpty(), result.toString()); } |
### Question:
JoltCli { protected static boolean runJolt( String[] args ) { ArgumentParser parser = ArgumentParsers.newArgumentParser( "jolt" ); Subparsers subparsers = parser.addSubparsers().help( "transform: given a Jolt transform spec, runs the specified transforms on the input data.\n" + "diffy: diff two JSON documents.\n" + "sort: sort a JSON document alphabetically for human readability." ); for ( Map.Entry<String, JoltCliProcessor> entry : JOLT_CLI_PROCESSOR_MAP.entrySet() ) { entry.getValue().intializeSubCommand( subparsers ); } Namespace ns; try { ns = parser.parseArgs( args ); } catch ( ArgumentParserException e ) { parser.handleError( e ); return false; } JoltCliProcessor joltToolProcessor = JOLT_CLI_PROCESSOR_MAP.get( args[0] ); if ( joltToolProcessor != null ) { return joltToolProcessor.process( ns ); } else { return false; } } static void main( String[] args ); }### Answer:
@Test public void testRunJolt() throws IOException { String path = System.getProperty( "user.dir" ); if ( path.endsWith( "cli" ) ) { path += " } else { path += " } Assert.assertTrue( JoltCli.runJolt( new String[] {"diffy", path + "input1.json", path + "input1.json", "-s"} ) ); Assert.assertFalse( JoltCli.runJolt( new String[] {"diffy", path + "input1.json", path + "input2.json", "-s"} ) ); Assert.assertTrue( JoltCli.runJolt( new String[] {"sort", path + "input1.json"} ) ); Assert.assertTrue( JoltCli.runJolt( new String[] {"transform", path + "spec.json", path + "transformInput.json"} ) ); } |
### Question:
ChainrFactory { public static Chainr fromFileSystem( String chainrSpecFilePath ) { return fromFileSystem( chainrSpecFilePath, null ); } static Chainr fromClassPath( String chainrSpecClassPath ); static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ); static Chainr fromFileSystem( String chainrSpecFilePath ); static Chainr fromFileSystem( String chainrSpecFilePath, ChainrInstantiator chainrInstantiator ); static Chainr fromFile( File chainrSpecFile ); static Chainr fromFile( File chainrSpecFile, ChainrInstantiator chainrInstantiator ); }### Answer:
@Test public void testGetChainrInstanceFromFileSystem_success() throws Exception { Chainr result = ChainrFactory.fromFileSystem( fileSystemPath + WELLFORMED_INPUT_FILENAME ); Assert.assertNotNull( result, "ChainrFactory did not return an instance of Chainr." ); }
@Test( expectedExceptions = JsonUnmarshalException.class, expectedExceptionsMessageRegExp = "Unable to unmarshal JSON.*" ) public void testGetChainrInstanceFromFileSystem_error() throws Exception { ChainrFactory.fromFileSystem( fileSystemPath + MALFORMED_INPUT_FILENAME ); }
@Test public void testGetChainrInstanceFromFileSystemWithInstantiator_success() throws Exception { Chainr result = ChainrFactory.fromFileSystem( fileSystemPath + WELLFORMED_INPUT_FILENAME, new DefaultChainrInstantiator() ); Assert.assertNotNull( result, "ChainrFactory did not return an instance of Chainr." ); }
@Test(expectedExceptions = JsonUnmarshalException.class, expectedExceptionsMessageRegExp = "Unable to unmarshal JSON.*") public void testGetChainrInstanceFromFileSystemWithInstantiator_error() throws Exception { ChainrFactory.fromFileSystem( fileSystemPath + MALFORMED_INPUT_FILENAME, new DefaultChainrInstantiator() ); } |
### Question:
ActiveConsumerList { public void heartbeat(String consumerName, long heartbeatTime, String ip) { if (!m_consumers.containsKey(consumerName)) { m_changed = true; m_consumers.put(consumerName, new ClientContext(consumerName, ip, -1, null, null, heartbeatTime)); } else { ClientContext consumerContext = m_consumers.get(consumerName); if (!StringUtils.equals(consumerContext.getIp(), ip)) { m_changed = true; consumerContext.setIp(ip); } consumerContext.setLastHeartbeatTime(heartbeatTime); } } void heartbeat(String consumerName, long heartbeatTime, String ip); void purgeExpired(long timeoutMillis, long now); boolean getAndResetChanged(); Map<String, ClientContext> getActiveConsumers(); }### Answer:
@Test public void testHeartbeat() throws Exception { String consumerName = "c1"; String ip = "1.1.1.1"; long heartbeatTime = 1L; m_list.heartbeat(consumerName, heartbeatTime, ip); Map<String, ClientContext> activeConsumers = m_list.getActiveConsumers(); assertEquals(1, activeConsumers.size()); TestHelper.assertClientContextEquals(consumerName, ip, heartbeatTime, activeConsumers.get(consumerName)); assertTrue(m_list.getAndResetChanged()); } |
### Question:
ActiveConsumerList { public void purgeExpired(long timeoutMillis, long now) { Iterator<Entry<String, ClientContext>> iter = m_consumers.entrySet().iterator(); while (iter.hasNext()) { Entry<String, ClientContext> entry = iter.next(); if (entry.getValue().getLastHeartbeatTime() + timeoutMillis < now) { iter.remove(); m_changed = true; } } } void heartbeat(String consumerName, long heartbeatTime, String ip); void purgeExpired(long timeoutMillis, long now); boolean getAndResetChanged(); Map<String, ClientContext> getActiveConsumers(); }### Answer:
@Test public void testPurgeExpired() throws Exception { String consumerName = "c1"; String ip = "1.1.1.1"; long heartbeatTime = 1L; m_list.heartbeat(consumerName, heartbeatTime, ip); m_list.purgeExpired(10, 12L); Map<String, ClientContext> activeConsumers = m_list.getActiveConsumers(); assertEquals(0, activeConsumers.size()); assertTrue(m_list.getAndResetChanged()); m_list.heartbeat(consumerName, heartbeatTime, ip); m_list.purgeExpired(10, 1L); activeConsumers = m_list.getActiveConsumers(); assertEquals(1, activeConsumers.size()); TestHelper.assertClientContextEquals(consumerName, ip, heartbeatTime, activeConsumers.get(consumerName)); assertTrue(m_list.getAndResetChanged()); } |
### Question:
DefaultMetaService implements MetaService, Initializable { @Override public Topic findTopicByName(String topicName) { try { return findTopic(topicName, getMeta()); } catch (Exception e) { return null; } } @Override List<Partition> listPartitionsByTopic(String topicName); @Override Storage findStorageByTopic(String topicName); @Override Partition findPartitionByTopicAndPartition(String topicName, int partitionId); @Override List<Topic> listTopicsByPattern(String topicPattern); @Override Topic findTopicByName(String topicName); @Override int translateToIntGroupId(String topicName, String groupName); @Override List<Datasource> listAllMysqlDataSources(); @Override int getAckTimeoutSecondsByTopicAndConsumerGroup(String topicName, String groupId); @Override LeaseAcquireResponse tryAcquireConsumerLease(Tpg tpg, String sessionId); @Override LeaseAcquireResponse tryRenewConsumerLease(Tpg tpg, Lease lease, String sessionId); @Override LeaseAcquireResponse tryRenewBrokerLease(String topic, int partition, Lease lease, String sessionId,
int brokerPort); @Override LeaseAcquireResponse tryAcquireBrokerLease(String topic, int partition, String sessionId, int brokerPort); @Override void initialize(); @Override synchronized Pair<Endpoint, Long> findEndpointByTopicAndPartition(String topic, int partition); @Override RetryPolicy findRetryPolicyByTopicAndGroup(String topicName, String groupId); @Override boolean containsEndpoint(Endpoint endpoint); @Override boolean containsConsumerGroup(String topicName, String groupId); @Override Offset findMessageOffsetByTime(String topic, int partition, long time); @Override Map<Integer, Offset> findMessageOffsetByTime(String topic, long time); @Override List<ZookeeperEnsemble> listAllZookeeperEnsemble(); @Override Idc getPrimaryIdc(); }### Answer:
@Test public void testFindTopicByName() throws Exception { Topic topic = m_metaService.findTopicByName("test_broker"); assertEquals("test_broker", topic.getName()); topic = m_metaService.findTopicByName("topic_not_found"); assertNull(topic); } |
### Question:
DefaultMetaService implements MetaService, Initializable { @Override public boolean containsEndpoint(Endpoint endpoint) { return getMeta().getEndpoints().containsKey(endpoint.getId()); } @Override List<Partition> listPartitionsByTopic(String topicName); @Override Storage findStorageByTopic(String topicName); @Override Partition findPartitionByTopicAndPartition(String topicName, int partitionId); @Override List<Topic> listTopicsByPattern(String topicPattern); @Override Topic findTopicByName(String topicName); @Override int translateToIntGroupId(String topicName, String groupName); @Override List<Datasource> listAllMysqlDataSources(); @Override int getAckTimeoutSecondsByTopicAndConsumerGroup(String topicName, String groupId); @Override LeaseAcquireResponse tryAcquireConsumerLease(Tpg tpg, String sessionId); @Override LeaseAcquireResponse tryRenewConsumerLease(Tpg tpg, Lease lease, String sessionId); @Override LeaseAcquireResponse tryRenewBrokerLease(String topic, int partition, Lease lease, String sessionId,
int brokerPort); @Override LeaseAcquireResponse tryAcquireBrokerLease(String topic, int partition, String sessionId, int brokerPort); @Override void initialize(); @Override synchronized Pair<Endpoint, Long> findEndpointByTopicAndPartition(String topic, int partition); @Override RetryPolicy findRetryPolicyByTopicAndGroup(String topicName, String groupId); @Override boolean containsEndpoint(Endpoint endpoint); @Override boolean containsConsumerGroup(String topicName, String groupId); @Override Offset findMessageOffsetByTime(String topic, int partition, long time); @Override Map<Integer, Offset> findMessageOffsetByTime(String topic, long time); @Override List<ZookeeperEnsemble> listAllZookeeperEnsemble(); @Override Idc getPrimaryIdc(); }### Answer:
@Test public void testContainsEndpoint() throws Exception { assertTrue(m_metaService.containsEndpoint(new Endpoint("br0"))); assertFalse(m_metaService.containsEndpoint(new Endpoint("notFound"))); } |
### Question:
ExponentialSchedulePolicy implements SchedulePolicy { @Override public long fail(boolean shouldSleep) { int delayTime = m_lastDelayTime; if (delayTime == 0) { delayTime = m_delayBase; } else { delayTime = Math.min(m_lastDelayTime << 1, m_delayUpperbound); } if (shouldSleep) { try { Thread.sleep(delayTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } m_lastDelayTime = delayTime; return delayTime; } ExponentialSchedulePolicy(int delayBase, int delayUpperbound); @Override long fail(boolean shouldSleep); @Override void succeess(); }### Answer:
@Test public void testFail() { ExponentialSchedulePolicy policy = new ExponentialSchedulePolicy(10, 80); assertEquals(10, policy.fail(false)); assertEquals(20, policy.fail(false)); assertEquals(40, policy.fail(false)); assertEquals(80, policy.fail(false)); for (int i = 0; i < 100; i++) { assertEquals(80, policy.fail(false)); } } |
### Question:
Magic { public static void writeMagic(ByteBuf buf) { buf.writeBytes(MAGIC); } static void readAndCheckMagic(ByteBuffer buf); static void readAndCheckMagic(ByteBuf buf); static void writeMagic(ByteBuf buf); static int length(); }### Answer:
@Test public void testWrite() { ByteBuf buf = Unpooled.buffer(); Magic.writeMagic(buf); byte[] bytes = new byte[Magic.MAGIC.length]; buf.readBytes(bytes); assertArrayEquals(Magic.MAGIC, bytes); } |
### Question:
Magic { public static void readAndCheckMagic(ByteBuffer buf) { byte[] magic = new byte[MAGIC.length]; buf.get(magic); for (int i = 0; i < magic.length; i++) { if (magic[i] != MAGIC[i]) { throw new IllegalArgumentException("Magic number mismatch"); } } } static void readAndCheckMagic(ByteBuffer buf); static void readAndCheckMagic(ByteBuf buf); static void writeMagic(ByteBuf buf); static int length(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testReadAndCheckByteBufFail() { byte[] bytes = new byte[Magic.MAGIC.length]; System.arraycopy(Magic.MAGIC, 0, bytes, 0, Magic.MAGIC.length); bytes[bytes.length - 1] = (byte) (bytes[bytes.length - 1] + 1); Magic.readAndCheckMagic(Unpooled.wrappedBuffer(bytes)); }
@Test public void testReadAndCheckByteBuf() { byte[] bytes = new byte[Magic.MAGIC.length]; System.arraycopy(Magic.MAGIC, 0, bytes, 0, Magic.MAGIC.length); Magic.readAndCheckMagic(Unpooled.wrappedBuffer(bytes)); }
@Test(expected = IllegalArgumentException.class) public void testReadAndCheckByteBufferFail() { byte[] bytes = new byte[Magic.MAGIC.length]; System.arraycopy(Magic.MAGIC, 0, bytes, 0, Magic.MAGIC.length); bytes[bytes.length - 1] = (byte) (bytes[bytes.length - 1] + 1); Magic.readAndCheckMagic(ByteBuffer.wrap(bytes)); }
@Test public void testReadAndCheckByteBuffer() { byte[] bytes = new byte[Magic.MAGIC.length]; System.arraycopy(Magic.MAGIC, 0, bytes, 0, Magic.MAGIC.length); Magic.readAndCheckMagic(ByteBuffer.wrap(bytes)); } |
### Question:
MessageCodecUtils { public static ByteBuffer getPayload(ByteBuffer consumerMsg) { Pair<ByteBuffer, Date> pair = getPayloadAndBornTime(consumerMsg); return pair != null ? pair.getKey() : null; } static ByteBuffer getPayload(ByteBuffer consumerMsg); static Pair<ByteBuffer, Date> getPayloadAndBornTime(ByteBuffer consumerMsg); static byte[] getPayload(byte[] consumerMsg); }### Answer:
@Test public void getJsonPayloadByByteBuffer() { ProducerMessage<String> proMsg = new ProducerMessage<String>(); String expected = "Hello Ctrip"; proMsg.setTopic("kafka.SimpleTextTopic"); proMsg.setBody(expected); proMsg.setPartitionKey("MyPartition"); proMsg.setKey("MyKey"); proMsg.setBornTime(System.currentTimeMillis()); DefaultMessageCodec codec = new DefaultMessageCodec(); byte[] proMsgByte = codec.encode(proMsg); ByteBuffer byteBuffer = ByteBuffer.wrap(proMsgByte); ByteBuffer payload = MessageCodecUtils.getPayload(byteBuffer); Object actual = JSON.parseObject(payload.array(), String.class); assertEquals(expected, actual); }
@Test public void getJsonPayloadByByteArray() { ProducerMessage<String> proMsg = new ProducerMessage<String>(); String expected = "Hello Ctrip"; proMsg.setTopic("kafka.SimpleTextTopic"); proMsg.setBody(expected); proMsg.setPartitionKey("MyPartition"); proMsg.setKey("MyKey"); proMsg.setBornTime(System.currentTimeMillis()); DefaultMessageCodec codec = new DefaultMessageCodec(); byte[] proMsgByte = codec.encode(proMsg); byte[] payload = MessageCodecUtils.getPayload(proMsgByte); Object actual = JSON.parseObject(payload, String.class); assertEquals(expected, actual); } |
### Question:
DefaultMessageCodec implements MessageCodec { @Override public BaseConsumerMessage<?> decode(String topic, ByteBuf buf, Class<?> bodyClazz) { Magic.readAndCheckMagic(buf); MessageCodecVersion version = getVersion(buf); return version.getHandler().decode(topic, buf, bodyClazz); } @Override void encode(ProducerMessage<?> msg, ByteBuf buf); @Override byte[] encode(ProducerMessage<?> msg); @Override PartialDecodedMessage decodePartial(ByteBuf buf); @Override BaseConsumerMessage<?> decode(String topic, ByteBuf buf, Class<?> bodyClazz); @Override void encodePartial(PartialDecodedMessage msg, ByteBuf buf); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testMagicNumberCheckFail() throws Exception { ByteBuf buf = Unpooled.buffer(); buf.writeBytes(new byte[] { 1, 2, 3, 4 }); MessageCodec codec = new DefaultMessageCodec(); codec.decode("topic", buf, String.class); }
@Test(expected = IllegalArgumentException.class) public void testUnknowVersion() throws Exception { ByteBuf buf = Unpooled.buffer(); Magic.writeMagic(buf); buf.writeByte(100); MessageCodec codec = new DefaultMessageCodec(); codec.decode("topic", buf, String.class); } |
### Question:
HashPartitioningStrategy implements PartitioningStrategy { @Override public int computePartitionNo(String key, int partitionCount) { if (key == null) { return m_random.nextInt(Integer.MAX_VALUE) % partitionCount; } else { return (key.hashCode() == Integer.MIN_VALUE ? 0 : Math.abs(key.hashCode())) % partitionCount; } } @Override int computePartitionNo(String key, int partitionCount); }### Answer:
@Test public void testNormal() throws Exception { for (int i = 0; i < 100000; i++) { int partitionNo = strategy.computePartitionNo(generateRandomString(100), 5); assertTrue(partitionNo < 5); assertTrue(partitionNo >= 0); } }
@Test public void testNull() throws Exception { int partitionNo = strategy.computePartitionNo(null, 5); assertTrue(partitionNo < 5); assertTrue(partitionNo >= 0); } |
### Question:
RetryPolicyFactory { public static RetryPolicy create(String policyValue) { if (policyValue != null) { RetryPolicy policy = m_cache.get(policyValue); if (policy == null) { synchronized (m_cache) { policy = m_cache.get(policyValue); if (policy == null) { policy = createPolicy(policyValue); m_cache.put(policyValue, policy); } } } if (policy != null) { return policy; } } throw new IllegalArgumentException(String.format("Unknown retry policy for value %s", policyValue)); } static RetryPolicy create(String policyValue); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testInvalid1() throws Exception { RetryPolicyFactory.create(null); }
@Test(expected = IllegalArgumentException.class) public void testInvalid2() throws Exception { RetryPolicyFactory.create("2"); }
@Test(expected = IllegalArgumentException.class) public void testInvalid3() throws Exception { RetryPolicyFactory.create("2:"); }
@Test(expected = IllegalArgumentException.class) public void testInvalid4() throws Exception { RetryPolicyFactory.create("2: "); }
@Test(expected = IllegalArgumentException.class) public void testInvalid5() throws Exception { RetryPolicyFactory.create(" :1"); }
@Test public void testValid() throws Exception { RetryPolicy policy = RetryPolicyFactory.create("1:[1,2]"); assertTrue(policy instanceof FrequencySpecifiedRetryPolicy); assertEquals(2, policy.getRetryTimes()); }
@Test public void testValid2() throws Exception { RetryPolicy policy = RetryPolicyFactory.create("3:[10,5000]"); assertTrue(policy instanceof FixedIntervalRetryPolicy); assertEquals(10, policy.getRetryTimes()); assertEquals(5000, ((FixedIntervalRetryPolicy) policy).getIntervalMillis()); } |
### Question:
DefaultCMessagingConfigService implements CMessagingConfigService, Initializable { @Override public String getGroupId(String exchangeName, String idAndQueueName) { Exchange exchange = findExchange(exchangeName); String result = null; if (exchange != null) { ConsumeGroup group = exchange.getConsume().findConsumeGroup(idAndQueueName); if (group != null) { result = group.getHermesConsumerGroup(); } } return result; } @Override String getTopic(String exchangeName); @Override String getGroupId(String exchangeName, String idAndQueueName); @Override boolean isHermesProducerEnabled(String exchangeName, String identifier, String ip); @Override int getConsumerType(String exchangeName, String identifier, String ip); @Override void initialize(); }### Answer:
@Test public void testGetGroupId() throws Exception { DefaultCMessagingConfigService s = createServiceWithXml("consume_both.xml"); assertEquals("hermes-cid0", s.getGroupId("ex1", "cid0")); assertEquals("hermes-cid1", s.getGroupId("ex1", "cid1")); assertNull(s.getGroupId("ex1", "cid10")); } |
### Question:
DefaultCMessagingConfigService implements CMessagingConfigService, Initializable { @Override public String getTopic(String exchangeName) { Exchange exchange = findExchange(exchangeName); String result = null; if (exchange != null) { result = exchange.getHermesTopic(); } return result; } @Override String getTopic(String exchangeName); @Override String getGroupId(String exchangeName, String idAndQueueName); @Override boolean isHermesProducerEnabled(String exchangeName, String identifier, String ip); @Override int getConsumerType(String exchangeName, String identifier, String ip); @Override void initialize(); }### Answer:
@Test public void testGetTopic() throws Exception { DefaultCMessagingConfigService s = createServiceWithXml("consume_both.xml"); assertEquals("hermes-ex1", s.getTopic("ex1")); assertEquals("hermes-ex2", s.getTopic("ex2")); assertNull(s.getTopic("ex10")); } |
### Question:
DefaultPullConsumerHolder implements PullConsumerHolder<T>, MessageListener<T> { @Override public PulledBatch<T> poll(int maxMessageCount, int timeout) { long startTime = System.currentTimeMillis(); Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_CONSUME_POLL_TRIED, m_topic + ":" + m_group); try { PulledBatch<T> batch = retrive(maxMessageCount, timeout, RetrivePolicy.FAVOUR_FAST_RETURN); if (batch.getMessages() != null && !batch.getMessages().isEmpty()) { CatUtil.logElapse(CatConstants.TYPE_MESSAGE_CONSUME_POLL_ELAPSE, m_topic + ":" + m_group, startTime, batch .getMessages().size(), null, Transaction.SUCCESS); } return batch; } finally { t.setStatus(Transaction.SUCCESS); t.complete(); } } DefaultPullConsumerHolder(String topic, String groupId, int partitionCount, PullConsumerConfig config,
AckManager ackManager, OffsetStorage offsetStorage, ConsumerConfig consumerConfig); @Override void onMessage(List<ConsumerMessage<T>> msgs); @Override PulledBatch<T> poll(int maxMessageCount, int timeout); @Override PulledBatch<T> collect(int maxMessageCount, int timeout); @Override void close(); void setConsumerHolder(ConsumerHolder consumerHolder); }### Answer:
@Test public void testPollFail() { long start = System.currentTimeMillis(); int timeout = 10; int error = 100; List<ConsumerMessage<String>> msgs = holder.poll(1, timeout).getMessages(); assertTrue(System.currentTimeMillis() - start < config.getScanIntervalMax() + timeout + error); assertEquals(0, msgs.size()); } |
### Question:
DefaultPullConsumerHolder implements PullConsumerHolder<T>, MessageListener<T> { @Override public PulledBatch<T> collect(int maxMessageCount, int timeout) { long startTime = System.currentTimeMillis(); Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_CONSUME_COLLECT_TRIED, m_topic + ":" + m_group); try { PulledBatch<T> batch = retrive(maxMessageCount, timeout, RetrivePolicy.FAVOUR_MORE_MESSAGE); if (batch.getMessages() != null && !batch.getMessages().isEmpty()) { CatUtil.logElapse(CatConstants.TYPE_MESSAGE_CONSUME_COLLECT_ELAPSE, m_topic + ":" + m_group, startTime, batch.getMessages().size(), null, Transaction.SUCCESS); } return batch; } finally { t.setStatus(Transaction.SUCCESS); t.complete(); } } DefaultPullConsumerHolder(String topic, String groupId, int partitionCount, PullConsumerConfig config,
AckManager ackManager, OffsetStorage offsetStorage, ConsumerConfig consumerConfig); @Override void onMessage(List<ConsumerMessage<T>> msgs); @Override PulledBatch<T> poll(int maxMessageCount, int timeout); @Override PulledBatch<T> collect(int maxMessageCount, int timeout); @Override void close(); void setConsumerHolder(ConsumerHolder consumerHolder); }### Answer:
@Test public void testCollectFail() { long start = System.currentTimeMillis(); int timeout = 10; int error = 100; List<ConsumerMessage<String>> msgs = holder.collect(1, timeout).getMessages(); assertTrue(System.currentTimeMillis() - start < config.getScanIntervalMax() + timeout + error); assertEquals(0, msgs.size()); } |
### Question:
MySQLMessageQueueStorage implements MessageQueueStorage, Initializable { @Override public synchronized Object findLastOffset(Tpp tpp, int groupId) throws DalException { String topic = tpp.getTopic(); int partition = tpp.getPartition(); int priority = tpp.getPriorityInt(); if (!hasStorageForPriority(tpp.getTopic(), tpp.getPriorityInt())) { return 0L; } return findLastOffset(topic, partition, priority, groupId).getOffset(); } @Override void appendMessages(String topicName, int partition, boolean priority,
Collection<MessageBatchWithRawData> batches); @Override synchronized Object findLastOffset(Tpp tpp, int groupId); @Override FetchResult fetchMessages(Tpp tpp, List<Object> offsets); @Override FetchResult fetchMessages(Tpp tpp, Object startOffset, int batchSize, String filter); @Override void nack(Tpp tpp, String groupId, boolean resend, List<Pair<Long, MessageMeta>> msgId2Metas); @Override void ack(Tpp tpp, String groupId, boolean resend, long msgSeq); @Override synchronized Object findLastResendOffset(Tpg tpg); @SuppressWarnings("unchecked") @Override FetchResult fetchResendMessages(Tpg tpg, Object startOffset, int batchSize); @Override Object findMessageOffsetByTime(Tpp tpp, long time); @Override void initialize(); }### Answer:
@Test public void testFindLastOffset() throws Exception { Tpp tpp = new Tpp("order_new", 0, true); s.findLastOffset(tpp, 100); } |
### Question:
MySQLMessageQueueStorage implements MessageQueueStorage, Initializable { @Override public synchronized Object findLastResendOffset(Tpg tpg) throws DalException { int intGroupId = m_metaService.translateToIntGroupId(tpg.getTopic(), tpg.getGroupId()); OffsetResend offset = findLastResendOffset(tpg.getTopic(), tpg.getPartition(), intGroupId); return new Pair<>(offset.getLastScheduleDate(), offset.getLastId()); } @Override void appendMessages(String topicName, int partition, boolean priority,
Collection<MessageBatchWithRawData> batches); @Override synchronized Object findLastOffset(Tpp tpp, int groupId); @Override FetchResult fetchMessages(Tpp tpp, List<Object> offsets); @Override FetchResult fetchMessages(Tpp tpp, Object startOffset, int batchSize, String filter); @Override void nack(Tpp tpp, String groupId, boolean resend, List<Pair<Long, MessageMeta>> msgId2Metas); @Override void ack(Tpp tpp, String groupId, boolean resend, long msgSeq); @Override synchronized Object findLastResendOffset(Tpg tpg); @SuppressWarnings("unchecked") @Override FetchResult fetchResendMessages(Tpg tpg, Object startOffset, int batchSize); @Override Object findMessageOffsetByTime(Tpp tpp, long time); @Override void initialize(); }### Answer:
@Test public void testFindLastResendOffset() throws Exception { Tpg tpg = new Tpg("order_new", 0, "group1"); s.findLastResendOffset(tpg); } |
### Question:
StringResolver { public String get(@StringRes int resId, Object... args) { return resources.getString(resId, args); } @Inject StringResolver(Resources resources); String get(@StringRes int resId, Object... args); }### Answer:
@Test public void shouldGetStringWithoutArguments() throws Exception { resolver.get(R.string.application); then(resources).should().getString(R.string.application, new Object[0]); }
@Test @SuppressLint("StringFormatInvalid") public void shouldGetStringWithArguments() throws Exception { resolver.get(R.string.application, "arg0", "arg1"); then(resources).should().getString(R.string.application, "arg0", "arg1"); } |
### Question:
SpinedBuffer extends AbstractSpinedBuffer implements Consumer<E>, Iterable<E> { @SuppressWarnings("unchecked") public SpinedBuffer(int initialCapacity) { super(initialCapacity); curChunk = (E[]) new Object[1 << initialChunkPower]; } @SuppressWarnings("unchecked") SpinedBuffer(int initialCapacity); @SuppressWarnings("unchecked") SpinedBuffer(); E get(long index); void copyInto(E[] array, int offset); E[] asArray(IntFunction<E[]> arrayFactory); @Override void clear(); @Override Iterator<E> iterator(); @Override void forEach(Consumer<? super E> consumer); @Override void accept(E e); @Override String toString(); Spliterator<E> spliterator(); }### Answer:
@Test(groups = { "serialization-hostile" }) public void testSpinedBuffer() { List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); SpinedBuffer<Integer> sb = new SpinedBuffer<>(); for (int i = 0; i < TEST_SIZE; i++) { list1.add(i); sb.accept(i); } Iterator<Integer> it = sb.iterator(); for (int i = 0; i < TEST_SIZE; i++) list2.add(it.next()); assertFalse(it.hasNext()); assertEquals(list1, list2); for (int i = 0; i < TEST_SIZE; i++) assertEquals(sb.get(i), (Integer) i, Integer.toString(i)); list2.clear(); sb.forEach(list2::add); assertEquals(list1, list2); Integer[] array = sb.asArray(LambdaTestHelpers.integerArrayGenerator); list2.clear(); for (Integer i : array) list2.add(i); assertEquals(list1, list2); } |
### Question:
LayoutBinder implements FileScopeProvider { public IdentifierExpr addVariable(String name, String type, Location location, boolean declared) { Preconditions.check(!mUserDefinedVariables.containsKey(name), "%s has already been defined as %s", name, type); final IdentifierExpr id = mExprModel.identifier(name); id.setUserDefinedType(type); id.enableDirectInvalidation(); if (location != null) { id.addLocation(location); } mUserDefinedVariables.put(name, type); if (declared) { id.setDeclared(); } return id; } LayoutBinder(ResourceBundle.LayoutFileBundle layoutBundle); void resolveWhichExpressionsAreUsed(); IdentifierExpr addVariable(String name, String type, Location location,
boolean declared); HashMap<String, String> getUserDefinedVariables(); BindingTarget createBindingTarget(ResourceBundle.BindingTargetBundle targetBundle); Expr parse(String input, boolean isTwoWay, @Nullable Location locationInFile); List<BindingTarget> getBindingTargets(); List<BindingTarget> getSortedTargets(); boolean isEmpty(); ExprModel getModel(); void sealModel(); String writeViewBinderBaseClass(boolean forLibrary); String writeViewBinder(int minSdk); String getPackage(); boolean isMerge(); String getModulePackage(); String getLayoutname(); String getImplementationName(); String getClassName(); String getTag(); boolean hasVariations(); @Override String provideScopeFilePath(); }### Answer:
@Test public void testRegisterId() { int originalSize = mExprModel.size(); mLayoutBinder.addVariable("test", "java.lang.String", null); assertEquals(originalSize + 1, mExprModel.size()); final Map.Entry<String, Expr> entry = findIdentifier("test"); final Expr value = entry.getValue(); assertEquals(value.getClass(), IdentifierExpr.class); final IdentifierExpr id = (IdentifierExpr) value; assertEquals("test", id.getName()); assertEquals(new JavaClass(String.class), id.getResolvedType()); assertTrue(id.isDynamic()); } |
### Question:
LayoutBinder implements FileScopeProvider { public Expr parse(String input, boolean isTwoWay, @Nullable Location locationInFile) { final Expr parsed = mExpressionParser.parse(input, locationInFile); parsed.setBindingExpression(true); parsed.setTwoWay(isTwoWay); return parsed; } LayoutBinder(ResourceBundle.LayoutFileBundle layoutBundle); void resolveWhichExpressionsAreUsed(); IdentifierExpr addVariable(String name, String type, Location location,
boolean declared); HashMap<String, String> getUserDefinedVariables(); BindingTarget createBindingTarget(ResourceBundle.BindingTargetBundle targetBundle); Expr parse(String input, boolean isTwoWay, @Nullable Location locationInFile); List<BindingTarget> getBindingTargets(); List<BindingTarget> getSortedTargets(); boolean isEmpty(); ExprModel getModel(); void sealModel(); String writeViewBinderBaseClass(boolean forLibrary); String writeViewBinder(int minSdk); String getPackage(); boolean isMerge(); String getModulePackage(); String getLayoutname(); String getImplementationName(); String getClassName(); String getTag(); boolean hasVariations(); @Override String provideScopeFilePath(); }### Answer:
@Test public void testParse() { int originalSize = mExprModel.size(); mLayoutBinder.addVariable("user", "android.databinding.tool2.LayoutBinderTest.TestUser", null); mLayoutBinder.parse("user.name", false, null); mLayoutBinder.parse("user.lastName", false, null); assertEquals(originalSize + 3, mExprModel.size()); final List<Expr> bindingExprs = mExprModel.getBindingExpressions(); assertEquals(2, bindingExprs.size()); IdentifierExpr id = mExprModel.identifier("user"); assertTrue(bindingExprs.get(0) instanceof FieldAccessExpr); assertTrue(bindingExprs.get(1) instanceof FieldAccessExpr); assertEquals(2, id.getParents().size()); assertTrue(bindingExprs.get(0).getChildren().contains(id)); assertTrue(bindingExprs.get(1).getChildren().contains(id)); } |
### Question:
Location { public boolean contains(Location other) { if (startLine > other.startLine) { return false; } if (startLine == other.startLine && startOffset > other.startOffset) { return false; } if (endLine < other.endLine) { return false; } return !(endLine == other.endLine && endOffset < other.endOffset); } Location(); Location(Location other); Location(Token start, Token end); Location(ParserRuleContext context); Location(int startLine, int startOffset, int endLine, int endOffset); @Override String toString(); void setParentLocation(Location parentLocation); @Override boolean equals(Object o); @Override int hashCode(); boolean isValid(); boolean contains(Location other); Location toAbsoluteLocation(); String toUserReadableString(); static Location fromUserReadableString(String str); LocationScopeProvider createScope(); static final int NaN; @XmlAttribute(name = "startLine")
public int startLine; @XmlAttribute(name = "startOffset")
public int startOffset; @XmlAttribute(name = "endLine")
public int endLine; @XmlAttribute(name = "endOffset")
public int endOffset; @XmlElement(name = "parentLocation")
public Location parentLocation; }### Answer:
@Test public void testContains() { Location location1 = new Location(0, 0, 10, 1); Location location2 = new Location(0, 0, 9, 1); assertTrue(location1.contains(location2)); location2.endLine = 10; assertTrue(location1.contains(location2)); location2.endOffset = 2; assertFalse(location1.contains(location2)); } |
### Question:
DiffUtil { public static DiffResult calculateDiff(Callback cb) { return calculateDiff(cb, true); } private DiffUtil(); static DiffResult calculateDiff(Callback cb); static DiffResult calculateDiff(Callback cb, boolean detectMoves); }### Answer:
@Test public void testDisableMoveDetection() { initWithSize(5); move(0, 4); List<Item> applied = applyUpdates(mBefore, DiffUtil.calculateDiff(mCallback, false)); assertThat(applied.size(), is(5)); assertThat(applied.get(4).newItem, is(true)); assertThat(applied.contains(mBefore.get(0)), is(false)); } |
### Question:
ViewInfoStore { void addToPreLayout(ViewHolder holder, ItemHolderInfo info) { InfoRecord record = mLayoutHolderMap.get(holder); if (record == null) { record = InfoRecord.obtain(); mLayoutHolderMap.put(holder, record); } record.preInfo = info; record.flags |= FLAG_PRE; } void onViewDetached(ViewHolder viewHolder); }### Answer:
@Test public void addOverridePre() { RecyclerView.ViewHolder vh = new MockViewHolder(); MockInfo info = new MockInfo(); mStore.addToPreLayout(vh, info); MockInfo info2 = new MockInfo(); mStore.addToPreLayout(vh, info2); assertSame(info2, find(vh, FLAG_PRE)); }
@Test public void addToPreLayout() { RecyclerView.ViewHolder vh = new MockViewHolder(); MockInfo info = new MockInfo(); mStore.addToPreLayout(vh, info); assertSame(info, find(vh, FLAG_PRE)); assertTrue(mStore.isInPreLayout(vh)); mStore.removeViewHolder(vh); assertFalse(mStore.isInPreLayout(vh)); } |
### Question:
ViewInfoStore { void addToPostLayout(ViewHolder holder, ItemHolderInfo info) { InfoRecord record = mLayoutHolderMap.get(holder); if (record == null) { record = InfoRecord.obtain(); mLayoutHolderMap.put(holder, record); } record.postInfo = info; record.flags |= FLAG_POST; } void onViewDetached(ViewHolder viewHolder); }### Answer:
@Test public void addOverridePost() { RecyclerView.ViewHolder vh = new MockViewHolder(); MockInfo info = new MockInfo(); mStore.addToPostLayout(vh, info); MockInfo info2 = new MockInfo(); mStore.addToPostLayout(vh, info2); assertSame(info2, find(vh, FLAG_POST)); }
@Test public void addToPostLayout() { RecyclerView.ViewHolder vh = new MockViewHolder(); MockInfo info = new MockInfo(); mStore.addToPostLayout(vh, info); assertSame(info, find(vh, FLAG_POST)); mStore.removeViewHolder(vh); assertNull(find(vh, FLAG_POST)); } |
### Question:
ViewInfoStore { @Nullable ItemHolderInfo popFromPreLayout(ViewHolder vh) { return popFromLayoutStep(vh, FLAG_PRE); } void onViewDetached(ViewHolder viewHolder); }### Answer:
@Test public void popFromPreLayout() { assertEquals(0, sizeOf(FLAG_PRE)); RecyclerView.ViewHolder vh = new MockViewHolder(); MockInfo info = new MockInfo(); mStore.addToPreLayout(vh, info); assertSame(info, mStore.popFromPreLayout(vh)); assertNull(mStore.popFromPreLayout(vh)); } |
### Question:
ViewInfoStore { void addToOldChangeHolders(long key, ViewHolder holder) { mOldChangedHolders.put(key, holder); } void onViewDetached(ViewHolder viewHolder); }### Answer:
@Test public void addToOldChangeHolders() { RecyclerView.ViewHolder vh = new MockViewHolder(); mStore.addToOldChangeHolders(1, vh); assertSame(vh, mStore.getFromOldChangeHolders(1)); mStore.removeViewHolder(vh); assertNull(mStore.getFromOldChangeHolders(1)); } |
### Question:
TimingSource { public final void addTickListener(TickListener listener) { if (listener == null) return; f_tickListeners.add(listener); } abstract void init(); abstract void dispose(); abstract boolean isDisposed(); final void addTickListener(TickListener listener); final void removeTickListener(TickListener listener); final void addPostTickListener(PostTickListener listener); final void removePostTickListener(PostTickListener listener); final void submit(Runnable task); void runPerTick(); }### Answer:
@Test public void tick1() { final ManualTimingSource ts = new ManualTimingSource(); tickCounter = 0; ts.addTickListener(new TickListener() { public void timingSourceTick(TimingSource source, long nanoTime) { tickCounter++; Assert.assertSame(ts, source); } }); Assert.assertEquals(0, tickCounter); }
@Test public void tick2() { final ManualTimingSource ts = new ManualTimingSource(); tickCounter = 0; ts.addTickListener(new TickListener() { public void timingSourceTick(TimingSource source, long nanoTime) { tickCounter++; Assert.assertSame(ts, source); } }); ts.tick(); Assert.assertEquals(1, tickCounter); }
@Test public void tick3() { final ManualTimingSource ts = new ManualTimingSource(); tickCounter = 0; ts.addTickListener(new TickListener() { public void timingSourceTick(TimingSource source, long nanoTime) { tickCounter++; Assert.assertSame(ts, source); } }); ts.tick(); ts.tick(); Assert.assertEquals(2, tickCounter); }
@Test public void tick4() { final ManualTimingSource ts = new ManualTimingSource(); tickCounter = 0; ts.addTickListener(new TickListener() { public void timingSourceTick(TimingSource source, long nanoTime) { tickCounter++; Assert.assertSame(ts, source); } }); for (int i = 0; i < 1000; i++) ts.tick(); Assert.assertEquals(1000, tickCounter); } |
### Question:
TimingSource { public final void submit(Runnable task) { if (task == null) return; final WrappedRunnable wrapped = new WrappedRunnable(task); f_oneShotQueue.add(wrapped); } abstract void init(); abstract void dispose(); abstract boolean isDisposed(); final void addTickListener(TickListener listener); final void removeTickListener(TickListener listener); final void addPostTickListener(PostTickListener listener); final void removePostTickListener(PostTickListener listener); final void submit(Runnable task); void runPerTick(); }### Answer:
@Test public void runTask() { final ManualTimingSource ts = new ManualTimingSource(); taskCounter = 0; ts.submit(new Runnable() { public void run() { taskCounter++; } }); ts.tick(); Assert.assertEquals(1, taskCounter); } |
### Question:
PropertySetter { public static <T> TimingTargetAdapter getTargetTo(Object object, String propertyName, KeyFrames<T> keyFrames) { return getTargetHelper(object, propertyName, keyFrames, true); } private PropertySetter(); static TimingTargetAdapter getTarget(Object object, String propertyName, KeyFrames<T> keyFrames); static TimingTargetAdapter getTarget(Object object, String propertyName, T... values); static TimingTargetAdapter getTarget(Object object, String propertyName, Interpolator interpolator, T... values); static TimingTargetAdapter getTargetTo(Object object, String propertyName, KeyFrames<T> keyFrames); static TimingTargetAdapter getTargetTo(Object object, String propertyName, T... values); static TimingTargetAdapter getTargetTo(Object object, String propertyName, Interpolator interpolator, T... values); }### Answer:
@Test(expected = IllegalArgumentException.class) public void noSuchPropertyTo1() { MyProps pt = new MyProps(); PropertySetter.getTargetTo(pt, "wrong", 1, 2, 3); }
@Test(expected = IllegalArgumentException.class) public void noSuchPropertyTo2() { MyProps pt = new MyProps(); PropertySetter.getTargetTo(pt, "byteValue", (byte) 1, (byte) 2, (byte) 3); }
@Test public void valuePropertyTo() { MyProps pt = new MyProps(); pt.setValue(100); TimingTarget tt = PropertySetter.getTargetTo(pt, "value", 1, 2, 3); ManualTimingSource ts = new ManualTimingSource(); Animator a = new Animator.Builder(ts).addTarget(tt).build(); a.start(); ts.tick(); Assert.assertEquals(100, pt.getValue()); while (a.isRunning()) ts.tick(); Assert.assertEquals(3, pt.getValue()); } |
### Question:
FileSystemPathRelative implements FileSystemPath { @Override public final Path path() { if (fromPath.equals(artifactPath)) return artifactPath.path(); return fromPath.path().relativize(artifactPath.path()); } FileSystemPathRelative(Path fromPath, String artifactPath); FileSystemPathRelative(String fromPath, String artifactPath); FileSystemPathRelative(FileSystemPath fromPath, FileSystemPath artifactPath); @Override final Path path(); @Override final boolean exist(); }### Answer:
@Test public void asStringForParentWithSlashInTheEnd() { MatcherAssert.assertThat( new FileSystemPathRelative("/a/b/", "/a/b/c").path(), Matchers.is(new PathMatcher("c"))); }
@Test public void asStringForParentWithoutSlashInTheEnd() { MatcherAssert.assertThat( new FileSystemPathRelative("/a/b", "/a/b/c").path(), Matchers.is(new PathMatcher("c"))); }
@Test public void asStringWhenParentIsEqualsToFull() { MatcherAssert.assertThat( new FileSystemPathRelative("/a/b/c", "/a/b/c").path(), Matchers.is(new PathMatcher("/a/b/c"))); }
@Test public void asStringForRelativeParentWithSlashInTheEnd() { MatcherAssert.assertThat( new FileSystemPathRelative("a/b/", "a/b/c").path(), Matchers.is(new PathMatcher("c"))); }
@Test public void asStringForRelativeParentWithoutSlashInTheEnd() { MatcherAssert.assertThat( new FileSystemPathRelative("a/b", "a/b/c").path(), Matchers.is(new PathMatcher("c"))); } |
### Question:
DirectoryWithAutomaticDeletion implements Directory { @Override public final void create() throws IOException { Runtime.getRuntime() .addShutdownHook( new Thread("ds") { @Override public void run() { try { directory.remove(); } catch (IOException e) { throw new RuntimeException(e); } } }); directory.create(); } DirectoryWithAutomaticDeletion(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }### Answer:
@Test public void create() throws IOException { final java.io.File file = testFolder.getRoot(); new DirectoryWithAutomaticDeletion(new Directory.Fake(file.toPath())).create(); MatcherAssert.assertThat("The directory wasn't created", file.exists()); } |
### Question:
DirectoryWithAutomaticDeletion implements Directory { @Override public final void remove() throws IOException { directory.remove(); } DirectoryWithAutomaticDeletion(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }### Answer:
@Test public void remove() throws IOException { final java.io.File file = testFolder.getRoot(); new DirectoryWithAutomaticDeletion(new Directory.Fake(file.toPath())).remove(); MatcherAssert.assertThat("The directory exists", file.exists()); } |
### Question:
DirectoryWithAutomaticDeletion implements Directory { @Override public final boolean exist() { return directory.exist(); } DirectoryWithAutomaticDeletion(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }### Answer:
@Test public void exist() { MatcherAssert.assertThat( "The directory isn't present", new DirectoryWithAutomaticDeletion( new Directory.Fake(testFolder.getRoot().toPath(), true)) .exist()); } |
### Question:
DirectoryWithAutomaticDeletion implements Directory { @Override public final Path path() { return directory.path(); } DirectoryWithAutomaticDeletion(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }### Answer:
@Test public void path() { final Path file = testFolder.getRoot().toPath(); MatcherAssert.assertThat( new DirectoryWithAutomaticDeletion(new Directory.Fake(file)).path(), Matchers.equalTo(file)); } |
### Question:
FileSystemFiltered implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { return fileSystem.files().stream() .filter(f -> condition.applicable(f.path().toString())) .collect(Collectors.toList()); } FileSystemFiltered(FileSystem fileSystem, Condition condition); @Override List<FileSystemPath> files(); }### Answer:
@Test public void files() throws FileSystemException { MatcherAssert.assertThat( new FileSystemFiltered( new FileSystem.Fake( Collections.singletonList(new FileSystemPath.Fake())), new Condition.Fake(false)) .files(), Matchers.hasSize(0)); } |
### Question:
RegexCondition implements Condition { @Override public final boolean applicable(String identity) { return regex.matcher(identity).matches(); } RegexCondition(); RegexCondition(String regex); RegexCondition(Pattern regex); @Override final boolean applicable(String identity); }### Answer:
@Test public void applicable() { MatcherAssert.assertThat( "Regex doesn't work for " + this.className, new RegexCondition().applicable(this.className)); } |
### Question:
SunshineSuitePrintable implements SunshineSuite { @Override public final List<SunshineTest> tests() throws SuiteException { final List<SunshineTest> tests = this.sunshineSuite.tests(); final StringBuilder message = new StringBuilder(); message.append("Sunshine found ") .append(tests.size()) .append( " classes by the specified pattern. They all will be passed to appropriate xUnit engine.") .append("\nClasses:"); tests.forEach(c -> message.append("\n- ").append(c)); System.out.println(message); return tests; } SunshineSuitePrintable(SunshineSuite sunshineSuite); @Override final List<SunshineTest> tests(); }### Answer:
@Test public void tests() throws SuiteException { final SunshineTest.Fake test = new SunshineTest.Fake(); MatcherAssert.assertThat( new SunshineSuitePrintable(new SunshineSuite.Fake(test)).tests(), Matchers.contains(test)); } |
### Question:
Sun implements Star { @Override public final void shine() { try { final Status status = this.core.status(); System.out.println( new StringBuilder("\n===============================================\n") .append("Total tests run: ") .append(status.runCount()) .append(", Failures: ") .append(status.failureCount()) .append(", Skips: ") .append(status.ignoreCount()) .append("\n===============================================\n")); System.exit(status.code()); } catch (KernelException e) { e.printStackTrace(System.out); System.exit(Sun.SUNSHINE_ERROR); } } Sun(Kernel<?> kernel); @Override final void shine(); }### Answer:
@Test public void shine() { exit.expectSystemExitWithStatus(0); new Sun(new Kernel.Fake(new Fake())).shine(); } |
### Question:
FileSystemOfClasspathClasses implements FileSystem { @Override public final List<FileSystemPath> files() throws FileSystemException { return fileSystem.files(); } FileSystemOfClasspathClasses(); private FileSystemOfClasspathClasses(FileSystem fileSystem); @Override final List<FileSystemPath> files(); }### Answer:
@Test public void files() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfClasspathClasses().files(), Matchers.not(Matchers.empty())); } |
### Question:
FileSystemOfPath implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { try { List<FileSystemPath> files = new ArrayList<>(); Files.walkFileTree( path, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs) { files.add(new FileSystemPathRelative(path, dir.toString())); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { files.add(new FileSystemPathRelative(path, file.toString())); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return FileVisitResult.CONTINUE; } }); return files; } catch (IOException e) { throw new FileSystemException(e); } } FileSystemOfPath(String path); FileSystemOfPath(Path path); @Override List<FileSystemPath> files(); }### Answer:
@Test public void files() throws FileSystemException { CustomTypeSafeMatcher<Integer> matcher = new CustomTypeSafeMatcher<Integer>("Has at least one item") { @Override protected boolean matchesSafely(Integer item) { return item > 0; } }; MatcherAssert.assertThat( new FileSystemOfPath(RESOURCES).files(), Matchers.hasSize(matcher)); } |
### Question:
SequentialExecution implements Kernel<Listener> { @Override public Status status() throws KernelException { final List<Status> results = new ArrayList<>(); for (Kernel<Listener> kernel : this.elements) { results.add(kernel.status()); } return new CompositeStatus(results); } @SafeVarargs SequentialExecution(Kernel<Listener>... kernels); SequentialExecution(List<Kernel<Listener>> kernels); @Override Status status(); @Override Kernel<Listener> with(Listener... listeners); }### Answer:
@Test public void testStatus() throws KernelException { MatcherAssert.assertThat( new SequentialExecution<Object>( new Kernel.Fake(new Status.Fake()), new Kernel.Fake(new Status.Fake((short) 1, 2, 1, 1))) .status() .code(), Matchers.is((short) 1)); } |
### Question:
SequentialExecution implements Kernel<Listener> { @Override public Kernel<Listener> with(Listener... listeners) { return new SequentialExecution<>( this.elements.stream() .map(listenerKernel -> listenerKernel.with(listeners)) .collect(Collectors.toList())); } @SafeVarargs SequentialExecution(Kernel<Listener>... kernels); SequentialExecution(List<Kernel<Listener>> kernels); @Override Status status(); @Override Kernel<Listener> with(Listener... listeners); }### Answer:
@Test public void testWithListeners() { final List<Object> listeners = new ArrayList<>(); new SequentialExecution<Object>(new Kernel.Fake(new Status.Fake(), listeners)) .with(new Object()); MatcherAssert.assertThat(listeners, Matchers.hasSize(1)); } |
### Question:
FileSystemOfFileSystems implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { List<FileSystemPath> files = new ArrayList<>(); for (FileSystem fileSystem : fileSystems) { files.addAll(fileSystem.files()); } return files; } FileSystemOfFileSystems(List<FileSystem> fileSystems); FileSystemOfFileSystems(FileSystem... fileSystems); @Override List<FileSystemPath> files(); }### Answer:
@Test public void files() throws FileSystemException { List<FileSystem> fileSystems = Arrays.asList( new FileSystem.Fake(Collections.singletonList(new FileSystemPath.Fake())), new FileSystem.Fake(Collections.singletonList(new FileSystemPath.Fake()))); MatcherAssert.assertThat( new FileSystemOfFileSystems(fileSystems).files(), Matchers.hasSize(2)); } |
### Question:
FileSystemPathBase implements FileSystemPath { @Override public final Path path() { return directory.resolve(file); } FileSystemPathBase(String path); FileSystemPathBase(String directory, String file); FileSystemPathBase(Path path); FileSystemPathBase(Directory directory, String fsPath); FileSystemPathBase(Path directory, String file); @Override final Path path(); @Override final boolean exist(); }### Answer:
@Test public void path() { final String path = "aa"; MatcherAssert.assertThat( new FileSystemPathBase(path).path(), Matchers.equalTo(Paths.get(path))); }
@Test public void pathWithFolder() { final String directory = "aa"; final String file = "file"; MatcherAssert.assertThat( new FileSystemPathBase(directory, file).path(), Matchers.equalTo(Paths.get(directory + "/" + file))); } |
### Question:
FileSystemPathBase implements FileSystemPath { @Override public final boolean exist() { return Files.exists(path()); } FileSystemPathBase(String path); FileSystemPathBase(String directory, String file); FileSystemPathBase(Path path); FileSystemPathBase(Directory directory, String fsPath); FileSystemPathBase(Path directory, String file); @Override final Path path(); @Override final boolean exist(); }### Answer:
@Test public void exist() { MatcherAssert.assertThat( "File is absent", new FileSystemPathBase( "src/main/java/org/tatools/sunshine/core/FileSystemPathBase.java") .exist()); } |
### Question:
DirectoryBase implements Directory { @Override public final void create() throws IOException { Files.createDirectory(fileSystemPath.path()); } DirectoryBase(String path); DirectoryBase(Path path); DirectoryBase(FileSystemPath fileSystemPath); @Override final void create(); @Override final void remove(); @Override final boolean exist(); @Override final Path path(); }### Answer:
@Test public void create() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.getRoot().getAbsolutePath(), "a"); new DirectoryBase(path).create(); MatcherAssert.assertThat("The directory wasn't created", path.exist()); } |
### Question:
DirectoryBase implements Directory { @Override public final void remove() throws IOException { Files.walk(fileSystemPath.path(), FileVisitOption.FOLLOW_LINKS) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(java.io.File::delete); } DirectoryBase(String path); DirectoryBase(Path path); DirectoryBase(FileSystemPath fileSystemPath); @Override final void create(); @Override final void remove(); @Override final boolean exist(); @Override final Path path(); }### Answer:
@Test public void remove() throws IOException { java.io.File file = testFolder.newFolder(); final FileSystemPathBase path = new FileSystemPathBase(file.toString()); new DirectoryBase(path).remove(); MatcherAssert.assertThat("The directory exists", !path.exist()); } |
### Question:
DirectoryBase implements Directory { @Override public final boolean exist() { return fileSystemPath.exist(); } DirectoryBase(String path); DirectoryBase(Path path); DirectoryBase(FileSystemPath fileSystemPath); @Override final void create(); @Override final void remove(); @Override final boolean exist(); @Override final Path path(); }### Answer:
@Test public void exist() { MatcherAssert.assertThat( "The directory isn't present", new DirectoryBase(new FileSystemPathBase(testFolder.getRoot().getAbsolutePath())) .exist()); } |
### Question:
DirectoryBase implements Directory { @Override public final Path path() { return fileSystemPath.path(); } DirectoryBase(String path); DirectoryBase(Path path); DirectoryBase(FileSystemPath fileSystemPath); @Override final void create(); @Override final void remove(); @Override final boolean exist(); @Override final Path path(); }### Answer:
@Test public void path() { final String path = "a"; MatcherAssert.assertThat(new DirectoryBase(path).path(), Matchers.equalTo(Paths.get(path))); } |
### Question:
VerboseRegex implements Condition { @Override public final boolean applicable(String identity) { if (say[0]) { this.printer.println( String.format( "The following pattern will be used for classes filtering: %s", this.regexCondition.regex.pattern())); Arrays.fill(say, false); } return this.regexCondition.applicable(identity); } VerboseRegex(RegexCondition condition); VerboseRegex(RegexCondition regexCondition, PrintStream printer); @Override final boolean applicable(String identity); }### Answer:
@Test public void testIfMessageIsDisplayedOnce() { final ByteArrayOutputStream result = new ByteArrayOutputStream(); final VerboseRegex regex = new VerboseRegex(new RegexCondition("ddd"), new PrintStream(result)); regex.applicable("a"); regex.applicable("b"); MatcherAssert.assertThat( new String(result.toByteArray()), Matchers.is("The following pattern will be used for classes filtering: ddd\n")); } |
### Question:
DirectoryWithAutomaticCreation implements Directory { @Override public final void create() throws IOException { this.directory.create(); } DirectoryWithAutomaticCreation(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }### Answer:
@Test public void create() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.newFolder().toString(), "a"); new DirectoryWithAutomaticCreation(new DirectoryBase(path)).create(); MatcherAssert.assertThat("The directory wasn't created", path.exist()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.