How to debug Solr plugin? - java

I have written a search component to be used with SOLR. I want to debug it. I tried debugging the SOLR itself using remote debugging feature of eclipse but it doesn't work for plugin and shows source not found.
Then I tried including my plugin project as source project but that did not work either. The debugger doesn't stops at breakpoints for plugin.
Any help in this regard shall be greatly appreciated!

You can write a Junit test in your eclipse project using an embedded solr. This makes debugging easier. All you need to do, is to create the config files for the solr-core (solrconfig.xml, schema.xml, etc.; you could probably copy the solr core dir from your solr installation) in your test resources directory and point the CoreContainer to that directory. This core container can be used to get the configured solr core and your searcher.
JUnit and Solr-core are the dependencies needed.
Below is an example of the test-code:
/**
* This is a starting point for testing the component with embedded solr!
*/
public class SearchComponentTest
{
private static CoreContainer container;
private static SolrCore core;
private static final Logger logger = LoggerFactory.getLogger(DataImportRequestHandlerTest.class.getName());
/*
* PREPARE AND TEAR DOWN FOR TESTS
*/
#BeforeClass
public static void prepareClass() throws Exception
{
// create the coreContainer from conf dir in test resources
container = new CoreContainer(
DataImportRequestHandlerTest.class.getResource("/solrDir").getPath().substring(1));
container.load();
core = container.getCore("CORENAME");
logger.info("Solr core loaded!");
}
#AfterClass
public static void cleanUpClass()
{
core.close();
container.shutdown();
logger.info("Solr core shut down!");
}
/* TESTS TO RUN */
/**
* Test the search component here or just trigger it to debug
*/
#Test
public void testSearchComponent()
{
/* PREPARE */
SearchComponent mySearchComp = core.getSearchComponent("componentNameFromSolrConf");
/* RUN */
// do something with your search component
/* CHECK */
// check results with asserts :)
}
}

Related

Unit testing: Entry name 'res/layout/test_toolbar.xml' collided

I've tried to do some unit test example that included in an Android Studio project like ExampleInstrumentedTest and ExampleUnitTest, so the result is :
Entry name 'res/layout/test_toolbar.xml' collided
I've searched everywhere on google but there's not answers to this specific problem, so any help will be grateful
here's the source of the basic unit test example :
ExampleUnitTest
* Example local unit test, which will execute on the development machine (host).
*
* #see Testing documentation
*/
public class ExampleUnitTest {
#Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}}
ExampleInstrumentedTest
* Instrumented test, which will execute on an Android device.
*
* #see Testing documentation
*/
#RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
#Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getContext();
assertEquals("com.example.abder.emarque", appContext.getPackageName());
}}
I just did the following and It solved my problem.
Invalidate caches and Restart (File -> Invalidate Caches / Restart)
Clean Project (Build -> Clean Project)
This happens due to same xml may be included in third party SDKs.
Solution: exclude 'res/layout/test_toolbar.xml' in packagingOptions of app's build.gradle file.
packagingOptions { exclude 'res/layout/test_toolbar.xml' }

NetBeans : JUnit no tests executed

