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); } } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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 RuntimeException(e); } } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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().addListener(client, request, listener); requestLocationUpdatesInternal(request); return new SimplePendingResult(true); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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 public void requestLocationUpdates_pendingIntent_shouldCallService() throws Exception { LocationRequest request = LocationRequest.create(); PendingIntent pendingIntent = mock(PendingIntent.class); api.requestLocationUpdates(connectedClient, request, pendingIntent); verify(service).requestLocationUpdates(request); }
@Test public void requestLocationUpdates_callback_shouldCallService() throws Exception { LocationRequest request = LocationRequest.create(); TestLocationCallback callback = new TestLocationCallback(); Looper looper = Looper.myLooper(); api.requestLocationUpdates(connectedClient, request, callback, looper); verify(service).requestLocationUpdates(request); }
@Test(expected = RuntimeException.class) public void requestLocationUpdates_listenerWithLooper_shouldThrowExceptionIfNotYetImplemented() { LocationRequest request = LocationRequest.create(); TestLocationListener listener = new TestLocationListener(); api.requestLocationUpdates(connectedClient, request, listener, null); }
@Test public void requestLocationUpdates_listener_shouldReturnFusedLocationPendingResult() { PendingResult<Status> result = api.requestLocationUpdates(connectedClient, LocationRequest.create(), new TestLocationListener()); assertThat(result.await().getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); assertThat(result.await(1000, TimeUnit.MILLISECONDS).getStatus().getStatusCode()).isEqualTo( Status.SUCCESS); assertThat(result.isCanceled()).isFalse(); com.mapzen.android.lost.internal.TestResultCallback callback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(callback); assertThat(callback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); com.mapzen.android.lost.internal.TestResultCallback otherCallback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(otherCallback, 1000, TimeUnit.MILLISECONDS); assertThat(otherCallback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); }
@Test public void requestLocationUpdates_pendingIntent_shouldReturnFusedLocationPendingResult() { PendingResult<Status> result = api.requestLocationUpdates(connectedClient, LocationRequest.create(), mock(PendingIntent.class)); assertThat(result.await().getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); assertThat(result.await(1000, TimeUnit.MILLISECONDS).getStatus().getStatusCode()).isEqualTo( Status.SUCCESS); assertThat(result.isCanceled()).isFalse(); com.mapzen.android.lost.internal.TestResultCallback callback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(callback); assertThat(callback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); com.mapzen.android.lost.internal.TestResultCallback otherCallback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(otherCallback, 1000, TimeUnit.MILLISECONDS); assertThat(otherCallback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); }
@Test public void requestLocationUpdates_callback_shouldReturnFusedLocationPendingResult() { PendingResult<Status> result = api.requestLocationUpdates(connectedClient, LocationRequest.create(), new TestLocationCallback(), Looper.myLooper()); assertThat(result.await().getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); assertThat(result.await(1000, TimeUnit.MILLISECONDS).getStatus().getStatusCode()).isEqualTo( Status.SUCCESS); assertThat(result.isCanceled()).isFalse(); com.mapzen.android.lost.internal.TestResultCallback callback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(callback); assertThat(callback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); com.mapzen.android.lost.internal.TestResultCallback otherCallback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(otherCallback, 1000, TimeUnit.MILLISECONDS); assertThat(otherCallback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); } |
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationListener listener) { throwIfNotConnected(client); boolean hasResult = LostClientManager.shared().removeListener(client, listener); checkAllListenersPendingIntentsAndCallbacks(); return new SimplePendingResult(hasResult); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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() throws Exception { PendingIntent callbackIntent = mock(PendingIntent.class); api.removeLocationUpdates(connectedClient, callbackIntent); verify(service).removeLocationUpdates(); }
@Test public void removeLocationUpdates_callback_shouldCallService() throws Exception { TestLocationCallback callback = new TestLocationCallback(); api.removeLocationUpdates(connectedClient, callback); verify(service).removeLocationUpdates(); }
@Test public void removeLocationUpdates_shouldNotReturnStatusSuccessIfListenerNotRemoved() { TestResultCallback callback = new TestResultCallback(); TestLocationListener listener = new TestLocationListener(); LostClientManager.shared().removeListener(connectedClient, listener); PendingResult<Status> result = api.removeLocationUpdates(connectedClient, listener); result.setResultCallback(callback); assertThat(callback.status).isNull(); }
@Test public void removeLocationUpdates_shouldNotReturnStatusSuccessIfPendingIntentNotRemoved() { TestResultCallback callback = new TestResultCallback(); PendingIntent pendingIntent = mock(PendingIntent.class); PendingResult<Status> result = api.removeLocationUpdates(connectedClient, pendingIntent); result.setResultCallback(callback); assertThat(callback.status).isNull(); }
@Test public void removeLocationUpdates_shouldNotReturnStatusSuccessIfCallbackNotRemoved() { TestResultCallback callback = new TestResultCallback(); LocationCallback locationCallback = new TestLocationCallback(); PendingResult<Status> result = api.removeLocationUpdates(connectedClient, locationCallback); result.setResultCallback(callback); assertThat(callback.status).isNull(); } |
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 RuntimeException(e); } return new SimplePendingResult(true); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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().getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); assertThat(result.await(1000, TimeUnit.MILLISECONDS).getStatus().getStatusCode()).isEqualTo( Status.SUCCESS); assertThat(result.isCanceled()).isFalse(); com.mapzen.android.lost.internal.TestResultCallback callback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(callback); assertThat(callback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); com.mapzen.android.lost.internal.TestResultCallback otherCallback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(otherCallback, 1000, TimeUnit.MILLISECONDS); assertThat(otherCallback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); } |
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) { throw new RuntimeException(e); } return new SimplePendingResult(true); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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.setMockLocation(connectedClient, new Location("test")); assertThat(result.await().getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); assertThat(result.await(1000, TimeUnit.MILLISECONDS).getStatus().getStatusCode()).isEqualTo( Status.SUCCESS); assertThat(result.isCanceled()).isFalse(); com.mapzen.android.lost.internal.TestResultCallback callback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(callback); assertThat(callback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); com.mapzen.android.lost.internal.TestResultCallback otherCallback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(otherCallback, 1000, TimeUnit.MILLISECONDS); assertThat(otherCallback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); } |
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 (RemoteException e) { throw new RuntimeException(e); } return new SimplePendingResult(true); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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", "name"); assertThat(result.await().getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); assertThat(result.await(1000, TimeUnit.MILLISECONDS).getStatus().getStatusCode()).isEqualTo( Status.SUCCESS); assertThat(result.isCanceled()).isFalse(); com.mapzen.android.lost.internal.TestResultCallback callback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(callback); assertThat(callback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); com.mapzen.android.lost.internal.TestResultCallback otherCallback = new com.mapzen.android.lost.internal.TestResultCallback(); result.setResultCallback(otherCallback, 1000, TimeUnit.MILLISECONDS); assertThat(otherCallback.getStatus().getStatusCode()).isEqualTo(Status.SUCCESS); } |
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_AUTO_CREATE); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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.class); api.onConnect(context); verify(context).bindService(new Intent(context, FusedLocationProviderService.class), api, Context.BIND_AUTO_CREATE); } |
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { @Override public void onServiceConnected(IBinder binder) { service = IFusedLocationProviderService.Stub.asInterface(binder); isBound = true; registerRemoteCallback(); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client,
LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client,
LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client,
Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path,
String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); } | @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 = Float.MAX_VALUE; long bestTime = Long.MIN_VALUE; for (String provider : providers) { try { final Location location = locationManager.getLastKnownLocation(provider); if (location != null) { final float accuracy = location.getAccuracy(); final long time = location.getTime(); if (time > minTime && accuracy < bestAccuracy) { bestLocation = location; bestAccuracy = accuracy; bestTime = time; } else if (time < minTime && bestAccuracy == Float.MAX_VALUE && time > bestTime) { bestLocation = location; bestTime = time; } } } catch (SecurityException e) { Log.e(TAG, "Permissions not granted for provider: " + provider, e); } } return bestLocation; } FusionEngine(Context context, Callback callback); @Override Location getLastLocation(); @Override boolean isProviderEnabled(String provider); @Override void onLocationChanged(Location location); @Override void onStatusChanged(String provider, int status, Bundle extras); @Override void onProviderEnabled(String provider); @Override void onProviderDisabled(String provider); static boolean isBetterThan(Location locationA, Location locationB); static final long RECENT_UPDATE_THRESHOLD_IN_MILLIS; static final long RECENT_UPDATE_THRESHOLD_IN_NANOS; } | @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.setLastKnownLocation(GPS_PROVIDER, location); assertThat(fusionEngine.getLastLocation()).isEqualTo(location); }
@Test public void getLastLocation_shouldReturnNetworkLocationIfOnlyProvider() throws Exception { Location location = new Location(NETWORK_PROVIDER); shadowLocationManager.setLastKnownLocation(NETWORK_PROVIDER, location); assertThat(fusionEngine.getLastLocation()).isEqualTo(location); }
@Test public void getLastLocation_shouldReturnPassiveLocationIfOnlyProvider() throws Exception { Location location = new Location(PASSIVE_PROVIDER); shadowLocationManager.setLastKnownLocation(PASSIVE_PROVIDER, location); assertThat(fusionEngine.getLastLocation()).isEqualTo(location); }
@Test public void getLastLocation_shouldReturnMostAccurateResult() throws Exception { Location gpsLocation = new Location(GPS_PROVIDER); gpsLocation.setAccuracy(1000); shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, gpsLocation); Location networkLocation = new Location(NETWORK_PROVIDER); networkLocation.setAccuracy(100); shadowLocationManager.setLastKnownLocation(NETWORK_PROVIDER, networkLocation); Location passiveLocation = new Location(PASSIVE_PROVIDER); passiveLocation.setAccuracy(10); shadowLocationManager.setLastKnownLocation(PASSIVE_PROVIDER, passiveLocation); assertThat(fusionEngine.getLastLocation()).isEqualTo(passiveLocation); }
@Test public void getLastLocation_shouldIgnoreStaleLocations() throws Exception { long time = System.currentTimeMillis(); initTestClock(time); Location gpsLocation = new Location(GPS_PROVIDER); gpsLocation.setAccuracy(100); gpsLocation.setTime(time); shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, gpsLocation); Location networkLocation = new Location(NETWORK_PROVIDER); networkLocation.setAccuracy(100); networkLocation.setTime(time - (2 * RECENT_UPDATE_THRESHOLD_IN_MILLIS)); shadowLocationManager.setLastKnownLocation(NETWORK_PROVIDER, networkLocation); assertThat(fusionEngine.getLastLocation()).isEqualTo(gpsLocation); }
@Test public void getLastLocation_ifNoFreshLocationsShouldReturnMostRecent() throws Exception { long time = System.currentTimeMillis(); initTestClock(time); Location gpsLocation = new Location(GPS_PROVIDER); gpsLocation.setAccuracy(100); gpsLocation.setTime(time - (2 * RECENT_UPDATE_THRESHOLD_IN_MILLIS)); shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, gpsLocation); Location networkLocation = new Location(NETWORK_PROVIDER); networkLocation.setAccuracy(100); networkLocation.setTime(time - (3 * RECENT_UPDATE_THRESHOLD_IN_MILLIS)); shadowLocationManager.setLastKnownLocation(NETWORK_PROVIDER, networkLocation); assertThat(fusionEngine.getLastLocation()).isEqualTo(gpsLocation); }
@SuppressWarnings("MissingPermission") @Test public void getLastLocation_shouldReturnNullIfNoLocationPermissionsGranted() throws Exception { Context mockContext = mock(Context.class); LocationManager mockLocatinManager = mock(LocationManager.class); List<String> providers = new ArrayList<>(3); providers.add(GPS_PROVIDER); providers.add(NETWORK_PROVIDER); providers.add(PASSIVE_PROVIDER); when(mockContext.getSystemService(Context.LOCATION_SERVICE)).thenReturn(mockLocatinManager); when(mockLocatinManager.getAllProviders()).thenReturn(providers); when(mockLocatinManager.getLastKnownLocation(GPS_PROVIDER)).thenThrow(new SecurityException()); when(mockLocatinManager.getLastKnownLocation(NETWORK_PROVIDER)).thenThrow( new SecurityException()); when(mockLocatinManager.getLastKnownLocation(PASSIVE_PROVIDER)).thenThrow( new SecurityException()); final FusionEngine fusionEngine = new FusionEngine(mockContext, callback); assertThat(fusionEngine.getLastLocation()).isNull(); } |
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_UPDATE_THRESHOLD_IN_NANOS) { return true; } if (!locationA.hasAccuracy()) { return false; } if (!locationB.hasAccuracy()) { return true; } return locationA.getAccuracy() < locationB.getAccuracy(); } FusionEngine(Context context, Callback callback); @Override Location getLastLocation(); @Override boolean isProviderEnabled(String provider); @Override void onLocationChanged(Location location); @Override void onStatusChanged(String provider, int status, Bundle extras); @Override void onProviderEnabled(String provider); @Override void onProviderDisabled(String provider); static boolean isBetterThan(Location locationA, Location locationB); static final long RECENT_UPDATE_THRESHOLD_IN_MILLIS; static final long RECENT_UPDATE_THRESHOLD_IN_NANOS; } | @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 { Location locationA = new Location("test"); Location locationB = null; assertThat(FusionEngine.isBetterThan(locationA, locationB)).isTrue(); }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Test @Config(sdk = 17) public void isBetterThan_shouldReturnTrueIfLocationBIsStale_Api17() throws Exception { final long timeInNanos = System.currentTimeMillis() * MS_TO_NS; Location locationA = new Location("test"); Location locationB = new Location("test"); locationA.setElapsedRealtimeNanos(timeInNanos); locationB.setElapsedRealtimeNanos(timeInNanos - RECENT_UPDATE_THRESHOLD_IN_NANOS - 1); assertThat(FusionEngine.isBetterThan(locationA, locationB)).isTrue(); }
@Test @Config(sdk = 16) public void isBetterThan_shouldReturnTrueIfLocationBIsStale_Api16() throws Exception { final long timeInMillis = System.currentTimeMillis(); Location locationA = new Location("test"); Location locationB = new Location("test"); locationA.setTime(timeInMillis); locationB.setTime(timeInMillis - RECENT_UPDATE_THRESHOLD_IN_MILLIS - 1); assertThat(FusionEngine.isBetterThan(locationA, locationB)).isTrue(); }
@Test public void isBetterThan_shouldReturnFalseIfLocationAHasNoAccuracy() throws Exception { Location locationA = new Location("test"); Location locationB = new Location("test"); locationA.removeAccuracy(); locationB.setAccuracy(30.0f); assertThat(FusionEngine.isBetterThan(locationA, locationB)).isFalse(); }
@Test public void isBetterThan_shouldReturnTrueIfLocationBHasNoAccuracy() throws Exception { Location locationA = new Location("test"); Location locationB = new Location("test"); locationA.setAccuracy(30.0f); locationB.removeAccuracy(); assertThat(FusionEngine.isBetterThan(locationA, locationB)).isTrue(); }
@Test public void isBetterThan_shouldReturnTrueIfLocationAIsMoreAccurate() throws Exception { Location locationA = new Location("test"); Location locationB = new Location("test"); locationA.setAccuracy(30.0f); locationB.setAccuracy(40.0f); assertThat(FusionEngine.isBetterThan(locationA, locationB)).isTrue(); }
@Test public void isBetterThan_shouldReturnFalseIfLocationBIsMoreAccurate() throws Exception { Location locationA = new Location("test"); Location locationB = new Location("test"); locationA.setAccuracy(40.0f); locationB.setAccuracy(30.0f); assertThat(FusionEngine.isBetterThan(locationA, locationB)).isFalse(); } |
FusedLocationProviderServiceDelegate implements LocationEngine.Callback { public Location getLastLocation() { return locationEngine.getLastLocation(); } FusedLocationProviderServiceDelegate(Context context); void init(IFusedLocationProviderCallback callback); Location getLastLocation(); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) LocationAvailability getLocationAvailability(); void requestLocationUpdates(LocationRequest request); void removeLocationUpdates(); void setMockMode(boolean isMockMode); void setMockLocation(Location mockLocation); void setMockTrace(String path, String filename); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportLocation(Location location); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderDisabled(String provider); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderEnabled(String provider); } | @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(); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) LocationAvailability getLocationAvailability(); void requestLocationUpdates(LocationRequest request); void removeLocationUpdates(); void setMockMode(boolean isMockMode); void setMockLocation(Location mockLocation); void setMockTrace(String path, String filename); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportLocation(Location location); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderDisabled(String provider); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderEnabled(String provider); } | @Test public void requestLocationUpdates_shouldRegisterGpsAndNetworkListener() throws Exception { delegate.requestLocationUpdates(LocationRequest.create().setPriority(PRIORITY_HIGH_ACCURACY)); assertThat(shadowLocationManager.getRequestLocationUpdateListeners()).hasSize(2); }
@Test public void requestLocationUpdates_shouldRegisterGpsAndNetworkListenerViaPendingIntent() throws Exception { delegate.requestLocationUpdates(LocationRequest.create().setPriority(PRIORITY_HIGH_ACCURACY)); assertThat(shadowLocationManager.getRequestLocationUpdateListeners()).hasSize(2); } |
FusedLocationProviderServiceDelegate implements LocationEngine.Callback { @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) public LocationAvailability getLocationAvailability() { return locationEngine.createLocationAvailability(); } FusedLocationProviderServiceDelegate(Context context); void init(IFusedLocationProviderCallback callback); Location getLastLocation(); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) LocationAvailability getLocationAvailability(); void requestLocationUpdates(LocationRequest request); void removeLocationUpdates(); void setMockMode(boolean isMockMode); void setMockLocation(Location mockLocation); void setMockTrace(String path, String filename); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportLocation(Location location); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderDisabled(String provider); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderEnabled(String provider); } | @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); LocationAvailability availability = delegate.getLocationAvailability(); assertThat(availability.isLocationAvailable()).isTrue(); }
@Test public void getLocationAvailability_gps_network_shouldBeUnavailable() { shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true); shadowLocationManager.setProviderEnabled(NETWORK_PROVIDER, true); LocationAvailability availability = delegate.getLocationAvailability(); assertThat(availability.isLocationAvailable()).isFalse(); }
@Test public void getLocationAvailability_gps_shouldBeAvailable() { shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true); Location location = new Location("test"); shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, location); LocationAvailability availability = delegate.getLocationAvailability(); assertThat(availability.isLocationAvailable()).isTrue(); }
@Test public void getLocationAvailability_gps_shouldBeUnavailable() { shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true); LocationAvailability availability = delegate.getLocationAvailability(); assertThat(availability.isLocationAvailable()).isFalse(); }
@Test public void getLocationAvailability_network_shouldBeAvailable() { shadowLocationManager.setProviderEnabled(NETWORK_PROVIDER, true); Location location = new Location("test"); shadowLocationManager.setLastKnownLocation(NETWORK_PROVIDER, location); LocationAvailability availability = delegate.getLocationAvailability(); assertThat(availability.isLocationAvailable()).isTrue(); }
@Test public void getLocationAvailability_network_shouldBeUnavailable() { shadowLocationManager.setProviderEnabled(NETWORK_PROVIDER, true); LocationAvailability availability = delegate.getLocationAvailability(); assertThat(availability.isLocationAvailable()).isFalse(); }
@Test public void getLocationAvailability_shouldBeUnavailable() { LocationAvailability availability = delegate.getLocationAvailability(); assertThat(availability.isLocationAvailable()).isFalse(); } |
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 location); static final long MS_TO_NS; } | @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(sdk = 16) public void getTimeInNanos_shouldUseUtcTimeInMillisForSdk16AndLower() throws Exception { final long millis = 1000; final Location location = new Location("mock"); location.setTime(millis); assertThat(SystemClock.getTimeInNanos(location)).isEqualTo(millis * MS_TO_NS); } |
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); static InputStream getResourceAsStream(String path); } | @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] = Arrays.copyOfRange(raw, start, end); start = end; } return parts; } static byte[][] split(byte[] raw, int partSize); } | @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 (int i = 0; i < combine1.length; i++) { assertEquals((byte) combine1[i], bytes1[i]); } byte[][] parts2 = ByteKit.split(bytes1, 11); assertEquals( parts2.length, bytes1.length % 11 == 0 ? bytes1.length / 11 : bytes1.length / 11 + 1); Byte[] combine2 = Arrays.stream(parts2) .flatMap( part -> { List<Byte> bytes = new ArrayList<>(); for (byte b : part) { bytes.add(b); } return bytes.stream(); }) .toArray(Byte[]::new); for (int i = 0; i < combine2.length; i++) { assertEquals((byte) combine2[i], bytes1[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 { writer.append(line).append("\n"); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } }, contextSize); } static void write(UnifiedDiff diff, Function<String, List<String>> originalLinesProvider, Writer writer, int contextSize); static void write(UnifiedDiff diff, Function<String, List<String>> originalLinesProvider, Consumer<String> writer, int contextSize); } | @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 StringWriter(); UnifiedDiffWriter.write(diff, f -> Collections.EMPTY_LIST, writer, 5); System.out.println(writer.toString()); }
@Test public void testWriteWithNewFile() throws URISyntaxException, IOException { List<String> original = new ArrayList<>(); List<String> revised = new ArrayList<>(); revised.add("line1"); revised.add("line2"); Patch<String> patch = DiffUtils.diff(original, revised); UnifiedDiff diff = new UnifiedDiff(); diff.addFile( UnifiedDiffFile.from(null, "revised", patch) ); StringWriter writer = new StringWriter(); UnifiedDiffWriter.write(diff, f -> original, writer, 5); System.out.println(writer.toString()); String[] lines = writer.toString().split("\\n"); assertEquals("--- /dev/null", lines[0]); assertEquals("+++ revised", lines[1]); assertEquals("@@ -0,0 +1,2 @@", lines[2]); } |
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 parseUnifiedDiff(InputStream stream); } | @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.getFiles().get(0); assertEquals("diff -r 83e41b73d115 -r a4438263b228 tests/test-check-pyflakes.t", file1.getDiffCommand()); assertEquals("tests/test-check-pyflakes.t", file1.getFromFile()); assertEquals("tests/test-check-pyflakes.t", file1.getToFile()); assertEquals(1, file1.getPatch().getDeltas().size()); assertNull(diff.getTail()); }
@Test public void testParseIssue98() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue98.diff")); assertThat(diff.getFiles().size()).isEqualTo(1); assertEquals(1, diff.getFiles().size()); final UnifiedDiffFile file1 = diff.getFiles().get(0); assertEquals("100644", file1.getDeletedFileMode()); assertEquals("src/test/java/se/bjurr/violations/lib/model/ViolationTest.java", file1.getFromFile()); assertThat(diff.getTail()).isEqualTo("2.25.1"); }
@Test public void testSimpleParse() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff(UnifiedDiffReaderTest.class.getResourceAsStream("jsqlparser_patch_1.diff")); System.out.println(diff); assertThat(diff.getFiles().size()).isEqualTo(2); UnifiedDiffFile file1 = diff.getFiles().get(0); assertThat(file1.getFromFile()).isEqualTo("src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt"); assertThat(file1.getPatch().getDeltas().size()).isEqualTo(3); assertThat(diff.getTail()).isEqualTo("2.17.1.windows.2\n"); }
@Test public void testSimpleParse2() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff(UnifiedDiffReaderTest.class.getResourceAsStream("jsqlparser_patch_1.diff")); System.out.println(diff); assertThat(diff.getFiles().size()).isEqualTo(2); UnifiedDiffFile file1 = diff.getFiles().get(0); assertThat(file1.getFromFile()).isEqualTo("src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt"); assertThat(file1.getPatch().getDeltas().size()).isEqualTo(3); AbstractDelta<String> first = file1.getPatch().getDeltas().get(0); assertThat(first.getSource().size()).isGreaterThan(0); assertThat(first.getTarget().size()).isGreaterThan(0); assertThat(diff.getTail()).isEqualTo("2.17.1.windows.2\n"); }
@Test public void testParseIssue46() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue46.diff")); System.out.println(diff); assertThat(diff.getFiles().size()).isEqualTo(1); UnifiedDiffFile file1 = diff.getFiles().get(0); assertThat(file1.getFromFile()).isEqualTo(".vhd"); assertThat(file1.getPatch().getDeltas().size()).isEqualTo(1); assertThat(diff.getTail()).isNull(); }
@Test public void testParseIssue33() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue33.diff")); assertThat(diff.getFiles().size()).isEqualTo(1); UnifiedDiffFile file1 = diff.getFiles().get(0); assertThat(file1.getFromFile()).isEqualTo("Main.java"); assertThat(file1.getPatch().getDeltas().size()).isEqualTo(1); assertThat(diff.getTail()).isNull(); assertThat(diff.getHeader()).isNull(); }
@Test public void testParseIssue51() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue51.diff")); System.out.println(diff); assertThat(diff.getFiles().size()).isEqualTo(2); UnifiedDiffFile file1 = diff.getFiles().get(0); assertThat(file1.getFromFile()).isEqualTo("f1"); assertThat(file1.getPatch().getDeltas().size()).isEqualTo(1); UnifiedDiffFile file2 = diff.getFiles().get(1); assertThat(file2.getFromFile()).isEqualTo("f2"); assertThat(file2.getPatch().getDeltas().size()).isEqualTo(1); assertThat(diff.getTail()).isNull(); }
@Test public void testParseIssue79() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue79.diff")); assertThat(diff.getFiles().size()).isEqualTo(1); UnifiedDiffFile file1 = diff.getFiles().get(0); assertThat(file1.getFromFile()).isEqualTo("test/Issue.java"); assertThat(file1.getPatch().getDeltas().size()).isEqualTo(0); assertThat(diff.getTail()).isNull(); assertThat(diff.getHeader()).isNull(); }
@Test public void testParseIssue84() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue84.diff")); assertThat(diff.getFiles().size()).isEqualTo(2); UnifiedDiffFile file1 = diff.getFiles().get(0); assertThat(file1.getFromFile()).isEqualTo("config/ant-phase-verify.xml"); assertThat(file1.getPatch().getDeltas().size()).isEqualTo(1); UnifiedDiffFile file2 = diff.getFiles().get(1); assertThat(file2.getFromFile()).isEqualTo("/dev/null"); assertThat(file2.getPatch().getDeltas().size()).isEqualTo(1); assertThat(diff.getTail()).isEqualTo("2.7.4"); assertThat(diff.getHeader()).startsWith("From b53e612a2ab5ff15d14860e252f84c0f343fe93a Mon Sep 17 00:00:00 2001"); } |
StringUtils { public static String htmlEntites(String str) { return str.replace("<", "<").replace(">", ">"); } 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 columnWidth); } | @Test public void testHtmlEntites() { assertEquals("<test>", 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 columnWidth); } | @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, int columnWidth); static String wrapText(String line, int columnWidth); } | @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(IllegalArgumentException.class, () -> StringUtils.wrapText("test", -1)); } |
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, matcher.start())); } list.add(matcher.group()); pos = matcher.end(); } if (pos < str.length()) { list.add(str.substring(pos)); } } return list; } private DiffRowGenerator(Builder builder); static Builder create(); List<DiffRow> generateDiffRows(List<String> original, List<String> revised); List<DiffRow> generateDiffRows(final List<String> original, Patch<String> patch); static final BiPredicate<String, String> DEFAULT_EQUALIZER; static final BiPredicate<String, String> IGNORE_WHITESPACE_EQUALIZER; static final Function<String, String> LINE_NORMALIZER_FOR_HTML; static final Function<String, List<String>> SPLITTER_BY_CHARACTER; static final Pattern SPLIT_BY_WORD_PATTERN; static final Function<String, List<String>> SPLITTER_BY_WORD; static final Pattern WHITESPACE_PATTERN; } | @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.splitStringPreserveDelimiter("test , test2", DiffRowGenerator.SPLIT_BY_WORD_PATTERN); System.out.println(list); assertEquals(5, list.size()); assertEquals("[test, , ,, , test2]", list.toString()); }
@Test public void testSplitString3() { List<String> list = DiffRowGenerator.splitStringPreserveDelimiter("test,test2,", DiffRowGenerator.SPLIT_BY_WORD_PATTERN); System.out.println(list); assertEquals(4, list.size()); assertEquals("[test, ,, test2, ,]", list.toString()); } |
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> changes); static Patch<T> generate(List<T> original, List<T> revised, List<Change> _changes, boolean includeEquals); } | @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, patch)); } catch (PatchFailedException e) { fail(e.getMessage()); } }
@Test public void testPatch_Delete() { final List<String> deleteTest_from = Arrays.asList("ddd", "fff", "ggg", "hhh"); final List<String> deleteTest_to = Arrays.asList("ggg"); final Patch<String> patch = DiffUtils.diff(deleteTest_from, deleteTest_to); try { assertEquals(deleteTest_to, DiffUtils.patch(deleteTest_from, patch)); } catch (PatchFailedException e) { fail(e.getMessage()); } }
@Test public void testPatch_Change() { final List<String> changeTest_from = Arrays.asList("aaa", "bbb", "ccc", "ddd"); final List<String> changeTest_to = Arrays.asList("aaa", "bxb", "cxc", "ddd"); final Patch<String> patch = DiffUtils.diff(changeTest_from, changeTest_to); try { assertEquals(changeTest_to, DiffUtils.patch(changeTest_from, patch)); } catch (PatchFailedException e) { fail(e.getMessage()); } } |
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) { progress.diffStart(); } PathNode path = buildPath(source, target, progress); List<Change> result = buildRevision(path, source, target); if (progress != null) { progress.diffEnd(); } return result; } MyersDiff(); MyersDiff(final BiPredicate<T, T> equalizer); @Override List<Change> computeDiff(final List<T> source, final List<T> target, DiffAlgorithmListener progress); } | @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)); assertNotNull(patch); assertEquals(4, patch.getDeltas().size()); assertEquals("Patch{deltas=[[DeleteDelta, position: 0, lines: [A, B]], [InsertDelta, position: 3, lines: [B]], [DeleteDelta, position: 5, lines: [B]], [InsertDelta, position: 7, lines: [C]]]}", patch.toString()); }
@Test public void testDiffMyersExample1ForwardWithListener() { List<String> original = Arrays.asList("A", "B", "C", "A", "B", "B", "A"); List<String> revised = Arrays.asList("C", "B", "A", "B", "A", "C"); List<String> logdata = new ArrayList<>(); final Patch<String> patch = Patch.generate(original, revised, new MyersDiff<String>().computeDiff(original, revised, new DiffAlgorithmListener() { @Override public void diffStart() { logdata.add("start"); } @Override public void diffStep(int value, int max) { logdata.add(value + " - " + max); } @Override public void diffEnd() { logdata.add("end"); } })); assertNotNull(patch); assertEquals(4, patch.getDeltas().size()); assertEquals("Patch{deltas=[[DeleteDelta, position: 0, lines: [A, B]], [InsertDelta, position: 3, lines: [B]], [DeleteDelta, position: 5, lines: [B]], [InsertDelta, position: 7, lines: [C]]]}", patch.toString()); System.out.println(logdata); assertEquals(8, logdata.size()); } |
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(List<T> original, List<T> revised); static Patch<T> diff(List<T> original, List<T> revised, boolean includeEqualParts); static Patch<String> diff(String sourceText, String targetText,
DiffAlgorithmListener progress); static Patch<T> diff(List<T> source, List<T> target,
BiPredicate<T, T> equalizer); static Patch<T> diff(List<T> original, List<T> revised,
DiffAlgorithmI<T> algorithm, DiffAlgorithmListener progress); static Patch<T> diff(List<T> original, List<T> revised,
DiffAlgorithmI<T> algorithm, DiffAlgorithmListener progress,
boolean includeEqualParts); static Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmI<T> algorithm); static Patch<String> diffInline(String original, String revised); static List<T> patch(List<T> original, Patch<T> patch); static List<T> unpatch(List<T> revised, Patch<T> patch); } | @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); assertEquals(new Chunk<>(1, Collections.<String>emptyList()), delta.getSource()); assertEquals(new Chunk<>(1, Arrays.asList("jjj", "kkk")), delta.getTarget()); }
@Test public void testDiff_Delete() { final Patch<String> patch = DiffUtils.diff(Arrays.asList("ddd", "fff", "ggg"), Arrays. asList("ggg")); assertNotNull(patch); assertEquals(1, patch.getDeltas().size()); final AbstractDelta<String> delta = patch.getDeltas().get(0); assertTrue(delta instanceof DeleteDelta); assertEquals(new Chunk<>(0, Arrays.asList("ddd", "fff")), delta.getSource()); assertEquals(new Chunk<>(0, Collections.<String>emptyList()), delta.getTarget()); }
@Test public void testDiff_Change() { final List<String> changeTest_from = Arrays.asList("aaa", "bbb", "ccc"); final List<String> changeTest_to = Arrays.asList("aaa", "zzz", "ccc"); final Patch<String> patch = DiffUtils.diff(changeTest_from, changeTest_to); assertNotNull(patch); assertEquals(1, patch.getDeltas().size()); final AbstractDelta<String> delta = patch.getDeltas().get(0); assertTrue(delta instanceof ChangeDelta); assertEquals(new Chunk<>(1, Arrays.asList("bbb")), delta.getSource()); assertEquals(new Chunk<>(1, Arrays.asList("zzz")), delta.getTarget()); }
@Test public void testDiff_EmptyList() { final Patch<String> patch = DiffUtils.diff(new ArrayList<>(), new ArrayList<>()); assertNotNull(patch); assertEquals(0, patch.getDeltas().size()); }
@Test public void testDiff_EmptyListWithNonEmpty() { final Patch<String> patch = DiffUtils.diff(new ArrayList<>(), Arrays.asList("aaa")); assertNotNull(patch); assertEquals(1, patch.getDeltas().size()); final AbstractDelta<String> delta = patch.getDeltas().get(0); assertTrue(delta instanceof InsertDelta); }
@Test public void testDiffIntegerList() { List<Integer> original = Arrays.asList(1, 2, 3, 4, 5); List<Integer> revised = Arrays.asList(2, 3, 4, 6); final Patch<Integer> patch = DiffUtils.diff(original, revised); for (AbstractDelta delta : patch.getDeltas()) { System.out.println(delta); } assertEquals(2, patch.getDeltas().size()); assertEquals("[DeleteDelta, position: 0, lines: [1]]", patch.getDeltas().get(0).toString()); assertEquals("[ChangeDelta, position: 4, lines: [5] to [6]]", patch.getDeltas().get(1).toString()); }
@Test public void testDiffMissesChangeForkDnaumenkoIssue31() { List<String> original = Arrays.asList("line1", "line2", "line3"); List<String> revised = Arrays.asList("line1", "line2-2", "line4"); Patch<String> patch = DiffUtils.diff(original, revised); assertEquals(1, patch.getDeltas().size()); assertEquals("[ChangeDelta, position: 1, lines: [line2, line3] to [line2-2, line4]]", patch.getDeltas().get(0).toString()); }
@Test @Disabled public void testPossibleDiffHangOnLargeDatasetDnaumenkoIssue26() throws IOException { ZipFile zip = new ZipFile(TestConstants.MOCK_FOLDER + "/large_dataset1.zip"); Patch<String> patch = DiffUtils.diff( readStringListFromInputStream(zip.getInputStream(zip.getEntry("ta"))), readStringListFromInputStream(zip.getInputStream(zip.getEntry("tb")))); assertEquals(1, patch.getDeltas().size()); }
@Test public void testDiffMyersExample1() { final Patch<String> patch = DiffUtils.diff(Arrays.asList("A", "B", "C", "A", "B", "B", "A"), Arrays.asList("C", "B", "A", "B", "A", "C")); assertNotNull(patch); assertEquals(4, patch.getDeltas().size()); assertEquals("Patch{deltas=[[DeleteDelta, position: 0, lines: [A, B]], [InsertDelta, position: 3, lines: [B]], [DeleteDelta, position: 5, lines: [B]], [InsertDelta, position: 7, lines: [C]]]}", patch.toString()); }
@Test public void testDiff_Equal() { final Patch<String> patch = DiffUtils.diff( Arrays.asList("hhh", "jjj", "kkk"), Arrays.asList("hhh", "jjj", "kkk"), true); assertNotNull(patch); assertEquals(1, patch.getDeltas().size()); final AbstractDelta<String> delta = patch.getDeltas().get(0); assertTrue(delta instanceof EqualDelta); assertEquals(new Chunk<>(0, Arrays.asList("hhh", "jjj", "kkk")), delta.getSource()); assertEquals(new Chunk<>(0, Arrays.asList("hhh", "jjj", "kkk")), delta.getTarget()); }
@Test public void testDiff_InsertWithEqual() { final Patch<String> patch = DiffUtils.diff(Arrays.asList("hhh"), Arrays. asList("hhh", "jjj", "kkk"), true); assertNotNull(patch); assertEquals(2, patch.getDeltas().size()); AbstractDelta<String> delta = patch.getDeltas().get(0); assertTrue(delta instanceof EqualDelta); assertEquals(new Chunk<>(0, Arrays.asList("hhh")), delta.getSource()); assertEquals(new Chunk<>(0, Arrays.asList("hhh")), delta.getTarget()); delta = patch.getDeltas().get(1); assertTrue(delta instanceof InsertDelta); assertEquals(new Chunk<>(1, Collections.<String>emptyList()), delta.getSource()); assertEquals(new Chunk<>(1, Arrays.asList("jjj", "kkk")), delta.getTarget()); }
@Test public void testDiff_ProblemIssue42() { final Patch<String> patch = DiffUtils.diff( Arrays.asList("The", "dog", "is", "brown"), Arrays.asList("The", "fox", "is", "down"), true); System.out.println(patch); assertNotNull(patch); assertEquals(4, patch.getDeltas().size()); assertThat(patch.getDeltas()).extracting(d -> d.getType().name()) .containsExactly("EQUAL", "CHANGE", "EQUAL", "CHANGE"); AbstractDelta<String> delta = patch.getDeltas().get(0); assertTrue(delta instanceof EqualDelta); assertEquals(new Chunk<>(0, Arrays.asList("The")), delta.getSource()); assertEquals(new Chunk<>(0, Arrays.asList("The")), delta.getTarget()); delta = patch.getDeltas().get(1); assertTrue(delta instanceof ChangeDelta); assertEquals(new Chunk<>(1, Arrays.asList("dog")), delta.getSource()); assertEquals(new Chunk<>(1, Arrays.asList("fox")), delta.getTarget()); delta = patch.getDeltas().get(2); assertTrue(delta instanceof EqualDelta); assertEquals(new Chunk<>(2, Arrays.asList("is")), delta.getSource()); assertEquals(new Chunk<>(2, Arrays.asList("is")), delta.getTarget()); delta = patch.getDeltas().get(3); assertTrue(delta instanceof ChangeDelta); assertEquals(new Chunk<>(3, Arrays.asList("brown")), delta.getSource()); assertEquals(new Chunk<>(3, Arrays.asList("down")), delta.getTarget()); } |
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()) { revList.add(character.toString()); } Patch<String> patch = DiffUtils.diff(origList, revList); for (AbstractDelta<String> delta : patch.getDeltas()) { delta.getSource().setLines(compressLines(delta.getSource().getLines(), "")); delta.getTarget().setLines(compressLines(delta.getTarget().getLines(), "")); } return patch; } private DiffUtils(); static Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmListener progress); static Patch<T> diff(List<T> original, List<T> revised); static Patch<T> diff(List<T> original, List<T> revised, boolean includeEqualParts); static Patch<String> diff(String sourceText, String targetText,
DiffAlgorithmListener progress); static Patch<T> diff(List<T> source, List<T> target,
BiPredicate<T, T> equalizer); static Patch<T> diff(List<T> original, List<T> revised,
DiffAlgorithmI<T> algorithm, DiffAlgorithmListener progress); static Patch<T> diff(List<T> original, List<T> revised,
DiffAlgorithmI<T> algorithm, DiffAlgorithmListener progress,
boolean includeEqualParts); static Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmI<T> algorithm); static Patch<String> diffInline(String original, String revised); static List<T> patch(List<T> original, Patch<T> patch); static List<T> unpatch(List<T> revised, Patch<T> patch); } | @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).getSource().getLines().size()); assertEquals("test", patch.getDeltas().get(0).getTarget().getLines().get(0)); }
@Test public void testDiffInline2() { final Patch<String> patch = DiffUtils.diffInline("es", "fest"); assertEquals(2, patch.getDeltas().size()); assertTrue(patch.getDeltas().get(0) instanceof InsertDelta); assertEquals(0, patch.getDeltas().get(0).getSource().getPosition()); assertEquals(2, patch.getDeltas().get(1).getSource().getPosition()); assertEquals(0, patch.getDeltas().get(0).getSource().getLines().size()); assertEquals(0, patch.getDeltas().get(1).getSource().getLines().size()); assertEquals("f", patch.getDeltas().get(0).getTarget().getLines().get(0)); assertEquals("t", patch.getDeltas().get(1).getTarget().getLines().get(0)); } |
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/select/SelectTest.java", "src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java"); } |
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(String line, List<String> list, int maxWidth); static int findBreakBefore(String line, int start); static int findBreakAfter(String line, int start); static List<String> splitIntoLines(String str); } | @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 get seperated into two segement and the filter continues the filtering process with the second segment until the end of the gps track is reached."; int maxWidth = 60; LOG.info(StringUtils.wrapString(str, maxWidth)); } |
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(@StringRes int resourceId); @NonNull static UnparsedLexString say(@NonNull CharSequence template); @NonNull static LexList list(@NonNull List<? extends CharSequence> items); @NonNull static LexList list(@NonNull CharSequence... text); } | @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 UnparsedLexString say(@StringRes int resourceId); @NonNull static UnparsedLexString say(@NonNull CharSequence template); @NonNull static LexList list(@NonNull List<? extends CharSequence> items); @NonNull static LexList list(@NonNull CharSequence... text); } | @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_throwsException_onUninflatedKeys() { Lex.say("This is {KEY_ONE} and {KEY_TWO}.").with(LexKey.KEY_ONE, "key one").make(); }
@Test(expected = LexDuplicateKeyException.class) public void with_throwsException_onDuplicateKeys() { Lex.say("This is {KEY_ONE}.") .with(LexKey.KEY_ONE, "a test") .with(LexKey.KEY_ONE, "a test") .make(); }
@Test public void with_wrappedIn() { CharSequence result = Lex.say(R.string.this_is_a_template) .with(LexKey.SOMETHING, "test") .wrappedIn(new ForegroundColorSpan(Color.RED)) .make(); final int spanCount = ((SpannableStringBuilder) result) .getSpans(0, result.length(), Object.class).length; assertEquals(2, spanCount); }
@Test public void with_resourceId() { assertEquals("This is a test.", Lex .say(R.string.this_is_a_template) .with(LexKey.SOMETHING, R.string.test) .makeString()); }
@Test public void withNumber() { assertEquals("3 fingers", Lex .say("{COUNT} fingers") .withNumber(LexKey.COUNT, 3) .makeString()); }
@Test public void withNumber_andNumberFormat() { assertEquals("3.5 average", Lex .say("{COUNT} average") .withNumber(LexKey.COUNT, 3.5, new DecimalFormat("#.#")) .makeString()); }
@Test public void withPlural() { int count = 3; assertEquals("3 Names", Lex .say("{COUNT} {SOMETHING}") .with(LexKey.COUNT, String.valueOf(count)) .withPlural(LexKey.SOMETHING, count, R.plurals.name).makeString()); count = 1; assertEquals("1 Name", Lex .say("{COUNT} {SOMETHING}") .with(LexKey.COUNT, String.valueOf(count)) .withPlural(LexKey.SOMETHING, count, R.plurals.name).makeString()); }
@Test public void to_populatesTextView() { TextView tv = new TextView(RuntimeEnvironment.application); Lex.say(R.string.this_is_a_template) .with(LexKey.SOMETHING, "test") .into(tv); assertEquals("This is a test.", tv.getText().toString()); }
@Test(expected = LexNotInitializedException.class) public void make_throwsException_ifNotInitialized() { Lex.resources = null; assertEquals("This is key1 and key2.", Lex.say("This is {KEY_ONE} and {KEY_TWO}.") .with(LexKey.KEY_ONE, "key1") .with(LexKey.KEY_TWO, "key2").makeString()); }
@Test public void makeString_inflatesKeys() { assertEquals("This is key1 and key2.", Lex.say("This is {KEY_ONE} and {KEY_TWO}.") .with(LexKey.KEY_ONE, "key1") .with(LexKey.KEY_TWO, "key2").makeString()); }
@Test public void makeString_withResId_inflatesKeys() { assertEquals("some thing.", Lex.say(R.string.thing_template) .with(LexKey.SOMETHING, "thing").makeString()); }
@Test public void make_retainsSpans() { SpannableStringBuilder ssb = new SpannableStringBuilder("Hello {KEY_ONE}, you are {KEY_TWO} years old."); ssb.setSpan("bold", 5, 28, 0); CharSequence formatted = Lex.say(ssb).with(LexKey.KEY_ONE, "Abe").with(LexKey.KEY_TWO, "20").make(); assertEquals("Hello Abe, you are 20 years old.", formatted.toString()); assertTrue(formatted instanceof Spannable); }
@Test public void say_withCustomDelimiters_parsesKeys() { assertEquals("This is key1 and key2.", Lex.say("This is <<KEY_ONE>> and <<KEY_TWO>>.") .delimitBy("<<", ">>") .with(LexKey.KEY_ONE, "key1") .with(LexKey.KEY_TWO, "key2").makeString()); }
@Test(expected = LexInvalidKeyException.class) public void with_throwsException_onNullKey() { Lex.say("This is {KEY_ONE}.").with(null, "a test").make(); }
@Test(expected = LexInvalidValueException.class) public void with_throwsException_onNullValue() { Lex.say("This is {KEY_ONE}.").with(LexKey.KEY_ONE, null).make(); }
@Test(expected = LexInvalidKeyException.class) public void make_throwsException_ifMissingNonOptionalKeys() { Lex.say("This is {KEY_ONE}.") .with(LexKey.KEY_ONE, "key one") .with(LexKey.KEY_TWO, " key two").make(); }
@Test(expected = LexInvalidKeyException.class) public void make_throwsException_ifWrongKeys() { Lex.say("This is {KEY_ONE}.").with(LexKey.KEY_TWO, "a test").make(); } |
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 UnparsedLexString say(@StringRes int resourceId); @NonNull static UnparsedLexString say(@NonNull CharSequence template); @NonNull static LexList list(@NonNull List<? extends CharSequence> items); @NonNull static LexList list(@NonNull CharSequence... text); } | @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 ").make().toString()); }
@Test public void list_ofThree_usesLastItemSeparator() { assertEquals("One, Two, and Three", Lex.list("One", "Two", "Three") .separator(", ") .lastItemSeparator(", and ").make().toString()); }
@Test public void list_ofThree_usesSeparator() { assertEquals("One, Two, Three", Lex.list("One", "Two", "Three") .separator(", ") .make().toString()); }
@Test public void list_ofMoreThanThree_usesLastItemSeparator() { assertEquals("One, Two, Three, and Four", Lex.list("One", "Two", "Three", "Four") .separator(", ") .lastItemSeparator(", and ").make().toString()); }
@Test public void list_usesTwoItemSeparator_IfTwoItems() { assertEquals("One and Two", Lex.list("One", "Two") .separator(", ") .twoItemSeparator(" and ") .lastItemSeparator(", and ").make().toString()); }
@Test public void list_ofNoItems_usesEmptyText() { assertEquals("No items.", Lex.list(new CharSequence[]{}) .separator(", ") .twoItemSeparator(" and ") .lastItemSeparator(", and ") .emptyText("No items.") .make().toString()); }
@Test public void list_wrappedInSpan() { final CharSequence result = Lex .list("One", "Two") .wrappedIn(new ForegroundColorSpan(Color.RED)) .separator(", ") .make(); final int spanCount = ((SpannableStringBuilder) result) .getSpans(0, result.length(), Object.class).length; assertEquals(2, spanCount); }
@Test public void list_separator_withResourceId() { assertEquals("One and Two", Lex.list("One", "Two").separator(R.string.and_separator).makeString()); }
@Test public void list_twoItemSeparator_withResourceId() { assertEquals("One and Two", Lex.list("One", "Two").twoItemSeparator(R.string.and_separator).makeString()); }
@Test public void list_lastItemSeparator_withResourceId() { assertEquals("One, Two and Three", Lex .list("One", "Two", "Three") .separator(R.string.comma_separator) .lastItemSeparator(R.string.and_separator).makeString()); }
@Test(expected = LexNoSeparatorException.class) public void list_ofThreeOrMoreItemsWithoutSeparator_throwsLexNoSeparatorException() { Lex.list("One", "Two", "Three", "Four").make(); }
@Test public void list_into_populatesTextView() { TextView tv = new TextView(RuntimeEnvironment.application); Lex.list("One", "Two") .separator(R.string.and_separator) .into(tv); assertEquals("One and Two", tv.getText().toString()); } |
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(new FileInputStream(file))); final NodeList list = doc.getElementsByTagName("Object"); for (int i = 0; i < list.getLength(); i++) { final Node node = list.item(i); try { final PsIssue issue = new PsIssue(); issue.ruleId = getNodeByAttributeName(node, "RuleName").getTextContent(); issue.message = getNodeByAttributeName(node, "Message").getTextContent(); String line = getNodeByAttributeName(node, "Line").getTextContent(); if (!StringUtils.isEmpty(line)) { issue.line = Integer.parseInt(line); } issue.severity = getNodeByAttributeName(node, "Severity").getTextContent(); issue.file = getNodeByAttributeName(node, "File").getTextContent(); issues.add(issue); } catch (Exception e) { LOGGER.warn("Unexpected error reading results from: " + node.getTextContent(), e); } } return issues; } List<PsIssue> read(final File file); } | @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() throws Throwable { File file = temp.newFile("main", "results.xml"); FileUtils.copyURLToFile(getClass().getResource("/results/psanalyzerSingle.xml"), file); List<PsIssue> issues = sut.read(file); Assert.assertEquals(1, issues.size()); PsIssue issue = issues.get(0); Assert.assertEquals("C:\\test.ps1", issue.file); Assert.assertEquals(5, issue.line); Assert.assertEquals("Message", issue.message); Assert.assertEquals("PSAvoidUsingPositionalParameters", issue.ruleId); Assert.assertEquals("Information", issue.severity); } |
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(file))); tokens.setComplexity(Integer.parseInt(doc.getDocumentElement().getAttribute("complexity"))); final NodeList list = doc.getElementsByTagName("Token"); for (int i = 0; i < list.getLength(); i++) { try { final Node node = list.item(i); final Tokens.Token token = new Tokens.Token(); token.setText(getChildByName(node, "Text").getTextContent()); token.setValue(getChildByName(node, "Value").getTextContent()); token.setTokenFlags(getChildByName(node, "TokenFlags").getTextContent()); token.setKind(getChildByName(node, "Kind").getTextContent()); token.setcType(getChildByName(node, "CType").getTextContent()); token.setStartLineNumber(Integer.parseInt(getChildByName(node, "StartLineNumber").getTextContent())); token.setEndLineNumber(Integer.parseInt(getChildByName(node, "EndLineNumber").getTextContent())); token.setStartOffset(Long.parseLong(getChildByName(node, "StartOffset").getTextContent())); token.setEndOffset(Long.parseLong(getChildByName(node, "EndOffset").getTextContent())); token.setStartColumnNumber( Integer.parseInt(getChildByName(node, "StartColumnNumber").getTextContent())); token.setEndColumnNumber(Integer.parseInt(getChildByName(node, "EndColumnNumber").getTextContent())); tokens.getTokens().add(token); } catch (Exception e) { LOGGER.warn("Unexpected error reading results", e); } } return tokens; } Tokens read(final File file); } | @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 Throwable { File file = temp.newFile("main", "results.xml"); FileUtils.copyURLToFile(getClass().getResource("/results/tokensSingle.xml"), file); Tokens tokens = sut.read(file); Assert.assertEquals(1, tokens.getTokens().size()); Assert.assertEquals(10, tokens.getComplexity()); Token token = tokens.getTokens().get(0); Assert.assertEquals("Token", token.getcType()); Assert.assertEquals(32, token.getEndColumnNumber()); Assert.assertEquals(2, token.getEndLineNumber()); Assert.assertEquals(31, token.getEndOffset()); Assert.assertEquals("Comment", token.getKind()); Assert.assertEquals(4, token.getStartColumnNumber()); Assert.assertEquals(1, token.getStartLineNumber()); Assert.assertEquals("#Import-Module PSScriptAnalyzer", token.getText()); Assert.assertEquals("ParseModeInvariant", token.getTokenFlags()); Assert.assertEquals("", token.getValue()); } |
ScriptAnalyzerRulesDefinition implements RulesDefinition { public void define(final Context context) { final String repositoryKey = ScriptAnalyzerRulesDefinition.getRepositoryKeyForLanguage(); final String repositoryName = ScriptAnalyzerRulesDefinition.getRepositoryNameForLanguage(); defineRulesForLanguage(context, repositoryKey, repositoryName, PowershellLanguage.KEY); } void define(final Context context); static String getRepositoryKeyForLanguage(); static String getRepositoryNameForLanguage(); } | @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.indexOf(e.getKey()); while (index != -1) { sb.replace(index, index + key.length(), e.getValue()); index = sb.indexOf(key, index + key.length()); } } return sb.toString(); } DictionaryLookup(Dictionary dictionary); @Override List<WordData> lookup(CharSequence word); static String applyReplacements(CharSequence word, LinkedHashMap<String, String> replacements); @Override Iterator<WordData> iterator(); Dictionary getDictionary(); char getSeparatorChar(); } | @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", conversion)); assertEquals("fizdrygałką", DictionaryLookup.applyReplacements("fizdrygałk\\a", conversion)); assertEquals("George Bush", DictionaryLookup.applyReplacements("Barack Bush", conversion)); assertEquals("xxxxxxxx", DictionaryLookup.applyReplacements("____", conversion)); } |
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 = ""; int keyLength = 0; boolean found = false; for (final String auxKey : replacementsTheRest.keySet()) { int auxIndex = sb.indexOf(auxKey, fromIndex); if (auxIndex > -1 && (auxIndex < index || (auxIndex == index && !(auxKey.length() < keyLength)))) { index = auxIndex; key = auxKey; keyLength = auxKey.length(); } } if (index < MAX_WORD_LENGTH) { for (final String rep : replacementsTheRest.get(key)) { if (!found) { replaced.addAll(getAllReplacements(str, index + key.length(), level + 1)); found = true; } int ind = sb.indexOf(rep, fromIndex - rep.length() + 1); if (rep.length() > key.length() && ind > -1 && (ind == index || ind == index - rep.length() + 1)) { continue; } sb.replace(index, index + key.length(), rep); replaced.addAll(getAllReplacements(sb.toString(), index + rep.length(), level + 1)); sb.setLength(0); sb.append(str); } } if (!found) { replaced.add(sb.toString()); } return replaced; } Speller(final Dictionary dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; } | @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("taught")); assertTrue(!reps.contains("tgheached")); }
@Test public void testGetAllReplacements() throws IOException { final URL url = getClass().getResource("test-utf-spell.dict"); final Speller spell = new Speller(Dictionary.read(url)); assertTrue(spell.isMisspelled("rzarzerzarzu")); assertEquals("[rzarzerzarzu]", Arrays.toString(spell.getAllReplacements("rzarzerzarzu", 0, 0).toArray())); } |
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(wordToCheck.charAt(0)); return wordToCheck.length() > 0 && (!dictionaryMetadata.isIgnoringPunctuation() || isAlphabetic) && (!dictionaryMetadata.isIgnoringNumbers() || containsNoDigit(wordToCheck)) && !(dictionaryMetadata.isIgnoringCamelCase() && isCamelCase(wordToCheck)) && !(dictionaryMetadata.isIgnoringAllUppercase() && isAlphabetic && isAllUppercase(wordToCheck)) && !isInDictionary(wordToCheck) && (!dictionaryMetadata.isConvertingCase() || !(!isMixedCase(wordToCheck) && (isInDictionary(wordToCheck.toLowerCase(dictionaryMetadata.getLocale())) || isAllUppercase(wordToCheck) && isInDictionary(initialUppercase(wordToCheck))))); } Speller(final Dictionary dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; } | @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(!spell.isMisspelled("SłowozGarbem")); assertTrue(!spell.isMisspelled("Ćwikła")); assertTrue(!spell.isMisspelled("TOJESTTEST")); final Speller oldStyleSpell = new Speller(dictionary, 1); assertTrue(oldStyleSpell.isMisspelled("Paragraf22")); assertTrue(oldStyleSpell.isMisspelled("!")); assertTrue(oldStyleSpell.isMisspelled("Abaka")); final URL url1 = getClass().getResource("test-infix.dict"); final Speller spell1 = new Speller(Dictionary.read(url1)); assertTrue(!spell1.isMisspelled("Rzekunia")); assertTrue(spell1.isAllUppercase("RZEKUNIA")); assertTrue(spell1.isMisspelled("RZEKUNIAA")); assertTrue(!spell1.isMisspelled("RZEKUNIA")); } |
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 Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; } | @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.isCamelCase("CAmel")); assertTrue(!spell.isCamelCase("")); assertTrue(!spell.isCamelCase(null)); } |
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 dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; } | @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.isNotCapitalizedWord("cAmel")); assertTrue(spell.isNotCapitalizedWord("CAmel")); assertTrue(spell.isNotCapitalizedWord("")); } |
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(final Dictionary dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; } | @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("Mitmuss")); reps = speller.findReplacements("Walt"); assertTrue(reps.get(0).equals("Wald")); assertTrue(reps.get(1).equals("Band")); reps = speller.findReplacements("yout"); assertTrue(reps.get(0).equals("youd")); assertTrue(reps.get(1).equals("ijond")); assertTrue(reps.get(2).equals("ijo")); reps = speller.findReplacements("yousut"); assertTrue(reps.get(0).equals("ijoussud")); assertTrue(reps.get(1).equals("ijousod")); assertTrue(reps.get(2).equals("ijoussuud")); assertTrue(reps.get(3).equals("youd")); reps = speller.findReplacements("yo"); assertTrue(reps.get(0).equals("ijo")); assertTrue(reps.get(1).equals("ij")); reps = speller.findReplacements("Clarkem"); assertTrue(reps.get(0).equals("Ciarkę")); assertTrue(reps.get(1).equals("Clarke")); assertTrue(reps.get(2).equals("Clarkiem")); assertTrue(reps.get(3).equals("Clarkom")); assertTrue(reps.get(4).equals("Czarkę")); }
@Test public void testIssue94() throws Exception { final URL url = getClass().getResource("issue94.dict"); final Speller speller = new Speller(Dictionary.read(url)); List<String> reps = speller.findReplacements("schänken"); assertTrue(reps.get(0).equals("Schänken")); assertTrue(reps.get(1).equals("schenken")); }
@Test public void testFindReplacements() throws IOException { final Speller spell = new Speller(dictionary, 1); assertTrue(spell.findReplacements("abka").contains("abak")); List<String> reps = spell.findReplacements("bak"); for (final String word: reps) { assertTrue(spell.isInDictionary(word)); } assertTrue(spell.findReplacements("abka~~").isEmpty()); assertTrue(!spell.findReplacements("Rezkunia").contains("Rzekunia")); final URL url1 = getClass().getResource("test-infix.dict"); final Speller spell1 = new Speller(Dictionary.read(url1)); assertTrue(spell1.findReplacements("Rezkunia").contains("Rzekunia")); assertTrue(spell1.findReplacements("Rzękunia").contains("Rzekunia")); assertTrue(spell1.isInDictionary("Rzekunia")); assertTrue(spell1.findReplacements("Rzekunia").isEmpty()); assertTrue(spell1.findReplacements("Strefakibica").isEmpty()); assertTrue(spell1.findReplacements("").isEmpty()); assertTrue(spell1.findReplacements("\u0000").isEmpty()); assertTrue(spell1.findReplacements("«…»").isEmpty()); assertTrue(spell1.findReplacements("+").isEmpty()); }
@Test public void testFindReplacementsInUTF() throws IOException { final URL url = getClass().getResource("test-utf-spell.dict"); final Speller spell = new Speller(Dictionary.read(url)); assertTrue(spell.findReplacements("gęslą").contains("gęślą")); assertTrue(spell.findReplacements("ćwikla").contains("ćwikła")); assertTrue(spell.findReplacements("Swierczewski").contains("Świerczewski")); assertTrue(spell.findReplacements("zółwiową").contains("żółwiową")); assertTrue(spell.findReplacements("Żebrowsk").contains("Żebrowski")); assertTrue(spell.findReplacements("święto").contains("Święto")); assertTrue(spell.findReplacements("gesla").contains("gęślą")); assertTrue(spell.findReplacements("swieto").contains("Święto")); assertTrue(spell.findReplacements("zolwiowa").contains("żółwiową")); assertTrue(spell.findReplacements("jexn").contains("jaźń")); assertTrue(spell.findReplacements("zażulv").contains("zażółć")); assertTrue(spell.findReplacements("zarzulv").contains("zażółć")); assertTrue(spell.findReplacements("Rzebrowski").contains("Żebrowski")); assertTrue(spell.findReplacements("rzółw").contains("żółw")); assertTrue(spell.findReplacements("Świento").contains("Święto")); assertTrue(spell.findReplacements("zArzółć").get(0).equals("zażółć")); } |
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 (OutputStream os = new BufferedOutputStream(Files.newOutputStream(output))) { serializer.serialize(fsa, os); } return ExitStatus.SUCCESS; } FSACompile(); FSACompile(Path input,
Path output,
SerializationFormat format,
boolean acceptBom,
boolean acceptCr,
boolean ignoreEmpty); @Override ExitStatus call(); static void main(String[] args); } | @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 (OutputStream os = Files.newOutputStream(input)) { Iterator<String> i = sequences.iterator(); while (i.hasNext()) { os.write(i.next().getBytes(StandardCharsets.UTF_8)); if (!i.hasNext() && randomBoolean()) { break; } else { os.write('\n'); if (randomBoolean()) { os.write('\n'); } } } } SerializationFormat format = randomFrom(SerializationFormat.values()); Assertions.assertThat(new FSACompile( input, output, format, false, false, true).call()).isEqualTo(ExitStatus.SUCCESS); try (InputStream is = Files.newInputStream(output)) { FSA fsa = FSA.read(is); Assertions.assertThat(fsa).isNotNull(); Set<String> result = new HashSet<>(); for (ByteBuffer bb : fsa) { result.add(BufferUtils.toString(bb, StandardCharsets.UTF_8)); } Assertions.assertThat(result).containsOnlyElementsOf(sequences); } } |
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 ignoreEmpty); @Override ExitStatus call(); static void main(String[] args); } | @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[] { "--exit", "false", "--input", input.toAbsolutePath().toString(), "--output", output.toAbsolutePath().toString() }); return null; } }); Assertions.assertThat(out).contains("--ignore-empty"); }
@Test public void testCrWarning() throws Exception { final Path input = newTempFile(); final Path output = newTempFile(); Files.write(input, "abc\r\ndef\r\n".getBytes(StandardCharsets.US_ASCII)); String out = sysouts(new Callable<Void>() { @Override public Void call() throws Exception { FSACompile.main(new String[] { "--exit", "false", "--input", input.toAbsolutePath().toString(), "--output", output.toAbsolutePath().toString() }); return null; } }); Assertions.assertThat(out).contains("CR"); }
@Test public void testBomWarning() throws Exception { final Path input = newTempFile(); final Path output = newTempFile(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }); baos.write("abc\ndef\nxyz".getBytes(UTF8)); Files.write(input, baos.toByteArray()); String out = sysouts(new Callable<Void>() { @Override public Void call() throws Exception { FSACompile.main(new String[] { "--exit", "false", "--input", input.toAbsolutePath().toString(), "--output", output.toAbsolutePath().toString() }); return null; } }); Assertions.assertThat(out).contains("UTF-8 BOM"); } |
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(word, dictionaryMetadata.getInputConversionPairs()); } formsList.wrap(forms, 0, 0); charBuffer = BufferUtils.clearAndEnsureCapacity(charBuffer, word.length()); for (int i = 0; i < word.length(); i++) { char chr = word.charAt(i); if (chr == separatorChar) { return formsList; } charBuffer.put(chr); } charBuffer.flip(); try { byteBuffer = BufferUtils.charsToBytes(encoder, charBuffer, byteBuffer); } catch (UnmappableInputException e) { return formsList; } final MatchResult match = matcher.match(matchResult, byteBuffer .array(), 0, byteBuffer.remaining(), rootNode); if (match.kind == SEQUENCE_IS_A_PREFIX) { final int arc = fsa.getArc(match.node, separator); if (arc != 0 && !fsa.isArcFinal(arc)) { int formsCount = 0; finalStatesIterator.restartFrom(fsa.getEndNode(arc)); while (finalStatesIterator.hasNext()) { final ByteBuffer bb = finalStatesIterator.next(); final byte[] ba = bb.array(); final int bbSize = bb.remaining(); if (formsCount >= forms.length) { forms = Arrays.copyOf(forms, forms.length + EXPAND_SIZE); for (int k = 0; k < forms.length; k++) { if (forms[k] == null) forms[k] = new WordData(decoder); } } final WordData wordData = forms[formsCount++]; if (dictionaryMetadata.getOutputConversionPairs().isEmpty()) { wordData.update(byteBuffer, word); } else { wordData.update(byteBuffer, applyReplacements(word, dictionaryMetadata.getOutputConversionPairs())); } assert prefixBytes <= bbSize : sequenceEncoder.getClass() + " >? " + bbSize; int sepPos; for (sepPos = prefixBytes; sepPos < bbSize; sepPos++) { if (ba[sepPos] == separator) { break; } } wordData.stemBuffer = sequenceEncoder.decode(wordData.stemBuffer, byteBuffer, ByteBuffer.wrap(ba, 0, sepPos)); sepPos++; final int tagSize = bbSize - sepPos; if (tagSize > 0) { wordData.tagBuffer = BufferUtils.clearAndEnsureCapacity(wordData.tagBuffer, tagSize); wordData.tagBuffer.put(ba, sepPos, tagSize); wordData.tagBuffer.flip(); } } formsList.wrap(forms, 0, formsCount); } } else { } return formsList; } DictionaryLookup(Dictionary dictionary); @Override List<WordData> lookup(CharSequence word); static String applyReplacements(CharSequence word, LinkedHashMap<String, String> replacements); @Override Iterator<WordData> iterator(); Dictionary getDictionary(); char getSeparatorChar(); } | @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 DictionaryLookup(new Dictionary(fsa, metadata)); assertEquals(0, s.lookup("l+A").size()); } |
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("The metadata file (with at least the column separator and byte encoding) " + "is required. Check out the examples."); return ExitStatus.ERROR_OTHER; } final Path output = metadataPath.resolveSibling( metadataPath.getFileName().toString().replaceAll( "\\." + DictionaryMetadata.METADATA_FILE_EXTENSION + "$", ".dict")); if (!overwrite && Files.exists(output)) { throw new ExitStatusException(ExitStatus.ERROR_CONFIRMATION_REQUIRED, "Output dictionary file already exists: %s, use %s to override.", output, ARG_OVERWRITE); } final DictionaryMetadata metadata; try (InputStream is = new BufferedInputStream(Files.newInputStream(metadataPath))) { metadata = DictionaryMetadata.read(is); } final List<byte[]> sequences = binaryInput.readBinarySequences(input, (byte) '\n'); final CharsetDecoder charsetDecoder = metadata.getDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); final byte separator = metadata.getSeparator(); final ISequenceEncoder sequenceEncoder = metadata.getSequenceEncoderType().get(); if (!sequences.isEmpty()) { Iterator<byte[]> i = sequences.iterator(); byte [] row = i.next(); final int separatorCount = countOf(separator, row); if (separatorCount < 1 || separatorCount > 2) { throw new ExitStatusException(ExitStatus.ERROR_OTHER, "Invalid input. Each row must consist of [base,inflected,tag?] columns, where ',' is a " + "separator character (declared as: %s). This row contains %d separator characters: %s", Character.isJavaIdentifierPart(metadata.getSeparatorAsChar()) ? "'" + Character.toString(metadata.getSeparatorAsChar()) + "'" : "0x" + Integer.toHexString((int) separator & 0xff), separatorCount, new String(row, charsetDecoder.charset())); } while (i.hasNext()) { row = i.next(); int count = countOf(separator, row); if (count != separatorCount) { throw new ExitStatusException(ExitStatus.ERROR_OTHER, "The number of separators (%d) is inconsistent with previous lines: %s", count, new String(row, charsetDecoder.charset())); } } } ByteBuffer encoded = ByteBuffer.allocate(0); ByteBuffer source = ByteBuffer.allocate(0); ByteBuffer target = ByteBuffer.allocate(0); ByteBuffer tag = ByteBuffer.allocate(0); ByteBuffer assembled = ByteBuffer.allocate(0); for (int i = 0, max = sequences.size(); i < max; i++) { byte[] row = sequences.get(i); int sep1 = indexOf(separator, row, 0); int sep2 = indexOf(separator, row, sep1 + 1); if (sep2 < 0) { sep2 = row.length; } source = BufferUtils.clearAndEnsureCapacity(source, sep1); source.put(row, 0, sep1); source.flip(); final int len = sep2 - (sep1 + 1); target = BufferUtils.clearAndEnsureCapacity(target, len); target.put(row, sep1 + 1, len); target.flip(); final int len2 = row.length - (sep2 + 1); tag = BufferUtils.clearAndEnsureCapacity(tag, len2); if (len2 > 0) { tag.put(row, sep2 + 1, len2); } tag.flip(); encoded = sequenceEncoder.encode(encoded, target, source); assembled = BufferUtils.clearAndEnsureCapacity(assembled, target.remaining() + 1 + encoded.remaining() + 1 + tag.remaining()); assembled.put(target); assembled.put(separator); assembled.put(encoded); if (tag.hasRemaining()) { assembled.put(separator); assembled.put(tag); } assembled.flip(); sequences.set(i, BufferUtils.toArray(assembled)); } Collections.sort(sequences, FSABuilder.LEXICAL_ORDERING); FSA fsa = FSABuilder.build(sequences); FSASerializer serializer = format.getSerializer(); try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(output))) { serializer.serialize(fsa, os); } if (validate) { DictionaryLookup dictionaryLookup = new DictionaryLookup(new Dictionary(fsa, metadata)); for (Iterator<?> i = dictionaryLookup.iterator(); i.hasNext(); i.next()) { } } return ExitStatus.SUCCESS; } DictCompile(); DictCompile(Path input,
boolean overwrite,
boolean validate,
boolean acceptBom,
boolean acceptCr,
boolean ignoreEmpty); @Override ExitStatus call(); static void main(String[] args); } | @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 writer = Files.newBufferedWriter(metadata, StandardCharsets.UTF_8)) { DictionaryMetadata.builder() .separator(separator) .encoder(randomFrom(EncoderType.values())) .encoding(StandardCharsets.UTF_8) .build() .write(writer); } final boolean useTags = randomBoolean(); Set<String> sequences = new LinkedHashSet<>(); for (int seqs = randomIntBetween(0, 100); --seqs >= 0;) { String base; switch (randomIntBetween(0, 5)) { case 0: base = randomAsciiLettersOfLength(('A' - separator) & 0xff); break; default: base = randomAsciiLettersOfLengthBetween(1, 100); break; } String inflected; switch (randomIntBetween(0, 5)) { case 0: inflected = base; break; case 1: inflected = randomAsciiLettersOfLengthBetween(0, 5) + base; break; case 3: inflected = base + randomAsciiLettersOfLengthBetween(0, 5); break; case 4: inflected = randomAsciiLettersOfLengthBetween(0, 5) + base + randomAsciiLettersOfLengthBetween(0, 5); break; default: inflected = randomAsciiLettersOfLengthBetween(0, 200); break; } sequences.add( base + separator + inflected + (useTags ? (separator + randomAsciiLettersOfLengthBetween(0, 10)) : "")); } final boolean ignoreEmpty = randomBoolean(); try (Writer writer = Files.newBufferedWriter(input, StandardCharsets.UTF_8)) { for (String in : sequences) { writer.write(in); writer.write('\n'); if (ignoreEmpty && randomBoolean()) { writer.write('\n'); } } } boolean validate = randomBoolean(); Assertions.assertThat(new DictCompile(input, false, validate, false, false, ignoreEmpty).call()) .isEqualTo(ExitStatus.SUCCESS); Path dict = input.resolveSibling("dictionary.dict"); Assertions.assertThat(dict).isRegularFile(); DictionaryLookup dictionaryLookup = new DictionaryLookup(Dictionary.read(dict)); Set<String> reconstructed = new LinkedHashSet<>(); for (WordData wd : dictionaryLookup) { reconstructed.add("" + wd.getStem() + separator + wd.getWord() + (useTags ? separator : "") + (wd.getTag() == null ? "" : wd.getTag())); } Assertions.assertThat(reconstructed).containsOnlyElementsOf(sequences); if (useTags && sequences.size() == 1) { String onlyOne = sequences.iterator().next(); if (onlyOne.endsWith(Character.toString(separator))) { sequences.clear(); sequences.add(onlyOne.substring(0, onlyOne.length() - 1)); } } Files.delete(input); Assertions.assertThat(new DictDecompile(dict, null, true, validate).call()) .isEqualTo(ExitStatus.SUCCESS); List<String> allLines = Files.readAllLines(input, StandardCharsets.UTF_8); Assertions.assertThat(allLines).containsOnlyElementsOf(sequences); } |
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(byte[][] input); static FSA build(Iterable<byte[]> input); Map<InfoEntry, Object> getInfo(); static final Comparator<byte[]> LEXICAL_ORDERING; } | @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(fsa); }
@Test public void testSmallInput() throws Exception { byte[][] input = { "abc".getBytes("UTF-8"), "bbc".getBytes("UTF-8"), "d".getBytes("UTF-8"), }; checkCorrect(input, FSABuilder.build(input)); }
@Test public void testRandom25000_largerAlphabet() { FSA fsa = FSABuilder.build(input); checkCorrect(input, fsa); checkMinimal(fsa); }
@Test public void testRandom25000_smallAlphabet() throws IOException { FSA fsa = FSABuilder.build(input2); checkCorrect(input2, fsa); checkMinimal(fsa); } |
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 Iterator<WordData> iterator(); Dictionary getDictionary(); char getSeparatorChar(); } | @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); } } Dictionary(FSA fsa, DictionaryMetadata metadata); static Dictionary read(Path location); static Dictionary read(URL dictURL); static Dictionary read(InputStream fsaStream, InputStream metadataStream); final FSA fsa; final DictionaryMetadata metadata; } | @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().getResource("test-infix.info").openStream()) { Files.copy(dictInput, dict); Files.copy(infoInput, info); } assertNotNull(Dictionary.read(dict.toUri().toURL())); assertNotNull(Dictionary.read(dict)); } |
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 Dictionary dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; } | @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")).contains("Abaka abace"); final URL url1 = getClass().getResource("test-infix.dict"); final Speller spell1 = new Speller(Dictionary.read(url1)); assertTrue(spell1.replaceRunOnWords("Rzekunia").isEmpty()); assertTrue(spell1.replaceRunOnWords("RzekuniaRzeczypospolitej").contains("Rzekunia Rzeczypospolitej")); assertTrue(spell1.replaceRunOnWords("RzekuniaRze").isEmpty()); final URL url2 = getClass().getResource("single-char-word.dict"); final Speller spell2 = new Speller(Dictionary.read(url2)); assertTrue(spell2.replaceRunOnWords("alot").contains("a lot")); assertTrue(spell2.replaceRunOnWords("aalot").contains("aa lot")); assertTrue(spell2.replaceRunOnWords("aamusement").contains("a amusement")); assertTrue(spell2.replaceRunOnWords("clot").isEmpty()); assertTrue(spell2.replaceRunOnWords("foobar").isEmpty()); } |
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 == EXACT_MATCH) { containsSeparators = false; for (int i=0; i<word.length(); i++) { if (word.charAt(i) == dictionaryMetadata.getSeparator()) { containsSeparators = true; break; } } } if (match.kind == EXACT_MATCH && !containsSeparators) { return true; } return containsSeparators && match.kind == SEQUENCE_IS_A_PREFIX && byteBuffer.remaining() > 0 && fsa.getArc(match.node, dictionaryMetadata.getSeparator()) != 0; } Speller(final Dictionary dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; } | @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+aaa")); final URL url = getClass().getResource("test-utf-spell.dict"); final Speller spell = new Speller(Dictionary.read(url)); assertTrue(spell.isInDictionary("jaźń")); assertTrue(spell.isInDictionary("zażółć")); assertTrue(spell.isInDictionary("żółwiową")); assertTrue(spell.isInDictionary("ćwikła")); assertTrue(spell.isInDictionary("Żebrowski")); assertTrue(spell.isInDictionary("Święto")); assertTrue(spell.isInDictionary("Świerczewski")); assertTrue(spell.isInDictionary("abc")); }
@Test public void testFrequencyNonUTFDictionary() throws IOException { final URL url1 = getClass().getResource("test_freq_iso.dict"); final Speller spell = new Speller(Dictionary.read(url1)); assertTrue(spell.isInDictionary("a")); assertTrue(!spell.isInDictionary("aõh")); } |
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(final Dictionary dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; } | @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 = spell.findSimilarWords("mist"); assertTrue(reps.toString().equals("[list, fist, dist, gist, wist, hist]")); reps = spell.findSimilarWords("Fist"); assertTrue(reps.toString().equals("[fist, list, mist, dist, gist, wist, hist]")); reps = spell.findSimilarWords("licit"); assertTrue(reps.toString().equals("[list, fist, mist, dist, gist, wist, hist]")); } |
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(@NotNull final String destinationString); } | @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) { assertNotNull(registry.getDestinationFactory(prefix)); } for (String prefix : WorldDestination.PREFIXES) { assertNotNull(registry.getDestinationFactory(prefix)); } } |
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); } DestinationFactory destinationFactory = getDestinationFactory(destParts[0]); if (destinationFactory != null) { return destinationFactory.createDestination(api, destinationString); } return new UnknownDestination(api, this, getRegistrationCount(), destinationString); } DestinationRegistry(@NotNull final MultiverseCoreAPI api); void registerDestinationFactory(@NotNull DestinationFactory destinationFactory); @NotNull Destination parseDestination(@NotNull final String destinationString); } | @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); assertEquals(UnknownDestination.class, dest.getClass()); dest = registry.parseDestination(""); assertNotNull(dest); assertEquals(WorldDestination.class, dest.getClass()); assertEquals("world:", dest.getDestinationString()); }
@Test public void testParseInvalidDestinations() throws Exception { Destination dest = registry.parseDestination("blafhga:fff"); assertNotNull(dest); assertEquals(UnknownDestination.class, dest.getClass()); dest = registry.parseDestination(":::::::"); assertNotNull(dest); assertEquals(UnknownDestination.class, dest.getClass()); }
@Test public void testParseExtraColonsDestinations() throws Exception { Destination dest = registry.parseDestination("world:some:world"); assertNotNull(dest); assertEquals(WorldDestination.class, dest.getClass()); assertEquals("world:some:world", dest.getDestinationString()); } |
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 hashCode(); } | @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 testTeleportLocation() throws Exception { BasePlayer player = api.getServerInterface().getPlayer("Player"); assertNotNull(player); ExactDestination dest = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0)); assertNotEquals(dest.getDestination(), ((Entity) player).getLocation()); assertEquals(1, ((Entity) player).getVelocity().length(), 0.00001); dest.teleport(player, (Entity) player); assertEquals(dest.getDestination(), ((Entity) player).getLocation()); assertEquals(1, ((Entity) player).getVelocity().length(), 0.00001); } |
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); @Override String getDestinationString(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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)); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertFalse(a.equals(null)); assertFalse(b.equals(null)); b = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50, 50, 50.5, 0, 0)); assertFalse(a.equals(b)); assertFalse(b.equals(a)); a = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50, 50, 50.5, 0, 0)); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertFalse(a.equals(null)); assertFalse(b.equals(null)); } |
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()); matcher = pattern.matcher(" 3 "); assertFalse(matcher.matches()); matcher = pattern.matcher(""); assertFalse(matcher.matches()); matcher = pattern.matcher(" "); assertFalse(matcher.matches()); matcher = pattern.matcher("-1235-951"); assertFalse(matcher.matches()); matcher = pattern.matcher(":123.12345:11231"); assertFalse(matcher.matches()); matcher = pattern.matcher("1.2"); assertTrue(matcher.matches()); matcher = pattern.matcher("50000"); assertTrue(matcher.matches()); matcher = pattern.matcher("+50000"); assertTrue(matcher.matches()); matcher = pattern.matcher("-50000"); assertTrue(matcher.matches()); matcher = pattern.matcher("10023.4554"); assertTrue(matcher.matches()); matcher = pattern.matcher("14123456135661241123123124516123156"); assertTrue(matcher.matches()); matcher = pattern.matcher("14123456135661241.123123124516123156"); assertTrue(matcher.matches()); matcher = pattern.matcher("123"); assertTrue(matcher.matches()); assertEquals(2, matcher.groupCount()); matcher = pattern.matcher("123.12345"); assertTrue(matcher.matches()); assertEquals(2, matcher.groupCount()); assertEquals("123.12345", matcher.group("test")); } |
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())); } } CannonDestination(@NotNull MultiverseCoreAPI api, @Nullable EntityCoordinates coordinates, double speed); @Override @NotNull String getDestinationString(); @Override void teleport(@NotNull Permissible teleporter, @NotNull Entity teleportee); @Override boolean equals(final Object o); @Override int hashCode(); double getLaunchSpeed(); } | @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(api, "cannon:5"); dest.getDestination(); } |
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 MultiverseCoreAPI api, @Nullable EntityCoordinates coordinates, double speed); @Override @NotNull String getDestinationString(); @Override void teleport(@NotNull Permissible teleporter, @NotNull Entity teleportee); @Override boolean equals(final Object o); @Override int hashCode(); double getLaunchSpeed(); } | @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); assertFalse(a.equals(b)); assertFalse(b.equals(a)); b = new CannonDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 0, 0, 0, 0, 0), 5); assertFalse(a.equals(b)); assertFalse(b.equals(a)); a = new CannonDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 0, 0, 0, 0, 0), 5); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertFalse(a.equals(null)); assertFalse(b.equals(null)); } |
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(name, env, seedString, type, generateStructures, generator, true); } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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 invocation) throws Throwable { WorldCreationSettings s = (WorldCreationSettings) invocation.getArguments()[0]; assertEquals(testName, s.name()); assertEquals(testWorldEnvironment, s.env()); assertEquals(testSeed, s.seed()); assertEquals(testWorldType, s.type()); assertEquals(testGenerateStructures, s.generateStructures()); assertEquals(testGenerator, s.generator()); assertEquals(testAdjustSpawn, s.adjustSpawn()); return WorldManagerUtilFactory.getMockedWorldManagerUtil().createWorld(s); } }).when(mockWorldManager).addWorld(any(WorldCreationSettings.class)); mockWorldManager.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); MultiverseWorld w = worldManager.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); assertEquals(testName, w.getName()); assertNotEquals(testName.toUpperCase(), w.getName()); assertEquals(testWorldEnvironment, w.getEnvironment()); assertEquals(testSeed.longValue(), w.getSeed()); assertEquals(testWorldType, w.getWorldType()); assertEquals(testGenerator, w.getGenerator()); assertEquals(testAdjustSpawn, w.isAdjustSpawnEnabled()); boolean thrown = false; try { worldManager.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); } catch (WorldCreationException e) { thrown = true; assertEquals(Language.WORLD_ALREADY_EXISTS, e.getBundledMessage().getMessage()); assertEquals(testName, e.getBundledMessage().getArgs()[0]); } assertTrue(thrown); thrown = false; try { worldManager.addWorld(testName.toUpperCase(), testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); } catch (WorldCreationException e) { thrown = true; assertEquals(Language.WORLD_ALREADY_EXISTS, e.getBundledMessage().getMessage()); assertEquals(testName.toUpperCase(), e.getBundledMessage().getArgs()[0]); } assertTrue(thrown); } |
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(@NotNull final String name,
@Nullable final WorldEnvironment env,
@Nullable final String seedString,
@Nullable final WorldType type,
@Nullable final Boolean generateStructures,
@Nullable final String generator); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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_the_end")); MultiverseWorld w = worldManager.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); assertTrue(worldManager.isLoaded(w.getName())); worldManager.unloadWorld(w); assertFalse(worldManager.isLoaded(w.getName())); assertFalse(worldManager.isLoaded(w.getName().toUpperCase())); } |
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); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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("world_the_end")); MultiverseWorld w = worldManager.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); assertTrue(worldManager.isManaged(w.getName())); worldManager.unloadWorld(w); assertTrue(worldManager.isManaged(w.getName())); worldManager.removeWorld(w.getName()); assertFalse(worldManager.isManaged(w.getName())); w = worldManager.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); assertTrue(worldManager.isManaged(w.getName())); } |
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; } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); assertNotNull(worldManager.getWorld(testName)); assertEquals(w, worldManager.getWorld(testName)); } |
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 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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)); worldManager.unloadWorld(w); assertFalse(worldManager.getWorlds().contains(w)); worldManager.loadWorld(w.getName()); assertTrue(worldManager.getWorlds().contains(w)); assertEquals(4, worldManager.getWorlds().size()); } |
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(Language.WORLD_NOT_MANAGED, name)); } try { CoreLogger.fine("Loading world '%s'...", name); final WorldProperties properties = this.worldManagerUtil.getWorldProperties(name); final WorldCreationSettings settings = new WorldCreationSettings(name); settings.generator(properties.getGenerator()); settings.seed(properties.getSeed()); settings.env(properties.getEnvironment()); settings.adjustSpawn(properties.isAdjustingSpawn()); try { return addWorld(settings); } catch (final WorldCreationException e) { throw new WorldManagementException(Message.bundleMessage(Language.WORLD_LOAD_ERROR, name), e); } } catch (final PluginBaseException e) { throw new WorldManagementException(Message.bundleMessage(Language.WORLD_LOAD_ERROR, name), e); } } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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]); } assertTrue(thrown); 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]); } assertTrue(thrown); thrown = false; try { worldManager.loadWorld(testName); } catch (WorldManagementException e) { thrown = true; assertEquals(Language.WORLD_NOT_MANAGED, e.getBundledMessage().getMessage()); assertEquals(testName, e.getBundledMessage().getArgs()[0]); } assertTrue(thrown); thrown = false; MultiverseWorld w = worldManager.addWorld(testName, testWorldEnvironment, testSeedString, testWorldType, testGenerateStructures, testGenerator, testAdjustSpawn); try { worldManager.loadWorld(testName); } catch (WorldManagementException e) { thrown = true; assertEquals(Language.WORLD_ALREADY_LOADED, e.getBundledMessage().getMessage()); assertEquals(testName, e.getBundledMessage().getArgs()[0]); } assertTrue(thrown); thrown = false; worldManager.unloadWorld(testName); assertFalse(worldManager.isLoaded(testName)); worldManager.loadWorld(testName); MultiverseWorld w1 = worldManager.getWorld(testName); assertNotNull(w1); assertNotSame(w1, w); assertEquals(testName, w1.getName()); } |
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 TeleportException(Message.bundleMessage(NOT_FOUND, playerName)); } } PlayerDestination(@NotNull MultiverseCoreAPI api, @NotNull String playerName); @NotNull @Override String getDestinationString(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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, "player:fakeplayer"); dest.getDestination(); }
@Test public void testTeleportLocation() throws Exception { BasePlayer player = api.getServerInterface().getPlayer("Player"); assertNotNull(player); ((Entity) player).teleport(Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0)); PlayerDestination dest = new PlayerDestination(api, "someplayer"); assertNotEquals(dest.getDestination(), ((Entity) player).getLocation()); assertEquals(1, ((Entity) player).getVelocity().length(), 0.00001); dest.teleport(player, (Entity) player); assertEquals(dest.getDestination(), ((Entity) player).getLocation()); assertEquals(1, ((Entity) player).getVelocity().length(), 0.00001); } |
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 worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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 location = Locations.getEntityCoordinates(safeWorld.getName(), safeWorld.getWorldUID(), sLoc.getX(), sLoc.getY(), sLoc.getZ(), sLoc.getPitch(), sLoc.getYaw()); CoreLogger.fine("Removing players from world '%s'...", world.getName()); for (final BasePlayer p : world.getPlayers()) { if (p instanceof Entity) { teleporter.safelyTeleport(null, (Entity) p, location); } } } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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(name)) { unloadedWorlds.add(name); } } return Collections.unmodifiableList(unloadedWorlds); } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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 WorldManagementException(Message.bundleMessage(Language.WORLD_REMOVE_ERROR, name), e); } if (isManaged(name)) { try { this.worldManagerUtil.removeWorldProperties(name); } catch (final PluginBaseException e) { throw new WorldManagementException(Message.bundleMessage(Language.WORLD_REMOVE_ERROR, name), e); } return true; } return false; } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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.getCorrectlyCasedWorldName(worldName); if (!isThisAWorld(name)) { throw new WorldManagementException(Message.bundleMessage(Language.CANNOT_DELETE_NONWORLD, name)); } if (isLoaded(name)) { try { unloadWorld(name); } catch (final WorldManagementException e) { throw new WorldManagementException(Message.bundleMessage(Language.WORLD_DELETE_ERROR, name), e); } } try { this.worldManagerUtil.deleteWorld(name); } catch (IOException e) { throw new WorldManagementException(Message.bundleMessage(Language.WORLD_DELETE_FAILED, name), e); } if (removeMVWorld) { try { removeWorld(name); } catch (final WorldManagementException e) { throw new WorldManagementException(Message.bundleMessage(Language.WORLD_DELETE_PERSISTENCE_ERROR, name), e); } } } WorldManager(@NotNull final MultiverseCoreAPI api, @NotNull final WorldManagerUtil worldManagerUtil); @NotNull UUID getWorldUUID(@NotNull String worldName); @NotNull 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); @NotNull 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,
boolean useSpawnAdjust); @NotNull MultiverseWorld addWorld(@NotNull final WorldCreationSettings settings); boolean isLoaded(@NotNull final String name); boolean isManaged(@NotNull final String name); @Nullable MultiverseWorld getWorld(@NotNull final String name); @NotNull Collection<MultiverseWorld> getWorlds(); @NotNull MultiverseWorld loadWorld(@NotNull final String name); boolean unloadWorld(@NotNull final String name); void unloadWorld(@NotNull final MultiverseWorld world); void saveWorld(@NotNull MultiverseWorld world); void removePlayersFromWorld(@NotNull final MultiverseWorld world); @NotNull Collection<String> getUnloadedWorlds(); boolean removeWorld(@NotNull final String name); void deleteWorld(@NotNull final String worldName, final boolean removeMVWorld); boolean isThisAWorld(@NotNull final String name); @NotNull BundledMessage whatWillThisDelete(@NotNull final String name); @NotNull Collection<String> getPotentialWorlds(); } | @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 String getDestinationString(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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"); assertFalse(a.equals(b)); assertFalse(b.equals(a)); } |
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 Locations.getEntityCoordinates(world, getApi().getWorldManager().getWorldUUID(world), mvWorld.getSpawnLocation()); } WorldDestination(@NotNull MultiverseCoreAPI api, @NotNull String world); @Override String getDestinationString(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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() throws Exception { BasePlayer player = api.getServerInterface().getPlayer("Player"); assertNotNull(player); ((Entity) player).teleport(Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0)); WorldDestination dest = new WorldDestination(api, "world"); assertNotEquals(dest.getDestination(), ((Entity) player).getLocation()); assertEquals(1, ((Entity) player).getVelocity().length(), 0.00001); dest.teleport(player, (Entity) player); assertEquals(dest.getDestination(), ((Entity) player).getLocation()); assertEquals(1, ((Entity) player).getVelocity().length(), 0.00001); } |
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 api, @NotNull String world); @Override String getDestinationString(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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"); assertFalse(a.equals(b)); assertFalse(b.equals(a)); } |
DestinationRegistry { public void registerDestinationFactory(@NotNull DestinationFactory destinationFactory) { CoreLogger.fine("Registering DestinationFactory: " + destinationFactory); if (destinationFactory.getDestinationPrefixes().isEmpty()) { CoreLogger.warning("DestinationFactory: %s cannot be registered without any prefixes.", destinationFactory.getClass()); } for (String prefix : destinationFactory.getDestinationPrefixes()) { if (prefix.isEmpty()) { CoreLogger.warning("DestinationFactory: %s attempted to register an empty prefix.", destinationFactory.getClass()); continue; } prefix = prefix.toLowerCase(); if (!prefixFactoryMap.containsKey(prefix) || !destinationFactory.getWeakPrefixes().contains(prefix)) { prefixFactoryMap.put(prefix, destinationFactory); CoreLogger.finer("Registered prefix: %s to DestinationFactory: %s", prefix, destinationFactory.getClass()); } else { CoreLogger.finer("Skipped weak prefix: %s for DestinationFactory: %s as that prefix has previously been registered.", prefix, destinationFactory.getClass()); } } } DestinationRegistry(@NotNull final MultiverseCoreAPI api); void registerDestinationFactory(@NotNull DestinationFactory destinationFactory); @NotNull Destination parseDestination(@NotNull final String destinationString); } | @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.getDestinationFactory(prefix)); } } |
AnnotationUtils { public static String getClassAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType) { return getClassAttributeFromAnnotationAsFqn(element, annotationType, "value"); } private AnnotationUtils(); static AnnotationValue getAnnotationValueOfAttribute(AnnotationMirror annotationMirror); static AnnotationValue getAnnotationValueOfAttribute(AnnotationMirror annotationMirror, String key); static AnnotationValue getAnnotationValueOfAttributeWithDefaults(AnnotationMirror annotationMirror); static String[] getMandatoryAttributeValueNames(AnnotationMirror annotationMirror); static String[] getOptionalAttributeValueNames(AnnotationMirror annotationMirror); static AnnotationValue getAnnotationValueOfAttributeWithDefaults(AnnotationMirror annotationMirror, String key); static ExecutableElement getExecutableElementForAnnotationAttributeName(AnnotationMirror annotationMirror, String key); static String getClassAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType); static String getClassAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType, String attributeName); static TypeMirror getClassAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType); static TypeMirror getClassAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType, String attributeName); static AnnotationMirror getAnnotationMirror(Element element, Class<? extends Annotation> clazz); static AnnotationMirror getAnnotationMirror(Element element, String fqClassName); static Element getElementForAnnotationMirror(AnnotationMirror annotationMirror); static String[] getClassArrayAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType); static String[] getClassArrayAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType, String attributeName); static TypeMirror[] getClassArrayAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType); static TypeMirror[] getClassArrayAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType, String attributeName); } | @Test public void annotationUtilsTest_classAttribute_emptyValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ANNOTATION).filterByAllOf(ClassAttributeAnnotation.class) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("test_classAttribute_empty") .getResult().get(0); MatcherAssert.assertThat(AnnotationUtils.getClassAttributeFromAnnotationAsFqn(testElement, ClassAttributeAnnotation.class), Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void getClassAttributeFromAnnotationAsFqn_shouldReturnNullForNonMatchingClassAttributes() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(ClassAttributeTestcase_WithCorrectClassAttribute.class); MatcherAssert.assertThat("PRECONDITION : TypeElement must exist", typeElement, Matchers.notNullValue()); String result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, DefaultValueAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, DefaultValueAnnotation.class, "mandatoryValue"); MatcherAssert.assertThat(result, Matchers.nullValue()); result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, ClassArrayAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, NoAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void annotationUtilsTest_classAttribute_StringClassValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ANNOTATION).filterByAllOf(ClassAttributeAnnotation.class) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("test_classAttribute_atDefaultValue") .getResult().get(0); MatcherAssert.assertThat(AnnotationUtils.getClassAttributeFromAnnotationAsFqn(testElement, ClassAttributeAnnotation.class), Matchers.equalTo(String.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void annotationUtilsTest_classAttributeWithExplicitAttributeName_LongClassValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ANNOTATION).filterByAllOf(ClassAttributeAnnotation.class) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("test_classAttribute_atNamedAttribute") .getResult().get(0); MatcherAssert.assertThat(AnnotationUtils.getClassAttributeFromAnnotationAsFqn(testElement, ClassAttributeAnnotation.class, "classAttribute"), Matchers.equalTo(Long.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void getClassAttributeFromAnnotationAsFqn_shouldGetClassAttributeSuccefully() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(ClassAttributeTestcase_WithCorrectClassAttribute.class); MatcherAssert.assertThat("PRECONDITION : TypeElement must exist", typeElement, Matchers.notNullValue()); String result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, ClassAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match String : " , String.class.getCanonicalName().equals(result)); result = AnnotationUtils.getClassAttributeFromAnnotationAsFqn(typeElement, ClassAttributeAnnotation.class,"classAttribute"); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match Long : " , Long.class.getCanonicalName().equals(result)); } }) .compilationShouldSucceed() .executeTest(); } |
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 interface : ", CoreMatchers.IS_INTERFACE.getMatcher().check(typeElement)); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkMismatchingMethod_class() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non method : ", !CoreMatchers.IS_INTERFACE.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); }
@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_INTERFACE.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); } |
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.AccessEnclosedElements.getEnclosedElementsByName(typeElement, "testField"); MatcherAssert.assertThat("Precondition: must have found a field", fieldList.size() >= 1); MatcherAssert.assertThat("Should return true for field : ", CoreMatchers.IS_FIELD.getMatcher().check(fieldList.get(0))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkMismatchingMethod_class() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non field : ", !CoreMatchers.IS_FIELD.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); }
@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_FIELD.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); } |
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(CoreMatchers.BY_MODIFIER).hasNoneOf(Modifier.STATIC, Modifier.ABSTRACT) .applyValidator(CoreMatchers.HAS_NO_PARAMETERS) .applyInvertedValidator(CoreMatchers.HAS_VOID_RETURN_TYPE) .justValidate() ) { return false; } TypeMirror returnType = element.getReturnType(); String methodName = element.getSimpleName().toString(); return methodName.startsWith("get") || (TypeUtils.TypeComparison.isTypeEqual(returnType, TypeUtils.TypeRetrieval.getTypeMirror(boolean.class)) && ((methodName.startsWith("is") || methodName.startsWith("has")))); } @Override boolean check(ExecutableElement element); } | @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)); } }) .compilationShouldSucceed() .executeTest(); } |
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.TypeRetrieval.getTypeMirror(toCheckFor)); } ByReturnTypeMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, Class toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(Class toGetStringRepresentationFor); } | @Test public void byReturnTypeMirrorMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have a return type", executableElement.getReturnType(), Matchers.notNullValue()); MatcherAssert.assertThat("Precondition: return type must be of type String but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getReturnType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should have found matching return type", CoreMatchers.BY_RETURN_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, String.class)); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byReturnTypeMirrorMatcher_noMatch() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have a return type", executableElement.getReturnType(), Matchers.notNullValue()); MatcherAssert.assertThat("Precondition: return type must be of type String but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getReturnType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should have found a non matching return type", !CoreMatchers.BY_RETURN_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, Boolean.class)); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byReturnTypeMirrorMatcher_nullValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have a return type", executableElement.getReturnType(), Matchers.notNullValue()); MatcherAssert.assertThat("Precondition: return type must be of type String but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getReturnType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_RETURN_TYPE.getMatcher().checkForMatchingCharacteristic(null, String.class)); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_RETURN_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, null)); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_RETURN_TYPE.getMatcher().checkForMatchingCharacteristic(null, null)); } }) .compilationShouldSucceed() .executeTest(); } |
ByReturnTypeMatcher implements CriteriaMatcher<ExecutableElement, Class> { @Override public String getStringRepresentationOfPassedCharacteristic(Class toGetStringRepresentationFor) { return toGetStringRepresentationFor != null ? toGetStringRepresentationFor.getCanonicalName() : ""; } ByReturnTypeMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, Class toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(Class toGetStringRepresentationFor); } | @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.getMatcher().getStringRepresentationOfPassedCharacteristic(null), Matchers.is("")); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void getStringRepresentationOfPassedCharacteristic_getStringRepresetation() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should have created valid string representation", CoreMatchers.BY_RETURN_TYPE.getMatcher().getStringRepresentationOfPassedCharacteristic(String.class), Matchers.is(String.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } |
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 annotation type : ", CoreMatchers.IS_ANNOTATION_TYPE.getMatcher().check(typeElement)); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkMismatchingAnnotationType() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non annotation (class) : ", !CoreMatchers.IS_ANNOTATION_TYPE.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); }
@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_ANNOTATION_TYPE.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); } |
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("Precondition: should have found one method", result != null); MatcherAssert.assertThat("Precondition: found method has to be of type package", result instanceof PackageElement); MatcherAssert.assertThat("Should return true for method : ", CoreMatchers.IS_PACKAGE.getMatcher().check(result)); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkMismatchingPackageElement_class() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non Package : ", !CoreMatchers.IS_PACKAGE.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); }
@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_PACKAGE.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); } |
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(CoreMatchers.BY_MODIFIER).hasNoneOf(Modifier.STATIC, Modifier.ABSTRACT) .applyValidator(CoreMatchers.BY_NUMBER_OF_PARAMETERS).hasOneOf(1) .applyValidator(CoreMatchers.HAS_VOID_RETURN_TYPE) .applyValidator(CoreMatchers.BY_REGEX_NAME).hasOneOf("set.*") .justValidate(); } @Override boolean check(ExecutableElement element); } | @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)); } }) .compilationShouldSucceed() .executeTest(); } |
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(), toCheckFor); } ByReturnTypeMirrorMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, TypeMirror toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(TypeMirror toGetStringRepresentationFor); } | @Test public void byReturnTypeMirrorMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have a return type", executableElement.getReturnType(), Matchers.notNullValue()); MatcherAssert.assertThat("Precondition: return type must be of type String but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getReturnType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should have found matching return type", CoreMatchers.BY_RETURN_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, TypeUtils.TypeRetrieval.getTypeMirror(String.class))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byReturnTypeMirrorMatcher_noMatch() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have a return type", executableElement.getReturnType(), Matchers.notNullValue()); MatcherAssert.assertThat("Precondition: return type must be of type String but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getReturnType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should have found a non matching return type", !CoreMatchers.BY_RETURN_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, TypeUtils.TypeRetrieval.getTypeMirror(Boolean.class))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byReturnTypeMirrorMatcher_nullValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have a return type", executableElement.getReturnType(), Matchers.notNullValue()); MatcherAssert.assertThat("Precondition: return type must be of type String but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getReturnType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_RETURN_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(null, TypeUtils.TypeRetrieval.getTypeMirror(String.class))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_RETURN_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, null)); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_RETURN_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(null, null)); } }) .compilationShouldSucceed() .executeTest(); } |
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); } else { MessagerUtils.printMessage(element, kind, message, args); } } FluentValidatorMessage(final Element element, Diagnostic.Kind kind, final ValidationMessage message, Object... args); FluentValidatorMessage(final Element element, final AnnotationMirror annotationMirror, Diagnostic.Kind kind, final ValidationMessage message, Object... args); FluentValidatorMessage(final Element element, final AnnotationMirror annotationMirror, final AnnotationValue annotationValue, Diagnostic.Kind kind, final ValidationMessage message, Object... args); void issueMessage(); } | @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}"), "SUCCESS"); message.issueMessage(); } }) .compilationShouldFail() .executeTest(); }
@Test public void checkWarningElementMessage() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { FluentValidatorMessage message = new FluentValidatorMessage(element, Diagnostic.Kind.WARNING, PlainValidationMessage.create("TEST ${0}"), "SUCCESS"); message.issueMessage(); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkInfoElementMessage() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { FluentValidatorMessage message = new FluentValidatorMessage(element, Diagnostic.Kind.NOTE, PlainValidationMessage.create("TEST ${0}"), "SUCCESS"); message.issueMessage(); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkElementWithAnnotationMirror() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> annotatedElement = ElementUtils.AccessEnclosedElements.getEnclosedElementsWithAllAnnotationsOf(element, FilterTestAnnotation1.class); MatcherAssert.assertThat("PRECONDITION : Must have found one element", annotatedElement.size() == 1); AnnotationMirror annotationMirror = AnnotationUtils.getAnnotationMirror(annotatedElement.get(0), FilterTestAnnotation1.class); MatcherAssert.assertThat("PRECONDITION : Must have found one annotation", annotationMirror, Matchers.notNullValue()); FluentValidatorMessage message = new FluentValidatorMessage(annotatedElement.get(0), annotationMirror, Diagnostic.Kind.NOTE, PlainValidationMessage.create("TEST ${0}"), "SUCCESS"); message.issueMessage(); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkElementWithAnnotationMirrorAndAnnotationValue() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> annotatedElement = ElementUtils.AccessEnclosedElements.getEnclosedElementsWithAllAnnotationsOf(element, FilterTestAnnotation1.class); MatcherAssert.assertThat("PRECONDITION : Must have found one element", annotatedElement.size() == 1); AnnotationMirror annotationMirror = AnnotationUtils.getAnnotationMirror(annotatedElement.get(0), FilterTestAnnotation1.class); MatcherAssert.assertThat("PRECONDITION : Must have found one annotation", annotationMirror, Matchers.notNullValue()); MatcherAssert.assertThat("PRECONDITION : Must have found one annotation", annotationMirror.getElementValues().size() == 1); FluentValidatorMessage message = new FluentValidatorMessage(element, annotatedElement.get(0).getAnnotationMirrors().get(0), annotationMirror.getElementValues().get(0), Diagnostic.Kind.NOTE, PlainValidationMessage.create("TEST ${0}"), "SUCCESS"); message.issueMessage(); } }) .compilationShouldSucceed() .executeTest(); } |
ByReturnTypeMirrorMatcher implements CriteriaMatcher<ExecutableElement, TypeMirror> { @Override public String getStringRepresentationOfPassedCharacteristic(TypeMirror toGetStringRepresentationFor) { return toGetStringRepresentationFor != null ? toGetStringRepresentationFor.toString() : ""; } ByReturnTypeMirrorMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, TypeMirror toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(TypeMirror toGetStringRepresentationFor); } | @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.getMatcher().getStringRepresentationOfPassedCharacteristic(null), Matchers.is("")); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void getStringRepresentationOfPassedCharacteristic_getStringRepresentation() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should have created valid string representation", CoreMatchers.BY_RETURN_TYPE_MIRROR.getMatcher().getStringRepresentationOfPassedCharacteristic(TypeUtils.TypeRetrieval.getTypeMirror(String.class)), Matchers.is(String.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } |
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)); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkMismatchingTypeElement_class() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { Element result = ElementUtils.AccessEnclosingElements.getFirstEnclosingElementOfKind(element, ElementKind.PACKAGE); MatcherAssert.assertThat("Precondition: should have found one method", result != null); MatcherAssert.assertThat("Precondition: found method has to be of zype PackageElement", result instanceof PackageElement); MatcherAssert.assertThat("Should return false for package : ", !CoreMatchers.IS_TYPE_ELEMENT.getMatcher().check(result)); } }) .compilationShouldSucceed() .executeTest(); }
@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_TYPE_ELEMENT.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); } |
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, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: found method has to be of type ExecutableElement", result.get(0) instanceof ExecutableElement); MatcherAssert.assertThat("Should return true for method : ", CoreMatchers.IS_EXECUTABLE_ELEMENT.getMatcher().check(result.get(0))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkMismatchingExecutableElement_class() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non ExecutableElement : ", !CoreMatchers.IS_EXECUTABLE_ELEMENT.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); }
@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_EXECUTABLE_ELEMENT.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); } |
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; } for (int i = 0; i < element.getParameters().size(); i++) { VariableElement parameterElement = element.getParameters().get(i); if(!TypeUtils.TypeComparison.isErasedTypeEqual(parameterElement.asType(), TypeUtils.TypeRetrieval.getTypeMirror(toCheckFor[i]) )){ return false; } } return true; } ByParameterTypeMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, Class[] toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(Class[] toGetStringRepresentationFor); } | @Test public void byParameterTypeMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: found method has to be of type ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Precondition: first parameter must be of type Boolean but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getParameters().get(0).asType().toString().equals(Boolean.class.getCanonicalName())); MatcherAssert.assertThat("Precondition: second parameter must be of type String but is " + executableElement.getParameters().get(1).asType().toString(), executableElement.getParameters().get(1).asType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should have found matching parameters", CoreMatchers.BY_PARAMETER_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(Boolean.class, String.class))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byParameterTypeMatcher_match_withGenericType() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element1) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(GenericTypeTestClass.class); MatcherAssert.assertThat("Precondition: should have found the testclass", typeElement, Matchers.notNullValue()); List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(typeElement, "methodWithGenericParameter"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: found method has to be of type ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 5 parameters", executableElement.getParameters().size() == 5); MatcherAssert.assertThat("Precondition: first parameter must be of type List but is " + executableElement.getParameters().get(0).asType().toString(), TypeUtils.getTypes().erasure(executableElement.getParameters().get(0).asType()).toString().equals(List.class.getCanonicalName())); MatcherAssert.assertThat("Precondition: second parameter must be of type String but is " + executableElement.getParameters().get(1).asType().toString(), executableElement.getParameters().get(1).asType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should have found matching parameters", CoreMatchers.BY_PARAMETER_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(List.class, String.class, int.class, int[].class, List[].class))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byParameterTypeMatcher_noMatch() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(String.class, Boolean.class))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(Boolean.class))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(Boolean.class, String.class, String.class))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byParameterTypeMatcher_nullValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE.getMatcher().checkForMatchingCharacteristic(null, Utilities.convertVarargsToArray(String.class, Boolean.class))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE.getMatcher().checkForMatchingCharacteristic(executableElement, null)); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE.getMatcher().checkForMatchingCharacteristic(null, null)); } }) .compilationShouldSucceed() .executeTest(); } |
ByParameterTypeMatcher implements CriteriaMatcher<ExecutableElement, Class[]> { @Override public String getStringRepresentationOfPassedCharacteristic(Class[] toGetStringRepresentationFor) { if (toGetStringRepresentationFor != null) { StringBuilder stringBuilder = new StringBuilder("["); boolean isFirst = true; for (Class<?> element : toGetStringRepresentationFor) { if (isFirst) { isFirst = false; } else { stringBuilder.append(", "); } stringBuilder.append(element.getCanonicalName()); } stringBuilder.append("]"); return stringBuilder.toString(); } else { return null; } } ByParameterTypeMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, Class[] toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(Class[] toGetStringRepresentationFor); } | @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.getMatcher().getStringRepresentationOfPassedCharacteristic(null), Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void getStringRepresentationOfPassedCharacteristic_getStringRepresentation() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should have created valid string representation", CoreMatchers.BY_PARAMETER_TYPE.getMatcher().getStringRepresentationOfPassedCharacteristic(Utilities.convertVarargsToArray(String.class, Boolean.class)), Matchers.is("[java.lang.String, java.lang.Boolean]")); } }) .compilationShouldSucceed() .executeTest(); } |
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) { return false; } for (int i = 0; i < element.getParameters().size(); i++) { TypeMirror parameterTypeMirror = toCheckFor[i]; if (parameterTypeMirror == null) { return false; } if(!TypeUtils.TypeComparison.isErasedTypeEqual(element.getParameters().get(i).asType(), parameterTypeMirror )){ return false; } } return true; } ByParameterTypeMirrorMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, TypeMirror[] toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(TypeMirror[] toGetStringRepresentationFor); } | @Test public void byParameterTypeMirrorMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: found element has to be of type ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Precondition: first parameter must be of type Boolean but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getParameters().get(0).asType().toString().equals(Boolean.class.getCanonicalName())); MatcherAssert.assertThat("Precondition: second parameter must be of type String but is " + executableElement.getParameters().get(1).asType().toString(), executableElement.getParameters().get(1).asType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should have found matching parameters", CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(TypeUtils.TypeRetrieval.getTypeMirror(Boolean.class), TypeUtils.TypeRetrieval.getTypeMirror(String.class)))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byParameterTypeMirrorMatcher_match_withGenericParameter() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(GenericTypeTestClass.class); MatcherAssert.assertThat("Precondition: should have found the testclass", typeElement, Matchers.notNullValue()); List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(typeElement, "methodWithGenericParameter"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: found element has to be of type ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 5 parameters", executableElement.getParameters().size() == 5); MatcherAssert.assertThat("Should have found matching parameters", CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(TypeUtils.TypeRetrieval.getTypeMirror(List.class), TypeUtils.TypeRetrieval.getTypeMirror(String.class), TypeUtils.TypeRetrieval.getTypeMirror(int.class), TypeUtils.TypeRetrieval.getTypeMirror(int[].class), TypeUtils.TypeRetrieval.getTypeMirror(List[].class)))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byParameterTypeMirrorMatcher_noMatch() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(TypeUtils.TypeRetrieval.getTypeMirror(String.class), TypeUtils.TypeRetrieval.getTypeMirror(Boolean.class)))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(TypeUtils.TypeRetrieval.getTypeMirror(Boolean.class)))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(TypeUtils.TypeRetrieval.getTypeMirror(Boolean.class), TypeUtils.TypeRetrieval.getTypeMirror(String.class), TypeUtils.TypeRetrieval.getTypeMirror(String.class)))); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void byParameterTypeMirrorMatcher_nullValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(null, Utilities.convertVarargsToArray(TypeUtils.TypeRetrieval.getTypeMirror(String.class), TypeUtils.TypeRetrieval.getTypeMirror(Boolean.class)))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(executableElement, null)); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().checkForMatchingCharacteristic(null, null)); } }) .compilationShouldSucceed() .executeTest(); } |
ByParameterTypeMirrorMatcher implements CriteriaMatcher<ExecutableElement, TypeMirror[]> { @Override public String getStringRepresentationOfPassedCharacteristic(TypeMirror[] toGetStringRepresentationFor) { if (toGetStringRepresentationFor != null) { StringBuilder stringBuilder = new StringBuilder("["); boolean isFirst = true; for (TypeMirror element : toGetStringRepresentationFor) { if (isFirst) { isFirst = false; } else { stringBuilder.append(", "); } stringBuilder.append(element.toString()); } stringBuilder.append("]"); return stringBuilder.toString(); } else { return null; } } ByParameterTypeMirrorMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, TypeMirror[] toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(TypeMirror[] toGetStringRepresentationFor); } | @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.getMatcher().getStringRepresentationOfPassedCharacteristic(null), Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void getStringRepresentationOfPassedCharacteristic_getStringRepresentation() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should have created valid string representation", CoreMatchers.BY_PARAMETER_TYPE_MIRROR.getMatcher().getStringRepresentationOfPassedCharacteristic(Utilities.convertVarargsToArray(TypeUtils.TypeRetrieval.getTypeMirror(String.class), TypeUtils.TypeRetrieval.getTypeMirror(Boolean.class))), Matchers.is("[java.lang.String, java.lang.Boolean]")); } }) .compilationShouldSucceed() .executeTest(); } |
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.assertThat("Precondition: should have found one method", result != null); MatcherAssert.assertThat("Precondition: found method has to be of type PackageElement", result instanceof PackageElement); MatcherAssert.assertThat("Should return true for method : ", CoreMatchers.IS_PACKAGE_ELEMENT.getMatcher().check(result)); } }) .compilationShouldSucceed() .executeTest(); }
@Test public void checkMismatchingPackageElement_class() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non PackageElement : ", !CoreMatchers.IS_PACKAGE_ELEMENT.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); }
@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_PACKAGE_ELEMENT.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); } |
ByElementKindMatcher implements CriteriaMatcher<Element, ElementKind> { @Override public String getStringRepresentationOfPassedCharacteristic(ElementKind toGetStringRepresentationFor) { return toGetStringRepresentationFor != null ? toGetStringRepresentationFor.name() : null; } @Override boolean checkForMatchingCharacteristic(Element element, ElementKind toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(ElementKind toGetStringRepresentationFor); } | @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_getStringRepresentationOfPassedCharacteristic_passedNullValue() { MatcherAssert.assertThat("Should return null for null valued parameter", unit.getStringRepresentationOfPassedCharacteristic(null) == null); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.