Mocking cassandra session object - session

I an trying to mock the session object of cassandra which is obtained in the actual code in the following way...
session = cluster.connect(keyspace);
What I am looking for is "To execute the statement and return the mock session object"
I have tried the following options
MemberModifier.stub(MemberMatcher.method(Cluster.class, "connect" String.class)).toReturn(session);
PowerMockito.when(cluster.connect(keyspace)).thenReturn(session);
PowerMockito.when(cluster.connect(keyspace)).thenAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { return session; } });
PowerMockito.when(cluster.connect(keyspace)).thenReturn(session);
Session testSession = cassandraService.getCassandraDBConnection();
None of these individually or in combination seem to work.
When the relevant JUnit is executed, the error that I get is
Stack Trace here below...
All host(s) tried for query failed (tried: /<<ip address>>:<<port no>> (com.datastax.driver.core.exceptions.TransportException: [/ip address] Cannot connect))
at com.datastax.driver.core.ControlConnection.reconnectInternal(ControlConnection.java:231)
at com.datastax.driver.core.ControlConnection.connect(ControlConnection.java:77)
at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1414)
at com.datastax.driver.core.Cluster.init(Cluster.java:162)
at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:333)
at com.datastax.driver.core.Cluster.connect(Cluster.java:283)
at com.capitalone.payments.customerprofile.service.CassandraInteractionService.getCassandraDBConnection(CassandraInteractionService.java:202)
Could somebody guide me here please?
(I have masked ip address and port number in stack trace)
Thanks!
-Sriram

I guess that you want to mock the Java driver session object for testing right ?
In this case, I would recommend:
Use an embedded Cassandra server for unit test, see Achilles Embedded Cassandra or Cassandra Unit
Use the Stubbed Cassandra which simulate CQL requests and responses. This is probably the closest to achieve what you want instead of mocking

Related

Neo4j Dynamic cql switching

I want to switch database based on a request header, which I have managed to do but in a rather clunky way.
I had to change my jdbc driver to neo native driver to get the "USE database" prefix to work.
I had to prefix my cql query with "USE database "
What I really want is to do this via AOP, such that I can annotate the method with my custom java annotation and this aspect will just call "USE DATABASE" in isolation before going on to the joinpoint and calling the actual query.
When I try this though I get this error
Query cannot conclude with USE GRAPH (must be RETURN or an update clause)
Is it possible ?
You can change the database on the session object.
try (Session session = driver.session(SessionConfig.forDatabase( "databaseName" ))) {
session.executeWrite((tx) -> tx.run(stmt, params));
}
You shouldn't use JDBC for apps, that's rather for tools.
https://neo4j.com/docs/java-manual/current/cypher-workflow/#java-database-selection

Apache Geode - Creating region on DUnit Based Test Server/Remote Server with same code from client

