Connect to embedded Neo4j during test debugging - unit-testing

I'm using embedded Neo4j for JUnit tests with the following rule configuration:
#Rule
public Neo4jRule neo4jRule = new Neo4jRule()
.withConfig("dbms.connector.1.enabled", "true")
.withConfig("dbms.connector.1.listen_address", "localhost:4710")
.withConfig("dbms.connector.1.type", "HTTP")
.withConfig("dbms.connector.bolt.enabled", "true")
.withConfig("dbms.connector.bolt.listen_address", ":4711")
.withConfig("apoc.autoIndex.enabled", "true")
.withConfig("ShellSettings.remote_shell_enabled", "true")
.withConfig("ShellSettings.remote_shell_port", "5555")
.withProcedure(apoc.index.FulltextIndex.class)
.withProcedure(apoc.index.FreeTextSearch.class)
.withProcedure(apoc.cypher.Cypher.class);
Now I would like to connect via cypher-shell during debugging (breakpoint set) in order to take a look what is actually in the test database at some point. Unfortunately, neither cypher-shell -a localhost:4711 nor neo4j-shell -port 5555 get the connection. The first one doesn't return (remains pending), the second one returns Connection refused. What am I missing? Any idea on how to get a connection?

When a breakpoint hit during debugging, the embedded server also stops responding.
If you want to look at the state of your DB during unit tests, you need to pause the execution without the breakpoint. My solution is not exactly what you want but you can try this
#Test
public void yourTest() throws IOException {
try {
System.out.pritnln(neo4j.httpURI());
Thread.sleep(100000L);
} catch (Exception e) {
e.printStackTrace();
}
}
The above code will pause for 100s, you can click the link in console to open Neo4j browser and query the DB.

Related

Hystrix fallbackMethod will not be called in unit test?

I am starting to use Hystrix on my application to deal with data coming from external services. Some main points in my code:
#HystrixCommand(fallbackMethod = "getImagesFallback")
public ImageResultResource getImages(String url)
{
ResponseEntity<ResultResource> result = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(getRequestHeaders()), ResultResource.class);
return result.getBody().getImageResultResource();
}
public ImageResultResource getImagesFallback(String url, Throwable e)
{
return new ImageResultResource();
}
In my unit test, I would like to test the fallback case, for example when the external service returns 404 Not Found response, so I mock my test like below:
doThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND))//
.when(Mockito.spy(new ImageConnector()))//
.getImages(myMockedURL)
But when I run the test, it seems that the fallbackMethod that I defined above was not called. It returned directly the 404 Not Found that I mocked for the external service while I expect that the fallbackMethod should be catched here and no 404 Not Found will be thrown here.
Can anyone give me hint how can I test my fallbackMethod in this case, or did I make something wrong with the configuration here? Thank you so much!
Your fallback method needs to have the same signature as the method with the HystrixCommand annotation or the same signature with the addition of a Throwable. Here is the relevant Javanica documentation
public ImageResultResource getImagesFallback(String url, Throwable e) {
return new ImageResultResource();
}
Hystrix custom fallback methods throws the exception having the instance of HystrixRuntimeException..
So, you need to catch this exception and use getMessage method of it to print it.

Owin TestServer logs multiple times while testing - how can I fix this?

I'm trying to write unit tests for an OWIN service, but any log statements in my tests start duplicating once I run the tests all at once and really make the log output on the build server useless due to all the noise. I've distilled the problem down to a very simple repro:
[TestFixture]
public class ServerTest
{
[Test]
public void LogOnce()
{
using (TestServer.Create(app => { }))
{
Debug.WriteLine("Log once");
}
}
[Test]
public void LogTwice()
{
using (TestServer.Create(app => { }))
{
Debug.WriteLine("Log twice");
}
}
}
If I run one test at a time I get the expected output:
=> ServerTest.LogOnce
Log once
=> ServerTest.LogTwice
Log twice
If I run the tests all at once I get:
=> ServerTest.LogOnce
Log once
=> ServerTest.LogTwice
Log twice
Log twice
Initializing the TestServer once will solve the problem, but I am looking for a solution that allows me to continue instantiating as many TestServer instances as I choose.
This post points out how HostingEngine is defaulting on the TraceListener and ways to disable this:
TraceListener in OWIN Self Hosting
With that insight, I traced through the source code of TestServer.Create and confirmed that it is internally creating a HostingEngine which turns on a TraceListener that ultimately outputs results to the console. I have confirmed the highest voted (at the time of this writing) fix on that page works for the TestServer and believe the other solutions there are also excellent choices.
It was very time consuming and annoying having to figure this out. It is difficult to discover and non-obvious to wire up an opt-out. An opt-in solution would be better.

