method2testcases
stringlengths
118
3.08k
### Question: LicenseResolver { public static License read(final String license) { final String trimmedLicense = license.trim(); if (sLicenses.containsKey(trimmedLicense)) { return sLicenses.get(trimmedLicense); } else { throw new IllegalStateException(String.format("no such license available: %s, did you forget to register it?", trimmedLicense)); } } private LicenseResolver(); static void registerLicense(final License license); static License read(final String license); }### Answer: @Test(expected = IllegalStateException.class) public void testReadUnknownLicense() throws Exception { LicenseResolver.read(TEST_LICENSE_NAME); } @Test public void testReadKnownLicense() throws Exception { final License license = LicenseResolver.read("MIT License"); assertNotNull(license); assertEquals("MIT License", license.getName()); }
### Question: XPathRecordReader { public synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued) { addField0(xpath, name, multiValued, false, 0); return this; } XPathRecordReader(String forEachXpath); synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued); synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued, int flags); List<Map<String, Object>> getAllRecords(Reader r); void streamRecords(Reader r, Handler handler); static final int FLATTEN; }### Answer: @Test public void unsupported_Xpaths() { String xml = "<root><b><a x=\"a/b\" h=\"hello-A\"/> </b></root>"; XPathRecordReader rr=null; try { rr = new XPathRecordReader(" Assert.fail("A RuntimeException was expected: } catch (RuntimeException ex) { } try { rr.addField("bold" ,"b", false); Assert.fail("A RuntimeException was expected: 'b' xpaths must begin with '/'."); } catch (RuntimeException ex) { } }
### Question: EvaluatorBag { public static Evaluator getSqlEscapingEvaluator() { return new Evaluator() { public String evaluate(String expression, Context context) { List l = parseParams(expression, context.getVariableResolver()); if (l.size() != 1) { throw new DataImportHandlerException(SEVERE, "'escapeSql' must have at least one parameter "); } String s = l.get(0).toString(); return s.replaceAll("'", "''").replaceAll("\"", "\"\"").replaceAll("\\\\", "\\\\\\\\"); } }; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }### Answer: @Test public void testGetSqlEscapingEvaluator() { Evaluator sqlEscaper = EvaluatorBag.getSqlEscapingEvaluator(); runTests(sqlTests, sqlEscaper); }
### Question: EvaluatorBag { public static Evaluator getUrlEvaluator() { return new Evaluator() { public String evaluate(String expression, Context context) { List l = parseParams(expression, context.getVariableResolver()); if (l.size() != 1) { throw new DataImportHandlerException(SEVERE, "'encodeUrl' must have at least one parameter "); } String s = l.get(0).toString(); try { return URLEncoder.encode(s.toString(), "UTF-8"); } catch (Exception e) { wrapAndThrow(SEVERE, e, "Unable to encode expression: " + expression + " with value: " + s); return null; } } }; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }### Answer: @Test public void testGetUrlEvaluator() throws Exception { Evaluator urlEvaluator = EvaluatorBag.getUrlEvaluator(); runTests(urlTests, urlEvaluator); }
### Question: DocBuilder { @SuppressWarnings("unchecked") static Class loadClass(String name, SolrCore core) throws ClassNotFoundException { try { return core != null ? core.getResourceLoader().findClass(name) : Class.forName(name); } catch (Exception e) { try { String n = DocBuilder.class.getPackage().getName() + "." + name; return core != null ? core.getResourceLoader().findClass(n) : Class.forName(n); } catch (Exception e1) { throw new ClassNotFoundException("Unable to load " + name + " or " + DocBuilder.class.getPackage().getName() + "." + name, e); } } } DocBuilder(DataImporter dataImporter, SolrWriter writer, DataImporter.RequestParams reqParams); VariableResolverImpl getVariableResolver(); @SuppressWarnings("unchecked") void execute(); @SuppressWarnings("unchecked") void addStatusMessage(String msg); @SuppressWarnings("unchecked") Set<Map<String, Object>> collectDelta(DataConfig.Entity entity, VariableResolverImpl resolver, Set<Map<String, Object>> deletedRows); void abort(); public Statistics importStatistics; static final String TIME_ELAPSED; static final String LAST_INDEX_TIME; static final String INDEX_START_TIME; }### Answer: @Test public void loadClass() throws Exception { Class clz = DocBuilder.loadClass("RegexTransformer", null); Assert.assertNotNull(clz); }
### Question: EntityProcessorBase extends EntityProcessor { public void init(Context context) { rowIterator = null; this.context = context; if (isFirstInit) { firstInit(context); } query = null; } void init(Context context); Map<String, Object> nextModifiedRowKey(); Map<String, Object> nextDeletedRowKey(); Map<String, Object> nextModifiedParentRowKey(); Map<String, Object> nextRow(); void destroy(); static final String TRANSFORMER; static final String TRANSFORM_ROW; static final String ON_ERROR; static final String ABORT; static final String CONTINUE; static final String SKIP; static final String SKIP_DOC; static final String CACHE_KEY; static final String CACHE_LOOKUP; }### Answer: @Test public void multiTransformer() { List<Map<String, String>> fields = new ArrayList<Map<String, String>>(); Map<String, String> entity = new HashMap<String, String>(); entity.put("transformer", T1.class.getName() + "," + T2.class.getName() + "," + T3.class.getName()); fields.add(TestRegexTransformer.getField("A", null, null, null, null)); fields.add(TestRegexTransformer.getField("B", null, null, null, null)); Context context = AbstractDataImportHandlerTestCase.getContext(null, null, new MockDataSource(), Context.FULL_DUMP, fields, entity); Map<String, Object> src = new HashMap<String, Object>(); src.put("A", "NA"); src.put("B", "NA"); EntityProcessorWrapper sep = new EntityProcessorWrapper(new SqlEntityProcessor(), null); sep.init(context); Map<String, Object> res = sep.applyTransformer(src); Assert.assertNotNull(res.get("T1")); Assert.assertNotNull(res.get("T2")); Assert.assertNotNull(res.get("T3")); }
### Question: MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { private int compare(String a, String b) { if (a != null && b != null) { return a.compareTo(b); } if (a == null) { if (b == null) { return 0; } return -1; } return 1; } MetaLocale(); MetaLocale(String language, String script, String territory, String variant); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testCompare() { MetaLocale meta1 = new MetaLocale(null, "Latn", null, null); MetaLocale meta2 = new MetaLocale(null, "Grek", null, null); assertEquals(meta1.compareTo(meta2), 5); assertEquals(meta2.compareTo(meta1), -5); meta2 = new MetaLocale("en", "Latn", null, null); assertEquals(meta1.compareTo(meta2), -1); assertEquals(meta2.compareTo(meta1), 1); }
### Question: MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { @Override public boolean equals(Object obj) { if (obj instanceof MetaLocale) { MetaLocale other = (MetaLocale) obj; return Arrays.equals(fields, other.fields); } return false; } MetaLocale(); MetaLocale(String language, String script, String territory, String variant); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testEquals() { MetaLocale meta1 = new MetaLocale(null, "Latn", null, null); MetaLocale meta2 = new MetaLocale(null, "Latn", null, null); assertEquals(meta1, meta2); assertEquals(meta1.hashCode(), meta2.hashCode()); meta2 = new MetaLocale("und", "Latn", null, null); assertEquals(meta1, meta2); assertEquals(meta1.hashCode(), meta2.hashCode()); meta2 = new MetaLocale("en", "Latn", null, null); assertNotEquals(meta1, meta2); assertNotEquals(meta1.hashCode(), meta2.hashCode()); }
### Question: UnitFactorMap { public UnitCategory getUnitCategory() { return category; } UnitFactorMap(UnitCategory category); private UnitFactorMap(UnitCategory category, Map<Unit, Map<Unit, UnitFactor>> factors); UnitCategory getUnitCategory(); UnitValue convert(UnitValue value, Unit to); UnitValue convert(UnitValue value, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }### Answer: @Test public void testBasics() { assertEquals(UnitCategory.ANGLE, new UnitFactorMap(UnitCategory.ANGLE).getUnitCategory()); }
### Question: UnitFactorMap { public void sortUnits(Unit[] units) { Arrays.sort(units, (a, b) -> { Integer ia = unitOrder.get(a); Integer ib = unitOrder.get(b); if (ia == null) { return 1; } if (ib == null) { return -1; } return Integer.compare(ia, ib); }); } UnitFactorMap(UnitCategory category); private UnitFactorMap(UnitCategory category, Map<Unit, Map<Unit, UnitFactor>> factors); UnitCategory getUnitCategory(); UnitValue convert(UnitValue value, Unit to); UnitValue convert(UnitValue value, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }### Answer: @Test public void testSortUnits() { Unit[] units = new Unit[] { Unit.KILOMETER, Unit.NANOMETER, Unit.MILE, Unit.INCH, Unit.LIGHT_YEAR }; UnitFactors.LENGTH.sortUnits(units); Unit[] expected = new Unit[] { Unit.LIGHT_YEAR, Unit.MILE, Unit.KILOMETER, Unit.INCH, Unit.NANOMETER }; assertEquals(units, expected); units = new Unit[] { Unit.AMPERE, Unit.INCH, Unit.BUSHEL, Unit.MILE }; UnitFactors.LENGTH.sortUnits(units); expected = new Unit[] { Unit.MILE, Unit.INCH, Unit.AMPERE, Unit.BUSHEL }; assertEquals(units, expected); }
### Question: UnitFactorMap { public String dump(Unit unit) { StringBuilder buf = new StringBuilder(); buf.append(unit).append(":\n"); Map<Unit, UnitFactor> map = factors.get(unit); for (Unit base : map.keySet()) { UnitFactor factor = map.get(base); buf.append(" ").append(factor).append(" "); buf.append(factor.rational().compute(RoundingMode.HALF_EVEN).toPlainString()).append('\n'); } return buf.toString(); } UnitFactorMap(UnitCategory category); private UnitFactorMap(UnitCategory category, Map<Unit, Map<Unit, UnitFactor>> factors); UnitCategory getUnitCategory(); UnitValue convert(UnitValue value, Unit to); UnitValue convert(UnitValue value, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }### Answer: @Test public void testDumpMapping() { String factors = UnitFactors.LENGTH.dump(Unit.INCH); assertTrue(factors.contains("Factor(2.54, CENTIMETER)")); assertTrue(factors.contains("Factor(1 / 12, FOOT)")); }
### Question: UnitFactorSet { public List<UnitValue> factors() { return factors; } UnitFactorSet(Unit base, UnitFactorMap factorMap, Unit...units); UnitFactorSet(UnitFactorMap factorMap, Unit...units); private UnitFactorSet(Unit unitBase, boolean forceBase, UnitFactorMap factorMap, Unit...units); Unit base(); List<UnitValue> factors(); }### Answer: @Test public void testDurationFactors() { UnitFactorSet set = new UnitFactorSet(UnitFactors.DURATION, Unit.YEAR, Unit.DAY, Unit.MONTH); assertEquals(set.factors(), Arrays.asList( new UnitValue("365.2425", Unit.YEAR), new UnitValue("30.436875", Unit.MONTH), new UnitValue("1", Unit.DAY) )); }
### Question: DigitBuffer implements CharSequence { @Override public DigitBuffer subSequence(int start, int end) { start = clamp(start, 0, size - 1); end = clamp(end, start, size - 1); int sz = end - start; char[] newbuf = new char[16 + sz]; System.arraycopy(buf, start, newbuf, 0, sz); return new DigitBuffer(newbuf, sz); } DigitBuffer(); DigitBuffer(int capacity); private DigitBuffer(char[] buf, int size); void reset(); @Override int length(); @Override DigitBuffer subSequence(int start, int end); @Override char charAt(int i); int capacity(); char first(); char last(); DigitBuffer append(String s); void append(DigitBuffer other); DigitBuffer append(char ch); void appendTo(StringBuilder dest); void reverse(int start); @Override String toString(); }### Answer: @Test public void testSubsequence() { DigitBuffer buf = new DigitBuffer(); for (int i = 0; i < 10; i++) { char ch = (char)('a' + i); buf.append(ch); } assertEquals(buf.length(), 10); DigitBuffer sub = buf.subSequence(2, 7); assertEquals(sub.length(), 5); assertEquals(sub.toString(), "cdefg"); sub = buf.subSequence(2, 2); assertEquals(sub.length(), 0); assertEquals(sub.toString(), ""); sub = buf.subSequence(-1, 5); assertEquals(sub.length(), 5); assertEquals(sub.toString(), "abcde"); sub = buf.subSequence(2, 20); assertEquals(sub.length(), 7); assertEquals(sub.toString(), "cdefghi"); sub = buf.subSequence(7, 2); assertEquals(sub.length(), 0); assertEquals(sub.toString(), ""); }
### Question: NumberFormattingUtils { public static int integerDigits(BigDecimal n) { return n.precision() - n.scale(); } static int integerDigits(BigDecimal n); static BigDecimal setup( BigDecimal n, // number to be formatted NumberRoundMode roundMode, // rounding mode NumberFormatMode formatMode, // formatting mode (significant digits, etc) int minIntDigits, // maximum integer digits to emit int maxFracDigits, // maximum fractional digits to emit int minFracDigits, // minimum fractional digits to emit int maxSigDigits, // maximum significant digits to emit int minSigDigits); static void format( BigDecimal n, DigitBuffer buf, NumberFormatterParams params, boolean currencyMode, boolean grouping, int minIntDigits, int primaryGroupingSize, int secondaryGroupingSize); }### Answer: @Test public void testIntegerDigits() { for (int i = 1; i < 10; i++) { intDigits(num("12345", i), 5); intDigits(num("0.12345", i), 0); intDigits(num("12345.12345", i), 5); } }
### Question: MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { public String variant() { return getField(VARIANT, ""); } MetaLocale(); MetaLocale(String language, String script, String territory, String variant); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testVariant() { MetaLocale meta = new MetaLocale("en", null, "US", "POSIX"); assertEquals(meta.compact(), "en-US-POSIX"); assertEquals(meta.expanded(), "en-Zzzz-US-POSIX"); }
### Question: NumberPattern { public Format format() { return format == null ? DEFAULT_FORMAT : format; } protected NumberPattern(String pattern, List<Node> parsed, Format format); String pattern(); List<Node> parsed(); Format format(); String render(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testDecimalStandard() { assertPattern("-#,##0.###", MINUS, format(3, 0, 1, 3, 0)); assertPattern("#,##,##0.###", format(3, 2, 1, 3, 0)); assertPattern("-#0.######", MINUS, format(0, 0, 1, 6, 0)); } @Test public void testDecimalPercent() { assertPattern("#,##0%", format(3, 0, 1, 0, 0), PERCENT); assertPattern("#,##0\u00a0%", format(3, 0, 1, 0, 0), text(NBSP), PERCENT); assertPattern("#,##,##0%", format(3, 2, 1, 0, 0), PERCENT); assertPattern("-%#,##0", MINUS, PERCENT, format(3, 0, 1, 0, 0)); assertPattern("%\u00a0#,##0", PERCENT, text(NBSP), format(3, 0, 1, 0, 0)); } @Test public void testDecimalLong() { assertPattern("0 billion", format(0, 0, 1, 0, 0), text(" billion")); assertPattern("000 thousand", format(0, 0, 3, 0, 0), text(" thousand")); }
### Question: LanguageMatcher { public Match match(String desiredRaw) { return matchImpl(parse(desiredRaw), DEFAULT_THRESHOLD); } LanguageMatcher(String supportedLocales); LanguageMatcher(List<String> supportedLocales); Match match(String desiredRaw); Match match(String desiredRaw, int threshold); Match match(List<String> desired); Match match(List<String> desired, int threshold); List<Match> matches(String desiredRaw); List<Match> matches(String desiredRaw, int threshold); List<Match> matches(List<String> desired); List<Match> matches(List<String> desired, int threshold); }### Answer: @Test public void testCases() throws IOException { for (Case c : load()) { match(c.supported, c.desired, c.result); } } @Test public void testBasic() { match("en-US fr-FR de-DE es-ES", "zh ar de", "de-DE"); } @Test public void testList() { match(asList("en", "ar", "zh", "es"), asList("no", "he", "zh", "es"), "zh"); match(asList("en_US", "fr_FR", "und-DE"), asList("zh", "de"), "und-DE"); match(asList("en ar", "de es fr"), asList("no he", "es"), "es"); }
### Question: FileInfosPresenter implements FileInfosContract.Presenter { @Override public void loadFileInfos() { mFileInfosRepository .listFileInfos(mDirectory) .observeOn(mSchedulerProvider.ui()) .subscribe(new Action1<List<FileInfo>>() { @Override public void call(List<FileInfo> fileInfos) { if (fileInfos.isEmpty()) { mView.showNoFileInfos(); } else { mView.showFileInfos(fileInfos); } } }); } FileInfosPresenter(@NonNull FileInfo directory, @NonNull BaseSchedulerProvider schedulerProvider, @NonNull FileInfosContract.View view, @NonNull FileInfosRepository fileInfosRepository); @Override void subscribe(); @Override void unsubscribe(); @Override void loadFileInfos(); }### Answer: @Test public void loadFileInfos_success() throws Exception { setAvailableFileInfos(mMockFileInfosRepository); mFileInfosPresenter.loadFileInfos(); Mockito.verify(mMockView, Mockito.times(1)).showFileInfos(Mockito.anyListOf(FileInfo.class)); }
### Question: UserServiceImpl implements UserService { @Override public void create(User user) { User existing = userRepository.findByUsername(user.getUsername()); Assert.isNull(existing, "user already exist: " + user.getUsername()); String hash = encoder.encode(user.getPassword()); user.setPassword(hash); user.setEnabled(true); user = userRepository.save(user); UserRole userRole = new UserRole(user.getId(), UserUtility.ROLE_USER); userRoleRepository.save(userRole); logger.info("new user has been created {}", user.getUsername()); } @Override void create(User user); }### Answer: @Test public void shouldFailWhenUserIsNotFound() throws Exception { doReturn(null).when(userRepository).findByUsername(anyString()); try { final User user = new User("imrenagi", "imrenagi", "imre"); userService.create(user); fail(); } catch (Exception e) { } } @Test public void shouldSaveNewUserWithUserRole() { final User user = new User("imrenagi", "imrenagi", "imre", "nagi"); user.setId(1L); doReturn(null).when(userRepository).findByUsername(user.getUsername()); doReturn(user).when(userRepository).save(any(User.class)); userService.create(user); verify(userRepository, times(1)).save(any(User.class)); verify(userRoleRepository, times(1)).save(any(UserRole.class)); }
### Question: MysqlUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userRepository.findByUsername(s); log.info("user is found! -> " + user.getUsername()); if (user == null) { log.info("user is not found!"); throw new UsernameNotFoundException(s); } return user; } @Override UserDetails loadUserByUsername(String s); }### Answer: @Test public void shouldReturnUserDetailWhenAUserIsFound() throws Exception { final User user = new User("imrenagi", "1234", "imre", "nagi"); doReturn(user).when(repository).findByUsername(user.getUsername()); UserDetails found = userDetailsService.loadUserByUsername(user.getUsername()); assertEquals(user.getUsername(), found.getUsername()); assertEquals(user.getPassword(), found.getPassword()); verify(repository, times(1)).findByUsername(user.getUsername()); } @Test public void shouldFailWhenUserIsNotFound() throws Exception { doReturn(null).when(repository).findByUsername(anyString()); try { userDetailsService.loadUserByUsername(anyString()); fail(); } catch (Exception e) { } }
### Question: AccountServiceImpl implements AccountService { @Override public Account findByUserName(String username) { Assert.hasLength(username); return repository.findByUsername(username); } @Override Account findByUserName(String username); @Override Account findByEmail(String email); @Override Account create(User user); @Override List<Account> findAll(); }### Answer: @Test public void shouldFindByUserName() { final Account account = new Account(); account.setUsername("test"); doReturn(account).when(repository).findByUsername(account.getUsername()); Account found = accountService.findByUserName(account.getUsername()); assertEquals(account, found); verify(repository, times(1)).findByUsername(account.getUsername()); } @Test(expected = IllegalArgumentException.class) public void shouldFailFindByUserNameForEmptyUsername() { accountService.findByUserName(""); }
### Question: AccountServiceImpl implements AccountService { @Override public Account findByEmail(String email) { Assert.hasLength(email); return repository.findByEmail(email); } @Override Account findByUserName(String username); @Override Account findByEmail(String email); @Override Account create(User user); @Override List<Account> findAll(); }### Answer: @Test public void shouldFindByEmail() { final Account account = new Account(); account.setUsername("imrenagi"); account.setEmail("[email protected]"); doReturn(account).when(repository).findByEmail(account.getEmail()); Account found = accountService.findByEmail(account.getEmail()); assertEquals(account, found); verify(repository, times(1)).findByEmail(account.getEmail()); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenFindByEmptyEmail() { accountService.findByEmail(""); }
### Question: BigFontGenerator { public String convert(String text, int position) { HashMap<Character, String> hashMap = fonts.get(position); ArrayList<String> chars = new ArrayList<>(); for (int i = 0; i < text.length(); i++) { String s = hashMap.get(Character.toUpperCase(text.charAt(i))); if (s == null) { throw new UnsupportedOperationException("Invalid character " + text.charAt(i)); } chars.add(s); } StringBuilder result = new StringBuilder(); String[][] maps = new String[chars.size()][chars.get(0).split("\\n").length]; for (int i = 0; i < chars.size(); i++) { String str = chars.get(i); maps[i] = str.split("\\r?\\n"); } for (int j = 0; j < maps[0].length; j++) { for (int i = 0; i < chars.size(); i++) { result.append(maps[i][j]); } if (j != maps[0].length - 1) { result.append("\n"); } } return result.toString(); } BigFontGenerator(); boolean isLoaded(); void load(InputStream[] inputStream); int getSize(); String convert(String text, int position); }### Answer: @Test public void convert() throws Exception { String path = "C:\\github\\ascii_generate\\app\\src\\test\\java\\com\\duy\\ascii\\art\\bigtext\\out.txt"; PrintStream stream = new PrintStream(new FileOutputStream(path)); for (int i = 0; i < mBigFontGenerator.getSize(); i++) { String convert = mBigFontGenerator.convert("hello", i); stream.println(convert); System.out.println(convert); } stream.flush(); stream.close(); }
### Question: Main { public static void main(String[] args) throws Exception { if (args.length > 0 && args[0].equals("-Xjdb")) { String[] newargs = new String[args.length + 2]; Class<?> c = Class.forName("com.sun.tools.example.debug.tty.TTY"); Method method = c.getDeclaredMethod("main", new Class<?>[] { args.getClass() }); method.setAccessible(true); System.arraycopy(args, 1, newargs, 3, args.length - 1); newargs[0] = "-connect"; newargs[1] = "com.sun.jdi.CommandLineLaunch:options=-esa -ea:com.sun.tools..."; newargs[2] = "com.sun.tools.javac.Main"; method.invoke(null, new Object[] { newargs }); } else { System.exit(compile(args)); } } static void main(String[] args); static int compile(String[] args); static int compile(String[] args, PrintWriter out); }### Answer: @Test public void testMain_fullversion() throws Exception { String[] args = {"-fullversion"}; Main.main(args); } @Test public void testMain_SimpleCompile() { String [] args = { JavacTestTool.JAVAFILES_PATH + "Simple.java", "-d", JavacTestTool.CLASSFILES_PATH, "-verbose" }; try { Main.main(args); } catch (Exception e) { e.printStackTrace(); } } @Test public void testMain_Xprint() throws Exception { String[] args = { "-Xprint", "java.lang.String"}; Main.main(args); } @Test public void testMain_X() throws Exception { String[] args = {"-X"}; Main.main(args); } @Test public void testMain_help() throws Exception { String[] args = {"-help"}; Main.main(args); } @Test public void testMain_version() throws Exception { String[] args = {"-version"}; Main.main(args); }
### Question: Launcher { public static void main(String... args) { JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); JFileChooser fileChooser; Preferences prefs = Preferences.userNodeForPackage(Launcher.class); if (args.length > 0) fileChooser = new JFileChooser(args[0]); else { String fileName = prefs.get("recent.file", null); fileChooser = new JFileChooser(); if (fileName != null) { fileChooser = new JFileChooser(); fileChooser.setSelectedFile(new File(fileName)); } } if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { String fileName = fileChooser.getSelectedFile().getPath(); prefs.put("recent.file", fileName); javac.run( System.in, null, null, "-d", "D:/Workspace/JSE/workspace/Compiler_javac/test-files/class-files", fileName); } } static void main(String... args); }### Answer: @Test public void testLauncher_fileChooser() { String[] args = {"D:/Workspace/JSE/workspace/Compiler_javac"}; Launcher.main(args); } @Test public void testLauncher_noArgs() { String[] args = {}; Launcher.main(args); } @Test public void testLauncher_Xprint() throws Exception { String[] args = { "-Xprint", "java.lang.String"}; Launcher.main(args); }
### Question: Main { public static int compile(String[] args) { com.sun.tools.javac.main.Main compiler = new com.sun.tools.javac.main.Main("javac"); return compiler.compile(args); } static void main(String[] args); static int compile(String[] args); static int compile(String[] args, PrintWriter out); }### Answer: @Test public void testMain_nullArgs() throws Exception { String[] args = {}; int status = Main.compile(args); assertTrue(status == 2); System.exit(status); }
### Question: Parser { public MavenRepositoryURL getRepositoryURL() { return m_repositoryURL; } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void behaviorSnapshotEnbled() throws MalformedURLException { Parser parser; parser = new Parser( "http: assertTrue(parser.getRepositoryURL().isSnapshotsEnabled()); assertTrue(parser.getRepositoryURL().isReleasesEnabled()); }
### Question: Parser { public String getResourceName() { return m_resourceName; } Parser( final String path ); String getResourceName(); }### Answer: @Test public void getResourceNameWithContainingSlash() throws MalformedURLException { assertEquals( "Resource name", "somewhere/resource", new Parser( "somewhere/resource" ).getResourceName() ); } @Test public void getResourceNameWithoutLeadingSlash() throws MalformedURLException { assertEquals( "Resource name", "resource", new Parser( "resource" ).getResourceName() ); } @Test public void getResourceNameWithLeadingSlash() throws MalformedURLException { assertEquals( "Resource name", "resource", new Parser( "/resource" ).getResourceName() ); }
### Question: AbstractConnection extends URLConnection { protected static boolean checkJarIsLegal(String name) { boolean isMatched = false; for (Pattern pattern : blacklist) { isMatched = pattern.matcher(name).find(); if (isMatched) { break; } } return !isMatched; } protected AbstractConnection( final URL url, final Configuration configuration ); @Override InputStream getInputStream(); @Override void connect(); }### Answer: @Test public void testCheckJarIsLegal() { String[] servletJarNamesToTest = { "servlet.jar", "servlet-2.5.jar", "servlet-api.jar", "servlet-api-2.5.jar" }; for (String servletName : servletJarNamesToTest) { assertFalse(AbstractConnection.checkJarIsLegal(servletName)); } String[] jasperJarNamesToTest = { "jasper.jar", "jasper-2.5.jar", }; for (String servletName : jasperJarNamesToTest) { assertFalse(AbstractConnection.checkJarIsLegal(servletName)); } }
### Question: Parser { public URL getWrappedJarURL() { return m_wrappedJarURL; } Parser( final String path, final boolean certificateCheck ); URL getWrappedJarURL(); Properties getWrappingProperties(); OverwriteMode getOverwriteMode(); }### Answer: @Test public void validWrappedJarURL() throws MalformedURLException { Parser parser = new Parser( "file:toWrap.jar", true ); assertEquals( "Wrapped Jar URL", new URL( "file:toWrap.jar" ), parser.getWrappedJarURL() ); assertNotNull( "Properties was not expected to be null", parser.getWrappedJarURL() ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public Boolean getCertificateCheck() { if( !contains( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ) ) { return set( ServiceConstants.PROPERTY_CERTIFICATE_CHECK, Boolean.valueOf( m_propertyResolver.get( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ) ) ); } return get( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ); } ConfigurationImpl( final PropertyResolver propertyResolver ); Boolean getCertificateCheck(); }### Answer: @Test public void getCertificateCheck() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.url.wrap.certificateCheck" ) ).andReturn( "true" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Certificate check", true, config.getCertificateCheck() ); verify( propertyResolver ); } @Test public void getDefaultCertificateCheck() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.url.wrap.certificateCheck" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Certificate check", false, config.getCertificateCheck() ); verify( propertyResolver ); }
### Question: Connection extends URLConnection { @Override public InputStream getInputStream() throws IOException { return new BundleBuilder( m_parser.getOptions(), new ResourceWriter( new FileTailImpl( m_parser.getDirectory(), m_parser.getTailExpr() ) .getParentOfTail() ) ).build(); } Connection( URL url, Configuration config ); @Override InputStream getInputStream(); void connect(); }### Answer: @Test public void simple() throws IOException { String clazz = this.getClass().getName().replaceAll( "\\.", "/" ) + ".class"; URL url = new URL( "http:.$tail=" + clazz + "&Foo=bar" ); Configuration config = createMock( Configuration.class ); Connection con = new Connection( url, config ); InputStream inp = con.getInputStream(); FunctionalTest.dumpToConsole( inp, 16 ); }
### Question: Parser { public File getDirectory() { return m_directory; } Parser( String url ); File getDirectory(); Properties getOptions(); String getTailExpr(); }### Answer: @Test public void parseValidURL() throws IOException { File f = new File( System.getProperty( "java.io.tmpdir" ) ); assertEquals( f.getCanonicalPath(), new Parser( "http:" + f.getCanonicalPath() ).getDirectory().getAbsolutePath() ); }
### Question: Parser { public Properties getOptions() { return m_options; } Parser( String url ); File getDirectory(); Properties getOptions(); String getTailExpr(); }### Answer: @Test public void parseWithMoreParams() throws IOException, URISyntaxException { Parser parser = new Parser( "http:." + "$a=1&b=2" ); assertEquals( "1", parser.getOptions().get( "a" ) ); assertEquals( "2", parser.getOptions().get( "b" ) ); assertEquals( 2, parser.getOptions().size() ); }
### Question: Parser { public String getSnapshotPath( final String version, final String timestamp, final String buildnumber ) { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( version ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( VERSION_SEPARATOR ) .append( getSnapshotVersion( version, timestamp, buildnumber ) ) .append( m_fullClassifier ) .append( TYPE_SEPARATOR ) .append( m_type ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void snapshotPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version-SNAPSHOT" ); assertEquals( "Artifact snapshot path", "group/artifact/version-SNAPSHOT/artifact-version-timestamp-build.jar", parser.getSnapshotPath( "version-SNAPSHOT", "timestamp", "build" ) ); }
### Question: Parser { public String getArtifactPath() { return getArtifactPath( m_version ); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void artifactPathWithVersion() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact path", "group/artifact/version2/artifact-version2.jar", parser.getArtifactPath( "version2" ) ); }
### Question: Parser { public String getVersionMetadataPath( final String version ) { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( version ) .append( FILE_SEPARATOR ) .append( METADATA_FILE ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void versionMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Version metadata path", "group/artifact/version2/maven-metadata.xml", parser.getVersionMetadataPath( "version2" ) ); }
### Question: Parser { public String getArtifactMetdataPath() { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( METADATA_FILE ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void artifactMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact metadata path", "group/artifact/maven-metadata.xml", parser.getArtifactMetdataPath() ); }
### Question: Parser { public String getArtifactLocalMetdataPath() { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( METADATA_FILE_LOCAL ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void artifactLocalMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact local metadata path", "group/artifact/maven-metadata-local.xml", parser.getArtifactLocalMetdataPath() ); }
### Question: Connection extends URLConnection { public InputStream getInputStream() throws IOException { connect(); InputStream is; if( url.getAuthority() != null ) { is = getFromSpecificBundle(); } else { is = getFromClasspath(); if( is == null ) { is = getFromInstalledBundles(); } } if( is == null ) { throw new IOException( "URL [" + m_parser.getResourceName() + "] could not be resolved from classpath" ); } return is; } Connection( final URL url, final BundleContext bundleContext ); @Override void connect(); InputStream getInputStream(); static final String PROTOCOL; }### Answer: @Test public void searchFirstTheThreadClasspath() throws IOException { BundleContext context = createMock( BundleContext.class ); replay( context ); InputStream is = new Connection( new URL( "http:connection/resource" ), context ).getInputStream(); assertNotNull( "Returned input stream is null", is ); verify( context ); }
### Question: RelevanceModel { public static Dataset concat(Dataset d1, Dataset d2) { double[][] X = concat(d1.getX(), d2.getX()); double[] y = concat(d1.getY(), d2.getY()); return new Dataset(X, y); } static void main(String[] args); static Dataset concat(Dataset d1, Dataset d2); static double[] concat(double[] y1, double[] y2); static double[][] concat(double[][] X1, double[][] X2); static double auc(SoftClassifier<double[]> model, Dataset dataset); static double[] predict(SoftClassifier<double[]> model, Dataset dataset); }### Answer: @Test public void concat1d() { double[] y1 = { 1.0, 2.0, 3.0 }; double[] y2 = { 4.0, 5.0 }; double[] y = RelevanceModel.concat(y1, y2); double[] expected = { 1.0, 2.0, 3.0, 4.0, 5.0 }; assertTrue(Arrays.equals(y, expected)); } @Test public void concat2d() { double[][] X1 = { { 0.0, 1.0 }, { 0.0, 2.0 }, { 0.0, 3.0 } }; double[][] X2 = { { 0.0, 4.0 }, { 0.0, 5.0 } }; double[][] X = RelevanceModel.concat(X1, X2); double[][] expected = { { 0.0, 1.0 }, { 0.0, 2.0 }, { 0.0, 3.0 }, { 0.0, 4.0 }, { 0.0, 5.0 } }; assertTrue(Arrays.deepEquals(X, expected)); }
### Question: NerGroup { public static List<String> groupNer(List<Word> tokens) { if (tokens.isEmpty()) { return Collections.emptyList(); } String prevNer = "O"; List<List<Word>> groups = new ArrayList<>(); List<Word> group = new ArrayList<>(); for (Word w : tokens) { String ner = w.getNer(); if (prevNer.equals(ner) && !"O".equals(ner)) { group.add(w); continue; } groups.add(group); group = new ArrayList<>(); group.add(w); prevNer = ner; } groups.add(group); return groups.stream() .filter(l -> !l.isEmpty()) .map(list -> joinLemmas(list)) .collect(Collectors.toList()); } static List<String> groupNer(List<Word> tokens); }### Answer: @Test public void test() { List<Word> tokens = Arrays.asList( new Word("My", "My", "_", "O"), new Word("name", "name", "_", "O"), new Word("is", "is", "_", "O"), new Word("Justin", "Justin", "_", "PERSON"), new Word("Bieber", "Bieber", "_", "PERSON"), new Word("I", "I", "_", "O"), new Word("live", "live", "_", "O"), new Word("in", "in", "_", "O"), new Word("Brooklyn", "Brooklyn", "_", "LOCATION"), new Word(",", ",", "_", "O"), new Word("New", "New", "_", "LOCATION"), new Word("York", "York", "_", "LOCATION"), new Word(".", ".", "_", "O") ); List<String> results = NerGroup.groupNer(tokens); List<String> expected = Arrays.asList("My", "name", "is", "Justin Bieber", "I", "live", "in", "Brooklyn", ",", "New York", "."); assertEquals(expected, results); }
### Question: DefaultJavaRunner implements StoppableJavaRunner { static String getJavaExecutable( final String javaHome ) throws PlatformException { if( javaHome == null ) { throw new PlatformException( "JAVA_HOME is not set." ); } return javaHome + "/bin/java"; } DefaultJavaRunner(); DefaultJavaRunner( boolean wait ); synchronized void exec( final String[] vmOptions, final String[] classpath, final String mainClass, final String[] programOptions, final String javaHome, final File workingDirectory ); synchronized void exec( final String[] vmOptions, final String[] classpath, final String mainClass, final String[] programOptions, final String javaHome, final File workingDirectory, final String[] envOptions ); void shutdown(); void waitForExit(); }### Answer: @Test public void getJavaExecutable() throws Exception { assertEquals( "Java executable", "javaHome/bin/java", DefaultJavaRunner.getJavaExecutable( "javaHome" ) ); } @Test( expected = PlatformException.class ) public void getJavaExecutableWithInvalidJavaHome() throws Exception { DefaultJavaRunner.getJavaExecutable( null ); }
### Question: ConciergePlatformBuilder implements PlatformBuilder { public String[] getArguments( final PlatformContext context ) { return null; } ConciergePlatformBuilder( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getArguments() throws MalformedURLException { replay( m_bundleContext ); assertArrayEquals( "Arguments", null, new ConciergePlatformBuilder( m_bundleContext, "version" ).getArguments( m_platformContext ) ); verify( m_bundleContext ); }
### Question: KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String getMainClassName() { return MAIN_CLASS_NAME; } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void mainClassName() { replay( m_bundleContext ); assertEquals( "Main class name", "org.knopflerfish.framework.Main", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getMainClassName() ); verify( m_bundleContext ); }
### Question: KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String getRequiredProfile( final PlatformContext context ) { final Boolean console = context.getConfiguration().startConsole(); if( console == null || !console ) { return null; } else { return CONSOLE_PROFILE; } } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getRequiredProfilesWithoutConsole() { expect( m_configuration.startConsole() ).andReturn( null ); replay( m_bundleContext, m_configuration ); assertNull( "Required profiles is not null", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getRequiredProfile( m_platformContext ) ); verify( m_bundleContext, m_configuration ); } @Test public void getRequiredProfilesWithConsole() { expect( m_configuration.startConsole() ).andReturn( true ); replay( m_bundleContext, m_configuration ); assertEquals( "Required profiles", "tui", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getRequiredProfile( m_platformContext ) ); verify( m_bundleContext, m_configuration ); }
### Question: KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String[] getArguments( final PlatformContext context ) { NullArgumentException.validateNotNull( context, "Platform context" ); return new String[]{ "-xargs", context.getFilePathStrategy().normalizeAsUrl( new File( new File( context.getWorkingDirectory(), CONFIG_DIRECTORY ), CONFIG_INI ) ) }; } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getArguments() throws MalformedURLException { replay( m_bundleContext ); assertArrayEquals( "Arguments", new String[]{ "-xargs", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "knopflerfish/config.ini" ) ), }, new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getArguments( m_platformContext ) ); verify( m_bundleContext ); }
### Question: KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String[] getVMOptions( final PlatformContext context ) { NullArgumentException.validateNotNull( context, "Platform context" ); final Collection<String> vmOptions = new ArrayList<String>(); final File workingDirectory = context.getWorkingDirectory(); vmOptions.add( "-Dorg.osgi.framework.dir=" + context.getFilePathStrategy().normalizeAsPath( new File( new File( workingDirectory, CONFIG_DIRECTORY ), CACHE_DIRECTORY ) ) ); return vmOptions.toArray( new String[vmOptions.size()] ); } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getVMOptions() { replay( m_bundleContext ); assertArrayEquals( "System properties", new String[]{ "-Dorg.osgi.framework.dir=" + m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "knopflerfish/fwdir" ) ) }, new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getVMOptions( m_platformContext ) ); verify( m_bundleContext ); } @Test( expected = IllegalArgumentException.class ) public void getSystemPropertiesWithNullPlatformContext() { replay( m_bundleContext ); new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getVMOptions( null ); verify( m_bundleContext ); }
### Question: CommandLineImpl implements CommandLine { public String[] getMultipleOption( final String key ) { final List<String> values = m_options.get( key ); return values == null || values.size() == 0 ? new String[0] : values.toArray( new String[values.size()] ); } CommandLineImpl( final String... args ); String getOption( final String key ); String[] getMultipleOption( final String key ); List<String> getArguments(); String getArgumentsFileURL(); @Override String toString(); static final Pattern OPTION_PATTERN; }### Answer: @Test public void arrayValueNotDefined() { CommandLine commandLine = new CommandLineImpl( "--some" ); assertArrayEquals( "Option value", new String[0], commandLine.getMultipleOption( "array" ) ); }
### Question: PlatformImpl implements Platform { void validateBundle( final URL url, final File file ) throws PlatformException { String bundleSymbolicName = null; String bundleName = null; JarFile jar = null; try { jar = new JarFile( file, false ); final Manifest manifest = jar.getManifest(); if ( manifest == null ) { throw new PlatformException( "[" + url + "] is not a valid bundle" ); } bundleSymbolicName = manifest.getMainAttributes().getValue( Constants.BUNDLE_SYMBOLICNAME ); bundleName = manifest.getMainAttributes().getValue( Constants.BUNDLE_NAME ); } catch ( IOException e ) { throw new PlatformException( "[" + url + "] is not a valid bundle", e ); } finally { if ( jar != null ) { try { jar.close(); } catch ( IOException ignore ) { } } } if ( bundleSymbolicName == null && bundleName == null ) { throw new PlatformException( "[" + url + "] is not a valid bundle" ); } } PlatformImpl( final PlatformBuilder platformBuilder ); void setResolver( final PropertyResolver propertyResolver ); void start( final List<SystemFileReference> systemFiles, final List<BundleReference> bundles, final Properties properties, @SuppressWarnings("rawtypes") final Dictionary config, final JavaRunner javaRunner ); String toString(); }### Answer: @Test( expected = PlatformException.class ) public void validateBundleWithNoManifestAndCheckAttributes() throws Exception { replay( m_builder, m_bundleContext, m_config ); PlatformImpl platform = new PlatformImpl( m_builder ); File file = FileUtils.getFileFromClasspath( "platform/withoutManifest.jar" ); URL url = file.toURL(); platform.validateBundle( url, file ); } @Test( expected = PlatformException.class ) public void validateBundleWithInvalidFile() throws Exception { replay( m_builder, m_bundleContext, m_config ); PlatformImpl platform = new PlatformImpl( m_builder ); File file = FileUtils.getFileFromClasspath( "platform/invalid.jar" ); URL url = file.toURL(); platform.validateBundle( url, file ); }
### Question: ConfigurationImpl implements Configuration { public String getProperty( final String key ) { return m_properties.getProperty( key ); } ConfigurationImpl( final String url ); String getProperty( final String key ); @SuppressWarnings( "unchecked" ) String[] getPropertyNames( final String regex ); }### Answer: @Test public void constructorWithValidClasspathConfiguration() { Configuration config = new ConfigurationImpl( "classpath:org/ops4j/pax/runner/configuration/runner.properties" ); assertEquals( "platform.test", "org.ops4j.pax.runner.platform.Activator", config.getProperty( "platform.test" ) ); }
### Question: ExecutionEnvironment { public String getSystemPackages() { return m_systemPackages; } ExecutionEnvironment( final String ee ); String getSystemPackages(); String getExecutionEnvironment(); static String join( final Collection<String> toJoin, final String delimiter ); }### Answer: @Test public void createPackageListWithURLEE() throws Exception { assertEquals( "System packages", "system.package.1,system.package.2", new ExecutionEnvironment( FileUtils.getFileFromClasspath( "platform/systemPackages.profile" ).toURL().toExternalForm() ).getSystemPackages() ); } @Test public void createPackageListNONE() throws Exception { assertEquals( "System packages", "", new ExecutionEnvironment( "NONE" ).getSystemPackages() ); } @Test public void createPackageListLetterCase() throws Exception { assertEquals( "System packages", "javax.microedition.io,javax.microedition.pki,javax.security.auth.x500", new ExecutionEnvironment( "cdc-1.1/foundation-1.1" ).getSystemPackages() ); } @Test public void createPackageListWithMoreEEs() throws Exception { assertEquals( "System packages", "system.package.1,system.package.2,system.package.3", new ExecutionEnvironment( FileUtils.getFileFromClasspath( "platform/systemPackages.profile" ).toURL().toExternalForm() + "," + FileUtils.getFileFromClasspath( "platform/systemPackages2.profile" ).toURL().toExternalForm() ).getSystemPackages() ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public String getWorkingDirectory() { if( !contains( ServiceConstants.CONFIG_WORKING_DIRECTORY ) ) { String workDir = m_propertyResolver.get( ServiceConstants.CONFIG_WORKING_DIRECTORY ); if( workDir == null ) { workDir = DEFAULT_WORKING_DIRECTORY; } return set( ServiceConstants.CONFIG_WORKING_DIRECTORY, workDir ); } return get( ServiceConstants.CONFIG_WORKING_DIRECTORY ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }### Answer: @Test public void getWorkingDirectory() throws MalformedURLException { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.workingDirectory" ) ).andReturn( "myWorkingDirectory" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Working directory", "myWorkingDirectory", config.getWorkingDirectory() ); verify( propertyResolver ); } @Test public void getDefualtWorkingDirectory() throws MalformedURLException { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.workingDirectory" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Default working directory", "runner", config.getWorkingDirectory() ); verify( propertyResolver ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public String getSystemPackages() { if( !contains( ServiceConstants.CONFIG_SYSTEM_PACKAGES ) ) { return set( ServiceConstants.CONFIG_SYSTEM_PACKAGES, m_propertyResolver.get( ServiceConstants.CONFIG_SYSTEM_PACKAGES ) ); } return get( ServiceConstants.CONFIG_SYSTEM_PACKAGES ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }### Answer: @Test public void getSystemPackages() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.systemPackages" ) ).andReturn( "systemPackages" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "System packages", "systemPackages", config.getSystemPackages() ); verify( propertyResolver ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public String getExecutionEnvironment() { if( !contains( ServiceConstants.CONFIG_EXECUTION_ENV ) ) { String javaVersion = m_propertyResolver.get( ServiceConstants.CONFIG_EXECUTION_ENV ); if( javaVersion == null ) { javaVersion = "J2SE-" + System.getProperty( "java.version" ).substring( 0, 3 ); } return set( ServiceConstants.CONFIG_EXECUTION_ENV, javaVersion ); } return get( ServiceConstants.CONFIG_EXECUTION_ENV ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }### Answer: @Test public void getExecutionEnvironment() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.ee" ) ).andReturn( "some-ee" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Execution environment", "some-ee", config.getExecutionEnvironment() ); verify( propertyResolver ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public String getJavaHome() { if( !contains( ServiceConstants.CONFIG_JAVA_HOME ) ) { String javaHome = m_propertyResolver.get( ServiceConstants.CONFIG_JAVA_HOME ); if( javaHome == null ) { javaHome = System.getProperty( "JAVA_HOME" ); if( javaHome == null ) { try { javaHome = System.getenv( "JAVA_HOME" ); } catch( Error e ) { } if( javaHome == null ) { javaHome = System.getProperty( "java.home" ); } } } return set( ServiceConstants.CONFIG_JAVA_HOME, javaHome ); } return get( ServiceConstants.CONFIG_JAVA_HOME ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }### Answer: @Test public void getJavaHome() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.javaHome" ) ).andReturn( "javaHome" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Java home", "javaHome", config.getJavaHome() ); verify( propertyResolver ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public String getProfiles() { if( !contains( ServiceConstants.CONFIG_PROFILES ) ) { return set( ServiceConstants.CONFIG_PROFILES, m_propertyResolver.get( ServiceConstants.CONFIG_PROFILES ) ); } return get( ServiceConstants.CONFIG_PROFILES ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }### Answer: @Test public void getProfiles() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.profiles" ) ).andReturn( "myProfile" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Profiles", "myProfile", config.getProfiles() ); verify( propertyResolver ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public String getFrameworkProfile() { if( !contains( ServiceConstants.CONFIG_FRAMEWORK_PROFILE ) ) { String profile = m_propertyResolver.get( ServiceConstants.CONFIG_FRAMEWORK_PROFILE ); if( profile == null ) { profile = DEFAULT_FRAMEWORK_PROFILE; } return set( ServiceConstants.CONFIG_FRAMEWORK_PROFILE, profile ); } return get( ServiceConstants.CONFIG_FRAMEWORK_PROFILE ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }### Answer: @Test public void getFrameworkProfile() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.frameworkProfile" ) ).andReturn( "myProfile" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Framework profile", "myProfile", config.getFrameworkProfile() ); verify( propertyResolver ); } @Test public void getDefaultFrameworkProfile() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.frameworkProfile" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Framework profile", "runner", config.getFrameworkProfile() ); verify( propertyResolver ); }
### Question: Activator implements BundleActivator { public void stop( final BundleContext bundleContext ) throws Exception { NullArgumentException.validateNotNull( bundleContext, "Bundle context" ); if( m_serviceTracker != null ) { m_serviceTracker.close(); m_serviceTracker = null; } if( m_registrations != null ) { for( ServiceRegistration registration : m_registrations.values() ) { if( registration != null ) { registration.unregister(); } } } if( m_managedServiceReg != null ) { m_managedServiceReg.unregister(); } m_platforms = null; m_bundleContext = null; LOGGER.debug( "Platform extender stopped" ); } Activator(); void start( final BundleContext bundleContext ); void stop( final BundleContext bundleContext ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void stopWithNullBundleContext() throws Exception { new Activator().stop( null ); } @Test public void stop() throws Exception { BundleContext context = createMock( BundleContext.class ); replay( context ); new Activator().stop( context ); verify( context ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public Boolean isDownloadFeedback() { if( !contains( ServiceConstants.CONFIG_DOWNLOAD_FEEDBACK ) ) { String downloadFeedback = m_propertyResolver.get( ServiceConstants.CONFIG_DOWNLOAD_FEEDBACK ); if( downloadFeedback == null ) { downloadFeedback = Boolean.TRUE.toString(); } return set( ServiceConstants.CONFIG_DOWNLOAD_FEEDBACK, Boolean.valueOf( downloadFeedback ) ); } return get( ServiceConstants.CONFIG_OVERWRITE_SYSTEM_BUNDLES ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }### Answer: @Test public void isDownloadFeebackDefault() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.downloadFeedback" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Download feedback", true, config.isDownloadFeedback() ); verify( propertyResolver ); } @Test public void isDownloadFeedback() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.downloadFeedback" ) ).andReturn( "false" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Download feedback", false, config.isDownloadFeedback() ); verify( propertyResolver ); }
### Question: AbstractPlatformBuilderActivator implements BundleActivator { public void start( final BundleContext bundleContext ) throws Exception { NullArgumentException.validateNotNull( bundleContext, "Bundle context" ); m_bundleContext = bundleContext; registerPlatformBuilders( createPlatformBuilders( m_bundleContext ) ); LOGGER.debug( "Platform builder [" + this + "] started" ); } void start( final BundleContext bundleContext ); void stop( final BundleContext bundleContext ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void startWithNullBundleContext() throws Exception { new TestAPBActivator().start( null ); } @Test public void start() throws Exception { BundleContext context = createMock( BundleContext.class ); expect( context.registerService( eq( PlatformBuilder.class.getName() ), eq( m_platformBuilder1 ), (Dictionary) notNull() ) ).andReturn( null ); expect( context.registerService( eq( PlatformBuilder.class.getName() ), eq( m_platformBuilder2 ), (Dictionary) notNull() ) ).andReturn( null ); expect( m_platformBuilder1.getProviderName() ).andReturn( "provider" ); expect( m_platformBuilder1.getProviderVersion() ).andReturn( "version1" ); expect( m_platformBuilder2.getProviderName() ).andReturn( "provider" ); expect( m_platformBuilder2.getProviderVersion() ).andReturn( "version2" ); replay( context, m_platformBuilder1, m_platformBuilder2 ); new TestAPBActivator().start( context ); verify( context, m_platformBuilder1, m_platformBuilder2 ); }
### Question: AbstractPlatformBuilderActivator implements BundleActivator { public void stop( final BundleContext bundleContext ) throws Exception { NullArgumentException.validateNotNull( bundleContext, "Bundle context" ); if( m_platformBuilderServiceReg != null ) { for( ServiceRegistration registration : m_platformBuilderServiceReg ) { if( registration != null ) { registration.unregister(); } } m_platformBuilderServiceReg = null; } m_bundleContext = null; LOGGER.debug( "Platform builder [" + this + "] stopped" ); } void start( final BundleContext bundleContext ); void stop( final BundleContext bundleContext ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void stopWithNullBundleContext() throws Exception { new TestAPBActivator().stop( null ); } @Test public void stop() throws Exception { BundleContext context = createMock( BundleContext.class ); replay( context ); new TestAPBActivator().stop( context ); verify( context ); }
### Question: Activator implements BundleActivator { public void start( final BundleContext bundleContext ) throws Exception { NullArgumentException.validateNotNull( bundleContext, "Bundle context" ); m_bundleContext = bundleContext; m_extender = createExtender(); m_extender.start(); trackURLStreamHandlerService(); LOGGER.debug( "URL stream handler service extender started" ); } void start( final BundleContext bundleContext ); void stop( final BundleContext bundleContext ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void startWithNullBundleContext() throws Exception { new Activator().start( null ); } @Test public void start() throws Exception { BundleContext context = createMock( BundleContext.class ); expect( context.createFilter( "(objectClass=" + URLStreamHandlerService.class.getName() + ")" ) ).andReturn( createMock( Filter.class ) ); context.addServiceListener( (ServiceListener) notNull(), eq( "(objectClass=" + URLStreamHandlerService.class.getName() + ")" ) ); expect( context.getServiceReferences( eq( URLStreamHandlerService.class.getName() ), (String) isNull() ) ).andReturn( null ); replay( context ); new Activator().start( context ); verify( context ); }
### Question: Activator implements BundleActivator { public void stop( final BundleContext bundleContext ) throws Exception { NullArgumentException.validateNotNull( bundleContext, "Bundle context" ); if( m_serviceTracker != null ) { m_serviceTracker.close(); m_serviceTracker = null; } m_extender = null; m_bundleContext = null; LOGGER.debug( "URL stream handler service extender stopped" ); } void start( final BundleContext bundleContext ); void stop( final BundleContext bundleContext ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void stopWithNullBundleContext() throws Exception { new Activator().stop( null ); } @Test public void stop() throws Exception { BundleContext context = createMock( BundleContext.class ); replay( context ); new Activator().stop( context ); verify( context ); }
### Question: URLUtils { public static URLStreamHandlerFactory getURLStreamHandlerFactory() { Field field = getURLStreamHandlerFactoryField(); field.setAccessible( true ); try { return (URLStreamHandlerFactory) field.get( null ); } catch( IllegalAccessException e ) { throw new RuntimeException( "Cannot access URLStreamHandlerFactory field", e ); } } private URLUtils(); static void setURLStreamHandlerFactory( final URLStreamHandlerFactory urlStreamHandlerFactory ); static URLStreamHandlerFactory resetURLStreamHandlerFactory(); static URLStreamHandlerFactory getURLStreamHandlerFactory(); }### Answer: @Test public void getURLStreamHandlerFactory() { URLStreamHandlerFactory factory = createMock( URLStreamHandlerFactory.class ); URL.setURLStreamHandlerFactory( factory ); assertEquals( "Factory", factory, URLUtils.getURLStreamHandlerFactory() ); }
### Question: URLUtils { public static void setURLStreamHandlerFactory( final URLStreamHandlerFactory urlStreamHandlerFactory ) { try { URL.setURLStreamHandlerFactory( urlStreamHandlerFactory ); } catch( Error err ) { LOGGER.debug( "URLStreamHandlerFactory already set in the system. Replacing it with a composite" ); synchronized( URL.class ) { final URLStreamHandlerFactory currentFactory = resetURLStreamHandlerFactory(); if( currentFactory == null ) { URL.setURLStreamHandlerFactory( urlStreamHandlerFactory ); } else if( currentFactory instanceof CompositeURLStreamHandlerFactory ) { URL.setURLStreamHandlerFactory( currentFactory ); ( (CompositeURLStreamHandlerFactory) currentFactory ).registerFactory( urlStreamHandlerFactory ); } else { URL.setURLStreamHandlerFactory( new CompositeURLStreamHandlerFactory() .registerFactory( urlStreamHandlerFactory ) .registerFactory( currentFactory ) ); } } } } private URLUtils(); static void setURLStreamHandlerFactory( final URLStreamHandlerFactory urlStreamHandlerFactory ); static URLStreamHandlerFactory resetURLStreamHandlerFactory(); static URLStreamHandlerFactory getURLStreamHandlerFactory(); }### Answer: @Test public void setURLStreamHandlerFactory() { URLStreamHandlerFactory factory = createMock( URLStreamHandlerFactory.class ); URLUtils.setURLStreamHandlerFactory( factory ); assertEquals( "Factory", factory, URLUtils.getURLStreamHandlerFactory() ); } @Test public void compositeFactorySetup() { URLStreamHandlerFactory factory1 = createMock( URLStreamHandlerFactory.class ); URLStreamHandlerFactory factory2 = createMock( URLStreamHandlerFactory.class ); URLUtils.setURLStreamHandlerFactory( factory1 ); URLUtils.setURLStreamHandlerFactory( factory2 ); expect( factory1.createURLStreamHandler( "foo" ) ).andReturn( null ); expect( factory2.createURLStreamHandler( "foo" ) ).andReturn( null ); replay( factory1, factory2 ); try { new URL( "foo:bar" ); } catch( MalformedURLException ignore ) { } verify( factory1, factory2 ); }
### Question: URLStreamHandlerExtender implements URLStreamHandlerFactory { public void register( final String[] protocols, final URLStreamHandlerService urlStreamHandlerService ) { LOGGER.debug( "Registering protocols [" + Arrays.toString( protocols ) + "] to service [" + urlStreamHandlerService + "]" ); NullArgumentException.validateNotEmptyContent( protocols, true, "Protocol" ); NullArgumentException.validateNotNull( urlStreamHandlerService, "URL stream handler service" ); for( String protocol : protocols ) { m_proxies.put( protocol, createProxy( urlStreamHandlerService ) ); } } URLStreamHandlerExtender(); void start(); void register( final String[] protocols, final URLStreamHandlerService urlStreamHandlerService ); void unregister( final String[] protocols ); URLStreamHandler createURLStreamHandler( final String protocol ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void registerWithNullProtocol() { new URLStreamHandlerExtender().register( null, createMock( URLStreamHandlerService.class ) ); } @Test( expected = IllegalArgumentException.class ) public void registerWithEmptyProtocol() { new URLStreamHandlerExtender().register( new String[]{ " " }, createMock( URLStreamHandlerService.class ) ); } @Test( expected = IllegalArgumentException.class ) public void registerWithNullService() { new URLStreamHandlerExtender().register( new String[]{ "protocol" }, null ); } @Test public void register() { new URLStreamHandlerExtender().register( new String[]{ "protocol" }, createMock( URLStreamHandlerService.class ) ); }
### Question: URLStreamHandlerExtender implements URLStreamHandlerFactory { public void unregister( final String[] protocols ) { LOGGER.debug( "Unregistering protocols [" + Arrays.toString( protocols ) + "]" ); NullArgumentException.validateNotEmptyContent( protocols, true, "Protocols" ); for( String protocol : protocols ) { m_proxies.remove( protocol ); } } URLStreamHandlerExtender(); void start(); void register( final String[] protocols, final URLStreamHandlerService urlStreamHandlerService ); void unregister( final String[] protocols ); URLStreamHandler createURLStreamHandler( final String protocol ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void unregisterWithNullProtocol() { new URLStreamHandlerExtender().unregister( null ); } @Test( expected = IllegalArgumentException.class ) public void unregisterWithEmptyProtocol() { new URLStreamHandlerExtender().unregister( new String[]{ " " } ); } @Test public void unregister() { new URLStreamHandlerExtender().unregister( new String[]{ "protocol" } ); }
### Question: URLStreamHandlerExtender implements URLStreamHandlerFactory { public URLStreamHandler createURLStreamHandler( final String protocol ) { NullArgumentException.validateNotEmpty( protocol, true, "Protocol" ); return m_proxies.get( protocol ); } URLStreamHandlerExtender(); void start(); void register( final String[] protocols, final URLStreamHandlerService urlStreamHandlerService ); void unregister( final String[] protocols ); URLStreamHandler createURLStreamHandler( final String protocol ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void createURLStreamHandlerWithNullProtocol() { new URLStreamHandlerExtender().createURLStreamHandler( null ); } @Test( expected = IllegalArgumentException.class ) public void createURLStreamHandlerWithEmptyProtocol() { new URLStreamHandlerExtender().createURLStreamHandler( " " ); } @Test public void createURLStreamHandlerWithUnknownProtocol() { assertNull( "URL stream handler was supposed to be null", new URLStreamHandlerExtender().createURLStreamHandler( "protocol" ) ); }
### Question: ConciergePlatformBuilder implements PlatformBuilder { public String getMainClassName() { return MAIN_CLASS_NAME; } ConciergePlatformBuilder( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void mainClassName() { replay( m_bundleContext ); assertEquals( "Main class name", "ch.ethz.iks.concierge.framework.Framework", new ConciergePlatformBuilder( m_bundleContext, "version" ).getMainClassName() ); verify( m_bundleContext ); }
### Question: ConciergePlatformBuilder implements PlatformBuilder { public String getRequiredProfile( final PlatformContext context ) { final Boolean console = context.getConfiguration().startConsole(); if( console == null || !console ) { return null; } else { return CONSOLE_PROFILE; } } ConciergePlatformBuilder( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getRequiredProfilesWithoutConsole() { expect( m_configuration.startConsole() ).andReturn( null ); replay( m_bundleContext, m_configuration ); assertNull( "Required profiles is not null", new ConciergePlatformBuilder( m_bundleContext, "version" ).getRequiredProfile( m_platformContext ) ); verify( m_bundleContext, m_configuration ); } @Test public void getRequiredProfilesWithConsole() { expect( m_configuration.startConsole() ).andReturn( true ); replay( m_bundleContext, m_configuration ); assertEquals( "Required profiles", "tui", new ConciergePlatformBuilder( m_bundleContext, "version" ).getRequiredProfile( m_platformContext ) ); verify( m_bundleContext, m_configuration ); }
### Question: CordeauReader { public CordeauReader(VehicleRoutingProblem.Builder vrpBuilder) { super(); this.vrpBuilder = vrpBuilder; } CordeauReader(VehicleRoutingProblem.Builder vrpBuilder); void read(String fileName); void setCoordProjectionFactor(double coordProjectionFactor); }### Answer: @Test public void testCordeauReader() { VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new CordeauReader(vrpBuilder).read(getPath("p01")); vrpBuilder.build(); }
### Question: VehicleImpl extends AbstractVehicle { @Override public Location getEndLocation() { return endLocation; } private VehicleImpl(Builder builder); static Vehicle copyOf(Vehicle vehicle); static NoVehicle createNoVehicle(); @Override String toString(); @Override double getEarliestDeparture(); @Override double getLatestArrival(); @Override VehicleType getType(); @Override String getId(); @Override boolean isReturnToDepot(); @Override Location getStartLocation(); @Override Location getEndLocation(); @Override Skills getSkills(); @Override Break getBreak(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void whenEndLocationCoordIsSet_itIsDoneCorrectly() { Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("startLoc")).setEndLocation(Location.newInstance(1, 2)).build(); assertEquals(1.0, v.getEndLocation().getCoordinate().getX(), 0.01); assertEquals(2.0, v.getEndLocation().getCoordinate().getY(), 0.01); }
### Question: VehicleImpl extends AbstractVehicle { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VehicleImpl other = (VehicleImpl) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } private VehicleImpl(Builder builder); static Vehicle copyOf(Vehicle vehicle); static NoVehicle createNoVehicle(); @Override String toString(); @Override double getEarliestDeparture(); @Override double getLatestArrival(); @Override VehicleType getType(); @Override String getId(); @Override boolean isReturnToDepot(); @Override Location getStartLocation(); @Override Location getEndLocation(); @Override Skills getSkills(); @Override Break getBreak(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void whenTwoVehiclesHaveTheSameId_theyShouldBeEqual() { Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("start")).setEndLocation(Location.newInstance("start")).setReturnToDepot(false).build(); Vehicle v2 = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("start")).setEndLocation(Location.newInstance("start")).setReturnToDepot(false).build(); assertTrue(v.equals(v2)); }
### Question: VehicleTypeImpl implements VehicleType { @Override public Capacity getCapacityDimensions() { return capacityDimensions; } private VehicleTypeImpl(VehicleTypeImpl.Builder builder); @Override boolean equals(Object o); @Override int hashCode(); @Override Object getUserData(); @Override String getTypeId(); @Override VehicleTypeImpl.VehicleCostParams getVehicleCostParams(); @Override String toString(); @Override double getMaxVelocity(); @Override Capacity getCapacityDimensions(); @Override String getProfile(); }### Answer: @Test public void whenAddingTwoCapDimension_nuOfDimsShouldBeTwo() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t") .addCapacityDimension(0, 2) .addCapacityDimension(1, 4) .build(); assertEquals(2, type.getCapacityDimensions().getNuOfDimensions()); } @Test public void whenAddingTwoCapDimension_dimValuesMustBeCorrect() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t") .addCapacityDimension(0, 2) .addCapacityDimension(1, 4) .build(); assertEquals(2, type.getCapacityDimensions().get(0)); assertEquals(4, type.getCapacityDimensions().get(1)); } @Test public void whenTypeIsBuiltWithoutSpecifyingCapacity_itShouldHvCapWithOneDim() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").build(); assertEquals(1, type.getCapacityDimensions().getNuOfDimensions()); } @Test public void whenTypeIsBuiltWithoutSpecifyingCapacity_itShouldHvCapDimValOfZero() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").build(); assertEquals(0, type.getCapacityDimensions().get(0)); } @Test public void whenBuildingTypeJustByCallingNewInstance_capMustBeCorrect() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("foo").build(); assertEquals(0, type.getCapacityDimensions().get(0)); }
### Question: VehicleTypeImpl implements VehicleType { @Override public String getTypeId() { return typeId; } private VehicleTypeImpl(VehicleTypeImpl.Builder builder); @Override boolean equals(Object o); @Override int hashCode(); @Override Object getUserData(); @Override String getTypeId(); @Override VehicleTypeImpl.VehicleCostParams getVehicleCostParams(); @Override String toString(); @Override double getMaxVelocity(); @Override Capacity getCapacityDimensions(); @Override String getProfile(); }### Answer: @Test public void whenBuildingTypeJustByCallingNewInstance_typeIdMustBeCorrect() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("foo").build(); assertEquals("foo", type.getTypeId()); }
### Question: VehicleTypeImpl implements VehicleType { @Override public double getMaxVelocity() { return maxVelocity; } private VehicleTypeImpl(VehicleTypeImpl.Builder builder); @Override boolean equals(Object o); @Override int hashCode(); @Override Object getUserData(); @Override String getTypeId(); @Override VehicleTypeImpl.VehicleCostParams getVehicleCostParams(); @Override String toString(); @Override double getMaxVelocity(); @Override Capacity getCapacityDimensions(); @Override String getProfile(); }### Answer: @Test public void whenSettingMaxVelocity_itShouldBeSetCorrectly() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setMaxVelocity(10).build(); assertEquals(10, type.getMaxVelocity(), 0.0); }
### Question: VehicleTypeImpl implements VehicleType { @Override public VehicleTypeImpl.VehicleCostParams getVehicleCostParams() { return vehicleCostParams; } private VehicleTypeImpl(VehicleTypeImpl.Builder builder); @Override boolean equals(Object o); @Override int hashCode(); @Override Object getUserData(); @Override String getTypeId(); @Override VehicleTypeImpl.VehicleCostParams getVehicleCostParams(); @Override String toString(); @Override double getMaxVelocity(); @Override Capacity getCapacityDimensions(); @Override String getProfile(); }### Answer: @Test public void whenSettingPerDistanceCosts_itShouldBeSetCorrectly() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setCostPerDistance(10).build(); assertEquals(10.0, type.getVehicleCostParams().perDistanceUnit, 0.0); }
### Question: VehicleTypeImpl implements VehicleType { @Override public String getProfile() { return profile; } private VehicleTypeImpl(VehicleTypeImpl.Builder builder); @Override boolean equals(Object o); @Override int hashCode(); @Override Object getUserData(); @Override String getTypeId(); @Override VehicleTypeImpl.VehicleCostParams getVehicleCostParams(); @Override String toString(); @Override double getMaxVelocity(); @Override Capacity getCapacityDimensions(); @Override String getProfile(); }### Answer: @Test public void whenAddingProfile_itShouldBeCorrect() { VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setProfile("car").build(); assertEquals("car", type.getProfile()); }
### Question: VehicleTypeImpl implements VehicleType { @Override public Object getUserData() { return userData; } private VehicleTypeImpl(VehicleTypeImpl.Builder builder); @Override boolean equals(Object o); @Override int hashCode(); @Override Object getUserData(); @Override String getTypeId(); @Override VehicleTypeImpl.VehicleCostParams getVehicleCostParams(); @Override String toString(); @Override double getMaxVelocity(); @Override Capacity getCapacityDimensions(); @Override String getProfile(); }### Answer: @Test public void whenSettingUserData_itIsAssociatedWithTheVehicleType() { VehicleType one = VehicleTypeImpl.Builder.newInstance("type").setUserData(new HashMap<String, Object>()) .build(); VehicleType two = VehicleTypeImpl.Builder.newInstance("type").setUserData(42).build(); VehicleType three = VehicleTypeImpl.Builder.newInstance("type").build(); assertTrue(one.getUserData() instanceof Map); assertEquals(42, two.getUserData()); assertNull(three.getUserData()); }
### Question: JobInsertionContext { public VehicleRoute getRoute() { return route; } JobInsertionContext(VehicleRoute route, Job job, Vehicle newVehicle, Driver newDriver, double newDepTime); VehicleRoute getRoute(); Job getJob(); Vehicle getNewVehicle(); Driver getNewDriver(); double getNewDepTime(); List<TourActivity> getAssociatedActivities(); void setRelatedActivityContext(ActivityContext relatedActivityContext); ActivityContext getRelatedActivityContext(); void setActivityContext(ActivityContext activityContext); ActivityContext getActivityContext(); }### Answer: @Test public void routeShouldBeAssigned() { assertEquals(route, context.getRoute()); }
### Question: JobInsertionContext { public Job getJob() { return job; } JobInsertionContext(VehicleRoute route, Job job, Vehicle newVehicle, Driver newDriver, double newDepTime); VehicleRoute getRoute(); Job getJob(); Vehicle getNewVehicle(); Driver getNewDriver(); double getNewDepTime(); List<TourActivity> getAssociatedActivities(); void setRelatedActivityContext(ActivityContext relatedActivityContext); ActivityContext getRelatedActivityContext(); void setActivityContext(ActivityContext activityContext); ActivityContext getActivityContext(); }### Answer: @Test public void jobShouldBeAssigned() { assertEquals(job, context.getJob()); }
### Question: JobInsertionContext { public Vehicle getNewVehicle() { return newVehicle; } JobInsertionContext(VehicleRoute route, Job job, Vehicle newVehicle, Driver newDriver, double newDepTime); VehicleRoute getRoute(); Job getJob(); Vehicle getNewVehicle(); Driver getNewDriver(); double getNewDepTime(); List<TourActivity> getAssociatedActivities(); void setRelatedActivityContext(ActivityContext relatedActivityContext); ActivityContext getRelatedActivityContext(); void setActivityContext(ActivityContext activityContext); ActivityContext getActivityContext(); }### Answer: @Test public void vehicleShouldBeAssigned() { assertEquals(vehicle, context.getNewVehicle()); }
### Question: JobInsertionContext { public Driver getNewDriver() { return newDriver; } JobInsertionContext(VehicleRoute route, Job job, Vehicle newVehicle, Driver newDriver, double newDepTime); VehicleRoute getRoute(); Job getJob(); Vehicle getNewVehicle(); Driver getNewDriver(); double getNewDepTime(); List<TourActivity> getAssociatedActivities(); void setRelatedActivityContext(ActivityContext relatedActivityContext); ActivityContext getRelatedActivityContext(); void setActivityContext(ActivityContext activityContext); ActivityContext getActivityContext(); }### Answer: @Test public void driverShouldBeAssigned() { assertEquals(driver, context.getNewDriver()); }
### Question: JobInsertionContext { public double getNewDepTime() { return newDepTime; } JobInsertionContext(VehicleRoute route, Job job, Vehicle newVehicle, Driver newDriver, double newDepTime); VehicleRoute getRoute(); Job getJob(); Vehicle getNewVehicle(); Driver getNewDriver(); double getNewDepTime(); List<TourActivity> getAssociatedActivities(); void setRelatedActivityContext(ActivityContext relatedActivityContext); ActivityContext getRelatedActivityContext(); void setActivityContext(ActivityContext activityContext); ActivityContext getActivityContext(); }### Answer: @Test public void depTimeShouldBeAssigned() { assertEquals(0., context.getNewDepTime(), 0.001); }
### Question: JobInsertionContext { public List<TourActivity> getAssociatedActivities() { return associatedActivities; } JobInsertionContext(VehicleRoute route, Job job, Vehicle newVehicle, Driver newDriver, double newDepTime); VehicleRoute getRoute(); Job getJob(); Vehicle getNewVehicle(); Driver getNewDriver(); double getNewDepTime(); List<TourActivity> getAssociatedActivities(); void setRelatedActivityContext(ActivityContext relatedActivityContext); ActivityContext getRelatedActivityContext(); void setActivityContext(ActivityContext activityContext); ActivityContext getActivityContext(); }### Answer: @Test public void relatedActivitiesShouldBeAssigned() { context.getAssociatedActivities().add(mock(TourActivity.class)); context.getAssociatedActivities().add(mock(TourActivity.class)); assertEquals(2, context.getAssociatedActivities().size()); }
### Question: Location implements HasIndex, HasId { public static Location newInstance(double x, double y) { return Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(x, y)).build(); } private Location(Builder builder); static Location newInstance(double x, double y); static Location newInstance(String id); static Location newInstance(int index); Object getUserData(); @Override String getId(); @Override int getIndex(); Coordinate getCoordinate(); String getName(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); final static int NO_INDEX; }### Answer: @Test(expected = IllegalArgumentException.class) public void whenIndexSmallerZero_throwException() { Location l = Location.Builder.newInstance().setIndex(-1).build(); } @Test(expected = IllegalArgumentException.class) public void whenCoordinateAndIdAndIndexNotSet_throwException() { Location l = Location.Builder.newInstance().build(); }
### Question: VehicleRoutingProblem { public FleetSize getFleetSize() { return fleetSize; } private VehicleRoutingProblem(Builder builder); @Override String toString(); FleetSize getFleetSize(); Map<String, Job> getJobs(); Collection<Job> getJobsWithLocation(); Map<String, Job> getJobsInclusiveInitialJobsInRoutes(); Collection<VehicleRoute> getInitialVehicleRoutes(); Collection<VehicleType> getTypes(); Collection<Vehicle> getVehicles(); VehicleRoutingTransportCosts getTransportCosts(); VehicleRoutingActivityCosts getActivityCosts(); Collection<Location> getAllLocations(); List<AbstractActivity> getActivities(Job job); int getNuActivities(); JobActivityFactory getJobActivityFactory(); List<AbstractActivity> copyAndGetActivities(Job job); }### Answer: @Test public void whenBuildingWithInfiniteFleet_fleetSizeShouldBeInfinite() { VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance(); builder.setFleetSize(FleetSize.INFINITE); VehicleRoutingProblem vrp = builder.build(); assertEquals(FleetSize.INFINITE, vrp.getFleetSize()); } @Test public void whenBuildingWithFiniteFleet_fleetSizeShouldBeFinite() { VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance(); builder.setFleetSize(FleetSize.FINITE); VehicleRoutingProblem vrp = builder.build(); assertEquals(FleetSize.FINITE, vrp.getFleetSize()); }
### Question: VehicleRoutingProblem { public Collection<Vehicle> getVehicles() { return Collections.unmodifiableCollection(vehicles); } private VehicleRoutingProblem(Builder builder); @Override String toString(); FleetSize getFleetSize(); Map<String, Job> getJobs(); Collection<Job> getJobsWithLocation(); Map<String, Job> getJobsInclusiveInitialJobsInRoutes(); Collection<VehicleRoute> getInitialVehicleRoutes(); Collection<VehicleType> getTypes(); Collection<Vehicle> getVehicles(); VehicleRoutingTransportCosts getTransportCosts(); VehicleRoutingActivityCosts getActivityCosts(); Collection<Location> getAllLocations(); List<AbstractActivity> getActivities(Job job); int getNuActivities(); JobActivityFactory getJobActivityFactory(); List<AbstractActivity> copyAndGetActivities(Job job); }### Answer: @Test public void whenAddingFourVehiclesAllAtOnce_vrpShouldContainTheCorrectNuOfVehicles() { VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance(); VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setStartLocation(Location.newInstance("start")).build(); VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocation(Location.newInstance("start")).build(); VehicleImpl v3 = VehicleImpl.Builder.newInstance("v3").setStartLocation(Location.newInstance("start")).build(); VehicleImpl v4 = VehicleImpl.Builder.newInstance("v4").setStartLocation(Location.newInstance("start")).build(); builder.addAllVehicles(Arrays.asList(v1, v2, v3, v4)); VehicleRoutingProblem vrp = builder.build(); assertEquals(4, vrp.getVehicles().size()); }
### Question: VehicleRoutingProblem { public Collection<VehicleType> getTypes() { return Collections.unmodifiableCollection(vehicleTypes); } private VehicleRoutingProblem(Builder builder); @Override String toString(); FleetSize getFleetSize(); Map<String, Job> getJobs(); Collection<Job> getJobsWithLocation(); Map<String, Job> getJobsInclusiveInitialJobsInRoutes(); Collection<VehicleRoute> getInitialVehicleRoutes(); Collection<VehicleType> getTypes(); Collection<Vehicle> getVehicles(); VehicleRoutingTransportCosts getTransportCosts(); VehicleRoutingActivityCosts getActivityCosts(); Collection<Location> getAllLocations(); List<AbstractActivity> getActivities(Job job); int getNuActivities(); JobActivityFactory getJobActivityFactory(); List<AbstractActivity> copyAndGetActivities(Job job); }### Answer: @Test public void whenBuildingWithFourVehiclesAndTwoTypes_vrpShouldContainTheCorrectNuOfTypes() { VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type1").build(); VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("type2").build(); VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setStartLocation(Location.newInstance("yo")).setType(type1).build(); VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocation(Location.newInstance("yo")).setType(type1).build(); VehicleImpl v3 = VehicleImpl.Builder.newInstance("v3").setStartLocation(Location.newInstance("yo")).setType(type2).build(); VehicleImpl v4 = VehicleImpl.Builder.newInstance("v4").setStartLocation(Location.newInstance("yo")).setType(type2).build(); builder.addVehicle(v1).addVehicle(v2).addVehicle(v3).addVehicle(v4); VehicleRoutingProblem vrp = builder.build(); assertEquals(2, vrp.getTypes().size()); }
### Question: VehicleRoutingProblem { public VehicleRoutingActivityCosts getActivityCosts() { return activityCosts; } private VehicleRoutingProblem(Builder builder); @Override String toString(); FleetSize getFleetSize(); Map<String, Job> getJobs(); Collection<Job> getJobsWithLocation(); Map<String, Job> getJobsInclusiveInitialJobsInRoutes(); Collection<VehicleRoute> getInitialVehicleRoutes(); Collection<VehicleType> getTypes(); Collection<Vehicle> getVehicles(); VehicleRoutingTransportCosts getTransportCosts(); VehicleRoutingActivityCosts getActivityCosts(); Collection<Location> getAllLocations(); List<AbstractActivity> getActivities(Job job); int getNuActivities(); JobActivityFactory getJobActivityFactory(); List<AbstractActivity> copyAndGetActivities(Job job); }### Answer: @Test public void whenSettingActivityCosts_vrpShouldContainIt() { VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance(); builder.setActivityCosts(new VehicleRoutingActivityCosts() { @Override public double getActivityCost(TourActivity tourAct, double arrivalTime, Driver driver, Vehicle vehicle) { return 4.0; } @Override public double getActivityDuration(TourActivity tourAct, double arrivalTime, Driver driver, Vehicle vehicle) { return tourAct.getOperationTime(); } }); VehicleRoutingProblem problem = builder.build(); assertEquals(4.0, problem.getActivityCosts().getActivityCost(null, 0.0, null, null), 0.01); }
### Question: VehicleRoutingProblem { public VehicleRoutingTransportCosts getTransportCosts() { return transportCosts; } private VehicleRoutingProblem(Builder builder); @Override String toString(); FleetSize getFleetSize(); Map<String, Job> getJobs(); Collection<Job> getJobsWithLocation(); Map<String, Job> getJobsInclusiveInitialJobsInRoutes(); Collection<VehicleRoute> getInitialVehicleRoutes(); Collection<VehicleType> getTypes(); Collection<Vehicle> getVehicles(); VehicleRoutingTransportCosts getTransportCosts(); VehicleRoutingActivityCosts getActivityCosts(); Collection<Location> getAllLocations(); List<AbstractActivity> getActivities(Job job); int getNuActivities(); JobActivityFactory getJobActivityFactory(); List<AbstractActivity> copyAndGetActivities(Job job); }### Answer: @Test public void whenSettingRoutingCosts_vprShouldContainIt() { VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance(); builder.setRoutingCost(new AbstractForwardVehicleRoutingTransportCosts() { @Override public double getDistance(Location from, Location to, double departureTime, Vehicle vehicle) { return 0; } @Override public double getTransportTime(Location from, Location to, double departureTime, Driver driver, Vehicle vehicle) { return 0; } @Override public double getTransportCost(Location from, Location to, double departureTime, Driver driver, Vehicle vehicle) { return 4.0; } }); VehicleRoutingProblem problem = builder.build(); assertEquals(4.0, problem.getTransportCosts().getTransportCost(loc(""), loc(""), 0.0, null, null), 0.01); }
### Question: VehicleRoutingProblem { public Collection<VehicleRoute> getInitialVehicleRoutes() { Collection<VehicleRoute> copiedInitialRoutes = new ArrayList<>(); for (VehicleRoute route : initialVehicleRoutes) { copiedInitialRoutes.add(VehicleRoute.copyOf(route)); } return copiedInitialRoutes; } private VehicleRoutingProblem(Builder builder); @Override String toString(); FleetSize getFleetSize(); Map<String, Job> getJobs(); Collection<Job> getJobsWithLocation(); Map<String, Job> getJobsInclusiveInitialJobsInRoutes(); Collection<VehicleRoute> getInitialVehicleRoutes(); Collection<VehicleType> getTypes(); Collection<Vehicle> getVehicles(); VehicleRoutingTransportCosts getTransportCosts(); VehicleRoutingActivityCosts getActivityCosts(); Collection<Location> getAllLocations(); List<AbstractActivity> getActivities(Job job); int getNuActivities(); JobActivityFactory getJobActivityFactory(); List<AbstractActivity> copyAndGetActivities(Job job); }### Answer: @Test public void whenAddingInitialRoute_itShouldBeAddedCorrectly() { VehicleImpl vehicle = VehicleImpl.Builder.newInstance("v") .setStartLocation(Location.newInstance("start")).setEndLocation(Location.newInstance("end")).build(); VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle, DriverImpl.noDriver()).build(); VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); vrpBuilder.addInitialVehicleRoute(route); VehicleRoutingProblem vrp = vrpBuilder.build(); assertTrue(!vrp.getInitialVehicleRoutes().isEmpty()); }
### Question: Capacity { public int getNuOfDimensions() { return dimensions.length; } private Capacity(Capacity capacity); private Capacity(Builder builder); static Capacity addup(Capacity cap1, Capacity cap2); static Capacity subtract(Capacity cap, Capacity cap2subtract); static Capacity invert(Capacity cap2invert); static double divide(Capacity numerator, Capacity denominator); static Capacity copyOf(Capacity capacity); int getNuOfDimensions(); int get(int index); boolean isLessOrEqual(Capacity toCompare); boolean isGreaterOrEqual(Capacity toCompare); @Override String toString(); static Capacity max(Capacity cap1, Capacity cap2); static Capacity min(Capacity cap1, Capacity cap2); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void whenSettingSimplyOneCapDimension_nuOfDimensionMustBeCorrect() { Capacity.Builder capBuilder = Capacity.Builder.newInstance(); capBuilder.addDimension(0, 4); Capacity cap = capBuilder.build(); assertEquals(1, cap.getNuOfDimensions()); } @Test public void whenSettingTwoCapDimension_nuOfDimensionMustBeCorrect() { Capacity.Builder capBuilder = Capacity.Builder.newInstance(); capBuilder.addDimension(0, 4); capBuilder.addDimension(1, 10); Capacity cap = capBuilder.build(); assertEquals(2, cap.getNuOfDimensions()); } @Test public void whenSettingRandomNuOfCapDimension_nuOfDimensionMustBeCorrect() { Random rand = new Random(); int nuOfCapDimensions = 1 + rand.nextInt(100); Capacity.Builder capBuilder = Capacity.Builder.newInstance(); capBuilder.addDimension(nuOfCapDimensions - 1, 4); Capacity cap = capBuilder.build(); assertEquals(nuOfCapDimensions, cap.getNuOfDimensions()); }
### Question: Capacity { public int get(int index) { if (index < dimensions.length) return dimensions[index]; return 0; } private Capacity(Capacity capacity); private Capacity(Builder builder); static Capacity addup(Capacity cap1, Capacity cap2); static Capacity subtract(Capacity cap, Capacity cap2subtract); static Capacity invert(Capacity cap2invert); static double divide(Capacity numerator, Capacity denominator); static Capacity copyOf(Capacity capacity); int getNuOfDimensions(); int get(int index); boolean isLessOrEqual(Capacity toCompare); boolean isGreaterOrEqual(Capacity toCompare); @Override String toString(); static Capacity max(Capacity cap1, Capacity cap2); static Capacity min(Capacity cap1, Capacity cap2); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void whenSettingOneDimValue_valueMustBeCorrect() { Capacity.Builder capBuilder = Capacity.Builder.newInstance(); capBuilder.addDimension(0, 4); Capacity cap = capBuilder.build(); assertEquals(4, cap.get(0)); } @Test public void whenGettingIndexWhichIsHigherThanNuOfCapDimensions_itShouldReturn0() { Capacity.Builder capBuilder = Capacity.Builder.newInstance(); capBuilder.addDimension(0, 4); Capacity cap = capBuilder.build(); assertEquals(0, cap.get(2)); }
### Question: Capacity { public static Capacity copyOf(Capacity capacity) { if (capacity == null) return null; return new Capacity(capacity); } private Capacity(Capacity capacity); private Capacity(Builder builder); static Capacity addup(Capacity cap1, Capacity cap2); static Capacity subtract(Capacity cap, Capacity cap2subtract); static Capacity invert(Capacity cap2invert); static double divide(Capacity numerator, Capacity denominator); static Capacity copyOf(Capacity capacity); int getNuOfDimensions(); int get(int index); boolean isLessOrEqual(Capacity toCompare); boolean isGreaterOrEqual(Capacity toCompare); @Override String toString(); static Capacity max(Capacity cap1, Capacity cap2); static Capacity min(Capacity cap1, Capacity cap2); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void whenCopyingNull_itShouldReturnNull() { Capacity nullCap = Capacity.copyOf(null); assertTrue(nullCap == null); }
### Question: Capacity { public static Capacity addup(Capacity cap1, Capacity cap2) { if (cap1 == null || cap2 == null) throw new NullPointerException("arguments must not be null"); Capacity.Builder capacityBuilder = Capacity.Builder.newInstance(); for (int i = 0; i < Math.max(cap1.getNuOfDimensions(), cap2.getNuOfDimensions()); i++) { capacityBuilder.addDimension(i, cap1.get(i) + cap2.get(i)); } return capacityBuilder.build(); } private Capacity(Capacity capacity); private Capacity(Builder builder); static Capacity addup(Capacity cap1, Capacity cap2); static Capacity subtract(Capacity cap, Capacity cap2subtract); static Capacity invert(Capacity cap2invert); static double divide(Capacity numerator, Capacity denominator); static Capacity copyOf(Capacity capacity); int getNuOfDimensions(); int get(int index); boolean isLessOrEqual(Capacity toCompare); boolean isGreaterOrEqual(Capacity toCompare); @Override String toString(); static Capacity max(Capacity cap1, Capacity cap2); static Capacity min(Capacity cap1, Capacity cap2); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test(expected = NullPointerException.class) public void whenOneOfArgsIsNullWhenAdding_itShouldThrowException() { Capacity cap1 = Capacity.Builder.newInstance().addDimension(0, 1).addDimension(1, 2).build(); @SuppressWarnings("unused") Capacity result = Capacity.addup(cap1, null); }
### Question: Capacity { public static Capacity subtract(Capacity cap, Capacity cap2subtract) { if (cap == null || cap2subtract == null) throw new NullPointerException("arguments must not be null"); Capacity.Builder capacityBuilder = Capacity.Builder.newInstance(); for (int i = 0; i < Math.max(cap.getNuOfDimensions(), cap2subtract.getNuOfDimensions()); i++) { int dimValue = cap.get(i) - cap2subtract.get(i); capacityBuilder.addDimension(i, dimValue); } return capacityBuilder.build(); } private Capacity(Capacity capacity); private Capacity(Builder builder); static Capacity addup(Capacity cap1, Capacity cap2); static Capacity subtract(Capacity cap, Capacity cap2subtract); static Capacity invert(Capacity cap2invert); static double divide(Capacity numerator, Capacity denominator); static Capacity copyOf(Capacity capacity); int getNuOfDimensions(); int get(int index); boolean isLessOrEqual(Capacity toCompare); boolean isGreaterOrEqual(Capacity toCompare); @Override String toString(); static Capacity max(Capacity cap1, Capacity cap2); static Capacity min(Capacity cap1, Capacity cap2); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test(expected = NullPointerException.class) public void whenOneOfArgsIsNullWhenSubtracting_itShouldThrowException() { Capacity cap1 = Capacity.Builder.newInstance().addDimension(0, 1).addDimension(1, 2).build(); @SuppressWarnings("unused") Capacity result = Capacity.subtract(cap1, null); }
### Question: Capacity { @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Capacity)) return false; Capacity capacity = (Capacity) o; return Arrays.equals(dimensions, capacity.dimensions); } private Capacity(Capacity capacity); private Capacity(Builder builder); static Capacity addup(Capacity cap1, Capacity cap2); static Capacity subtract(Capacity cap, Capacity cap2subtract); static Capacity invert(Capacity cap2invert); static double divide(Capacity numerator, Capacity denominator); static Capacity copyOf(Capacity capacity); int getNuOfDimensions(); int get(int index); boolean isLessOrEqual(Capacity toCompare); boolean isGreaterOrEqual(Capacity toCompare); @Override String toString(); static Capacity max(Capacity cap1, Capacity cap2); static Capacity min(Capacity cap1, Capacity cap2); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldBeEqual(){ Capacity cap1 = Capacity.Builder.newInstance().build(); Capacity cap2 = Capacity.Builder.newInstance().build(); Assert.assertTrue(cap1.equals(cap2)); } @Test public void shouldBeEqual2(){ Capacity cap1 = Capacity.Builder.newInstance().addDimension(0,10).addDimension(1,100).addDimension(2,1000).build(); Capacity cap2 = Capacity.Builder.newInstance().addDimension(0,10).addDimension(2, 1000).addDimension(1,100).build(); Assert.assertTrue(cap1.equals(cap2)); }
### Question: Shipment extends AbstractJob { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Shipment other = (Shipment) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } Shipment(Builder builder); @Override String getId(); Location getPickupLocation(); double getPickupServiceTime(); Location getDeliveryLocation(); double getDeliveryServiceTime(); TimeWindow getDeliveryTimeWindow(); Collection<TimeWindow> getDeliveryTimeWindows(); TimeWindow getPickupTimeWindow(); Collection<TimeWindow> getPickupTimeWindows(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Capacity getSize(); @Override Skills getRequiredSkills(); @Override String getName(); @Override int getPriority(); @Override double getMaxTimeInVehicle(); @Override List<Activity> getActivities(); }### Answer: @Test public void whenTwoShipmentsHaveTheSameId_theyShouldBeEqual() { Shipment one = Shipment.Builder.newInstance("s").addSizeDimension(0, 10).setPickupLocation(Location.Builder.newInstance().setId("foo").build()). setDeliveryLocation(TestUtils.loc("foofoo")).setPickupServiceTime(10).setDeliveryServiceTime(20).build(); Shipment two = Shipment.Builder.newInstance("s").addSizeDimension(0, 10).setPickupLocation(Location.Builder.newInstance().setId("foo").build()). setDeliveryLocation(TestUtils.loc("foofoo")).setPickupServiceTime(10).setDeliveryServiceTime(20).build(); assertTrue(one.equals(two)); }