method2testcases
stringlengths 118
3.08k
|
---|
### Question:
CryptoRequestBuilder extends AbstractStocksRequestBuilder<Quote, CryptoRequestBuilder> implements IEXCloudV1RestRequest<Quote> { @Override public RestRequest<Quote> build() { return RestRequestBuilder.<Quote>builder() .withPath("/crypto/{symbol}/quote") .addPathParam(SYMBOL_PARAM_NAME, getSymbol()).get() .withResponse(new GenericType<Quote>() {}) .build(); } @Override RestRequest<Quote> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final String symbol = "IBM"; final RestRequest<Quote> request = new CryptoRequestBuilder() .withSymbol(symbol) .build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/crypto/{symbol}/quote"); assertThat(request.getResponseType()).isEqualTo(new GenericType<Quote>() {}); assertThat(request.getPathParams()).containsExactly(entry("symbol", symbol)); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
DailySentimentRequestBuilder extends AbstractSentimentRequestBuilder<Sentiment, DailySentimentRequestBuilder> implements IEXCloudV1RestRequest<Sentiment> { @Override public RestRequest<Sentiment> build() { if (date != null) { return requestWithDate(); } else if (sentimentType != null) { return requestWithType(); } return request(); } DailySentimentRequestBuilder(); @Override RestRequest<Sentiment> build(); }### Answer:
@Test public void shouldSuccessfullyCreateTypeRequest() { final String symbol = "IBM"; final RestRequest<Sentiment> request = new DailySentimentRequestBuilder() .withSymbol(symbol) .build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/stock/{symbol}/sentiment/{type}"); assertThat(request.getResponseType()).isEqualTo(new GenericType<Sentiment>() {}); assertThat(request.getPathParams()).contains(entry("symbol", symbol), entry("type", "daily")); assertThat(request.getQueryParams()).isEmpty(); }
@Test public void shouldSuccessfullyCreateTypeAndDateRequest() { final String symbol = "IBM"; final RestRequest<Sentiment> request = new DailySentimentRequestBuilder() .withDate(LocalDate.of(2019, 5, 11)) .withSymbol(symbol) .build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/stock/{symbol}/sentiment/{type}/{date}"); assertThat(request.getResponseType()).isEqualTo(new GenericType<Sentiment>() {}); assertThat(request.getPathParams()).contains(entry("symbol", symbol), entry("type", "daily"), entry("date", "20190511")); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
SentimentRequestBuilder extends AbstractSentimentRequestBuilder<List<Sentiment>, SentimentRequestBuilder> implements IEXCloudV1RestRequest<List<Sentiment>> { @Override public RestRequest<List<Sentiment>> build() { if (date != null) { return requestWithDate(); } else if (sentimentType != null) { return requestWithType(); } return request(); } SentimentRequestBuilder withSentimentType(final SentimentType sentimentType); @Override RestRequest<List<Sentiment>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final String symbol = "IBM"; final RestRequest<List<Sentiment>> request = new SentimentRequestBuilder() .withSymbol(symbol) .build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/stock/{symbol}/sentiment"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<Sentiment>>() {}); assertThat(request.getPathParams()).containsExactly(entry("symbol", symbol)); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
MarketRequestBuilder extends AbstractRequestFilterBuilder<List<MarketVolume>, MarketRequestBuilder> implements IEXApiRestRequest<List<MarketVolume>>, IEXCloudV1RestRequest<List<MarketVolume>> { @Override public RestRequest<List<MarketVolume>> build() { return RestRequestBuilder.<List<MarketVolume>>builder() .withPath("/market").get() .withResponse(new GenericType<List<MarketVolume>>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<MarketVolume>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final RestRequest<List<MarketVolume>> request = new MarketRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/market"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<MarketVolume>>() {}); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
Logo implements Serializable { public String getUrl() { return url; } @JsonCreator Logo(@JsonProperty("url") final String url); String getUrl(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void constructor() { final String url = fixture.create(String.class); final Logo logo = new Logo(url); assertThat(logo.getUrl()).isEqualTo(url); } |
### Question:
RecordStatsRequestBuilder extends AbstractRequestFilterBuilder<RecordsStats, RecordStatsRequestBuilder> implements IEXApiRestRequest<RecordsStats>, IEXCloudV1RestRequest<RecordsStats> { @Override public RestRequest<RecordsStats> build() { return RestRequestBuilder.<RecordsStats>builder() .withPath("/stats/records").get() .withResponse(RecordsStats.class) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<RecordsStats> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequestWithYearMonthDate() { final RestRequest<RecordsStats> request = new RecordStatsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/stats/records"); assertThat(request.getResponseType()).isEqualTo(new GenericType<RecordsStats>() {}); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
RecentStatsRequestBuilder extends AbstractRequestFilterBuilder<List<RecentStats>, RecentStatsRequestBuilder> implements IEXApiRestRequest<List<RecentStats>>, IEXCloudV1RestRequest<List<RecentStats>> { @Override public RestRequest<List<RecentStats>> build() { return RestRequestBuilder.<List<RecentStats>>builder() .withPath("/stats/recent").get() .withResponse(new GenericType<List<RecentStats>>() { }) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<RecentStats>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequestWithYearMonthDate() { final RestRequest<List<RecentStats>> request = new RecentStatsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/stats/recent"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<RecentStats>>() {}); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
IntradayStatsRequestBuilder extends AbstractRequestFilterBuilder<IntradayStats, HistoricalStatsRequestBuilder> implements IEXApiRestRequest<IntradayStats>, IEXCloudV1RestRequest<IntradayStats> { @Override public RestRequest<IntradayStats> build() { return RestRequestBuilder.<IntradayStats>builder() .withPath("/stats/intraday").get() .withResponse(IntradayStats.class) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<IntradayStats> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequestWithYearMonthDate() { final RestRequest<IntradayStats> request = new IntradayStatsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/stats/intraday"); assertThat(request.getResponseType()).isEqualTo(new GenericType<IntradayStats>() {}); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
IEXNextDayExDateRequestBuilder extends AbstractDailyListRequestBuilder<List<IEXNextDayExDate>, IEXNextDayExDateRequestBuilder> implements IEXApiRestRequest<List<IEXNextDayExDate>> { @Override public RestRequest<List<IEXNextDayExDate>> build() { return RestRequestBuilder.<List<IEXNextDayExDate>>builder() .withPath("/ref-data/daily-list/next-day-ex-date/{date}") .addPathParam("date", getPeriod()).get() .withResponse(new GenericType<List<IEXNextDayExDate>>() { }) .build(); } @Override RestRequest<List<IEXNextDayExDate>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final LocalDate date = LocalDate.of(2017, 5, 5); final RestRequest<List<IEXNextDayExDate>> request = new IEXNextDayExDateRequestBuilder() .withDate(date) .build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/daily-list/next-day-ex-date/{date}"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<IEXNextDayExDate>>() {}); assertThat(request.getPathParams()).contains(entry("date", "20170505")); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
SymbolsRequestBuilder extends AbstractRequestFilterBuilder<List<ExchangeSymbol>, SymbolsRequestBuilder> implements IEXApiRestRequest<List<ExchangeSymbol>> { @Override public RestRequest<List<ExchangeSymbol>> build() { return RestRequestBuilder.<List<ExchangeSymbol>>builder() .withPath("/ref-data/symbols").get() .withResponse(new GenericType<List<ExchangeSymbol>>() { }) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<ExchangeSymbol>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final RestRequest<List<ExchangeSymbol>> request = new SymbolsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/symbols"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<ExchangeSymbol>>() {}); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
IEXDividendsRequestBuilder extends AbstractDailyListRequestBuilder<List<IEXDividends>, IEXDividendsRequestBuilder> implements IEXApiRestRequest<List<IEXDividends>> { @Override public RestRequest<List<IEXDividends>> build() { return RestRequestBuilder.<List<IEXDividends>>builder() .withPath("/ref-data/daily-list/dividends/{date}") .addPathParam("date", getPeriod()).get() .withResponse(new GenericType<List<IEXDividends>>() { }) .build(); } @Override RestRequest<List<IEXDividends>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final LocalDate date = LocalDate.of(2017, 5, 5); final RestRequest<List<IEXDividends>> request = new IEXDividendsRequestBuilder() .withDate(date) .build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/daily-list/dividends/{date}"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<IEXDividends>>() {}); assertThat(request.getPathParams()).contains(entry("date", "20170505")); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
IEXSymbolDirectoryRequestBuilder extends AbstractDailyListRequestBuilder<List<IEXSymbolDirectory>, IEXSymbolDirectoryRequestBuilder> implements IEXApiRestRequest<List<IEXSymbolDirectory>> { @Override public RestRequest<List<IEXSymbolDirectory>> build() { return RestRequestBuilder.<List<IEXSymbolDirectory>>builder() .withPath("/ref-data/daily-list/symbol-directory/{date}") .addPathParam("date", getPeriod()).get() .withResponse(new GenericType<List<IEXSymbolDirectory>>() { }) .build(); } @Override RestRequest<List<IEXSymbolDirectory>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final LocalDate date = LocalDate.of(2017, 5, 5); final RestRequest<List<IEXSymbolDirectory>> request = new IEXSymbolDirectoryRequestBuilder() .withDate(date) .build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/daily-list/symbol-directory/{date}"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<IEXSymbolDirectory>>() {}); assertThat(request.getPathParams()).contains(entry("date", "20170505")); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
IEXCorporateActionsRequestBuilder extends AbstractDailyListRequestBuilder<List<IEXCorporateActions>, IEXCorporateActionsRequestBuilder> implements IEXApiRestRequest<List<IEXCorporateActions>> { @Override public RestRequest<List<IEXCorporateActions>> build() { return RestRequestBuilder.<List<IEXCorporateActions>>builder() .withPath("/ref-data/daily-list/corporate-actions/{date}") .addPathParam("date", getPeriod()).get() .withResponse(new GenericType<List<IEXCorporateActions>>() { }) .build(); } @Override RestRequest<List<IEXCorporateActions>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final LocalDate date = LocalDate.of(2017, 5, 5); final RestRequest<List<IEXCorporateActions>> request = new IEXCorporateActionsRequestBuilder() .withDate(date) .build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/daily-list/corporate-actions/{date}"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<IEXCorporateActions>>() {}); assertThat(request.getPathParams()).contains(entry("date", "20170505")); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
AbstractDailyListRequestBuilder implements IRestRequestBuilder<R> { String getPeriod() { return sample ? "sample" : date == null ? "" : IEX_DATE_FORMATTER.format(date); } B withDate(final LocalDate date); B withSample(); }### Answer:
@Test public void shouldReturnEmptyString() { final IEXCorporateActionsRequestBuilder requestBuilder = new IEXCorporateActionsRequestBuilder(); final String period = requestBuilder.getPeriod(); assertThat(period).isEmpty(); } |
### Question:
OptionsSymbolsRequestBuilder extends AbstractRequestFilterBuilder<Map<String, List<String>>, OptionsSymbolsRequestBuilder> implements IEXCloudV1RestRequest<Map<String, List<String>>> { @Override public RestRequest<Map<String, List<String>>> build() { return RestRequestBuilder.<Map<String, List<String>>>builder() .withPath("/ref-data/options/symbols").get() .withResponse(new GenericType<Map<String, List<String>>>() { }) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<Map<String, List<String>>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final RestRequest<Map<String, List<String>>> request = new OptionsSymbolsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/options/symbols"); assertThat(request.getResponseType()).isEqualTo(new GenericType<Map<String, List<String>>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
FieldMetadata implements Serializable { public String getType() { return type; } @JsonCreator FieldMetadata(
@JsonProperty("type") final String type); String getType(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void constructor() { final String type = fixture.create(String.class); final FieldMetadata fieldMetadata = new FieldMetadata(type); assertThat(fieldMetadata.getType()).isEqualTo(type); } |
### Question:
DoubleGenerator extends RangeGenerator<Double> { public static DoubleGenerator getGridDoubleGenerator(Double start, Double end) { return new DoubleGenerator(start, end, DoubleGenerator::gridGen); } private DoubleGenerator(Double start,
Double end,
BiFunction<DoubleGenerator, Integer, List<Double>> function); @Override List<Double> expend(int size); static DoubleGenerator getGridDoubleGenerator(Double start, Double end); static DoubleGenerator getUniformDoubleGenerator(Double start, Double end); }### Answer:
@Test public void getGridDoubleGenerator() { DoubleGenerator dg = DoubleGenerator.getGridDoubleGenerator(0.0, 1.0); double[] expected = {0.0,0.2,0.4,0.6,0.8}; Assert.assertArrayEquals(expected, TestUtils.toArray(dg.expend(5)), 0.001); } |
### Question:
DoubleGenerator extends RangeGenerator<Double> { public static DoubleGenerator getUniformDoubleGenerator(Double start, Double end) { return new DoubleGenerator(start, end, DoubleGenerator::genUniform); } private DoubleGenerator(Double start,
Double end,
BiFunction<DoubleGenerator, Integer, List<Double>> function); @Override List<Double> expend(int size); static DoubleGenerator getGridDoubleGenerator(Double start, Double end); static DoubleGenerator getUniformDoubleGenerator(Double start, Double end); }### Answer:
@Test public void getUniformDoubleGenerator() { DoubleGenerator dg = DoubleGenerator.getUniformDoubleGenerator(0.0, 1.0); String joined = Joiner.on(",").join(dg.expend(5)); System.out.println(joined); } |
### Question:
Config implements Runnable { static Config getConfig(String[] args) { Config config = new Config(); CommandLine.run(config, System.err, args); return config; } @Override void run(); }### Answer:
@Test public void testCommand() { String[] args = {"","train","task","tt"}; Config config = Config.getConfig(args); Assert.assertEquals(config.isTrain, false); Assert.assertEquals(config.task, "tt"); } |
### Question:
User { public boolean isReady() { return getStatus() == Status.READY; } User(); User(long id, String email, String nickname); long getId(); void setId(long id); String getEmail(); void setEmail(String email); String getPassword(); void setPassword(String password); String getNickname(); void setNickname(String nickname); Status getStatus(); void setStatus(Status status); void gameStart(); void ready(); long getEnteredRoomId(); void setEnteredRoomId(long enteredRoomId); boolean matchPassword(User user); boolean isAbleToEnter(long id); @JsonIgnore boolean isLobby(); boolean isSameUser(String nickname); void enterLobby(); void enterRoom(long id); @Override String toString(); boolean isReady(); void toggleReady(); }### Answer:
@Test public void isReady() { User user = new User(); user.enterRoom(1); assertEquals(false, user.isReady()); } |
### Question:
UserClass implements Serializable { public void setPassword(String password) throws UserException { int MIN_PASSWORD_LENGTH = 6; int MAX_PASSWORD_LENGTH = 16; if((password != null && !password.isEmpty()) && (password.length() < MIN_PASSWORD_LENGTH || password.length() > MAX_PASSWORD_LENGTH)){ throw new UserException("A senha deve ter entre 6 e 16 caracteres"); }else if(password == null || password.isEmpty()){ throw new UserException("Preencha todos os campos!"); }else{ this.password = password; } } UserClass(); UserClass(String className, String institution, float cutOff, String password,
float addition, Integer sizeGroups); String getClassName(); void setClassName(String className); int getSizeGroups(); void setSizeGroups(int sizeGroups); String getInstitution(); void setInstitution(String institution); String getPassword(); void setPassword(String password); float getAddition(); void setAddition(float addition); float getCutOff(); void setCutOff(float cutOff); }### Answer:
@Test public void UserClass_Password(){ boolean isValid = false; UserClass userClass = new UserClass(); try { isValid = true; userClass.setPassword("nome"); } catch (UserException e) { isValid = false; e.printStackTrace(); } assertFalse(isValid); } |
### Question:
About { public int getShowImage(int position){ switch(position){ case 0: return R.drawable.trezentos_icon; case 1: return R.drawable.tedx; case 2: return R.drawable.about_youtube; case 3: return R.drawable.about_youtube; case 4: return R.drawable.documents; case 5: return R.drawable.about_record; default: return R.drawable.about_unb_tv; } } About(); About(String title, String subTitle); void setTitle(String title); String getTitle(); void setSubTitle(String subTitle); String getSubTitle(); int getShowImage(int position); }### Answer:
@Test public void shouldValidateAboutImage(){ About about = new About(); assertEquals(R.drawable.trezentos_icon, about.getShowImage(0)); assertEquals(R.drawable.tedx, about.getShowImage(1)); assertEquals(R.drawable.about_youtube, about.getShowImage(2)); assertEquals(R.drawable.about_youtube, about.getShowImage(3)); assertEquals(R.drawable.documents, about.getShowImage(4)); assertEquals(R.drawable.about_record, about.getShowImage(5)); assertEquals(R.drawable.about_unb_tv, about.getShowImage(6)); } |
### Question:
Student extends UserAccount { @Override public String toString(){ return "Aluno"; } Student(); @Override String toString(); String getStudentEmail(); void setStudentEmail(String studentEmail); Double getFirstGrade(); void setFirstGrade(Double firstGrade); Double getSecondGrade(); void setSecondGrade(Double secondGrade); }### Answer:
@Test public void shouldValidateToString(){ Student student = new Student(); assertEquals("Aluno", student.toString()); } |
### Question:
ScriptExtractor extends DefaultObjectPipe<Reader, ObjectReceiver<String>> { @Override public void process(final Reader reader) { try { Document document = Jsoup.parse(IOUtils.toString(reader)); Element firstScript = document.select("script").first(); getReceiver().process(firstScript.data()); } catch (IOException e) { e.printStackTrace(); } } @Override void process(final Reader reader); }### Answer:
@Test public void testShouldProcessRecordsFollowedbySeparator() { scriptExtractor.process(IN); verify(receiver).process(OUT); verifyNoMoreInteractions(receiver); } |
### Question:
Label { @Override public String toString() { return buffer.stringAt(0, RECORD_LABEL_LENGTH, Iso646Constants.CHARSET); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void toString_shouldReturnRecordLabel() { assertEquals(RECORD_LABEL, label.toString()); } |
### Question:
RecordBuilder { public void setRecordStatus(final char recordStatus) { require7BitAscii(recordStatus); label.setRecordStatus(recordStatus); } RecordBuilder(final RecordFormat recordFormat); void setCharset(final Charset charset); Charset getCharset(); void setRecordStatus(final char recordStatus); void setImplCodes(final char[] implCodes); void setImplCode(final int index, final char implCode); void setSystemChars(final char[] systemChars); void setSystemChar(final int index, final char systemChar); void setReservedChar(final char reservedChar); void appendIdentifierField(final String value); void appendIdentifierField(final char[] implDefinedPart,
final String value); void appendReferenceField(final char[] tag, final String value); void appendReferenceField(final char[] tag,
final char[] implDefinedPart, final String value); void startDataField(final char[] tag); void startDataField(final char[] tag, final char[] indicators); void startDataField(final char[] tag, final char[] indicators,
final char[] implDefinedPart); void endDataField(); void appendSubfield(final String value); void appendSubfield(final char[] identifier, final String value); byte[] build(); void reset(); @Override String toString(); }### Answer:
@Test(expected=IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionIfRecordStatusIsNot7BitAscii() { builder.setRecordStatus('\u00df'); }
@Test(expected=IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionIfRecordStatusIsInformationSeparator() { builder.setRecordStatus('\u001e'); } |
### Question:
RecordBuilder { public void setImplCodes(final char[] implCodes) { Require.notNull(implCodes); Require.that(implCodes.length == IMPL_CODES_LENGTH); require7BitAscii(implCodes); label.setImplCodes(implCodes); } RecordBuilder(final RecordFormat recordFormat); void setCharset(final Charset charset); Charset getCharset(); void setRecordStatus(final char recordStatus); void setImplCodes(final char[] implCodes); void setImplCode(final int index, final char implCode); void setSystemChars(final char[] systemChars); void setSystemChar(final int index, final char systemChar); void setReservedChar(final char reservedChar); void appendIdentifierField(final String value); void appendIdentifierField(final char[] implDefinedPart,
final String value); void appendReferenceField(final char[] tag, final String value); void appendReferenceField(final char[] tag,
final char[] implDefinedPart, final String value); void startDataField(final char[] tag); void startDataField(final char[] tag, final char[] indicators); void startDataField(final char[] tag, final char[] indicators,
final char[] implDefinedPart); void endDataField(); void appendSubfield(final String value); void appendSubfield(final char[] identifier, final String value); byte[] build(); void reset(); @Override String toString(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfLengthOfImplCodesIsLessThanFour() { builder.setImplCodes(asChars("123")); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfLengthOfImplCodesIsGreaterThanFour() { builder.setImplCodes(asChars("12345")); }
@Test(expected=IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionIfImplCodesAreNot7BitAscii() { builder.setImplCodes(asChars("12\u00df4")); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfImplCodesIsNull() { builder.setImplCodes(null); } |
### Question:
MarcXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void omitXmlDeclaration(boolean omitXmlDeclaration) { this.omitXmlDeclaration = omitXmlDeclaration; } MarcXmlEncoder(); void omitXmlDeclaration(boolean omitXmlDeclaration); void setXmlVersion(String xmlVersion); void setXmlEncoding(String xmlEncoding); void setFormatted(boolean formatted); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); }### Answer:
@Test public void doNotOmitXmlDeclaration() { encoder.omitXmlDeclaration(false); addOneRecord(encoder); encoder.closeStream(); String actual = resultCollector.toString(); assertTrue(actual.startsWith(XML_DECLARATION)); }
@Test public void omitXmlDeclaration() { encoder.omitXmlDeclaration(true); addOneRecord(encoder); encoder.closeStream(); String actual = resultCollector.toString(); assertTrue(actual.startsWith("<marc:collection")); assertTrue(actual.endsWith(XML_MARC_COLLECTION_END_TAG)); } |
### Question:
RecordBuilder { public void setSystemChar(final int index, final char systemChar) { Require.that(0 <= index && index < SYSTEM_CHARS_LENGTH); require7BitAscii(systemChar); label.setSystemChar(index, systemChar); } RecordBuilder(final RecordFormat recordFormat); void setCharset(final Charset charset); Charset getCharset(); void setRecordStatus(final char recordStatus); void setImplCodes(final char[] implCodes); void setImplCode(final int index, final char implCode); void setSystemChars(final char[] systemChars); void setSystemChar(final int index, final char systemChar); void setReservedChar(final char reservedChar); void appendIdentifierField(final String value); void appendIdentifierField(final char[] implDefinedPart,
final String value); void appendReferenceField(final char[] tag, final String value); void appendReferenceField(final char[] tag,
final char[] implDefinedPart, final String value); void startDataField(final char[] tag); void startDataField(final char[] tag, final char[] indicators); void startDataField(final char[] tag, final char[] indicators,
final char[] implDefinedPart); void endDataField(); void appendSubfield(final String value); void appendSubfield(final char[] identifier, final String value); byte[] build(); void reset(); @Override String toString(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfSystemCharIndexGreaterThan2() { builder.setSystemChar(3, '1'); } |
### Question:
RecordBuilder { public void setReservedChar(final char reservedChar) { require7BitAscii(reservedChar); label.setReservedChar(reservedChar); } RecordBuilder(final RecordFormat recordFormat); void setCharset(final Charset charset); Charset getCharset(); void setRecordStatus(final char recordStatus); void setImplCodes(final char[] implCodes); void setImplCode(final int index, final char implCode); void setSystemChars(final char[] systemChars); void setSystemChar(final int index, final char systemChar); void setReservedChar(final char reservedChar); void appendIdentifierField(final String value); void appendIdentifierField(final char[] implDefinedPart,
final String value); void appendReferenceField(final char[] tag, final String value); void appendReferenceField(final char[] tag,
final char[] implDefinedPart, final String value); void startDataField(final char[] tag); void startDataField(final char[] tag, final char[] indicators); void startDataField(final char[] tag, final char[] indicators,
final char[] implDefinedPart); void endDataField(); void appendSubfield(final String value); void appendSubfield(final char[] identifier, final String value); byte[] build(); void reset(); @Override String toString(); }### Answer:
@Test(expected=IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionIfReservedCharIsNot7BitAscii() { builder.setReservedChar('\u00df'); }
@Test(expected=IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionIfReservedCharIsInformationSeparator() { builder.setReservedChar('\u001d'); } |
### Question:
MarcXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setXmlVersion(String xmlVersion) { this.xmlVersion = xmlVersion; } MarcXmlEncoder(); void omitXmlDeclaration(boolean omitXmlDeclaration); void setXmlVersion(String xmlVersion); void setXmlEncoding(String xmlEncoding); void setFormatted(boolean formatted); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); }### Answer:
@Test public void setXmlVersion() { encoder.omitXmlDeclaration(false); encoder.setXmlVersion("1.1"); addOneRecord(encoder); encoder.closeStream(); String actual = resultCollector.toString(); assertTrue(actual.startsWith(XML_1_DECLARATION)); } |
### Question:
MarcXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setXmlEncoding(String xmlEncoding) { this.xmlEncoding = xmlEncoding; } MarcXmlEncoder(); void omitXmlDeclaration(boolean omitXmlDeclaration); void setXmlVersion(String xmlVersion); void setXmlEncoding(String xmlEncoding); void setFormatted(boolean formatted); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); }### Answer:
@Test public void setXmlEncoding() { encoder.omitXmlDeclaration(false); encoder.setXmlEncoding("UTF-16"); addOneRecord(encoder); encoder.closeStream(); String actual = resultCollector.toString(); assertTrue(actual.startsWith(XML_16_DECLARATION)); } |
### Question:
RecordBuilder { public void appendSubfield(final String value) { requireInDataField(); Require.notNull(value); fields.appendSubfield(defaultIdentifier, value); } RecordBuilder(final RecordFormat recordFormat); void setCharset(final Charset charset); Charset getCharset(); void setRecordStatus(final char recordStatus); void setImplCodes(final char[] implCodes); void setImplCode(final int index, final char implCode); void setSystemChars(final char[] systemChars); void setSystemChar(final int index, final char systemChar); void setReservedChar(final char reservedChar); void appendIdentifierField(final String value); void appendIdentifierField(final char[] implDefinedPart,
final String value); void appendReferenceField(final char[] tag, final String value); void appendReferenceField(final char[] tag,
final char[] implDefinedPart, final String value); void startDataField(final char[] tag); void startDataField(final char[] tag, final char[] indicators); void startDataField(final char[] tag, final char[] indicators,
final char[] implDefinedPart); void endDataField(); void appendSubfield(final String value); void appendSubfield(final char[] identifier, final String value); byte[] build(); void reset(); @Override String toString(); }### Answer:
@Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionIfAppendSubfieldIsNotCalledWithinAppendFieldSequence() { builder.appendSubfield(asChars("A"), "Value"); } |
### Question:
RecordBuilder { public void endDataField() { requireInDataField(); final int fieldEnd = fields.endField(); appendState = AppendState.DATA_FIELD; try { directory.addEntries(tag, implDefinedPart, fieldStart, fieldEnd); } catch (final FormatException e) { fields.undoLastField(); throw e; } } RecordBuilder(final RecordFormat recordFormat); void setCharset(final Charset charset); Charset getCharset(); void setRecordStatus(final char recordStatus); void setImplCodes(final char[] implCodes); void setImplCode(final int index, final char implCode); void setSystemChars(final char[] systemChars); void setSystemChar(final int index, final char systemChar); void setReservedChar(final char reservedChar); void appendIdentifierField(final String value); void appendIdentifierField(final char[] implDefinedPart,
final String value); void appendReferenceField(final char[] tag, final String value); void appendReferenceField(final char[] tag,
final char[] implDefinedPart, final String value); void startDataField(final char[] tag); void startDataField(final char[] tag, final char[] indicators); void startDataField(final char[] tag, final char[] indicators,
final char[] implDefinedPart); void endDataField(); void appendSubfield(final String value); void appendSubfield(final char[] identifier, final String value); byte[] build(); void reset(); @Override String toString(); }### Answer:
@Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionIfEndAppendFieldIsNotMatchedByStartAppendField() { builder.endDataField(); } |
### Question:
Histogram extends DefaultStreamReceiver { @Override public void resetStream() { histogram.clear(); } Histogram(); Histogram(final String countField); Map<String, Integer> getHistogram(); boolean isCountEntities(); void setCountEntities(final boolean countEntities); boolean isCountLiterals(); void setCountLiterals(final boolean countLiterals); String getCountField(); void setCountField(final String countField); @Override void startEntity(final String name); @Override void literal(final String name, final String value); @Override void resetStream(); }### Answer:
@Test public void testResetStream() { final Histogram histogram = new Histogram(); histogram.setCountEntities(true); assertTrue(histogram.isCountEntities()); assertFalse(histogram.isCountLiterals()); assertNull(histogram.getCountField()); histogram.startRecord(RECORD_ID); histogram.startEntity(ENTITIES[0]); histogram.endEntity(); histogram.endRecord(); final Map<String, Integer> expected = new HashMap<String, Integer>(); expected.put(ENTITIES[0], Integer.valueOf(1)); assertEquals(expected, histogram.getHistogram()); histogram.resetStream(); expected.clear(); assertEquals(expected, histogram.getHistogram()); } |
### Question:
UniformSampler extends
DefaultObjectPipe<T, ObjectReceiver<T>> { @Override public void process(final T obj) { assert !isClosed(); assert null!=obj; count += 1; if (sample.size() < sampleSize) { sample.add(obj); } else { final double p = sampleSize / (double)count; if (random.nextDouble() < p) { sample.set(random.nextInt(sampleSize), obj); } } } UniformSampler(final int sampleSize); UniformSampler(final String sampleSize); int getSampleSize(); void setSeed(final long seed); @Override void process(final T obj); }### Answer:
@Test public void testShouldEmitARandomSubsetOfTheInputObjects() { for(int i = 0; i < setSize; ++i) { sampler.process(Integer.toString(i)); } sampler.closeStream(); final InOrder ordered = inOrder(receiver); for(int i = 0; i < expected.length; ++i) { ordered.verify(receiver).process(expected[i]); } ordered.verify(receiver).closeStream(); } |
### Question:
EntityPathTracker extends DefaultStreamReceiver { public String getCurrentPath() { return currentPath.toString(); } String getCurrentPath(); String getCurrentPathWith(final String literalName); String getCurrentEntityName(); String getEntitySeparator(); void setEntitySeparator(final String entitySeparator); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void closeStream(); @Override void resetStream(); static final String DEFAULT_ENTITY_SEPARATOR; }### Answer:
@Test public void getCurrentPath_shouldReturnEmptyPathIfProcessingHasNotStarted() { assertTrue(pathTracker.getCurrentPath().isEmpty()); } |
### Question:
MarcXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setFormatted(boolean formatted) { this.formatted = formatted; } MarcXmlEncoder(); void omitXmlDeclaration(boolean omitXmlDeclaration); void setXmlVersion(String xmlVersion); void setXmlEncoding(String xmlEncoding); void setFormatted(boolean formatted); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); }### Answer:
@Test public void createARecordPrettyPrint() { encoder.setFormatted(true); addOneRecord(encoder); encoder.closeStream(); String expected = XML_DECLARATION + "\n" + XML_ROOT_OPEN + "\n" + "\t<marc:record>\n" + "\t\t<marc:controlfield tag=\"001\">92005291</marc:controlfield>\n" + "\t\t<marc:datafield tag=\"010\" ind1=\" \" ind2=\" \">\n" + "\t\t\t<marc:subfield code=\"a\">92005291</marc:subfield>\n" + "\t\t</marc:datafield>\n" + "\t</marc:record>\n" + XML_MARC_COLLECTION_END_TAG; String actual = resultCollector.toString(); assertEquals(expected, actual); } |
### Question:
EntityPathTracker extends DefaultStreamReceiver { public String getCurrentEntityName() { return entityStack.peek(); } String getCurrentPath(); String getCurrentPathWith(final String literalName); String getCurrentEntityName(); String getEntitySeparator(); void setEntitySeparator(final String entitySeparator); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void closeStream(); @Override void resetStream(); static final String DEFAULT_ENTITY_SEPARATOR; }### Answer:
@Test public void getCurrentEntityName_shouldReturnNullIfProcessingNotStarted() { assertNull(pathTracker.getCurrentEntityName()); } |
### Question:
NullFilter extends ForwardingStreamPipe { @Override public void literal(final String name, final String value) { if (value != null) { getReceiver().literal(name, value); } else if (replacement != null) { getReceiver().literal(name, replacement); } } void setReplacement(final String replacement); String getReplacement(); @Override void literal(final String name, final String value); }### Answer:
@Test public void shouldForwardAllEvents() { nullFilter.startRecord(RECORD_ID); nullFilter.startEntity(ENTITY_NAME); nullFilter.literal(LITERAL_NAME, LITERAL_VALUE); nullFilter.endEntity(); nullFilter.endRecord(); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); ordered.verify(receiver).startEntity(ENTITY_NAME); ordered.verify(receiver).literal(LITERAL_NAME, LITERAL_VALUE); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); }
@Test public void shouldDiscardNullValues() { nullFilter.startRecord(RECORD_ID); nullFilter.startEntity(ENTITY_NAME); nullFilter.literal(LITERAL_NAME, LITERAL_VALUE); nullFilter.literal(LITERAL_NAME, null); nullFilter.endEntity(); nullFilter.endRecord(); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); ordered.verify(receiver).startEntity(ENTITY_NAME); ordered.verify(receiver).literal(LITERAL_NAME, LITERAL_VALUE); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); } |
### Question:
DuplicateObjectFilter extends
DefaultObjectPipe<T, ObjectReceiver<T>> { @Override public void process(final T obj) { if (!obj.equals(lastObj)) { lastObj = obj; getReceiver().process(obj); } } @Override void process(final T obj); }### Answer:
@Test public void testShouldEliminateDuplicateObjects() { duplicateObjectFilter.process(OBJECT1); duplicateObjectFilter.process(OBJECT1); duplicateObjectFilter.process(OBJECT2); verify(receiver).process(OBJECT1); verify(receiver).process(OBJECT2); verifyNoMoreInteractions(receiver); } |
### Question:
ObjectToLiteral extends
DefaultObjectPipe<T, StreamReceiver> { @Override public void process(final T obj) { assert obj!=null; assert !isClosed(); getReceiver().startRecord(""); getReceiver().literal(literalName, obj.toString()); getReceiver().endRecord(); } void setLiteralName(final String literalName); String getLiteralName(); @Override void process(final T obj); static final String DEFAULT_LITERAL_NAME; }### Answer:
@Test public void testShouldUseObjectAsLiteralValue() { objectToLiteral.process(OBJ_DATA); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).literal(ObjectToLiteral.DEFAULT_LITERAL_NAME, OBJ_DATA); ordered.verify(receiver).endRecord(); } |
### Question:
ObjectTimer extends TimerBase<ObjectReceiver<T>> implements ObjectPipe<T, ObjectReceiver<T>> { @Override public void process(final T obj) { startMeasurement(); getReceiver().process(obj); stopMeasurement(); } ObjectTimer(); ObjectTimer(final String logPrefix); @Override void process(final T obj); }### Answer:
@Test public void testShouldMeasureExecutionTime() { objectTimer.process(""); objectTimer.process(""); objectTimer.process(""); objectTimer.process(""); objectTimer.closeStream(); } |
### Question:
FormetaEncoder extends
DefaultStreamPipe<ObjectReceiver<String>> { public void setStyle(final FormatterStyle formatterStyle) { this.style = formatterStyle; formatter = formatterStyle.createFormatter(); } FormatterStyle getStyle(); void setStyle(final FormatterStyle formatterStyle); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); }### Answer:
@Test public void testShouldOutputConciseRecordRepresentation() { encoder.setStyle(FormatterStyle.CONCISE); executeEvents(); verify(receiver).process(CONCISE_RECORD); }
@Test public void testShouldOutputVerboseRecordRepresentation() { encoder.setStyle(FormatterStyle.VERBOSE); executeEvents(); verify(receiver).process(VERBOSE_RECORD); }
@Test public void testShouldOutputMultilineRecordRepresentation() { encoder.setStyle(FormatterStyle.MULTILINE); executeEvents(); verify(receiver).process(MULTILINE_RECORD); } |
### Question:
MarcXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { @Override protected void onResetStream() { if (!atStreamStart) { writeFooter(); } sendAndClearData(); atStreamStart = true; } MarcXmlEncoder(); void omitXmlDeclaration(boolean omitXmlDeclaration); void setXmlVersion(String xmlVersion); void setXmlEncoding(String xmlEncoding); void setFormatted(boolean formatted); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); }### Answer:
@Test public void sendAndClearDataWhenOnResetStream() { encoder.onResetStream(); String expected = ""; String actual = resultCollector.toString(); assertEquals(expected, actual); } |
### Question:
FormetaDecoder extends
DefaultObjectPipe<String, StreamReceiver> { @Override public void process(final String record) { parser.parse(record); } FormetaDecoder(); @Override void process(final String record); }### Answer:
@Test public void testShouldProcessRecords() { decoder.process(RECORD); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("lit1", "value 1"); ordered.verify(receiver).startEntity(" ent1"); ordered.verify(receiver).literal("lit2", "value {x}"); ordered.verify(receiver).literal("lit\\3", "value 2 "); ordered.verify(receiver).endEntity(); ordered.verify(receiver).literal("lit4", "value '3'"); ordered.verify(receiver).endRecord(); } |
### Question:
TripleObjectWriter extends DefaultObjectReceiver<Triple> { @Override public void process(final Triple triple) { final Path filePath = buildFilePath(triple); ensureParentPathExists(filePath); try(final Writer writer = Files.newBufferedWriter(filePath, encoding)) { writer.write(triple.getObject()); } catch (final IOException e) { throw new MetafactureException(e); } } TripleObjectWriter(final String baseDir); void setEncoding(final String encoding); void setEncoding(final Charset encoding); String getEncoding(); @Override void process(final Triple triple); }### Answer:
@Test public void shouldWriteObjectOfTripleIntoFile() throws IOException { tripleObjectWriter.process(new Triple(SUBJECT1, PREDICATE, OBJECT1)); tripleObjectWriter.process(new Triple(SUBJECT2, PREDICATE, OBJECT2)); final Path file1 = baseDir.resolve(Paths.get(SUBJECT1, PREDICATE)); final Path file2 = baseDir.resolve(Paths.get(SUBJECT2, PREDICATE)); assertEquals(OBJECT1, readFileContents(file1)); assertEquals(OBJECT2, readFileContents(file2)); }
@Test public void shouldMapStructuredSubjectsToDirectories() throws IOException { tripleObjectWriter.process(new Triple(STRUCTURED_SUBJECT, PREDICATE, OBJECT1)); final Path file = baseDir.resolve(Paths.get(STRUCTURED_SUBJECT_A, STRUCTURED_SUBJECT_B, PREDICATE)); assertEquals(readFileContents(file), OBJECT1); } |
### Question:
TripleObjectRetriever extends DefaultObjectPipe<Triple, ObjectReceiver<Triple>> { @Override public void process(final Triple triple) { assert !isClosed(); if (triple.getObjectType() != ObjectType.STRING) { return; } final String objectValue = retrieveObjectValue(triple.getObject()); getReceiver().process(new Triple(triple.getSubject(), triple.getPredicate(), objectValue)); } void setDefaultEncoding(final String defaultEncoding); void setDefaultEncoding(final Charset defaultEncoding); String getDefaultEncoding(); @Override void process(final Triple triple); }### Answer:
@Test public void shouldReplaceObjectValueWithResourceContentRetrievedFromUrl() { tripleObjectRetriever.process(new Triple(SUBJECT, PREDICATE, objectUrl)); verify(receiver).process(new Triple(SUBJECT, PREDICATE, OBJECT_VALUE)); }
@Test public void shouldSkipTriplesWithObjectTypeEntity() { tripleObjectRetriever.process( new Triple(SUBJECT, PREDICATE, ENTITY, ObjectType.ENTITY)); verifyZeroInteractions(receiver); } |
### Question:
ObjectExceptionCatcher extends
DefaultObjectPipe<T, ObjectReceiver<T>> { @Override public void process(final T obj) { try { getReceiver().process(obj); } catch(final Exception e) { LOG.error("{}'{}' while processing object: {}", logPrefix, e.getMessage(), obj); if (logStackTrace) { final StringWriter stackTraceWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stackTraceWriter)); LOG.error("{}Stack Trace:\n{}", logPrefix, stackTraceWriter.toString()); } } } ObjectExceptionCatcher(); ObjectExceptionCatcher(final String logPrefix); void setLogPrefix(final String logPrefix); String getLogPrefix(); void setLogStackTrace(final boolean logStackTrace); boolean isLogStackTrace(); @Override void process(final T obj); }### Answer:
@Test public void shouldCatchException() { exceptionCatcher.process("data"); } |
### Question:
CharMap implements Map<Character, V> { @Override public V get(final Object key) { if (key instanceof Character) { final Character beite = (Character) key; return get(beite.charValue()); } return null; } @SuppressWarnings("unchecked") CharMap(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override V get(final Object key); V get(final char key); @Override V put(final Character key, final V value); void put(final char key, final V value); void put(final Entry<V>[] table, final char key, final V value); @Override V remove(final Object key); @Override void putAll(final Map<? extends Character, ? extends V> map); @Override void clear(); @Override Set<Character> keySet(); @Override Collection<V> values(); @Override Set<java.util.Map.Entry<Character, V>> entrySet(); }### Answer:
@Test public void testEmptyMap() { final Map<Character, Integer> map = new CharMap<Integer>(); for (byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; ++i) { assertNull(map.get(Byte.valueOf(i))); } } |
### Question:
XmlUtil { public static String escape(final String unescaped) { return escape(unescaped, true); } private XmlUtil(); static String nodeToString(final Node node); static String nodeToString(final Node node,
final boolean omitXMLDecl); static String nodeListToString(final NodeList nodes); static boolean isXmlMimeType(final String mimeType); static String escape(final String unescaped); static String escape(final String unescaped, final boolean escapeUnicode); }### Answer:
@Test public void escape_shouldEscapeXmlSpecialChars() { final String unescaped = "< > ' & \""; final String result = XmlUtil.escape(unescaped); assertEquals("< > ' & "", result); }
@Test public void escape_shouldNotEscapeAsciiChars() { final String unescaped ="Kafka"; final String result = XmlUtil.escape(unescaped); assertEquals("Kafka", result); }
@Test public void escape_shouldEscapeAllNonAsciiChars() { final String unescaped = "K\u00f8benhavn"; final String result = XmlUtil.escape(unescaped); assertEquals("København", result); }
@Test public void escape_shouldEscapeSurrogatePairsAsSingleEntity() { final String unescaped = "Smile: \ud83d\ude09"; final String result = XmlUtil.escape(unescaped); assertEquals("Smile: 😉", result); } |
### Question:
Require { public static <T> T notNull(final T object) { return notNull(object, "parameter must not be null"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); }### Answer:
@Test(expected = IllegalArgumentException.class) public void notNullShouldThrowIllegalArgumentExceptionIfArgIsNull() { Require.notNull(null); }
@Test public void notNullShouldReturnArgIfArgIsNotNull() { final Object obj = new Object(); assertSame(obj, Require.notNull(obj)); } |
### Question:
Require { public static int notNegative(final int value) { return notNegative(value, "parameter must not be negative"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); }### Answer:
@Test(expected = IllegalArgumentException.class) public void notNegativeShouldThrowIllegalArgumentExceptionIfArgIsNegative() { Require.notNegative(-1); }
@Test public void notNegativeShouldReturnArgIfArgIsNotNegative() { assertEquals(0, Require.notNegative(0)); } |
### Question:
Require { public static void that(final boolean condition) { that(condition, "parameter is not valid"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); }### Answer:
@Test(expected = IllegalArgumentException.class) public void thatShouldFailIfArgumentIsFalse() { Require.that(false); }
@Test public void thatShouldDoNothingIfArgumentIsTrue() { Require.that(true); } |
### Question:
Require { public static int validArrayIndex(final int index, final int arrayLength) { return validArrayIndex(index, arrayLength, "array index out of range"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); }### Answer:
@Test(expected = IndexOutOfBoundsException.class) public void validArrayIndexShouldThrowIndexOutOfBoundsExceptionIfIndexIsNegative() { Require.validArrayIndex(-1, 2); }
@Test(expected = IndexOutOfBoundsException.class) public void validArrayIndexShouldThrowIndexOutOfBoundsExceptionIfIndexIsGreaterThanArrayLength() { Require.validArrayIndex(2, 2); }
@Test public void validArrayIndexShouldDoNothingIfIndexIsWithinArrayBounds() { assertEquals(1, Require.validArrayIndex(1, 2)); } |
### Question:
Require { public static void validArraySlice(final int sliceFrom, final int sliceLength, final int arrayLength) { validArraySlice(sliceFrom, sliceLength, arrayLength, "array slice out of range"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); }### Answer:
@Test(expected = IndexOutOfBoundsException.class) public void validArraySliceShouldThrowIndexOutOfBoundsExceptionIfIndexIsNegative() { Require.validArraySlice(-1, 1, 2); }
@Test(expected = IndexOutOfBoundsException.class) public void validArraySliceShouldThrowIndexOutOfBoundsExceptionIfLengthIsNegative() { Require.validArraySlice(0, -1, 2); }
@Test(expected = IndexOutOfBoundsException.class) public void validArraySliceShouldThrowIndexOutOfBoundsExceptionIfIndexPlusLengthIsGreaterThanArrayLength() { Require.validArraySlice(1, 2, 2); }
@Test public void validArraySliceShouldDoNothingIfIndexAndLengthAreWithinArrayBounds() { Require.validArraySlice(0, 1, 2); } |
### Question:
StringUtil { public static char[] copyToBuffer(final String str, final char[] currentBuffer) { assert str != null; assert currentBuffer != null; assert currentBuffer.length > 0; final int strLen = str.length(); char[] buffer = currentBuffer; int bufferLen = buffer.length; while(strLen > bufferLen) { bufferLen *= 2; } if (bufferLen > buffer.length) { buffer = new char[bufferLen]; } str.getChars(0, strLen, buffer, 0); return buffer; } private StringUtil(); static O fallback(final O value, final O fallbackValue); static String format(final String format, final Map<String, String> variables); static String format(final String format, final String varStartIndicator, final String varEndIndicator,
final Map<String, String> variables); static String format(final String format, final boolean ignoreMissingVars,
final Map<String, String> variables); static String format(final String format, final String varStartIndicator, final String varEndIndicator,
final boolean ignoreMissingVars, final Map<String, String> variables); static char[] copyToBuffer(final String str, final char[] currentBuffer); static String repeatChars(final char ch, final int count); }### Answer:
@Test public void copyToBufferShouldResizeBufferIfNecessary() { final char[] buffer = new char[2]; final String str = STRING_WITH_10_CHARS; final char[] newBuffer = StringUtil.copyToBuffer(str, buffer); assertTrue(newBuffer.length >= str.length()); }
@Test public void copyToBufferShouldReturnBufferContainingTheStringData() { final int bufferLen = STRING_WITH_4_CHARS.length(); char[] buffer = new char[bufferLen]; final String str = STRING_WITH_4_CHARS; buffer = StringUtil.copyToBuffer(str, buffer); assertEquals(STRING_WITH_4_CHARS, String.valueOf(buffer, 0, bufferLen)); } |
### Question:
ResourceUtil { public static String readAll(InputStream inputStream, Charset encoding) throws IOException { try (Reader reader = new InputStreamReader(inputStream, encoding)) { return readAll(reader); } } private ResourceUtil(); static InputStream getStream(final String name); static InputStream getStream(final File file); static Reader getReader(final String name); static Reader getReader(final File file); static Reader getReader(final String name, final String encoding); static Reader getReader(final File file, final String encoding); static URL getUrl(final String name); static URL getUrl(final File file); static Properties loadProperties(final String location); static Properties loadProperties(final InputStream stream); static Properties loadProperties(final URL url); static String loadTextFile(final String location); static List<String> loadTextFile(final String location,
final List<String> list); static String readAll(InputStream inputStream, Charset encoding); static String readAll(Reader reader); }### Answer:
@Test public void readAll_shouldReturnEmptyStringIfStreamIsEmpty() throws IOException { final String result = ResourceUtil.readAll(new StringReader("")); assertTrue(result.isEmpty()); }
@Test public void readAll_shouldReadStreamThatFitsIntoOneBuffer() throws IOException { final String input = repeat("a", BUFFER_SIZE - 1); final String result = ResourceUtil.readAll(new StringReader(input)); assertEquals(input, result); }
@Test public void readAll_shouldReadStreamThatFitsExactlyIntoOneBuffer() throws IOException { final String input = repeat("b", BUFFER_SIZE); final String result = ResourceUtil.readAll(new StringReader(input)); assertEquals(input, result); }
@Test public void readAll_shouldReadStreamThatSpansMultipleBuffers() throws IOException { final String input = repeat("c", BUFFER_SIZE * 2 + 1); final String result = ResourceUtil.readAll(new StringReader(input)); assertEquals(input, result); } |
### Question:
NamedValue implements Comparable<NamedValue> { @Override public int compareTo(final NamedValue namedValue) { final int first = name.compareTo(namedValue.name); if (first == 0) { return value.compareTo(namedValue.value); } return first; } NamedValue(final String name, final String value); String getName(); String getValue(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(final NamedValue namedValue); @Override String toString(); }### Answer:
@Test public void testNamedValueCompare(){ final NamedValue namedValue1 = new NamedValue(SMALL, SMALL); final NamedValue namedValue2 = new NamedValue(SMALL, BIG); final NamedValue namedValue3 = new NamedValue(BIG, BIG); final NamedValue namedValue4 = new NamedValue(SMALL, SMALL); Assert.assertTrue(namedValue1.compareTo(namedValue4)==0); Assert.assertTrue(namedValue1.compareTo(namedValue2)==-1); Assert.assertTrue(namedValue2.compareTo(namedValue1)==1); Assert.assertTrue(namedValue2.compareTo(namedValue3)==-1); Assert.assertTrue(namedValue3.compareTo(namedValue2)==1); Assert.assertTrue(namedValue1.compareTo(namedValue4)==0); } |
### Question:
Splitter implements StreamPipe<StreamReceiver> { @Override public void resetStream() { buffer.clear(); metamorph.resetStream(); for (final StreamReceiver receiver: receiverMap.values()) { receiver.resetStream(); } } Splitter(final String morphDef); Splitter(final Reader morphDef); Splitter(final Metamorph metamorph); @Override R setReceiver(final R receiver); R setReceiver(final String key, final R receiver); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); @Override void resetStream(); @Override void closeStream(); }### Answer:
@Test public void shouldPassResetStreamToAllReceivers() { splitter.resetStream(); verify(receiver1).resetStream(); verify(receiver2).resetStream(); } |
### Question:
Splitter implements StreamPipe<StreamReceiver> { @Override public void closeStream() { buffer.clear(); metamorph.closeStream(); for (final StreamReceiver receiver: receiverMap.values()) { receiver.closeStream(); } } Splitter(final String morphDef); Splitter(final Reader morphDef); Splitter(final Metamorph metamorph); @Override R setReceiver(final R receiver); R setReceiver(final String key, final R receiver); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); @Override void resetStream(); @Override void closeStream(); }### Answer:
@Test public void shouldPassCloseStreamToAllReceivers() { splitter.closeStream(); verify(receiver1).closeStream(); verify(receiver2).closeStream(); } |
### Question:
NormalizeUTF8 extends AbstractSimpleStatelessFunction { @Override public String process(final String value) { return Normalizer.normalize(value, Form.NFC); } @Override String process(final String value); }### Answer:
@Test public void testProcess() { final NormalizeUTF8 normalize = new NormalizeUTF8(); assertEquals("Normalization incorrect", OUTPUT_STR, normalize.process(INPUT_STR)); } |
### Question:
ISBN extends AbstractSimpleStatelessFunction { @Override public String process(final String value) { String result = cleanse(value); final int size = result.length(); if (verifyCheckDigit && !isValid(result)) { result = errorString; } else if (!(size == ISBN10_SIZE || size == ISBN13_SIZE)) { result = errorString; } else { if (to10 && ISBN13_SIZE == size) { result = isbn13to10(result); } else if (to13 && ISBN10_SIZE == size) { result = isbn10to13(result); } } return result; } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); }### Answer:
@Test public void testProcess(){ final ISBN isbn = new ISBN(); isbn.setTo("isbn13"); assertEquals(ISBN13A, isbn.process(ISBN10A)); isbn.setTo("isbn10"); assertEquals(ISBN10A, isbn.process(ISBN13A)); isbn.setTo("cleanse"); assertEquals(ISBN10A, isbn.process(ISBN10A_DIRTY)); } |
### Question:
ISBN extends AbstractSimpleStatelessFunction { public static String isbn10to13(final String isbn) { if (isbn.length() != ISBN10_SIZE) { throw new IllegalArgumentException( "isbn must be 10 characters long"); } final String isbn13Data = "978" + isbn.substring(0, ISBN10_SIZE - 1); return isbn13Data + check13(isbn13Data); } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); }### Answer:
@Test public void testTo13() { assertEquals(ISBN13A, ISBN.isbn10to13(ISBN10A)); }
@Test(expected = IllegalArgumentException.class) public void testInvalidInputTo13() { ISBN.isbn10to13(ISBN_INCORRECT_SIZE3); } |
### Question:
ISBN extends AbstractSimpleStatelessFunction { public static String isbn13to10(final String isbn) { if (isbn.length() != ISBN13_SIZE) { throw new IllegalArgumentException( "isbn must be 13 characters long"); } final String isbn10Data = isbn.substring(3, 12); return isbn10Data + check10(isbn10Data); } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); }### Answer:
@Test public void testTo10() { assertEquals(ISBN10A,ISBN.isbn13to10(ISBN13A)); }
@Test(expected = IllegalArgumentException.class) public void testInvalidInputTo10() { ISBN.isbn13to10(ISBN_INCORRECT_SIZE2); } |
### Question:
ISBN extends AbstractSimpleStatelessFunction { public static String cleanse(final String isbn) { String normValue = isbn.replace('x', 'X'); normValue = DIRT_PATTERN.matcher(normValue).replaceAll(""); final Matcher matcher = ISBN_PATTERN.matcher(normValue); if (matcher.find()) { return matcher.group(); } return ""; } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); }### Answer:
@Test public void testCleanse() { assertEquals(ISBN10A,ISBN.cleanse(ISBN10A_DIRTY)); } |
### Question:
ISBN extends AbstractSimpleStatelessFunction { public static boolean isValid(final String isbn) { boolean result = false; if (isbn.length() == ISBN10_SIZE) { result = check10(isbn.substring(0, ISBN10_SIZE - 1)) == isbn .charAt(ISBN10_SIZE - 1); } else if (isbn.length() == ISBN13_SIZE) { result = check13(isbn.substring(0, ISBN13_SIZE - 1)) == isbn .charAt(ISBN13_SIZE - 1); } return result; } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); }### Answer:
@Test public void testIsValid() { assertFalse(ISBN.isValid(ISBN_INCORRECT_CHECK13)); assertFalse(ISBN.isValid(ISBN_INCORRECT_CHECK10)); assertFalse(ISBN.isValid(ISBN_INCORRECT_SIZE1)); assertFalse(ISBN.isValid(ISBN_INCORRECT_SIZE2)); assertFalse(ISBN.isValid(ISBN_INCORRECT_SIZE3)); assertTrue(ISBN.isValid(ISBN10B)); assertTrue(ISBN.isValid(ISBN10A)); assertTrue(ISBN.isValid(ISBN13A )); assertTrue(ISBN.isValid(ISBN.cleanse(ISBN10C_DIRTY))); assertTrue(ISBN.isValid(ISBN.cleanse(ISBN13D_DIRTY))); assertTrue(ISBN.isValid(ISBN.cleanse(ISBN10F_DIRTY))); } |
### Question:
CGXmlHandler extends DefaultXmlPipe<StreamReceiver> { @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) { if (!CGXML_NAMESPACE.equals(uri)) { return; } switch (localName) { case ROOT_TAG: verifyValidVersion(attributes); break; case RECORDS_TAG: break; case RECORD_TAG: emitStartRecord(attributes); break; case ENTITY_TAG: emitStartEntity(attributes); break; case LITERAL_TAG: emitLiteral(attributes); break; default: throw new FormatException("Unexpected element: " + localName); } } @Override void startElement(final String uri, final String localName,
final String qName, final Attributes attributes); @Override void endElement(final String uri, final String localName,
final String qName); static final String CGXML_NAMESPACE; }### Answer:
@Test(expected = FormatException.class) public void shouldThrowFormatExceptionIfVersionIsNot1() { attributes.addAttribute("", "version", "cgxml:version", "CDATA", "2.0"); cgXmlHandler.startElement(CGXML_NS, "cgxml", "cgxml:cgxml", attributes); }
@Test public void shouldEmitStartRecordWithEmptyIdIfIdAttributeIsMissing() { cgXmlHandler.startElement(CGXML_NS, "record", "cgxml:record", attributes); verify(receiver).startRecord(""); }
@Test(expected = FormatException.class) public void shouldThrowFormatExceptionEmptyNameAttributeIsMissing() { cgXmlHandler.startElement(CGXML_NS, "entity", "cgxml:entity", attributes); }
@Test(expected = FormatException.class) public void shouldThrowFormatExceptionIfLiteralNameAttributeIsMissing() { attributes.addAttribute("", "value", "cgxml:value", "CDATA", "l-val"); cgXmlHandler.startElement(CGXML_NS, "literal", "cgxml:literal", attributes); } |
### Question:
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { protected static void writeEscaped(final StringBuilder builder, final String str) { builder.append(XmlUtil.escape(str, false)); } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; }### Answer:
@Test public void shouldOnlyEscapeXmlReservedCharacters() { final StringBuilder builder = new StringBuilder(); SimpleXmlEncoder.writeEscaped(builder , "&<>'\" üäö"); assertEquals("&<>'" üäö", builder.toString()); } |
### Question:
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setSeparateRoots(final boolean separateRoots) { this.separateRoots = separateRoots; } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; }### Answer:
@Test public void shouldWrapEachRecordInRootTagIfSeparateRootsIsTrue() { simpleXmlEncoder.setSeparateRoots(true); emitTwoRecords(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record></records><?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record></records>", getResultXml()); }
@Test public void shouldWrapAllRecordsInOneRootTagtIfSeparateRootsIsFalse() { simpleXmlEncoder.setSeparateRoots(false); emitTwoRecords(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record><record><tag>value</tag></record></records>", getResultXml()); } |
### Question:
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setNamespaces(final Map<String, String> namespaces) { this.namespaces = namespaces; } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; }### Answer:
@Test public void shouldAddNamespaceToRootElement() { final Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("ns", "http: simpleXmlEncoder.setNamespaces(namespaces); emitEmptyRecord(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records xmlns:ns=\"http: getResultXml()); }
@Test public void shouldAddNamespaceWithEmptyKeyAsDefaultNamespaceToRootTag() { final Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("", "http: simpleXmlEncoder.setNamespaces(namespaces); emitEmptyRecord(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records xmlns=\"http: getResultXml()); } |
### Question:
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setNamespaceFile(final String file) { final Properties properties; try { properties = ResourceUtil.loadProperties(file); } catch (IOException e) { throw new MetafactureException("Failed to load namespaces list", e); } for (final Entry<Object, Object> entry : properties.entrySet()) { namespaces.put(entry.getKey().toString(), entry.getValue().toString()); } } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; }### Answer:
@Test public void shouldAddNamespaceWithEmptyKeyFromPropertiesFileAsDefaultNamespaceToRootTag() { simpleXmlEncoder.setNamespaceFile("org/metafacture/xml/SimpleXmlEncoderTest_namespaces.properties"); emitEmptyRecord(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records xmlns=\"http: getResultXml()); } |
### Question:
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setWriteRootTag(final boolean writeRootTag) { this.writeRootTag = writeRootTag; } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; }### Answer:
@Test public void shouldNotEmitRootTagIfWriteRootTagIsFalse() { simpleXmlEncoder.setWriteRootTag(false); emitEmptyRecord(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><record />", getResultXml()); } |
### Question:
LineRecorder implements ObjectPipe<String, ObjectReceiver<String>> { @Override public void process(final String line) { assert !isClosed(); if (line.matches(recordMarkerRegexp)) { getReceiver().process(record.toString()); record = new StringBuilder(SB_CAPACITY); } else record.append(line + "\n"); } void setRecordMarkerRegexp(final String regexp); @Override void process(final String line); @Override void resetStream(); @Override void closeStream(); @Override R setReceiver(R receiver); }### Answer:
@Test public void shouldEmitRecords() { lineRecorder.process(RECORD1_PART1); lineRecorder.process(RECORD1_PART2); lineRecorder.process(RECORD1_ENDMARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process( RECORD1_PART1 + LINE_SEPARATOR + RECORD1_PART2 + LINE_SEPARATOR); lineRecorder.process(RECORD2_PART1); lineRecorder.process(RECORD2_PART2); lineRecorder.process(RECORD2_ENDMARKER); ordered.verify(receiver).process( RECORD2_PART1 + LINE_SEPARATOR + RECORD2_PART2 + LINE_SEPARATOR); ordered.verifyNoMoreInteractions(); } |
### Question:
LineSplitter extends DefaultObjectPipe<String, ObjectReceiver<String>> { @Override public void process(final String lines) { assert !isClosed(); for (final String record : LINE_PATTERN.split(lines)) { getReceiver().process(record); } } @Override void process(final String lines); }### Answer:
@Test public void shouldSplitInputStringAtNewLines() { lineSplitter.process(PART1 + "\n" + PART2 + "\n" + PART3); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process(PART1); ordered.verify(receiver).process(PART2); ordered.verify(receiver).process(PART3); ordered.verifyNoMoreInteractions(); }
@Test public void shouldPassInputWithoutNewLinesUnchanged() { lineSplitter.process(PART1); verify(receiver).process(PART1); verifyNoMoreInteractions(receiver); }
@Test public void shouldOutputEmptyStringsForSequencesOfNewLines() { lineSplitter.process(PART1 + "\n\n" + PART2); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process(PART1); ordered.verify(receiver).process(""); ordered.verify(receiver).process(PART2); ordered.verifyNoMoreInteractions(); }
@Test public void shouldOutputEmptyStringForNewLinesAtStartOfTheInput() { lineSplitter.process("\n" + PART1); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process(""); ordered.verify(receiver).process(PART1); ordered.verifyNoMoreInteractions(); }
@Test public void shouldNotOutputEmptyStringForNewLinesAtEndOfTheInput() { lineSplitter.process(PART1 + "\n"); verify(receiver).process(PART1); verifyNoMoreInteractions(receiver); } |
### Question:
UnicodeNormalizer extends
DefaultObjectPipe<String, ObjectReceiver<String>> { @Override public void process(final String str) { assert null != str; assert !isClosed(); getReceiver().process(Normalizer.normalize(str, normalizationForm)); } void setNormalizationForm(final Normalizer.Form normalizationForm); Normalizer.Form getNormalizationForm(); @Override void process(final String str); static final Normalizer.Form DEFAULT_NORMALIZATION_FORM; }### Answer:
@Test public void testShouldReplaceDiacriticsWithPrecomposedChars() { normalizer.process(STRING_WITH_DIACRITICS); verify(receiver).process(STRING_WITH_PRECOMPOSED_CHARS); } |
### Question:
CsvDecoder extends DefaultObjectPipe<String, StreamReceiver> { @Override public void process(final String string) { assert !isClosed(); final String[] parts = parseCsv(string); if(hasHeader){ if(header.length==0){ header = parts; }else if(parts.length==header.length){ getReceiver().startRecord(String.valueOf(++count)); for (int i = 0; i < parts.length; ++i) { getReceiver().literal(header[i], parts[i]); } getReceiver().endRecord(); }else{ throw new IllegalArgumentException( String.format( "wrong number of columns (expected %s, was %s) in input line: %s", header.length, parts.length, string)); } }else{ getReceiver().startRecord(String.valueOf(++count)); for (int i = 0; i < parts.length; ++i) { getReceiver().literal(String.valueOf(i), parts[i]); } getReceiver().endRecord(); } } CsvDecoder(final String separator); CsvDecoder(final char separator); CsvDecoder(); @Override void process(final String string); void setHasHeader(final boolean hasHeader); void setSeparator(final String separator); }### Answer:
@Test public void testSimple() { decoder.process("a,b,c"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("h1", "a"); ordered.verify(receiver).literal("h2", "b"); ordered.verify(receiver).literal("h3", "c"); ordered.verify(receiver).endRecord(); }
@Test public void testQuoted() { decoder.process("a,\"b1,b2,b3\",c"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("h1", "a"); ordered.verify(receiver).literal("h2", "b1,b2,b3"); ordered.verify(receiver).literal("h3", "c"); ordered.verify(receiver).endRecord(); } |
### Question:
DirectoryEntry { char[] getTag() { assert currentPosition < directoryEnd; return buffer.charsAt(currentPosition, TAG_LENGTH); } DirectoryEntry(final Iso646ByteBuffer buffer, final RecordFormat recordFormat,
final int baseAddress); @Override String toString(); }### Answer:
@Test public void constructor_shouldSetFirstEntryAsCurrentEntry() { assertArrayEquals("001".toCharArray(), directoryEntry.getTag()); } |
### Question:
DirectoryEntry { boolean endOfDirectoryReached() { return currentPosition >= directoryEnd; } DirectoryEntry(final Iso646ByteBuffer buffer, final RecordFormat recordFormat,
final int baseAddress); @Override String toString(); }### Answer:
@Test public void endOfDirectoryReached_shouldReturnFalseIfNotAtEndOFDirectory() { assertFalse(directoryEntry.endOfDirectoryReached()); } |
### Question:
Iso646ByteBuffer { int getLength() { return byteArray.length; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); }### Answer:
@Test public void getLength_shouldReturnRecordLength() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(3, byteBuffer.getLength()); } |
### Question:
Iso646ByteBuffer { int getFreeSpace() { return byteArray.length - writePosition; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); }### Answer:
@Test public void getFreeSpace_shouldReturnBufferLengthIfNothingWasWritten() { byteBuffer = new Iso646ByteBuffer(5); assertEquals(5, byteBuffer.getFreeSpace()); } |
### Question:
RecordReader extends
DefaultObjectPipe<Reader, ObjectReceiver<String>> { @Override public void process(final Reader reader) { assert !isClosed(); try { boolean nothingRead = true; int size; while ((size = reader.read(buffer)) != -1) { nothingRead = false; int offset = 0; for (int i = 0; i < size; ++i) { if (buffer[i] == separator) { builder.append(buffer, offset, i - offset); offset = i + 1; emitRecord(); } } builder.append(buffer, offset, size - offset); } if (!nothingRead) { emitRecord(); } } catch (final IOException e) { throw new MetafactureException(e); } } void setSeparator(final String separator); void setSeparator(final char separator); char getSeparator(); void setSkipEmptyRecords(final boolean skipEmptyRecords); boolean getSkipEmptyRecords(); @Override void process(final Reader reader); static final char DEFAULT_SEPARATOR; }### Answer:
@Test public void testShouldUseGlobalSeparatorAsDefaultSeparator() { recordReader.process(new StringReader( RECORD1 + DEFAULT_SEPARATOR + RECORD2 + DEFAULT_SEPARATOR)); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process(RECORD1); ordered.verify(receiver).process(RECORD2); verifyNoMoreInteractions(receiver); } |
### Question:
Iso646ByteBuffer { String stringAt(final int fromIndex, final int length, final Charset charset) { return new String(byteArray, fromIndex, length, charset); } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); }### Answer:
@Test public void stringAt_shouldReturnEmptyStringIfLengthIsZero() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals("", byteBuffer.stringAt(0, 0, StandardCharsets.UTF_8)); } |
### Question:
Iso646ByteBuffer { char charAt(final int index) { return byteToChar(index); } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); }### Answer:
@Test public void charAt_shouldReturnCharacterAtIndexDecodedAsIso646() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals('T', byteBuffer.charAt(0)); }
@Test(expected = FormatException.class) public void charAt_shouldThrowFormatExceptionIfByteValueIsNotInIso646() { byteBuffer = new Iso646ByteBuffer(asBytes("ü")); byteBuffer.charAt(0); } |
### Question:
Iso646ByteBuffer { char[] charsAt(final int fromIndex, final int length) { assert length >= 0; assert 0 <= fromIndex && (fromIndex + length) <= byteArray.length; final char[] chars = new char[length]; for (int i = 0; i < length; ++i) { chars[i] = byteToChar(fromIndex + i); } return chars; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); }### Answer:
@Test public void charsAt_shouldReturnBytesAsCharacterArrayDecodedAsIso646() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux Tox")); assertArrayEquals("Tux".toCharArray(), byteBuffer.charsAt(0, 3)); }
@Test(expected = FormatException.class) public void charsAt_shouldThrowFormatExceptionIfByteValueIsNotInIso646() { byteBuffer = new Iso646ByteBuffer(asBytes("Tüx Tox")); byteBuffer.charsAt(0, 4); }
@Test public void charsAt_shouldReturnEmptyCharacterArrayIfLengthIsZero() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertArrayEquals(new char[0], byteBuffer.charsAt(0, 0)); } |
### Question:
Iso646ByteBuffer { byte byteAt(final int index) { return byteArray[index]; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); }### Answer:
@Test public void byteAt_shouldReturnByteAtIndex() { byteBuffer = new Iso646ByteBuffer(new byte[] { 0x01, 0x02 }); assertEquals(0x02, byteBuffer.byteAt(1)); } |
### Question:
Iso646ByteBuffer { int parseIntAt(final int index) { return byteToDigit(index); } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); }### Answer:
@Test public void parseIntAt_shouldReturnIntValueAtIndex() { byteBuffer = new Iso646ByteBuffer(asBytes("299")); assertEquals(2, byteBuffer.parseIntAt(0)); }
@Test(expected = NumberFormatException.class) public void parseIntAt_shouldThrowFormatExceptionIfNotADigit() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); byteBuffer.parseIntAt(0); }
@Test public void parseIntAt_shouldReturnIntValueForRange() { byteBuffer = new Iso646ByteBuffer(asBytes("299")); assertEquals(299, byteBuffer.parseIntAt(0, 3)); }
@Test public void parseIntAt_shouldReturnZeroIfLengthIsZero() { byteBuffer = new Iso646ByteBuffer(asBytes("123")); assertEquals(0, byteBuffer.parseIntAt(0, 0)); }
@Test(expected = NumberFormatException.class) public void parseIntAt_shouldThrowFormatExceptionIfNotANumber() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); byteBuffer.parseIntAt(0, 3); }
@Test(expected = NumberFormatException.class) public void parseIntAt_shouldThrowFormatExceptionIfNumberIsTooLarge() { byteBuffer = new Iso646ByteBuffer(asBytes("123456789123456789")); byteBuffer.parseIntAt(0, 18); } |
### Question:
FileOpener extends DefaultObjectPipe<String, ObjectReceiver<Reader>> { @Override public void process(final String file) { try { final InputStream fileStream = new FileInputStream(file); try { final InputStream decompressor = compression.createDecompressor(fileStream); try { final Reader reader = new InputStreamReader(new BOMInputStream( decompressor), encoding); getReceiver().process(reader); } catch (final IOException | MetafactureException e) { decompressor.close(); throw e; } } catch (final IOException | MetafactureException e) { fileStream.close(); throw e; } } catch (final IOException e) { throw new MetafactureException(e); } } String getEncoding(); void setEncoding(final String encoding); FileCompression getCompression(); void setCompression(final FileCompression compression); void setCompression(final String compression); @Override void process(final String file); }### Answer:
@Test public void testUtf8IsDefaultEncoding() throws IOException { assumeFalse("Default encoding is UTF-8: It is not possible to test whether " + "FileOpener sets the encoding to UTF-8 correctly.", StandardCharsets.UTF_8.equals(Charset.defaultCharset())); final File testFile = createTestFile(); final FileOpener opener = new FileOpener(); opener.setReceiver(receiver); opener.process(testFile.getAbsolutePath()); opener.closeStream(); verify(receiver).process(processedObject.capture()); assertEquals(DATA, ResourceUtil.readAll(processedObject.getValue())); } |
### Question:
Iso646ByteBuffer { @Override public String toString() { return stringAt(0, byteArray.length, Iso646Constants.CHARSET); } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); }### Answer:
@Test public void toString_shouldReturnBufferContentDecodedAsISO646() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux tüt")); assertEquals("Tux t" + ASCII_UNMAPPABLE_CHAR + ASCII_UNMAPPABLE_CHAR + "t", byteBuffer.toString()); } |
### Question:
Record { public String getRecordId() { if (recordIdFieldStart == RECORD_ID_MISSING) { return null; } final int dataStart = baseAddress + recordIdFieldStart; final int dataLength = buffer.distanceTo(DATA_SEPARATORS, dataStart); return buffer.stringAt(dataStart, dataLength, charset); } Record(final byte[] recordData); RecordFormat getRecordFormat(); char getRecordStatus(); char[] getImplCodes(); char[] getSystemChars(); char getReservedChar(); void setCharset(final Charset charset); Charset getCharset(); String getRecordId(); String getLabel(); void processFields(final FieldHandler fieldHandler); }### Answer:
@Test public void getIdentifier_shouldReturnRecordIdentifier() { final byte[] data = asBytes("00034SIMPL0000030SYS110R" + "00120\u001e" + "ID\u001e\u001d"); record = new Record(data); assertEquals("ID", record.getRecordId()); }
@Test public void getIdentifier_shouldReturnNullIfRecordHasNoIdentifier() { final byte[] data = asBytes("00034SIMPL0000030SYS110R" + "00220\u001e" + "XY\u001e\u001d"); record = new Record(data); assertNull(record.getRecordId()); } |
### Question:
Label { RecordFormat getRecordFormat() { return RecordFormat.create() .withIndicatorLength(getIndicatorLength()) .withIdentifierLength(getIdentifierLength()) .withFieldLengthLength(getFieldLengthLength()) .withFieldStartLength(getFieldStartLength()) .withImplDefinedPartLength(getImplDefinedPartLength()) .build(); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getRecordFormat_shouldReturnRecordFormatObject() { final RecordFormat recordFormat = label.getRecordFormat(); assertNotNull(recordFormat); final RecordFormat expectedFormat = RecordFormat.create() .withIndicatorLength(INDICATOR_LENGTH) .withIdentifierLength(IDENTIFIER_LENGTH) .withFieldStartLength(FIELD_START_LENGTH) .withFieldLengthLength(FIELD_LENGTH_LENGTH) .withImplDefinedPartLength(IMPL_DEFINED_PART_LENGTH) .build(); assertEquals(expectedFormat, recordFormat); } |
### Question:
Label { int getRecordLength() { return buffer.parseIntAt(RECORD_LENGTH_START, RECORD_LENGTH_LENGTH); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getRecordLength_shouldReturnRecordLength() { assertEquals(RECORD_LENGTH, label.getRecordLength()); } |
### Question:
Label { char getRecordStatus() { return buffer.charAt(RECORD_STATUS_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getRecordStatus_shouldReturnRecordStatus() { assertEquals(RECORD_STATUS, label.getRecordStatus()); } |
### Question:
Label { char[] getImplCodes() { return buffer.charsAt(IMPL_CODES_START, IMPL_CODES_LENGTH); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getImplCodes_shouldReturnImplCodes() { assertArrayEquals(IMPL_CODES, label.getImplCodes()); } |
### Question:
Label { int getIndicatorLength() { return buffer.parseIntAt(INDICATOR_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getIndicatorLength_shouldReturnIndicatorLength() { assertEquals(INDICATOR_LENGTH, label.getIndicatorLength()); } |
### Question:
Label { int getIdentifierLength() { return buffer.parseIntAt(IDENTIFIER_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getIdentifierLength_shouldReturnIdentifierLength() { assertEquals(IDENTIFIER_LENGTH, label.getIdentifierLength()); } |
### Question:
Label { int getBaseAddress() { return buffer.parseIntAt(BASE_ADDRESS_START, BASE_ADDRESS_LENGTH); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getBaseAddress_shouldReturnBaseAddress() { assertEquals(BASE_ADDRESS, label.getBaseAddress()); } |
### Question:
Label { char[] getSystemChars() { return buffer.charsAt(SYSTEM_CHARS_START, SYSTEM_CHARS_LENGTH); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getSystemChars_shouldReturnUserSystemChars() { assertArrayEquals(SYSTEM_CHARS, label.getSystemChars()); } |
### Question:
Label { int getFieldLengthLength() { return buffer.parseIntAt(FIELD_LENGTH_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getFieldLengthLength_shouldReturnFieldLengthLength() { assertEquals(FIELD_LENGTH_LENGTH, label.getFieldLengthLength()); } |
### Question:
Label { int getFieldStartLength() { return buffer.parseIntAt(FIELD_START_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void getFieldStartLength_shouldReturnFieldStartLength() { assertEquals(FIELD_START_LENGTH, label.getFieldStartLength()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.