Importing python module in c# using pythonnet - python.net

I noticed there are two different ways to import a python module in pythonnet in c#:
var testModule = PythonEngine.ImportModule("testModule");
and
using (Py.GIL())
{
var testModule = Py.Import("testModule");
{
What are the reasons for using one over the other?

Related

Androidx ServiceTestRule cannot find my service

To be fair, I am not testing the service, but am using a service as part of my test classes to test a Bluetooth library. So my test class needs to create a service that invokes the Bluetooth library. The test class then needs to bind to this service to perform the tests. However, attempting to start the service always gives me the following error which leads to a Nullpointer exception
W/ActivityManager: Unable to start service Intent { cmp=com.example.androidhdpadapter.test/com.lampreynetworks.ahd.oxp.transport.BluetoothTestService } U=0: not found
At this stage, the test class is very simple:
package com.lampreynetworks.ahd.oxp.transport;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ServiceTestRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.fail;
#RunWith(AndroidJUnit4.class)
public class AndroidServiceBluetoothAdapterTests
{
private final static String TAG =
AndroidServiceBluetoothAdapterTests.class.getName();
#Rule
public final ServiceTestRule serviceRule = new ServiceTestRule();
#Test
public void testAndroidBluetoothAdapter() throws TimeoutException, InterruptedException
{
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Intent intent = new Intent(context, BluetoothTestService.class);
serviceRule.startService(intent);
Thread.sleep(12000);
IBinder binder = serviceRule.bindService(intent);
BluetoothTestService service = ((BluetoothTestService.TestManagerBinder) binder).getService();
serviceRule.unbindService();
}
}
There are NUMEROUS posts regarding problems with testing services and I have tried all of them (messing with gradle.build file dependencies, conflicts between androidx.test and android.support.test, etc.). I have also tried invoking the service in the standard manner without ServiceTestRule, but that likely failed because there is no AndroidManifest for the test that specifies the service (I don't know if that can be done).
Maybe it is not possible to use Androidx's ServiceTestRule unless one is actually testing a service that is part of an application. Here I am testing a Bluetooth Library that is typically invoked by a service, and this test service is NOT part of the library, but exists only in the androidTests directory.
The reason I am doing this is that Android has buggy Bluetooth and on some platforms, the Bluetooth spontaneously shuts down and then restarts. My Bluetooth Library tries to recover from this shutdown. The recovery works BUT for every spontaneous shutdown and recovery, I get a service leak. That is what I am trying to solve in a simplified framework instead of a full-fledged application.

How to create a cucumber-java custom formatter to get cucumber tags

I have a cucumber project and I want to get al the tags in the project to be able to choose them as parameters.
I found this question where cucumber had an option to get the tags but I found that doesn't work anymore, then I found this other question where I found I need a custom formatter to get my tags, but it is for ruby, and I need it for Java, so then I found this article on how to create a custom formatter, but I found that this worked for the cukes version and I'm using the io one.
So I searched inside the cucumber packages and created a custom formatter from a copy of the JSONFormatter inside the package cucumber.runtime.formatter, here is my code:
import cucumber.api.TestCase;
import cucumber.api.event.*;
import cucumber.api.formatter.Formatter;
import cucumber.api.formatter.NiceAppendable;
import gherkin.deps.com.google.gson.Gson;
import gherkin.deps.com.google.gson.GsonBuilder;
import gherkin.pickles.PickleTag;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class TagsFormatter implements Formatter {
private String currentFeatureFile;
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final NiceAppendable out;
private List<String> tags = new ArrayList<>();
private EventHandler<TestCaseStarted> caseStartedHandler = this::handleTestCaseStarted;
private EventHandler<TestRunFinished> runFinishedHandler = event -> finishReport();
public TagsFormatter(Appendable out) {
this.out = new NiceAppendable(out);
}
#Override
public void setEventPublisher(EventPublisher publisher) {
publisher.registerHandlerFor(TestCaseStarted.class, caseStartedHandler);
publisher.registerHandlerFor(TestRunFinished.class, runFinishedHandler);
}
private void handleTestCaseStarted(TestCaseStarted event) {
if (currentFeatureFile == null || !currentFeatureFile.equals(event.testCase.getUri())) {
currentFeatureFile = event.testCase.getUri();
collectTags(event.testCase);
}
}
private void finishReport() {
out.append(gson.toJson(tags));
out.close();
}
private void collectTags(TestCase testCase) {
testCase.getTags();
tags.addAll(testCase.getTags()
.stream()
.map(PickleTag::getName)
.collect(Collectors.toList()));
}
}
I copied the libraries I need to run cucumber in a lib folder inside my project and tried running it using my formatter like this:
java -cp .\lib\cucumber-core-2.4.0.jar;.\lib\gherkin-5.0.0.jar;.\lib\cucumber-java-2.4.0.jar;.\lib\cucumber-jvm-deps-1.0.6.jar cucumber.api.cli.Main -p "com.myproject.formatters.TagsFormatter:tags.txt"
But Im getting a class not found exception:
λ java -cp .\lib\cucumber-core-2.4.0.jar;.\lib\gherkin-5.0.0.jar;.\lib\cucumber-java-2.4.0.jar;.\lib\cucumber-jvm-deps-1.0.6.jar cucumber.api.cli.Main -p "com.myproject.formatters.TagsFormatter:tags.txt"
Exception in thread "main" cucumber.runtime.CucumberException: Couldn't load plugin class: com.myproject.formatters.TagsFormatter
at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:181)
at cucumber.runtime.formatter.PluginFactory.pluginClass(PluginFactory.java:166)
at cucumber.runtime.formatter.PluginFactory.getPluginClass(PluginFactory.java:223)
at cucumber.runtime.formatter.PluginFactory.isFormatterName(PluginFactory.java:201)
at cucumber.runtime.RuntimeOptions$ParsedPluginData.addPluginName(RuntimeOptions.java:471)
at cucumber.runtime.RuntimeOptions.parse(RuntimeOptions.java:157)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:115)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:108)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:100)
at cucumber.api.cli.Main.run(Main.java:31)
at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.ClassNotFoundException: com.myproject.formatters.TagsFormatter
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:174)
... 10 more
So, how can I create this formatter in a way it is recognized? or at least get the tags list from cucumber from console?
Thanks
By just eyeballing your code, I don't think there is anything wrong with it. However your command does not appear to include a compiled version of the TagsFormatter on the class path.
If your compiled sources are in .\bin\ make sure to include that folder ie:
java -cp .\lib\cucumber-core-2.4.0.jar;.\lib\gherkin-5.0.0.jar;.\lib\cucumber-java-2.4.0.jar;.\lib\cucumber-jvm-deps-1.0.6.jar;.\bin\* cucumber.api.cli.Main -p "com.myproject.formatters.TagsFormatter:tags.txt"

