while creating pact verification test i am using httpTarget Method. but the problem is my service dont have a port value. how can we run this? please advise.
Service URL=http://services.groupkt.com/country/get/iso3code/IND
below is my verification test.
package se.ff.bsv;
import au.com.dius.pact.provider.junit.PactRunner;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.State;
import au.com.dius.pact.provider.junit.loader.PactFolder;
import au.com.dius.pact.provider.junit.loader.PactUrl;
import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.TestTarget;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import java.net.URL;
import java.util.Map;
#RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner
#Provider("getCountryService") // Set up name of tested provider
#PactFolder("../pacts") // Point where to find pacts (See also section Pacts source in documentation)
//#PactUrl(urls = {"http://services.groupkt.com/country/get/iso3code/IND"} )
public class getCountryContractTest {
#State("There is a country with alpha2_code as IN having name as India") // Method will be run before testing
// interactions that require "with-data"
// state
public void hammerSmith() {
System.out.println("There is a country with alpha2_code as IN having name as India");
}
#TestTarget // Annotation denotes Target that will be used for tests
//public final Target target = new HttpTarget(8111);// Out-of-the-box implementation of Target (for more information take a look at Test Target section)
public final Target target = new HttpTarget("http", "services.groupkt.com",);
}
You can't say your service don't have a port, but you can say your service uses a default port (for instance). In that case, try to use port 80.
Related
I know how to use two runner classes to rerun failed scenarios, but I want this feature only for one test.
Let's say that I have 100 scenarios and I only want to rerun scenario 40 when it fails, but if any other scenaria fails, I don't want it to rerun. Is there a way to implement this for one test in particular?
To see how to rerun all failed scenarios, check out this question:
How to rerun the failed scenarios using Cucumber?
You'll have to write custom code for this. Fortunately this is relatively easy with the JUnit Platform API (JUnit 5).
https://github.com/cucumber/cucumber-jvm/tree/main/cucumber-junit-platform-engine#rerunning-failed-scenarios
package com.example;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.engine.discovery.UniqueIdSelector;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary.Failure;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectDirectory;
import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request;
public class RunCucumber {
public static void main(String[] args) {
LauncherDiscoveryRequest request = request()
.selectors(
selectDirectory("path/to/features")
)
.build();
Launcher launcher = LauncherFactory.create();
SummaryGeneratingListener listener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(listener);
launcher.execute(request);
TestExecutionSummary summary = listener.getSummary();
// Do something with summary
List<UniqueIdSelector> failures = summary.getFailures().stream()
.map(Failure::getTestIdentifier)
.filter(TestIdentifier::isTest)
// Filter more to select scenarios to rerun
.map(TestIdentifier::getUniqueId)
.map(DiscoverySelectors::selectUniqueId)
.collect(Collectors.toList());
LauncherDiscoveryRequest rerunRequest = request()
.selectors(failures)
.build();
launcher.execute(rerunRequest);
TestExecutionSummary rerunSummary = listener.getSummary();
// Do something with rerunSummary
}
}
I followed the steps on Google Cloud's Java and OpenTelemetry site (https://cloud.google.com/trace/docs/setup/java-ot) and made a simple hello world Java application locally and am trying to get my traces to show up on Google Cloud Trace using their trace exporter.
All the setup code is the same, and the program compiles and runs successfully. However, I don't see anything on the Trace dashboard. I know it is not an issue with IAM or my service account key because I ran the Python example and it shows up in Cloud Trace dashboard just fine.
Anyone have any guidance on why the Java version could be silently failing?
Thanks
package hello;
import org.joda.time.LocalTime;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.exporter.logging.LoggingSpanExporter;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.export.IntervalMetricReader;
import java.io.IOException;
import java.util.Random;
import com.google.cloud.opentelemetry.trace.TraceConfiguration;
import com.google.cloud.opentelemetry.trace.TraceExporter;
import java.util.Collections;
import static java.util.Collections.singleton;
import java.time.Duration;
public class HelloWorld {
private static final Random random = new Random();
private static OpenTelemetry setupTraceExporter() {
try {
TraceExporter traceExporter = TraceExporter.createWithConfiguration(
TraceConfiguration.builder().setProjectId("my-test-id").build());
// Register the TraceExporter with OpenTelemetry
return OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(traceExporter).build())
.build())
.buildAndRegisterGlobal();
} catch (IOException e) {
System.out.println("Uncaught Exception");
System.out.println(e);
return null;
}
}
public static void main(String[] args) {
System.out.println("Starting the example application");
/* SET UP */
OpenTelemetry otel = setupTraceExporter();
/* Creating tracer */
Tracer tracer =
otel.getTracer("java foo");
Span span = tracer.spanBuilder("my span").startSpan();
// put the span into the current Context
try (Scope scope = span.makeCurrent()) {
System.out.println("Hello");
Thread.sleep(4000);
} catch (Throwable t) {
span.setStatus(StatusCode.ERROR, "error");
System.out.println(t);
} finally {
span.end();
}
System.out.println("Closing");
//otel.getSdkTracerProvider().shutdown();
}
}
After some debugging, I figured out the answer.
Seems like with this simple example, the BatchSpanProcessor is not a good idea because there is only one span that is getting traced.
SimpleSpanProcessor directly forwards the spans to Cloud Trace no matter what whereas BatchSpanProcessor waits until there is enough data before pushing to Cloud Trace. Hence why I was not seeing anything in Cloud Trace because BatchSpanProcessor hadn't registered enough spans for it to actually upload it to Google Cloud.
Span Processors Documentation
Change the following lines
return OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(SimpleSpanProcessor.create(traceExporter))
.build())
.buildAndRegisterGlobal();
Hope this helps others!
Cucumber not executing both the features with created stepdefinations
I have tried with tag, also given both full path of both the features but still the same
package runners;
import com.cucumber.listener.ExtentProperties;
import com.cucumber.listener.Reporter;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import managers.Common;
import managers.FileReader;
import org.apache.log4j.PropertyConfigurator;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import java.io.File;
#RunWith(Cucumber.class)
#CucumberOptions(
features = ".//src//test//java//FeatureList",glue = "stepDefinations",
plugin = { "com.cucumber.listener.ExtentCucumberFormatter:",
"junit:target/cucumber-results.xml"},
tags={"#API"},
monochrome = true
)
public class TestRunner {
static String ReportName= Common.ReportName();
#BeforeClass
public static void setup() {
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setReportPath("target/cucumber-reports/"+ReportName+".html");
PropertyConfigurator.configure(".//src//log4j.properties");
}
#AfterClass
public static void writeExtentReport() {
Reporter.loadXMLConfig(new File(FileReader.getInstance().getConfigReader().getReportConfigPath()));
Reporter.setSystemInfo("User Name", System.getProperty("user.name"));
Reporter.setSystemInfo("Time Zone", System.getProperty("user.timezone"));
Reporter.setSystemInfo("Environment", FileReader.getInstance().getConfigReader().getEnvironment());
}
}
Not sure why its always running error codes.feature but never enums.feature
Feature: Enums Codes
#API
Scenario: xxx Enums Codes
Given Run get method "xxxxxxxxxxx" api to get fetch all type of xxx xxx
Then response should be 200
And xxxxxxxxxxxxxx
Feature: Error Codes
#API
Scenario: xxError Codes
Given Run "xxxx" api to get response
Then response should be 200
And Verify xx Error Codes xx error response
"features" is looking for a filesystem path:
features = ".//src//test//java//FeatureList"
Try this -
1 features = "src/test/java/FeatureList"
2 features = "FeatureList"
I'm working on a simple automated java program for using the box api and am trying to use json. I've borrowed the first part of the checkstyle sample code from the Github's repo example SearchExamplesAsAppUser, figuring it should work.
When I run it, I get a this error
java.lang.NoClassDefFoundError: org/bouncycastle/operator/OperatorCreationException
The problem seems to be stemming from the statement:
api = BoxDeveloperEditionAPIConnection.getAppUserConnection(USER_ID, boxConfig, accessTokenCache);
The Jars which I am using are (aside from commons, all recommended by box):
bcpkix-jdk15on-1.52.jar
bcprov-jdk15on-1.52.jar
box-java-sdk-2.14.1.jar
jose4j-0.4.4.jar
minimal-json-0.9.1.jar
commons-codec-1.9.jar
commons-httpclient-3.1.jar
commons-logging-1.2.jar
I am using netbeans so all of the jars above are listed under the libraries to use fr compilation.
The code is as follows:
package boxapitest;
import com.box.sdk.BoxAPIConnection;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.box.sdk.BoxConfig;
import com.box.sdk.BoxDeveloperEditionAPIConnection;
import com.box.sdk.BoxItem;
import com.box.sdk.BoxMetadataFilter;
import com.box.sdk.BoxSearch;
import com.box.sdk.BoxSearchParameters;
import com.box.sdk.BoxUser;
import com.box.sdk.DateRange;
import com.box.sdk.IAccessTokenCache;
import com.box.sdk.InMemoryLRUAccessTokenCache;
import com.box.sdk.PartialCollection;
import com.box.sdk.SizeRange;
public final class BoxAPITest {
private static final String USER_ID = "***email address removed for privacy***";
private static final int MAX_DEPTH = 1;
private static final int MAX_CACHE_ENTRIES = 100;
private static BoxDeveloperEditionAPIConnection api;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
// Turn off logging to prevent polluting the output.
Logger.getLogger("com.box.sdk").setLevel(Level.SEVERE);
//It is a best practice to use an access token cache to prevent unneeded requests to Box for access tokens.
//For production applications it is recommended to use a distributed cache like Memcached or Redis, and to
//implement IAccessTokenCache to store and retrieve access tokens appropriately for your environment.
IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES);
Reader reader;
reader = new FileReader("\\My Path\\file.json");
BoxConfig boxConfig = BoxConfig.readFrom(reader);
api = BoxDeveloperEditionAPIConnection.getAppUserConnection(USER_ID, boxConfig, accessTokenCache);
//api = BoxAPIConnection.getAppUserConnection(USER_ID, boxConfig, accessTokenCache);
BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo();
System.out.format("Welcome, %s!\n\n", userInfo.getName());
}
}
Any assistance would be most appreciated.
Bentaye actually provided the answer. One of my jars was corrupt.
I am very trying the pact-jvm-provider-junit using IntelliJ IDEA as my IDE.
I'm testing out the provided ContractTest example:
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.ClassRule;
import au.com.dius.pact.provider.junit.State;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.target.TestTarget;
import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junit.TargetRequestFilter;
import org.apache.http.HttpRequest;
import au.com.dius.pact.provider.junit.PactRunner;
import au.com.dius.pact.provider.junit.loader.PactFolder;
import au.com.dius.pact.provider.junit.loader.PactUrl;
import au.com.dius.pact.provider.junit.VerificationReports;
import com.github.restdriver.clientdriver.ClientDriverRule;
import org.junit.runner.RunWith;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import static com.github.restdriver.clientdriver.RestClientDriver.giveEmptyResponse;
import static com.github.restdriver.clientdriver.RestClientDriver.onRequestTo;
#RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner
#Provider("uicc_repository") // Set up name of tested provider
//#PactFolder("rs") // Point where to find pacts (See also section Pacts source in documentation)
#PactUrl(urls = {"file:///C:/IdeaProjects/src/pack-test-provider/resources/test_consumer-test_provider.json"}) // Point where to find pacts (See also section Pacts source in documentation)
#VerificationReports(value = {"markdown","json"}, reportDir = "C:/IdeaProjects/src/pack-test-provider/resources")
public class ContractTest {
// NOTE: this is just an example of embedded service that listens to requests, you should start here real service
#ClassRule //Rule will be applied once: before/after whole contract test suite
public static final ClientDriverRule embeddedService = new ClientDriverRule(6060);
private static final Logger LOGGER = LoggerFactory.getLogger(ContractTest.class);
#BeforeClass //Method will be run once: before whole contract test suite
public static void setUpService() {
//Run DB, create schema
//Run service
//...
}
#Before //Method will be run before each test of interaction
public void before() {
// Rest data
// Mock dependent service responses
// ...
embeddedService.addExpectation(
onRequestTo("/data"), giveEmptyResponse()
);
}
#TestTarget // Annotation denotes Target that will be used for tests
public final Target target = new HttpTarget(6060); // Out-of-the-box implementation of Target (for more information take a look at Test Target section)
#State("default") // Method will be run before testing interactions that require "default" or "no-data" state
public void toDefaultState() {
// Prepare service before interaction that require "default" state
// ...
System.out.println("Now service in default state");
LOGGER.info("Now service in default state");
}
}
But when I try to run the test (Run -> Run ContractTest), it's like the test is not ran at all:
Mar 15, 2017 3:24:00 PM org.junit.platform.launcher.core.ServiceLoaderTestEngineRegistry loadTestEngines
INFO: Discovered TestEngines with IDs: [junit-jupiter, junit-vintage]
Mar 15, 2017 3:24:01 PM org.junit.vintage.engine.execution.TestRun lookupTestDescriptor
WARNING: Runner au.com.dius.pact.provider.junit.PactRunner on class rs.ContractTest reported event for unknown Description: rs.ContractTest. It will be ignored.
Process finished with exit code 0
enter image description here
I am not sure if it's an issue with how I am running the test in IntelliJ or I am missing something in the pact-jvm-provider "runner".
Appreciate any help on this topic.
Thanks!