Starting an embedded Cassandra instance for Unit tests - unit-testing

I need to start a Embedded cassandra instance to perform some operations on a Cassandra keyspace via Unit tests. Programming Language is Java. What are the options to start an embedded cassandra?
I used the mojo maven plugin, however after starting the instance using following command, I do not see the cassandra instance started at default port 9042 on localhost.
Plugin:http://www.mojohaus.org/cassandra-maven-plugin/usage.html
Command to start: mvn cassandra:run -Dcassandra.nativeTransportPort=9042
Is there something missing in terms of usage or do I need to use something different?
Thanks
Jyothi

It depends on what you are trying to test. Cassandra Maven Plugin (of which I was one of the original authors) and Cassandra Unit both do something very similar in that they start an in-JVM instance of Cassandra.
This works great if you just want to do some CRUD stuff in you integration tests, but really does not help if you want to test scenarios like consistency level failures and retries in the face of various failure cases, particularly for multiple datacenters. And Cassandra is just a beast at this point so it means you need a lot of memory for you tests to run.
To really verify things like the above, I recommend using Simulacron:
https://github.com/datastax/simulacron/blob/master/doc/java_api/README.md
And an example integration:
https://github.com/datastax/java-driver/blob/9f0d89799a8a1e4cd1022dd7c43333924c36a648/integration-tests/src/test/java/com/datastax/oss/driver/api/core/ProtocolVersionMixedClusterIT.java
This is what the driver teams use to test behavior scenarios, though they still rely on a CCM test bridge (also an option) for a lot of block and tackle stuff. For both, the way it's plumbed into maven in that project should be used as an example of best practices:
https://github.com/datastax/java-driver/blob/3.x/pom.xml#L749-L816
And profile switching for such:
https://github.com/datastax/java-driver/blob/3.x/pom.xml#L925-L947
And using the profiles:
https://github.com/datastax/java-driver/blob/3.x/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java#L146
To really get your head around it, I recommend pulling down the driver project and picking it apart to see how this is all put together. Probably the biggest win is that this whole project does not have any dependency on Cassandra code.

We use Cassandra unit for unit tests. This library provides useful helpers and allows to start Embedded Cassandra from code very easy
EmbeddedCassandraServerHelper.startEmbeddedCassandra();

You can also take a look at https://github.com/nosan/embedded-cassandra/wiki
e.g. If you want to start Cassandra using JUnit4 you can do this in one line:
public class CassandraRuleTests {
#ClassRule
public static final CassandraRule cassandra = new CassandraRule(CqlScript.classpath("init.cql"));
#Test
public void testMe() {
}
}
Cassandra will be forked as a separate process. You can also set path to JAVA_HOME 8 via javaHome property in case if you use java 9 and higher.

You will need to provide the below configuration to cassandra-maven-plugin to start native transport port (9042)
<startNativeTransport>true</startNativeTransport>
So your plugin will looke like
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cassandra-maven-plugin</artifactId>
<version>3.6</version>
<configuration>
<startNativeTransport>true</startNativeTransport>
</configuration>
</plugin>

Related

Detect leiningen test mode

