JaCoCo Vs Intellij Code coverage tool (If Else condition) - scala

I have a simple method with a unit test written in flat spec , in intellij when I try to run my test using JaCoCo as coverage tool the IF condition is partially covered where as same test code using Intellij code coverage tool it is 100% covered so does JaCoCo has any kind of problem ?
def ifElse(novalue: String, platform: String) =
if (novalue == "NoValue" && platform == "PLATFORM") {
true
} else {
false
}
Unit test code
it should "ifElse True Test" in {
ifElse("NoValue", "PLATFORM") should be(true)
ifElse("blah", "blah") should be(false)
ifElse("NoValue", "PLATFORM2") should be(false)
ifElse("NoValue2", "PLATFORM") should be(false)
}
Using Intellij Code Coverage Tool 100% covered if condition :-
Using JaCoCo Code Coverage Tool if condition is not getting covered :-
Thanks
Sri

Related

Integrate µTest (micro test) for Scala into a Gradle project

I'm using Gradle for my Scala projects and a bit frustrated about documentation of scalatest. So I searched for a alternative test framework. The only one I found was µTest (micro test). But so far I could not found a way to integrate µTest into Gradle.
After time of investigation I found a solution. If I have a sample test:
import utest._
object SampleTests extends TestSuite {
val tests:Tests = Tests {
var x = 0
'outer1 - {
x += 1
'inner1 - {
x += 2
assert(x == 3) // 0 + 1 + 2
x
}
'inner2 - {
x += 3
assert(x == 4) // 0 + 1 + 3
x
}
}
'outer2 - {
x += 4
'inner3 - {
x += 5
assert(x == 9) // 0 + 4 + 5
x
}
}
}
def main(args: Array[String]): Unit = {
val results = TestRunner.runAndPrint(SampleTests.tests, "SampleTests")
}
}
Importent is that there is a main funtion which calls a method of the TestRunner with a parameter of type Tests. This parameter can be a value or a method defined with def.
Furthermore the test code should be inside test source location (test instead of main).
For triggering this code you need to modify the build.gradle file. There you can insert a user defined task like this:
task microTest(type: JavaExec) {
main = 'package.SampleTests'
classpath = sourceSets.test.runtimeClasspath
}
Of course you need to declare the dependency inside build.gradle to the test framework:
testImplementation "com.lihaoyi:utest_2.a:x.y.z"
Fazit:
There is a way to trigger the tests with
./gradlew microTest
or click with the mouse inside your IDE at the listed gradle task. The output of the test framework micro test will be printed to the console in the expected way. But when you call this task indirectly by defining the following line inside build.gradle:
test.finalizedBy microTest
with click at the test task in the IDE (Intellij), then the colored output is replaced by special characters.
When not clicking (entering the command line: ./gradlew test) all output is printed correctly.

Soap UI Groovy - Run test step on failed assertion

I have a SOAP project and wish to run one test step if an assertion fails and another if it passes.
Please see the following pseudocode:
If assertion of node fails
run testStep "Activate"
Else
run testStep "Deactivate"
Is this possible?!
Thanks
Let us assume that the test case has following steps.
Step1
Step2
Step3
And here you wish to execute one of the 2nd or 3rd step based on the result of Step1.
So, add Script Assertion to the Step1 as mentioned below.
Please note that the focus of the below script is to enable to disable. You need to create the condition when to activate and which step.
I am just giving a sample condition for the demo.
//Closure to enable to disable the test step
def changeStep = { name, isDisable ->
context.testCase.testSteps[name].disabled = isDisable
}
def value = 1
def map = [:]
//Change the step names as needed to your environment.
if (1 == value) {
map['Step2'] = true
map['Step3'] = false
} else {
map['Step2'] = false
map['Step3'] = true
}
map.collect {k, v -> changeStep(k, v)}
Also keep in mind that when the value is true, respective step is disabled. false to enable the step.
Now, when the test case is executed, the unwanted test step is automatically disabled so that it won't run.
You can try below code and see it works for your requirement :
def data = ["true","false"]
for(int i=0;i<data.size();i++)
{
if(data[i] == "true")
{
testRunner.runTestStepByName("customer - activate")
}
else if(data[i] == "false")
{
testRunner.runTestStepByName("customer - deactivate")
}
}
Here "customer - activate" and "customer - deactivate" are the names of the Test Steps

Shell like application using sbt console

I would like to deploy some scala code, to be used very similar to sbt console
(command line interface, history, etc)
and would like to
customize it
and made it simple to deploy.
Can sbt console be used with these changes:
Removed startup info messages
Removed scala welcome message
Customized command prompt instead of "scala>" to be "myApp>"
No access to local nor global ivy/maven repositories (all jars
available, including sbt jars and dependencies)
Anybody passed this path ?
I have tried
Using sbt to build command line application
but with no much progress so far
(I guessed it was intented to very similar situation)
Are there ready made plugin available ?
Any other tool related or unrelated to sbt ?
Thank you
Actully, no need for sbt. To have it tweaked, scala code should be changed.
For the sbt "Customized command prompt" part, you have a good example with "sbt: Customize the Shell prompt in sbt" from Patrick Bailey (patmandenver).
create the ~/.sbt/0.13/global.sbt file:
vi ~/.sbt/0.13/global.sbt
And place the following in it.
shellPrompt := { state =>
def textColor(color: Int) = { s"\033[38;5;${color}m" }
def backgroundColor(color:Int) = { s"\033[48;5;${color}m" }
def reset = { s"\033[0m" }
def formatText(str: String)(txtColor: Int, backColor: Int) = {
s"${textColor(txtColor)}${backgroundColor(backColor)}${str}${reset}"
}
val red = 1
val green = 2
val yellow = 11
val white = 15
val black = 16
val orange = 166
formatText(s"[${name.value}]")(white, orange) +
"\n " +
formatText("\u276f")(green, black) +
formatText("\u276f")(yellow, black) +
formatText("\u276f ")(red, black)
}
Run reload in sbt and….
That can be amended/enhanced/completed to add other information you would need in your case.

