Here are the examples of the java api @org.junit.Rule taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
11866 Examples
19
Source : TaskTest.java
with Apache License 2.0
from zuoweitan
with Apache License 2.0
from zuoweitan
public clreplaced TaskTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private void runTaskTest(Callable<Task<?>> callable) {
try {
Task<?> task = callable.call();
task.waitForCompletion();
if (task.isFaulted()) {
Exception error = task.getError();
if (error instanceof RuntimeException) {
throw (RuntimeException) error;
}
throw new RuntimeException(error);
} else if (task.isCancelled()) {
throw new RuntimeException(new CancellationException());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testCache() {
replacedertSame(Task.forResult(null), Task.forResult(null));
Task<Boolean> trueTask = Task.forResult(true);
replacedertTrue(trueTask.getResult());
replacedertSame(trueTask, Task.forResult(true));
Task<Boolean> falseTask = Task.forResult(false);
replacedertFalse(falseTask.getResult());
replacedertSame(falseTask, Task.forResult(false));
replacedertSame(Task.cancelled(), Task.cancelled());
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
public void testPrimitives() {
Task<Integer> complete = Task.forResult(5);
Task<Integer> error = Task.forError(new RuntimeException());
Task<Integer> cancelled = Task.cancelled();
replacedertTrue(complete.isCompleted());
replacedertEquals(5, complete.getResult().intValue());
replacedertFalse(complete.isFaulted());
replacedertFalse(complete.isCancelled());
replacedertTrue(error.isCompleted());
replacedertTrue(error.getError() instanceof RuntimeException);
replacedertTrue(error.isFaulted());
replacedertFalse(error.isCancelled());
replacedertTrue(cancelled.isCompleted());
replacedertFalse(cancelled.isFaulted());
replacedertTrue(cancelled.isCancelled());
}
@Test
public void testDelay() throws InterruptedException {
final Task<Void> delayed = Task.delay(200);
Thread.sleep(50);
replacedertFalse(delayed.isCompleted());
Thread.sleep(200);
replacedertTrue(delayed.isCompleted());
replacedertFalse(delayed.isFaulted());
replacedertFalse(delayed.isCancelled());
}
@Test
public void testDelayWithCancelledToken() throws InterruptedException {
CancellationTokenSource cts = new CancellationTokenSource();
cts.cancel();
final Task<Void> delayed = Task.delay(200, cts.getToken());
replacedertTrue(delayed.isCancelled());
}
@Test
public void testDelayWithToken() throws InterruptedException {
CancellationTokenSource cts = new CancellationTokenSource();
final Task<Void> delayed = Task.delay(200, cts.getToken());
replacedertFalse(delayed.isCancelled());
cts.cancel();
replacedertTrue(delayed.isCancelled());
}
@Test
public void testSynchronousContinuation() {
final Task<Integer> complete = Task.forResult(5);
final Task<Integer> error = Task.forError(new RuntimeException());
final Task<Integer> cancelled = Task.cancelled();
complete.continueWith(new Continuation<Integer, Void>() {
public Void then(Task<Integer> task) {
replacedertEquals(complete, task);
replacedertTrue(task.isCompleted());
replacedertEquals(5, task.getResult().intValue());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
return null;
}
});
error.continueWith(new Continuation<Integer, Void>() {
public Void then(Task<Integer> task) {
replacedertEquals(error, task);
replacedertTrue(task.isCompleted());
replacedertTrue(task.getError() instanceof RuntimeException);
replacedertTrue(task.isFaulted());
replacedertFalse(task.isCancelled());
return null;
}
});
cancelled.continueWith(new Continuation<Integer, Void>() {
public Void then(Task<Integer> task) {
replacedertEquals(cancelled, task);
replacedertTrue(cancelled.isCompleted());
replacedertFalse(cancelled.isFaulted());
replacedertTrue(cancelled.isCancelled());
return null;
}
});
}
@Test
public void testSynchronousChaining() {
Task<Integer> first = Task.forResult(1);
Task<Integer> second = first.continueWith(new Continuation<Integer, Integer>() {
public Integer then(Task<Integer> task) {
return 2;
}
});
Task<Integer> third = second.continueWithTask(new Continuation<Integer, Task<Integer>>() {
public Task<Integer> then(Task<Integer> task) {
return Task.forResult(3);
}
});
replacedertTrue(first.isCompleted());
replacedertTrue(second.isCompleted());
replacedertTrue(third.isCompleted());
replacedertEquals(1, first.getResult().intValue());
replacedertEquals(2, second.getResult().intValue());
replacedertEquals(3, third.getResult().intValue());
}
@Test
public void testSynchronousCancellation() {
Task<Integer> first = Task.forResult(1);
Task<Integer> second = first.continueWith(new Continuation<Integer, Integer>() {
public Integer then(Task<Integer> task) {
throw new CancellationException();
}
});
replacedertTrue(first.isCompleted());
replacedertTrue(second.isCancelled());
}
@Test
public void testSynchronousContinuationTokenAlreadyCancelled() {
CancellationTokenSource cts = new CancellationTokenSource();
final Capture<Boolean> continuationRun = new Capture<>(false);
cts.cancel();
Task<Integer> first = Task.forResult(1);
Task<Integer> second = first.continueWith(new Continuation<Integer, Integer>() {
public Integer then(Task<Integer> task) {
continuationRun.set(true);
return 2;
}
}, cts.getToken());
replacedertTrue(first.isCompleted());
replacedertTrue(second.isCancelled());
replacedertFalse(continuationRun.get());
}
@Test
public void testSynchronousTaskCancellation() {
Task<Integer> first = Task.forResult(1);
Task<Integer> second = first.continueWithTask(new Continuation<Integer, Task<Integer>>() {
public Task<Integer> then(Task<Integer> task) {
throw new CancellationException();
}
});
replacedertTrue(first.isCompleted());
replacedertTrue(second.isCancelled());
}
@Test
public void testBackgroundCall() {
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.callInBackground(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(100);
return 5;
}
}).continueWith(new Continuation<Integer, Void>() {
public Void then(Task<Integer> task) {
replacedertEquals(5, task.getResult().intValue());
return null;
}
});
}
});
}
@Test
public void testBackgroundCallTokenCancellation() {
final CancellationTokenSource cts = new CancellationTokenSource();
final CancellationToken ct = cts.getToken();
final Capture<Boolean> waitingToBeCancelled = new Capture<>(false);
final Object cancelLock = new Object();
Task<Integer> task = Task.callInBackground(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
synchronized (cancelLock) {
waitingToBeCancelled.set(true);
cancelLock.wait();
}
ct.throwIfCancellationRequested();
return 5;
}
});
while (true) {
synchronized (cancelLock) {
if (waitingToBeCancelled.get()) {
cts.cancel();
cancelLock.notify();
break;
}
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
try {
task.waitForCompletion();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
replacedertTrue(task.isCancelled());
}
@Test
public void testBackgroundCallTokenAlreadyCancelled() {
final CancellationTokenSource cts = new CancellationTokenSource();
cts.cancel();
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.callInBackground(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(100);
return 5;
}
}, cts.getToken()).continueWith(new Continuation<Integer, Void>() {
public Void then(Task<Integer> task) {
replacedertTrue(task.isCancelled());
return null;
}
});
}
});
}
@Test
public void testBackgroundCallWaiting() throws Exception {
Task<Integer> task = Task.callInBackground(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(100);
return 5;
}
});
task.waitForCompletion();
replacedertTrue(task.isCompleted());
replacedertEquals(5, task.getResult().intValue());
}
@Test
public void testBackgroundCallWaitingWithTimeouts() throws Exception {
final Object sync = new Object();
Task<Integer> task = Task.callInBackground(new Callable<Integer>() {
public Integer call() throws Exception {
synchronized (sync) {
sync.wait();
Thread.sleep(100);
}
return 5;
}
});
// wait -> timeout
replacedertFalse(task.waitForCompletion(100, TimeUnit.MILLISECONDS));
synchronized (sync) {
sync.notify();
}
// wait -> completes
replacedertTrue(task.waitForCompletion(1000, TimeUnit.MILLISECONDS));
// wait -> already completed
replacedertTrue(task.waitForCompletion(100, TimeUnit.MILLISECONDS));
replacedertEquals(5, task.getResult().intValue());
}
@Test
public void testBackgroundCallWaitingOnError() throws Exception {
Task<Integer> task = Task.callInBackground(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(100);
throw new RuntimeException();
}
});
task.waitForCompletion();
replacedertTrue(task.isCompleted());
replacedertTrue(task.isFaulted());
}
@Test
public void testBackgroundCallWaitOnCancellation() throws Exception {
Task<Integer> task = Task.callInBackground(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(100);
return 5;
}
}).continueWithTask(new Continuation<Integer, Task<Integer>>() {
public Task<Integer> then(Task<Integer> task) {
return Task.cancelled();
}
});
task.waitForCompletion();
replacedertTrue(task.isCompleted());
replacedertTrue(task.isCancelled());
}
@Test
public void testBackgroundError() {
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.callInBackground(new Callable<Integer>() {
public Integer call() throws Exception {
throw new IllegalStateException();
}
}).continueWith(new Continuation<Integer, Void>() {
public Void then(Task<Integer> task) {
replacedertTrue(task.isFaulted());
replacedertTrue(task.getError() instanceof IllegalStateException);
return null;
}
});
}
});
}
@Test
public void testBackgroundCancellation() {
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.callInBackground(new Callable<Void>() {
public Void call() throws Exception {
throw new CancellationException();
}
}).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) {
replacedertTrue(task.isCancelled());
return null;
}
});
}
});
}
@Test
public void testUnobservedError() throws InterruptedException {
try {
final Object sync = new Object();
Task.setUnobservedExceptionHandler(new Task.UnobservedExceptionHandler() {
@Override
public void unobservedException(Task<?> t, UnobservedTaskException e) {
synchronized (sync) {
sync.notify();
}
}
});
synchronized (sync) {
startFailedTask();
System.gc();
sync.wait();
}
} finally {
Task.setUnobservedExceptionHandler(null);
}
}
// runs in a separate method to ensure it is out of scope.
private void startFailedTask() throws InterruptedException {
Task.call(new Callable<Object>() {
@Override
public Object call() throws Exception {
throw new RuntimeException();
}
}).waitForCompletion();
}
@Test
public void testWhenAllNoTasks() {
Task<Void> task = Task.whenAll(new ArrayList<Task<Void>>());
replacedertTrue(task.isCompleted());
replacedertFalse(task.isCancelled());
replacedertFalse(task.isFaulted());
}
@Test
public void testWhenAnyResultFirstSuccess() {
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<Integer>> tasks = new ArrayList<>();
final Task<Integer> firstToCompleteSuccess = Task.callInBackground(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(50);
return 10;
}
});
tasks.addAll(launchTasksWithRandomCompletions(5));
tasks.add(firstToCompleteSuccess);
tasks.addAll(launchTasksWithRandomCompletions(5));
return Task.whenAnyResult(tasks).continueWith(new Continuation<Task<Integer>, Void>() {
@Override
public Void then(Task<Task<Integer>> task) throws Exception {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertEquals(firstToCompleteSuccess, task.getResult());
replacedertTrue(task.getResult().isCompleted());
replacedertFalse(task.getResult().isCancelled());
replacedertFalse(task.getResult().isFaulted());
replacedertEquals(10, (int) task.getResult().getResult());
return null;
}
});
}
});
}
@Test
public void testWhenAnyFirstSuccess() {
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<?>> tasks = new ArrayList<>();
final Task<String> firstToCompleteSuccess = Task.callInBackground(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(50);
return "SUCCESS";
}
});
tasks.addAll(launchTasksWithRandomCompletions(5));
tasks.add(firstToCompleteSuccess);
tasks.addAll(launchTasksWithRandomCompletions(5));
return Task.whenAny(tasks).continueWith(new Continuation<Task<?>, Object>() {
@Override
public Object then(Task<Task<?>> task) throws Exception {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertEquals(firstToCompleteSuccess, task.getResult());
replacedertTrue(task.getResult().isCompleted());
replacedertFalse(task.getResult().isCancelled());
replacedertFalse(task.getResult().isFaulted());
replacedertEquals("SUCCESS", task.getResult().getResult());
return null;
}
});
}
});
}
@Test
public void testWhenAnyResultFirstError() {
final Exception error = new RuntimeException("This task failed.");
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<Integer>> tasks = new ArrayList<>();
final Task<Integer> firstToCompleteError = Task.callInBackground(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(50);
throw error;
}
});
tasks.addAll(launchTasksWithRandomCompletions(5));
tasks.add(firstToCompleteError);
tasks.addAll(launchTasksWithRandomCompletions(5));
return Task.whenAnyResult(tasks).continueWith(new Continuation<Task<Integer>, Object>() {
@Override
public Object then(Task<Task<Integer>> task) throws Exception {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertEquals(firstToCompleteError, task.getResult());
replacedertTrue(task.getResult().isCompleted());
replacedertFalse(task.getResult().isCancelled());
replacedertTrue(task.getResult().isFaulted());
replacedertEquals(error, task.getResult().getError());
return null;
}
});
}
});
}
@Test
public void testWhenAnyFirstError() {
final Exception error = new RuntimeException("This task failed.");
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<?>> tasks = new ArrayList<>();
final Task<String> firstToCompleteError = Task.callInBackground(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(50);
throw error;
}
});
tasks.addAll(launchTasksWithRandomCompletions(5));
tasks.add(firstToCompleteError);
tasks.addAll(launchTasksWithRandomCompletions(5));
return Task.whenAny(tasks).continueWith(new Continuation<Task<?>, Object>() {
@Override
public Object then(Task<Task<?>> task) throws Exception {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertEquals(firstToCompleteError, task.getResult());
replacedertTrue(task.getResult().isCompleted());
replacedertFalse(task.getResult().isCancelled());
replacedertTrue(task.getResult().isFaulted());
replacedertEquals(error, task.getResult().getError());
return null;
}
});
}
});
}
@Test
public void testWhenAnyResultFirstCancelled() {
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<Integer>> tasks = new ArrayList<>();
final Task<Integer> firstToCompleteCancelled = Task.callInBackground(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(50);
throw new CancellationException();
}
});
tasks.addAll(launchTasksWithRandomCompletions(5));
tasks.add(firstToCompleteCancelled);
tasks.addAll(launchTasksWithRandomCompletions(5));
return Task.whenAnyResult(tasks).continueWith(new Continuation<Task<Integer>, Object>() {
@Override
public Object then(Task<Task<Integer>> task) throws Exception {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertEquals(firstToCompleteCancelled, task.getResult());
replacedertTrue(task.getResult().isCompleted());
replacedertTrue(task.getResult().isCancelled());
replacedertFalse(task.getResult().isFaulted());
return null;
}
});
}
});
}
@Test
public void testWhenAnyFirstCancelled() {
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<?>> tasks = new ArrayList<>();
final Task<String> firstToCompleteCancelled = Task.callInBackground(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(50);
throw new CancellationException();
}
});
tasks.addAll(launchTasksWithRandomCompletions(5));
tasks.add(firstToCompleteCancelled);
tasks.addAll(launchTasksWithRandomCompletions(5));
return Task.whenAny(tasks).continueWith(new Continuation<Task<?>, Object>() {
@Override
public Object then(Task<Task<?>> task) throws Exception {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertEquals(firstToCompleteCancelled, task.getResult());
replacedertTrue(task.getResult().isCompleted());
replacedertTrue(task.getResult().isCancelled());
replacedertFalse(task.getResult().isFaulted());
return null;
}
});
}
});
}
/**
* Launches a given number of tasks (of Integer) that will complete either in a completed,
* cancelled or faulted state (random distribution).
* Each task will reach completion after a somehow random delay (between 500 and 600 ms).
* Each task reaching a success completion state will have its result set to a random Integer
* (between 0 to 1000).
* @param numberOfTasksToLaunch The number of tasks to launch
* @return A collection containing all the tasks that have been launched
*/
private Collection<Task<Integer>> launchTasksWithRandomCompletions(int numberOfTasksToLaunch) {
final ArrayList<Task<Integer>> tasks = new ArrayList<>();
for (int i = 0; i < numberOfTasksToLaunch; i++) {
Task<Integer> task = Task.callInBackground(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep((long) (500 + (Math.random() * 100)));
double rand = Math.random();
if (rand >= 0.7) {
throw new RuntimeException("This task failed.");
} else if (rand >= 0.4) {
throw new CancellationException();
}
return (int) (Math.random() * 1000);
}
});
tasks.add(task);
}
return tasks;
}
@Test
public void testWhenAllSuccess() {
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<Void>> tasks = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Task<Void> task = Task.callInBackground(new Callable<Void>() {
@Override
public Void call() throws Exception {
Thread.sleep((long) (Math.random() * 100));
return null;
}
});
tasks.add(task);
}
return Task.whenAll(tasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
for (Task<Void> t : tasks) {
replacedertTrue(t.isCompleted());
}
return null;
}
});
}
});
}
@Test
public void testWhenAllOneError() {
final Exception error = new RuntimeException("This task failed.");
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<Void>> tasks = new ArrayList<>();
for (int i = 0; i < 20; i++) {
final int number = i;
Task<Void> task = Task.callInBackground(new Callable<Void>() {
@Override
public Void call() throws Exception {
Thread.sleep((long) (Math.random() * 100));
if (number == 10) {
throw error;
}
return null;
}
});
tasks.add(task);
}
return Task.whenAll(tasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) {
replacedertTrue(task.isCompleted());
replacedertTrue(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertFalse(task.getError() instanceof AggregateException);
replacedertEquals(error, task.getError());
for (Task<Void> t : tasks) {
replacedertTrue(t.isCompleted());
}
return null;
}
});
}
});
}
@Test
public void testWhenAllTwoErrors() {
final Exception error0 = new RuntimeException("This task failed (0).");
final Exception error1 = new RuntimeException("This task failed (1).");
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<Void>> tasks = new ArrayList<>();
for (int i = 0; i < 20; i++) {
final int number = i;
Task<Void> task = Task.callInBackground(new Callable<Void>() {
@Override
public Void call() throws Exception {
Thread.sleep((long) (number * 10));
if (number == 10) {
throw error0;
} else if (number == 11) {
throw error1;
}
return null;
}
});
tasks.add(task);
}
return Task.whenAll(tasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) {
replacedertTrue(task.isCompleted());
replacedertTrue(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertTrue(task.getError() instanceof AggregateException);
replacedertEquals(2, ((AggregateException) task.getError()).getInnerThrowables().size());
replacedertEquals(error0, ((AggregateException) task.getError()).getInnerThrowables().get(0));
replacedertEquals(error1, ((AggregateException) task.getError()).getInnerThrowables().get(1));
replacedertEquals(error0, task.getError().getCause());
for (Task<Void> t : tasks) {
replacedertTrue(t.isCompleted());
}
return null;
}
});
}
});
}
@Test
public void testWhenAllCancel() {
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final ArrayList<Task<Void>> tasks = new ArrayList<>();
for (int i = 0; i < 20; i++) {
final TaskCompletionSource<Void> tcs = new TaskCompletionSource<>();
final int number = i;
Task.callInBackground(new Callable<Void>() {
@Override
public Void call() throws Exception {
Thread.sleep((long) (Math.random() * 100));
if (number == 10) {
tcs.setCancelled();
} else {
tcs.setResult(null);
}
return null;
}
});
tasks.add(tcs.getTask());
}
return Task.whenAll(tasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertTrue(task.isCancelled());
for (Task<Void> t : tasks) {
replacedertTrue(t.isCompleted());
}
return null;
}
});
}
});
}
@Test
public void testWhenAllResultNoTasks() {
Task<List<Void>> task = Task.whenAllResult(new ArrayList<Task<Void>>());
replacedertTrue(task.isCompleted());
replacedertFalse(task.isCancelled());
replacedertFalse(task.isFaulted());
replacedertTrue(task.getResult().isEmpty());
}
@Test
public void testWhenAllResultSuccess() {
runTaskTest(new Callable<Task<?>>() {
@Override
public Task<?> call() throws Exception {
final List<Task<Integer>> tasks = new ArrayList<>();
for (int i = 0; i < 20; i++) {
final int number = (i + 1);
Task<Integer> task = Task.callInBackground(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep((long) (Math.random() * 100));
return number;
}
});
tasks.add(task);
}
return Task.whenAllResult(tasks).continueWith(new Continuation<List<Integer>, Void>() {
@Override
public Void then(Task<List<Integer>> task) {
replacedertTrue(task.isCompleted());
replacedertFalse(task.isFaulted());
replacedertFalse(task.isCancelled());
replacedertEquals(tasks.size(), task.getResult().size());
for (int i = 0; i < tasks.size(); i++) {
Task<Integer> t = tasks.get(i);
replacedertTrue(t.isCompleted());
replacedertEquals(t.getResult(), task.getResult().get(i));
}
return null;
}
});
}
});
}
@Test
public void testAsyncChaining() {
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
final ArrayList<Integer> sequence = new ArrayList<>();
Task<Void> result = Task.forResult(null);
for (int i = 0; i < 20; i++) {
final int taskNumber = i;
result = result.continueWithTask(new Continuation<Void, Task<Void>>() {
public Task<Void> then(Task<Void> task) {
return Task.callInBackground(new Callable<Void>() {
public Void call() throws Exception {
sequence.add(taskNumber);
return null;
}
});
}
});
}
result = result.continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) {
replacedertEquals(20, sequence.size());
for (int i = 0; i < 20; i++) {
replacedertEquals(i, sequence.get(i).intValue());
}
return null;
}
});
return result;
}
});
}
@Test
public void testOnSuccess() {
Continuation<Integer, Integer> continuation = new Continuation<Integer, Integer>() {
public Integer then(Task<Integer> task) {
return task.getResult() + 1;
}
};
Task<Integer> complete = Task.forResult(5).onSuccess(continuation);
Task<Integer> error = Task.<Integer>forError(new IllegalStateException()).onSuccess(continuation);
Task<Integer> cancelled = Task.<Integer>cancelled().onSuccess(continuation);
replacedertTrue(complete.isCompleted());
replacedertEquals(6, complete.getResult().intValue());
replacedertFalse(complete.isFaulted());
replacedertFalse(complete.isCancelled());
replacedertTrue(error.isCompleted());
replacedertTrue(error.getError() instanceof RuntimeException);
replacedertTrue(error.isFaulted());
replacedertFalse(error.isCancelled());
replacedertTrue(cancelled.isCompleted());
replacedertFalse(cancelled.isFaulted());
replacedertTrue(cancelled.isCancelled());
}
@Test
public void testOnSuccessTask() {
Continuation<Integer, Task<Integer>> continuation = new Continuation<Integer, Task<Integer>>() {
public Task<Integer> then(Task<Integer> task) {
return Task.forResult(task.getResult() + 1);
}
};
Task<Integer> complete = Task.forResult(5).onSuccessTask(continuation);
Task<Integer> error = Task.<Integer>forError(new IllegalStateException()).onSuccessTask(continuation);
Task<Integer> cancelled = Task.<Integer>cancelled().onSuccessTask(continuation);
replacedertTrue(complete.isCompleted());
replacedertEquals(6, complete.getResult().intValue());
replacedertFalse(complete.isFaulted());
replacedertFalse(complete.isCancelled());
replacedertTrue(error.isCompleted());
replacedertTrue(error.getError() instanceof RuntimeException);
replacedertTrue(error.isFaulted());
replacedertFalse(error.isCancelled());
replacedertTrue(cancelled.isCompleted());
replacedertFalse(cancelled.isFaulted());
replacedertTrue(cancelled.isCancelled());
}
@Test
public void testContinueWhile() {
final AtomicInteger count = new AtomicInteger(0);
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.forResult(null).continueWhile(new Callable<Boolean>() {
public Boolean call() throws Exception {
return count.get() < 10;
}
}, new Continuation<Void, Task<Void>>() {
public Task<Void> then(Task<Void> task) throws Exception {
count.incrementAndGet();
return null;
}
}).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) throws Exception {
replacedertEquals(10, count.get());
return null;
}
});
}
});
}
@Test
public void testContinueWhileAsync() {
final AtomicInteger count = new AtomicInteger(0);
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.forResult(null).continueWhile(new Callable<Boolean>() {
public Boolean call() throws Exception {
return count.get() < 10;
}
}, new Continuation<Void, Task<Void>>() {
public Task<Void> then(Task<Void> task) throws Exception {
count.incrementAndGet();
return null;
}
}, Executors.newCachedThreadPool()).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) throws Exception {
replacedertEquals(10, count.get());
return null;
}
});
}
});
}
@Test
public void testContinueWhileAsyncCancellation() {
final AtomicInteger count = new AtomicInteger(0);
final CancellationTokenSource cts = new CancellationTokenSource();
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.forResult(null).continueWhile(new Callable<Boolean>() {
public Boolean call() throws Exception {
return count.get() < 10;
}
}, new Continuation<Void, Task<Void>>() {
public Task<Void> then(Task<Void> task) throws Exception {
if (count.incrementAndGet() == 5) {
cts.cancel();
}
return null;
}
}, Executors.newCachedThreadPool(), cts.getToken()).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) throws Exception {
replacedertTrue(task.isCancelled());
replacedertEquals(5, count.get());
return null;
}
});
}
});
}
@Test
public void testCallWithBadExecutor() {
final RuntimeException exception = new RuntimeException("BAD EXECUTORS");
Task.call(new Callable<Integer>() {
public Integer call() throws Exception {
return 1;
}
}, new Executor() {
@Override
public void execute(Runnable command) {
throw exception;
}
}).continueWith(new Continuation<Integer, Object>() {
@Override
public Object then(Task<Integer> task) throws Exception {
replacedertTrue(task.isFaulted());
replacedertTrue(task.getError() instanceof ExecutorException);
replacedertEquals(exception, task.getError().getCause());
return null;
}
});
}
@Test
public void testContinueWithBadExecutor() {
final RuntimeException exception = new RuntimeException("BAD EXECUTORS");
Task.call(new Callable<Integer>() {
public Integer call() throws Exception {
return 1;
}
}).continueWith(new Continuation<Integer, Integer>() {
@Override
public Integer then(Task<Integer> task) throws Exception {
return task.getResult();
}
}, new Executor() {
@Override
public void execute(Runnable command) {
throw exception;
}
}).continueWith(new Continuation<Integer, Object>() {
@Override
public Object then(Task<Integer> task) throws Exception {
replacedertTrue(task.isFaulted());
replacedertTrue(task.getError() instanceof ExecutorException);
replacedertEquals(exception, task.getError().getCause());
return null;
}
});
}
@Test
public void testContinueWithTaskAndBadExecutor() {
final RuntimeException exception = new RuntimeException("BAD EXECUTORS");
Task.call(new Callable<Integer>() {
public Integer call() throws Exception {
return 1;
}
}).continueWithTask(new Continuation<Integer, Task<Integer>>() {
@Override
public Task<Integer> then(Task<Integer> task) throws Exception {
return task;
}
}, new Executor() {
@Override
public void execute(Runnable command) {
throw exception;
}
}).continueWith(new Continuation<Integer, Object>() {
@Override
public Object then(Task<Integer> task) throws Exception {
replacedertTrue(task.isFaulted());
replacedertTrue(task.getError() instanceof ExecutorException);
replacedertEquals(exception, task.getError().getCause());
return null;
}
});
}
// region TaskCompletionSource
@Test
public void testTrySetResult() {
TaskCompletionSource<String> tcs = new TaskCompletionSource<>();
Task<String> task = tcs.getTask();
replacedertFalse(task.isCompleted());
boolean success = tcs.trySetResult("SHOW ME WHAT YOU GOT");
replacedertTrue(success);
replacedertTrue(task.isCompleted());
replacedertEquals("SHOW ME WHAT YOU GOT", task.getResult());
}
@Test
public void testTrySetError() {
TaskCompletionSource<Void> tcs = new TaskCompletionSource<>();
Task<Void> task = tcs.getTask();
replacedertFalse(task.isCompleted());
Exception exception = new RuntimeException("DISQUALIFIED");
boolean success = tcs.trySetError(exception);
replacedertTrue(success);
replacedertTrue(task.isCompleted());
replacedertEquals(exception, task.getError());
}
@Test
public void testTrySetCanceled() {
TaskCompletionSource<Void> tcs = new TaskCompletionSource<>();
Task<Void> task = tcs.getTask();
replacedertFalse(task.isCompleted());
boolean success = tcs.trySetCancelled();
replacedertTrue(success);
replacedertTrue(task.isCompleted());
replacedertTrue(task.isCancelled());
}
@Test
public void testTrySetOnCompletedTask() {
TaskCompletionSource<Void> tcs = new TaskCompletionSource<>();
tcs.setResult(null);
replacedertFalse(tcs.trySetResult(null));
replacedertFalse(tcs.trySetError(new RuntimeException()));
replacedertFalse(tcs.trySetCancelled());
}
@Test
public void testSetResultOnCompletedTask() {
TaskCompletionSource<Void> tcs = new TaskCompletionSource<>();
tcs.setResult(null);
thrown.expect(IllegalStateException.clreplaced);
tcs.setResult(null);
}
@Test
public void testSetErrorOnCompletedTask() {
TaskCompletionSource<Void> tcs = new TaskCompletionSource<>();
tcs.setResult(null);
thrown.expect(IllegalStateException.clreplaced);
tcs.setError(new RuntimeException());
}
@Test
public void testSetCancelledOnCompletedTask() {
TaskCompletionSource<Void> tcs = new TaskCompletionSource<>();
tcs.setResult(null);
thrown.expect(IllegalStateException.clreplaced);
tcs.setCancelled();
}
// endregion
// region deprecated
@SuppressWarnings("deprecation")
@Test
public void testDeprecatedTaskCompletionSource() {
Task<Void>.TaskCompletionSource tcsA = Task.create();
tcsA.setResult(null);
replacedertTrue(tcsA.getTask().isCompleted());
TaskCompletionSource<Void> tcsB = Task.create();
tcsB.setResult(null);
replacedertTrue(tcsA.getTask().isCompleted());
}
@SuppressWarnings("deprecation")
@Test
public void testDeprecatedAggregateExceptionMethods() {
final Exception error0 = new Exception("This is an exception (0).");
final Exception error1 = new Exception("This is an exception (1).");
final Error error2 = new Error("This is an error.");
List<Exception> exceptions = new ArrayList<>();
exceptions.add(error0);
exceptions.add(error1);
// Test old functionality
AggregateException aggregate = new AggregateException(exceptions);
replacedertEquals("There were multiple errors.", aggregate.getMessage());
replacedertEquals(2, aggregate.getErrors().size());
replacedertEquals(error0, aggregate.getErrors().get(0));
replacedertEquals(error1, aggregate.getErrors().get(1));
replacedertEquals(2, aggregate.getCauses().length);
replacedertEquals(error0, aggregate.getCauses()[0]);
replacedertEquals(error1, aggregate.getCauses()[1]);
// Test deprecated getErrors method returns sane results with non-Exceptions
aggregate = new AggregateException("message", new Throwable[] { error0, error1, error2 });
replacedertEquals("message", aggregate.getMessage());
replacedertEquals(3, aggregate.getErrors().size());
replacedertEquals(error0, aggregate.getErrors().get(0));
replacedertEquals(error1, aggregate.getErrors().get(1));
replacedertNotSame(error2, aggregate.getErrors().get(2));
replacedertEquals(error2, aggregate.getErrors().get(2).getCause());
}
// endregion
}
19
Source : TestJsonReader.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
public clreplaced TestJsonReader extends BaseTestQuery {
// private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestJsonReader.clreplaced);
private static final boolean VERBOSE_DEBUG = false;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testEmptyList() throws Exception {
String root = FileUtils.getResourceAsFile("/store/json/emptyLists").toURI().toString();
String query = String.format("select count(a[0]) as ct from dfs_test.`%s`", root, root);
testBuilder().sqlQuery(query).ordered().baselineColumns("ct").baselineValues(6l).build().run();
}
@Test
public void schemaChange() throws Exception {
test("select b from dfs.`${WORKING_PATH}/src/test/resources/vector/complex/writer/schemaChange/`");
}
@Test
public void testFieldSelectionBug() throws Exception {
try {
testBuilder().sqlQuery("select t.field_4.inner_3 as col_1, t.field_4 as col_2 from cp.`store/json/schema_change_int_to_string.json` t").unOrdered().optionSettingQueriesForTestQuery("alter session set `store.json.all_text_mode` = true").baselineColumns("col_1", "col_2").baselineValues(mapOf(), mapOf("inner_1", listOf(), "inner_3", mapOf())).baselineValues(mapOf("inner_object_field_1", "2"), mapOf("inner_1", listOf("1", "2", "3"), "inner_2", "3", "inner_3", mapOf("inner_object_field_1", "2"))).baselineValues(mapOf(), mapOf("inner_1", listOf("4", "5", "6"), "inner_2", "3", "inner_3", mapOf())).go();
} finally {
test("alter session set `store.json.all_text_mode` = false");
}
}
@Test
public void testSplitAndTransferFailure() throws Exception {
final String testVal = "a string";
testBuilder().sqlQuery("select flatten(config) as flat from cp.`/store/json/null_list.json`").ordered().baselineColumns("flat").baselineValues(listOf()).baselineValues(listOf(testVal)).go();
test("select flatten(config) as flat from cp.`/store/json/null_list_v2.json`");
testBuilder().sqlQuery("select flatten(config) as flat from cp.`/store/json/null_list_v2.json`").ordered().baselineColumns("flat").baselineValues(mapOf("repeated_varchar", listOf())).baselineValues(mapOf("repeated_varchar", listOf(testVal))).go();
testBuilder().sqlQuery("select flatten(config) as flat from cp.`/store/json/null_list_v3.json`").ordered().baselineColumns("flat").baselineValues(mapOf("repeated_map", listOf(mapOf("repeated_varchar", listOf())))).baselineValues(mapOf("repeated_map", listOf(mapOf("repeated_varchar", listOf(testVal))))).go();
}
@Test
@Ignore("DRILL-1824")
public void schemaChangeValidate() throws Exception {
//
testBuilder().sqlQuery(//
"select b from dfs.`${WORKING_PATH}/src/test/resources/vector/complex/writer/schemaChange/`").unOrdered().jsonBaselineFile(//
"/vector/complex/writer/expected.json").build().run();
}
public void runTestsOnFile(String filename, UserBitShared.QueryType queryType, String[] queries, long[] rowCounts) throws Exception {
if (VERBOSE_DEBUG) {
System.out.println("===================");
System.out.println("source data in json");
System.out.println("===================");
System.out.println(Files.toString(FileUtils.getResourceAsFile(filename), Charsets.UTF_8));
}
int i = 0;
for (String query : queries) {
if (VERBOSE_DEBUG) {
System.out.println("=====");
System.out.println("query");
System.out.println("=====");
System.out.println(query);
System.out.println("======");
System.out.println("result");
System.out.println("======");
}
int rowCount = testRunAndPrint(queryType, query);
replacedertEquals(rowCounts[i], rowCount);
System.out.println();
i++;
}
}
@Test
public void testReadCompressed() throws Exception {
String filepath = "compressed_json.json";
File f = folder.newFile(filepath);
PrintWriter out = new PrintWriter(f);
out.println("{\"a\" :5}");
out.close();
gzipIt(f);
testBuilder().sqlQuery("select * from dfs.`" + f.getPath() + ".gz" + "`").unOrdered().baselineColumns("a").baselineValues(5l).build().run();
// test reading the uncompressed version as well
testBuilder().sqlQuery("select * from dfs.`" + f.getPath() + "`").unOrdered().baselineColumns("a").baselineValues(5l).build().run();
}
public static void gzipIt(File sourceFile) throws IOException {
// modified from: http://www.mkyong.com/java/how-to-compress-a-file-in-gzip-format/
byte[] buffer = new byte[1024];
GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(sourceFile.getPath() + ".gz"));
FileInputStream in = new FileInputStream(sourceFile);
int len;
while ((len = in.read(buffer)) > 0) {
gzos.write(buffer, 0, len);
}
in.close();
gzos.finish();
gzos.close();
}
@Test
public void testDrill_1419() throws Exception {
String[] queries = { "select t.trans_id, t.trans_info.prod_id[0],t.trans_info.prod_id[1] from cp.`/store/json/clicks.json` t limit 5" };
long[] rowCounts = { 5 };
String filename = "/store/json/clicks.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
}
@Test
public void testRepeatedCount() throws Exception {
test("select repeated_count(str_list) from cp.`/store/json/json_basic_repeated_varchar.json`");
test("select repeated_count(INT_col) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_count(FLOAT4_col) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_count(VARCHAR_col) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_count(BIT_col) from cp.`/parquet/alltypes_repeated.json`");
}
@Test
public void testRepeatedContains() throws Exception {
test("select repeated_contains(str_list, 'asdf') from cp.`/store/json/json_basic_repeated_varchar.json`");
test("select repeated_contains(INT_col, -2147483648) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_contains(FLOAT4_col, -1000000000000.0) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_contains(VARCHAR_col, 'qwerty' ) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_contains(BIT_col, true) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_contains(BIT_col, false) from cp.`/parquet/alltypes_repeated.json`");
}
@Test
public void testSingleColumnRead_vector_fill_bug() throws Exception {
String[] queries = { "select * from cp.`/store/json/single_column_long_file.json`" };
long[] rowCounts = { 13512 };
String filename = "/store/json/single_column_long_file.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
}
@Test
public void testNonExistentColumnReadAlone() throws Exception {
String[] queries = { "select non_existent_column from cp.`/store/json/single_column_long_file.json`" };
long[] rowCounts = { 13512 };
String filename = "/store/json/single_column_long_file.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
}
@Test
public void testAllTextMode() throws Exception {
test("alter system set `store.json.all_text_mode` = true");
String[] queries = { "select * from cp.`/store/json/schema_change_int_to_string.json`" };
long[] rowCounts = { 3 };
String filename = "/store/json/schema_change_int_to_string.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
test("alter system set `store.json.all_text_mode` = false");
}
@Test
public void readComplexWithStar() throws Exception {
List<QueryDataBatch> results = testSqlWithResults("select * from cp.`/store/json/test_complex_read_with_star.json`");
replacedertEquals(1, results.size());
RecordBatchLoader batchLoader = new RecordBatchLoader(getAllocator());
QueryDataBatch batch = results.get(0);
replacedertTrue(batchLoader.load(batch.getHeader().getDef(), batch.getData()));
replacedertEquals(3, batchLoader.getSchema().getFieldCount());
testExistentColumns(batchLoader);
batch.release();
batchLoader.clear();
}
@Test
public void testNullWhereListExpected() throws Exception {
test("alter system set `store.json.all_text_mode` = true");
String[] queries = { "select * from cp.`/store/json/null_where_list_expected.json`" };
long[] rowCounts = { 3 };
String filename = "/store/json/null_where_list_expected.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
test("alter system set `store.json.all_text_mode` = false");
}
@Test
public void testNullWhereMapExpected() throws Exception {
test("alter system set `store.json.all_text_mode` = true");
String[] queries = { "select * from cp.`/store/json/null_where_map_expected.json`" };
long[] rowCounts = { 3 };
String filename = "/store/json/null_where_map_expected.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
test("alter system set `store.json.all_text_mode` = false");
}
@Test
public void ensureProjectionPushdown() throws Exception {
// Tests to make sure that we are correctly eliminating schema changing columns. If completes, means that the projection pushdown was successful.
test("alter system set `store.json.all_text_mode` = false; " + "select t.field_1, t.field_3.inner_1, t.field_3.inner_2, t.field_4.inner_1 " + "from cp.`store/json/schema_change_int_to_string.json` t");
}
// The project pushdown rule is correctly adding the projected columns to the scan, however it is not removing
// the redundant project operator after the scan, this tests runs a physical plan generated from one of the tests to
// ensure that the project is filtering out the correct data in the scan alone
@Test
public void testProjectPushdown() throws Exception {
String[] queries = { Files.toString(FileUtils.getResourceAsFile("/store/json/project_pushdown_json_physical_plan.json"), Charsets.UTF_8) };
long[] rowCounts = { 3 };
String filename = "/store/json/schema_change_int_to_string.json";
test("alter system set `store.json.all_text_mode` = false");
runTestsOnFile(filename, UserBitShared.QueryType.PHYSICAL, queries, rowCounts);
List<QueryDataBatch> results = testPhysicalWithResults(queries[0]);
replacedertEquals(1, results.size());
// "`field_1`", "`field_3`.`inner_1`", "`field_3`.`inner_2`", "`field_4`.`inner_1`"
RecordBatchLoader batchLoader = new RecordBatchLoader(getAllocator());
QueryDataBatch batch = results.get(0);
replacedertTrue(batchLoader.load(batch.getHeader().getDef(), batch.getData()));
// this used to be five. It is now three. This is because the plan doesn't have a project.
// Scanners are not responsible for projecting non-existent columns (as long as they project one column)
replacedertEquals(3, batchLoader.getSchema().getFieldCount());
testExistentColumns(batchLoader);
batch.release();
batchLoader.clear();
}
@Test
public void testJsonDirectoryWithEmptyFile() throws Exception {
String root = FileUtils.getResourceAsFile("/store/json/jsonDirectoryWithEmpyFile").toURI().toString();
String queryRightEmpty = String.format("select * from dfs_test.`%s`", root);
testBuilder().sqlQuery(queryRightEmpty).unOrdered().baselineColumns("a").baselineValues(1l).build().run();
}
private void testExistentColumns(RecordBatchLoader batchLoader) throws SchemaChangeException {
VectorWrapper<?> vw = batchLoader.getValueAccessorById(//
RepeatedBigIntVector.clreplaced, //
batchLoader.getValueVectorId(SchemaPath.getCompoundPath("field_1")).getFieldIds());
replacedertEquals("[1]", vw.getValueVector().getAccessor().getObject(0).toString());
replacedertEquals("[5]", vw.getValueVector().getAccessor().getObject(1).toString());
replacedertEquals("[5,10,15]", vw.getValueVector().getAccessor().getObject(2).toString());
vw = batchLoader.getValueAccessorById(//
IntVector.clreplaced, //
batchLoader.getValueVectorId(SchemaPath.getCompoundPath("field_3", "inner_1")).getFieldIds());
replacedertNull(vw.getValueVector().getAccessor().getObject(0));
replacedertEquals(2l, vw.getValueVector().getAccessor().getObject(1));
replacedertEquals(5l, vw.getValueVector().getAccessor().getObject(2));
vw = batchLoader.getValueAccessorById(//
IntVector.clreplaced, //
batchLoader.getValueVectorId(SchemaPath.getCompoundPath("field_3", "inner_2")).getFieldIds());
replacedertNull(vw.getValueVector().getAccessor().getObject(0));
replacedertNull(vw.getValueVector().getAccessor().getObject(1));
replacedertEquals(3l, vw.getValueVector().getAccessor().getObject(2));
vw = batchLoader.getValueAccessorById(//
RepeatedBigIntVector.clreplaced, //
batchLoader.getValueVectorId(SchemaPath.getCompoundPath("field_4", "inner_1")).getFieldIds());
replacedertEquals("[]", vw.getValueVector().getAccessor().getObject(0).toString());
replacedertEquals("[1,2,3]", vw.getValueVector().getAccessor().getObject(1).toString());
replacedertEquals("[4,5,6]", vw.getValueVector().getAccessor().getObject(2).toString());
}
@Test
public void testSelectStarWithUnionType() throws Exception {
try {
String query = "select * from cp.`jsoninput/union/a.json`";
testBuilder().sqlQuery(query).ordered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").baselineColumns("field1", "field2").baselineValues(1L, 1.2).baselineValues(listOf(2L), 1.2).baselineValues(mapOf("inner1", 3L, "inner2", 4L), listOf(3L, 4.0, "5")).baselineValues(mapOf("inner1", 3L, "inner2", listOf(mapOf("innerInner1", 1L, "innerInner2", listOf(3L, "a")))), listOf(mapOf("inner3", 7L), 4.0, "5", mapOf("inner4", 9L), listOf(mapOf("inner5", 10L, "inner6", 11L), mapOf("inner5", 12L, "inner7", 13L)))).go();
} finally {
testNoResult("alter session set `exec.enable_union_type` = false");
}
}
@Test
public void testSelectFromListWithCase() throws Exception {
String query = "select a, typeOf(a) `type` from " + "(select case when is_list(field2) then field2[4][1].inner7 end a " + "from cp.`jsoninput/union/a.json`) where a is not null";
try {
testBuilder().sqlQuery(query).ordered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").baselineColumns("a", "type").baselineValues(13L, "BIGINT").go();
} finally {
testNoResult("alter session set `exec.enable_union_type` = false");
}
}
@Test
public void testTypeCase() throws Exception {
String query = "select case when is_bigint(field1) " + "then field1 when is_list(field1) then field1[0] " + "when is_map(field1) then t.field1.inner1 end f1 from cp.`jsoninput/union/a.json` t";
try {
testBuilder().sqlQuery(query).ordered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").baselineColumns("f1").baselineValues(1L).baselineValues(2L).baselineValues(3L).baselineValues(3L).go();
} finally {
testNoResult("alter session set `exec.enable_union_type` = false");
}
}
@Test
public void testSumWithTypeCase() throws Exception {
String query = "select sum(cast(f1 as bigint)) sum_f1 from " + "(select case when is_bigint(field1) then field1 " + "when is_list(field1) then field1[0] when is_map(field1) then t.field1.inner1 end f1 " + "from cp.`jsoninput/union/a.json` t)";
try {
testBuilder().sqlQuery(query).ordered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").baselineColumns("sum_f1").baselineValues(9L).go();
} finally {
testNoResult("alter session set `exec.enable_union_type` = false");
}
}
@Test
public void testUnionExpressionMaterialization() throws Exception {
String query = "select a + b c from cp.`jsoninput/union/b.json`";
try {
testBuilder().sqlQuery(query).ordered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").baselineColumns("c").baselineValues(3L).baselineValues(7.0).baselineValues(11.0).go();
} finally {
testNoResult("alter session set `exec.enable_union_type` = false");
}
}
@Test
public void testSumMultipleBatches() throws Exception {
String dfs_temp = getDfsTestTmpSchemaLocation();
File table_dir = new File(dfs_temp, "multi_batch");
table_dir.mkdir();
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.json")));
for (int i = 0; i < 10000; i++) {
os.write("{ type : \"map\", data : { a : 1 } }\n".getBytes());
os.write("{ type : \"bigint\", data : 1 }\n".getBytes());
}
os.flush();
os.close();
String query = "select sum(cast(case when `type` = 'map' then t.data.a else data end as bigint)) `sum` from dfs_test.tmp.multi_batch t";
try {
testBuilder().sqlQuery(query).ordered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").baselineColumns("sum").baselineValues(20000L).go();
} finally {
testNoResult("alter session set `exec.enable_union_type` = false");
}
}
@Test
public void testSumFilesWithDifferentSchema() throws Exception {
String dfs_temp = getDfsTestTmpSchemaLocation();
File table_dir = new File(dfs_temp, "multi_file");
table_dir.mkdir();
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.json")));
for (int i = 0; i < 10000; i++) {
os.write("{ type : \"map\", data : { a : 1 } }\n".getBytes());
}
os.flush();
os.close();
os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "b.json")));
for (int i = 0; i < 10000; i++) {
os.write("{ type : \"bigint\", data : 1 }\n".getBytes());
}
os.flush();
os.close();
String query = "select sum(cast(case when `type` = 'map' then t.data.a else data end as bigint)) `sum` from dfs_test.tmp.multi_file t";
try {
testBuilder().sqlQuery(query).ordered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").baselineColumns("sum").baselineValues(20000L).go();
} finally {
testNoResult("alter session set `exec.enable_union_type` = false");
}
}
@Test
public void drill_4032() throws Exception {
String dfs_temp = getDfsTestTmpSchemaLocation();
File table_dir = new File(dfs_temp, "drill_4032");
table_dir.mkdir();
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.json")));
os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes());
os.write("{\"col1\": \"val1\",\"col2\": {\"col3\":\"abc\", \"col4\":\"xyz\"}}".getBytes());
os.flush();
os.close();
os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "b.json")));
os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes());
os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes());
os.flush();
os.close();
testNoResult("select t.col2.col3 from dfs_test.tmp.drill_4032 t");
}
@Test
public void drill_4479() throws Exception {
try {
String dfs_temp = getDfsTestTmpSchemaLocation();
File table_dir = new File(dfs_temp, "drill_4479");
table_dir.mkdir();
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "mostlynulls.json")));
// Create an entire batch of null values for 3 columns
for (int i = 0; i < JSONRecordReader.DEFAULT_ROWS_PER_BATCH; i++) {
os.write("{\"a\": null, \"b\": null, \"c\": null}".getBytes());
}
// Add a row with {bigint, float, string} values
os.write("{\"a\": 123456789123, \"b\": 99.999, \"c\": \"Hello World\"}".getBytes());
os.flush();
os.close();
String query1 = "select c, count(*) as cnt from dfs_test.tmp.drill_4479 t group by c";
String query2 = "select a, b, c, count(*) as cnt from dfs_test.tmp.drill_4479 t group by a, b, c";
String query3 = "select max(a) as x, max(b) as y, max(c) as z from dfs_test.tmp.drill_4479 t";
testBuilder().sqlQuery(query1).ordered().optionSettingQueriesForTestQuery("alter session set `store.json.all_text_mode` = true").baselineColumns("c", "cnt").baselineValues(null, 4096L).baselineValues("Hello World", 1L).go();
testBuilder().sqlQuery(query2).ordered().optionSettingQueriesForTestQuery("alter session set `store.json.all_text_mode` = true").baselineColumns("a", "b", "c", "cnt").baselineValues(null, null, null, 4096L).baselineValues("123456789123", "99.999", "Hello World", 1L).go();
testBuilder().sqlQuery(query3).ordered().optionSettingQueriesForTestQuery("alter session set `store.json.all_text_mode` = true").baselineColumns("x", "y", "z").baselineValues("123456789123", "99.999", "Hello World").go();
} finally {
testNoResult("alter session set `store.json.all_text_mode` = false");
}
}
@Test
public void testFlattenEmptyArrayWithAllTextMode() throws Exception {
File path = new File(BaseTestQuery.getTempDir("json/input"));
path.mkdirs();
path.deleteOnExit();
String pathString = path.toPath().toString();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path, "empty_array_all_text_mode.json")))) {
writer.write("{ \"a\": { \"b\": { \"c\": [] }, \"c\": [] } }");
}
try {
String query = String.format("select flatten(t.a.b.c) as c from dfs_test.`%s/empty_array_all_text_mode.json` t", pathString);
testBuilder().sqlQuery(query).unOrdered().optionSettingQueriesForTestQuery("alter session set `store.json.all_text_mode` = true").expectsEmptyResultSet().go();
testBuilder().sqlQuery(query).unOrdered().optionSettingQueriesForTestQuery("alter session set `store.json.all_text_mode` = false").expectsEmptyResultSet().go();
} finally {
testNoResult("alter session reset `store.json.all_text_mode`");
}
}
@Test
public void testFlattenEmptyArrayWithUnionType() throws Exception {
File path = new File(BaseTestQuery.getTempDir("json/input"));
path.mkdirs();
path.deleteOnExit();
String pathString = path.toPath().toString();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path, "empty_array.json")))) {
writer.write("{ \"a\": { \"b\": { \"c\": [] }, \"c\": [] } }");
}
try {
String query = String.format("select flatten(t.a.b.c) as c from dfs_test.`%s/empty_array.json` t", pathString);
testBuilder().sqlQuery(query).unOrdered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").expectsEmptyResultSet().go();
testBuilder().sqlQuery(query).unOrdered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").optionSettingQueriesForTestQuery("alter session set `store.json.all_text_mode` = true").expectsEmptyResultSet().go();
} finally {
testNoResult("alter session reset `store.json.all_text_mode`");
testNoResult("alter session reset `exec.enable_union_type`");
}
}
// DRILL-5521
@Test
public void testKvgenWithUnionAll() throws Exception {
File directory = new File(BaseTestQuery.getTempDir("json/input"));
try {
directory.mkdirs();
String fileName = "map.json";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(directory, fileName)))) {
writer.write("{\"rk\": \"a\", \"m\": {\"a\":\"1\"}}");
}
String query = String.format("select kvgen(m) as res from (select m from dfs_test.`%s/%s` union all " + "select convert_from('{\"a\" : null}' ,'json') as m from (values(1)))", directory.toPath().toString(), fileName);
replacedertEquals("Row count should match", 2, testSql(query));
} finally {
org.apache.commons.io.FileUtils.deleteQuietly(directory);
}
}
// DRILL-4264
@Test
public void testFieldWithDots() throws Exception {
File directory = new File(BaseTestQuery.getTempDir("json/input"));
try {
directory.mkdirs();
String fileName = "table.json";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(directory, fileName)))) {
writer.write("{\"rk.q\": \"a\", \"m\": {\"a.b\":\"1\", \"a\":{\"b\":\"2\"}, \"c\":\"3\"}}");
}
String query = String.format("select t.m.`a.b` as a,\n" + "t.m.a.b as b,\n" + "t.m['a.b'] as c,\n" + "t.rk.q as d,\n" + "t.`rk.q` as e\n" + "from dfs_test.`%s/%s` t", directory.toPath().toString(), fileName);
testBuilder().sqlQuery(query).unOrdered().baselineColumns("a", "b", "c", "d", "e").baselineValues("1", "2", "1", null, "a").go();
} finally {
org.apache.commons.io.FileUtils.deleteQuietly(directory);
}
}
}
19
Source : TestFlatten.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
public clreplaced TestFlatten extends BaseTestQuery {
/**
* enable this if you have the following files:
* - /tmp/yelp_academic_dataset_business.json
* - /tmp/mapkv.json
* - /tmp/drill1665.json
* - /tmp/bigfile.json
*/
public static boolean RUN_ADVANCED_TESTS = false;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testFlattenFailure() throws Exception {
test("select flatten(complex), rownum from cp.`/store/json/test_flatten_mappify2.json`");
// test("select complex, rownum from cp.`/store/json/test_flatten_mappify2.json`");
}
@Test
public void testFlatten_Drill2162_complex() throws Exception {
String path = folder.getRoot().toPath().toString();
String jsonRecords = BaseTestQuery.getFile("flatten/complex_transaction_example_data.json");
int numCopies = 700;
new TestConstantFolding.SmallFileCreator(folder).setRecord(jsonRecords).createFiles(1, numCopies, "json");
@SuppressWarnings("unchecked")
List<JsonStringHashMap<String, Object>> data = Lists.newArrayList(mapOf("uid", 1l, "lst_lst_0", listOf(1l, 2l, 3l, 4l, 5l), "lst_lst_1", listOf(2l, 3l, 4l, 5l, 6l), "lst_lst", listOf(listOf(1l, 2l, 3l, 4l, 5l), listOf(2l, 3l, 4l, 5l, 6l))), mapOf("uid", 2l, "lst_lst_0", listOf(1l, 2l, 3l, 4l, 5l), "lst_lst_1", listOf(2l, 3l, 4l, 5l, 6l), "lst_lst", listOf(listOf(1l, 2l, 3l, 4l, 5l), listOf(2l, 3l, 4l, 5l, 6l))));
List<JsonStringHashMap<String, Object>> result = flatten(flatten(flatten(data, "lst_lst_1"), "lst_lst_0"), "lst_lst");
TestBuilder builder = testBuilder().sqlQuery("select uid, flatten(d.lst_lst[1]) lst1, flatten(d.lst_lst[0]) lst0, flatten(d.lst_lst) lst from " + "dfs.`" + path + "/bigfile/bigfile.json` d").unOrdered().baselineColumns("uid", "lst1", "lst0", "lst");
for (int i = 0; i < numCopies; i++) {
for (JsonStringHashMap<String, Object> record : result) {
builder.baselineValues(record.get("uid"), record.get("lst_lst_1"), record.get("lst_lst_0"), record.get("lst_lst"));
}
}
builder.go();
}
@Test
public void testFlattenReferenceImpl() throws Exception {
@SuppressWarnings("unchecked")
List<JsonStringHashMap<String, Object>> data = Lists.newArrayList(mapOf("a", 1, "b", 2, "list_col", listOf(10, 9), "nested_list_col", listOf(listOf(100, 99), listOf(1000, 999))));
List<JsonStringHashMap<String, Object>> result = flatten(flatten(flatten(data, "list_col"), "nested_list_col"), "nested_list_col");
@SuppressWarnings("unchecked")
List<JsonStringHashMap<String, Object>> expectedResult = Lists.newArrayList(mapOf("nested_list_col", 100, "list_col", 10, "a", 1, "b", 2), mapOf("nested_list_col", 99, "list_col", 10, "a", 1, "b", 2), mapOf("nested_list_col", 1000, "list_col", 10, "a", 1, "b", 2), mapOf("nested_list_col", 999, "list_col", 10, "a", 1, "b", 2), mapOf("nested_list_col", 100, "list_col", 9, "a", 1, "b", 2), mapOf("nested_list_col", 99, "list_col", 9, "a", 1, "b", 2), mapOf("nested_list_col", 1000, "list_col", 9, "a", 1, "b", 2), mapOf("nested_list_col", 999, "list_col", 9, "a", 1, "b", 2));
int i = 0;
for (JsonStringHashMap<String, Object> record : result) {
replacedertEquals(record, expectedResult.get(i));
i++;
}
}
private List<JsonStringHashMap<String, Object>> flatten(List<JsonStringHashMap<String, Object>> incomingRecords, String colToFlatten) {
return flatten(incomingRecords, colToFlatten, colToFlatten);
}
private List<JsonStringHashMap<String, Object>> flatten(List<JsonStringHashMap<String, Object>> incomingRecords, String colToFlatten, String flattenedDataColName) {
List<JsonStringHashMap<String, Object>> output = Lists.newArrayList();
for (JsonStringHashMap<String, Object> incomingRecord : incomingRecords) {
List<?> dataToFlatten = (List<?>) incomingRecord.get(colToFlatten);
for (int i = 0; i < dataToFlatten.size(); i++) {
final JsonStringHashMap<String, Object> newRecord = new JsonStringHashMap<>();
newRecord.put(flattenedDataColName, dataToFlatten.get(i));
for (String s : incomingRecord.keySet()) {
if (s.equals(colToFlatten)) {
continue;
}
newRecord.put(s, incomingRecord.get(s));
}
output.add(newRecord);
}
}
return output;
}
@Test
public void testFlatten_Drill2162_simple() throws Exception {
String path = folder.getRoot().toPath().toString();
List<Long> inputList = Lists.newArrayList();
String jsonRecord = "{ \"int_list\" : [";
final int listSize = 30;
for (int i = 1; i < listSize; i++) {
jsonRecord += i + ", ";
inputList.add((long) i);
}
jsonRecord += listSize + "] }";
inputList.add((long) listSize);
int numRecords = 3000;
new TestConstantFolding.SmallFileCreator(folder).setRecord(jsonRecord).createFiles(1, numRecords, "json");
@SuppressWarnings("unchecked")
List<JsonStringHashMap<String, Object>> data = Lists.newArrayList(mapOf("int_list", inputList));
List<JsonStringHashMap<String, Object>> result = flatten(data, "int_list");
TestBuilder builder = testBuilder().sqlQuery("select flatten(int_list) as int_list from dfs.`" + path + "/bigfile/bigfile.json`").unOrdered().baselineColumns("int_list");
for (int i = 0; i < numRecords; i++) {
for (JsonStringHashMap<String, Object> record : result) {
builder.baselineValues(record.get("int_list"));
}
}
builder.go();
}
@Test
public void drill1671() throws Exception {
int rowCount = testSql("select * from (select count(*) as cnt from (select id, flatten(evnts1), flatten(evnts2), flatten(evnts3), flatten(evnts4), flatten(evnts5), flatten(evnts6), flatten(evnts7), flatten(evnts8), flatten(evnts9), flatten(evnts10), flatten(evnts11) from cp.`/flatten/many-arrays-50.json`)x )y where cnt = 2048");
replacedertEquals(rowCount, 1);
}
@Test
public void drill3370() throws Exception {
testBuilder().sqlQuery("select a from (select flatten(arr) as a from cp.`/flatten/drill-3370.json`) where a > 100").unOrdered().baselineColumns("a").baselineValues(131l).baselineValues(106l).go();
}
@Test
@Ignore("not yet fixed")
public void drill1660() throws Exception {
test("select * from cp.`/flatten/empty-rm.json`");
}
// repeated list within a repeated map
@Test
public void drill1673() throws Exception {
String path = folder.getRoot().toPath().toString();
String jsonRecords = BaseTestQuery.getFile("store/json/1673.json");
int numCopies = 25000;
new TestConstantFolding.SmallFileCreator(folder).setRecord(jsonRecords).createFiles(1, numCopies, "json");
TestBuilder builder = testBuilder().sqlQuery("select t.fixed_column as fixed_column, " + "flatten(t.list_column) as list_col " + "from dfs.`" + path + "/bigfile/bigfile.json` as t").baselineColumns("fixed_column", "list_col").unOrdered();
Object map1 = mapOf("id1", "1", "name", "zhu", "num", listOf(listOf(1l, 2l, 3l)));
Object map2 = mapOf("id1", "2", "name", "hao", "num", listOf(listOf(4l, 5l, 6l)));
for (int i = 0; i < numCopies; i++) {
builder.baselineValues("abc", map1);
builder.baselineValues("abc", map2);
}
builder.go();
}
@Test
public void drill1653() throws Exception {
int rowCount = testSql("select * from (select sum(t.flat.`value`) as sm from (select id, flatten(kvgen(m)) as flat from cp.`/flatten/missing-map.json`)t) where sm = 10 ");
replacedertEquals(1, rowCount);
}
@Test
public void drill1652() throws Exception {
if (RUN_ADVANCED_TESTS) {
test("select uid, flatten(transactions) from dfs.`/tmp/bigfile.json`");
}
}
@Test
@Ignore("Still not working.")
public void drill1649() throws Exception {
test("select event_info.uid, transaction_info.trans_id, event_info.event.evnt_id\n" + "from (\n" + " select userinfo.transaction.trans_id trans_id, max(userinfo.event.event_time) max_event_time\n" + " from (\n" + " select uid, flatten(events) event, flatten(transactions) transaction from cp.`/flatten/single-user-transactions.json`\n" + " ) userinfo\n" + " where userinfo.transaction.trans_time >= userinfo.event.event_time\n" + " group by userinfo.transaction.trans_id\n" + ") transaction_info\n" + "inner join\n" + "(\n" + " select uid, flatten(events) event\n" + " from cp.`/flatten/single-user-transactions.json`\n" + ") event_info\n" + "on transaction_info.max_event_time = event_info.event.event_time;");
}
@Test
public void testKVGenFlatten1() throws Exception {
// works - TODO and verify results
test("select flatten(kvgen(f1)) as monkey, x " + "from cp.`/store/json/test_flatten_mapify.json`");
}
@Test
public void testTwoFlattens() throws Exception {
// second re-write rule has been added to test the fixes together, this now runs
test("select `integer`, `float`, x, flatten(z), flatten(l) from cp.`/jsoninput/input2_modified.json`");
}
@Test
public void testFlattenRepeatedMap() throws Exception {
test("select `integer`, `float`, x, flatten(z) from cp.`/jsoninput/input2.json`");
}
@Test
public void testFlattenKVGenFlatten() throws Exception {
// currently does not fail, but produces incorrect results, requires second re-write rule to split up expressions
// with complex outputs
test("select `integer`, `float`, x, flatten(kvgen(flatten(z))) from cp.`/jsoninput/input2.json`");
}
@Test
public void testKVGenFlatten2() throws Exception {
// currently runs
// TODO - re-verify results by hand
if (RUN_ADVANCED_TESTS) {
test("select flatten(kvgen(visited_cellid_counts)) as mytb from dfs.`/tmp/mapkv.json`");
}
}
@Test
public void testFilterFlattenedRecords() throws Exception {
// WORKS!!
// TODO - hand verify results
test("select t2.key from (select t.monkey.`value` as val, t.monkey.key as key from (select flatten(kvgen(f1)) as monkey, x " + "from cp.`/store/json/test_flatten_mapify.json`) as t) as t2 where t2.val > 1");
}
@Test
public void testFilterFlattenedRecords2() throws Exception {
// previously failed in generated code
// "value" is neither a method, a field, nor a member clreplaced of "org.apache.drill.exec.expr.holders.RepeatedVarCharHolder" [ 42eb1fa1-0742-4e4f-8723-609215c18900 on 10.250.0.86:31010 ]
// appears to be resolving the data coming out of flatten as repeated, check fast schema stuff
// FIXED BY RETURNING PROPER SCHEMA DURING FAST SCHEMA STEP
// these types of problems are being solved more generally as we develp better support for chaning schema
if (RUN_ADVANCED_TESTS) {
test("select celltbl.catl from (\n" + " select flatten(categories) catl from dfs.`/tmp/yelp_academic_dataset_business.json` b limit 100\n" + " ) celltbl where celltbl.catl = 'Doctors'");
}
}
@Test
public void countAggFlattened() throws Exception {
if (RUN_ADVANCED_TESTS) {
test("select celltbl.catl, count(celltbl.catl) from ( " + "select business_id, flatten(categories) catl from dfs.`/tmp/yelp_academic_dataset_business.json` b limit 100 " + ") celltbl group by celltbl.catl limit 10 ");
}
}
@Test
public void flattenAndAdditionalColumn() throws Exception {
if (RUN_ADVANCED_TESTS) {
test("select business_id, flatten(categories) from dfs.`/tmp/yelp_academic_dataset_business.json` b");
}
}
@Test
public void testFailingFlattenAlone() throws Exception {
if (RUN_ADVANCED_TESTS) {
test("select flatten(categories) from dfs.`/tmp/yelp_academic_dataset_business.json` b ");
}
}
@Test
public void testDistinctAggrFlattened() throws Exception {
if (RUN_ADVANCED_TESTS) {
test(" select distinct(celltbl.catl) from (\n" + " select flatten(categories) catl from dfs.`/tmp/yelp_academic_dataset_business.json` b\n" + " ) celltbl");
}
}
@Test
public void testDrill1665() throws Exception {
if (RUN_ADVANCED_TESTS) {
test("select id, flatten(evnts) as rpt from dfs.`/tmp/drill1665.json`");
}
}
@Test
public void testFlattenComplexRepeatedMap() throws Exception {
test("select a, flatten(r_map_1), flatten(r_map_2) from cp.`/store/json/complex_repeated_map.json`");
}
@Test
public void testFlatten2_levelRepeatedMap() throws Exception {
test("select flatten(rm) from cp.`/store/json/2_level_repeated_map.json`");
}
@Test
public void testDrill_1770() throws Exception {
test("select flatten(sub.fk.`value`) from (select flatten(kvgen(map)) fk from cp.`/store/json/nested_repeated_map.json`) sub");
}
// DRILL-2254
@Test
public void testSingleFlattenFromNestedRepeatedList() throws Exception {
final String query = "select t.uid, flatten(t.odd) odd from cp.`project/complex/a.json` t";
testBuilder().sqlQuery(query).unOrdered().jsonBaselineFile("flatten/drill-2254-result-single.json").build().run();
}
// DRILL-2254 supplementary
@Test
public void testMultiFlattenFromNestedRepeatedList() throws Exception {
final String query = "select t.uid, flatten(flatten(t.odd)) odd from cp.`project/complex/a.json` t";
testBuilder().sqlQuery(query).unOrdered().jsonBaselineFile("flatten/drill-2254-result-multi.json").build().run();
}
// DRILL-2254 supplementary
@Test
public void testSingleMultiFlattenFromNestedRepeatedList() throws Exception {
final String query = "select t.uid, flatten(t.odd) once, flatten(flatten(t.odd)) twice from cp.`project/complex/a.json` t";
testBuilder().sqlQuery(query).unOrdered().jsonBaselineFile("flatten/drill-2254-result-mix.json").build().run();
}
@Test
public void testDrill_2013() throws Exception {
testBuilder().sqlQuery("select flatten(complex), rownum from cp.`/store/json/test_flatten_mappify2.json` where rownum > 5").expectsEmptyResultSet().build().run();
}
@Test
public void testDRILL_2106() throws Exception {
testBuilder().sqlQuery("select rl, flatten(rl) frl from (select `integer`, flatten(rl) as rl from cp.`jsoninput/input2.json`)").unOrdered().jsonBaselineFile("flatten/drill-2106-result.json").go();
testBuilder().sqlQuery("select rl, flatten(rl) frl from (select flatten(rl) as rl, `integer` from cp.`jsoninput/input2.json`)").unOrdered().jsonBaselineFile("flatten/drill-2106-result.json").go();
}
// see DRILL-2146
@Test
public void testFalttenWithStar() throws Exception {
String root = FileUtils.getResourceAsFile("/store/text/sample.json").toURI().toString();
String q1 = String.format("select *, flatten(j.topping) tt, flatten(j.batters.batter) bb, j.id " + "from dfs_test.`%s` j " + "where j.type = 'donut'", root);
String q2 = String.format("select *, flatten(j.topping) tt, flatten(j.batters.batter) bb, j.id, j.type " + "from dfs_test.`%s` j " + "where j.type = 'donut'", root);
test(q1);
test(q2);
}
// see DRILL-2012
@Test
public void testMultipleFalttenWithWhereClause() throws Exception {
String root = FileUtils.getResourceAsFile("/store/text/sample.json").toURI().toString();
String q1 = String.format("select flatten(j.topping) tt " + "from dfs_test.`%s` j " + "where j.type = 'donut'", root);
String q2 = String.format("select j.type, flatten(j.topping) tt " + "from dfs_test.`%s` j " + "where j.type = 'donut'", root);
test(q1);
test(q2);
}
// DRILL-2099
@Test
public void testFlattenAfterSort() throws Exception {
String query = "select flatten(s1.rms.rptd) rptds from " + "(select d.uid uid, flatten(d.map.rm) rms from cp.`jsoninput/flatten_post_sort.json` d order by d.uid) s1";
testBuilder().sqlQuery(query).unOrdered().jsonBaselineFile("flatten/drill-2099-result.json").go();
}
// DRILL-2268
@Test
public void testFlattenAfterJoin1() throws Exception {
String query = "select flatten(sub1.events) flat_events from " + "(select t1.events events from cp.`complex/json/flatten_join.json` t1 " + "inner join cp.`complex/json/flatten_join.json` t2 on t1.id=t2.id) sub1";
testBuilder().sqlQuery(query).unOrdered().jsonBaselineFile("complex/drill-2268-1-result.json").go();
}
// DRILL-2268
@Test
public void testFlattenAfterJoin2() throws Exception {
String query = "select flatten(t1.events) flat_events from cp.`complex/json/flatten_join.json` t1 " + "inner join cp.`complex/json/flatten_join.json` t2 on t1.id=t2.id";
testBuilder().sqlQuery(query).unOrdered().jsonBaselineFile("complex/drill-2268-2-result.json").go();
}
// DRILL-2268
@Test
public void testFlattenAfterJoin3() throws Exception {
String query = "select flatten(sub1.lst_lst) flat_lst_lst from " + "(select t1.lst_lst lst_lst from cp.`complex/json/flatten_join.json` t1 " + "inner join cp.`complex/json/flatten_join.json` t2 on t1.id=t2.id) sub1";
testBuilder().sqlQuery(query).unOrdered().jsonBaselineFile("complex/drill-2268-3-result.json").go();
}
@Test
public void testFlattenWithScalarFunc() throws Exception {
final String query = "select flatten(t.l) + 1 as c1 from cp.`/jsoninput/input2.json` t";
testBuilder().sqlQuery(query).unOrdered().baselineColumns("c1").baselineValues(5L).baselineValues(3L).baselineValues(5L).baselineValues(3L).baselineValues(5L).baselineValues(3L).go();
}
@Test
public void testFlattenOnEmptyArrayAndNestedMap() throws Exception {
File path = new File(BaseTestQuery.getTempDir("json/input"));
try {
path.mkdirs();
String pathString = path.toPath().toString();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path, "empty_arrays.json")))) {
writer.write("{\"a\" : {\"a1\" : \"a1\"}, \"b\" : [1]}\n");
for (int i = 0; i < JSONRecordReader.DEFAULT_ROWS_PER_BATCH; i++) {
writer.write("{\"a\" : {\"a1\" : \"a1\"}, \"b\" : [], \"c\" : 1}\n");
}
writer.write("{\"a\" : {\"a1\" : \"a1\"}, \"b\" : [1], \"c\" : 1}");
}
String query = "select typeof(t1.a.a1) as col from " + "(select t.*, flatten(t.b) as b from dfs_test.`%s/empty_arrays.json` t where t.c is not null) t1";
testBuilder().sqlQuery(query, pathString).unOrdered().baselineColumns("col").baselineValues("VARCHAR").go();
} finally {
deleteQuietly(path);
}
}
}
19
Source : TestConstantFolding.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
public clreplaced TestConstantFolding extends PlanTestBase {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
// This should run as a @BeforeClreplaced, but these methods must be defined static.
// Unfortunately, the temporary folder with an @Rule annotation cannot be static, this issue
// has been fixed in a newer version of JUnit
// http://stackoverflow.com/questions/2722358/junit-rule-temporaryfolder
public static clreplaced SmallFileCreator {
private final TemporaryFolder folder;
private static final List<String> values = Lists.newArrayList("1", "2", "3");
private static final String jsonRecord = "{\"col1\" : 1,\"col2\" : 2, \"col3\" : 3}";
private String record;
public SmallFileCreator(TemporaryFolder folder) {
this.folder = folder;
this.record = null;
}
public SmallFileCreator setRecord(String record) {
this.record = record;
return this;
}
public void createFiles(int smallFileLines, int bigFileLines, String extension, String delimiter) throws Exception {
if (record == null) {
if (extension.equals("csv") || extension.equals("tsv")) {
record = Joiner.on(delimiter).join(values);
} else if (extension.equals("json")) {
record = jsonRecord;
} else {
throw new UnsupportedOperationException(String.format("Extension %s not supported by %s", extension, SmallFileCreator.clreplaced.getSimpleName()));
}
}
PrintWriter out;
for (String fileAndFolderName : new String[] { "bigfile", "BIGFILE_2" }) {
File bigFolder = folder.newFolder(fileAndFolderName);
File bigFile = new File(bigFolder, fileAndFolderName + "." + extension);
out = new PrintWriter(bigFile);
for (int i = 0; i < bigFileLines; i++) {
out.println(record);
}
out.close();
}
for (String fileAndFolderName : new String[] { "smallfile", "SMALLFILE_2" }) {
File smallFolder = folder.newFolder(fileAndFolderName);
File smallFile = new File(smallFolder, fileAndFolderName + "." + extension);
out = new PrintWriter(smallFile);
for (int i = 0; i < smallFileLines; i++) {
out.println(record);
}
out.close();
}
}
public void createFiles(int smallFileLines, int bigFileLines, String extension) throws Exception {
String delimiter;
if (extension.equals("json")) {
delimiter = null;
} else if (extension.equals("csv")) {
delimiter = ",";
} else if (extension.equals("tsv")) {
delimiter = "\t";
} else {
throw new UnsupportedOperationException("Extension not recognized, please explicitly provide a delimiter.");
}
createFiles(smallFileLines, bigFileLines, extension, delimiter);
}
public void createFiles(int smallFileLines, int bigFileLines) throws Exception {
createFiles(smallFileLines, bigFileLines, "csv", ",");
}
}
@Test
public void testConstantFolding_allTypes() throws Exception {
try {
test("alter session set `store.json.all_text_mode` = true;");
test(String.format("alter session set `%s` = true", PlannerSettings.ENABLE_DECIMAL_DATA_TYPE_KEY));
String query2 = "SELECT * " + "FROM cp.`/parquet/alltypes.json` " + "WHERE 12 = extract(day from (to_timestamp('2014-02-12 03:18:31:07 AM', 'YYYY-MM-dd HH:mm:ss:SS a'))) " + "AND cast( `int_col` AS int) = castint('1') " + "AND cast( `bigint_col` AS bigint) = castbigint('100000000000') " + "AND cast( `decimal9_col` AS decimal(9, 4)) = 1.0 + 0.0 " + "AND cast( `decimal18_col` AS decimal(18,9)) = 123456789.000000000 + 0.0 " + "AND cast( `decimal28sparse_col` AS decimal(28, 14)) = 123456789.000000000 + 0.0 " + "AND cast( `decimal38sparse_col` AS decimal(38, 19)) = 123456789.000000000 + 0.0 " + "AND cast( `date_col` AS date) = cast('1995-01-01' as date) " + "AND cast( `date_col` AS date) = castdate('1995-01-01') " + "AND cast( `date_col` AS date) = DATE '1995-01-01' " + "AND cast( `timestamp_col` AS timestamp) = casttimestamp('1995-01-01 01:00:10.000') " + "AND cast( `float4_col` AS float) = castfloat4('1') " + "AND cast( `float8_col` AS DOUBLE) = castfloat8('1') " + "AND cast( `varbinary_col` AS varbinary(65000)) = castvarbinary('qwerty', 0) " + "AND cast( `intervalyear_col` AS interval year) = castintervalyear('P1Y') " + "AND cast( `intervalday_col` AS interval day) = castintervalday('P1D')" + "AND cast( `bit_col` AS boolean) = castbit('false') " + "AND `varchar_col` = concat('qwe','rty') " + "AND cast( `time_col` AS time) = casttime('01:00:00') " + "";
testBuilder().sqlQuery(query2).ordered().baselineColumns("TINYINT_col", "SMALLINT_col", "INT_col", "FLOAT4_col", "TIME_col", "DECIMAL9_col", "BIGINT_col", "UINT8_col", "FLOAT8_col", "DATE_col", "TIMESTAMP_col", "DECIMAL18_col", "INTERVALYEAR_col", "INTERVALDAY_col", "INTERVAL_col", "DECIMAL38SPARSE_col", "DECIMAL28SPARSE_col", "VARBINARY_col", "VARCHAR_col", "VAR16CHAR_col", "BIT_col").baselineValues("1", "1", "1", "1", "01:00:00", "1.0", "100000000000", "1", "1", "1995-01-01", "1995-01-01 01:00:10.000", "123456789.000000000", "P1Y", "P1D", "P1Y1M1DT1H1M", "123456789.000000000", "123456789.000000000", "qwerty", "qwerty", "qwerty", "false").go();
} finally {
test("alter session set `store.json.all_text_mode` = false;");
test(String.format("alter session set `%s` = false", PlannerSettings.ENABLE_DECIMAL_DATA_TYPE_KEY));
}
}
@Ignore("DRILL-2553")
@Test
public void testConstExprFolding_withParreplacedionPrune_verySmallFiles() throws Exception {
new SmallFileCreator(folder).createFiles(1, 8);
String path = folder.getRoot().toPath().toString();
testPlanOneExpectedPatternOneExcluded("select * from dfs.`" + path + "/*/*.csv` where dir0 = concat('small','file')", "smallfile", "bigfile");
}
@Test
public void testConstExprFolding_withParreplacedionPrune() throws Exception {
new SmallFileCreator(folder).createFiles(1, 1000);
String path = folder.getRoot().toPath().toString();
testPlanOneExpectedPatternOneExcluded("select * from dfs.`" + path + "/*/*.csv` where dir0 = concat('small','file')", "smallfile", "bigfile");
}
@Test
public void testConstExprFolding_nonDirFilter() throws Exception {
testPlanOneExpectedPatternOneExcluded("select * from cp.`functions/interp/test_input.csv` where columns[0] = 2+2", "Filter\\(condition=\\[=\\(ITEM\\(\\$[0-9]+, 0\\), 4\\)", "Filter\\(condition=\\[=\\(ITEM\\(\\$[0-9]+, 0\\), \\+\\(2, 2\\)\\)");
}
@Test
public void testConstantFoldingDisableOption() throws Exception {
try {
test("alter session set `planner.enable_constant_folding` = false");
testPlanOneExpectedPatternOneExcluded("select * from cp.`functions/interp/test_input.csv` where columns[0] = 2+2", "Filter\\(condition=\\[=\\(ITEM\\(\\$[0-9]+, 0\\), \\+\\(2, 2\\)\\)", "Filter\\(condition=\\[=\\(ITEM\\(\\$[0-9]+, 0\\), 4\\)");
} finally {
test("alter session set `planner.enable_constant_folding` = true");
}
}
@Test
public void testConstExprFolding_moreComplicatedNonDirFilter() throws Exception {
testPlanOneExpectedPatternOneExcluded("select * from cp.`functions/interp/test_input.csv` where columns[1] = ABS((6-18)/(2*3))", "Filter\\(condition=\\[=\\(ITEM\\(\\$[0-9]+, 1\\), 2\\)", "Filter\\(condition=\\[=\\(ITEM\\(\\$[0-9]+, 1\\), ABS\\(/\\(-\\(6, 18\\), \\*\\(2, 3\\)\\)\\)\\)");
}
@Test
public void testConstExprFolding_dontFoldRandom() throws Exception {
testPlanOneExpectedPatternOneExcluded("select * from cp.`functions/interp/test_input.csv` where columns[0] = random()", "Filter\\(condition=\\[=\\(ITEM\\(\\$[0-9]+, 0\\), RANDOM\\(\\)", "Filter\\(condition=\\[=\\(ITEM\\(\\$[0-9]+, 0\\), [0-9\\.]+");
}
@Test
public void testConstExprFolding_ToLimit0() throws Exception {
testPlanOneExpectedPatternOneExcluded("select * from cp.`functions/interp/test_input.csv` where 1=0", "Limit\\(offset=\\[0\\], fetch=\\[0\\]\\)", "Filter\\(condition=\\[=\\(1, 0\\)\\]\\)");
}
// Despite a comment indicating that the plan generated by the ReduceExpressionRule
// should be set to be always preferable to the input rel, I cannot get it to
// produce a plan with the reduced result. I can trace through where the rule is fired
// and I can see that the expression is being evaluated and the constant is being
// added to a project, but this is not part of the final plan selected. May
// need to open a calcite bug.
// Tried to disable the calc and filter rules, only leave the project one, didn't help.
@Ignore("DRILL-2218")
@Test
public void testConstExprFolding_InSelect() throws Exception {
testPlanOneExcludedPattern("select columns[0], 3+5 from cp.`functions/interp/test_input.csv`", "EXPR\\$[0-9]+=\\[\\+\\(3, 5\\)\\]");
}
}
19
Source : WalletsInTest.java
with MIT License
from zold-io
with MIT License
from zold-io
/**
* Test case for {@link WalletsIn}.
*
* @since 0.1
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle JavadocVariableCheck (500 lines)
*/
public final clreplaced WalletsInTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule
public final TemporaryFolder folder = new TemporaryFolder();
@Test
public void iteratesWallets() {
Matcherreplacedert.replacedertThat(new WalletsIn(Paths.get("src/test/resources/walletsIn")), // @checkstyle MagicNumber (1 line)
new IsIterableWithSize<>(new IsEqual<>(5)));
}
@Test
public void createsWalletInWallets() throws IOException {
final Wallets wallets = new WalletsIn(this.folder.newFolder().toPath());
wallets.create();
Matcherreplacedert.replacedertThat("Can't create wallet in wallets", wallets, new IsIterableWithSize<>(new IsEqual<>(1)));
}
@Test
public void createsWalletInFolder() throws IOException {
final Path path = this.folder.newFolder().toPath();
new WalletsIn(path).create();
Matcherreplacedert.replacedertThat("Can't create wallet in folder", new WalletsIn(path), new IsIterableWithSize<>(new IsEqual<>(1)));
}
@Test(expected = UnsupportedOperationException.clreplaced)
public void createsRightWallet() throws IOException {
final Path path = this.folder.newFolder().toPath();
final String network = "zold";
final String pubkey = "AAAAB3NzaC1yc2EAAAADAQABAAABAQC";
final long id = 1;
final Wallet actual = new WalletsIn(path).create(id, pubkey, network);
final Wallet expected = new Wallet.Fake(id, pubkey, network);
Matcherreplacedert.replacedertThat("Created wallet with different values than expected", actual, new IsEqual<>(expected));
}
@Test
public void doesNotOverwriteExistingWallet() throws Exception {
final Path path = this.folder.newFolder().toPath();
final Random random = new FkRandom(16725L);
new WalletsIn(path, random).create();
this.thrown.expect(IOException.clreplaced);
this.thrown.expectMessage("already exists");
new WalletsIn(path, random).create();
}
/**
* Fake randomizer that returns the same value each time.
*/
private static clreplaced FkRandom extends Random {
/**
* Serial version.
*/
private static final long serialVersionUID = 2905348968220129619L;
/**
* Value that represents a random number.
*/
private final long value;
/**
* Ctor.
* @param val Value that represents a random number.
*/
FkRandom(final long val) {
super();
this.value = val;
}
@Override
public long nextLong() {
return this.value;
}
}
}
19
Source : UnixResolverDnsServerAddressStreamProviderTest.java
with Apache License 2.0
from zhisheng17
with Apache License 2.0
from zhisheng17
public clreplaced UnixResolverDnsServerAddressStreamProviderTest {
@Rule
public final TemporaryFolder folder = new TemporaryFolder();
@Test
public void defaultLookupShouldReturnResultsIfOnlySingleFileSpecified() throws Exception {
File f = buildFile("domain linecorp.local\n" + "nameserver 127.0.0.2\n" + "nameserver 127.0.0.3\n");
UnixResolverDnsServerAddressStreamProvider p = new UnixResolverDnsServerAddressStreamProvider(f, null);
DnsServerAddressStream stream = p.nameServerAddressStream("somehost");
replacedertHostNameEquals("127.0.0.2", stream.next());
replacedertHostNameEquals("127.0.0.3", stream.next());
}
@Test
public void defaultReturnedWhenNoBetterMatch() throws Exception {
File f = buildFile("domain linecorp.local\n" + "nameserver 127.0.0.2\n" + "nameserver 127.0.0.3\n");
File f2 = buildFile("domain squarecorp.local\n" + "nameserver 127.0.0.4\n" + "nameserver 127.0.0.5\n");
UnixResolverDnsServerAddressStreamProvider p = new UnixResolverDnsServerAddressStreamProvider(f, f2);
DnsServerAddressStream stream = p.nameServerAddressStream("somehost");
replacedertHostNameEquals("127.0.0.2", stream.next());
replacedertHostNameEquals("127.0.0.3", stream.next());
}
@Test
public void moreRefinedSelectionReturnedWhenMatch() throws Exception {
File f = buildFile("domain linecorp.local\n" + "nameserver 127.0.0.2\n" + "nameserver 127.0.0.3\n");
File f2 = buildFile("domain dc1.linecorp.local\n" + "nameserver 127.0.0.4\n" + "nameserver 127.0.0.5\n");
UnixResolverDnsServerAddressStreamProvider p = new UnixResolverDnsServerAddressStreamProvider(f, f2);
DnsServerAddressStream stream = p.nameServerAddressStream("myhost.dc1.linecorp.local");
replacedertHostNameEquals("127.0.0.4", stream.next());
replacedertHostNameEquals("127.0.0.5", stream.next());
}
@Test
public void ndotsIsParsedIfPresent() throws IOException {
File f = buildFile("search localdomain\n" + "nameserver 127.0.0.11\n" + "options ndots:0\n");
replacedertEquals(0, parseEtcResolverFirstNdots(f));
f = buildFile("search localdomain\n" + "nameserver 127.0.0.11\n" + "options ndots:123 foo:goo\n");
replacedertEquals(123, parseEtcResolverFirstNdots(f));
}
@Test
public void defaultValueReturnedIfNdotsNotPresent() throws IOException {
File f = buildFile("search localdomain\n" + "nameserver 127.0.0.11\n");
replacedertEquals(DEFAULT_NDOTS, parseEtcResolverFirstNdots(f));
}
@Test
public void emptyEtcResolverDirectoryDoesNotThrow() throws IOException {
File f = buildFile("domain linecorp.local\n" + "nameserver 127.0.0.2\n" + "nameserver 127.0.0.3\n");
UnixResolverDnsServerAddressStreamProvider p = new UnixResolverDnsServerAddressStreamProvider(f, folder.newFolder().listFiles());
DnsServerAddressStream stream = p.nameServerAddressStream("somehost");
replacedertHostNameEquals("127.0.0.2", stream.next());
}
private File buildFile(String contents) throws IOException {
File f = folder.newFile();
OutputStream out = new FileOutputStream(f);
try {
out.write(contents.getBytes(CharsetUtil.UTF_8));
} finally {
out.close();
}
return f;
}
private static void replacedertHostNameEquals(String expectedHostname, InetSocketAddress next) {
replacedertEquals("unexpected hostname: " + next, expectedHostname, next.getHostString());
}
}
19
Source : PromiseNotifierTest.java
with Apache License 2.0
from zhisheng17
with Apache License 2.0
from zhisheng17
public clreplaced PromiseNotifierTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testNullPromisesArray() {
expectedException.expect(NullPointerException.clreplaced);
new PromiseNotifier<Void, Future<Void>>((Promise<Void>[]) null);
}
@SuppressWarnings("unchecked")
@Test
public void testNullPromiseInArray() {
expectedException.expect(IllegalArgumentException.clreplaced);
new PromiseNotifier<Void, Future<Void>>((Promise<Void>) null);
}
@Test
public void testListenerSuccess() throws Exception {
@SuppressWarnings("unchecked")
Promise<Void> p1 = mock(Promise.clreplaced);
@SuppressWarnings("unchecked")
Promise<Void> p2 = mock(Promise.clreplaced);
@SuppressWarnings("unchecked")
PromiseNotifier<Void, Future<Void>> notifier = new PromiseNotifier<Void, Future<Void>>(p1, p2);
@SuppressWarnings("unchecked")
Future<Void> future = mock(Future.clreplaced);
when(future.isSuccess()).thenReturn(true);
when(future.get()).thenReturn(null);
when(p1.trySuccess(null)).thenReturn(true);
when(p2.trySuccess(null)).thenReturn(true);
notifier.operationComplete(future);
verify(p1).trySuccess(null);
verify(p2).trySuccess(null);
}
@Test
public void testListenerFailure() throws Exception {
@SuppressWarnings("unchecked")
Promise<Void> p1 = mock(Promise.clreplaced);
@SuppressWarnings("unchecked")
Promise<Void> p2 = mock(Promise.clreplaced);
@SuppressWarnings("unchecked")
PromiseNotifier<Void, Future<Void>> notifier = new PromiseNotifier<Void, Future<Void>>(p1, p2);
@SuppressWarnings("unchecked")
Future<Void> future = mock(Future.clreplaced);
Throwable t = mock(Throwable.clreplaced);
when(future.isSuccess()).thenReturn(false);
when(future.isCancelled()).thenReturn(false);
when(future.cause()).thenReturn(t);
when(p1.tryFailure(t)).thenReturn(true);
when(p2.tryFailure(t)).thenReturn(true);
notifier.operationComplete(future);
verify(p1).tryFailure(t);
verify(p2).tryFailure(t);
}
}
19
Source : PromiseAggregatorTest.java
with Apache License 2.0
from zhisheng17
with Apache License 2.0
from zhisheng17
public clreplaced PromiseAggregatorTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testNullAggregatePromise() {
expectedException.expect(NullPointerException.clreplaced);
new PromiseAggregator<Void, Future<Void>>(null);
}
@Test
public void testAddNullFuture() {
@SuppressWarnings("unchecked")
Promise<Void> p = mock(Promise.clreplaced);
PromiseAggregator<Void, Future<Void>> a = new PromiseAggregator<Void, Future<Void>>(p);
expectedException.expect(NullPointerException.clreplaced);
a.add((Promise<Void>[]) null);
}
@SuppressWarnings("unchecked")
@Test
public void testSuccessfulNoPending() throws Exception {
Promise<Void> p = mock(Promise.clreplaced);
PromiseAggregator<Void, Future<Void>> a = new PromiseAggregator<Void, Future<Void>>(p);
Future<Void> future = mock(Future.clreplaced);
when(p.setSuccess(null)).thenReturn(p);
a.add();
a.operationComplete(future);
verifyNoMoreInteractions(future);
verify(p).setSuccess(null);
}
@SuppressWarnings("unchecked")
@Test
public void testSuccessfulPending() throws Exception {
Promise<Void> p = mock(Promise.clreplaced);
PromiseAggregator<Void, Future<Void>> a = new PromiseAggregator<Void, Future<Void>>(p);
Promise<Void> p1 = mock(Promise.clreplaced);
Promise<Void> p2 = mock(Promise.clreplaced);
when(p1.addListener(a)).thenReturn(p1);
when(p2.addListener(a)).thenReturn(p2);
when(p1.isSuccess()).thenReturn(true);
when(p2.isSuccess()).thenReturn(true);
when(p.setSuccess(null)).thenReturn(p);
replacedertThat(a.add(p1, null, p2), is(a));
a.operationComplete(p1);
a.operationComplete(p2);
verify(p1).addListener(a);
verify(p2).addListener(a);
verify(p1).isSuccess();
verify(p2).isSuccess();
verify(p).setSuccess(null);
}
@SuppressWarnings("unchecked")
@Test
public void testFailedFutureFailPending() throws Exception {
Promise<Void> p = mock(Promise.clreplaced);
PromiseAggregator<Void, Future<Void>> a = new PromiseAggregator<Void, Future<Void>>(p);
Promise<Void> p1 = mock(Promise.clreplaced);
Promise<Void> p2 = mock(Promise.clreplaced);
Throwable t = mock(Throwable.clreplaced);
when(p1.addListener(a)).thenReturn(p1);
when(p2.addListener(a)).thenReturn(p2);
when(p1.isSuccess()).thenReturn(false);
when(p1.cause()).thenReturn(t);
when(p.setFailure(t)).thenReturn(p);
when(p2.setFailure(t)).thenReturn(p2);
a.add(p1, p2);
a.operationComplete(p1);
verify(p1).addListener(a);
verify(p2).addListener(a);
verify(p1).cause();
verify(p).setFailure(t);
verify(p2).setFailure(t);
}
@SuppressWarnings("unchecked")
@Test
public void testFailedFutureNoFailPending() throws Exception {
Promise<Void> p = mock(Promise.clreplaced);
PromiseAggregator<Void, Future<Void>> a = new PromiseAggregator<Void, Future<Void>>(p, false);
Promise<Void> p1 = mock(Promise.clreplaced);
Promise<Void> p2 = mock(Promise.clreplaced);
Throwable t = mock(Throwable.clreplaced);
when(p1.addListener(a)).thenReturn(p1);
when(p2.addListener(a)).thenReturn(p2);
when(p1.isSuccess()).thenReturn(false);
when(p1.cause()).thenReturn(t);
when(p.setFailure(t)).thenReturn(p);
a.add(p1, p2);
a.operationComplete(p1);
verify(p1).addListener(a);
verify(p2).addListener(a);
verify(p1).isSuccess();
verify(p1).cause();
verify(p).setFailure(t);
}
}
19
Source : DnsResponseTest.java
with Apache License 2.0
from zhisheng17
with Apache License 2.0
from zhisheng17
public clreplaced DnsResponseTest {
private static final byte[][] packets = { { 0, 1, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3, 99, 111, 109, 0, 0, 1, 0, 1, -64, 12, 0, 1, 0, 1, 0, 0, 16, -113, 0, 4, -64, 0, 43, 10 }, { 0, 1, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3, 99, 111, 109, 0, 0, 28, 0, 1, -64, 12, 0, 28, 0, 1, 0, 0, 69, -8, 0, 16, 32, 1, 5, 0, 0, -120, 2, 0, 0, 0, 0, 0, 0, 0, 0, 16 }, { 0, 2, -127, -128, 0, 1, 0, 0, 0, 1, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3, 99, 111, 109, 0, 0, 15, 0, 1, -64, 16, 0, 6, 0, 1, 0, 0, 3, -43, 0, 45, 3, 115, 110, 115, 3, 100, 110, 115, 5, 105, 99, 97, 110, 110, 3, 111, 114, 103, 0, 3, 110, 111, 99, -64, 49, 119, -4, 39, 112, 0, 0, 28, 32, 0, 0, 14, 16, 0, 18, 117, 0, 0, 0, 14, 16 }, { 0, 3, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3, 99, 111, 109, 0, 0, 16, 0, 1, -64, 12, 0, 16, 0, 1, 0, 0, 84, 75, 0, 12, 11, 118, 61, 115, 112, 102, 49, 32, 45, 97, 108, 108 }, { -105, 19, -127, 0, 0, 1, 0, 0, 0, 13, 0, 0, 2, 104, 112, 11, 116, 105, 109, 98, 111, 117, 100, 114, 101, 97, 117, 3, 111, 114, 103, 0, 0, 1, 0, 1, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 20, 1, 68, 12, 82, 79, 79, 84, 45, 83, 69, 82, 86, 69, 82, 83, 3, 78, 69, 84, 0, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 70, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 69, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 75, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 67, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 76, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 71, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 73, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 66, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 77, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 65, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 72, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 74, -64, 49 } };
private static final byte[] malformedLoopPacket = { 0, 4, -127, -128, 0, 1, 0, 0, 0, 0, 0, 0, -64, 12, 0, 1, 0, 1 };
@Test
public void readResponseTest() throws Exception {
EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
for (byte[] p : packets) {
ByteBuf packet = embedder.alloc().buffer(512).writeBytes(p);
embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
AddressedEnvelope<DnsResponse, InetSocketAddress> envelope = embedder.readInbound();
replacedertThat(envelope, is(instanceOf(DatagramDnsResponse.clreplaced)));
DnsResponse response = envelope.content();
replacedertThat(response, is(sameInstance((Object) envelope)));
ByteBuf raw = Unpooled.wrappedBuffer(p);
replacedertThat(response.id(), is(raw.getUnsignedShort(0)));
replacedertThat(response.count(DnsSection.QUESTION), is(raw.getUnsignedShort(4)));
replacedertThat(response.count(DnsSection.ANSWER), is(raw.getUnsignedShort(6)));
replacedertThat(response.count(DnsSection.AUTHORITY), is(raw.getUnsignedShort(8)));
replacedertThat(response.count(DnsSection.ADDITIONAL), is(raw.getUnsignedShort(10)));
envelope.release();
}
}
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void readMalformedResponseTest() throws Exception {
EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
ByteBuf packet = embedder.alloc().buffer(512).writeBytes(malformedLoopPacket);
exception.expect(CorruptedFrameException.clreplaced);
embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
}
}
19
Source : EmbeddedJmsRuleStandardSetupTest.java
with Apache License 2.0
from zapodot
with Apache License 2.0
from zapodot
public clreplaced EmbeddedJmsRuleStandardSetupTest implements SendReceivable {
private static final String TEST_QUEUE = "test.queue";
private static final String TEST_MESSAGE = "Test message";
@Rule
public EmbeddedJmsRule embeddedJmsRule = EmbeddedJmsRule.builder().build();
@Test
public void connectionFactory() throws Exception {
final ConnectionFactory connectionFactory = embeddedJmsRule.connectionFactory();
replacedertThat(connectionFactory, notNullValue(ConnectionFactory.clreplaced));
}
@Test
public void connectAndSendAndReceive() throws Exception {
final ConnectionFactory connectionFactory = embeddedJmsRule.connectionFactory();
replacedertThat(sendReceive(connectionFactory, TEST_QUEUE, TEST_MESSAGE), equalTo(TEST_MESSAGE));
}
@Test
public void usingUri() throws Exception {
final ActiveMQConnectionFactory mqConnectionFactory = new ActiveMQConnectionFactory(embeddedJmsRule.brokerUri());
final Connection connection = mqConnectionFactory.createConnection();
connection.start();
try {
final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
try {
final Queue queue = session.createQueue(TEST_QUEUE);
final MessageProducer producer = session.createProducer(queue);
final QueueBrowser queueBrowser = session.createBrowser(queue);
try {
final String text = "Fire and forget";
final TextMessage textMessage = session.createTextMessage(text);
producer.send(textMessage);
replacedertThat(((TextMessage) queueBrowser.getEnumeration().nextElement()).getText(), equalTo(text));
} finally {
queueBrowser.close();
producer.close();
}
} finally {
session.close();
}
} finally {
connection.close();
}
}
}
19
Source : EmbeddedJmsRuleSpringJmsTest.java
with Apache License 2.0
from zapodot
with Apache License 2.0
from zapodot
public clreplaced EmbeddedJmsRuleSpringJmsTest {
private static final String TEST_MESSAGE = "Test message";
@Rule
public EmbeddedJmsRule embeddedJmsRule = EmbeddedJmsRule.builder().build();
@Test
public void jmsOperation() throws Exception {
final JmsOperations jmsOperations = createSpringJmsOperation();
final ExecutorService executorService = Executors.newFixedThreadPool(1);
try {
final Future<String> messageFuture = executorService.submit(receiveMessage(jmsOperations));
jmsOperations.convertAndSend(TEST_MESSAGE);
final String message = messageFuture.get(30L, TimeUnit.SECONDS);
replacedertThat(message, CoreMatchers.equalTo(TEST_MESSAGE));
} finally {
executorService.shutdownNow();
}
}
private JmsOperations createSpringJmsOperation() {
final JmsTemplate jmsTemplate = new JmsTemplate(embeddedJmsRule.connectionFactory());
jmsTemplate.setDefaultDestinationName(getClreplaced().getSimpleName());
jmsTemplate.setReceiveTimeout(TimeUnit.SECONDS.toMillis(10L));
jmsTemplate.afterPropertiesSet();
return jmsTemplate;
}
private Callable<String> receiveMessage(final JmsOperations jmsOperations) {
return () -> {
final TextMessage textMessage = (TextMessage) jmsOperations.receive();
try {
return textMessage.getText();
} catch (JMSException e) {
throw new IllegalStateException("Could not receive message", e);
}
};
}
}
19
Source : EmbeddedJmsRuleMarshalEnabledTest.java
with Apache License 2.0
from zapodot
with Apache License 2.0
from zapodot
public clreplaced EmbeddedJmsRuleMarshalEnabledTest implements SendReceivable {
private static final String TEST_QUEUE = EmbeddedJmsRuleMarshalEnabledTest.clreplaced.getSimpleName();
private static final String TEST_MESSAGE = "Test with wire format marshal";
@Rule
public EmbeddedJmsRule embeddedJmsRule = EmbeddedJmsRule.builder().withMarshalEnabled().withName("named").build();
@Test
public void sendAndReceiveUsingWireFormat() throws Exception {
final ConnectionFactory connectionFactory = embeddedJmsRule.connectionFactory();
replacedertEquals(TEST_MESSAGE, sendReceive(connectionFactory, TEST_QUEUE, TEST_MESSAGE));
}
}
19
Source : EmbeddedJmsRuleCamelTest.java
with Apache License 2.0
from zapodot
with Apache License 2.0
from zapodot
public clreplaced EmbeddedJmsRuleCamelTest extends CamelTestSupport {
private static final String MOCK_ENDPOINT_URI = "mock:output";
private static final String JMS_DESTINATION_URI = "activemq:queue:inputQueue";
@Rule
public EmbeddedJmsRule embeddedJmsRule = EmbeddedJmsRule.builder().build();
private ActiveMQComponent activeMQComponent() {
final ActiveMQComponent activeMQComponent = new ActiveMQComponent();
activeMQComponent.setConnectionFactory(embeddedJmsRule.connectionFactory());
return activeMQComponent;
}
@Override
protected JndiRegistry createRegistry() throws Exception {
final JndiRegistry registry = super.createRegistry();
registry.bind("activemq", activeMQComponent());
return registry;
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from(JMS_DESTINATION_URI).id("testRoute").convertBodyTo(String.clreplaced).log(LoggingLevel.INFO, "Received message ${id} with body \"${body}\"").to(MOCK_ENDPOINT_URI);
}
};
}
@Override
public boolean isUseRouteBuilder() {
return true;
}
@Override
protected int getShutdownTimeout() {
return 5;
}
@Test
public void sendAndReceiveUsingCamel() throws Exception {
final String messageBody = "Hello Camel!";
getMockEndpoint(MOCK_ENDPOINT_URI).expectedBodiesReceived(messageBody);
template.sendBody(JMS_DESTINATION_URI, messageBody);
replacedertMockEndpointsSatisfied();
}
}
19
Source : SampleSpringXmlApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
public clreplaced SampleSpringXmlApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() throws Exception {
SampleSpringXmlApplication.main(new String[0]);
String output = this.outputCapture.toString();
replacedertThat(output).contains("Hello World");
}
}
19
Source : SampleSimpleApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link SampleSimpleApplication}.
*
* @author Dave Syer
* @author Phillip Webb
*/
public clreplaced SampleSimpleApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
private String profiles;
@Before
public void init() {
this.profiles = System.getProperty("spring.profiles.active");
}
@After
public void after() {
if (this.profiles != null) {
System.setProperty("spring.profiles.active", this.profiles);
} else {
System.clearProperty("spring.profiles.active");
}
}
@Test
public void testDefaultSettings() throws Exception {
SampleSimpleApplication.main(new String[0]);
String output = this.outputCapture.toString();
replacedertThat(output).contains("Hello Phil");
}
@Test
public void testCommandLineOverrides() throws Exception {
SampleSimpleApplication.main(new String[] { "--name=Gordon", "--duration=1m" });
String output = this.outputCapture.toString();
replacedertThat(output).contains("Hello Gordon for 60 seconds");
}
}
19
Source : SampleQuartzApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link SampleQuartzApplication}.
*
* @author Eddú Meléndez
*/
public clreplaced SampleQuartzApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void quartzJobIsTriggered() throws InterruptedException {
try (ConfigurableApplicationContext context = SpringApplication.run(SampleQuartzApplication.clreplaced)) {
long end = System.currentTimeMillis() + 5000;
while ((!this.outputCapture.toString().contains("Hello World!")) && System.currentTimeMillis() < end) {
Thread.sleep(100);
}
replacedertThat(this.outputCapture.toString()).contains("Hello World!");
}
}
}
19
Source : SampleProfileApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
public clreplaced SampleProfileApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
private String profiles;
@Before
public void before() {
this.profiles = System.getProperty("spring.profiles.active");
}
@After
public void after() {
if (this.profiles != null) {
System.setProperty("spring.profiles.active", this.profiles);
} else {
System.clearProperty("spring.profiles.active");
}
}
@Test
public void testDefaultProfile() throws Exception {
SampleProfileApplication.main(new String[0]);
String output = this.outputCapture.toString();
replacedertThat(output).contains("Hello Phil");
}
@Test
public void testGoodbyeProfile() throws Exception {
System.setProperty("spring.profiles.active", "goodbye");
SampleProfileApplication.main(new String[0]);
String output = this.outputCapture.toString();
replacedertThat(output).contains("Goodbye Everyone");
}
@Test
public void testGenericProfile() throws Exception {
/*
* This is a profile that requires a new environment property, and one which is
* only overridden in the current working directory. That file also only contains
* partial overrides, and the default application.yml should still supply the
* "name" property.
*/
System.setProperty("spring.profiles.active", "generic");
SampleProfileApplication.main(new String[0]);
String output = this.outputCapture.toString();
replacedertThat(output).contains("Bonjour Phil");
}
@Test
public void testGoodbyeProfileFromCommandline() throws Exception {
SampleProfileApplication.main(new String[] { "--spring.profiles.active=goodbye" });
String output = this.outputCapture.toString();
replacedertThat(output).contains("Goodbye Everyone");
}
}
19
Source : SampleLogbackApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
public clreplaced SampleLogbackApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testLoadedCustomLogbackConfig() throws Exception {
SampleLogbackApplication.main(new String[0]);
this.outputCapture.expect(containsString("Sample Debug Message"));
this.outputCapture.expect(not(containsString("Sample Trace Message")));
}
@Test
public void testProfile() throws Exception {
SampleLogbackApplication.main(new String[] { "--spring.profiles.active=staging" });
this.outputCapture.expect(containsString("Sample Debug Message"));
this.outputCapture.expect(containsString("Sample Trace Message"));
}
}
19
Source : SampleLiquibaseApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
public clreplaced SampleLiquibaseApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() throws Exception {
try {
SampleLiquibaseApplication.main(new String[] { "--server.port=0" });
} catch (IllegalStateException ex) {
if (serverNotRunning(ex)) {
return;
}
}
String output = this.outputCapture.toString();
replacedertThat(output).contains("Successfully acquired change log lock").contains("Creating database history " + "table with name: PUBLIC.DATABASECHANGELOG").contains("Table person created").contains("ChangeSet clreplacedpath:/db/" + "changelog/db.changelog-master.yaml::1::" + "marceloverdijk ran successfully").contains("New row inserted into person").contains("ChangeSet clreplacedpath:/db/changelog/" + "db.changelog-master.yaml::2::" + "marceloverdijk ran successfully").contains("Successfully released change log lock");
}
@SuppressWarnings("serial")
private boolean serverNotRunning(IllegalStateException ex) {
NestedCheckedException nested = new NestedCheckedException("failed", ex) {
};
if (nested.contains(ConnectException.clreplaced)) {
Throwable root = nested.getRootCause();
if (root.getMessage().contains("Connection refused")) {
return true;
}
}
return false;
}
}
19
Source : SampleBitronixApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Basic integration tests for demo application.
*
* @author Phillip Webb
*/
public clreplaced SampleBitronixApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testTransactionRollback() throws Exception {
SampleBitronixApplication.main(new String[] {});
String output = this.outputCapture.toString();
replacedertThat(output).has(substring(1, "---->"));
replacedertThat(output).has(substring(1, "----> josh"));
replacedertThat(output).has(substring(2, "Count is 1"));
replacedertThat(output).has(substring(1, "Simulated error"));
}
@Test
public void testExposesXaAndNonXa() {
ApplicationContext context = SpringApplication.run(SampleBitronixApplication.clreplaced);
Object jmsConnectionFactory = context.getBean("jmsConnectionFactory");
Object xaJmsConnectionFactory = context.getBean("xaJmsConnectionFactory");
Object nonXaJmsConnectionFactory = context.getBean("nonXaJmsConnectionFactory");
replacedertThat(jmsConnectionFactory).isSameAs(xaJmsConnectionFactory);
replacedertThat(jmsConnectionFactory).isInstanceOf(PoolingConnectionFactory.clreplaced);
replacedertThat(nonXaJmsConnectionFactory).isNotInstanceOf(PoolingConnectionFactory.clreplaced);
}
private Condition<String> substring(int times, String substring) {
return new Condition<String>("containing '" + substring + "' " + times + " times") {
@Override
public boolean matches(String value) {
int i = 0;
while (value.contains(substring)) {
int beginIndex = value.indexOf(substring) + substring.length();
value = value.substring(beginIndex);
i++;
}
return i == times;
}
};
}
}
19
Source : SampleAtomikosApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Basic integration tests for demo application.
*
* @author Phillip Webb
*/
public clreplaced SampleAtomikosApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testTransactionRollback() throws Exception {
SampleAtomikosApplication.main(new String[] {});
String output = this.outputCapture.toString();
replacedertThat(output).has(substring(1, "---->"));
replacedertThat(output).has(substring(1, "----> josh"));
replacedertThat(output).has(substring(2, "Count is 1"));
replacedertThat(output).has(substring(1, "Simulated error"));
}
private Condition<String> substring(int times, String substring) {
return new Condition<String>("containing '" + substring + "' " + times + " times") {
@Override
public boolean matches(String value) {
int i = 0;
while (value.contains(substring)) {
int beginIndex = value.indexOf(substring) + substring.length();
value = value.substring(beginIndex);
i++;
}
return i == times;
}
};
}
}
19
Source : SampleJooqApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Integration tests for {@link SampleJooqApplication}.
*/
public clreplaced SampleJooqApplicationTests {
private static final String[] NO_ARGS = {};
@Rule
public OutputCapture out = new OutputCapture();
@Test
public void outputResults() {
SampleJooqApplication.main(NO_ARGS);
replacedertThat(this.out.toString()).contains("jOOQ Fetch 1 Greg Turnquest");
replacedertThat(this.out.toString()).contains("jOOQ Fetch 2 Craig Walls");
replacedertThat(this.out.toString()).contains("jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, " + "Spring Boot in Action : Craig Walls]");
}
}
19
Source : SampleSolrApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
public clreplaced SampleSolrApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() throws Exception {
try {
SampleSolrApplication.main(new String[0]);
} catch (IllegalStateException ex) {
if (serverNotRunning(ex)) {
return;
}
}
String output = this.outputCapture.toString();
replacedertThat(output).contains("name=Sony Playstation");
}
@SuppressWarnings("serial")
private boolean serverNotRunning(IllegalStateException ex) {
NestedCheckedException nested = new NestedCheckedException("failed", ex) {
};
Throwable root = nested.getRootCause();
if (root.getMessage().contains("Connection refused")) {
return true;
}
return false;
}
}
19
Source : SampleRedisApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link SampleRedisApplication}.
*
* @author Dave Syer
*/
public clreplaced SampleRedisApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() {
try {
SampleRedisApplication.main(new String[0]);
} catch (Exception ex) {
if (!redisServerRunning(ex)) {
return;
}
}
String output = this.outputCapture.toString();
replacedertThat(output).contains("Found key spring.boot.redis.test");
}
private boolean redisServerRunning(Throwable ex) {
System.out.println(ex.getMessage());
if (ex instanceof RedisConnectionFailureException) {
return false;
}
return (ex.getCause() == null || redisServerRunning(ex.getCause()));
}
}
19
Source : SampleNeo4jApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link SampleNeo4replacedplication}.
*
* @author Stephane Nicoll
*/
public clreplaced SampleNeo4replacedplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() {
try {
SampleNeo4replacedplication.main(new String[0]);
} catch (Exception ex) {
if (!neo4jServerRunning(ex)) {
return;
}
}
String output = this.outputCapture.toString();
replacedertThat(output).contains("firstName='Alice', lastName='Smith'");
}
private boolean neo4jServerRunning(Throwable ex) {
if (ex instanceof ServiceUnavailableException) {
return false;
}
return (ex.getCause() == null || neo4jServerRunning(ex.getCause()));
}
}
19
Source : SampleCouchbaseApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
public clreplaced SampleCouchbaseApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() {
try {
new SpringApplicationBuilder(SampleCouchbaseApplication.clreplaced).run("--server.port=0");
} catch (RuntimeException ex) {
if (serverNotRunning(ex)) {
return;
}
}
String output = this.outputCapture.toString();
replacedertThat(output).contains("firstName='Alice', lastName='Smith'");
}
private boolean serverNotRunning(RuntimeException ex) {
@SuppressWarnings("serial")
NestedCheckedException nested = new NestedCheckedException("failed", ex) {
};
if (nested.contains(ConnectException.clreplaced)) {
Throwable root = nested.getRootCause();
if (root.getMessage().contains("Connection refused")) {
return true;
}
}
return false;
}
}
19
Source : SampleBatchApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
public clreplaced SampleBatchApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() {
replacedertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.clreplaced))).isEqualTo(0);
String output = this.outputCapture.toString();
replacedertThat(output).contains("completed with the following parameters");
}
}
19
Source : SampleAopApplicationTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link SampleAopApplication}.
*
* @author Dave Syer
* @author Phillip Webb
*/
public clreplaced SampleAopApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
private String profiles;
@Before
public void init() {
this.profiles = System.getProperty("spring.profiles.active");
}
@After
public void after() {
if (this.profiles != null) {
System.setProperty("spring.profiles.active", this.profiles);
} else {
System.clearProperty("spring.profiles.active");
}
}
@Test
public void testDefaultSettings() throws Exception {
SampleAopApplication.main(new String[0]);
String output = this.outputCapture.toString();
replacedertThat(output).contains("Hello Phil");
}
@Test
public void testCommandLineOverrides() throws Exception {
SampleAopApplication.main(new String[] { "--name=Gordon" });
String output = this.outputCapture.toString();
replacedertThat(output).contains("Hello Gordon");
}
}
19
Source : RepackagerTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link Repackager}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public clreplaced RepackagerTests {
private static final Libraries NO_LIBRARIES = (callback) -> {
};
private static final long JAN_1_1980;
private static final long JAN_1_1985;
static {
Calendar calendar = Calendar.getInstance();
calendar.set(1980, 0, 1, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
JAN_1_1980 = calendar.getTime().getTime();
calendar.set(Calendar.YEAR, 1985);
JAN_1_1985 = calendar.getTime().getTime();
}
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private TestJarFile testJarFile;
@Before
public void setup() throws IOException {
this.testJarFile = new TestJarFile(this.temporaryFolder);
}
@Test
public void nullSource() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new Repackager(null));
}
@Test
public void missingSource() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new Repackager(new File("missing")));
}
@Test
public void directorySource() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new Repackager(this.temporaryFolder.getRoot()));
}
@Test
public void specificMainClreplaced() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.setMainClreplaced("a.b.C");
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes().getValue("Main-Clreplaced")).isEqualTo("org.springframework.boot.loader.JarLauncher");
replacedertThat(actualManifest.getMainAttributes().getValue("Start-Clreplaced")).isEqualTo("a.b.C");
replacedertThat(hasLauncherClreplacedes(file)).isTrue();
}
@Test
public void mainClreplacedFromManifest() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
manifest.getMainAttributes().putValue("Main-Clreplaced", "a.b.C");
this.testJarFile.addManifest(manifest);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes().getValue("Main-Clreplaced")).isEqualTo("org.springframework.boot.loader.JarLauncher");
replacedertThat(actualManifest.getMainAttributes().getValue("Start-Clreplaced")).isEqualTo("a.b.C");
replacedertThat(hasLauncherClreplacedes(file)).isTrue();
}
@Test
public void mainClreplacedFound() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes().getValue("Main-Clreplaced")).isEqualTo("org.springframework.boot.loader.JarLauncher");
replacedertThat(actualManifest.getMainAttributes().getValue("Start-Clreplaced")).isEqualTo("a.b.C");
replacedertThat(hasLauncherClreplacedes(file)).isTrue();
}
@Test
public void jarIsOnlyRepackagedOnce() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes().getValue("Main-Clreplaced")).isEqualTo("org.springframework.boot.loader.JarLauncher");
replacedertThat(actualManifest.getMainAttributes().getValue("Start-Clreplaced")).isEqualTo("a.b.C");
replacedertThat(hasLauncherClreplacedes(file)).isTrue();
}
@Test
public void multipleMainClreplacedFound() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/D.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
replacedertThatIllegalStateException().isThrownBy(() -> repackager.repackage(NO_LIBRARIES)).withMessageContaining("Unable to find a single main clreplaced " + "from the following candidates [a.b.C, a.b.D]");
}
@Test
public void noMainClreplaced() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
replacedertThatIllegalStateException().isThrownBy(() -> new Repackager(this.testJarFile.getFile()).repackage(NO_LIBRARIES)).withMessageContaining("Unable to find main clreplaced");
}
@Test
public void noMainClreplacedAndLayoutIsNone() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.setLayout(new Layouts.None());
repackager.repackage(file, NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes().getValue("Main-Clreplaced")).isEqualTo("a.b.C");
replacedertThat(hasLauncherClreplacedes(file)).isFalse();
}
@Test
public void noMainClreplacedAndLayoutIsNoneWithNoMain() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.setLayout(new Layouts.None());
repackager.repackage(file, NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes().getValue("Main-Clreplaced")).isNull();
replacedertThat(hasLauncherClreplacedes(file)).isFalse();
}
@Test
public void sameSourceAndDestinationWithBackup() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
replacedertThat(new File(file.getParent(), file.getName() + ".original")).exists();
replacedertThat(hasLauncherClreplacedes(file)).isTrue();
}
@Test
public void sameSourceAndDestinationWithoutBackup() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.setBackupSource(false);
repackager.repackage(NO_LIBRARIES);
replacedertThat(new File(file.getParent(), file.getName() + ".original")).doesNotExist();
replacedertThat(hasLauncherClreplacedes(file)).isTrue();
}
@Test
public void differentDestination() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("different.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
replacedertThat(new File(source.getParent(), source.getName() + ".original")).doesNotExist();
replacedertThat(hasLauncherClreplacedes(source)).isFalse();
replacedertThat(hasLauncherClreplacedes(dest)).isTrue();
}
@Test
public void nullDestination() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
Repackager repackager = new Repackager(this.testJarFile.getFile());
replacedertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES)).withMessageContaining("Invalid destination");
}
@Test
public void destinationIsDirectory() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
Repackager repackager = new Repackager(this.testJarFile.getFile());
replacedertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(this.temporaryFolder.getRoot(), NO_LIBRARIES)).withMessageContaining("Invalid destination");
}
@Test
public void overwriteDestination() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
Repackager repackager = new Repackager(this.testJarFile.getFile());
File dest = this.temporaryFolder.newFile("dest.jar");
dest.createNewFile();
repackager.repackage(dest, NO_LIBRARIES);
replacedertThat(hasLauncherClreplacedes(dest)).isTrue();
}
@Test
public void nullLibraries() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
replacedertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(file, null)).withMessageContaining("Libraries must not be null");
}
@Test
public void libraries() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
libJar.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced, JAN_1_1985);
File libJarFile = libJar.getFile();
File libJarFileToUnpack = libJar.getFile();
File libNonJarFile = this.temporaryFolder.newFile();
FileCopyUtils.copy(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, libNonJarFile);
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), libJarFileToUnpack);
File file = this.testJarFile.getFile();
libJarFile.setLastModified(JAN_1_1980);
Repackager repackager = new Repackager(file);
repackager.repackage((callback) -> {
callback.library(new Library(libJarFile, LibraryScope.COMPILE));
callback.library(new Library(libJarFileToUnpack, LibraryScope.COMPILE, true));
callback.library(new Library(libNonJarFile, LibraryScope.COMPILE));
});
replacedertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFile.getName())).isTrue();
replacedertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName())).isTrue();
replacedertThat(hasEntry(file, "BOOT-INF/lib/" + libNonJarFile.getName())).isFalse();
JarEntry entry = getEntry(file, "BOOT-INF/lib/" + libJarFile.getName());
replacedertThat(entry.getTime()).isEqualTo(JAN_1_1985);
entry = getEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName());
replacedertThat(entry.getComment()).startsWith("UNPACK:");
replacedertThat(entry.getComment().length()).isEqualTo(47);
}
@Test
public void duplicateLibraries() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
libJar.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File libJarFile = libJar.getFile();
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
replacedertThatIllegalStateException().isThrownBy(() -> repackager.repackage((callback) -> {
callback.library(new Library(libJarFile, LibraryScope.COMPILE, false));
callback.library(new Library(libJarFile, LibraryScope.COMPILE, false));
})).withMessageContaining("Duplicate library");
}
@Test
public void customLayout() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
libJar.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File libJarFile = libJar.getFile();
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
Layout layout = mock(Layout.clreplaced);
LibraryScope scope = mock(LibraryScope.clreplaced);
given(layout.getLauncherClreplacedName()).willReturn("testLauncher");
given(layout.getLibraryDestination(anyString(), eq(scope))).willReturn("test/");
given(layout.getLibraryDestination(anyString(), eq(LibraryScope.COMPILE))).willReturn("test-lib/");
repackager.setLayout(layout);
repackager.repackage((callback) -> callback.library(new Library(libJarFile, scope)));
replacedertThat(hasEntry(file, "test/" + libJarFile.getName())).isTrue();
replacedertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo("test-lib/");
replacedertThat(getManifest(file).getMainAttributes().getValue("Main-Clreplaced")).isEqualTo("testLauncher");
}
@Test
public void customLayoutNoBootLib() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
libJar.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File libJarFile = libJar.getFile();
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
Layout layout = mock(Layout.clreplaced);
LibraryScope scope = mock(LibraryScope.clreplaced);
given(layout.getLauncherClreplacedName()).willReturn("testLauncher");
repackager.setLayout(layout);
repackager.repackage((callback) -> callback.library(new Library(libJarFile, scope)));
replacedertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")).isNull();
replacedertThat(getManifest(file).getMainAttributes().getValue("Main-Clreplaced")).isEqualTo("testLauncher");
}
@Test
public void springBootVersion() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes()).containsKey(new Attributes.Name("Spring-Boot-Version"));
}
@Test
public void executableJarLayoutAttributes() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"), "BOOT-INF/lib/");
replacedertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Clreplacedes"), "BOOT-INF/clreplacedes/");
}
@Test
public void executableWarLayoutAttributes() throws Exception {
this.testJarFile.addClreplaced("WEB-INF/clreplacedes/a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile("war");
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
replacedertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"), "WEB-INF/lib/");
replacedertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Clreplacedes"), "WEB-INF/clreplacedes/");
}
@Test
public void nullCustomLayout() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
Repackager repackager = new Repackager(this.testJarFile.getFile());
replacedertThatIllegalArgumentException().isThrownBy(() -> repackager.setLayout(null)).withMessageContaining("Layout must not be null");
}
@Test
public void dontRecompressZips() throws Exception {
TestJarFile nested = new TestJarFile(this.temporaryFolder);
nested.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File nestedFile = nested.getFile();
this.testJarFile.addFile("test/nested.jar", nestedFile);
this.testJarFile.addClreplaced("A.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage((callback) -> callback.library(new Library(nestedFile, LibraryScope.COMPILE)));
try (JarFile jarFile = new JarFile(file)) {
replacedertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod()).isEqualTo(ZipEntry.STORED);
replacedertThat(jarFile.getEntry("BOOT-INF/clreplacedes/test/nested.jar").getMethod()).isEqualTo(ZipEntry.STORED);
}
}
@Test
public void addLauncherScript() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
Repackager repackager = new Repackager(source);
LaunchScript script = new MockLauncherScript("ABC");
repackager.repackage(dest, NO_LIBRARIES, script);
byte[] bytes = FileCopyUtils.copyToByteArray(dest);
replacedertThat(new String(bytes)).startsWith("ABC");
replacedertThat(hasLauncherClreplacedes(source)).isFalse();
replacedertThat(hasLauncherClreplacedes(dest)).isTrue();
try {
replacedertThat(Files.getPosixFilePermissions(dest.toPath())).contains(PosixFilePermission.OWNER_EXECUTE);
} catch (UnsupportedOperationException ex) {
// Probably running the test on Windows
}
}
@Test
public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() throws Exception {
TestJarFile nested = new TestJarFile(this.temporaryFolder);
nested.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File nestedFile = nested.getFile();
String name = "BOOT-INF/lib/" + nestedFile.getName();
this.testJarFile.addFile(name, nested.getFile());
this.testJarFile.addClreplaced("A.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage((callback) -> callback.library(new Library(nestedFile, LibraryScope.COMPILE, true)));
try (JarFile jarFile = new JarFile(file)) {
replacedertThat(jarFile.getEntry(name).getComment()).startsWith("UNPACK:");
}
}
@Test
public void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception {
TestJarFile nested = new TestJarFile(this.temporaryFolder);
nested.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File nestedFile = nested.getFile();
this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile());
this.testJarFile.addClreplaced("A.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
long sourceLength = nestedFile.length();
repackager.repackage((callback) -> {
nestedFile.delete();
File toZip = RepackagerTests.this.temporaryFolder.newFile();
ZipUtil.packEntry(toZip, nestedFile);
callback.library(new Library(nestedFile, LibraryScope.COMPILE));
});
try (JarFile jarFile = new JarFile(file)) {
replacedertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()).isEqualTo(sourceLength);
}
}
@Test
public void metaInfIndexListIsRemovedFromRepackagedJar() throws Exception {
this.testJarFile.addClreplaced("A.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addFile("META-INF/INDEX.LIST", this.temporaryFolder.newFile("INDEX.LIST"));
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
try (JarFile jarFile = new JarFile(dest)) {
replacedertThat(jarFile.getEntry("META-INF/INDEX.LIST")).isNull();
}
}
@Test
public void customLayoutFactoryWithoutLayout() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File source = this.testJarFile.getFile();
Repackager repackager = new Repackager(source, new TestLayoutFactory());
repackager.repackage(NO_LIBRARIES);
JarFile jarFile = new JarFile(source);
replacedertThat(jarFile.getEntry("test")).isNotNull();
jarFile.close();
}
@Test
public void customLayoutFactoryWithLayout() throws Exception {
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File source = this.testJarFile.getFile();
Repackager repackager = new Repackager(source, new TestLayoutFactory());
repackager.setLayout(new Layouts.Jar());
repackager.repackage(NO_LIBRARIES);
JarFile jarFile = new JarFile(source);
replacedertThat(jarFile.getEntry("test")).isNull();
jarFile.close();
}
@Test
public void metaInfAopXmlIsMovedBeneathBootInfClreplacedesWhenRepackaged() throws Exception {
this.testJarFile.addClreplaced("A.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addFile("META-INF/aop.xml", this.temporaryFolder.newFile("aop.xml"));
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
try (JarFile jarFile = new JarFile(dest)) {
replacedertThat(jarFile.getEntry("META-INF/aop.xml")).isNull();
replacedertThat(jarFile.getEntry("BOOT-INF/clreplacedes/META-INF/aop.xml")).isNotNull();
}
}
@Test
public void allEntriesUseUnixPlatformAndUtf8NameEncoding() throws IOException {
this.testJarFile.addClreplaced("A.clreplaced", ClreplacedWithMainMethod.clreplaced);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
try (ZipFile zip = new ZipFile(dest)) {
Enumeration<ZipArchiveEntry> entries = zip.getEntries();
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
replacedertThat(entry.getPlatform()).isEqualTo(ZipArchiveEntry.PLATFORM_UNIX);
replacedertThat(entry.getGeneralPurposeBit().usesUTF8ForNames()).isTrue();
}
}
}
@Test
public void loaderIsWrittenFirstThenApplicationClreplacedesThenLibraries() throws IOException {
this.testJarFile.addClreplaced("com/example/Application.clreplaced", ClreplacedWithMainMethod.clreplaced);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
File libraryOne = createLibrary();
File libraryTwo = createLibrary();
File libraryThree = createLibrary();
Repackager repackager = new Repackager(source);
repackager.repackage(dest, (callback) -> {
callback.library(new Library(libraryOne, LibraryScope.COMPILE, false));
callback.library(new Library(libraryTwo, LibraryScope.COMPILE, true));
callback.library(new Library(libraryThree, LibraryScope.COMPILE, false));
});
replacedertThat(getEntryNames(dest)).containsSubsequence("org/springframework/boot/loader/", "BOOT-INF/clreplacedes/com/example/Application.clreplaced", "BOOT-INF/lib/" + libraryOne.getName(), "BOOT-INF/lib/" + libraryTwo.getName(), "BOOT-INF/lib/" + libraryThree.getName());
}
@Test
public void existingEntryThatMatchesUnpackLibraryIsMarkedForUnpack() throws IOException {
File library = createLibrary();
this.testJarFile.addClreplaced("WEB-INF/clreplacedes/com/example/Application.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addFile("WEB-INF/lib/" + library.getName(), library);
File source = this.testJarFile.getFile("war");
File dest = this.temporaryFolder.newFile("dest.war");
Repackager repackager = new Repackager(source);
repackager.setLayout(new Layouts.War());
repackager.repackage(dest, (callback) -> callback.library(new Library(library, LibraryScope.COMPILE, true)));
replacedertThat(getEntryNames(dest)).containsSubsequence("org/springframework/boot/loader/", "WEB-INF/clreplacedes/com/example/Application.clreplaced", "WEB-INF/lib/" + library.getName());
JarEntry unpackLibrary = getEntry(dest, "WEB-INF/lib/" + library.getName());
replacedertThat(unpackLibrary.getComment()).startsWith("UNPACK:");
}
@Test
public void layoutCanOmitLibraries() throws IOException {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
libJar.addClreplaced("a/b/C.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
File libJarFile = libJar.getFile();
this.testJarFile.addClreplaced("a/b/C.clreplaced", ClreplacedWithMainMethod.clreplaced);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
Layout layout = mock(Layout.clreplaced);
LibraryScope scope = mock(LibraryScope.clreplaced);
repackager.setLayout(layout);
repackager.repackage((callback) -> callback.library(new Library(libJarFile, scope)));
replacedertThat(getEntryNames(file)).containsExactly("META-INF/", "META-INF/MANIFEST.MF", "a/", "a/b/", "a/b/C.clreplaced");
}
@Test
public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException {
File source = this.temporaryFolder.newFile("source.jar");
ZipOutputStream output = new ZipOutputStream(new FileOutputStream(source)) {
{
this.def = new Deflater(Deflater.NO_COMPRESSION, true);
}
};
byte[] data = new byte[1024 * 1024];
new Random().nextBytes(data);
ZipEntry entry = new ZipEntry("entry.dat");
output.putNextEntry(entry);
output.write(data);
output.closeEntry();
output.close();
File dest = this.temporaryFolder.newFile("dest.jar");
Repackager repackager = new Repackager(source);
repackager.setMainClreplaced("com.example.Main");
repackager.repackage(dest, NO_LIBRARIES);
}
private File createLibrary() throws IOException {
TestJarFile library = new TestJarFile(this.temporaryFolder);
library.addClreplaced("com/example/library/Library.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
return library.getFile();
}
private boolean hasLauncherClreplacedes(File file) throws IOException {
return hasEntry(file, "org/springframework/boot/") && hasEntry(file, "org/springframework/boot/loader/JarLauncher.clreplaced");
}
private boolean hasEntry(File file, String name) throws IOException {
return getEntry(file, name) != null;
}
private JarEntry getEntry(File file, String name) throws IOException {
try (JarFile jarFile = new JarFile(file)) {
return jarFile.getJarEntry(name);
}
}
private Manifest getManifest(File file) throws IOException {
try (JarFile jarFile = new JarFile(file)) {
return jarFile.getManifest();
}
}
private List<String> getEntryNames(File file) throws IOException {
List<String> entryNames = new ArrayList<>();
try (JarFile jarFile = new JarFile(file)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
entryNames.add(entries.nextElement().getName());
}
}
return entryNames;
}
private static clreplaced MockLauncherScript implements LaunchScript {
private final byte[] bytes;
MockLauncherScript(String script) {
this.bytes = script.getBytes();
}
@Override
public byte[] toByteArray() {
return this.bytes;
}
}
public static clreplaced TestLayoutFactory implements LayoutFactory {
@Override
public Layout getLayout(File source) {
return new TestLayout();
}
}
private static clreplaced TestLayout extends Layouts.Jar implements CustomLoaderLayout {
@Override
public void writeLoadedClreplacedes(LoaderClreplacedesWriter writer) throws IOException {
writer.writeEntry("test", new ByteArrayInputStream("test".getBytes()));
}
}
}
19
Source : MainClassFinderTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link MainClreplacedFinder}.
*
* @author Phillip Webb
*/
public clreplaced MainClreplacedFinderTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private TestJarFile testJarFile;
@Before
public void setup() throws IOException {
this.testJarFile = new TestJarFile(this.temporaryFolder);
}
@Test
public void findMainClreplacedInJar() throws Exception {
this.testJarFile.addClreplaced("B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("A.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
String actual = MainClreplacedFinder.findMainClreplaced(this.testJarFile.getJarFile(), "");
replacedertThat(actual).isEqualTo("B");
}
@Test
public void findMainClreplacedInJarSubFolder() throws Exception {
this.testJarFile.addClreplaced("a/b/c/D.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/F.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
String actual = MainClreplacedFinder.findMainClreplaced(this.testJarFile.getJarFile(), "");
replacedertThat(actual).isEqualTo("a.b.c.D");
}
@Test
public void usesBreadthFirstJarSearch() throws Exception {
this.testJarFile.addClreplaced("a/B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithMainMethod.clreplaced);
String actual = MainClreplacedFinder.findMainClreplaced(this.testJarFile.getJarFile(), "");
replacedertThat(actual).isEqualTo("a.B");
}
@Test
public void findSingleJarSearch() throws Exception {
this.testJarFile.addClreplaced("a/B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithMainMethod.clreplaced);
replacedertThatIllegalStateException().isThrownBy(() -> MainClreplacedFinder.findSingleMainClreplaced(this.testJarFile.getJarFile(), "")).withMessageContaining("Unable to find a single main clreplaced " + "from the following candidates [a.B, a.b.c.E]");
}
@Test
public void findSingleJarSearchPrefersAnnotatedMainClreplaced() throws Exception {
this.testJarFile.addClreplaced("a/B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", AnnotatedClreplacedWithMainMethod.clreplaced);
String mainClreplaced = MainClreplacedFinder.findSingleMainClreplaced(this.testJarFile.getJarFile(), "", "org.springframework.boot.loader.tools.sample.SomeApplication");
replacedertThat(mainClreplaced).isEqualTo("a.b.c.E");
}
@Test
public void findMainClreplacedInJarSubLocation() throws Exception {
this.testJarFile.addClreplaced("a/B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithMainMethod.clreplaced);
String actual = MainClreplacedFinder.findMainClreplaced(this.testJarFile.getJarFile(), "a/");
replacedertThat(actual).isEqualTo("B");
}
@Test
public void findMainClreplacedInFolder() throws Exception {
this.testJarFile.addClreplaced("B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("A.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
String actual = MainClreplacedFinder.findMainClreplaced(this.testJarFile.getJarSource());
replacedertThat(actual).isEqualTo("B");
}
@Test
public void findMainClreplacedInSubFolder() throws Exception {
this.testJarFile.addClreplaced("a/b/c/D.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/F.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
String actual = MainClreplacedFinder.findMainClreplaced(this.testJarFile.getJarSource());
replacedertThat(actual).isEqualTo("a.b.c.D");
}
@Test
public void usesBreadthFirstFolderSearch() throws Exception {
this.testJarFile.addClreplaced("a/B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithMainMethod.clreplaced);
String actual = MainClreplacedFinder.findMainClreplaced(this.testJarFile.getJarSource());
replacedertThat(actual).isEqualTo("a.B");
}
@Test
public void findSingleFolderSearch() throws Exception {
this.testJarFile.addClreplaced("a/B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithMainMethod.clreplaced);
replacedertThatIllegalStateException().isThrownBy(() -> MainClreplacedFinder.findSingleMainClreplaced(this.testJarFile.getJarSource())).withMessageContaining("Unable to find a single main clreplaced " + "from the following candidates [a.B, a.b.c.E]");
}
@Test
public void findSingleFolderSearchPrefersAnnotatedMainClreplaced() throws Exception {
this.testJarFile.addClreplaced("a/B.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", AnnotatedClreplacedWithMainMethod.clreplaced);
String mainClreplaced = MainClreplacedFinder.findSingleMainClreplaced(this.testJarFile.getJarSource(), "org.springframework.boot.loader.tools.sample.SomeApplication");
replacedertThat(mainClreplaced).isEqualTo("a.b.c.E");
}
@Test
public void doWithFolderMainMethods() throws Exception {
this.testJarFile.addClreplaced("a/b/c/D.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/F.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/G.clreplaced", ClreplacedWithMainMethod.clreplaced);
ClreplacedNameCollector callback = new ClreplacedNameCollector();
MainClreplacedFinder.doWithMainClreplacedes(this.testJarFile.getJarSource(), callback);
replacedertThat(callback.getClreplacedNames().toString()).isEqualTo("[a.b.G, a.b.c.D]");
}
@Test
public void doWithJarMainMethods() throws Exception {
this.testJarFile.addClreplaced("a/b/c/D.clreplaced", ClreplacedWithMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/c/E.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/F.clreplaced", ClreplacedWithoutMainMethod.clreplaced);
this.testJarFile.addClreplaced("a/b/G.clreplaced", ClreplacedWithMainMethod.clreplaced);
ClreplacedNameCollector callback = new ClreplacedNameCollector();
MainClreplacedFinder.doWithMainClreplacedes(this.testJarFile.getJarFile(), null, callback);
replacedertThat(callback.getClreplacedNames().toString()).isEqualTo("[a.b.G, a.b.c.D]");
}
private static clreplaced ClreplacedNameCollector implements MainClreplacedCallback<Object> {
private final List<String> clreplacedNames = new ArrayList<>();
@Override
public Object doWith(MainClreplaced mainClreplaced) {
this.clreplacedNames.add(mainClreplaced.getName());
return null;
}
public List<String> getClreplacedNames() {
return this.clreplacedNames;
}
}
}
19
Source : FileUtilsTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link FileUtils}.
*
* @author Dave Syer
* @author Phillip Webb
*/
public clreplaced FileUtilsTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File outputDirectory;
private File originDirectory;
@Before
public void init() {
this.outputDirectory = new File("target/test/remove");
this.originDirectory = new File("target/test/keep");
FileSystemUtils.deleteRecursively(this.outputDirectory);
FileSystemUtils.deleteRecursively(this.originDirectory);
this.outputDirectory.mkdirs();
this.originDirectory.mkdirs();
}
@Test
public void simpleDuplicateFile() throws IOException {
File file = new File(this.outputDirectory, "logback.xml");
file.createNewFile();
new File(this.originDirectory, "logback.xml").createNewFile();
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory);
replacedertThat(file.exists()).isFalse();
}
@Test
public void nestedDuplicateFile() throws IOException {
replacedertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue();
replacedertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue();
File file = new File(this.outputDirectory, "sub/logback.xml");
file.createNewFile();
new File(this.originDirectory, "sub/logback.xml").createNewFile();
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory);
replacedertThat(file.exists()).isFalse();
}
@Test
public void nestedNonDuplicateFile() throws IOException {
replacedertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue();
replacedertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue();
File file = new File(this.outputDirectory, "sub/logback.xml");
file.createNewFile();
new File(this.originDirectory, "sub/different.xml").createNewFile();
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory);
replacedertThat(file.exists()).isTrue();
}
@Test
public void nonDuplicateFile() throws IOException {
File file = new File(this.outputDirectory, "logback.xml");
file.createNewFile();
new File(this.originDirectory, "different.xml").createNewFile();
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory);
replacedertThat(file.exists()).isTrue();
}
@Test
public void hash() throws Exception {
File file = this.temporaryFolder.newFile();
try (OutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(new byte[] { 1, 2, 3 });
}
replacedertThat(FileUtils.sha1Hash(file)).isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf");
}
}
19
Source : DefaultLaunchScriptTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link DefaultLaunchScript}.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @author Justin Rosenberg
*/
public clreplaced DefaultLaunchScriptTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void loadsDefaultScript() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray());
replacedertThat(content).contains("Spring Boot Startup Script");
}
@Test
public void logFilenameCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("logFilename");
}
@Test
public void pidFilenameCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("pidFilename");
}
@Test
public void initInfoProvidesCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("initInfoProvides");
}
@Test
public void initInfoRequiredStartCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("initInfoRequiredStart");
}
@Test
public void initInfoRequiredStopCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("initInfoRequiredStop");
}
@Test
public void initInfoDefaultStartCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("initInfoDefaultStart");
}
@Test
public void initInfoDefaultStopCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("initInfoDefaultStop");
}
@Test
public void initInfoShortDescriptionCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("initInfoShortDescription");
}
@Test
public void initInfoDescriptionCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("initInfoDescription");
}
@Test
public void initInfoChkconfigCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("initInfoChkconfig");
}
@Test
public void modeCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("mode");
}
@Test
public void useStartStopDaemonCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("useStartStopDaemon");
}
@Test
public void logFolderCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("logFolder");
}
@Test
public void pidFolderCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("pidFolder");
}
@Test
public void confFolderCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("confFolder");
}
@Test
public void stopWaitTimeCanBeReplaced() throws Exception {
replacedertThatPlaceholderCanBeReplaced("stopWaitTime");
}
@Test
public void inlinedConfScriptFileLoad() throws IOException {
DefaultLaunchScript script = new DefaultLaunchScript(null, createProperties("inlinedConfScript:src/test/resources/example.script"));
String content = new String(script.toByteArray());
replacedertThat(content).contains("FOO=BAR");
}
@Test
public void defaultForUseStartStopDaemonIsTrue() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray());
replacedertThat(content).contains("USE_START_STOP_DAEMON=\"true\"");
}
@Test
public void defaultForModeIsAuto() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray());
replacedertThat(content).contains("MODE=\"auto\"");
}
@Test
public void defaultForStopWaitTimeIs60() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray());
replacedertThat(content).contains("STOP_WAIT_TIME=\"60\"");
}
@Test
public void loadFromFile() throws Exception {
File file = this.temporaryFolder.newFile();
FileCopyUtils.copy("ABC".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray());
replacedertThat(content).isEqualTo("ABC");
}
@Test
public void expandVariables() throws Exception {
File file = this.temporaryFolder.newFile();
FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o"));
String content = new String(script.toByteArray());
replacedertThat(content).isEqualTo("hello");
}
@Test
public void expandVariablesMultiLine() throws Exception {
File file = this.temporaryFolder.newFile();
FileCopyUtils.copy("h{{a}}l\nl{{b}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o"));
String content = new String(script.toByteArray());
replacedertThat(content).isEqualTo("hel\nlo");
}
@Test
public void expandVariablesWithDefaults() throws Exception {
File file = this.temporaryFolder.newFile();
FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray());
replacedertThat(content).isEqualTo("hello");
}
@Test
public void expandVariablesCanDefaultToBlank() throws Exception {
File file = this.temporaryFolder.newFile();
FileCopyUtils.copy("s{{p:}}{{r:}}ing".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray());
replacedertThat(content).isEqualTo("sing");
}
@Test
public void expandVariablesWithDefaultsOverride() throws Exception {
File file = this.temporaryFolder.newFile();
FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:a"));
String content = new String(script.toByteArray());
replacedertThat(content).isEqualTo("hallo");
}
@Test
public void expandVariablesMissingAreUnchanged() throws Exception {
File file = this.temporaryFolder.newFile();
FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray());
replacedertThat(content).isEqualTo("h{{a}}ll{{b}}");
}
private void replacedertThatPlaceholderCanBeReplaced(String placeholder) throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, createProperties(placeholder + ":__test__"));
String content = new String(script.toByteArray());
replacedertThat(content).contains("__test__");
}
private Map<?, ?> createProperties(String... pairs) {
Map<Object, Object> properties = new HashMap<>();
for (String pair : pairs) {
String[] keyValue = pair.split(":");
properties.put(keyValue[0], keyValue[1]);
}
return properties;
}
}
19
Source : JarURLConnectionTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link JarURLConnection}.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Rostyslav Dudka
*/
public clreplaced JarURLConnectionTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target"));
private File rootJarFile;
private JarFile jarFile;
@Before
public void setup() throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
TestJarCreator.createTestJar(this.rootJarFile);
this.jarFile = new JarFile(this.rootJarFile);
}
@Test
public void connectionToRootUsingAbsoluteUrl() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/");
replacedertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile);
}
@Test
public void connectionToRootUsingRelativeUrl() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/");
replacedertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile);
}
@Test
public void connectionToEntryUsingAbsoluteUrl() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat");
replacedertThat(JarURLConnection.get(url, this.jarFile).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingRelativeUrl() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/1.dat");
replacedertThat(JarURLConnection.get(url, this.jarFile).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() throws Exception {
URL url = new URL("jar:file:/" + getAbsolutePath() + "!/1.dat");
replacedertThat(JarURLConnection.get(url, this.jarFile).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlForNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat");
replacedertThat(JarURLConnection.get(url, this.jarFile).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingRelativeUrlForNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat");
replacedertThat(JarURLConnection.get(url, this.jarFile).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat");
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
replacedertThat(JarURLConnection.get(url, nested).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat");
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
replacedertThat(JarURLConnection.get(url, nested).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() throws Exception {
URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
replacedertThat(JarURLConnection.get(url, nested).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryWithSpaceNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/space nested.jar!/3.dat");
replacedertThat(JarURLConnection.get(url, this.jarFile).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat");
replacedertThat(JarURLConnection.get(url, this.jarFile).getInputStream()).hreplacedameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/w.jar!/3.dat");
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
replacedertThatExceptionOfType(FileNotFoundException.clreplaced).isThrownBy(JarURLConnection.get(url, nested)::getInputStream);
}
@Test
public void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception {
URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
replacedertThat(url.openConnection().getContentLength()).isEqualTo(1);
}
@Test
public void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception {
URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
replacedertThat(url.openConnection().getContentLengthLong()).isEqualTo(1);
}
@Test
public void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat");
JarURLConnection connection = JarURLConnection.get(url, this.jarFile);
replacedertThat(connection.getLastModified()).isEqualTo(connection.getJarEntry().getTime());
}
@Test
public void jarEntryBasicName() {
replacedertThat(new JarEntryName(new StringSequence("a/b/C.clreplaced")).toString()).isEqualTo("a/b/C.clreplaced");
}
@Test
public void jarEntryNameWithSingleByteEncodedCharacters() {
replacedertThat(new JarEntryName(new StringSequence("%61/%62/%43.clreplaced")).toString()).isEqualTo("a/b/C.clreplaced");
}
@Test
public void jarEntryNameWithDoubleByteEncodedCharacters() {
replacedertThat(new JarEntryName(new StringSequence("%c3%a1/b/C.clreplaced")).toString()).isEqualTo("\u00e1/b/C.clreplaced");
}
@Test
public void jarEntryNameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() {
replacedertThat(new JarEntryName(new StringSequence("%c3%a1/b/\u00c7.clreplaced")).toString()).isEqualTo("\u00e1/b/\u00c7.clreplaced");
}
private String getAbsolutePath() {
return this.rootJarFile.getAbsolutePath().replace('\\', '/');
}
private String getRelativePath() {
return this.rootJarFile.getPath().replace('\\', '/');
}
}
19
Source : JarFileTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link JarFile}.
*
* @author Phillip Webb
* @author Martin Lau
* @author Andy Wilkinson
*/
public clreplaced JarFileTests {
private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs";
private static final String HANDLERS_PACKAGE = "org.springframework.boot.loader";
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File rootJarFile;
private JarFile jarFile;
@Before
public void setup() throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
TestJarCreator.createTestJar(this.rootJarFile);
this.jarFile = new JarFile(this.rootJarFile);
}
@Test
public void jdkJarFile() throws Exception {
// Sanity checks to see how the default jar file operates
java.util.jar.JarFile jarFile = new java.util.jar.JarFile(this.rootJarFile);
Enumeration<java.util.jar.JarEntry> entries = jarFile.entries();
replacedertThat(entries.nextElement().getName()).isEqualTo("META-INF/");
replacedertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF");
replacedertThat(entries.nextElement().getName()).isEqualTo("1.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("2.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("d/");
replacedertThat(entries.nextElement().getName()).isEqualTo("d/9.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("special/");
replacedertThat(entries.nextElement().getName()).isEqualTo("special/\u00EB.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("nested.jar");
replacedertThat(entries.nextElement().getName()).isEqualTo("another-nested.jar");
replacedertThat(entries.nextElement().getName()).isEqualTo("space nested.jar");
replacedertThat(entries.hasMoreElements()).isFalse();
URL jarUrl = new URL("jar:" + this.rootJarFile.toURI() + "!/");
URLClreplacedLoader urlClreplacedLoader = new URLClreplacedLoader(new URL[] { jarUrl });
replacedertThat(urlClreplacedLoader.getResource("special/\u00EB.dat")).isNotNull();
replacedertThat(urlClreplacedLoader.getResource("d/9.dat")).isNotNull();
jarFile.close();
urlClreplacedLoader.close();
}
@Test
public void createFromFile() throws Exception {
JarFile jarFile = new JarFile(this.rootJarFile);
replacedertThat(jarFile.getName()).isNotNull();
jarFile.close();
}
@Test
public void getManifest() throws Exception {
replacedertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1");
}
@Test
public void getManifestEntry() throws Exception {
ZipEntry entry = this.jarFile.getJarEntry("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(this.jarFile.getInputStream(entry));
replacedertThat(manifest.getMainAttributes().getValue("Built-By")).isEqualTo("j1");
}
@Test
public void getEntries() {
Enumeration<java.util.jar.JarEntry> entries = this.jarFile.entries();
replacedertThat(entries.nextElement().getName()).isEqualTo("META-INF/");
replacedertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF");
replacedertThat(entries.nextElement().getName()).isEqualTo("1.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("2.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("d/");
replacedertThat(entries.nextElement().getName()).isEqualTo("d/9.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("special/");
replacedertThat(entries.nextElement().getName()).isEqualTo("special/\u00EB.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("nested.jar");
replacedertThat(entries.nextElement().getName()).isEqualTo("another-nested.jar");
replacedertThat(entries.nextElement().getName()).isEqualTo("space nested.jar");
replacedertThat(entries.hasMoreElements()).isFalse();
}
@Test
public void getSpecialResourceViaClreplacedLoader() throws Exception {
URLClreplacedLoader urlClreplacedLoader = new URLClreplacedLoader(new URL[] { this.jarFile.getUrl() });
replacedertThat(urlClreplacedLoader.getResource("special/\u00EB.dat")).isNotNull();
urlClreplacedLoader.close();
}
@Test
public void getJarEntry() {
java.util.jar.JarEntry entry = this.jarFile.getJarEntry("1.dat");
replacedertThat(entry).isNotNull();
replacedertThat(entry.getName()).isEqualTo("1.dat");
}
@Test
public void getInputStream() throws Exception {
InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("1.dat"));
replacedertThat(inputStream.available()).isEqualTo(1);
replacedertThat(inputStream.read()).isEqualTo(1);
replacedertThat(inputStream.available()).isEqualTo(0);
replacedertThat(inputStream.read()).isEqualTo(-1);
}
@Test
public void getName() {
replacedertThat(this.jarFile.getName()).isEqualTo(this.rootJarFile.getPath());
}
@Test
public void getSize() throws Exception {
try (ZipFile zip = new ZipFile(this.rootJarFile)) {
replacedertThat(this.jarFile.size()).isEqualTo(zip.size());
}
}
@Test
public void getEntryTime() throws Exception {
java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile);
replacedertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime()).isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime());
jdkJarFile.close();
}
@Test
public void close() throws Exception {
RandomAccessDataFile randomAccessDataFile = spy(new RandomAccessDataFile(this.rootJarFile));
JarFile jarFile = new JarFile(randomAccessDataFile);
jarFile.close();
verify(randomAccessDataFile).close();
}
@Test
public void getUrl() throws Exception {
URL url = this.jarFile.getUrl();
replacedertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/");
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
replacedertThat(jarURLConnection.getJarFile()).isSameAs(this.jarFile);
replacedertThat(jarURLConnection.getJarEntry()).isNull();
replacedertThat(jarURLConnection.getContentLength()).isGreaterThan(1);
replacedertThat(jarURLConnection.getContent()).isSameAs(this.jarFile);
replacedertThat(jarURLConnection.getContentType()).isEqualTo("x-java/jar");
replacedertThat(jarURLConnection.getJarFileURL().toURI()).isEqualTo(this.rootJarFile.toURI());
}
@Test
public void createEntryUrl() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "1.dat");
replacedertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat");
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
replacedertThat(jarURLConnection.getJarFile()).isSameAs(this.jarFile);
replacedertThat(jarURLConnection.getJarEntry()).isSameAs(this.jarFile.getJarEntry("1.dat"));
replacedertThat(jarURLConnection.getContentLength()).isEqualTo(1);
replacedertThat(jarURLConnection.getContent()).isInstanceOf(InputStream.clreplaced);
replacedertThat(jarURLConnection.getContentType()).isEqualTo("content/unknown");
replacedertThat(jarURLConnection.getPermission()).isInstanceOf(FilePermission.clreplaced);
FilePermission permission = (FilePermission) jarURLConnection.getPermission();
replacedertThat(permission.getActions()).isEqualTo("read");
replacedertThat(permission.getName()).isEqualTo(this.rootJarFile.getPath());
}
@Test
public void getMissingEntryUrl() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "missing.dat");
replacedertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat");
replacedertThatExceptionOfType(FileNotFoundException.clreplaced).isThrownBy(((JarURLConnection) url.openConnection())::getJarEntry);
}
@Test
public void getUrlStream() throws Exception {
URL url = this.jarFile.getUrl();
url.openConnection();
replacedertThatIOException().isThrownBy(url::openStream);
}
@Test
public void getEntryUrlStream() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "1.dat");
url.openConnection();
InputStream stream = url.openStream();
replacedertThat(stream.read()).isEqualTo(1);
replacedertThat(stream.read()).isEqualTo(-1);
}
@Test
public void getNestedJarFile() throws Exception {
JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries();
replacedertThat(entries.nextElement().getName()).isEqualTo("META-INF/");
replacedertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF");
replacedertThat(entries.nextElement().getName()).isEqualTo("3.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("4.dat");
replacedertThat(entries.nextElement().getName()).isEqualTo("\u00E4.dat");
replacedertThat(entries.hasMoreElements()).isFalse();
InputStream inputStream = nestedJarFile.getInputStream(nestedJarFile.getEntry("3.dat"));
replacedertThat(inputStream.read()).isEqualTo(3);
replacedertThat(inputStream.read()).isEqualTo(-1);
URL url = nestedJarFile.getUrl();
replacedertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/");
JarURLConnection conn = (JarURLConnection) url.openConnection();
replacedertThat(conn.getJarFile()).isSameAs(nestedJarFile);
replacedertThat(conn.getJarFileURL().toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar");
replacedertThat(conn.getInputStream()).isNotNull();
JarInputStream jarInputStream = new JarInputStream(conn.getInputStream());
replacedertThat(jarInputStream.getNextJarEntry().getName()).isEqualTo("3.dat");
replacedertThat(jarInputStream.getNextJarEntry().getName()).isEqualTo("4.dat");
replacedertThat(jarInputStream.getNextJarEntry().getName()).isEqualTo("\u00E4.dat");
jarInputStream.close();
replacedertThat(conn.getPermission()).isInstanceOf(FilePermission.clreplaced);
FilePermission permission = (FilePermission) conn.getPermission();
replacedertThat(permission.getActions()).isEqualTo("read");
replacedertThat(permission.getName()).isEqualTo(this.rootJarFile.getPath());
}
@Test
public void getNestedJarDirectory() throws Exception {
JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("d/"));
Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries();
replacedertThat(entries.nextElement().getName()).isEqualTo("9.dat");
replacedertThat(entries.hasMoreElements()).isFalse();
InputStream inputStream = nestedJarFile.getInputStream(nestedJarFile.getEntry("9.dat"));
replacedertThat(inputStream.read()).isEqualTo(9);
replacedertThat(inputStream.read()).isEqualTo(-1);
URL url = nestedJarFile.getUrl();
replacedertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/d!/");
replacedertThat(((JarURLConnection) url.openConnection()).getJarFile()).isSameAs(nestedJarFile);
}
@Test
public void getNestedJarEntryUrl() throws Exception {
JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
URL url = nestedJarFile.getJarEntry("3.dat").getUrl();
replacedertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat");
InputStream inputStream = url.openStream();
replacedertThat(inputStream).isNotNull();
replacedertThat(inputStream.read()).isEqualTo(3);
}
@Test
public void createUrlFromString() throws Exception {
JarFile.registerUrlProtocolHandler();
String spec = "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat";
URL url = new URL(spec);
replacedertThat(url.toString()).isEqualTo(spec);
InputStream inputStream = url.openStream();
replacedertThat(inputStream).isNotNull();
replacedertThat(inputStream.read()).isEqualTo(3);
JarURLConnection connection = (JarURLConnection) url.openConnection();
replacedertThat(connection.getURL().toString()).isEqualTo(spec);
replacedertThat(connection.getJarFileURL().toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar");
replacedertThat(connection.getEntryName()).isEqualTo("3.dat");
}
@Test
public void createNonNestedUrlFromString() throws Exception {
nonNestedJarFileFromString("jar:" + this.rootJarFile.toURI() + "!/2.dat");
}
@Test
public void createNonNestedUrlFromPathString() throws Exception {
nonNestedJarFileFromString("jar:" + this.rootJarFile.toPath().toUri() + "!/2.dat");
}
private void nonNestedJarFileFromString(String spec) throws Exception {
JarFile.registerUrlProtocolHandler();
URL url = new URL(spec);
replacedertThat(url.toString()).isEqualTo(spec);
InputStream inputStream = url.openStream();
replacedertThat(inputStream).isNotNull();
replacedertThat(inputStream.read()).isEqualTo(2);
JarURLConnection connection = (JarURLConnection) url.openConnection();
replacedertThat(connection.getURL().toString()).isEqualTo(spec);
replacedertThat(connection.getJarFileURL().toURI()).isEqualTo(this.rootJarFile.toURI());
replacedertThat(connection.getEntryName()).isEqualTo("2.dat");
}
@Test
public void getDirectoryInputStream() throws Exception {
InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d/"));
replacedertThat(inputStream).isNotNull();
replacedertThat(inputStream.read()).isEqualTo(-1);
}
@Test
public void getDirectoryInputStreamWithoutSlash() throws Exception {
InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d"));
replacedertThat(inputStream).isNotNull();
replacedertThat(inputStream.read()).isEqualTo(-1);
}
@Test
public void sensibleToString() throws Exception {
replacedertThat(this.jarFile.toString()).isEqualTo(this.rootJarFile.getPath());
replacedertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")).toString()).isEqualTo(this.rootJarFile.getPath() + "!/nested.jar");
}
@Test
public void verifySignedJar() throws Exception {
String clreplacedpath = System.getProperty("java.clreplaced.path");
String[] entries = clreplacedpath.split(System.getProperty("path.separator"));
String signedJarFile = null;
for (String entry : entries) {
if (entry.contains("bcprov")) {
signedJarFile = entry;
}
}
replacedertThat(signedJarFile).isNotNull();
java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile));
jarFile.getManifest();
Enumeration<JarEntry> jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
InputStream inputStream = jarFile.getInputStream(jarEntry);
inputStream.skip(Long.MAX_VALUE);
inputStream.close();
if (!jarEntry.getName().startsWith("META-INF") && !jarEntry.isDirectory() && !jarEntry.getName().endsWith("TigerDigest.clreplaced")) {
replacedertThat(jarEntry.getCertificates()).isNotNull();
}
}
jarFile.close();
}
@Test
public void jarFileWithScriptAtTheStart() throws Exception {
File file = this.temporaryFolder.newFile();
InputStream sourceJarContent = new FileInputStream(this.rootJarFile);
FileOutputStream outputStream = new FileOutputStream(file);
StreamUtils.copy("#/bin/bash", Charset.defaultCharset(), outputStream);
FileCopyUtils.copy(sourceJarContent, outputStream);
this.rootJarFile = file;
this.jarFile = new JarFile(file);
// Call some other tests to verify
getEntries();
getNestedJarFile();
}
@Test
public void cannotLoadMissingJar() throws Exception {
// relates to gh-1070
JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
URL nestedUrl = nestedJarFile.getUrl();
URL url = new URL(nestedUrl, nestedJarFile.getUrl() + "missing.jar!/3.dat");
replacedertThatExceptionOfType(FileNotFoundException.clreplaced).isThrownBy(url.openConnection()::getInputStream);
}
@Test
public void registerUrlProtocolHandlerWithNoExistingRegistration() {
String original = System.getProperty(PROTOCOL_HANDLER);
try {
System.clearProperty(PROTOCOL_HANDLER);
JarFile.registerUrlProtocolHandler();
String protocolHandler = System.getProperty(PROTOCOL_HANDLER);
replacedertThat(protocolHandler).isEqualTo(HANDLERS_PACKAGE);
} finally {
if (original == null) {
System.clearProperty(PROTOCOL_HANDLER);
} else {
System.setProperty(PROTOCOL_HANDLER, original);
}
}
}
@Test
public void registerUrlProtocolHandlerAddsToExistingRegistration() {
String original = System.getProperty(PROTOCOL_HANDLER);
try {
System.setProperty(PROTOCOL_HANDLER, "com.example");
JarFile.registerUrlProtocolHandler();
String protocolHandler = System.getProperty(PROTOCOL_HANDLER);
replacedertThat(protocolHandler).isEqualTo("com.example|" + HANDLERS_PACKAGE);
} finally {
if (original == null) {
System.clearProperty(PROTOCOL_HANDLER);
} else {
System.setProperty(PROTOCOL_HANDLER, original);
}
}
}
@Test
public void jarFileCanBeDeletedOnceItHasBeenClosed() throws Exception {
File temp = this.temporaryFolder.newFile();
TestJarCreator.createTestJar(temp);
JarFile jf = new JarFile(temp);
jf.close();
replacedertThat(temp.delete()).isTrue();
}
@Test
public void createUrlFromStringWithContextWhenNotFound() throws Exception {
// gh-12483
JarURLConnection.setUseFastExceptions(true);
try {
JarFile.registerUrlProtocolHandler();
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
URL context = nested.getUrl();
new URL(context, "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat").openConnection().getInputStream().close();
replacedertThatExceptionOfType(FileNotFoundException.clreplaced).isThrownBy(new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat").openConnection()::getInputStream);
} finally {
JarURLConnection.setUseFastExceptions(false);
}
}
}
19
Source : CentralDirectoryParserTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link CentralDirectoryParser}.
*
* @author Phillip Webb
*/
public clreplaced CentralDirectoryParserTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File jarFile;
private RandomAccessData jarData;
@Before
public void setup() throws Exception {
this.jarFile = this.temporaryFolder.newFile();
TestJarCreator.createTestJar(this.jarFile);
this.jarData = new RandomAccessDataFile(this.jarFile);
}
@Test
public void visitsInOrder() throws Exception {
MockCentralDirectoryVisitor visitor = new MockCentralDirectoryVisitor();
CentralDirectoryParser parser = new CentralDirectoryParser();
parser.addVisitor(visitor);
parser.parse(this.jarData, false);
List<String> invocations = visitor.getInvocations();
replacedertThat(invocations).startsWith("visitStart").endsWith("visitEnd").contains("visitFileHeader");
}
@Test
public void visitRecords() throws Exception {
Collector collector = new Collector();
CentralDirectoryParser parser = new CentralDirectoryParser();
parser.addVisitor(collector);
parser.parse(this.jarData, false);
Iterator<CentralDirectoryFileHeader> headers = collector.getHeaders().iterator();
replacedertThat(headers.next().getName().toString()).isEqualTo("META-INF/");
replacedertThat(headers.next().getName().toString()).isEqualTo("META-INF/MANIFEST.MF");
replacedertThat(headers.next().getName().toString()).isEqualTo("1.dat");
replacedertThat(headers.next().getName().toString()).isEqualTo("2.dat");
replacedertThat(headers.next().getName().toString()).isEqualTo("d/");
replacedertThat(headers.next().getName().toString()).isEqualTo("d/9.dat");
replacedertThat(headers.next().getName().toString()).isEqualTo("special/");
replacedertThat(headers.next().getName().toString()).isEqualTo("special/\u00EB.dat");
replacedertThat(headers.next().getName().toString()).isEqualTo("nested.jar");
replacedertThat(headers.next().getName().toString()).isEqualTo("another-nested.jar");
replacedertThat(headers.next().getName().toString()).isEqualTo("space nested.jar");
replacedertThat(headers.hasNext()).isFalse();
}
private static clreplaced Collector implements CentralDirectoryVisitor {
private List<CentralDirectoryFileHeader> headers = new ArrayList<>();
@Override
public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) {
}
@Override
public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) {
this.headers.add(fileHeader.clone());
}
@Override
public void visitEnd() {
}
public List<CentralDirectoryFileHeader> getHeaders() {
return this.headers;
}
}
private static clreplaced MockCentralDirectoryVisitor implements CentralDirectoryVisitor {
private final List<String> invocations = new ArrayList<>();
@Override
public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) {
this.invocations.add("visitStart");
}
@Override
public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) {
this.invocations.add("visitFileHeader");
}
@Override
public void visitEnd() {
this.invocations.add("visitEnd");
}
public List<String> getInvocations() {
return this.invocations;
}
}
}
19
Source : RandomAccessDataFileTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link RandomAccessDataFile}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public clreplaced RandomAccessDataFileTests {
private static final byte[] BYTES;
static {
BYTES = new byte[256];
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) i;
}
}
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File tempFile;
private RandomAccessDataFile file;
private InputStream inputStream;
@Before
public void setup() throws Exception {
this.tempFile = this.temporaryFolder.newFile();
FileOutputStream outputStream = new FileOutputStream(this.tempFile);
outputStream.write(BYTES);
outputStream.close();
this.file = new RandomAccessDataFile(this.tempFile);
this.inputStream = this.file.getInputStream();
}
@After
public void cleanup() throws Exception {
this.inputStream.close();
this.file.close();
}
@Test
public void fileNotNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(null)).withMessageContaining("File must not be null");
}
@Test
public void fileExists() {
File file = new File("/does/not/exist");
replacedertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(file)).withMessageContaining(String.format("File %s must exist", file.getAbsolutePath()));
}
@Test
public void readWithOffsetAndLengthShouldRead() throws Exception {
byte[] read = this.file.read(2, 3);
replacedertThat(read).isEqualTo(new byte[] { 2, 3, 4 });
}
@Test
public void readWhenOffsetIsBeyondEOFShouldThrowException() throws Exception {
replacedertThatExceptionOfType(IndexOutOfBoundsException.clreplaced).isThrownBy(() -> this.file.read(257, 0));
}
@Test
public void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() throws Exception {
RandomAccessData subsection = this.file.getSubsection(0, 10);
replacedertThatExceptionOfType(IndexOutOfBoundsException.clreplaced).isThrownBy(() -> subsection.read(11, 0));
}
@Test
public void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() throws Exception {
replacedertThatExceptionOfType(EOFException.clreplaced).isThrownBy(() -> this.file.read(256, 1));
}
@Test
public void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() throws Exception {
RandomAccessData subsection = this.file.getSubsection(0, 10);
replacedertThatExceptionOfType(EOFException.clreplaced).isThrownBy(() -> subsection.read(10, 1));
}
@Test
public void inputStreamRead() throws Exception {
for (int i = 0; i <= 255; i++) {
replacedertThat(this.inputStream.read()).isEqualTo(i);
}
}
@Test
public void inputStreamReadNullBytes() throws Exception {
replacedertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null)).withMessage("Bytes must not be null");
}
@Test
public void inputStreamReadNullBytesWithOffset() throws Exception {
replacedertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null, 0, 1)).withMessage("Bytes must not be null");
}
@Test
public void inputStreamReadBytes() throws Exception {
byte[] b = new byte[256];
int amountRead = this.inputStream.read(b);
replacedertThat(b).isEqualTo(BYTES);
replacedertThat(amountRead).isEqualTo(256);
}
@Test
public void inputStreamReadOffsetBytes() throws Exception {
byte[] b = new byte[7];
this.inputStream.skip(1);
int amountRead = this.inputStream.read(b, 2, 3);
replacedertThat(b).isEqualTo(new byte[] { 0, 0, 1, 2, 3, 0, 0 });
replacedertThat(amountRead).isEqualTo(3);
}
@Test
public void inputStreamReadMoreBytesThanAvailable() throws Exception {
byte[] b = new byte[257];
int amountRead = this.inputStream.read(b);
replacedertThat(b).startsWith(BYTES);
replacedertThat(amountRead).isEqualTo(256);
}
@Test
public void inputStreamReadPastEnd() throws Exception {
this.inputStream.skip(255);
replacedertThat(this.inputStream.read()).isEqualTo(0xFF);
replacedertThat(this.inputStream.read()).isEqualTo(-1);
replacedertThat(this.inputStream.read()).isEqualTo(-1);
}
@Test
public void inputStreamReadZeroLength() throws Exception {
byte[] b = new byte[] { 0x0F };
int amountRead = this.inputStream.read(b, 0, 0);
replacedertThat(b).isEqualTo(new byte[] { 0x0F });
replacedertThat(amountRead).isEqualTo(0);
replacedertThat(this.inputStream.read()).isEqualTo(0);
}
@Test
public void inputStreamSkip() throws Exception {
long amountSkipped = this.inputStream.skip(4);
replacedertThat(this.inputStream.read()).isEqualTo(4);
replacedertThat(amountSkipped).isEqualTo(4L);
}
@Test
public void inputStreamSkipMoreThanAvailable() throws Exception {
long amountSkipped = this.inputStream.skip(257);
replacedertThat(this.inputStream.read()).isEqualTo(-1);
replacedertThat(amountSkipped).isEqualTo(256L);
}
@Test
public void inputStreamSkipPastEnd() throws Exception {
this.inputStream.skip(256);
long amountSkipped = this.inputStream.skip(1);
replacedertThat(amountSkipped).isEqualTo(0L);
}
@Test
public void subsectionNegativeOffset() {
replacedertThatExceptionOfType(IndexOutOfBoundsException.clreplaced).isThrownBy(() -> this.file.getSubsection(-1, 1));
}
@Test
public void subsectionNegativeLength() {
replacedertThatExceptionOfType(IndexOutOfBoundsException.clreplaced).isThrownBy(() -> this.file.getSubsection(0, -1));
}
@Test
public void subsectionZeroLength() throws Exception {
RandomAccessData subsection = this.file.getSubsection(0, 0);
replacedertThat(subsection.getInputStream().read()).isEqualTo(-1);
}
@Test
public void subsectionTooBig() {
this.file.getSubsection(0, 256);
replacedertThatExceptionOfType(IndexOutOfBoundsException.clreplaced).isThrownBy(() -> this.file.getSubsection(0, 257));
}
@Test
public void subsectionTooBigWithOffset() {
this.file.getSubsection(1, 255);
replacedertThatExceptionOfType(IndexOutOfBoundsException.clreplaced).isThrownBy(() -> this.file.getSubsection(1, 256));
}
@Test
public void subsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 1);
replacedertThat(subsection.getInputStream().read()).isEqualTo(1);
}
@Test
public void inputStreamReadPastSubsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 2);
InputStream inputStream = subsection.getInputStream();
replacedertThat(inputStream.read()).isEqualTo(1);
replacedertThat(inputStream.read()).isEqualTo(2);
replacedertThat(inputStream.read()).isEqualTo(-1);
}
@Test
public void inputStreamReadBytesPastSubsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 2);
InputStream inputStream = subsection.getInputStream();
byte[] b = new byte[3];
int amountRead = inputStream.read(b);
replacedertThat(b).isEqualTo(new byte[] { 1, 2, 0 });
replacedertThat(amountRead).isEqualTo(2);
}
@Test
public void inputStreamSkipPastSubsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 2);
InputStream inputStream = subsection.getInputStream();
replacedertThat(inputStream.skip(3)).isEqualTo(2L);
replacedertThat(inputStream.read()).isEqualTo(-1);
}
@Test
public void inputStreamSkipNegative() throws Exception {
replacedertThat(this.inputStream.skip(-1)).isEqualTo(0L);
}
@Test
public void getFile() {
replacedertThat(this.file.getFile()).isEqualTo(this.tempFile);
}
@Test
public void concurrentReads() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(20);
List<Future<Boolean>> results = new ArrayList<>();
for (int i = 0; i < 100; i++) {
results.add(executorService.submit(() -> {
InputStream subsectionInputStream = RandomAccessDataFileTests.this.file.getSubsection(0, 256).getInputStream();
byte[] b = new byte[256];
subsectionInputStream.read(b);
return Arrays.equals(b, BYTES);
}));
}
for (Future<Boolean> future : results) {
replacedertThat(future.get()).isTrue();
}
}
}
19
Source : JarFileArchiveTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link JarFileArchive}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public clreplaced JarFileArchiveTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File rootJarFile;
private JarFileArchive archive;
private String rootJarFileUrl;
@Before
public void setup() throws Exception {
setup(false);
}
private void setup(boolean unpackNested) throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
this.rootJarFileUrl = this.rootJarFile.toURI().toString();
TestJarCreator.createTestJar(this.rootJarFile, unpackNested);
this.archive = new JarFileArchive(this.rootJarFile);
}
@Test
public void getManifest() throws Exception {
replacedertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1");
}
@Test
public void getEntries() {
Map<String, Archive.Entry> entries = getEntriesMap(this.archive);
replacedertThat(entries.size()).isEqualTo(11);
}
@Test
public void getUrl() throws Exception {
URL url = this.archive.getUrl();
replacedertThat(url.toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/");
}
@Test
public void getNestedArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry);
replacedertThat(nested.getUrl().toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/");
}
@Test
public void getNestedUnpackedArchive() throws Exception {
setup(true);
Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry);
replacedertThat(nested.getUrl().toString()).startsWith("file:");
replacedertThat(nested.getUrl().toString()).endsWith("/nested.jar");
}
@Test
public void unpackedLocationsAreUniquePerArchive() throws Exception {
setup(true);
Entry entry = getEntriesMap(this.archive).get("nested.jar");
URL firstNested = this.archive.getNestedArchive(entry).getUrl();
setup(true);
entry = getEntriesMap(this.archive).get("nested.jar");
URL secondNested = this.archive.getNestedArchive(entry).getUrl();
replacedertThat(secondNested).isNotEqualTo(firstNested);
}
@Test
public void unpackedLocationsFromSameArchiveShareSameParent() throws Exception {
setup(true);
File nested = new File(this.archive.getNestedArchive(getEntriesMap(this.archive).get("nested.jar")).getUrl().toURI());
File anotherNested = new File(this.archive.getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar")).getUrl().toURI());
replacedertThat(nested.getParent()).isEqualTo(anotherNested.getParent());
}
@Test
public void zip64ArchivesAreHandledGracefully() throws IOException {
File file = this.temporaryFolder.newFile("test.jar");
FileCopyUtils.copy(writeZip64Jar(), file);
replacedertThatIllegalStateException().isThrownBy(() -> new JarFileArchive(file)).withMessageContaining("Zip64 archives are not supported");
}
@Test
public void nestedZip64ArchivesAreHandledGracefully() throws IOException {
File file = this.temporaryFolder.newFile("test.jar");
JarOutputStream output = new JarOutputStream(new FileOutputStream(file));
JarEntry zip64JarEntry = new JarEntry("nested/zip64.jar");
output.putNextEntry(zip64JarEntry);
byte[] zip64JarData = writeZip64Jar();
zip64JarEntry.setSize(zip64JarData.length);
zip64JarEntry.setCompressedSize(zip64JarData.length);
zip64JarEntry.setMethod(ZipEntry.STORED);
CRC32 crc32 = new CRC32();
crc32.update(zip64JarData);
zip64JarEntry.setCrc(crc32.getValue());
output.write(zip64JarData);
output.closeEntry();
output.close();
JarFileArchive jarFileArchive = new JarFileArchive(file);
replacedertThatIllegalStateException().isThrownBy(() -> jarFileArchive.getNestedArchive(getEntriesMap(jarFileArchive).get("nested/zip64.jar"))).withMessageContaining("Failed to get nested archive for entry nested/zip64.jar");
}
private byte[] writeZip64Jar() throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
JarOutputStream jarOutput = new JarOutputStream(bytes);
for (int i = 0; i < 65537; i++) {
jarOutput.putNextEntry(new JarEntry(i + ".dat"));
jarOutput.closeEntry();
}
jarOutput.close();
return bytes.toByteArray();
}
private Map<String, Archive.Entry> getEntriesMap(Archive archive) {
Map<String, Archive.Entry> entries = new HashMap<>();
for (Archive.Entry entry : archive) {
entries.put(entry.getName(), entry);
}
return entries;
}
}
19
Source : ExplodedArchiveTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link ExplodedArchive}.
*
* @author Phillip Webb
* @author Dave Syer
* @author Andy Wilkinson
*/
public clreplaced ExplodedArchiveTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File rootFolder;
private ExplodedArchive archive;
@Before
public void setup() throws Exception {
createArchive();
}
private void createArchive() throws Exception {
createArchive(null);
}
private void createArchive(String folderName) throws Exception {
File file = this.temporaryFolder.newFile();
TestJarCreator.createTestJar(file);
this.rootFolder = (StringUtils.hasText(folderName) ? this.temporaryFolder.newFolder(folderName) : this.temporaryFolder.newFolder());
JarFile jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
File destination = new File(this.rootFolder.getAbsolutePath() + File.separator + entry.getName());
destination.getParentFile().mkdirs();
if (entry.isDirectory()) {
destination.mkdir();
} else {
copy(jarFile.getInputStream(entry), new FileOutputStream(destination));
}
}
this.archive = new ExplodedArchive(this.rootFolder);
jarFile.close();
}
private void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
}
@Test
public void getManifest() throws Exception {
replacedertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1");
}
@Test
public void getEntries() {
Map<String, Archive.Entry> entries = getEntriesMap(this.archive);
replacedertThat(entries.size()).isEqualTo(11);
}
@Test
public void getUrl() throws Exception {
replacedertThat(this.archive.getUrl()).isEqualTo(this.rootFolder.toURI().toURL());
}
@Test
public void getUrlWithSpaceInPath() throws Exception {
createArchive("spaces in the name");
replacedertThat(this.archive.getUrl()).isEqualTo(this.rootFolder.toURI().toURL());
}
@Test
public void getNestedArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry);
replacedertThat(nested.getUrl().toString()).isEqualTo("jar:" + this.rootFolder.toURI() + "nested.jar!/");
}
@Test
public void nestedDirArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("d/");
Archive nested = this.archive.getNestedArchive(entry);
Map<String, Entry> nestedEntries = getEntriesMap(nested);
replacedertThat(nestedEntries.size()).isEqualTo(1);
replacedertThat(nested.getUrl().toString()).isEqualTo("file:" + this.rootFolder.toURI().getPath() + "d/");
}
@Test
public void getNonRecursiveEntriesForRoot() {
ExplodedArchive archive = new ExplodedArchive(new File("/"), false);
Map<String, Archive.Entry> entries = getEntriesMap(archive);
replacedertThat(entries.size()).isGreaterThan(1);
}
@Test
public void getNonRecursiveManifest() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"));
replacedertThat(archive.getManifest()).isNotNull();
Map<String, Archive.Entry> entries = getEntriesMap(archive);
replacedertThat(entries.size()).isEqualTo(4);
}
@Test
public void getNonRecursiveManifestEvenIfNonRecursive() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false);
replacedertThat(archive.getManifest()).isNotNull();
Map<String, Archive.Entry> entries = getEntriesMap(archive);
replacedertThat(entries.size()).isEqualTo(3);
}
@Test
public void getResourcereplacedtream() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"));
replacedertThat(archive.getManifest()).isNotNull();
URLClreplacedLoader loader = new URLClreplacedLoader(new URL[] { archive.getUrl() });
replacedertThat(loader.getResourcereplacedtream("META-INF/spring/application.xml")).isNotNull();
loader.close();
}
@Test
public void getResourcereplacedtreamNonRecursive() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false);
replacedertThat(archive.getManifest()).isNotNull();
URLClreplacedLoader loader = new URLClreplacedLoader(new URL[] { archive.getUrl() });
replacedertThat(loader.getResourcereplacedtream("META-INF/spring/application.xml")).isNotNull();
loader.close();
}
private Map<String, Archive.Entry> getEntriesMap(Archive archive) {
Map<String, Archive.Entry> entries = new HashMap<>();
for (Archive.Entry entry : archive) {
entries.put(entry.getName(), entry);
}
return entries;
}
}
19
Source : AbstractExecutableArchiveLauncherTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Base clreplaced for testing {@link ExecutableArchiveLauncher} implementations.
*
* @author Andy Wilkinson
*/
public abstract clreplaced AbstractExecutableArchiveLauncherTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
protected File createJarArchive(String name, String entryPrefix) throws IOException {
File archive = this.temp.newFile(name);
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(archive));
jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/"));
jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/clreplacedes/"));
jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/lib/"));
JarEntry libFoo = new JarEntry(entryPrefix + "/lib/foo.jar");
libFoo.setMethod(ZipEntry.STORED);
ByteArrayOutputStream fooJarStream = new ByteArrayOutputStream();
new JarOutputStream(fooJarStream).close();
libFoo.setSize(fooJarStream.size());
CRC32 crc32 = new CRC32();
crc32.update(fooJarStream.toByteArray());
libFoo.setCrc(crc32.getValue());
jarOutputStream.putNextEntry(libFoo);
jarOutputStream.write(fooJarStream.toByteArray());
jarOutputStream.close();
return archive;
}
protected File explode(File archive) throws IOException {
File exploded = this.temp.newFolder("exploded");
JarFile jarFile = new JarFile(archive);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
File entryFile = new File(exploded, entry.getName());
if (entry.isDirectory()) {
entryFile.mkdirs();
} else {
FileCopyUtils.copy(jarFile.getInputStream(entry), new FileOutputStream(entryFile));
}
}
jarFile.close();
return exploded;
}
protected Set<URL> getUrls(List<Archive> archives) throws MalformedURLException {
Set<URL> urls = new HashSet<>(archives.size());
for (Archive archive : archives) {
urls.add(archive.getUrl());
}
return urls;
}
}
19
Source : BuildInfoTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link BuildInfo}.
*
* @author Andy Wilkinson
*/
public clreplaced BuildInfoTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void basicExecution() {
Properties properties = buildInfoProperties(createTask(createProject("test")));
replacedertThat(properties).containsKey("build.time");
replacedertThat(properties).containsEntry("build.artifact", "unspecified");
replacedertThat(properties).containsEntry("build.group", "");
replacedertThat(properties).containsEntry("build.name", "test");
replacedertThat(properties).containsEntry("build.version", "unspecified");
}
@Test
public void customArtifactIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setArtifact("custom");
replacedertThat(buildInfoProperties(task)).containsEntry("build.artifact", "custom");
}
@Test
public void projectGroupIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
task.getProject().setGroup("com.example");
replacedertThat(buildInfoProperties(task)).containsEntry("build.group", "com.example");
}
@Test
public void customGroupIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setGroup("com.example");
replacedertThat(buildInfoProperties(task)).containsEntry("build.group", "com.example");
}
@Test
public void customNameIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setName("Example");
replacedertThat(buildInfoProperties(task)).containsEntry("build.name", "Example");
}
@Test
public void projectVersionIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
task.getProject().setVersion("1.2.3");
replacedertThat(buildInfoProperties(task)).containsEntry("build.version", "1.2.3");
}
@Test
public void customVersionIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setVersion("2.3.4");
replacedertThat(buildInfoProperties(task)).containsEntry("build.version", "2.3.4");
}
@Test
public void timeIsSetInProperties() {
BuildInfo task = createTask(createProject("test"));
replacedertThat(buildInfoProperties(task)).containsEntry("build.time", DateTimeFormatter.ISO_INSTANT.format(task.getProperties().getTime()));
}
@Test
public void timeCanBeRemovedFromProperties() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setTime(null);
replacedertThat(buildInfoProperties(task)).doesNotContainKey("build.time");
}
@Test
public void timeCanBeCustomizedInProperties() {
Instant now = Instant.now();
BuildInfo task = createTask(createProject("test"));
task.getProperties().setTime(now);
replacedertThat(buildInfoProperties(task)).containsEntry("build.time", DateTimeFormatter.ISO_INSTANT.format(now));
}
@Test
public void additionalPropertiesAreReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().getAdditional().put("a", "alpha");
task.getProperties().getAdditional().put("b", "bravo");
replacedertThat(buildInfoProperties(task)).containsEntry("build.a", "alpha");
replacedertThat(buildInfoProperties(task)).containsEntry("build.b", "bravo");
}
private Project createProject(String projectName) {
try {
File projectDir = this.temp.newFolder(projectName);
return ProjectBuilder.builder().withProjectDir(projectDir).withName(projectName).build();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private BuildInfo createTask(Project project) {
return project.getTasks().create("testBuildInfo", BuildInfo.clreplaced);
}
private Properties buildInfoProperties(BuildInfo task) {
task.generateBuildProperties();
return buildInfoProperties(new File(task.getDestinationDir(), "build-info.properties"));
}
private Properties buildInfoProperties(File file) {
replacedertThat(file).isFile();
Properties properties = new Properties();
try (FileReader reader = new FileReader(file)) {
properties.load(reader);
return properties;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
19
Source : AbstractFieldValuesProcessorTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Abstract base clreplaced for {@link FieldValuesParser} tests.
*
* @author Phillip Webb
* @author Stephane Nicoll
*/
public abstract clreplaced AbstractFieldValuesProcessorTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
protected abstract FieldValuesParser createProcessor(ProcessingEnvironment env);
@Test
public void getFieldValues() throws Exception {
TestProcessor processor = new TestProcessor();
TestCompiler compiler = new TestCompiler(this.temporaryFolder);
compiler.getTask(FieldValues.clreplaced).call(processor);
Map<String, Object> values = processor.getValues();
replacedertThat(values.get("string")).isEqualTo("1");
replacedertThat(values.get("stringNone")).isNull();
replacedertThat(values.get("stringConst")).isEqualTo("c");
replacedertThat(values.get("bool")).isEqualTo(true);
replacedertThat(values.get("boolNone")).isEqualTo(false);
replacedertThat(values.get("boolConst")).isEqualTo(true);
replacedertThat(values.get("boolObject")).isEqualTo(true);
replacedertThat(values.get("boolObjectNone")).isNull();
replacedertThat(values.get("boolObjectConst")).isEqualTo(true);
replacedertThat(values.get("integer")).isEqualTo(1);
replacedertThat(values.get("integerNone")).isEqualTo(0);
replacedertThat(values.get("integerConst")).isEqualTo(2);
replacedertThat(values.get("integerObject")).isEqualTo(3);
replacedertThat(values.get("integerObjectNone")).isNull();
replacedertThat(values.get("integerObjectConst")).isEqualTo(4);
replacedertThat(values.get("charset")).isEqualTo("US-ASCII");
replacedertThat(values.get("charsetConst")).isEqualTo("UTF-8");
replacedertThat(values.get("mimeType")).isEqualTo("text/html");
replacedertThat(values.get("mimeTypeConst")).isEqualTo("text/plain");
replacedertThat(values.get("object")).isEqualTo(123);
replacedertThat(values.get("objectNone")).isNull();
replacedertThat(values.get("objectConst")).isEqualTo("c");
replacedertThat(values.get("objectInstance")).isNull();
replacedertThat(values.get("stringArray")).isEqualTo(new Object[] { "FOO", "BAR" });
replacedertThat(values.get("stringArrayNone")).isNull();
replacedertThat(values.get("stringEmptyArray")).isEqualTo(new Object[0]);
replacedertThat(values.get("stringArrayConst")).isEqualTo(new Object[] { "OK", "KO" });
replacedertThat(values.get("stringArrayConstElements")).isEqualTo(new Object[] { "c" });
replacedertThat(values.get("integerArray")).isEqualTo(new Object[] { 42, 24 });
replacedertThat(values.get("unknownArray")).isNull();
replacedertThat(values.get("durationNone")).isNull();
replacedertThat(values.get("durationNanos")).isEqualTo("5ns");
replacedertThat(values.get("durationMillis")).isEqualTo("10ms");
replacedertThat(values.get("durationSeconds")).isEqualTo("20s");
replacedertThat(values.get("durationMinutes")).isEqualTo("30m");
replacedertThat(values.get("durationHours")).isEqualTo("40h");
replacedertThat(values.get("durationDays")).isEqualTo("50d");
replacedertThat(values.get("dataSizeNone")).isNull();
replacedertThat(values.get("dataSizeBytes")).isEqualTo("5B");
replacedertThat(values.get("dataSizeKilobytes")).isEqualTo("10KB");
replacedertThat(values.get("dataSizeMegabytes")).isEqualTo("20MB");
replacedertThat(values.get("dataSizeGigabytes")).isEqualTo("30GB");
replacedertThat(values.get("dataSizeTerabytes")).isEqualTo("40TB");
}
@SupportedAnnotationTypes({ "org.springframework.boot.configurationsample.ConfigurationProperties" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
private clreplaced TestProcessor extends AbstractProcessor {
private FieldValuesParser processor;
private Map<String, Object> values = new HashMap<>();
@Override
public synchronized void init(ProcessingEnvironment env) {
this.processor = createProcessor(env);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
if (element instanceof TypeElement) {
try {
this.values.putAll(this.processor.getFieldValues((TypeElement) element));
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
}
}
return false;
}
public Map<String, Object> getValues() {
return this.values;
}
}
}
19
Source : SpringBootDependencyInjectionTestExecutionListenerTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link SpringBootDependencyInjectionTestExecutionListener}.
*
* @author Phillip Webb
*/
public clreplaced SpringBootDependencyInjectionTestExecutionListenerTests {
@Rule
public OutputCapture out = new OutputCapture();
private SpringBootDependencyInjectionTestExecutionListener reportListener = new SpringBootDependencyInjectionTestExecutionListener();
@Test
public void orderShouldBeSameAsDependencyInjectionTestExecutionListener() {
Ordered injectionListener = new DependencyInjectionTestExecutionListener();
replacedertThat(this.reportListener.getOrder()).isEqualTo(injectionListener.getOrder());
}
@Test
public void prepareFailingTestInstanceShouldPrintReport() throws Exception {
TestContext testContext = mock(TestContext.clreplaced);
given(testContext.getTestInstance()).willThrow(new IllegalStateException());
SpringApplication application = new SpringApplication(Config.clreplaced);
application.setWebApplicationType(WebApplicationType.NONE);
ConfigurableApplicationContext applicationContext = application.run();
given(testContext.getApplicationContext()).willReturn(applicationContext);
try {
this.reportListener.prepareTestInstance(testContext);
} catch (IllegalStateException ex) {
// Expected
}
this.out.expect(containsString("CONDITIONS EVALUATION REPORT"));
this.out.expect(containsString("Positive matches"));
this.out.expect(containsString("Negative matches"));
}
@Test
public void originalFailureIsThrownWhenReportGenerationFails() throws Exception {
TestContext testContext = mock(TestContext.clreplaced);
IllegalStateException originalFailure = new IllegalStateException();
given(testContext.getTestInstance()).willThrow(originalFailure);
SpringApplication application = new SpringApplication(Config.clreplaced);
application.setWebApplicationType(WebApplicationType.NONE);
given(testContext.getApplicationContext()).willThrow(new RuntimeException());
replacedertThatIllegalStateException().isThrownBy(() -> this.reportListener.prepareTestInstance(testContext)).isEqualTo(originalFailure);
}
@Configuration
@ImportAutoConfiguration(JacksonAutoConfiguration.clreplaced)
static clreplaced Config {
}
}
19
Source : OutputCaptureTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link OutputCapture}.
*
* @author Roland Weisleder
*/
public clreplaced OutputCaptureTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void toStringShouldReturnAllCapturedOutput() {
System.out.println("Hello World");
replacedertThat(this.outputCapture.toString()).contains("Hello World");
}
@Test
public void reset() {
System.out.println("Hello");
this.outputCapture.reset();
System.out.println("World");
replacedertThat(this.outputCapture.toString()).doesNotContain("Hello").contains("World");
}
}
19
Source : BasicJsonTesterTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link BasicJsonTester}.
*
* @author Phillip Webb
*/
public clreplaced BasicJsonTesterTests {
private static final String JSON = "{\"spring\":[\"boot\",\"framework\"]}";
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private BasicJsonTester json = new BasicJsonTester(getClreplaced());
@Test
public void createWhenResourceLoadClreplacedIsNullShouldThrowException() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new BasicJsonTester(null)).withMessageContaining("ResourceLoadClreplaced must not be null");
}
@Test
public void fromJsonStringShouldReturnJsonContent() {
replacedertThat(this.json.from(JSON)).isEqualToJson("source.json");
}
@Test
public void fromResourceStringShouldReturnJsonContent() {
replacedertThat(this.json.from("source.json")).isEqualToJson(JSON);
}
@Test
public void fromResourceStringWithClreplacedShouldReturnJsonContent() {
replacedertThat(this.json.from("source.json", getClreplaced())).isEqualToJson(JSON);
}
@Test
public void fromByteArrayShouldReturnJsonContent() {
replacedertThat(this.json.from(JSON.getBytes())).isEqualToJson("source.json");
}
@Test
public void fromFileShouldReturnJsonContent() throws Exception {
File file = this.tempFolder.newFile("file.json");
FileCopyUtils.copy(JSON.getBytes(), file);
replacedertThat(this.json.from(file)).isEqualToJson("source.json");
}
@Test
public void fromInputStreamShouldReturnJsonContent() {
InputStream inputStream = new ByteArrayInputStream(JSON.getBytes());
replacedertThat(this.json.from(inputStream)).isEqualToJson("source.json");
}
@Test
public void fromResourceShouldReturnJsonContent() {
Resource resource = new ByteArrayResource(JSON.getBytes());
replacedertThat(this.json.from(resource)).isEqualToJson("source.json");
}
}
19
Source : DevToolsSettingsTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link DevToolsSettings}.
*
* @author Phillip Webb
*/
public clreplaced DevToolsSettingsTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private static final String ROOT = DevToolsSettingsTests.clreplaced.getPackage().getName().replace('.', '/') + "/";
@Test
public void includePatterns() throws Exception {
DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-include.properties");
replacedertThat(settings.isRestartInclude(new URL("file://test/a"))).isTrue();
replacedertThat(settings.isRestartInclude(new URL("file://test/b"))).isTrue();
replacedertThat(settings.isRestartInclude(new URL("file://test/c"))).isFalse();
}
@Test
public void excludePatterns() throws Exception {
DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-exclude.properties");
replacedertThat(settings.isRestartExclude(new URL("file://test/a"))).isTrue();
replacedertThat(settings.isRestartExclude(new URL("file://test/b"))).isTrue();
replacedertThat(settings.isRestartExclude(new URL("file://test/c"))).isFalse();
}
@Test
public void defaultIncludePatterns() throws Exception {
DevToolsSettings settings = DevToolsSettings.get();
replacedertThat(settings.isRestartExclude(makeUrl("spring-boot"))).isTrue();
replacedertThat(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))).isTrue();
replacedertThat(settings.isRestartExclude(makeUrl("spring-boot-actuator"))).isTrue();
replacedertThat(settings.isRestartExclude(makeUrl("spring-boot-starter"))).isTrue();
replacedertThat(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))).isTrue();
}
private URL makeUrl(String name) throws IOException {
File file = this.temporaryFolder.newFolder();
file = new File(file, name);
file = new File(file, "target");
file = new File(file, "clreplacedes");
file.mkdirs();
return file.toURI().toURL();
}
}
19
Source : RestartServerTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link RestartServer}.
*
* @author Phillip Webb
*/
public clreplaced RestartServerTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void sourceFolderUrlFilterMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new RestartServer((SourceFolderUrlFilter) null)).withMessageContaining("SourceFolderUrlFilter must not be null");
}
@Test
public void updateAndRestart() throws Exception {
URL url1 = new URL("file:/proj/module-a.jar!/");
URL url2 = new URL("file:/proj/module-b.jar!/");
URL url3 = new URL("file:/proj/module-c.jar!/");
URL url4 = new URL("file:/proj/module-d.jar!/");
URLClreplacedLoader clreplacedLoaderA = new URLClreplacedLoader(new URL[] { url1, url2 });
URLClreplacedLoader clreplacedLoaderB = new URLClreplacedLoader(new URL[] { url3, url4 }, clreplacedLoaderA);
SourceFolderUrlFilter filter = new DefaultSourceFolderUrlFilter();
MockRestartServer server = new MockRestartServer(filter, clreplacedLoaderB);
ClreplacedLoaderFiles files = new ClreplacedLoaderFiles();
ClreplacedLoaderFile fileA = new ClreplacedLoaderFile(Kind.ADDED, new byte[0]);
ClreplacedLoaderFile fileB = new ClreplacedLoaderFile(Kind.ADDED, new byte[0]);
files.addFile("my/module-a", "ClreplacedA.clreplaced", fileA);
files.addFile("my/module-c", "ClreplacedB.clreplaced", fileB);
server.updateAndRestart(files);
Set<URL> expectedUrls = new LinkedHashSet<>(Arrays.asList(url1, url3));
replacedertThat(server.restartUrls).isEqualTo(expectedUrls);
replacedertThat(server.restartFiles).isEqualTo(files);
}
@Test
public void updateSetsJarLastModified() throws Exception {
long startTime = System.currentTimeMillis();
File folder = this.temp.newFolder();
File jarFile = new File(folder, "module-a.jar");
new FileOutputStream(jarFile).close();
jarFile.setLastModified(0);
URL url = jarFile.toURI().toURL();
URLClreplacedLoader clreplacedLoader = new URLClreplacedLoader(new URL[] { url });
SourceFolderUrlFilter filter = new DefaultSourceFolderUrlFilter();
MockRestartServer server = new MockRestartServer(filter, clreplacedLoader);
ClreplacedLoaderFiles files = new ClreplacedLoaderFiles();
ClreplacedLoaderFile fileA = new ClreplacedLoaderFile(Kind.ADDED, new byte[0]);
files.addFile("my/module-a", "ClreplacedA.clreplaced", fileA);
server.updateAndRestart(files);
replacedertThat(jarFile.lastModified()).isGreaterThan(startTime - 1000);
}
@Test
public void updateReplacesLocalFilesWhenPossible() throws Exception {
// This is critical for Cloud Foundry support where the application is
// run exploded and resources can be found from the servlet root (outside of the
// clreplacedloader)
File folder = this.temp.newFolder();
File clreplacedFile = new File(folder, "ClreplacedA.clreplaced");
FileCopyUtils.copy("abc".getBytes(), clreplacedFile);
URL url = folder.toURI().toURL();
URLClreplacedLoader clreplacedLoader = new URLClreplacedLoader(new URL[] { url });
SourceFolderUrlFilter filter = new DefaultSourceFolderUrlFilter();
MockRestartServer server = new MockRestartServer(filter, clreplacedLoader);
ClreplacedLoaderFiles files = new ClreplacedLoaderFiles();
ClreplacedLoaderFile fileA = new ClreplacedLoaderFile(Kind.ADDED, "def".getBytes());
files.addFile("my/module-a", "ClreplacedA.clreplaced", fileA);
server.updateAndRestart(files);
replacedertThat(FileCopyUtils.copyToByteArray(clreplacedFile)).isEqualTo("def".getBytes());
}
private static clreplaced MockRestartServer extends RestartServer {
MockRestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, ClreplacedLoader clreplacedLoader) {
super(sourceFolderUrlFilter, clreplacedLoader);
}
private Set<URL> restartUrls;
private ClreplacedLoaderFiles restartFiles;
@Override
protected void restart(Set<URL> urls, ClreplacedLoaderFiles files) {
this.restartUrls = urls;
this.restartFiles = files;
}
}
}
19
Source : RestarterTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link Restarter}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public clreplaced RestarterTests {
@Rule
public OutputCapture out = new OutputCapture();
@Before
public void setup() {
Restarter.setInstance(new TestableRestarter());
}
@After
public void cleanup() {
Restarter.clearInstance();
}
@Test
public void cantGetInstanceBeforeInitialize() {
Restarter.clearInstance();
replacedertThatIllegalStateException().isThrownBy(Restarter::getInstance).withMessageContaining("Restarter has not been initialized");
}
@Test
public void testRestart() throws Exception {
Restarter.clearInstance();
Thread thread = new Thread(SampleApplication::main);
thread.start();
Thread.sleep(2600);
String output = this.out.toString();
replacedertThat(StringUtils.countOccurrencesOf(output, "Tick 0")).isGreaterThan(1);
replacedertThat(StringUtils.countOccurrencesOf(output, "Tick 1")).isGreaterThan(1);
replacedertThat(CloseCountingApplicationListener.closed).isGreaterThan(0);
}
@Test
@SuppressWarnings("rawtypes")
public void getOrAddAttributeWithNewAttribute() {
ObjectFactory objectFactory = mock(ObjectFactory.clreplaced);
given(objectFactory.getObject()).willReturn("abc");
Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory);
replacedertThat(attribute).isEqualTo("abc");
}
@Test
public void addUrlsMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addUrls(null)).withMessageContaining("Urls must not be null");
}
@Test
public void addUrls() throws Exception {
URL url = new URL("file:/proj/module-a.jar!/");
Collection<URL> urls = Collections.singleton(url);
Restarter restarter = Restarter.getInstance();
restarter.addUrls(urls);
restarter.restart();
ClreplacedLoader clreplacedLoader = ((TestableRestarter) restarter).getRelaunchClreplacedLoader();
replacedertThat(((URLClreplacedLoader) clreplacedLoader).getURLs()[0]).isEqualTo(url);
}
@Test
public void addClreplacedLoaderFilesMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addClreplacedLoaderFiles(null)).withMessageContaining("ClreplacedLoaderFiles must not be null");
}
@Test
public void addClreplacedLoaderFiles() throws Exception {
ClreplacedLoaderFiles clreplacedLoaderFiles = new ClreplacedLoaderFiles();
clreplacedLoaderFiles.addFile("f", new ClreplacedLoaderFile(Kind.ADDED, "abc".getBytes()));
Restarter restarter = Restarter.getInstance();
restarter.addClreplacedLoaderFiles(clreplacedLoaderFiles);
restarter.restart();
ClreplacedLoader clreplacedLoader = ((TestableRestarter) restarter).getRelaunchClreplacedLoader();
replacedertThat(FileCopyUtils.copyToByteArray(clreplacedLoader.getResourcereplacedtream("f"))).isEqualTo("abc".getBytes());
}
@Test
@SuppressWarnings("rawtypes")
public void getOrAddAttributeWithExistingAttribute() {
Restarter.getInstance().getOrAddAttribute("x", () -> "abc");
ObjectFactory objectFactory = mock(ObjectFactory.clreplaced);
Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory);
replacedertThat(attribute).isEqualTo("abc");
verifyZeroInteractions(objectFactory);
}
@Test
public void getThreadFactory() throws Exception {
final ClreplacedLoader parentLoader = Thread.currentThread().getContextClreplacedLoader();
final ClreplacedLoader contextClreplacedLoader = new URLClreplacedLoader(new URL[0]);
Thread thread = new Thread(() -> {
Runnable runnable = mock(Runnable.clreplaced);
Thread regular = new Thread();
ThreadFactory factory = Restarter.getInstance().getThreadFactory();
Thread viaFactory = factory.newThread(runnable);
// Regular threads will inherit the current thread
replacedertThat(regular.getContextClreplacedLoader()).isEqualTo(contextClreplacedLoader);
// Factory threads should inherit from the initial thread
replacedertThat(viaFactory.getContextClreplacedLoader()).isEqualTo(parentLoader);
});
thread.setContextClreplacedLoader(contextClreplacedLoader);
thread.start();
thread.join();
}
@Test
public void getInitialUrls() throws Exception {
Restarter.clearInstance();
RestartInitializer initializer = mock(RestartInitializer.clreplaced);
URL[] urls = new URL[] { new URL("file:/proj/module-a.jar!/") };
given(initializer.getInitialUrls(any(Thread.clreplaced))).willReturn(urls);
Restarter.initialize(new String[0], false, initializer, false);
replacedertThat(Restarter.getInstance().getInitialUrls()).isEqualTo(urls);
}
@Component
@EnableScheduling
public static clreplaced SampleApplication {
private int count = 0;
private static volatile boolean quit = false;
@Scheduled(fixedDelay = 200)
public void tickBean() {
System.out.println("Tick " + this.count++ + " " + Thread.currentThread());
}
@Scheduled(initialDelay = 500, fixedDelay = 500)
public void restart() {
System.out.println("Restart " + Thread.currentThread());
if (!SampleApplication.quit) {
Restarter.getInstance().restart();
}
}
public static void main(String... args) {
Restarter.initialize(args, false, new MockRestartInitializer(), true);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleApplication.clreplaced);
context.addApplicationListener(new CloseCountingApplicationListener());
Restarter.getInstance().prepare(context);
System.out.println("Sleep " + Thread.currentThread());
sleep();
quit = true;
}
private static void sleep() {
try {
Thread.sleep(1200);
} catch (InterruptedException ex) {
// Ignore
}
}
}
private static clreplaced CloseCountingApplicationListener implements ApplicationListener<ContextClosedEvent> {
static int closed = 0;
@Override
public void onApplicationEvent(ContextClosedEvent event) {
closed++;
}
}
private static clreplaced TestableRestarter extends Restarter {
private ClreplacedLoader relaunchClreplacedLoader;
TestableRestarter() {
this(Thread.currentThread(), new String[] {}, false, new MockRestartInitializer());
}
protected TestableRestarter(Thread thread, String[] args, boolean forceReferenceCleanup, RestartInitializer initializer) {
super(thread, args, forceReferenceCleanup, initializer);
}
@Override
public void restart(FailureHandler failureHandler) {
try {
stop();
start(failureHandler);
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
@Override
protected Throwable relaunch(ClreplacedLoader clreplacedLoader) {
this.relaunchClreplacedLoader = clreplacedLoader;
return null;
}
@Override
protected void stop() {
}
public ClreplacedLoader getRelaunchClreplacedLoader() {
return this.relaunchClreplacedLoader;
}
}
}
19
Source : RestartApplicationListenerTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link RestartApplicationListener}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public clreplaced RestartApplicationListenerTests {
private static final String ENABLED_PROPERTY = "spring.devtools.restart.enabled";
private static final String[] ARGS = new String[] { "a", "b", "c" };
@Rule
public final OutputCapture output = new OutputCapture();
@Before
@After
public void cleanup() {
Restarter.clearInstance();
System.clearProperty(ENABLED_PROPERTY);
}
@Test
public void isHighestPriority() {
replacedertThat(new RestartApplicationListener().getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE);
}
@Test
public void initializeWithReady() {
testInitialize(false);
replacedertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("args", ARGS);
replacedertThat(Restarter.getInstance().isFinished()).isTrue();
replacedertThat((List<?>) ReflectionTestUtils.getField(Restarter.getInstance(), "rootContexts")).isNotEmpty();
}
@Test
public void initializeWithFail() {
testInitialize(true);
replacedertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("args", ARGS);
replacedertThat(Restarter.getInstance().isFinished()).isTrue();
replacedertThat((List<?>) ReflectionTestUtils.getField(Restarter.getInstance(), "rootContexts")).isEmpty();
}
@Test
public void disableWithSystemProperty() {
System.setProperty(ENABLED_PROPERTY, "false");
this.output.reset();
testInitialize(false);
replacedertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("enabled", false);
replacedertThat(this.output.toString()).contains("Restart disabled due to System property");
}
private void testInitialize(boolean failed) {
Restarter.clearInstance();
RestartApplicationListener listener = new RestartApplicationListener();
SpringApplication application = new SpringApplication();
ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.clreplaced);
listener.onApplicationEvent(new ApplicationStartingEvent(application, ARGS));
replacedertThat(Restarter.getInstance()).isNotEqualTo(nullValue());
replacedertThat(Restarter.getInstance().isFinished()).isFalse();
listener.onApplicationEvent(new ApplicationPreparedEvent(application, ARGS, context));
if (failed) {
listener.onApplicationEvent(new ApplicationFailedEvent(application, ARGS, context, new RuntimeException()));
} else {
listener.onApplicationEvent(new ApplicationReadyEvent(application, ARGS, context));
}
}
}
19
Source : ClassLoaderFilesResourcePatternResolverTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link ClreplacedLoaderFilesResourcePatternResolver}.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @author Stephane Nicoll
*/
public clreplaced ClreplacedLoaderFilesResourcePatternResolverTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private ClreplacedLoaderFiles files;
private ClreplacedLoaderFilesResourcePatternResolver resolver;
@Before
public void setup() {
this.files = new ClreplacedLoaderFiles();
this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(new GenericApplicationContext(), this.files);
}
@Test
public void getClreplacedLoaderShouldReturnClreplacedLoader() {
replacedertThat(this.resolver.getClreplacedLoader()).isNotNull();
}
@Test
public void getResourceShouldReturnResource() {
Resource resource = this.resolver.getResource("index.html");
replacedertThat(resource).isNotNull().isInstanceOf(ClreplacedPathResource.clreplaced);
}
@Test
public void getResourceWhenHreplacedervletContextShouldReturnServletResource() {
GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext());
this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(context, this.files);
Resource resource = this.resolver.getResource("index.html");
replacedertThat(resource).isNotNull().isInstanceOf(ServletContextResource.clreplaced);
}
@Test
public void getResourceWhenDeletedShouldReturnDeletedResource() throws Exception {
File folder = this.temp.newFolder();
File file = createFile(folder, "name.clreplaced");
this.files.addFile(folder.getName(), "name.clreplaced", new ClreplacedLoaderFile(Kind.DELETED, null));
Resource resource = this.resolver.getResource("file:" + file.getAbsolutePath());
replacedertThat(resource).isNotNull().isInstanceOf(DeletedClreplacedLoaderFileResource.clreplaced);
}
@Test
public void getResourcesShouldReturnResources() throws Exception {
File folder = this.temp.newFolder();
createFile(folder, "name.clreplaced");
Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**");
replacedertThat(resources).isNotEmpty();
}
@Test
public void getResourcesWhenDeletedShouldFilterDeleted() throws Exception {
File folder = this.temp.newFolder();
createFile(folder, "name.clreplaced");
this.files.addFile(folder.getName(), "name.clreplaced", new ClreplacedLoaderFile(Kind.DELETED, null));
Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**");
replacedertThat(resources).isEmpty();
}
@Test
public void customResourceLoaderIsUsedInNonWebApplication() {
GenericApplicationContext context = new GenericApplicationContext();
ResourceLoader resourceLoader = mock(ResourceLoader.clreplaced);
context.setResourceLoader(resourceLoader);
this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(context, this.files);
this.resolver.getResource("foo.txt");
verify(resourceLoader).getResource("foo.txt");
}
@Test
public void customProtocolResolverIsUsedInNonWebApplication() {
GenericApplicationContext context = new GenericApplicationContext();
Resource resource = mock(Resource.clreplaced);
ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource);
context.addProtocolResolver(resolver);
this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(context, this.files);
Resource actual = this.resolver.getResource("foo:some-file.txt");
replacedertThat(actual).isSameAs(resource);
verify(resolver).resolve(eq("foo:some-file.txt"), any(ResourceLoader.clreplaced));
}
@Test
public void customResourceLoaderIsUsedInWebApplication() {
GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext());
ResourceLoader resourceLoader = mock(ResourceLoader.clreplaced);
context.setResourceLoader(resourceLoader);
this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(context, this.files);
this.resolver.getResource("foo.txt");
verify(resourceLoader).getResource("foo.txt");
}
@Test
public void customProtocolResolverIsUsedInWebApplication() {
GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext());
Resource resource = mock(Resource.clreplaced);
ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource);
context.addProtocolResolver(resolver);
this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(context, this.files);
Resource actual = this.resolver.getResource("foo:some-file.txt");
replacedertThat(actual).isSameAs(resource);
verify(resolver).resolve(eq("foo:some-file.txt"), any(ResourceLoader.clreplaced));
}
private ProtocolResolver mockProtocolResolver(String path, Resource resource) {
ProtocolResolver resolver = mock(ProtocolResolver.clreplaced);
given(resolver.resolve(eq(path), any(ResourceLoader.clreplaced))).willReturn(resource);
return resolver;
}
private File createFile(File folder, String name) throws IOException {
File file = new File(folder, name);
FileCopyUtils.copy("test".getBytes(), file);
return file;
}
}
19
Source : ChangeableUrlsTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Tests for {@link ChangeableUrls}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public clreplaced ChangeableUrlsTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void folderUrl() throws Exception {
URL url = makeUrl("myproject");
replacedertThat(ChangeableUrls.fromUrls(url).size()).isEqualTo(1);
}
@Test
public void fileUrl() throws Exception {
URL url = this.temporaryFolder.newFile().toURI().toURL();
replacedertThat(ChangeableUrls.fromUrls(url)).isEmpty();
}
@Test
public void httpUrl() throws Exception {
URL url = new URL("http://spring.io");
replacedertThat(ChangeableUrls.fromUrls(url)).isEmpty();
}
@Test
public void httpsUrl() throws Exception {
URL url = new URL("https://spring.io");
replacedertThat(ChangeableUrls.fromUrls(url)).isEmpty();
}
@Test
public void skipsUrls() throws Exception {
ChangeableUrls urls = ChangeableUrls.fromUrls(makeUrl("spring-boot"), makeUrl("spring-boot-autoconfigure"), makeUrl("spring-boot-actuator"), makeUrl("spring-boot-starter"), makeUrl("spring-boot-starter-some-thing"));
replacedertThat(urls).isEmpty();
}
@Test
public void urlsFromJarClreplacedPathAreConsidered() throws Exception {
File relative = this.temporaryFolder.newFolder();
URL absoluteUrl = this.temporaryFolder.newFolder().toURI().toURL();
File jarWithClreplacedPath = makeJarFileWithUrlsInManifestClreplacedPath("project-core/target/clreplacedes/", "project-web/target/clreplacedes/", "does-not-exist/target/clreplacedes", relative.getName() + "/", absoluteUrl);
new File(jarWithClreplacedPath.getParentFile(), "project-core/target/clreplacedes").mkdirs();
new File(jarWithClreplacedPath.getParentFile(), "project-web/target/clreplacedes").mkdirs();
ChangeableUrls urls = ChangeableUrls.fromClreplacedLoader(new URLClreplacedLoader(new URL[] { jarWithClreplacedPath.toURI().toURL(), makeJarFileWithNoManifest() }));
replacedertThat(urls.toList()).containsExactly(new URL(jarWithClreplacedPath.toURI().toURL(), "project-core/target/clreplacedes/"), new URL(jarWithClreplacedPath.toURI().toURL(), "project-web/target/clreplacedes/"), relative.toURI().toURL(), absoluteUrl);
}
private URL makeUrl(String name) throws IOException {
File file = this.temporaryFolder.newFolder();
file = new File(file, name);
file = new File(file, "target");
file = new File(file, "clreplacedes");
file.mkdirs();
return file.toURI().toURL();
}
private File makeJarFileWithUrlsInManifestClreplacedPath(Object... urls) throws Exception {
File clreplacedpathJar = this.temporaryFolder.newFile("clreplacedpath.jar");
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
manifest.getMainAttributes().putValue(Attributes.Name.CLreplaced_PATH.toString(), StringUtils.arrayToDelimitedString(urls, " "));
new JarOutputStream(new FileOutputStream(clreplacedpathJar), manifest).close();
return clreplacedpathJar;
}
private URL makeJarFileWithNoManifest() throws Exception {
File clreplacedpathJar = this.temporaryFolder.newFile("no-manifest.jar");
new ZipOutputStream(new FileOutputStream(clreplacedpathJar)).close();
return clreplacedpathJar.toURI().toURL();
}
}
See More Examples