Is there a not too dirty way to detect at runtime, whether the code was started with lein test? I just want to select a different redis database, so solutions like environ or using different resource files seem to be a bit overkill.
For example, leiningen automatically enables the test profile, but I haven't found a way to get a list of currently enabled profiles.
There is no simple way to do it. Neither lein.test nor clojure.test expose such information. Even if you find a way to hack into some private var of lein test or clojure.test and check it to determine if your code is run as part of lein test.
However, it would have a very big issue: your production code would need to require testing library code (e.g. clojure.test) or even worse your build tool code (lein test plugin code).
You might try to define such configuration var (dynamic or not) in your production code and set it in your tests using fixtures.
The best solution would be to configure your application dynamically based on the external variable like system property or environment variable (e.g. by using suggested environ). This way you can have as many different configuration sets as you need (e.g. prod vs unit test vs integration test vs performance tests and so on) and not just two (prod vs test).
It might seem like overkill, but component for instance is invented for exact usecases like this. Or dependency injection in general.
I know that feeling, it's just a private project, no need for difficult stuff etc. Thats why I put together my own template so that all I need to get started is run lein new ...
This is my solution to circumvent the "just want to select a different redis database" usecases.
Edit It is a template for a web framework: https://github.com/sveri/closp but a lot of these parts are not specific to web dev, especially the components part: https://github.com/sveri/closp/tree/master/resources/leiningen/new/closp/clj/components
There is also an integration test where I make use of test components specifically: https://github.com/sveri/closp/blob/master/resources/leiningen/new/closp/integtest/clj/web/setup.clj
I found a way with Cprop. Set a var in your "env/{test|prod|test}/config.clj" file:
(System/setProperty "lein.profile" "dev")
then you can read the value:
(require '[cprop.source :as source])
(str "from-system-props: >> " (:lein-profile (source/from-system-props)))
other option is to search for the key ":conf" in the system-props:
:conf "test-config.edn"
because the config file changes according to the profile.

Distributing unit testing across virtual machines

I've spent the last few days looking around for an existing solution to a functional testing problem, but I am out of ideas and would appreciate some SO help!
I've got a preexisting suite of functional networking tests currently written in C++ using Boost.Test and Google Test, but might become rewritten into Rust soon. These generally take the following form:
unit test fixture {
1. Start a thread representing "the server" which goes and listens on some localhost port for incoming network connections.
2. Do client stuff representing "the client" to that localhost port.
3. Join the server thread, fetching an errors or problems.
4. Exit with success or failure.
}
This is great, and it works well. However it only tests loopback and in the real world the server component is probably in its own process running behind a NAT routed network, so it's not particularly realistic and therefore not really testing the code. What I think I'm looking for is some method of splitting the server thread part off into its own process, and then some method of getting the server test process and the client test process to work together to run the functional tests. Ideally speaking the server and client processes would run in separate "machines", this is something I can automate using OpenVZ scripting fairly easily so consider that problem out of scope, though it makes forking the process non-ideal.
I had been thinking that in this age of Web 2.0 et al surely this is a very common functional test scenario, and therefore that established patterns and test frameworks would abound. I mean, I as an old timer thinks "DCOM" as my first thought on how to solve this, though that's a 1990s Microsoft only solution. And maybe there is some modern and portable equivalent, and I am not searching for the right terms here, so here is my first question:
Is there any standard functional testing library or framework which extends Google Test or Boost.Test etc which lets you easily choose at runtime whether the server and client parts of each functional test should run as threads or as processes or best of all, as processes inside their own virtual machine with its own network stack?
This test scenario is surely common as muck. But let's assume it isn't, and no such tool exists. If it doesn't, then we need to extend Boost.Test or Google Test with some extra support. Firstly, we need to associate with each test fixture a supporting "server" part test fixture, and for the threaded test scenario we need to always run the server and client test fixtures concurrently. So, my second question:
Is there any way of strongly associating two test fixtures in any of the popular C++ or Rust unit testing frameworks where the two fixtures are seen as two halves of the same test, and always executed concurrently?
This leaves the second part: how to get a unit test framework to execute only the client parts in one process and only the server parts in the other process, and to do both always concurrently and in sync with one another, and moreover to merge the junit XML output from both parts into a single test result. So:
Is there any alternative functional testing approach, methodology, or open source solution which is better suited for distributed network functional testing than unit test frameworks such as Google Test or Boost.Test? Preferably something libvirt aware so it can orchestrate virtual machines as part of the testing setup and teardown? For example, is there some Jenkins plugin or something which could use Jenkins slaves in each OpenVZ container to orchestrate the concurrent execution of the multiple parts of each of the functional tests? Or is old fashioned CORBA still the least worst solution here? Is there maybe some way of automatically wrapping up test fixtures into a REST HTTP API?
I did do a quick review of the major integration testing frameworks, so Citrus, STAF and Twister. I'll be honest in saying they all seem way overkill for what I want which is a quick and easy way of making the existing functional test suite use a more realistic network routing than loopback. That's all I really want essentially, and I don't care how it's done so long as the check and requires still appear in Jenkins. Over to you Stackoverflow!
My thanks in advance for any help.
I have had similar requirements but I am come from the Java side of the world. What you can easily do is having a distributed management of nodes / machines using jGroups.
Once you understand how it works you can build a distributed system of nodes by just using 100 lines of code. With this system you can span and control child processes on each of those systems and check output and everything yourself. Should only cost you a day to take a jGroup example and get this running.
Once you have the infrastructure copy code and execute it as independent process your control is easy. Then use some of those nodes and get Selenium up and use a number of browser windows and execute scripts (or use Sikuli) and do your testing. Since the Selenium process is again Java you can generate all kind of reports you print to console or send directly to the cluster since those processes can join the cluster using jGroups too.
Such a system can be implemented in a week and it is really under your control. Very simple to do and very extendable.
Also you can provide plugins for Jenkins, Jira or Quality Center to interact with it and trigger test execution and management.

CQ - Writing Server-side JUnit tests

I've been trying to write a JUnit test case for one of my Java class which creates a page with some given properties in CQ. For it, it need to get reference of SlingRepository and ResourceResolverFactory. I was using this to get an idea on how to achieve this. In the document it says that a POST to "http://$HOST:$PORT/system/sling/junit/" path is used to execute tests on server side. But in CQ I get a 404 error for this path.
Is there any alternative URL in CQ for this? Or will really appreciate if anyone can suggest a better approach?
Thanks
One approach is to use a Sling test runner to execute the JUnit tests via a browser. This is the approach you are mentioning. We had to first install the code in this JAR (org.apache.sling.junit.core) to add the code that allows the URL you listed to work. Once that code is there, this URL will allow you to run tests using the test runner's built in page to run/display tests: http://localhost:4502/system/sling/junit/). My team did this for a while, but we soon moved to a different approach--using the Intellij IDE to develop the Java code for CQ and write the JUnit tests, then executing them within the IDE using the built-in JUnit test runner. The same approach works in Eclipse. For our team this approach was superior because it allowed developers to remain in context in the IDE without having to switch to a browser to run the tests.
The key is being able to resolve the references to classes that are installed/available via CQ, such as the SlingRepository and ResourceResolverFactory classes--and other stuff we commonly used, such as the Resource, ResourceResolver, Node, and Session classes. We use a CQ extension (http://helpx.adobe.com/experience-manager/kb/HowToUseCQ5AsMavenRepository.html) to allow our CQ instance to act like a Maven repository. This allows us to export the CQ JARs so we can then reference them as dependencies in the Java projects we create whenever we may need to use some of the classes available via CQ itself.
Once we set up the project dependencies, then we were able to write code--and corresponding unit tests--within the Intellij IDE. We were able to run the tests within the IDE, allowing developers to remain in context and work on the code that will run in CQ just like they work on any Java code (including things like running tests in debug mode or with code coverage, running single tests, running all tests in a class, using keyboard shortcuts to kick off tests, etc.). For us this approach had many advantages over the browser-based Sling test runner, so I recommend this approach.
Some potential considerations:
Exporting from CQ as a Maven repo may not be the best performance--you may want to add things to your own Maven repo for faster access
You may want to script some of the steps so adding project dependencies is not a manual process, but rather is something done via an automated process
You could even export all CQ JARs--or add some scripting to parse out and repackage only the public classes--and make any CQ class available to your Java projects

Unit testing installation of services

Our installer program is going to be installing a number of system services, under both Windows and UNIX, using JavaServiceWrapper. There will be a class responsible for creating JavaServiceWrapper config files, installing the services, etc.
Can I have some suggestions on how to unit-test this class?
I would not struggle too much with unit testing such a class, rather I would go for integration / smoke tests. You need these anyway to verify that your installation works properly - preferably not only on your own machine, but also in the target environment, in real life, before you are about to demonstrate it to your boss and most important client :-)
Update: I assume that the class in question would not contain much complicated logic, rather just gluing together different pieces supplied by other APIs. However, if this is not the case, and you feel you can't easily test a significant part of its functionality via integration tests, you can still try unit testing with good ol' mocks and/or dependency injection.
Lol! Found this last night. Environmentally Friendly Deployment. I really think as more complex your deployment, the more you need to validate your environment.

How do you get up and running with a build server?

I think everyone here would agree that in order to be considered a professional software house there are number fundamental things you must have in place.
There is no doubt that one of these things is a build server, the question is, how far do you need to go.
What are the minimum requirements for the build server? (Somewhere to just compile?)
What is the ultimate goal for your build server? (Scheduled, source control integration, auto deployment to test / live servers)
Where is a good place to start assuming you have nothing at the moment?
It would be great if we could list out a few simple tasks that an amateur developer could take on board in order to set them on the right track to a fully functional build server.
It would also be good to hear about people that feel they have a "complete" system setup that performs all the functionality they require and how they went about setting it all up from scratch.
You can start by looking into Cruise Control.
There's also CruiseControl.net if that's your poison.
Essentially though, you need the following ingredients:
A dedicated environment (Virtual Machine/server. Don't use a developer's machine, unless it's just you. Even then, run a VM if you can. Much easier to move it to a server when/if one becomes available in your organisation)
A source control system that supports labelled/tagged revisions (for example, Subversion+TortoiseSVN)
Build scripts. These can be batchfiles that start the devenv.exe or msbuild.exe applications with a command line, or you can use something like Ant or NAnt.
In this scenario, CruiseControl acts as the Continous Integration server, and can make sure that you have builds done as you check in your code. This means you know whether the build is broken quicker than if you just had nightly builds. You should probably also have nightly builds, though.
Hudson is a great CI.
We run farm locally, but we started by downloading hudson.war and doing
java -jar hudson.war
It integrates with SCM, bug trucking systems it is really awesome.
You'll need some disk space if you want to keep old build.
Enjoy it is most straightforward CI solution so far.
HTH,
Hubert.
If you're using Cruise Control, the place to start is an Ant build.xml that does the job manually.
You need a version control system that can do labeled check-outs.
You need JUnit tests to run using the Ant task and generate HTML reports.
Id say you'd have to start by implementing a build strategy so you can build your code in a structured way - I use NANT.
For a basic build server - use one of the CI offerings out there that monitors your source control and triggers a build whenever a change is detected. eg: cruiseControl.
Once you get the basic build together - add the running of your unit tests after a successfuly build.
The most successful system i've had in place had 3 different builds :-
- one that fired on a check in - all this did was build the code.
- an on demand one that would build the application, generate the installer and then put
the installer into a shared drive for the testers to pick up
- a daily build that fired at 10pm. This:
- ran some code generation to build DB and C# code from a UML model
- build the code
- created a new build verification test user on a test oracle instance
- ran the application schema into the db
- fired off a bunch of unit tests
- cleaned up the db user (if the tests were successful)
- ran coverage analysis to build a report of the unit code coverage
Software we used for this was NANT, CruiseControl.NET, a custom code generation system, custom app to build an oracle schema, and NCover for the code analysis.
Start by having a read of Martin Fowler's excellent paper on Continuous Integration.
We built such a system for a major project >2,000 kSLOC and it proved itself to be invaluable.
HTH
cheers,
Rob
Cruise, Maven, Hudson etc are all great but its always worth having a stopgap solution.
You should have a batch file, shell script or simply written instructions that will allow you to run a build from any machine. We have had build servers unavailable in the past and the ability to switch quickly to another machine was invaluable!
The spec of the build machine need not be important unless you have a monster project. We try and keep our build times down to 10 minutes (including unit tests) and we have a pretty big project.
Don't be tempted to create or write your own build system because "none of the tools out there are good enough". All modern build systems allow you to write plugins to do custom stuff.
I'm using Cruisecontrol.NET and an msbuild buildscript.
I can use the buildscript manually so that I can get the latest version of the codebase, built the codebase very easily using the commandline. (This is very interesting if you are working on an application that consists of multiple solutions).
Next to that, my CruiseControl.NET buildserver uses this buildscript as well. It checks on a regular interval if there have been changes committed to the source-control.
If that happens, CC.NET performs the 'get-latest' task that I've defined in the buildscript, builds everything, executes unit-tests and performs a statical code analysis (fxcop).
My 'buildserver' is just an old workstation. It's a PIV, 3Ghz with 1gb RAM, and it does its job perfectly.
One additional thing that I would find interesting, is to have the ability to automatically deploy a new version, or build a setup.
I haven't done that yet, since I'm not sure whether it is a good idea, nor have I found a good strategy yet to do so ...
I mean; is deploying a new version of some components into production for a mission-critical application a good idea ? I don't think so ...
I think this is a good place to start:
[http://confluence.public.thoughtworks.org/display/CC/Home;jsessionid=5201DA7E8D361EB164C40E519DA0F0DE][1]
At least, that's where I started looking when setting up my build server. :)
[1]: Home of CruiseControl
Roughly in order - minimal/least sophisticated through more sophisticated
able to get a specific set of source onto any machine
able to build that source (with no problems)
able to (schedule) build each night/or some other defined period with no user intervention
One (or more) dedicated build server (not shared as qa or dev machine)
able to do a build after each check-in/commit
Notify interested parties of the build status after a build
Provide build status at any time
Create installers as part of the build
ability to deploy/live if build is good
Run unit tests
Run tests on the product
Report the results of those tests
Static code analysis and reporting
...
And the list goes on and on
Don't be afraid to just start with batch files or shell scripts or other ad-hoc means. People made perfectly good software before the CI craze. there were plenty of good processes before Hudson and Cruise Control - ( I am not knocking those or others - I use Hudson among others) - but don't miss the point - these things are here to help you - not become overbearing process)
I couldn't give you all the details about how we set our build server up (I was only involved at the start), but:
We started with an in-house system, implemented in ASP.NET and a .NET Windows Service, using NAnt to do the actual builds. Actually, most of the workflow was implemented in NAnt (e.g. emailing people, copying stuff around, etc.).
We moved to JetBrains TeamCity (there's a free cut-down version available), which is still serving us well.
We use it for builds triggered by a commit: these just build the binaries and run the unit tests. From here, we can do a complete build, which does the MSI as well. From there, we have system test builds that run more in-depth tests, across an environment built with virtual machines (with a separate domain controller, SQL Server box, etc.). When the system tests pass, the build is made available to our QA department for manual testing and some regression tests that we've not automated yet.
In the java space I've tested most of the available build environments. The issue with automatic build is that you quite often end up spending a fair amount of time following it up. After we switched to the commercial bamboo from atlassian, we found that we have to spend a lot less time pampering the build box, which in our case turns out to be very good economy. Bamboo also supports clustering, so you can add inexpensive boxes as needs evolves.
Try & find something that fits in with your existing practices in terms of building - e.g. it's not going to be a good fit to try & use an Ant-based buildserver if you're using Maven, for instance!
Ideally, it should just be able to monitor your source-control system, checkout the code, build, run some tests & publish the results without you being aware of it, or at least not 'till it's reporting a failure. Personally, I'd suggest Hudson (https://hudson.dev.java.net/) as a good starting point as it's easy to get installed & running & has a decent UI.
We start by writing batch scripts that will run on the developers machine. Once we have all the processes automated, we move them to the build server.
On the tools side we are currently moving from Cruise Control to TFS.