Set the test name for DynamicTest - maven-surefire-plugin

I'm leveraging the DynamicTest functionality of JUnit 5.3.0-M1 and there's a showstopping point I can't seem to figure out with regards to the test name.
My expectation (right or wrong) is that the displayName of the DynamicTest translates to what I'm used to seeing as the test name in the test output.
For example, given the following TestFactory method
public class RequestAcceptTest {
private final Proxy.Location proxy = Proxy.location();
#TestFactory
Collection<DynamicTest> testAllMimeTypes() {
final List<DynamicTest> tests = new ArrayList<>();
for (final Method method : Method.values()) {
for (final MimeType mimeType : MimeType.values()) {
final String displayName = String.format("testAccept%svia%s", mimeType.name(), method);
tests.add(dynamicTest(displayName, () -> {
assertAccept(200, method, mimeType);
}));
}
}
return tests;
}
I would expect to see failures output by maven-surefire-plugin contain the DynamicTest displayName somewhere, possibly like so:
[ERROR] Tests run: 6, Failures: 6, Errors: 0, Skipped: 0, Time elapsed: 1,578.898 s <<< FAILURE! - in com.example.prototype.proxy.RequestAcceptTest
[ERROR] testAcceptApplicationJsonviaGET Time elapsed: 0.013 s <<< FAILURE!
org.opentest4j.AssertionFailedError
at com.example.prototype.proxy.RequestAcceptTest.assertAccept(RequestAcceptTest.java:73)
at com.example.prototype.proxy.RequestAcceptTest.lambda$testAllMimeTypes$0(RequestAcceptTest.java:64)
[ERROR] testAcceptApplicationJsonviaPUT Time elapsed: 0.001 s <<< FAILURE!
org.opentest4j.AssertionFailedError
at com.example.prototype.proxy.RequestAcceptTest.assertAccept(RequestAcceptTest.java:73)
at com.example.prototype.proxy.RequestAcceptTest.lambda$testAllMimeTypes$0(RequestAcceptTest.java:64)
[ERROR] testAcceptApplicationJsonviaPOST Time elapsed: 0.001 s <<< FAILURE!
org.opentest4j.AssertionFailedError
at com.example.prototype.proxy.RequestAcceptTest.assertAccept(RequestAcceptTest.java:73)
at com.example.prototype.proxy.RequestAcceptTest.lambda$testAllMimeTypes$0(RequestAcceptTest.java:64)
Instead it is array indexed.
[ERROR] Tests run: 6, Failures: 6, Errors: 0, Skipped: 0, Time elapsed: 1,578.898 s <<< FAILURE! - in com.example.prototype.proxy.RequestAcceptTest
[ERROR] testAllMimeTypes[1] Time elapsed: 0.013 s <<< FAILURE!
org.opentest4j.AssertionFailedError
at com.example.prototype.proxy.RequestAcceptTest.assertAccept(RequestAcceptTest.java:73)
at com.example.prototype.proxy.RequestAcceptTest.lambda$testAllMimeTypes$0(RequestAcceptTest.java:64)
[ERROR] testAllMimeTypes[2] Time elapsed: 0.001 s <<< FAILURE!
org.opentest4j.AssertionFailedError
at com.example.prototype.proxy.RequestAcceptTest.assertAccept(RequestAcceptTest.java:73)
at com.example.prototype.proxy.RequestAcceptTest.lambda$testAllMimeTypes$0(RequestAcceptTest.java:64)
[ERROR] testAllMimeTypes[3] Time elapsed: 0.001 s <<< FAILURE!
org.opentest4j.AssertionFailedError
at com.example.prototype.proxy.RequestAcceptTest.assertAccept(RequestAcceptTest.java:73)
at com.example.prototype.proxy.RequestAcceptTest.lambda$testAllMimeTypes$0(RequestAcceptTest.java:64)
As well, the failure summary just shows the lambda names and does not contain any reference to displayName
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR] RequestAcceptTest.lambda$testAllMimeTypes$0:64->assertAccept:73
[ERROR] RequestAcceptTest.lambda$testAllMimeTypes$0:64->assertAccept:73
[ERROR] RequestAcceptTest.lambda$testAllMimeTypes$0:64->assertAccept:73
In reality, I don't have 6 or 10 test, but 10,000. I don't care how, but I do need some information I control to show up in the test output.
If I'm unable to communicate to the casual observer what the test was, then the feature is unfortunately not usable and I'll probably have to go back to bytecode generating test methods.
I also do not know if this is a JUnit question or a Maven-Surefire-Plugin question.