How to run Karate from java application not from JUnit test

I managed to run Karate tests using Junit. But what I want is to run Karate from java application instead of Junit runner.
Currently I'am running from JUnit:
import com.intuit.karate.cucumber.CucumberRunner;
import com.intuit.karate.cucumber.KarateStats;
import cucumber.api.CucumberOptions;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
#CucumberOptions(tags = {"~#ignore"})
public class TestParallel {
#Test
public void testParallel() {
KarateStats stats = CucumberRunner.parallel(getClass(), 5, "target/surefire-reports");
assertTrue("scenarios failed", stats.getFailCount() == 0);
}
}
I tried calling the Junit class from my application main using the code below:
JUnitCore junit = new JUnitCore();
Result result = junit.run(TestParallel.class);
But I have this error:
java.lang.NoClassDefFoundError: com/intuit/karate/cucumber/CucumberRunner
Yes, please use the Java API, documented here: https://github.com/intuit/karate#java-api
Note that you won't get reports if you go down this path.
I solved the problem by removing the test scope from the karate dependencies in the pom.
Everything works fine including the reports and the output.

How to implement and run cucumber test files using testng

Trying to implement selenium + Cucumber + Testng instead of Junit.
My queries are
What is the alternate for #Runwith(Cucumber.class) in testng
How to run the class file which contains the path to feature file
package runner;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
#CucumberOptions(features="src/main/java/testCases/Cucumber/Login_Cucumber.Feature",glue="")
public class TestRunner extends AbstractTestNGCucumberTests {
}
TestNg uses #CucumberOptions tag to declare parameters
#CucumberOptions(plugin = "json:target/cucumber-report.json")
public class RunCukesTest extends AbstractTestNGCucumberTests {
}
or
#CucumberOptions(features = "src/test/resources/features/Download.feature",
glue = "uk.co.automatictester.jwebfwk.glue",
format = {"pretty"})
Check this out: https://github.com/cucumber/cucumber-jvm/tree/master/examples/java-calculator-testng
Also a possible dup of :How to integrate the cucumber in testNG?
Install TestNG Eclipse Plugin. Afterwards you should be able to run TestNG Test.
First of all, Cucumber have .feature files and not test files.
Answer to your first question: 1. What is the alternate for #Runwith(Cucumber.class) in testng? "You don't need #RunWith while running with TestNG"
I didn't understand your second question but you need to understand that Cucumber runs end execute the Runner class by default and you have already defined feature files in #CucumberOptions section.
To make it more clear you can easily implement and Run Cucumber project using TestNG. The whole game is in your pom.xml file and Runner class.
Following detail also explains that you can run each scenario in cucumber as a test using TestNG.
How? It's explained below:
First of all, update your Cucumber Maven dependencies from info.cukes to io.cucumber dependencies
Following Java code in Cucumber Runner Class worked perfectly for me to run each scenario as TestNG test in feature files:
#CucumberOptions(features = "src/test/resources", plugin = "json:target/cucumber-report-feature-composite.json")
public class TestRunner {
private TestNGCucumberRunner testNGCucumberRunner;
#BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
#Test(groups = "cucumber scenarios", description = "Runs Cucumber
Scenarios", dataProvider = "scenarios")
public void scenario(PickleEventWrapper pickleEvent, CucumberFeatureWrapper
cucumberFeature) throws Throwable{
testNGCucumberRunner.runScenario(pickleEvent.getPickleEvent());
}
#DataProvider
public Object[][] scenarios() {
return testNGCucumberRunner.provideScenarios();
}
#AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
}
Run with mvn clean test command and see the magic :)
I would be happy to see your problem resolved. Please let me know if this issue is still not resolved.
Reference: https://github.com/cucumber/cucumber-jvm/blob/master/testng/README.md
I followed this approach: https://github.com/cucumber/cucumber-jvm/blob/master/examples/java-calculator-testng/src/test/java/cucumber/examples/java/calculator/RunCukesByCompositionTest.java
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
#CucumberOptions(features="src/test/resources/features",glue="stepDefinitions",tags="#Test01",plugin= {"pretty", "html:target/cucumber-reports" },monochrome=true)
public class RunnerTest extends AbstractTestNGCucumberTests{
}
It will work for sure.
This perfectly worked for me
package com.shyom.cucumberOptions;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
#CucumberOptions(
plugin = "json:target/cucumber-report.json",
features = "/shyom/src/test/java/feature",
glue="stepDefinations"
)
public class TestRunner extends AbstractTestNGCucumberTests{
}

How to use selenium-server-standalone-2.0rc2 while creating script with RC

package com.html;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
import junit.framework.TestCase;
public class Html5 extends TestCase{`enter code here`
Selenium selenium1;
public void setUp()
{
selenium1=new DefaultSelenium("localhost",4444,"*firefox","http://live.com");
selenium1.start();
}
}
Error appearing in com.thoughtworks.selenium.DefaultSelenium; and DefaultSelenium("localhost",4444,"*firefox","http://live.com"); line.
Please suggest.
First :
What the enter code here string does there ?
Secondly :
If there is an error in the import com.thoughtworks.selenium.DefaultSelenium; and in the new DefaultSelenium, it's certainly that the jars are not in your classpath
selenium-server-standalone contains the Selenium server classes, but not the client ones, where DefaultSelenium is. You'll have to bring the client jars in your classpath, that is selenium2-java for this version I think
I think you need to give Path to firefox.exe in your Constructor..So
selenium1 = new DefaultSelenium("localhost",4444,"*firefox","http://live.com"); Goes like
selenium1 = new DefaultSelenium("localhost",4444,"*firefox C:\Documents and Settings\Mozilla Firefox\firefox.exe","http://live.com");
Try this once.