So I'm getting this persistent error using netbeans. I've got a LinkedList class which I am testing via a JUnit test, which I created by clicking on LinkedList.java: Tools -> Create/Update Tests and this LinkedListTest.java class is now located in test packages.
My LinkedList.java file works correctly when tested in a file with a main method.
public class LinkedListTest {
#Test
public void testAddFirst() {
LinkedList linkedList = new LinkedList();
Country c1 = new Country("Australia");
linkedList.addFirst(c1);
assertEquals("Australias", linkedList.getValue(0)); // Should fail a test
} // default test methods beneath
All my imports check out. JUnit 5.3.1 and I had to download apiguardian1.1.0.jar from MVN repository to clear an error for:
reason: class file for org.apiguardian.api.API$Status not found
I right-click in this file and select Test File, or use Ctrl+F6, I've selected Test File from the original LinkedList file, I've even used Alt+F6 which tests the whole project. Yet I'm met with 'No tests executed.', an empty Test Results window, and no Notifications. What am I doing wrong?
Thanks for any help
Edit: I just switched from netbeans to eclipse.
You forget to extend Runner with class --
use like below with class -
public class LinkedListTest extends Runner {
}
Hope this help you.

Does Maven offer hooks at the very beginning of runtime

Say we are running mvn test.
I am wondering if there is a way to configure Maven to run some files before executing tests. In my case, I want to configure a library, but don't want to have to configure this library for every entrypoint in my app/tests. I am just looking to configure the lib for every mvn lifecycle hook which invokes a runtime.
Something like this:
#MavenRuntimeLifecycle
public class Whatever {
public void runtimeBegin(){
// right when the java process starts up
Mylib.configure("foo");
}
public void runtimeEnd(){
// right before the process shuts down
}
}
I assume this would be a Maven specific thing - not that it has to be in the same Java process as my server or tests etc.
Note that using Node.js, I would simply do it like so:
export class MyLib {
isConfigLoaded = false;
static loadConfig(){
// ...
}
static void run(){
if(!this.isConfigLoaded){
MyLib.loadConfig(require('../some/path/to/.mylib.config.js'));
this.isConfigLoaded = true;
}
this.doTheThing();
}
}
I could do the same thing with Java or Maven project, and just store a .java file in the resources directory. It's more manual, but it could be done.

WatchService not working in integration tests

I have a scala class which uses the java nio WatchService to detect creation of new folders in a specific directory.
The WatchService works well when the app is running and I manually copy a folder into the target folder.
I have created a unit test using scalatest that initializes my class and copies a test folder into the target folder using Apache Commons
FileUtils.copyDirectory(testFolder, new File(targetFolder, testFolder.getName), false)
The watch service does not detect any new entry created in the target folder within 30 seconds. My code is inside an eventually block similar to
eventually(timeout(Span(30, Seconds)), interval(Span(1, Seconds))) {
// CHECK IF THE SERVICE DETECTED THE NEW ENTRY
}
Any idea why this does not work in unit tests?
Just discovered the problem was in the way I used scalatest. I was trying to use a fixture to open/close my service in the features boundaries:
describe("The WatchService") {
withWatchService { watchService =>
it("should test feature 1") { /* test code here */ }
it("should test feature 2") { /* test code here */ }
}
}
The code above does not work: the watch service is closed before the features are completed. To make it work I have created a unique feature with the fixture nested inside it:
describe("The WatchService") {
it("should test features") {
withWatchService { watchService =>
/* test code here */
}
}
}

How to run tests against Neo4j with custom unmanaged extension?

I have my own custom-written unmanaged extension for Neo4j database.
I want to run integration tests againt fully-functional database, with unmanaged extension available there.
Neo4j provides tool called neo4j-harness that makes it easier to write integration tests for unmanged extensions. More iformation is available here.
Blog post
1) Determine Neo4j version that is needed (used).
Maven:
<properties>
<version.neo4j>2.2.5</version.neo4j>
</properties>
2) Add dependency for neo4j-harness.
Maven:
<dependency>
<groupId>org.neo4j.test</groupId>
<artifactId>neo4j-harness</artifactId>
<version>${version.neo4j}</version>
<!-- If you want to use Neo4j server in sources, instead of tests, then remove this line -->
<scope>test</scope>
</dependency>
3) Be sure that you unmanaged extension sources is available in tests.
Maven:
If you write tests into same module with extension, then everything is OK.
If you write tests in seperate module (i.e. integration-tests), then make sure that extension is available there.
<dependency>
<groupId>my.company</groupId>
<artifactId>unmanaged-extension</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
4) Create Neo4jTestServer class that is responsible for database start-up and shutdown.
/**
* Spin-up Neo4j server with loaded unmanaged extension.
*/
public final class Neo4jTestServer {
public static final String EXTENSION_MOUNT_POINT = "/ext";
public static final String EXTENSION_RESOURCES = "my.company.extension.resources";
// Alternative way to get package
// public static final String EXTENSION_RESOURCES = SomeResource.class.getPackage().getName();
private static Neo4jTestServer INSTANCE = null;
public static synchronized Neo4jTestServer getInstance() {
if (INSTANCE == null) {
INSTANCE = new Neo4jTestServer();
}
return INSTANCE;
}
private final ServerControls serverControls;
private Neo4jTestServer() {
serverControls = TestServerBuilders.newInProcessBuilder()
.withExtension(EXTENSION_MOUNT_POINT, EXTENSION_RESOURCES)
// Resource can be specified directly
// .withExtension(EXTENSION_MOUNT_POINT, SomeResource.class)
.newServer();
}
public ServerControls getServerControls() {
return serverControls;
}
public void shutdown() {
serverControls.close();
}
}
Usage:
Neo4jTestServer server = Neo4jTestServer.getInstance();
// Get Neo4j server URI, with port
server.getServerControls().getHttpUri();
// Shutdown server
server.shutdown();
Notes:
SomeResource is JAX-RS resource that provides custom functionality
If you have more than 1 resource, and want to use class to specify unmanaged extension, instead of string - there is no need to specify all thoose classes. Neo4j will scan specified class package for other resources and load them automatically.
All resources should be in same package
Tip: You can create ResourcesRootPackageMarker class in same package, where all resources reside and use this class to specify package. It makes code more resilient to future code refactorings.
5) Optional. Specify JVM shutdown hook to shutdown database.
final Neo4jTestServer server = Neo4jTestServer.getInstance();
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
server.shutdown();
}
});
6) To verify that everything is working and your unmanaged extension is available - execute tests, start database and examine output generated by Neo4j server.
You should see something like this:
INFO: Scanning for root resource and provider classes in the packages:
my.company.extension.resources
Sep 14, 2015 5:25:15 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
class my.company.extension.resources.SomeResource
class my.company.extension.resources.AnotherResource
EDIT: Graphaware test framework, information provided by MicTech
Alternatively, there is GraphAware Test framework provided by graphaware, that gives possibility to test any Neo4j-related code.
This module provides means of easily testing code that talks to the Neo4j database in one way or another. The target audience of this module are Java developers who write Neo4j-related code, as well as authors of GraphAware Modules and APIs.
Here you can find some posts about how framework can be used (autored by Graphaware developers).
Basically what you need to do is:
1) Create extension:
#Path("/helloworld")
public class HelloWorldUnmanagedExtension {
private final HelloWorldNodeCreator nodeCreator;
public HelloWorldUnmanagedExtension(#Context GraphDatabaseService database) {
nodeCreator = new HelloWorldNodeCreator(database);
}
#POST
#Path("/create")
public Response createHelloWorldNode() {
Node node = nodeCreator.createHelloWorldNode();
return Response.ok(String.valueOf(node.getId())).build();
}
}
2) Extend your test with WrappingServerIntegrationTest and necessary configuration.
public class HelloWorldUnmanagedExtensionApiTest extends WrappingServerIntegrationTest {
#Override
protected Map<String, String> thirdPartyJaxRsPackageMappings() {
return Collections.singletonMap("com.graphaware.example.unmanaged", "/ext");
}
#Test
public void shouldCreateAndReturnNode() {
String result = TestUtils.post(baseNeoUrl() + "/ext/helloworld/create", 200);
assertEquals("0", result);
GraphUnit.assertSameGraph(getDatabase(), "CREATE (:HelloWorld {hello:'world'})");
}
}
Here can be found more detailed instructions on how to test unmanaged extension with Graphaware test framework.
Everything should be up-and-running now and ready for testing. Good luck!

Categories

Resources