Maven took back surefire integration but didnt integrate with displayname yet :(. https://github.com/junit-team/junit5/issues/990
Romain

If you configure maven-surefire-plugin, then the XML report will contain testcase name as "A() - B", where:
A is method name with annotation #TestFactory
B is is displayName from DynamicTest
pom.xml/build/plugins:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M6</version>
<configuration>
<statelessTestsetReporter implementation="org.apache.maven.plugin.surefire.extensions.junit5.JUnit5Xml30StatelessReporter">
<usePhrasedTestCaseMethodName>true</usePhrasedTestCaseMethodName>
</statelessTestsetReporter>
</configuration>
</plugin>
https://maven.apache.org/surefire/maven-surefire-plugin/examples/junit-platform.html#Surefire_Extensions_and_Reports_Configuration_for_.40DisplayName
https://issues.apache.org/jira/browse/SUREFIRE-1546

Related

No selenium test gets executed on Azure DevOps

I am trying to run my selenium-cucumber tests on Azure Dev Ops.
I run my tests locally on command prompt or on terminal with
mvn test -Dcucumber.filter.tags="#ForgotPassword" -Dbrowser=Firefox
This works perfectly fine. Now, I want to run the same thing on Azure DevOps. Hence, I have created a pipeline as below
Maven task is as below
But, when I run the pipeline, in the logs, it does not detect any test and no test is executed.
? ?
? src/test/resources/cucumber.properties: cucumber.publish.enabled=true ?
? src/test/resources/junit-platform.properties: cucumber.publish.enabled=true ?
? Environment variable: CUCUMBER_PUBLISH_ENABLED=true ?
? JUnit: #CucumberOptions(publish = true) ?
? ?
? More information at https://cucumber.io/docs/cucumber/environment-variables/ ?
? ?
? Disable this message with one of the following: ?
? ?
? src/test/resources/cucumber.properties: cucumber.publish.quiet=true ?
? src/test/resources/junit-platform.properties: cucumber.publish.quiet=true ?
?????????????????????????????????????????????????????????????????????????????????????
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.65 s - in com.mohg.automation.cucumberOptions.TestNGTestRunner
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:09 min
[INFO] Finished at: 2022-08-04T15:01:19Z
[INFO] ------------------------------------------------------------------------
Am I missing anything here?
From your screenshot, you are defining the maven command arguments in Maven Task Goal field. This is the root cause of the issue.
You need to define the argument in the Option field.
For example:
Yaml Sample:
- task: Maven#3
displayName: 'Maven pom.xml'
inputs:
goals: test
options: '-Dcucumber.filter.tags="#ForgotPassword" -Dbrowser=Firefox'
testResultsFiles: '**/surefire-reports/TEST-*.xml'

Apache Beam ReadFromKafka using Python runs in Flink but no published messages are passing through

I have a local cluster running in Minikube. My pipeline job is written in python and is a basic consumer of Kafka. My pipeline looks as follows:
def run():
import apache_beam as beam
options = PipelineOptions([
"--runner=FlinkRunner",
"--flink_version=1.10",
"--flink_master=localhost:8081",
"--environment_type=EXTERNAL",
"--environment_config=localhost:50000",
"--streaming",
"--flink_submit_uber_jar"
])
options.view_as(SetupOptions).save_main_session = True
options.view_as(StandardOptions).streaming = True
with beam.Pipeline(options=options) as p:
(p
| 'Create words' >> ReadFromKafka(
topics=['mullerstreamer'],
consumer_config={
'bootstrap.servers': '192.168.49.1:9092,192.168.49.1:9093',
'auto.offset.reset': 'earliest',
'enable.auto.commit': 'true',
'group.id': 'BEAM-local'
}
)
| 'print' >> beam.Map(print)
)
if __name__ == "__main__":
run()
The Flink runner shows no records passing through in "Records received"
Am I missing something basic?
--environment_type=EXTERNAL means you are starting up the workers manually, and is primarily for internal testing. Does it work if you don't specify an environment_type/config at all?
def run(bootstrap_servers, topic, pipeline_args):
bootstrap_servers = 'localhost:9092'
topic = 'wordcount'
pipeline_args = pipeline_args.append('--flink_submit_uber_jar')
pipeline_options = PipelineOptions([
"--runner=FlinkRunner",
"--flink_master=localhost:8081",
"--flink_version=1.12",
pipeline_args
],
save_main_session=True, streaming=True)
with beam.Pipeline(options=pipeline_options) as pipeline:
_ = (
pipeline
| ReadFromKafka(
consumer_config={'bootstrap.servers': bootstrap_servers},
topics=[topic])
| beam.FlatMap(lambda kv: log_ride(kv[1])))
I'm facing another issue with latest apache Beam 2.30.0, Flink 1.12.4
2021/06/10 17:39:42 Initializing python harness: /opt/apache/beam/boot --id=1-2 --provision_endpoint=localhost:42353
2021/06/10 17:39:50 Failed to retrieve staged files: failed to retrieve /tmp/staged in 3 attempts: failed to retrieve chunk for /tmp/staged/pickled_main_session
caused by:
rpc error: code = Unknown desc = ; failed to retrieve chunk for /tmp/staged/pickled_main_session
caused by:
rpc error: code = Unknown desc = ; failed to retrieve chunk for /tmp/staged/pickled_main_session
caused by:
rpc error: code = Unknown desc = ; failed to retrieve chunk for /tmp/staged/pickled_main_session
caused by:
rpc error: code = Unknown desc =
2021-06-10 17:39:53,076 WARN org.apache.flink.runtime.taskmanager.Task [] - [3]ReadFromKafka(beam:external:java:kafka:read:v1)/{KafkaIO.Read, Remove Kafka Metadata} -> [1]FlatMap(<lambda at kafka-taxi.py:88>) (1/1)#0 (9d941b13ae9f28fd1460bc242b7f6cc9) switched from RUNNING to FAILED.
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: No container running for id d727ca3c0690d949f9ed1da9c3435b3ab3af70b6b422dc82905eed2f74ec7a15

How to generate Cucumber extent reports 4 through Gradle

I am executing the Cucumber automation test scripts through gradle, though i am able to execute the test successfully but reports are not getting generated. I did give a try with with below gradle tasks
one at a time.
Cucumber gradle tasks copied below
a) for the below gradle task i am able to execute the scripts which does not generate reports as i have not included the reports statements inside args
task cucumber() {
dependsOn assemble, testClasses
doLast {
javaexec {
main = "io.cucumber.core.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'pretty',
'--glue','com.hal.brands.test.stepdefinition',
'src/test/resources','src/main/java',
'--tags', '#Api'
]
}
}
}
b) I tried to include the few statements related to reporting as shown in below gradle task but it failed with a exception
task cucumber() {
dependsOn assemble, testClasses
doLast {
javaexec {
main = "io.cucumber.core.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'pretty', 'json:target/HalBrands.json', 'com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:',
'--monochrome', 'true',
'--features','src\test\resources\featurefile',
'--glue','com.hal.brands.test.stepdefinition',
'src/test/resources','src/main/java',
'--tags', '#Api'
]
}
}
}
Exception details given below
BUILD SUCCESSFUL in 1s
6 actionable tasks: 6 up-to-date
E:\GradleProj_workspace\GadleDemoProj>gradle cucumber
> Configure project :
http://api-qa.dpr-prv.halbrands.us.cloudappzero.azureflash.com
E:\GradleProj_workspace\GadleDemoProj
> Task :cucumber FAILED
Exception in thread "main" java.lang.IllegalArgumentException: com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter: is not valid. Try URI[:LINE]*
at io.cucumber.core.model.FeatureWithLines.parse(FeatureWithLines.java:56)
at io.cucumber.core.options.RuntimeOptionsParser.parse(RuntimeOptionsParser.java:131)
at io.cucumber.core.options.CommandlineOptionsParser.parse(CommandlineOptionsParser.java:25)
at io.cucumber.core.options.CommandlineOptionsParser.parse(CommandlineOptionsParser.java:29)
at io.cucumber.core.cli.Main.run(Main.java:29)
at io.cucumber.core.cli.Main.main(Main.java:14)
Caused by: java.lang.IllegalArgumentException: Expected scheme-specific part at index 68: com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:
at java.net.URI.create(URI.java:852)
at io.cucumber.core.model.FeaturePath.parseProbableURI(FeaturePath.java:72)
at io.cucumber.core.model.FeaturePath.parse(FeaturePath.java:57)
at io.cucumber.core.model.FeatureWithLines.parseFeaturePath(FeatureWithLines.java:77)
at io.cucumber.core.model.FeatureWithLines.parse(FeatureWithLines.java:53)
... 5 more
Caused by: java.net.URISyntaxException: Expected scheme-specific part at index 68: com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:
at java.net.URI$Parser.fail(URI.java:2848)
at java.net.URI$Parser.failExpecting(URI.java:2854)
at java.net.URI$Parser.parse(URI.java:3057)
at java.net.URI.<init>(URI.java:588)
at java.net.URI.create(URI.java:850)
... 9 more
FAILURE: Build failed with an exception.
* Where:
Build file 'E:\GradleProj_workspace\GadleDemoProj\build.gradle' line: 104
* What went wrong:
Execution failed for task ':cucumber'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_202\bin\java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 1s
6 actionable tasks: 1 executed, 5 up-to-date
E:\GradleProj_workspace\GadleDemoProj>
**---------------------------------------------------------------------------------------------------------------**
I am not sure where i am going wrong in the above 'b' gradle task . Please help with me at the earliest as iam literally wasting lot of time here trying out many possibilities. Also i want to keep you informed that i am new gradle stuff.
Have also copied cucumberoptions as present in my cucumber runner file
#CucumberOptions(features = { "classpath:featurefile" }, glue = { "classpath:com.hal.brands.test.stepdefinition",
"classpath:com.hal.brands.helper" },
plugin = { "pretty", "json:target/HalBrands.json", "com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:" },
monochrome = true, tags = "#Api")
Pls take off the json: to get rid of the exception you are getting wrt to invalid scheme!
The Complete solution is given below .
task cucumber() {
dependsOn assemble, testClasses
doLast {
javaexec {
main = "io.cucumber.core.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'pretty',
'--plugin', 'json:target/HalBrands.json',
'--plugin', 'com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:Report',
'--glue','com.hal.brands.test.stepdefinition',
'src/test/resources','src/main/java',
'--tags', '#Api'
]
}
}
}