NUnit causes WebException when using System.Net.WebClient

The method below is working as intended when running through tests in MS test and through a Console application. When running it through a NUnit test I get an WebException.
Has any one else had this problem, and is there a way around it? It is not an option to use another testing framework.
public void Download(string username, string password, string dwlFileName, string dwlUrl)
{
var webClient = new WebClient();
webClient.Headers.Add("Authorization",
"Basic " +
Convert.ToBase64String(new ASCIIEncoding().GetBytes(username + ":" + password)));
webClient.DownloadFile(dwlUrl, dwlFileName);
}
Exception:
System.Net.WebException was caught
HResult=-2146233079
Message=The remote server returned an error: (403) Forbidden.
Source=System
StackTrace:
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at TestProject.WebHelper.Download(String username, String password, String dwlFileName, String dwlUrl) in TestProject.WebHelper...
InnerException: null
Enviroment
Visual Studio 2012
NUnit 2.6.3
Any help would be much appreciated. Thanks! :)
EDIT
Have tried Nunit testrunner and resharpner test runner. Both fails.
I used wireshark to examine the the data sent. And found out there is one more call on the nunit test then the ms-test.
Until you answer the question, one thing to keep in mind is that the actual test runs under the process of the test runner. If the runner has some issues/restrictions those might interfere probably.
Do you have multiple tests that try to access that URL? In that case the server might have some security policies and will drop requests that might consider to be Denial of Service(too similar that come in too often).
Try adding a user agent header: webClient.Headers.Add("user-agent", "Other");

J2me application showing error in some mobile

i have a j2me application with web service stub.
it worked in some mobiles.
but in some mobiles "Application Error" comes up.
i tried creating package making versions MIDP 2.0 and CLDC 1.0(made stub for CLDC 1.0 also)
still it is showing "Application Error"
if I create the package without stub the application works properly.
The stub was generated using "Sun Java Wireless Toolkit 2.5.2 for CLDC"
can anyone help?
new Thread(new Runnable(){
public void run()
{
try {
MobiService_Stub ms = new MobiService_Stub();
resultBox.setString(ms.sendString( textbox.getString()));
}catch (JAXRPCException cnfe){
resultBox.setString("No connection found");
} catch (RemoteException e) {
// TODO Auto-generated catch block
resultBox.setString(e.getMessage());
}
}
}).start();
resultBox.addCommand(cmd_Cancel);
}
I have come up with "Application Error" messages when I try to run a Midlet that uses a JSR not available in that device. You should verify that the JSR or APIs you import are supported by your testing devices.

SQLite database verification after nhibernate schema generation

