java.lang.UnsatisfiedLinkError with Robolectric and Couchbase - unit-testing

I am unable to get started with using Robolectric unit tests because of the following error it has with couchbase db.
java.lang.UnsatisfiedLinkError: com.couchbase.lite.internal.database.sqlite.SQLiteConnection.nativeOpen(Ljava/lang/String;ILjava/lang/String;ZZ)J
This error is thrown in my CouchbaseWrapper class at syntax,
// Get existing db with that name
// or create a new one if it doesn't exist.
database = manager.getDatabase(dbname);
If I do database = manager.getDatabase(dbname, true);, then this step "passes" but other steps return NPE.
Here is my testcase:
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class)
public class OnBoardingPageOneTest {
private OnboardingActivity onboardingActivity;
#Before
public void setUp() {
onboardingActivity = Robolectric.setupActivity(OnboardingActivity.class);
}
#Test
public void verifyElementsArePresent() {
assertThat(onboardingActivity.findViewById(R.id.text_container), is(not(null)));
assertThat(onboardingActivity.findViewById(R.id.intro_video_view), is(not(null)));
assertThat(onboardingActivity.findViewById(R.id.play_button), is(not(null)));
assertThat(onboardingActivity.findViewById(R.id.loading_progress), is(not(null)));
}
}
Log
Library not found: /native/osx/x86_64/libsqlcipher.dylib
Library not found: /native/osx/x86_64/libsqlite3.dylib
Library not found: /native/osx/x86_64/libsqlcipher.dylib
Library not found: /native/osx/x86_64/libsqlite3.dylib
java.lang.UnsatisfiedLinkError: com.couchbase.lite.internal.database.sqlite.SQLiteConnection.nativeOpen(Ljava/lang/String;ILjava/lang/String;ZZ)J
at com.couchbase.lite.internal.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at com.couchbase.lite.internal.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:194)
at com.couchbase.lite.internal.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:178)
at com.couchbase.lite.internal.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:461)
at

Related

Quarkus kubernetesMockServer for application initialization