How to ensure that test is executed after all tests in scalatest?

I want to test that all methods of a REST API are covered by tests.
All http calls are recorded into a mutable set, and I have a piece of code that checks correspondence between specification and the result set of recored api calls.
I can place this check in a separate test at the end of FunSuite and it would be executed after all other tests. However, there are two problems: I have to copy-paste it in every file that tests API and make sure it is at the end of file.
Using common trait does not work: tests from parent class are executed before tests from child class. Placing the test inside afterAll does not work either: scalatest swallows all exceptions (including test failures) thrown in it.
Is there a way to run some test after all others without boilerplate?
Personally I would go with dedicated coverage tool such as scoverage. One advantage would be avoiding global state.
Nevertheless, as per question, a way to execute test after all tests would be via Suites and BeforeAndAfterAll traits like so
import org.scalatest.{BeforeAndAfterAll, Suites, Matchers}
class AllSuites extends Suites(
new FooSpec,
new BarSpec,
) with BeforeAndAfterAll withy Matchers {
override def afterAll(): Unit = {
// matchers here as usual
}
}
Here is a toy example with global state as per question
AllSuites.scala
import org.scalatest.{BeforeAndAfterAll, Matchers, Suites}
object GlobalMutableState {
val set = scala.collection.mutable.Set[Int]()
}
class AllSuites extends Suites(
new HelloSpec,
new GoodbyeSpec
) with BeforeAndAfterAll with Matchers {
override def afterAll(): Unit = {
GlobalMutableState.set should contain theSameElementsAs Set(3,2)
}
}
HelloSpec.scala
#DoNotDiscover
class HelloSpec extends FlatSpec with Matchers {
"The Hello object" should "say hello" in {
GlobalMutableState.set.add(1)
"hello" shouldEqual "hello"
}
}
GoodbyeSpec.scala
#DoNotDiscover
class GoodbyeSpec extends FlatSpec with Matchers {
"The Goodbye object" should "say goodbye" in {
GlobalMutableState.set.add(2)
"goodbye" shouldEqual "goodbye"
}
}
Now executing sbt test gives something like
[info] example.AllSuites *** ABORTED ***
[info] HashSet(1, 2) did not contain the same elements as Set(3, 2) (AllSuites.scala:15)
[info] HelloSpec:
[info] The Hello object
[info] - should say hello
[info] GoodbyeSpec:
[info] The Goodbye object
[info] - should say goodbye
[info] Run completed in 377 milliseconds.
[info] Total number of tests run: 2
[info] Suites: completed 2, aborted 1
[info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0
[info] *** 1 SUITE ABORTED ***
[error] Error during tests:
[error] example.AllSuites
[error] (Test / test) sbt.TestsFailedException: Tests unsuccessful

Scala 2.11 refined with scalatest MustMatchers and Await causes compiler error "trying to do lub/glb of typevar ?F[?T, ?B]"

I have been trying to use the refined with scalatest and am getting compiler errors at the "typer" phase: trying to do lub/glb of typevar ?F[?T, ?B]
This is my best attempt at a minimalist reproduction of the issue using a self-contained ammonite script:
import $ivy.`eu.timepit::refined:0.9.0`
import $ivy.`org.scalatestplus.play::scalatestplus-play:3.1.2`
import org.scalatest.{MustMatchers, WordSpec}
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import eu.timepit.refined.auto.autoInfer
class RefinedSpec extends WordSpec with MustMatchers {
val duration = 500.millis
val fut = Future.successful("123")
Await.result(fut, atMost = duration)
}
If you make any one of the following changes to the above it will successfully compile:
delete: import eu.timepit.refined.auto.autoInfer
remove: with MustMatchers from the class definition
delete: Await.result(fut, atMost = duration)
To clarify, this is a compilation error, not a runtime error. The original error is happening in a play app (scala 2.11.11) whilst running test:compile in sbt, but it's probably easier to reproduce it with the ammonite script.
The ammonite version I'm using gives version info:
Welcome to the Ammonite Repl 1.1.2
(Scala 2.11.12 Java 1.8.0_25)
Installed using:
sudo sh -c '(echo "#!/usr/bin/env sh" && curl -L https://github.com/lihaoyi/Ammonite/releases/download/1.1.2/2.11-1.1.2) > /usr/local/bin/amm && chmod +x /usr/local/bin/amm' && amm
More error details from the ammonite example:
scala.reflect.internal.FatalError:
trying to do lub/glb of typevar ?F[?T, ?B]
while compiling: fail.sc
during phase: typer
library version: version 2.11.12
compiler version: version 2.11.12
reconstructed args: -nowarn -Yresolve-term-conflict:object
last tree to typer: Ident(<argument>)
tree position: line 15 of fail.sc
tree tpe: String
symbol: <none>
symbol definition: <none> (a NoSymbol)
symbol package: <none>
symbol owners:
call site: class RefinedSpec in object fail in package $file
From play sbt test:compile I also get this kind of output:
[error] last tree to typer: Ident(<argument>)
[error] tree position: line 13 of ...../RefinedSpec.scala
[error] tree tpe: String
[error] symbol: <none>
[error] symbol definition: <none> (a NoSymbol)
[error] symbol package: <none>
[error] symbol owners:
[error] call site: class RefinedSpec in package foo in package foo
[error]
[error] == Source file context for tree position ==
[error]
[error] 10 val duration = 500.millis
[error] 11 val fut = Future.successful("123")
[error] 12 Await.result(fut, atMost = duration)
[error] 13 }
This isn't a serious issue as I can just remove the autoInfer import as I'm not actually using it. It will trip people up though because they'll tend to do:
import eu.timepit.refined.auto._
to get automatic conversion from compile-time constants into refined types, when they can probably just get away with:
import eu.timepit.refined.auto.autoRefineV

Resources