What is the simplest most effective way to verify that your SQLite db is actually out there after using NHib's schema generation tool?
Cheers,
Berryl
EDIT
I am hoping there is something tied to the ISession (like the connection property) that can be tested; sometimes when running a series of tests it seems like a good session (IsOpen & IsConnected are true) but the db is not there (a query against it gets an error like 'no such table').
EDIT - WHAT I AM DOING NOW
Connection string & other cfg properties
public static Configuration GetSQLiteConfig()
{
return new Configuration()
.SetProperty(ENV.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
.SetProperty(ENV.ConnectionDriver, typeof (SQLite20Driver).AssemblyQualifiedName)
.SetProperty(ENV.ConnectionString, "Data Source=:memory:;Version=3;New=True;Pooling=True;Max Pool Size=1")
.SetProperty(ENV.ProxyFactoryFactoryClass, typeof (ProxyFactoryFactory).AssemblyQualifiedName)
.SetProperty(ENV.ReleaseConnections, "on_close")
.SetProperty(ENV.CurrentSessionContextClass, typeof (ThreadStaticSessionContext).AssemblyQualifiedName);
}
How I test the db now, for lack of something 'better' (this tests the mappings)
public static void VerifyAllMappings(ISessionFactory sessionFactory, ISession session)
{
Check.RequireNotNull<ISessionFactory>(sessionFactory);
Check.Require(session.IsOpen && session.IsConnected);
_verifyMappings(sessionFactory, session);
}
private static void _verifyMappings(ISessionFactory sessionFactory, ISession session) {
try {
foreach (var entry in sessionFactory.GetAllClassMetadata())
{
session.CreateCriteria(entry.Value.GetMappedClass(EntityMode.Poco))
.SetMaxResults(0).List();
}
}
catch (Exception ex) {
Console.WriteLine(ex);
throw;
}
}
public static void VerifyAllMappings(ISessionFactory sessionFactory, ISession session)
{
Check.Require(!sessionFactory.IsClosed);
Check.Require(session.IsOpen && session.IsConnected);
try {
foreach (var entry in sessionFactory.GetAllClassMetadata())
{
session.CreateCriteria(entry.Value.GetMappedClass(EntityMode.Poco))
.SetMaxResults(0).List();
}
}
catch (Exception ex) {
Debug.WriteLine(ex);
throw;
}
}
I generate the schema in a session provider whenever a new session is opened:
public ISession Session
{
get
{
var session = (ISession)CallContext.GetData(_lookupSessionKey);
try
{
if (session == null)
{
_log.Debug("Opening new Session for this context.");
session = FactoryContext.Factory.OpenSession();
if(RunTypeBehaviorQualifier != RunType.Production)
SchemaManager.GenerateNewDb(FactoryContext.Cfg, session.Connection);
CallContext.SetData(_lookupSessionKey, session);
}
}
catch (HibernateException ex)
{
throw new InfrastructureException(ex);
}
return session;
}
}
Now this is all probably way over engineered, but I need multiple database connections and I've been having trouble keeping it simpler & working. It's also a lot of info for one question, but maybe someone else has actually got this all down to a science. The test below runs fine within it's own test fixture, but not in conjunction with other tests.
[Test]
public void Schema_CanGenerateNewDbWithSchemaApplied()
{
DbMappingTestHelpers.VerifyAllMappings(_dbContext.FactoryContext.Factory, _dbContext.Session);
}
Berryl,
As far as I can see you're strugling against mapped entities because you are using different connections. Is there any requirement that obligates you to use more than one "real" DB connection? I mean, can your tests share the same session (logically)? If not, you can simply configure your DB as:
<property name="connection.connection_string">Data Source=NonTransactionalDB.txt;Version=3;New=True;Pooling=True;Max Pool Size=1;</property>
The important part of it are the pooling options. As every session will aways use the same connection, you won't have problems with recreating the schema everytime.
It's important to remeber, though, that it introduces to you some limitations about transactions. As SQLite can't handle more than one transaction per connection, running your tests in parallel can bring you problems (something like a "database file is locked" Exception").
Cheers,
Filipe
Berryl, just to make it easir to visualize, I'll post as another answer. Feel free to give me another up if it helps you. :)
Below is the code that I use to check if my NH configuration object was properly configured.
// assert: verify some properties just to see if connection properties were applyed ane entities mapped
Assert.AreEqual<string>(cfg.Properties["connection.connection_string"], #"Server=localhost;Initial Catalog=MoveFrameworkDataNHibernate;User Id=sa;Password=sa");
Assert.AreEqual<string>(cfg.Properties["dialect"], "NHibernate.Dialect.MsSql2000Dialect");
Assert.IsNotNull(cfg.GetClassMapping(typeof(MappedEntity)));
Sincerely, I don't fell safe too that the DB is available checking the configuration object, but that's a way to know: yeah, my entities are there and I'm pointing to the right DB.
I understand that you are afraid of using a second SQLite connection and the DB was exposed in a previous one, so you will get undesired exceptions, but as far as I can see, the only other option to check if your entities are there would be something like the code below. As it refers to the SessionFactory, though, it helps nothing more than the previous option.
tx.Session.SessionFactory.GetClassMetadata(typeof(MappedEntity)) != null
The last option that I can think, in this case, would be to execute a SQL directly to your DB with an EXISTS check. I don't know how agnostic the EXISTS command is between ALL DBs implementations, but to a simple check like we're talking here it shouldn't be a big problem.
Hope this helps!
BTW: it's jfneis. Neis is a surname. Nothing to do with fries, french fries or something like. :)
Cheers.
Filipe