I am working on a Quarkus application to acct as an Operator in a OpenShift/Kubernetes cluster. When writing the tests using a kubernetesMockServer it is working fine for REST calls to developed application but when code runs inside an Initialization Block it is failing, in the log I see that mock server is replying with a 404 error:
2020-02-17 11:04:12,148 INFO [okh.moc.MockWebServer] (MockWebServer /127.0.0.1:53048) MockWebServer[57577] received request: GET /apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions HTTP/1.1 and responded: HTTP/1.1 404 Client Error
On the TestCode I have:
#QuarkusTestResource(KubernetesMockServerTestResource.class)
#QuarkusTest
class TestAIRController {
#MockServer
KubernetesMockServer mockServer;
private CustomResourceDefinition crd;
private CustomResourceDefinitionList crdlist;
#BeforeEach
public void before() {
crd = new CustomResourceDefinitionBuilder()
.withApiVersion("apiextensions.k8s.io/v1beta1")
.withNewMetadata().withName("types.openshift.example-cloud.com")
.endMetadata()
.withNewSpec()
.withNewNames()
.withKind("Type")
.withPlural("types")
.endNames()
.withGroup("openshift.example-cloud.com")
.withVersion("v1")
.withScope("Namespaced")
.endSpec()
.build();
crdlist = new CustomResourceDefinitionListBuilder().withItems(crd).build();
mockServer.expect().get().withPath("/apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions")
.andReturn(200, crdlist)
.always();
}
#Test
void test() {
RestAssured.when().get("/dummy").then().body("size()", Is.is(0));
}
}
The dummy rest is using the same code for searching the CRD, and in fact when running withouth the class observing the startup event it works fine
#Path("/dummy")
public class Dummy {
private static final Logger LOGGER =LoggerFactory.getLogger(Dummy.class);
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response listCRDs(){
KubernetesClient oc = new DefaultKubernetesClient();
CustomResourceDefinition crd = oc.customResourceDefinitions()
.list().getItems().stream()
.filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
.findFirst().get();
LOGGER.info("CRD NAME is {}", crd.getMetadata().getName());
return Response.ok(new ArrayList<String>()).build();
}
}
Finally this is an except of the
#ApplicationScoped
public class AIRWatcher {
private static final Logger LOGGER = LoggerFactory.getLogger(AIRWatcher.class);
void OnStart(#Observes StartupEvent ev) {
KubernetesClient oc = new DefaultKubernetesClient();
CustomResourceDefinition crd = oc.customResourceDefinitions()
.list().getItems().stream()
.filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
.findFirst().get();
LOGGER.info("Using {}", crd.getMetadata().getName());
}
}
It's like for some reason the mock server is still not initialized for the Startup event, is there any way to solve it?
The problem is that the Mock Server is only configured to respond right before the test execution, while this code:
void OnStart(#Observes StartupEvent ev) {
KubernetesClient oc = new DefaultKubernetesClient();
CustomResourceDefinition crd = oc.customResourceDefinitions()
.list().getItems().stream()
.filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
.findFirst().get();
LOGGER.info("Using {}", crd.getMetadata().getName());
}
runs when the application is actually comes up (which is before any #BeforeEach runs).
Can you please open an issue on the Quarkus Github? This should be something we provide a solution for

IllegalArgumentException while running contract unit test in Kotlin (Corda)

When I try to run my Junit tests (Wrote in Kotlin) I get the following exception :
java.lang.IllegalArgumentException: Attempted to find dependent attachment for class javax/xml/bind/DatatypeConverter, but could not find a suitable candidate.
I tried to comment/decomment some lines in following code, it seems that the exception occurs when I call command()
class IRIssueTests {
class DummyCommand : TypeOnlyCommandData()
private val ledgerServices = MockServices(listOf("com.my.package.name"))
private val ALICE = TestIdentity(CordaX500Name(organisation = "Alice", locality = "TestLand", country = "US"))
#Test
fun mustIncludeIssueCommand() {
val ir = IRState(
UniqueIdentifier(),
mutableListOf(ALICE.party)
)
ledgerServices.ledger {
transaction {
output(IRContract.ID, ir)
command(listOf(ALICE.publicKey), DummyCommand())
fails()
}
transaction {
output(IRContract.ID, ir)
command(listOf(ALICE.publicKey), IRContract.Commands.Issue())
verifies()
}
}
}
}
I would like to understand why I'm getting this exception and how to resolve it to make my test passing
Kotlin tests must be run with JDK8.
Change configuration of JDK8 in your project before running tests.
This will avoid this exception

How to write single test runner for classes with different #RunWith()?

I wrote simple method that executes tests in my test classes: DataContainerTest.class, AnotherTest.class.
public static void main(String [] args) throws Exception {
Result result = JUnitCore.runClasses(DataContainerTest.class, AnotherTest.class);
System.out.println(result.getRunCount());
System.out.println("Total number of tests " + result.getRunCount());
System.out.println("Total number of tests failed: " + result.getFailureCount());
for(Failure failures : result.getFailures()){
System.out.println(failures.getMessage());
}
System.out.println(result.wasSuccessful());
}
This method doesn't work for my another class CommandsTest.class, where i'm using annotation #RunWith(PowerMockRunner.class). See output below:
1
Total number of tests 1
Total number of tests failed: 1
No runnable methods
false
Here is the sample of the CommandsTest.class
#RunWith(PowerMockRunner.class)
#PrepareForTest({Helper.class,
UtilsPlatform.class,
SessionManager.class,
DataContainerTest.class,
FieldObserver.class,
android.util.Log.class})
public class CommandsTest {
private static Commands2 commands;
private static License mockedLicense;
private static HSQL hsql;
#BeforeClass
public static void setUpStatic() throws Exception {
commands = new Commands2();
PowerMockito.mockStatic(UtilsPlatform.class);
PowerMockito.when(UtilsPlatform.isTablet()).thenReturn(true);
PowerMockito.mockStatic(android.util.Log.class);
PowerMockito.mockStatic(FieldObserver.class);
PowerMockito.doNothing().when(FieldObserver.class, "put", Mockito.anyInt(),
Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any(Session.class));
hsql = PowerMockito.mock(HSQL.class);
PowerMockito.when(hsql, "OnCaseOpen", Mockito.anyInt(), Mockito.anyInt(),
Mockito.anyInt()).thenReturn(false);
mockedLicense = PowerMockito.mock(License.class);
}
#Before
public void setUp() throws Exception {
PowerMockito.mockStatic(SessionManager.class);
PowerMockito.mockStatic(Helper.class);
PowerMockito.doNothing().when(Helper.class, "writeToFile", Mockito.anyString(),
Mockito.any(SocketException.class));
PowerMockito.when(Helper.class, "getLicense").thenReturn(mockedLicense);
PowerMockito.doNothing().when(Helper.class, "fieldOpened", Mockito.anyString(), Mockito.anyString());
}
#Test
public void sendKeyCombinationEventTest_nullParameters_returnOne(){
Assert.assertEquals(1, commands.sendResponse());
}
#Test
public void sendKeyCombinationEventTest_registredGuisNotNullAndOneIsLocal_returnOne(){
Assert.assertEquals(1, commands.sendKeyCombinationEvent());
}
While pressing run button in AndroidStudio, all tests are passed but my own TestRunner cannot run tests in this class.
The best way to handle classes using #RunWith(PowerMockRunner.class) annotation is just put them into default test source of your android project and then run all tests via gradle test. You don't actually need to write own test runner.

Test execution in Spring Boot fails due to failed config load

I am trying to test my application and running into troubles:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = MainConfiguration.class)
public class ProductionDataRestClientTest {
#Test
public void testGetProductionDataAsync() {
}
}
The MainConfiguration class is as follows:
#Data
#Configuration
#Slf4j
#PropertySource(value = {
"classpath:/conf/application.properties", "classpath:/conf/application.build.properties",
"file:${configPath}/application.properties" }, ignoreResourceNotFound = true)
public class MainConfiguration {
#Value("${app.configName}")
private String configName;
#Value("${project.name}")
private String appName;
#Value("${project.version}")
private String appVersion;
#Value("${app.historySize}")
private int historySize;
#Value("${app.processOnlyVisibleEnvironments}")
private Boolean processOnlyVisibleEnvironments;
#PostConstruct
private void logConfig() {
appName = WordUtils.capitalize(appName);
log.info("constructed config: " + configName);
log.info(this.toString());
}
}
And the application.properties file is here:
app.configName=Internal Classpath
app.historySize=25
app.processOnlyVisibleEnvironments=true
client.timeout.connect=30000
client.timeout.read=30000
threading.pool.size.environmentProcessing=5
threading.pool.size.webServiceRequesting=10
My problem is, that Spring seems not to resolve the value identifiers as in normal executions, so the following stacktrace is thrown:
Caused by: java.lang.NumberFormatException: For input string: "${app.historySize}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.valueOf(Integer.java:766)
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:194)
at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:113)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:464)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:437)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:195)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:125)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:61)
... 47 more
I don't have any clue, I tried many different things, nothing worked.
Thanks in advance :)
There was a very simple way to solve this issue:
// To resolve ${} in #Value
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
This has to be a method of the loaded Configuration-file and helps resolving the placeholders.
Thanks for helping ;)

