/
AbstractJanusRunTest.java
435 lines (397 loc) · 12.5 KB
/
AbstractJanusRunTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/*
* $Id$
*
* Janus platform is an open-source multiagent platform.
* More details on http://www.janusproject.io
*
* Copyright (C) 2014-2015 Sebastian RODRIGUEZ, Nicolas GAUD, Stéphane GALLAND.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.janusproject.tests.testutils;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.inject.Module;
import com.google.inject.util.Modules;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import io.janusproject.Boot;
import io.janusproject.kernel.Kernel;
import io.janusproject.modules.StandardJanusPlatformModule;
import io.janusproject.services.executor.ChuckNorrisException;
import io.sarl.core.Initialize;
import io.sarl.core.Lifecycle;
import io.sarl.core.Schedules;
import io.sarl.lang.annotation.PerceptGuardEvaluator;
import io.sarl.lang.core.Agent;
import io.sarl.lang.core.BuiltinCapacitiesProvider;
import io.sarl.tests.api.Nullable;
/**
* Abstract class for creating unit tests that needs to launch a Janus instance.
*
* @param <S> - the type of the service.
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
@SuppressWarnings("all")
public abstract class AbstractJanusRunTest extends AbstractJanusTest {
/**
* Reference to the instance of the Janus kernel.
*/
protected Kernel janusKernel;
@Nullable
private List<Object> results;
@Rule
public TestWatcher janusRunWatcher = new TestWatcher() {
@Override
protected void starting(Description description) {
JanusRun skipRun = description.getAnnotation(JanusRun.class);
if (skipRun != null) {
try {
runJanus(skipRun.agent(), skipRun.enableLogging());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
protected void finished(Description description) {
if (AbstractJanusRunTest.this.janusKernel != null) {
AbstractJanusRunTest.this.janusKernel = null;
}
}
};
/**
* Replies the number of results provided by the ran platform.
*
* @return the number of results.
*/
protected int getNumberOfResults() {
return this.results.size();
}
/**
* Test if the number of results provided by the Janus platform is equal to the given number.
*
* @param expected - the expected number of results.
*/
protected void assertNumberOfResults(int expected) {
assertEquals("Invalid number of results provided by the platform.", expected, this.results.size());
}
/**
* Replies result at the given index of the run of the agent.
*
* @param type - the type of the result.
* @param index - the index of the result.
* @return the value; or <code>null</code> if no result.
*/
protected <T> T getResult(Class<T> type, int index) {
if (this.results != null) {
try {
return type.cast(this.results.get(index));
} catch (Throwable exception) {
//
}
}
return null;
}
/**
* Replies result at the given index of the run of the agent.
* @return the results.
*/
protected List<Object> getResults() {
if (this.results != null) {
return Collections.unmodifiableList(this.results);
}
return Collections.emptyList();
}
/**
* Replies the initialization parameters for the agents.
* @return the parameters.
*/
protected Object[] getAgentInitializationParameters() {
return new Object[] {
this.results,
};
}
/**
* Replies the index of the first result of the given type.
*
* @param type - the type of the result.
* @return the index; or <code>-1</code> if not found.
*/
protected int indexOfResult(Class<?> type) {
return indexOfResult(type, 0);
}
/**
* Replies the index of the first result of the given type starting at the given index.
*
* @param type - the type of the result.
* @param fromIndex - the start index.
* @return the index; or <code>-1</code> if not found.
*/
protected int indexOfResult(Class<?> type, int fromIndex) {
if (this.results != null) {
try {
for (int i = fromIndex; i < this.results.size(); ++i) {
Object r = this.results.get(i);
if (type.isInstance(r)) {
return i;
}
}
} catch (Throwable exception) {
//
}
}
return -1;
}
/**
* Start the Janus platform offline.
*
* This function has no timeout for the end of the run.
*
* @param type - the type of the agent to launch at start-up.
* @param enableLogging - indicates if the logging is enable or not.
* @throws Exception - if the kernel cannot be launched.
*/
protected void runJanus(Class<? extends TestingAgent> type, boolean enableLogging) throws Exception {
runJanus(type, enableLogging, true, -1);
}
/**
* Start the Janus platform offline with logging enabled.
*
* This function enables logging and has no timeout for the end of the run.
*
* @param type - the type of the agent to launch at start-up.
* @return the kernel.
* @throws Exception - if the kernel cannot be launched.
*/
protected void runJanus(Class<? extends TestingAgent> type) throws Exception {
runJanus(type, true, true, -1);
}
/**
* Start the Janus platform.
*
* @param type - the type of the agent to launch at start-up.
* @param enableLogging - indicates if the logging is enable or not.
* @param offline - indicates if the Janus platform is offline
* @param timeout - the maximum waiting time in seconds, or <code>-1</code> to ignore the timeout.
* @throws Exception - if the kernel cannot be launched.
*/
protected void runJanus(Class<? extends TestingAgent> type, boolean enableLogging, boolean offline, int timeout)
throws Exception {
setupTheJanusKernel(type, enableLogging, offline);
waitForTheKernel(timeout);
}
/**
* Set-up the Janus platform.
*
* @param type - the type of the agent to launch at start-up.
* @param enableLogging - indicates if the logging is enable or not.
* @param offline - indicates if the Janus platform is offline
* @return the kernel.
* @throws Exception - if the kernel cannot be launched.
*/
protected Kernel setupTheJanusKernel(Class<? extends TestingAgent> type, boolean enableLogging, boolean offline)
throws Exception {
assertNull("Janus already launched.", this.janusKernel);
Module module = new StandardJanusPlatformModule();
Boot.setConsoleLogger(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
//
}
@Override
public void write(byte[] b) throws IOException {
//
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
//
}
}));
this.results = new ArrayList<>();
if (!enableLogging) {
module = Modules.override(new StandardJanusPlatformModule()).with(new NoLogTestingModule());
} else {
module = Modules.override(new StandardJanusPlatformModule()).with(new ErrorLogTestingModule(this.results));
}
Boot.setOffline(offline);
this.janusKernel = Boot.startJanusWithModule(module, type, getAgentInitializationParameters());
Logger current = this.janusKernel.getLogger();
while (current.getParent() != null && current.getParent() != current) {
current = current.getParent();
}
if (current != null) {
current.setLevel(Level.OFF);
}
return this.janusKernel;
}
/**
* Wait for the end of the Janus platform.
*
* @param timeout - the maximum waiting time in seconds, or <code>-1</code> to ignore the timeout.
* @throws Exception - if the kernel cannot be launched.
*/
public void waitForTheKernel(int timeout) throws Exception {
long endTime;
if (timeout >= 0) {
endTime = System.currentTimeMillis() + timeout * 1000;
} else {
endTime = -1;
}
boolean isJanusRunning = this.janusKernel.isRunning();
while (isJanusRunning && (endTime == -1 || System.currentTimeMillis() <= endTime)) {
isJanusRunning = this.janusKernel.isRunning();
Thread.yield();
}
Boot.setConsoleLogger(null);
if (isJanusRunning) {
throw new TimeoutException();
}
}
/**
* Wait for the end of the Janus platform.
*
* @param timeout - the maximum waiting time in seconds, or <code>-1</code> to ignore the timeout.
* @param predicate the predicate to use as stop condition.
* @throws Exception - if the kernel cannot be launched.
*/
public void waitForTheKernel(int timeout, Function1<List<Object>, Boolean> predicate) throws Exception {
long endTime;
if (timeout >= 0) {
endTime = System.currentTimeMillis() + timeout * 1000;
} else {
endTime = -1;
}
boolean isJanusRunning = this.janusKernel.isRunning();
while (isJanusRunning && (endTime == -1 || System.currentTimeMillis() <= endTime)) {
isJanusRunning = this.janusKernel.isRunning() || !(predicate.apply(this.results));
Thread.yield();
}
Boot.setConsoleLogger(null);
if (isJanusRunning) {
throw new TimeoutException();
}
}
/**
* Interface that permits to mark a method that is manually launching the Janus.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
protected @interface JanusRun {
/**
* The type of the agent to launch.
*
* @return the type of the agent to launch.
*/
Class<? extends TestingAgent> agent();
/**
* Indicates if the logging is enabled.
*
* @return <code>true</code> if the logging is enabled; <code>false</code> otherwise.
*/
boolean enableLogging() default false;
}
/**
* Abstract implementation of an agent that is used for testing Janus
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
protected static abstract class TestingAgent extends Agent {
private List<Object> results;
/**
* @param provider - the provider of builtin capacities.
* @param parentID - the identifier of the parent's agent.
* @param agentID - the identifier of the agent.
*/
public TestingAgent(BuiltinCapacitiesProvider provider, UUID parentID, UUID agentID) {
super(provider, parentID, agentID);
}
/**
* Add a result.
*
* @param result - the result.
*/
protected void addResult(Object result) {
this.results.add(result);
}
/**
* Replies result at the given index of the run of the agent.
* @return the results.
*/
protected List<Object> getResults() {
if (this.results != null) {
return Collections.unmodifiableList(this.results);
}
return Collections.emptyList();
}
@PerceptGuardEvaluator
private void $guardEvaluator$Initialize(final Initialize occurrence, final Collection<Runnable> ___SARLlocal_runnableCollection) {
assert occurrence != null;
assert ___SARLlocal_runnableCollection != null;
___SARLlocal_runnableCollection.add(() -> $behaviorUnit$Initialize$0(occurrence));
}
/**
* Invoked at the start of the agent.
*
* @param occurrence - the initialization event.
*/
private void $behaviorUnit$Initialize$0(final Initialize occurrence) {
this.results = (List<Object>) occurrence.parameters[0];
try {
if (runAgentTest()) {
getSkill(Schedules.class).in(1000, (it) ->
getSkill(Lifecycle.class).killMe());
}
} catch (Throwable exception) {
if (!(exception instanceof ChuckNorrisException)) {
addResult(exception);
}
throw exception;
}
}
/**
* Invoked to run the unit test. This function is invoked at agent initialization
*
* @return <code>true</code> for killing the agent 1 second after its initialization.
*/
protected abstract boolean runAgentTest();
}
}