src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public Location getLastLocation(LostApiClient client) { throwIfNotConnected(client); try { return service.getLastLocation(); } catch (RemoteException e) { throw new RuntimeException(e); } } Fu...
@Test public void getLastLocation_shouldCallService() throws Exception { api.getLastLocation(connectedClient); verify(service).getLastLocation(); }
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public LocationAvailability getLocationAvailability(LostApiClient client) { throwIfNotConnected(client); try { return service.getLocationAvailability(); } catch (RemoteException e) { throw new...
@Test public void getLocationAvailability_shouldCallService() throws Exception { api.getLocationAvailability(connectedClient); verify(service).getLocationAvailability(); }
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener) { throwIfNotConnected(client); LostClientManager.shared().addListe...
@Test public void requestLocationUpdates_listener_shouldCallService() throws Exception { LocationRequest request = LocationRequest.create(); LocationListener listener = new TestLocationListener(); api.requestLocationUpdates(connectedClient, request, listener); verify(service).requestLocationUpdates(request); } @Test pu...
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationListener listener) { throwIfNotConnected(client); boolean hasResult = LostClientManager.shared().removeListener...
@Test public void removeLocationUpdates_listener_shouldCallService() throws Exception { LocationListener listener = new TestLocationListener(); api.removeLocationUpdates(connectedClient, listener); verify(service).removeLocationUpdates(); } @Test public void removeLocationUpdates_pendingIntent_shouldCallService() throw...
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode) { throwIfNotConnected(client); try { service.setMockMode(isMockMode); } catch (RemoteException e) { throw new...
@Test public void setMockMode_shouldCallService() throws Exception { api.setMockMode(connectedClient, true); verify(service).setMockMode(true); } @Test public void setMockMode_shouldReturnFusedLocationPendingResult() { PendingResult<Status> result = api.setMockMode(connectedClient, true); assertThat(result.await().getS...
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public PendingResult<Status> setMockLocation(LostApiClient client, Location mockLocation) { throwIfNotConnected(client); try { service.setMockLocation(mockLocation); } catch (RemoteException e...
@Test public void setMockLocation_shouldCallService() throws Exception { Location location = new Location("test"); api.setMockLocation(connectedClient, location); verify(service).setMockLocation(location); } @Test public void setMockLocation_shouldReturnFusedLocationPendingResult() { PendingResult<Status> result = api....
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public PendingResult<Status> setMockTrace(LostApiClient client, String path, String filename) { throwIfNotConnected(client); try { service.setMockTrace(path, filename); } catch (RemoteExceptio...
@Test public void setMockTrace_shouldCallService() throws Exception { api.setMockTrace(connectedClient, "path", "name"); verify(service).setMockTrace("path", "name"); } @Test public void setMockTrace_shouldReturnFusedLocationPendingResult() { PendingResult<Status> result = api.setMockTrace(connectedClient, "path", "nam...
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public void onConnect(Context context) { this.context = context; final Intent intent = new Intent(context, FusedLocationProviderService.class); context.bindService(intent, this, Context.BIND_A...
@Test public void onConnect_shouldStartService() throws Exception { Context context = mock(Context.class); api.onConnect(context); verify(context).startService(new Intent(context, FusedLocationProviderService.class)); } @Test public void onConnect_shouldBindService() throws Exception { Context context = mock(Context.cl...
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public void onServiceConnected(IBinder binder) { service = IFusedLocationProviderService.Stub.asInterface(binder); isBound = true; registerRemoteCallback(); } FusedLocationProviderApiImpl(Fuse...
@Test public void onServiceConnected_shouldRegisterServiceCallbacks() throws Exception { TestServiceStub binder = new TestServiceStub(); api.onServiceConnected(binder); assertThat(binder.callback).isNotNull(); }
FusionEngine extends LocationEngine implements LocationListener { @Override public Location getLastLocation() { final List<String> providers = locationManager.getAllProviders(); final long minTime = clock.getCurrentTimeInMillis() - RECENT_UPDATE_THRESHOLD_IN_MILLIS; Location bestLocation = null; float bestAccuracy = Fl...
@Test public void getLastLocation_shouldReturnNullIfNoLocationAvailable() throws Exception { assertThat(fusionEngine.getLastLocation()).isNull(); } @Test public void getLastLocation_shouldReturnGpsLocationIfOnlyProvider() throws Exception { Location location = new Location(GPS_PROVIDER); shadowLocationManager.setLastKn...
FusionEngine extends LocationEngine implements LocationListener { public static boolean isBetterThan(Location locationA, Location locationB) { if (locationA == null) { return false; } if (locationB == null) { return true; } if (SystemClock.getTimeInNanos(locationA) > SystemClock.getTimeInNanos(locationB) + RECENT_UPDAT...
@Test public void isBetterThan_shouldReturnFalseIfLocationAIsNull() throws Exception { Location locationA = null; Location locationB = new Location("test"); assertThat(FusionEngine.isBetterThan(locationA, locationB)).isFalse(); } @Test public void isBetterThan_shouldReturnTrueIfLocationBIsNull() throws Exception { Loca...
FusedLocationProviderServiceDelegate implements LocationEngine.Callback { public Location getLastLocation() { return locationEngine.getLastLocation(); } FusedLocationProviderServiceDelegate(Context context); void init(IFusedLocationProviderCallback callback); Location getLastLocation(); @RequiresPermission(anyOf = {ACC...
@Test public void getLastLocation_shouldReturnMostRecentLocation() throws Exception { Location location = new Location(GPS_PROVIDER); shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, location); assertThat(delegate.getLastLocation()).isNotNull(); }
FusedLocationProviderServiceDelegate implements LocationEngine.Callback { public void requestLocationUpdates(LocationRequest request) { locationEngine.setRequest(request); } FusedLocationProviderServiceDelegate(Context context); void init(IFusedLocationProviderCallback callback); Location getLastLocation(); @RequiresPe...
@Test public void requestLocationUpdates_shouldRegisterGpsAndNetworkListener() throws Exception { delegate.requestLocationUpdates(LocationRequest.create().setPriority(PRIORITY_HIGH_ACCURACY)); assertThat(shadowLocationManager.getRequestLocationUpdateListeners()).hasSize(2); } @Test public void requestLocationUpdates_sh...
FusedLocationProviderServiceDelegate implements LocationEngine.Callback { @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) public LocationAvailability getLocationAvailability() { return locationEngine.createLocationAvailability(); } FusedLocationProviderServiceDelegate(Context context); void ...
@Test public void getLocationAvailability_gps_network_shouldBeAvailable() { shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true); shadowLocationManager.setProviderEnabled(NETWORK_PROVIDER, true); Location location = new Location("test"); shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, location); Locati...
SystemClock implements Clock { public static long getTimeInNanos(Location location) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { return location.getElapsedRealtimeNanos(); } return location.getTime() * MS_TO_NS; } @Override long getCurrentTimeInMillis(); static long getTimeInNanos(Location loca...
@Test @Config(sdk = 17) public void getTimeInNanos_shouldReturnElapsedRealtimeNanosForSdk17AndUp() throws Exception { final long nanos = 1000000; final Location location = new Location("mock"); location.setElapsedRealtimeNanos(nanos); assertThat(SystemClock.getTimeInNanos(location)).isEqualTo(nanos); } @Test @Config(sd...
ResourceUtil { public static InputStream getResourceAsStream(String path) { if (StrUtil.startWithIgnoreCase(path, CLASSPATH_PRE)) { path = path.substring(CLASSPATH_PRE.length()); } return getClassLoader().getResourceAsStream(path); } static String getAbsolutePath(String path); static URL getResource(String path); stat...
@Test public void getResourceAsStreamTest() { InputStream resourceAsStream = ResourceUtil.getResourceAsStream("classpath:config/tio-quartz.properties"); Assert.assertNotNull(resourceAsStream); try { resourceAsStream.close(); } catch (IOException e) { } }
ByteKit { public static byte[][] split(byte[] raw, int partSize) { int length = raw.length % partSize == 0 ? raw.length / partSize : ((int) (raw.length / partSize)) + 1; byte[][] parts = new byte[length][]; int start = 0; for (int i = 0; i < length; i++) { int end = Integer.min(raw.length, start + partSize); parts[i] =...
@Test public void split() { byte[] bytes1 = new byte[12781]; for (int i = 0; i < bytes1.length; i++) { bytes1[i] = (byte) (256 * Math.random()); } byte[][] parts1 = ByteKit.split(bytes1, 1); assertEquals(parts1.length, bytes1.length); Byte[] combine1 = Arrays.stream(parts1).map(it -> it[0]).toArray(Byte[]::new); for (i...
UnifiedDiffWriter { public static void write(UnifiedDiff diff, Function<String, List<String>> originalLinesProvider, Writer writer, int contextSize) throws IOException { Objects.requireNonNull(originalLinesProvider, "original lines provider needs to be specified"); write(diff, originalLinesProvider, line -> { try { wri...
@Test public void testWrite() throws URISyntaxException, IOException { String str = readFile(UnifiedDiffReaderTest.class.getResource("jsqlparser_patch_1.diff").toURI(), Charset.defaultCharset()); UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff(new ByteArrayInputStream(str.getBytes())); StringWriter writer = new S...
UnifiedDiffReader { public static UnifiedDiff parseUnifiedDiff(InputStream stream) throws IOException, UnifiedDiffParserException { UnifiedDiffReader parser = new UnifiedDiffReader(new BufferedReader(new InputStreamReader(stream))); return parser.parse(); } UnifiedDiffReader(Reader reader); static UnifiedDiff parseUnif...
@Test public void testParseIssue85() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue85.diff")); assertThat(diff.getFiles().size()).isEqualTo(1); assertEquals(1, diff.getFiles().size()); final UnifiedDiffFile file1 = diff.get...
StringUtils { public static String htmlEntites(String str) { return str.replace("<", "&lt;").replace(">", "&gt;"); } private StringUtils(); static String htmlEntites(String str); static String normalize(String str); static List<String> wrapText(List<String> list, int columnWidth); static String wrapText(String line, i...
@Test public void testHtmlEntites() { assertEquals("&lt;test&gt;", StringUtils.htmlEntites("<test>")); }
StringUtils { public static String normalize(String str) { return htmlEntites(str).replace("\t", " "); } private StringUtils(); static String htmlEntites(String str); static String normalize(String str); static List<String> wrapText(List<String> list, int columnWidth); static String wrapText(String line, int columnWid...
@Test public void testNormalize_String() { assertEquals(" test", StringUtils.normalize("\ttest")); }
StringUtils { public static List<String> wrapText(List<String> list, int columnWidth) { return list.stream() .map(line -> wrapText(line, columnWidth)) .collect(toList()); } private StringUtils(); static String htmlEntites(String str); static String normalize(String str); static List<String> wrapText(List<String> list,...
@Test public void testWrapText_String_int() { assertEquals("te<br/>st", StringUtils.wrapText("test", 2)); assertEquals("tes<br/>t", StringUtils.wrapText("test", 3)); assertEquals("test", StringUtils.wrapText("test", 10)); } @Test public void testWrapText_String_int_zero() { Assertions.assertThrows(IllegalArgumentExcept...
DiffRowGenerator { protected final static List<String> splitStringPreserveDelimiter(String str, Pattern SPLIT_PATTERN) { List<String> list = new ArrayList<>(); if (str != null) { Matcher matcher = SPLIT_PATTERN.matcher(str); int pos = 0; while (matcher.find()) { if (pos < matcher.start()) { list.add(str.substring(pos, ...
@Test public void testSplitString() { List<String> list = DiffRowGenerator.splitStringPreserveDelimiter("test,test2", DiffRowGenerator.SPLIT_BY_WORD_PATTERN); assertEquals(3, list.size()); assertEquals("[test, ,, test2]", list.toString()); } @Test public void testSplitString2() { List<String> list = DiffRowGenerator.sp...
Patch { public Patch() { this(10); } Patch(); Patch(int estimatedPatchSize); List<T> applyTo(List<T> target); List<T> restore(List<T> target); void addDelta(AbstractDelta<T> delta); List<AbstractDelta<T>> getDeltas(); @Override String toString(); static Patch<T> generate(List<T> original, List<T> revised, List<Change>...
@Test public void testPatch_Insert() { final List<String> insertTest_from = Arrays.asList("hhh"); final List<String> insertTest_to = Arrays.asList("hhh", "jjj", "kkk", "lll"); final Patch<String> patch = DiffUtils.diff(insertTest_from, insertTest_to); try { assertEquals(insertTest_to, DiffUtils.patch(insertTest_from, p...
MyersDiff implements DiffAlgorithmI<T> { @Override public List<Change> computeDiff(final List<T> source, final List<T> target, DiffAlgorithmListener progress) { Objects.requireNonNull(source, "source list must not be null"); Objects.requireNonNull(target, "target list must not be null"); if (progress != null) { progres...
@Test public void testDiffMyersExample1Forward() { List<String> original = Arrays.asList("A", "B", "C", "A", "B", "B", "A"); List<String> revised = Arrays.asList("C", "B", "A", "B", "A", "C"); final Patch<String> patch = Patch.generate(original, revised, new MyersDiff<String>().computeDiff(original, revised, null)); as...
DiffUtils { public static <T> Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmListener progress) { return DiffUtils.diff(original, revised, new MyersDiff<>(), progress); } private DiffUtils(); static Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmListener progress); static Patch<T> diff(Li...
@Test public void testDiff_Insert() { final Patch<String> patch = DiffUtils.diff(Arrays.asList("hhh"), Arrays. asList("hhh", "jjj", "kkk")); assertNotNull(patch); assertEquals(1, patch.getDeltas().size()); final AbstractDelta<String> delta = patch.getDeltas().get(0); assertTrue(delta instanceof InsertDelta); assertEqua...
DiffUtils { public static Patch<String> diffInline(String original, String revised) { List<String> origList = new ArrayList<>(); List<String> revList = new ArrayList<>(); for (Character character : original.toCharArray()) { origList.add(character.toString()); } for (Character character : revised.toCharArray()) { revLis...
@Test public void testDiffInline() { final Patch<String> patch = DiffUtils.diffInline("", "test"); assertEquals(1, patch.getDeltas().size()); assertTrue(patch.getDeltas().get(0) instanceof InsertDelta); assertEquals(0, patch.getDeltas().get(0).getSource().getPosition()); assertEquals(0, patch.getDeltas().get(0).getSour...
UnifiedDiffReader { static String[] parseFileNames(String line) { String[] split = line.split(" "); return new String[]{ split[2].replaceAll("^a/", ""), split[3].replaceAll("^b/", "") }; } UnifiedDiffReader(Reader reader); static UnifiedDiff parseUnifiedDiff(InputStream stream); }
@Test public void testParseDiffBlock() { String[] files = UnifiedDiffReader.parseFileNames("diff --git a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java"); assertThat(files).containsExactly("src/test/java/net/sf/jsqlparser/statement/sel...
StringUtils { public static String wrapString(String str) { return wrapString(str, MAX_LENGTH); } static String StringAsHtmlWrapString(String string); static String wrapString(String str); static String wrapString(String str, int maxWidth); static List<String> wrap(String str, int maxWidth); static void wrapLineInto(S...
@Test public void testWrapString() { LOG.info("wrapString"); String str = "This filter is responsible to check whether the time difference between each pair of gps points contained by a gps track does not exceed a given threshold. if there is a pair of gps point where the time difference exceed the specified the track ...
Lex { public static void init(@NonNull Application app) { init(app, LexContext.OPEN_DELIMITER, LexContext.CLOSE_DELIMITER); } static void init(@NonNull Application app); static void init(@NonNull Application app, @NonNull String openDelimiter, @NonNull String closeDelimiter); @NonNull static UnparsedLexString say(@Str...
@Test(expected = LexAlreadyInitializedException.class) public void init_throwsException_onSecondInvocation() { Lex.init(RuntimeEnvironment.application); }
Lex { @NonNull public static UnparsedLexString say(@StringRes int resourceId) { checkState(); return say(resources.getString(resourceId)); } static void init(@NonNull Application app); static void init(@NonNull Application app, @NonNull String openDelimiter, @NonNull String closeDelimiter); @NonNull static UnparsedLex...
@Test public void into_setsTextViewValue() { TextView textView = new TextView(RuntimeEnvironment.application); Lex.say("This is {KEY_ONE}.").with(LexKey.KEY_ONE, "a test").into(textView); assertEquals("This is a test.", textView.getText().toString()); } @Test(expected = LexMissingKeyException.class) public void into_th...
Lex { @NonNull public static LexList list(@NonNull List<? extends CharSequence> items) { return list(items.toArray(new CharSequence[]{})); } static void init(@NonNull Application app); static void init(@NonNull Application app, @NonNull String openDelimiter, @NonNull String closeDelimiter); @NonNull static UnparsedLex...
@Test public void list_withListArg() { assertEquals("One Two Three", Lex .list(Arrays.asList("One", "Two", "Three")) .separator(" ") .makeString()); } @Test public void list_ofTwo_usesLastItemSeparator() { assertEquals("One, Two and Three", Lex.list("One", "Two", "Three") .separator(", ") .lastItemSeparator(" and ").ma...
IssuesReader { public List<PsIssue> read(final File file) throws Throwable { final List<PsIssue> issues = new LinkedList<>(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(new BOMInputStream(n...
@Test public void testReadMultipleIssues() throws Throwable { File file = temp.newFile("main", "results.xml"); FileUtils.copyURLToFile(getClass().getResource("/results/psanalyzer.xml"), file); List<PsIssue> issues = sut.read(file); Assert.assertEquals(4, issues.size()); } @Test public void testReadIssuesMapping() throw...
TokensReader { public Tokens read(final File file) throws Throwable { final Tokens tokens = new Tokens(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(new BOMInputStream(new FileInputStream(f...
@Test public void testReadMultipleIssues() throws Throwable { File file = temp.newFile("main", "results.xml"); FileUtils.copyURLToFile(getClass().getResource("/results/tokens.xml"), file); Tokens tokens = sut.read(file); Assert.assertEquals(76, tokens.getTokens().size()); } @Test public void testReadMapping() throws Th...
ScriptAnalyzerRulesDefinition implements RulesDefinition { public void define(final Context context) { final String repositoryKey = ScriptAnalyzerRulesDefinition.getRepositoryKeyForLanguage(); final String repositoryName = ScriptAnalyzerRulesDefinition.getRepositoryNameForLanguage(); defineRulesForLanguage(context, rep...
@Test public void testDefine() { Context t = new RulesDefinition.Context(); ScriptAnalyzerRulesDefinition def = new ScriptAnalyzerRulesDefinition(); def.define(t); Assert.assertEquals(1, t.repository(ScriptAnalyzerRulesDefinition.getRepositoryKeyForLanguage()).rules().size()); }
DictionaryLookup implements IStemmer, Iterable<WordData> { public static String applyReplacements(CharSequence word, LinkedHashMap<String, String> replacements) { StringBuilder sb = new StringBuilder(word); for (final Map.Entry<String, String> e : replacements.entrySet()) { String key = e.getKey(); int index = sb.index...
@Test public void testApplyReplacements() { LinkedHashMap<String, String> conversion = new LinkedHashMap<>(); conversion.put("'", "`"); conversion.put("fi", "fi"); conversion.put("\\a", "ą"); conversion.put("Barack", "George"); conversion.put("_", "xx"); assertEquals("filut", DictionaryLookup.applyReplacements("filut", c...
Speller { public List<String> getAllReplacements(final String str, final int fromIndex, final int level) { List<String> replaced = new ArrayList<>(); if (level > MAX_RECURSION_LEVEL) { replaced.add(str); return replaced; } StringBuilder sb = new StringBuilder(); sb.append(str); int index = MAX_WORD_LENGTH; String key =...
@Test public void testConcurrentReplacements() throws IOException { final URL url = getClass().getResource("dict-with-freq.dict"); final Speller spell = new Speller(Dictionary.read(url)); List<String> reps = spell.getAllReplacements("teached", 0, 0); assertTrue(reps.contains("teached")); assertTrue(reps.contains("taugh...
Speller { public boolean isMisspelled(final String word) { String wordToCheck = word; if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { wordToCheck = DictionaryLookup.applyReplacements(word, dictionaryMetadata.getInputConversionPairs()); } boolean isAlphabetic = wordToCheck.length() != 1 || isAlphabetic(wo...
@Test public void testIsMisspelled() throws IOException { final URL url = getClass().getResource("test-utf-spell.dict"); final Speller spell = new Speller(Dictionary.read(url)); assertTrue(!spell.isMisspelled("Paragraf22")); assertTrue(!spell.isMisspelled("!")); assertTrue(spell.isMisspelled("dziekie")); assertTrue(!sp...
Speller { public boolean isCamelCase(final String str) { return isNotEmpty(str) && !isAllUppercase(str) && isNotCapitalizedWord(str) && Character.isUpperCase(str.charAt(0)) && (!(str.length() > 1) || Character.isLowerCase(str.charAt(1))) && isNotAllLowercase(str); } Speller(final Dictionary dictionary); Speller(final ...
@Test public void testCamelCase() { final Speller spell = new Speller(dictionary, 1); assertTrue(spell.isCamelCase("CamelCase")); assertTrue(!spell.isCamelCase("Camel")); assertTrue(!spell.isCamelCase("CAMEL")); assertTrue(!spell.isCamelCase("camel")); assertTrue(!spell.isCamelCase("cAmel")); assertTrue(!spell.isCamelC...
Speller { boolean isNotCapitalizedWord(final String str) { if (isNotEmpty(str) && Character.isUpperCase(str.charAt(0))) { for (int i = 1; i < str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) && !Character.isLowerCase(c)) { return true; } } return false; } return true; } Speller(final Dictionary di...
@Test public void testCapitalizedWord() { final Speller spell = new Speller(dictionary, 1); assertTrue(spell.isNotCapitalizedWord("CamelCase")); assertTrue(!spell.isNotCapitalizedWord("Camel")); assertTrue(spell.isNotCapitalizedWord("CAMEL")); assertTrue(spell.isNotCapitalizedWord("camel")); assertTrue(spell.isNotCapit...
Speller { public ArrayList<String> findReplacements(String word) { final List<CandidateData> result = findReplacementCandidates(word); final ArrayList<String> resultSuggestions = new ArrayList<>(result.size()); for (CandidateData cd : result) { resultSuggestions.add(cd.getWord()); } return resultSuggestions; } Speller(...
@Test public void testReplacementsAndDistance2() throws Exception { final URL url = getClass().getResource("reps_dist2.dict"); final Speller speller = new Speller(Dictionary.read(url), 3); List<String> reps = speller.findReplacements("Rytmus"); assertTrue(reps.get(0).equals("Rhythmus")); assertTrue(reps.get(1).equals("...
HMatrix { public int get(final int i, final int j) { return p[(j - i + editDistance + 1) * rowLength + j]; } HMatrix(final int distance, final int maxLength); int get(final int i, final int j); void set(final int i, final int j, final int val); }
@Test public void stressTestInit() { for (int i = 0; i < 10; i++) { HMatrix H = new HMatrix(i, MAX_WORD_LENGTH); assertEquals(0, H.get(1, 1)); } }
FSACompile extends CliTool { @Override public ExitStatus call() throws Exception { final List<byte[]> sequences = binaryInput.readBinarySequences(input, (byte) '\n'); Collections.sort(sequences, FSABuilder.LEXICAL_ORDERING); FSA fsa = FSABuilder.build(sequences); FSASerializer serializer = format.getSerializer(); try (...
@Test @Repeat(iterations = 100) public void testCliInvocation() throws Exception { final Path input = newTempFile(); final Path output = newTempFile(); Set<String> sequences = new LinkedHashSet<>(); for (int seqs = randomIntBetween(0, 100); --seqs >= 0;) { sequences.add(randomAsciiLettersOfLengthBetween(1, 10)); } try ...
FSACompile extends CliTool { public static void main(String[] args) { main(args, new FSACompile()); } FSACompile(); FSACompile(Path input, Path output, SerializationFormat format, boolean acceptBom, boolean acceptCr, boolean igno...
@Test public void testEmptyWarning() throws Exception { final Path input = newTempFile(); final Path output = newTempFile(); Files.write(input, "abc\n\ndef".getBytes(StandardCharsets.US_ASCII)); String out = sysouts(new Callable<Void>() { @Override public Void call() throws Exception { FSACompile.main(new String[] { "-...
DictionaryLookup implements IStemmer, Iterable<WordData> { @Override public List<WordData> lookup(CharSequence word) { final byte separator = dictionaryMetadata.getSeparator(); final int prefixBytes = sequenceEncoder.prefixBytes(); if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { word = applyReplacements(...
@Test public void testSeparatorInLookupTerm() throws IOException { FSA fsa = FSA.read(getClass().getResourceAsStream("test-separator-in-lookup.fsa")); DictionaryMetadata metadata = new DictionaryMetadataBuilder() .separator('+') .encoding("iso8859-1") .encoder(EncoderType.INFIX) .build(); final DictionaryLookup s = new...
DictCompile extends CliTool { @Override public ExitStatus call() throws Exception { final Path metadataPath = DictionaryMetadata.getExpectedMetadataLocation(input); if (!Files.isRegularFile(metadataPath)) { System.err.println("Dictionary metadata file for the input does not exist: " + metadataPath); System.err.println(...
@Test @Repeat(iterations = 200) public void testRoundTrip() throws Exception { final Path input = newTempDir().resolve("dictionary.input"); final Path metadata = DictionaryMetadata.getExpectedMetadataLocation(input); char separator = RandomPicks.randomFrom(getRandom(), new Character [] { '|', ',', '\t', }); try (Writer...
FSABuilder { public static FSA build(byte[][] input) { final FSABuilder builder = new FSABuilder(); for (byte[] chs : input) { builder.add(chs, 0, chs.length); } return builder.complete(); } FSABuilder(); FSABuilder(int bufferGrowthSize); void add(byte[] sequence, int start, int len); FSA complete(); static FSA build(...
@Test public void testEmptyInput() { byte[][] input = {}; checkCorrect(input, FSABuilder.build(input)); } @Test public void testHashResizeBug() throws Exception { byte[][] input = { { 0, 1 }, { 0, 2 }, { 1, 1 }, { 2, 1 }, }; FSA fsa = FSABuilder.build(input); checkCorrect(input, FSABuilder.build(input)); checkMinimal(f...
DictionaryLookup implements IStemmer, Iterable<WordData> { public char getSeparatorChar() { return separatorChar; } DictionaryLookup(Dictionary dictionary); @Override List<WordData> lookup(CharSequence word); static String applyReplacements(CharSequence word, LinkedHashMap<String, String> replacements); @Override Itera...
@Test public void testGetSeparator() throws IOException { final URL url = this.getClass().getResource("test-separators.dict"); final DictionaryLookup s = new DictionaryLookup(Dictionary.read(url)); assertEquals('+', s.getSeparatorChar()); }
Dictionary { public static Dictionary read(Path location) throws IOException { final Path metadata = DictionaryMetadata.getExpectedMetadataLocation(location); try (InputStream fsaStream = Files.newInputStream(location); InputStream metadataStream = Files.newInputStream(metadata)) { return read(fsaStream, metadataStream...
@Test public void testReadFromFile() throws IOException { Path tempDir = super.newTempDir(); Path dict = tempDir.resolve("odd name.dict"); Path info = dict.resolveSibling("odd name.info"); try (InputStream dictInput = this.getClass().getResource("test-infix.dict").openStream(); InputStream infoInput = this.getClass().g...
Speller { public List<String> replaceRunOnWords(final String original) { final List<CandidateData> candidateData = replaceRunOnWordCandidates(original); final List<String> candidates = new ArrayList<>(); for (CandidateData candidate : candidateData) { candidates.add(candidate.word); } return candidates; } Speller(final...
@Test public void testRunonWords() throws IOException { final Speller spell = new Speller(dictionary); Assertions.assertThat(spell.replaceRunOnWords("abaka")).isEmpty(); Assertions.assertThat(spell.replaceRunOnWords("abakaabace")).contains("abaka abace"); Assertions.assertThat(spell.replaceRunOnWords("Abakaabace")).con...
Speller { public boolean isInDictionary(final CharSequence word) { try { byteBuffer = charSequenceToBytes(word); } catch (UnmappableInputException e) { return false; } final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode); if (containsSeparators && match.kind == E...
@Test public void testIsInDictionary() throws IOException { final URL url1 = getClass().getResource("test-infix.dict"); final Speller spell1 = new Speller(Dictionary.read(url1)); assertTrue(spell1.isInDictionary("Rzekunia")); assertTrue(!spell1.isInDictionary("Rzekunia+")); assertTrue(!spell1.isInDictionary("Rzekunia+a...
Speller { public ArrayList<String> findSimilarWords(String word) { final List<CandidateData> result = findSimilarWordCandidates(word); final ArrayList<String> resultSuggestions = new ArrayList<>(result.size()); for (CandidateData cd : result) { resultSuggestions.add(cd.getWord()); } return resultSuggestions; } Speller(...
@Test public void testFindSimilarWords() throws IOException { final URL url = getClass().getResource("dict-with-freq.dict"); final Speller spell = new Speller(Dictionary.read(url)); List<String> reps = spell.findSimilarWords("fist"); assertTrue(reps.toString().equals("[list, mist, dist, gist, wist, hist]")); reps = spe...
Destination { @NotNull protected final MultiverseCoreAPI getApi() { return this.api; } protected Destination(@NotNull MultiverseCoreAPI coreAPI); abstract void teleport(@NotNull Permissible teleporter, @NotNull Entity teleportee); @Override String toString(); }
@Test public void testGetApi() throws Exception { assertSame(api, basicDestination.getApi()); }
DestinationRegistry { @Nullable DestinationFactory getDestinationFactory(@NotNull String prefix) { return prefixFactoryMap.get(prefix); } DestinationRegistry(@NotNull final MultiverseCoreAPI api); void registerDestinationFactory(@NotNull DestinationFactory destinationFactory); @NotNull Destination parseDestination(@Not...
@Test public void testGetDefaultDestinationFactories() { for (String prefix : CannonDestination.PREFIXES) { assertNotNull(registry.getDestinationFactory(prefix)); } for (String prefix : ExactDestination.PREFIXES) { assertNotNull(registry.getDestinationFactory(prefix)); } for (String prefix : PlayerDestination.PREFIXES)...
DestinationRegistry { @NotNull public Destination parseDestination(@NotNull final String destinationString) throws InvalidDestinationException { String[] destParts = destinationString.split(":", 2); if (destParts.length == 1) { return worldDestinationFactory.createDestination(api, destinationString); } DestinationFacto...
@Test public void testParseWorldDestinations() throws Exception { Destination dest = registry.parseDestination("someworld"); assertNotNull(dest); assertEquals(WorldDestination.class, dest.getClass()); assertEquals("world:someworld", dest.getDestinationString()); dest = registry.parseDestination(":"); assertNotNull(dest...
DestinationRegistry { int getRegistrationCount() { return prefixFactoryMap.size(); } DestinationRegistry(@NotNull final MultiverseCoreAPI api); void registerDestinationFactory(@NotNull DestinationFactory destinationFactory); @NotNull Destination parseDestination(@NotNull final String destinationString); }
@Test public void testGetRegistrationCount() throws Exception { int originalCount = registry.getRegistrationCount(); registry.registerDestinationFactory(new TestDestination.Factory()); assertEquals(originalCount + TestDestination.PREFIXES.size(), registry.getRegistrationCount()); }
ExactDestination extends SimpleDestination { @Override @NotNull protected EntityCoordinates getDestination() { return this.coordinates; } ExactDestination(@NotNull MultiverseCoreAPI api, @NotNull EntityCoordinates coords); @Override String getDestinationString(); @Override boolean equals(final Object o); @Override int ...
@Test public void testValidDestinationStrings() throws Exception { for (String validDestination : validDestinations) { ExactDestination dest = factory.createDestination(api, validDestination); assertEquals(ExactDestination.class, dest.getClass()); assertNotNull(dest.getDestination()); } } @Test public void testTeleport...
ExactDestination extends SimpleDestination { @Override public boolean equals(final Object o) { return this == o || ((o != null) && (getClass() == o.getClass()) && Locations.equal(this.coordinates, ((ExactDestination) o).coordinates)); } ExactDestination(@NotNull MultiverseCoreAPI api, @NotNull EntityCoordinates coords)...
@Test public void testEquals() throws Exception { ExactDestination a = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0)); ExactDestination b = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0)); as...
DestinationUtil { static String numberRegex(@NotNull String name) { return String.format("(?<%s>[-+]?\\d+(\\.\\d+)?)", name); } private DestinationUtil(); }
@Test public void testNumberRegex() throws Exception { Pattern pattern = Pattern.compile(numberRegex("test")); Matcher matcher = pattern.matcher(":abc"); assertFalse(matcher.matches()); matcher = pattern.matcher("abc"); assertFalse(matcher.matches()); matcher = pattern.matcher(":1.2"); assertFalse(matcher.matches()); m...
DestinationUtil { static String colonJoin(Object... args) { StringBuilder builder = new StringBuilder(args[0].toString()); for (int i = 1; i < args.length; i++) builder.append(':').append(args[i].toString()); return builder.toString(); } private DestinationUtil(); }
@Test public void testColonJoin() throws Exception { String joined = colonJoin("", "", ""); assertEquals("::", joined); joined = colonJoin("a", "b", "c"); assertEquals("a:b:c", joined); joined = colonJoin("d", "e"); assertEquals("d:e", joined); }
Destination { @NotNull protected final SafeTeleporter getSafeTeleporter() { return getApi().getSafeTeleporter(); } protected Destination(@NotNull MultiverseCoreAPI coreAPI); abstract void teleport(@NotNull Permissible teleporter, @NotNull Entity teleportee); @Override String toString(); }
@Test public void testGetSafeTeleporter() throws Exception { assertSame(api.getSafeTeleporter(), basicDestination.getSafeTeleporter()); }
DestinationUtil { @NotNull static String removePrefix(@NotNull String destinationString) { String[] parts = destinationString.split(":", 2); return parts.length == 1 ? destinationString : parts[1]; } private DestinationUtil(); }
@Test public void testRemovePrefix() throws Exception { String removedPrefix = removePrefix("test"); assertEquals("test", removedPrefix); removedPrefix = removePrefix("test:blah"); assertEquals("blah", removedPrefix); removedPrefix = removePrefix("test:blah:bloo"); assertEquals("blah:bloo", removedPrefix); }
CannonDestination extends SimpleDestination { @NotNull @Override protected EntityCoordinates getDestination() throws TeleportException { if (coordinates != null) { return this.coordinates; } else { throw new TeleportException(Message.bundleMessage(Language.Destination.Cannon.LAUNCH_ONLY, getDestinationString())); } } C...
@Test public void testGetSpecificDestination() throws Exception { assertNotNull(factory.createDestination(api, "cannon:someworld:5:5.3:5.4:3:3:4").getDestination()); } @Test(expected = TeleportException.class) public void testGetLaunchDestination() throws Exception { CannonDestination dest = factory.createDestination(a...
CannonDestination extends SimpleDestination { @Override public boolean equals(final Object o) { return this == o || ((o != null) && (getClass() == o.getClass()) && Locations.equal(this.coordinates, ((CannonDestination) o).coordinates) && this.speed == ((CannonDestination) o).speed); } CannonDestination(@NotNull Multive...
@Test public void testEquals() throws Exception { CannonDestination a = new CannonDestination(api, null, 5); CannonDestination b = new CannonDestination(api, null, 5); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertFalse(a.equals(null)); assertFalse(b.equals(null)); b = new CannonDestination(api, null, 4); ass...
WorldManager { @NotNull public MultiverseWorld addWorld(@NotNull final String name, @Nullable final WorldEnvironment env, @Nullable final String seedString, @Nullable final WorldType type, @Nullable final Boolean generateStructures, @Nullable final String generator) throws WorldCreationException { return this.addWorld(...
@Test public void testAddWorld() throws Exception { WorldManager mockWorldManager = PowerMockito.spy(new WorldManager(MultiverseCoreAPIFactory.getMockedMultiverseCoreAPI() , WorldManagerUtilFactory.getMockedWorldManagerUtil())); doAnswer(new Answer<Object>() { @Override public Object answer(final InvocationOnMock invoc...
WorldManager { public boolean isLoaded(@NotNull final String name) { return this.worldsMap.containsKey(name.toLowerCase()); } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull MultiverseWorld addWorld(@No...
@Test public void testIsLoaded() throws Exception { assertTrue(worldManager.isLoaded("world")); assertFalse(worldManager.isLoaded("world1")); assertTrue(worldManager.isLoaded("WORLD")); assertTrue(worldManager.isLoaded("WOrLd")); assertTrue(worldManager.isLoaded("world_nether")); assertTrue(worldManager.isLoaded("world...
WorldManager { public boolean isManaged(@NotNull final String name) { final String lowerName = name.toLowerCase(); return this.worldsMap.containsKey(lowerName) || this.getUnloadedWorlds().contains(lowerName); } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNul...
@Test public void testIsManaged() throws Exception { assertTrue(worldManager.isManaged("world")); assertFalse(worldManager.isManaged("world1")); assertTrue(worldManager.isManaged("WORLD")); assertTrue(worldManager.isManaged("WOrLd")); assertTrue(worldManager.isManaged("world_nether")); assertTrue(worldManager.isManaged...
WorldManager { @Nullable public MultiverseWorld getWorld(@NotNull final String name) { final MultiverseWorld world = this.worldsMap.get(name.toLowerCase()); if (world != null) { return world; } for (final MultiverseWorld w : this.worldsMap.values()) { if (name.equalsIgnoreCase(w.getAlias())) { return w; } } return null...
@Test public void testGetWorld() throws Exception { assertNotNull(worldManager.getWorld("world")); assertNotNull(worldManager.getWorld("WORLD")); assertNotNull(worldManager.getWorld("woRlD")); assertNull(worldManager.getWorld("world1")); assertNull(worldManager.getWorld(testName)); MultiverseWorld w = worldManager.addW...
WorldManager { @NotNull public Collection<MultiverseWorld> getWorlds() { return Collections.unmodifiableCollection(this.worldsMap.values()); } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull MultiverseW...
@Test public void testGetWorlds() throws Exception { assertEquals(3, worldManager.getWorlds().size()); MultiverseWorld w = worldManager.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); assertTrue(worldManager.getWorlds().contains(w)); world...
WorldManager { @NotNull public MultiverseWorld loadWorld(@NotNull final String name) throws WorldManagementException { if (isLoaded(name)) { throw new WorldManagementException(Message.bundleMessage(Language.WORLD_ALREADY_LOADED, name)); } if (!isManaged(name)) { throw new WorldManagementException(Message.bundleMessage(...
@Test public void testLoadWorld() throws Exception { boolean thrown = false; try { worldManager.loadWorld("world"); } catch (WorldManagementException e) { thrown = true; assertEquals(Language.WORLD_ALREADY_LOADED, e.getBundledMessage().getMessage()); assertEquals("world", e.getBundledMessage().getArgs()[0]); } assertTr...
PlayerDestination extends SimpleDestination { @NotNull @Override protected EntityCoordinates getDestination() throws TeleportException { BasePlayer player = this.getApi().getServerInterface().getPlayer(playerName); if (player instanceof Entity) { return ((Entity) player).getLocation(); } else { throw new TeleportExcept...
@Test public void testGetOnlinePlayerDestination() throws Exception { assertNotNull(factory.createDestination(api, "player:someplayer").getDestination()); } @Test(expected = TeleportException.class) public void testGetOfflinePlayerDestination() throws Exception { PlayerDestination dest = factory.createDestination(api, ...
WorldManager { public boolean unloadWorld(@NotNull final String name) throws WorldManagementException { final MultiverseWorld world = getWorld(name); if (world != null) { unloadWorld(world); return true; } return false; } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUti...
@Test public void testUnloadWorld() throws Exception { }
WorldManager { public void removePlayersFromWorld(@NotNull final MultiverseWorld world) throws TeleportException { final MultiverseWorld safeWorld = getSafeWorld(); final SafeTeleporter teleporter = this.api.getSafeTeleporter(); final FacingCoordinates sLoc = safeWorld.getSpawnLocation(); final EntityCoordinates locati...
@Test public void testRemovePlayersFromWorld() throws Exception { }
WorldManager { @NotNull public Collection<String> getUnloadedWorlds() { final Collection<String> managedWorlds = this.worldManagerUtil.getManagedWorldNames(); final List<String> unloadedWorlds = new ArrayList<String>(managedWorlds.size() - getWorlds().size()); for (final String name : managedWorlds) { if (!isLoaded(nam...
@Test public void testGetUnloadedWorlds() throws Exception { }
WorldManager { public boolean removeWorld(@NotNull final String name) throws WorldManagementException { try { if (isLoaded(name) && !unloadWorld(name)) { throw new WorldManagementException(Message.bundleMessage(Language.WORLD_NOT_MANAGED, name)); } } catch (final WorldManagementException e) { throw new WorldManagementE...
@Test public void testRemoveWorld() throws Exception { }
WorldManager { public void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld) throws WorldManagementException { if (!isManaged(worldName)) { throw new WorldManagementException(Message.bundleMessage(Language.CANNOT_DELETE_UNMANAGED)); } final String name = this.worldManagerUtil.getCorrectlyCasedWo...
@Test public void testDeleteWorld() throws Exception { }
PlayerDestination extends SimpleDestination { @Override public boolean equals(final Object o) { return this == o || !(o == null || getClass() != o.getClass()) && playerName.equals(((PlayerDestination) o).playerName); } PlayerDestination(@NotNull MultiverseCoreAPI api, @NotNull String playerName); @NotNull @Override Str...
@Test public void testEquals() throws Exception { PlayerDestination a = new PlayerDestination(api, "player"); PlayerDestination b = new PlayerDestination(api, "player"); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertFalse(a.equals(null)); assertFalse(b.equals(null)); b = new PlayerDestination(api, "player2");...
WorldDestination extends SimpleDestination { @NotNull @Override protected EntityCoordinates getDestination() throws TeleportException { MultiverseWorld mvWorld = this.getApi().getWorldManager().getWorld(world); if (mvWorld == null) { throw new TeleportException(Message.bundleMessage(NOT_LOADED, world)); } return Locati...
@Test public void testGetDestination() throws Exception { WorldDestination dest = factory.createDestination(api, "world:world"); assertNotNull(dest.getDestination()); assertTrue(Locations.equal(api.getWorldManager().getWorld("world").getSpawnLocation(), dest.getDestination())); } @Test public void testTeleportLocation(...
WorldDestination extends SimpleDestination { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final WorldDestination that = (WorldDestination) o; return world.equals(that.world); } WorldDestination(@NotNull MultiverseCoreAPI...
@Test public void testEquals() throws Exception { WorldDestination a = new WorldDestination(api, "world"); WorldDestination b = new WorldDestination(api, "world"); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertFalse(a.equals(null)); assertFalse(b.equals(null)); b = new WorldDestination(api, "someworld"); asse...
DestinationRegistry { public void registerDestinationFactory(@NotNull DestinationFactory destinationFactory) { CoreLogger.fine("Registering DestinationFactory: " + destinationFactory); if (destinationFactory.getDestinationPrefixes().isEmpty()) { CoreLogger.warning("DestinationFactory: %s cannot be registered without an...
@Test public void testRegisterDestinationFactory() throws Exception { for (String prefix : TestDestination.PREFIXES) { assertNull(registry.getDestinationFactory(prefix)); } registry.registerDestinationFactory(new TestDestination.Factory()); for (String prefix : TestDestination.PREFIXES) { assertNotNull(registry.getDest...
AnnotationUtils { public static String getClassAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType) { return getClassAttributeFromAnnotationAsFqn(element, annotationType, "value"); } private AnnotationUtils(); static AnnotationValue getAnnotationValueOfAttribute(AnnotationMirror an...
@Test public void annotationUtilsTest_classAttribute_emptyValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyF...
IsInterfaceMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CheckKindOfElement.isInterface(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingInterface() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(Serializable.class); MatcherAssert.assertThat("Should return true for inter...
IsFieldMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CheckKindOfElement.isField(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingInterface() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(IsFieldMatcherTest.class); List<? extends Element> fieldList = ElementUtils...
IsGetterMethodMatcher implements ImplicitMatcher<ExecutableElement> { @Override public boolean check(ExecutableElement element) { if (element == null) { return false; } if (!FluentElementValidator.createFluentElementValidator(element) .applyValidator(CoreMatchers.BY_MODIFIER).hasAllOf(Modifier.PUBLIC) .applyValidator(C...
@Test public void checkNullValuedElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for null valued element : ", !CoreMatchers.IS_GETTER_METHOD.getMatcher().check(null)); } }) .c...
ByReturnTypeMatcher implements CriteriaMatcher<ExecutableElement, Class> { @Override public boolean checkForMatchingCharacteristic(ExecutableElement element, Class toCheckFor) { if (element == null || toCheckFor == null) { return false; } return TypeUtils.TypeComparison.isTypeEqual(element.getReturnType(), TypeUtils.Ty...
@Test public void byReturnTypeMirrorMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndPar...
ByReturnTypeMatcher implements CriteriaMatcher<ExecutableElement, Class> { @Override public String getStringRepresentationOfPassedCharacteristic(Class toGetStringRepresentationFor) { return toGetStringRepresentationFor != null ? toGetStringRepresentationFor.getCanonicalName() : ""; } ByReturnTypeMatcher(); @Override bo...
@Test public void getStringRepresentationOfPassedCharacteristic_nullValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should not have found matching parameters", CoreMatchers.BY_RETURN_TYPE.getMatche...
IsAnnotationTypeMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CheckKindOfElement.isAnnotation(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingAnnotationType() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(Override.class); MatcherAssert.assertThat("Should return true for anno...
IsPackageMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CheckKindOfElement.isPackage(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingPackage() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { Element result = ElementUtils.AccessEnclosingElements.getFirstEnclosingElementOfKind(element, ElementKind.PACKAGE); MatcherAssert.assertThat("...
IsSetterMethodMatcher implements ImplicitMatcher<ExecutableElement> { @Override public boolean check(ExecutableElement element) { if (element == null) { return false; } return FluentElementValidator.createFluentElementValidator(element) .applyValidator(CoreMatchers.BY_MODIFIER).hasAllOf(Modifier.PUBLIC) .applyValidator...
@Test public void checkNullValuedElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for null valued element : ", !CoreMatchers.IS_SETTER_METHOD.getMatcher().check(null)); } }) .c...
ByReturnTypeMirrorMatcher implements CriteriaMatcher<ExecutableElement, TypeMirror> { @Override public boolean checkForMatchingCharacteristic(ExecutableElement element, TypeMirror toCheckFor) { if (element == null || toCheckFor == null) { return false; } return TypeUtils.TypeComparison.isTypeEqual(element.getReturnType...
@Test public void byReturnTypeMirrorMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndPar...
FluentValidatorMessage { public void issueMessage() { if (annotationMirror != null && annotationValue != null) { MessagerUtils.printMessage(element, annotationMirror, annotationValue, kind, message, args); } else if (annotationMirror != null) { MessagerUtils.printMessage(element, annotationMirror, kind, message, args);...
@Test public void checkErrorElementMessage() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { FluentValidatorMessage message = new FluentValidatorMessage(element, Diagnostic.Kind.ERROR, PlainValidationMessage.create("TEST ${0}"), "...
ByReturnTypeMirrorMatcher implements CriteriaMatcher<ExecutableElement, TypeMirror> { @Override public String getStringRepresentationOfPassedCharacteristic(TypeMirror toGetStringRepresentationFor) { return toGetStringRepresentationFor != null ? toGetStringRepresentationFor.toString() : ""; } ByReturnTypeMirrorMatcher()...
@Test public void getStringRepresentationOfPassedCharacteristic_nullValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should not have found matching parameters", CoreMatchers.BY_RETURN_TYPE_MIRROR.ge...
IsTypeElementMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CastElement.isTypeElement(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingTypeElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non TypeElement : ", CoreMatchers.IS_TYPE_ELEMENT.getMatcher().check(element)); } }) .co...
IsExecutableElementMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CastElement.isExecutableElement(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingExecutableElement_method() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnType...
ByParameterTypeMatcher implements CriteriaMatcher<ExecutableElement, Class[]> { @Override public boolean checkForMatchingCharacteristic(ExecutableElement element, Class[] toCheckFor) { if (element == null || toCheckFor == null) { return false; } if (element.getParameters().size() != toCheckFor.length) { return false; }...
@Test public void byParameterTypeMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParame...
ByParameterTypeMatcher implements CriteriaMatcher<ExecutableElement, Class[]> { @Override public String getStringRepresentationOfPassedCharacteristic(Class[] toGetStringRepresentationFor) { if (toGetStringRepresentationFor != null) { StringBuilder stringBuilder = new StringBuilder("["); boolean isFirst = true; for (Cla...
@Test public void getStringRepresentationOfPassedCharacteristic_nullValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should not have found matching parameters", CoreMatchers.BY_PARAMETER_TYPE.getMat...
ByParameterTypeMirrorMatcher implements CriteriaMatcher<ExecutableElement, TypeMirror[]> { @Override public boolean checkForMatchingCharacteristic(ExecutableElement element, TypeMirror[] toCheckFor) { if (element == null || toCheckFor == null) { return false; } if (element.getParameters().size() != toCheckFor.length) {...
@Test public void byParameterTypeMirrorMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAnd...
ByParameterTypeMirrorMatcher implements CriteriaMatcher<ExecutableElement, TypeMirror[]> { @Override public String getStringRepresentationOfPassedCharacteristic(TypeMirror[] toGetStringRepresentationFor) { if (toGetStringRepresentationFor != null) { StringBuilder stringBuilder = new StringBuilder("["); boolean isFirst ...
@Test public void getStringRepresentationOfPassedCharacteristic_nullValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should not have found matching parameters", CoreMatchers.BY_PARAMETER_TYPE_MIRROR...
IsPackageElementMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CastElement.isPackageElement(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingPackageElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { Element result = ElementUtils.AccessEnclosingElements.getFirstEnclosingElementOfKind(element, ElementKind.PACKAGE); MatcherAssert.asser...
ByElementKindMatcher implements CriteriaMatcher<Element, ElementKind> { @Override public String getStringRepresentationOfPassedCharacteristic(ElementKind toGetStringRepresentationFor) { return toGetStringRepresentationFor != null ? toGetStringRepresentationFor.name() : null; } @Override boolean checkForMatchingCharact...
@Test public void test_getStringRepresentationOfPassedCharacteristic_happyPath() { MatcherAssert.assertThat("Should return cannonical class name of annotation class", unit.getStringRepresentationOfPassedCharacteristic(ElementKind.ENUM).equals(ElementKind.ENUM.name())); } @Test public void test_getStringRepresentationOf...