How to recreate closed client in Elasticsearch Unit Testing?

I have been using org.elasticsearch.test.ElasticsearchIntegrationTesting class for testing elasticsearch functionality.
I Use below code to import data into Elasticsearch and to search that data :**
#Test
public void searchData() throws Exception{
logger.info("searchData : searching data from Elasticsearch");
try {
csvImporter.client = client();
csvImporter.importData(); // In the importData method after data is imported we close the client
//In the below line getting Exception and it is inconsistent. Some times works fine
SearchResponse searchResponse = csvImporter.client.prepareSearch().setQuery(matchAllQuery()).execute().actionGet();
for (SearchHit searchHit : searchResponse.getHits()){
logger.info("Source Data >>>>>>>>>>>>>>>>>>>>> " + searchHit.sourceAsString());
}
} finally {
csvImporter.client.close();
}
}
Exception:
org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: []
at __randomizedtesting.SeedInfo.seed([86EB1B4AAE1739A5:99315B8D3D924DA1]:0)
at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:305)
at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:200)
at org.elasticsearch.client.transport.support.InternalTransportIndicesAdminClient.execute(InternalTransportIndicesAdminClient.java:86)
at org.elasticsearch.client.support.AbstractIndicesAdminClient.deleteTemplate(AbstractIndicesAdminClient.java:687)
at org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequestBuilder.doExecute(DeleteIndexTemplateRequestBuilder.java:40)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:91)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:65)
at org.elasticsearch.test.TestCluster.wipeTemplates(TestCluster.java:177)
at org.elasticsearch.test.TestCluster.wipe(TestCluster.java:76)
at org.elasticsearch.test.ElasticsearchIntegrationTest.beforeInternal(ElasticsearchIntegrationTest.java:292)
at org.elasticsearch.test.ElasticsearchIntegrationTest.before(ElasticsearchIntegrationTest.java:1946)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.carrotsearch.randomizedtesting.RandomizedRunner.invoke(RandomizedRunner.java:1665)
at com.carrotsearch.randomizedtesting.RandomizedRunner$9.evaluate(RandomizedRunner.java:898)
at com.carrotsearch.randomizedtesting.RandomizedRunner$10.evaluate(RandomizedRunner.java:914)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.apache.lucene.util.TestRuleSetupTeardownChained$1.evaluate(TestRuleSetupTeardownChained.java:50)
at org.apache.lucene.util.TestRuleFieldCacheSanity$1.evaluate(TestRuleFieldCacheSanity.java:51)
at org.apache.lucene.util.AbstractBeforeAfterRule$1.evaluate(AbstractBeforeAfterRule.java:46)
at com.carrotsearch.randomizedtesting.rules.SystemPropertiesInvariantRule$1.evaluate(SystemPropertiesInvariantRule.java:59)
at org.apache.lucene.util.TestRuleThreadAndTestName$1.evaluate(TestRuleThreadAndTestName.java:49)
at org.apache.lucene.util.TestRuleIgnoreAfterMaxFailures$1.evaluate(TestRuleIgnoreAfterMaxFailures.java:65)
at org.apache.lucene.util.TestRuleMarkFailure$1.evaluate(TestRuleMarkFailure.java:48)
at com.carrotsearch.randomizedtesting.rules.StatementAdapter.evaluate(StatementAdapter.java:36)
at com.carrotsearch.randomizedtesting.ThreadLeakControl$StatementRunner.run(ThreadLeakControl.java:367)
at com.carrotsearch.randomizedtesting.ThreadLeakControl.forkTimeoutingTask(ThreadLeakControl.java:809)
at com.carrotsearch.randomizedtesting.ThreadLeakControl$3.evaluate(ThreadLeakControl.java:460)
at com.carrotsearch.randomizedtesting.RandomizedRunner.runSingleTest(RandomizedRunner.java:873)
at com.carrotsearch.randomizedtesting.RandomizedRunner$5.evaluate(RandomizedRunner.java:775)
at com.carrotsearch.randomizedtesting.RandomizedRunner$6.evaluate(RandomizedRunner.java:809)
at com.carrotsearch.randomizedtesting.RandomizedRunner$7.evaluate(RandomizedRunner.java:820)
at org.apache.lucene.util.AbstractBeforeAfterRule$1.evaluate(AbstractBeforeAfterRule.java:46)
at org.apache.lucene.util.TestRuleStoreClassName$1.evaluate(TestRuleStoreClassName.java:42)
at com.carrotsearch.randomizedtesting.rules.SystemPropertiesInvariantRule$1.evaluate(SystemPropertiesInvariantRule.java:59)
at com.carrotsearch.randomizedtesting.rules.NoShadowingOrOverridesOnMethodsRule$1.evaluate(NoShadowingOrOverridesOnMethodsRule.java:39)
at com.carrotsearch.randomizedtesting.rules.NoShadowingOrOverridesOnMethodsRule$1.evaluate(NoShadowingOrOverridesOnMethodsRule.java:39)
at com.carrotsearch.randomizedtesting.rules.StatementAdapter.evaluate(StatementAdapter.java:36)
at org.apache.lucene.util.TestRuleAssertionsRequired$1.evaluate(TestRuleAssertionsRequired.java:43)
at org.apache.lucene.util.TestRuleMarkFailure$1.evaluate(TestRuleMarkFailure.java:48)
at org.apache.lucene.util.TestRuleIgnoreAfterMaxFailures$1.evaluate(TestRuleIgnoreAfterMaxFailures.java:65)
at org.apache.lucene.util.TestRuleIgnoreTestSuites$1.evaluate(TestRuleIgnoreTestSuites.java:55)
at com.carrotsearch.randomizedtesting.rules.StatementAdapter.evaluate(StatementAdapter.java:36)
at com.carrotsearch.randomizedtesting.ThreadLeakControl$StatementRunner.run(ThreadLeakControl.java:367)
at java.lang.Thread.run(Thread.java:745)
Since it is a Unit Testing I have not used configuration Settings to create client.
is there a way to recreate the client Object with same configuration settings??