use of org.easymock.IAnswer in project opennms by OpenNMS.
the class NewtsResourceStorageDaoTest method replay.
private void replay() {
EasyMock.expect(m_searcher.search(EasyMock.eq(m_context), EasyMock.anyObject(), EasyMock.anyBoolean())).andAnswer(new IAnswer<SearchResults>() {
public SearchResults answer() throws Throwable {
// Assume there is a single term query
Query q = (Query) EasyMock.getCurrentArguments()[1];
BooleanQuery bq = (BooleanQuery) q;
TermQuery tq = (TermQuery) bq.getClauses().get(0).getQuery();
String field = tq.getTerm().getField("");
String value = tq.getTerm().getValue();
SearchResults searchResults = new SearchResults();
for (Entry<ResourcePath, Set<String>> entry : m_indexedPaths.entrySet()) {
Map<String, String> attributes = Maps.newHashMap();
// Build the indexed attributes and attempt to match them against the given query
NewtsUtils.addIndicesToAttributes(entry.getKey(), attributes);
if (value.equals(attributes.get(field))) {
searchResults.addResult(new Resource(NewtsUtils.toResourceId(entry.getKey())), entry.getValue());
}
}
return searchResults;
}
}).atLeastOnce();
EasyMock.expect(m_searcher.getResourceAttributes(EasyMock.eq(m_context), EasyMock.anyObject())).andReturn(Maps.newHashMap()).anyTimes();
EasyMock.replay(m_searcher);
}
use of org.easymock.IAnswer in project aries by apache.
the class UtilTest method testNotInitialized.
@Test
public void testNotInitialized() throws Exception {
BaseActivator.activator = null;
URL url = getClass().getResource("/embedded3.jar");
assertNotNull("precondition", url);
Bundle providerBundle = EasyMock.createMock(Bundle.class);
final ClassLoader providerCL = new TestBundleClassLoader(new URL[] { url }, getClass().getClassLoader(), providerBundle);
EasyMock.expect(providerBundle.getBundleId()).andReturn(42L).anyTimes();
EasyMock.expect(providerBundle.getEntryPaths((String) EasyMock.anyObject())).andReturn(null).anyTimes();
Dictionary<String, String> providerHeaders = new Hashtable<String, String>();
providerHeaders.put(Constants.BUNDLE_CLASSPATH, ".,embedded3.jar");
EasyMock.expect(providerBundle.getHeaders()).andReturn(providerHeaders).anyTimes();
EasyMock.expect(providerBundle.getResource("embedded3.jar")).andReturn(url).anyTimes();
providerBundle.loadClass((String) EasyMock.anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Class<?>>() {
@Override
public Class<?> answer() throws Throwable {
return providerCL.loadClass((String) EasyMock.getCurrentArguments()[0]);
}
}).anyTimes();
EasyMock.replay(providerBundle);
Bundle clientBundle = EasyMock.createMock(Bundle.class);
EasyMock.replay(clientBundle);
ClassLoader clientCL = new TestBundleClassLoader(new URL[] {}, getClass().getClassLoader(), clientBundle);
Thread.currentThread().setContextClassLoader(null);
Util.fixContextClassloader(ServiceLoader.class.getName(), "load", MySPI.class, clientCL);
assertSame("The system is not yet initialized, so the TCCL should not be set", null, Thread.currentThread().getContextClassLoader());
}
use of org.easymock.IAnswer in project aries by apache.
the class ClientWeavingHookGenericCapabilityTest method mockProviderBundle.
private Bundle mockProviderBundle(String subdir, long id, Version version) throws Exception {
URL url = getClass().getResource("/" + getClass().getName().replace('.', '/') + ".class");
File classFile = new File(url.getFile());
File baseDir = new File(classFile.getParentFile(), subdir);
File directory = new File(baseDir, "/META-INF/services");
final List<String> classNames = new ArrayList<String>();
// Do a directory listing of the applicable META-INF/services directory
List<String> resources = new ArrayList<String>();
for (File f : directory.listFiles()) {
String fileName = f.getName();
if (fileName.startsWith(".") || fileName.endsWith("."))
continue;
classNames.addAll(getClassNames(f));
// Needs to be something like: META-INF/services/org.apache.aries.mytest.MySPI
String path = f.getAbsolutePath().substring(baseDir.getAbsolutePath().length());
path = path.replace('\\', '/');
if (path.startsWith("/")) {
path = path.substring(1);
}
resources.add(path);
}
// Set up the classloader that will be used by the ASM-generated code as the TCCL.
// It can load a META-INF/services file
final ClassLoader cl = new TestProviderBundleClassLoader(subdir, resources.toArray(new String[] {}));
final List<String> classResources = new ArrayList<String>();
for (String className : classNames) {
classResources.add("/" + className.replace('.', '/') + ".class");
}
BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
EasyMock.replay(bc);
Bundle providerBundle = EasyMock.createMock(Bundle.class);
String bsn = subdir;
int idx = bsn.indexOf('_');
if (idx > 0) {
bsn = bsn.substring(0, idx);
}
EasyMock.expect(providerBundle.getSymbolicName()).andReturn(bsn).anyTimes();
EasyMock.expect(providerBundle.getBundleId()).andReturn(id).anyTimes();
EasyMock.expect(providerBundle.getBundleContext()).andReturn(bc).anyTimes();
EasyMock.expect(providerBundle.getVersion()).andReturn(version).anyTimes();
EasyMock.expect(providerBundle.getEntryPaths("/")).andAnswer(new IAnswer<Enumeration<String>>() {
@Override
public Enumeration<String> answer() throws Throwable {
return Collections.enumeration(classResources);
}
}).anyTimes();
EasyMock.<Class<?>>expect(providerBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() {
@Override
public Class<?> answer() throws Throwable {
String name = (String) EasyMock.getCurrentArguments()[0];
if (!classNames.contains(name)) {
throw new ClassCastException(name);
}
return cl.loadClass(name);
}
}).anyTimes();
EasyMock.replay(providerBundle);
return providerBundle;
}
use of org.easymock.IAnswer in project karaf by apache.
the class GuardProxyCatalogTest method testCreateProxy.
@SuppressWarnings({ "unchecked", "rawtypes" })
public Dictionary<String, Object> testCreateProxy(BundleContext bc, Class intf, final Class proxyRegClass, Object testService) throws Exception {
// Create the object that is actually being tested here
GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
// The service being proxied has these properties
long serviceID = 456L;
final Hashtable<String, Object> serviceProps = new Hashtable<>();
serviceProps.put(Constants.OBJECTCLASS, new String[] { intf.getName() });
serviceProps.put(Constants.SERVICE_ID, serviceID);
serviceProps.put(".foo", 123L);
final Map<ServiceReference<?>, Object> serviceMap = new HashMap<>();
// The mock bundle context for the bundle providing the service is set up here
BundleContext providerBC = EasyMock.createMock(BundleContext.class);
// These are the expected service properties of the proxy registration. Note the proxy marker...
final Hashtable<String, Object> expectedProxyProps = new Hashtable<>(serviceProps);
expectedProxyProps.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE);
// This will check that the right proxy is being registered.
EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
if (!runningUnderCoverage) {
assertArrayEquals(new String[] { proxyRegClass.getName() }, (String[]) EasyMock.getCurrentArguments()[0]);
Object svc = EasyMock.getCurrentArguments()[1];
assertTrue(svc instanceof ServiceFactory);
}
Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
for (String key : expectedProxyProps.keySet()) {
assertEquals(expectedProxyProps.get(key), props.get(key));
}
ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
ServiceReference sr = mockServiceReference(props);
EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
reg.unregister();
EasyMock.expectLastCall().once();
EasyMock.replay(reg);
serviceMap.put(sr, EasyMock.getCurrentArguments()[1]);
return reg;
}).once();
EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(() -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes();
EasyMock.replay(providerBC);
// In some cases the proxy-creating code is looking for a classloader (e.g. when run through
// a coverage tool such as EclEmma). This will satisfy that.
BundleWiring bw = EasyMock.createMock(BundleWiring.class);
EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader()).anyTimes();
EasyMock.replay(bw);
// The mock bundle that provides the original service (and also the proxy is registered with this)
Bundle providerBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(providerBundle.getBundleContext()).andReturn(providerBC).anyTimes();
EasyMock.expect(providerBundle.adapt(BundleWiring.class)).andReturn(bw).anyTimes();
EasyMock.replay(providerBundle);
ServiceReference sr = mockServiceReference(providerBundle, serviceProps);
assertEquals("Precondition", 0, gpc.proxyMap.size());
assertEquals("Precondition", 0, gpc.createProxyQueue.size());
// Create the proxy for the service
gpc.proxyIfNotAlreadyProxied(sr);
assertEquals(1, gpc.proxyMap.size());
// The actual proxy creation is done asynchronously.
GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
assertNull("The registration shouldn't have happened yet", holder.registration);
assertEquals(1, gpc.createProxyQueue.size());
// Mimic the thread that works the queue to create the proxy
GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
ProxyManager pm = getProxyManager();
runnable.run(pm);
// The runnable should have put the actual registration in the holder
ServiceReference<?> proxySR = holder.registration.getReference();
for (String key : expectedProxyProps.keySet()) {
assertEquals(expectedProxyProps.get(key), proxySR.getProperty(key));
}
// Check that the proxy registration was done on the original provider bundle's context
EasyMock.verify(providerBC);
// Test that the actual proxy invokes the original service...
Object proxyService = serviceMap.get(proxySR);
assertNotSame("The proxy should not be the same object as the original service", testService, proxyService);
// Attempt to proxy the service again, make sure that no re-proxying happens
assertEquals("Precondition", 1, gpc.proxyMap.size());
assertEquals("Precondition", 0, gpc.createProxyQueue.size());
gpc.proxyIfNotAlreadyProxied(sr);
assertEquals("No additional proxy should have been created", 1, gpc.proxyMap.size());
assertEquals("No additional work on the queue is expected", 0, gpc.createProxyQueue.size());
Dictionary<String, Object> proxyProps = getServiceReferenceProperties(proxySR);
gpc.close();
// checks that the unregister call was made
EasyMock.verify(holder.registration);
return proxyProps;
}
use of org.easymock.IAnswer in project kafka by apache.
the class WorkerSinkTaskThreadedTest method expectPolls.
// Note that this can only be called once per test currently
private Capture<Collection<SinkRecord>> expectPolls(final long pollDelayMs) throws Exception {
// Stub out all the consumer stream/iterator responses, which we just want to verify occur,
// but don't care about the exact details here.
EasyMock.expect(consumer.poll(EasyMock.anyLong())).andStubAnswer(new IAnswer<ConsumerRecords<byte[], byte[]>>() {
@Override
public ConsumerRecords<byte[], byte[]> answer() throws Throwable {
// "Sleep" so time will progress
time.sleep(pollDelayMs);
ConsumerRecords<byte[], byte[]> records = new ConsumerRecords<>(Collections.singletonMap(new TopicPartition(TOPIC, PARTITION), Arrays.asList(new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET + recordsReturned, TIMESTAMP, TIMESTAMP_TYPE, 0L, 0, 0, RAW_KEY, RAW_VALUE))));
recordsReturned++;
return records;
}
});
EasyMock.expect(keyConverter.toConnectData(TOPIC, RAW_KEY)).andReturn(new SchemaAndValue(KEY_SCHEMA, KEY)).anyTimes();
EasyMock.expect(valueConverter.toConnectData(TOPIC, RAW_VALUE)).andReturn(new SchemaAndValue(VALUE_SCHEMA, VALUE)).anyTimes();
final Capture<SinkRecord> recordCapture = EasyMock.newCapture();
EasyMock.expect(transformationChain.apply(EasyMock.capture(recordCapture))).andAnswer(new IAnswer<SinkRecord>() {
@Override
public SinkRecord answer() {
return recordCapture.getValue();
}
}).anyTimes();
Capture<Collection<SinkRecord>> capturedRecords = EasyMock.newCapture(CaptureType.ALL);
sinkTask.put(EasyMock.capture(capturedRecords));
EasyMock.expectLastCall().anyTimes();
return capturedRecords;
}
Aggregations