How to fork the jvm for each test in sbt

I am working with some classes that (for some reason) can only be used once within a single VM. My test cases work if I run them individually (fork := true) enabled in my sbt settings.
If I run more than one of these tests, they fail with an exception that has to with a thread executor rejecting a task (it's most likely closed). It would be very time consuming to find out what causes the problem and even if I find the problem, I might not be able to resolve it (I do not have access to the source code).
I am currently using the specs2 test framework, but any test framework using sbt would be acceptable.
Is there any test framework for sbt that is capable of running each test in a jvm fork?
Thoughts or ideas on possible other solutions are of course welcome.
It turns out this is fairly easy to achieve. The documentation is sufficient and can be found at Testing - Forking tests
// Define a method to group tests, in my case a single test per group
def singleTests(tests: Seq[TestDefinition]) =
tests map { test =>
new Group(
name = test.name,
tests = Seq(test),
runPolicy = SubProcess(javaOptions = Seq.empty[String]))
}
// Add the following to the `Project` settings
testGrouping in Test <<= definedTests in Test map singleTests
Using non-deprecated syntax:
testGrouping in Test := (definedTests in Test).value map { test =>
Tests.Group(name = test.name, tests = Seq(test), runPolicy = Tests.SubProcess(
ForkOptions(
javaHome.value,
outputStrategy.value,
Nil,
Some(baseDirectory.value),
javaOptions.value,
connectInput.value,
envVars.value
)))
}
2023 proper syntax:
Test / testGrouping := (Test / definedTests).value map { test =>
Tests.Group(name = test.name, tests = Seq(test), runPolicy = Tests.SubProcess(
ForkOptions(
javaHome = javaHome.value,
outputStrategy = outputStrategy.value,
bootJars = Vector.empty,
workingDirectory = Some(baseDirectory.value),
runJVMOptions = javaOptions.value.toVector,
connectInput = connectInput.value,
envVars = envVars.value
)))

Jython Build has no Output

Hey, I've been playing around with Jython a bit and I wrote the following test program:
from javax.swing import *
from java.awt import *
from java.awt.event import ActionListener
class JythonTest(JFrame):
_windowTitle = ""
def __init__(self):
self.initVars()
self.initLookAndFeel()
self.initComponents()
self.initGui()
def initVars(self):
self._windowTitle = "Jython Test"
JFrame.__init__(self, self._windowTitle)
def initLookAndFeel(self):
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
def initComponents(self):
label = JLabel("Hello World!", JLabel.CENTER)
label.setFont(Font("Arial", Font.BOLD, 30))
tabs = JTabbedPane()
tabs.addTab("Test", label)
tabs.addTab("Calculator", self.CalculatorPane())
self.add(tabs)
def initGui(self):
self.setSize(400,200)
self.setDefaultCloseOperation(self.EXIT_ON_CLOSE)
self.setVisible(1)
class CalculatorPane(JPanel, ActionListener):
_txt1 = 0
_txt2 = 0
_box = 0
def __init__(self):
self.initVars()
self.initComponents()
def initVars(self):
pass
def initComponents(self):
self._txt1 = JTextField(5)
self._box = JComboBox(["+", "-", "*", "/"])
self._txt2 = JTextField(5)
btn = JButton("Go")
btn.addActionListener(self)
self.add(self._txt1)
self.add(self._box)
self.add(self._txt2)
self.add(btn)
def actionPerformed(self, ev):
val1 = self._txt1.getText()
val2 = self._txt2.getText()
operation = self._box.getSelectedItem()
val1 = int(val1)
val2 = int(val2)
if operation == "+":
answer = val1+val2
elif operation == "-":
answer = val1-val2
elif operation == "*":
answer = val1*val2
elif operation == "/":
answer = val1/val2
JOptionPane.showMessageDialog(self, "The answer is: " + str(answer))
if __name__ == "__main__":
win = JythonTest()
Here's my system info:
Operating System: Ubuntun 10.10
Netbeans Version: 6.9
My problem is that I can't compile the above code. It runs just fine when I click the run button, however, when I hit build or clean & build then I don't get any results. The build process runs in the bottom right corner for about half a second and then finishes. The output box opens up but it's entirely empty, even after the process ends. When I look at my project folder, nothing changes. Only two folders exist, nbproject and src. There probably should be a dist folder with a jar inside of it. Here's what's in the file structure:
user#computer: ~/NetBeansProjects/pythontest$ ls
nbproject src
user#computer: ~/NetBeansProjects/pythontest$ ls nbproject
private project.properties project.xml
user#computer: ~/NetBeansProjects/pythontest$ ls nbproject/private
private.xml
user#computer: ~/NetBeansProjects/pythontest$ ls src
pythontest.py setup.py
All I did to set up was install netbeans from the debian package (quite a while ago) and set up python/jython through the NetBeans python plugin. Any idea what's wrong?
The short answer is that it doesn't really work like that; I'm not aware of any IDE or tool support for packaging jython programs.
Usually what I do is just make a shell script that says:
java -cp "the/classpath/;" org.python.util.jython myscript.py
I've found that is the most foolproof way to run a jython program, and has saved me many headaches from not-working .jar files during development.
That said, there are methods of packaging jython programs in standalone .jar files, if that's what you want.
The best resource that I've found is the Distributing Jython Scripts page in the Jython FAQ, which describes a few different techniques for distributing jython scripts.
I usually only use the methods described there when "publishing" a program.