I am tryint to reuse the code in following documentation : https://geode.apache.org/docs/guide/11/developing/region_options/dynamic_region_creation.html
The first problem that i met is that
Cache cache = CacheFactory.getAnyInstance();
Region<String,RegionAttributes<?,?>> regionAttributesMetadataRegion = createRegionAttributesMetadataRegion(cache);
should not be executed in constructor. In case it is , the code is executed in client instance , it is failed on not server error.When this fixed i receive
[fatal 2021/02/15 16:38:24.915 EET <ServerConnection on port 40527 Thread 1> tid=81] Serialization filter is rejecting class org.restcomm.cache.geode.CreateRegionFunction
java.lang.Exception:
at org.apache.geode.internal.ObjectInputStreamFilterWrapper.lambda$createSerializationFilter$0(ObjectInputStreamFilterWrapper.java:233)
The problem is that code is getting executed on dunit MemberVM and the required class is actually the part of the package under which the test is getting executed.
So i guess i should somehow register the classes ( or may be jar ) separately to dunit MemberVM. How it can be done?
Another question is: currently the code is checking if the region exists and if not it calls the method. In both cases it also tries to create the clientRegion. The question is whether this is a correct approach?
Region<?,?> cache = instance.getRegion(name);
if(cache==null) {
Execution execution = FunctionService.onServers(instance);
ArrayList argList = new ArrayList();
argList.add(name);
Function function = new CreateRegionFunction();
execution.setArguments(argList).execute(function).getResult();
}
ClientRegionFactory<Object, Object> cf=this.instance.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).addCacheListener(new ExtendedCacheListener());
this.cache = cf.create(name);
BR
Yulian Oifa
The first problem that i met is that
Cache cache = CacheFactory.getAnyInstance();
should not be executed in constructor. In case it is , the code is executed in client instance , it is failed on not server error.When this fixed i receive
Once the Function is registered on server side, you can execute it by ID instead of sending the object across the wire (so you won't need to instantiate the function on the client), in which case you'll also avoid the Serialization filter error. As an example, FunctionService.onServers(instance).execute(CreateRegionFunction.ID).
The problem is that code is getting executed on dunit MemberVM and the required class is actually the part of the package under which the test is getting executed. So i guess i should somehow register the classes ( or may be jar ) separately to dunit MemberVM. How it can be done?
Indeed, for security reasons Geode doesn't allow serializing / deserializing arbitrary classes. Internal Geode distributed tests use the MemberVM and set a special property (serializable-object-filter) to circumvent this problem. Here's an example of how you can achieve that within your own tests.
Another question is: currently the code is checking if the region exists and if not it calls the method. In both cases it also tries to create the clientRegion. The question is whether this is a correct approach?
If the dynamically created region is used by the client application then yes, you should create it, otherwise you won't be able to use it.
As a side note, there's a lot of internal logic implemented by Geode when creating a Region so I wouldn't advice to dynamically create regions on your own. Instead, it would be advisable to use the gfsh create region command directly, or look at how it works internally (see here) and try to re-use that.

Is JavaSamplerClient the right way to test this setup?

I have a java server that communicates with java clients over the network. What I want to do is to verify that they are maintaining state and gather performance statistics for the server. I've used JMeter to test web services in the past and thought to use it to test this server.
The clients are pretty simple and only send and receive a few message types. They login to the server and create a session id. Then they can do a number of transactions using that id, get text data, send text data, ping to verify the connection is alive and finally logout.
Initially I thought I'd wrap the client code in a JavaSamplerClient, but having read the javadocs again I'm not sure that is a good idea. JavaSamplerClient looks like it expects to do one thing and return the same kind of data. But I want to not only return the performance numbers, but I want to verify that the state of the client and check that the data is not being corrupted.
Is using JavaSamplerClient in JMeter the right thing to use here or is there a better solution?
JavaSamplerClient can do everything you'll implement.
For instance, if you create your class as follows:
public class MySampler extends AbstractJavaSamplerClient {
#Override
public void setupTest(JavaSamplerContext context) {
return;
}
#Override
public SampleResult runTest(JavaSamplerContext context) {
return null;
}
#Override
public Arguments getDefaultParameters() {
return null;
}
If you don't intent to use GUI for sampler you can omit setupTest and getDefaultParameters methods and leave only runTest one.
Your test code should be placed inside runTest method. It returns an instance of SampleResult which is fully controllable.
for instance:
result.setResponseCode() - set response code based on any condition
result.setResponseMessage() - the same for response message
The bit you're looking for is probably
result.setResponseData() - here you can make your sampler to return anything you want.
Reference material: Beanshell vs JSR223 vs Java JMeter Scripting

Meteor 0.5.9: replacement for using Session in a server method?

So, I was attempting to do something like the following:
if(Meteor.isServer){
Meteor.methods({connect_to_api: function(vars){
// get data from remote API
return data;
}});
}
if(Meteor.isClient){
Template.myTpl.content = function(){
Meteor.call('connect_to_api', vars, function(err,data){
Session.set('placeholder', data);
});
return Session.get('placeholder');
};
}
This seemed to be working fine, but, of course, now breaks in 0.5.9 as the Session object has been removed from the server. How in the world do you now create a reactive Template that uses a server-only (stuff we don't want loading on the client) method call and get data back from that Method call. You can't put any Session references in the callback function because it doesn't exist on the server, and I don't know of any other reactive data sources available for this scenario.
I'm pretty new to Meteor, so I'm really trying to pin down best-practices stuff that has the best chance of being future-proof. Apparently the above implementation was not it.
EDIT: To clarify, this is not a problem of when I'm returning from the Template function. This is a problem of Session existing on the server. The above code will generate the following error message on the server:
Exception while invoking method 'connect_to_api' ReferenceError: Session is not defined
at Meteor.methods.connect_to_api (path/to/file.js:#:#)
at _.extend.protocol_handlers.method.exception ... etc etc
Setting the session in the callback seems to work fine, see this project I created on github: https://github.com/jtblin/meteor_session_test. In this example, I return data in a server method, and set it in the session in the callback.
There are 2 issues with your code:
1) Missing closing brace placement in Meteor.methods. The code should be:
Meteor.methods({
connect_to_api: function(vars) {
// get data from remote API
return data;
}
});
2) As explained above, you return the value in the session, before the callback is completed, i.e. before the callback method had the time to set the session variable. I guess this is why you don't see any data in the session variable yet.
I feel like an idiot (not the first time, not the last). Thanks to jtblin for showing me that Session.set does indeed work in the callback, I went back and scoured my Meteor.method function. Turns out there was one spot buried in the code where I was using Session.get which was what was throwing the error. Once I passed that value in from the client rather than trying to get it in the method itself, all was right with the world.
Oh, and you can indeed order things as above without issue.

How do I create an instance of Oracle.DataAccess.Client.OracleException to use with NMock

I'm using the Oracle.DataAccess.Client data provider client. I am having trouble constructing a new instance of an OracleException object, but it keeps telling me that there are no public constructors. I saw other having the same problem and tried their solutions, but they don't seem to work. Here's my test code:
object[] args = { 1, "Test Message" };
ConstructorInfo ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic
| BindingFlags.Instance, null, System.Type.GetTypeArray(args), null);
var e = (OracleException)ci.Invoke(args);
When debugging the test code, I always get a NULL value for 'ci'.
Has Oracle changed the library to not allow this? What am I doing wrong and what do I need to do to instantiate an OracleException object to use with NMock?
By the way, I'm using the Client library for version 10g.
Thanks,
Charlie
OracleException in ODP.NET not the same as OracleException in Microsoft client.
OracleException have 5 constructors information of which you can obtain by GetConstructors().
In the obtained list of the constructors you will see that there are no constructor with parameters (int, string). That why you getting NULL in ci.
If you give a proper list of the parameters you will have proper ConstructorInfo and will be able to call a constructor by Invoke(param);
However, OracleException constructor not designed to be called like this - not all the fields will have a proper information.
2All:
I need following OracleException:
ORA-00001 unique constraint (string.string) violated
ORA-03113 end-of-file on communication channel
ORA-03135: connection lost contact
ORA-12170: TNS: Connect timeout occurred
for testing. How do I create them?

Resources