Katalon Studio deleting groovy code from script when switching to manual or recording - katalon-studio

Did anybody see this as well, or am I doing something wrong?
I am working on a test case with Katalon Studio, in script mode. I have some Groovy script in it, (in particular a class definition, see start of code below). When I switch mode to work in manual or record mode, and then back to script mode, the groovy code (the class declaration in the example below) has disappeared...
Not very practical! Anything that should be done to avoid this?
Many thanks!
E.
Code example:
//Katalon Imports here
class Product {
String nozo
String price_string
Number qty = 1
Number price_ht = 0
Number price_ttc = 0
Product(String nozo, String price_string, Number qty = 1) {
this.nozo = nozo
this.price_string = price_string
def get_price = (this.price_string =~/(\d+)\s(\d+\.\d{2})/)
if(get_price) {
this.price_ttc = get_price[1] + get_price[2]
}
else this.price_ttc = 0
this.price_ht = this.price_ttc / 1.2
}
def get_price_order_line_ht() {
return this.price_ht * this.qty
}
}
// Intialisation of test data
Number qty_pdt1 = 2
'Open home page'
WebUI.openBrowser('http://localhost:8080/')
'Navigate to subrange'
WebUI.doubleClick(findTestObject('Object Repository/vb_desktop/home_page_desktop_fr/a_Lampadaire'))
// Etc...

Related

How to import other person's package?

import CtCILibrary.*;
public class RotateMatrix {
public static boolean rotate (int [][]matrix) {
if ( matrix.length == 0 || matrix.length != matrix[0].length) {
return false;
}
int n = matrix.length;
for ( int layer = 0 ; layer < n / 2 ; layer++ ) {
int first = layer;
int last = n - 1 - first;
for ( int i = first ; i < last; i++ ) {
int offset = i - first;
int top = matrix[first][i];
//left-> top
matrix[first][i] = matrix [last-offset][first];
//bottom -> left
matrix[last-offset][first] = matrix [last][last-offset];
//right -> bottom
matrix[last][last-offset]= matrix[i][last];
//top->right
matrix[i][last]=top;
}
}
return true;
}
Hi there, I'm trying to import the CtCI library to solve the problem but there's an error message. And from her GitHub, that was how she imported this class. I know we can import the class from java built-in library. But I'm not sure how import works when trying to import from someone else. Could someone explain it to me?
If you are doing serious programming for a long term app, and by import you refer to libraries/dependencies, I highly recommend you using maven for it.
If you don't use maven yet, you can just add the .jar files from you IDE to your project path, but with maven is way better.
If you mean importing a .java file written by someone else, to use part of it in your code, just put the file at your project path, you probably need to adapt its libraries and imports, and once ready you can just use its methods ans stuff. Just make sure you have tipped at the top of your current file the import sentence of that file.

Analyzer creating multiple diagnostics for compilation unit

I am writing a Roslyn Diagnostic to turn on/off option strict. Since there can only be one per file, I am using the compilation for the node to be examined:
context.RegisterSyntaxNodeAction(CompilationUnitCheck, SyntaxKind.CompilationUnit);
I am seeing multiple diagnostics displayed in the error list pane when running the development hive, at times as many as 3, but always at least 2 per file. They show the same location. What could be causing this, and what can I do to fix it?
private void CompilationUnitCheck(SyntaxNodeAnalysisContext context)
{
var orgRoot = (CompilationUnitSyntax) context.Node;
var fileName = System.IO.Path.GetFileNameWithoutExtension(orgRoot.SyntaxTree.FilePath) ;
if ((fileName?.EndsWith("designer", StringComparison.CurrentCultureIgnoreCase)).GetValueOrDefault() ||
"Reference".Equals(fileName, StringComparison.CurrentCultureIgnoreCase))
{
return;
}
if (fileName != "TestFile") return;
var newErrors = fileName == "TestFile";
var location = orgRoot.GetLocation();
string strictMsg = null ?? "Off";
var diagnostic = Diagnostic.Create(Rule, location, strictMsg);
context.ReportDiagnostic(diagnostic);
}
My current workaround is to get the hashcode of the root, and store that in a static list, if it's in the list, I don't check again.

Read password in Scala in a console-agnostic way

I have an easy task to accomplish: read a password from a command line prompt without exposing it. I know that there is java.io.Console.readPassword, however, there are times when you cannot access console as if you are running your app from an IDE (such as IntelliJ).
I stumbled upon this Password Masking in the Java Programming Language tutorial, which looks nice, but I fail to implement it in Scala. So far my solution is:
class EraserThread() extends Runnable {
private var stop = false
override def run(): Unit = {
stop = true
while ( stop ) {
System.out.print("\010*")
try
Thread.sleep(1)
catch {
case ie: InterruptedException =>
ie.printStackTrace()
}
}
}
def stopMasking(): Unit = {
this.stop = false
}
}
val et = new EraserThread()
val mask = new Thread(et)
mask.start()
val password = StdIn.readLine("Password: ")
et.stopMasking()
When I start this snippet I get a continuos printing of asterisks on new lines. E.g.:
*
*
*
*
Is there any specific in Scala why this is not working? Or is there any better way to do this in Scala in general?

IronRuby performance issue while using Variables

Here is code of very simple expression evaluator using IronRuby
public class BasicRubyExpressionEvaluator
{
ScriptEngine engine;
ScriptScope scope;
public Exception LastException
{
get; set;
}
private static readonly Dictionary<string, ScriptSource> parserCache = new Dictionary<string, ScriptSource>();
public BasicRubyExpressionEvaluator()
{
engine = Ruby.CreateEngine();
scope = engine.CreateScope();
}
public object Evaluate(string expression, DataRow context)
{
ScriptSource source;
parserCache.TryGetValue(expression, out source);
if (source == null)
{
source = engine.CreateScriptSourceFromString(expression, SourceCodeKind.SingleStatement);
parserCache.Add(expression, source);
}
var result = source.Execute(scope);
return result;
}
public void SetVariable(string variableName, object value)
{
scope.SetVariable(variableName, value);
}
}
and here is problem.
var evaluator = new BasicRubyExpressionEvaluator();
evaluator.SetVariable("a", 10);
evaluator.SetVariable("b", 1 );
evaluator.Evaluate("a+b+2", null);
vs
var evaluator = new BasicRubyExpressionEvaluator();
evaluator.Evaluate("10+1+2", null);
First Is 25 times slower than second. Any suggestions? String.Replace is not a solution for me.
I do not think the performance you are seeing is due to variable setting; the first execution of IronRuby in a program is always going to be slower than the second, regardless of what you're doing, since most of the compiler isn't loaded in until code is actually run (for startup performance reasons). Please try that example again, maybe running each version of your code in a loop, and you'll see the performance is roughly equivalent; the variable-version does have some overhead of method-dispatch to get the variables, but that should be negligible if you run it enough.
Also, in your hosting code, how come you are holding onto ScriptScopes in a dictionary? I would hold onto CompiledCode (result of engine.CreateScriptSourceFromString(...).Compile()) instead -- as that will help a lot more in repeat runs.
you can of course first build the string something like
evaluator.Evaluate(string.format("a={0}; b={1}; a + b + 2", 10, 1))
Or you can make it a method
if instead of your script you return a method then you should be able to use it like a regular C# Func object.
var script = #"
def self.addition(a, b)
a + b + 2
end
"
engine.ExecuteScript(script);
var = func = scope.GetVariable<Func<object,object,object>>("addition");
func(10,1)
This is probably not a working snippet but it shows the general idea.

Is there a tool to merge NUnit result files?

For unclear reasons my Nunit test fixture cannot be executed in a single run, so I'm forced to execute a few tests in separate runs. However this means that the test results are splitted over multiple output files.
Is there a tool available which can merge NUnit result XML files into a single XML file?
I've tried using the existing Nunit-summary tool, but this simply sequentially parses the XML files with the given XSL file and concatenates the result as one big file.
Instead I would like it to merge/group the results for the test cases into the right namespaces/testfixtures first and then feed it to the XSLT processor. This way all test results should be displayed by fixture even though they're not gathered in a single run.
This is probably too late to help you, but we recently encountered a similar issue and wrote a small open source tool to help out: https://github.com/15below/NUnitMerger
From the readme:
Using in MSBuild
Load the task:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
ToolsVersion="4.0"
DefaultTargets="Build">
<UsingTask AssemblyFile="$(MSBuildProjectDirectory)\..\Tools\MSBuild\15below.NUnitMerger.dll" TaskName="FifteenBelow.NUnitMerger.MSBuild.NUnitMergeTask" />
...
Feed it an array of files with in a target:
<Target Name="UnitTest" DependsOnTargets="OtherThings">
... Generate the individual files here in $(TestResultsDir) ...
<ItemGroup>
<ResultsFiles Include="$(TestResultsDir)\*.xml" />
</ItemGroup>
<NUnitMergeTask FilesToBeMerged="#(ResultsFiles)" OutputPath="$(MSBuildProjectDirectory)\TestResult.xml" />
</Target>
Find the resulting combined results at OutputPath.
Using in F#
Create an F# console app and add 15below.NUnitMerger.dll, System.Xml and System.Xml.Linq as references.
open FifteenBelow.NUnitMerger.Core
open System.IO
open System.Xml.Linq
// All my files are in one directory
WriteMergedNunitResults (#"..\testdir", "*.xml", "myMergedResults.xml")
// I want files from all over the place
let myFiles = ... some filenames as a Seq
myFiles
|> Seq.map (fun fileName -> XDocument.Parse(File.ReadAllText(fileName)))
|> FoldDocs
|> CreateMerged
|> fun x -> File.WriteAllText("myOtherMergedResults.xml", x.ToString())
I was using the 15below NUnitMerger above for a while, but wanted to extend it and since my F# skills are not good enough to do it there, I inspected their mechanism and implemented the following class in C# to achieve the same thing. Here is my starting code which might help anyone who also want to do this kind of manipulation in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
namespace RunNUnitTests
{
public static class NUnitMerger
{
public static bool MergeFiles(IEnumerable<string> files, string output)
{
XElement environment = null;
XElement culture = null;
var suites = new List<XElement>();
bool finalSuccess = true;
string finalResult = "";
double totalTime = 0;
int total = 0, errors = 0, failures = 0, notrun = 0, inconclusive = 0, ignored = 0, skipped = 0, invalid = 0;
foreach (var file in files)
{
var doc = XDocument.Load(file);
var tr = doc.Element("test-results");
if (environment == null)
environment = tr.Element("environment");
if (culture == null)
culture = tr.Element("culture-info");
total += Convert.ToInt32(tr.Attribute("total").Value);
errors += Convert.ToInt32(tr.Attribute("errors").Value);
failures += Convert.ToInt32(tr.Attribute("failures").Value);
notrun += Convert.ToInt32(tr.Attribute("not-run").Value);
inconclusive += Convert.ToInt32(tr.Attribute("inconclusive").Value);
ignored += Convert.ToInt32(tr.Attribute("ignored").Value);
skipped += Convert.ToInt32(tr.Attribute("skipped").Value);
invalid += Convert.ToInt32(tr.Attribute("invalid").Value);
var ts = tr.Element("test-suite");
string result = ts.Attribute("result").Value;
if (!Convert.ToBoolean(ts.Attribute("success").Value))
finalSuccess = false;
totalTime += Convert.ToDouble(ts.Attribute("time").Value);
if (finalResult != "Failure" && (String.IsNullOrEmpty(finalResult) || result == "Failure" || finalResult == "Success"))
finalResult = result;
suites.Add(ts);
}
if (String.IsNullOrEmpty(finalResult))
{
finalSuccess = false;
finalResult = "Inconclusive";
}
var project = XElement.Parse(String.Format("<test-suite type=\"Test Project\" name=\"\" executed=\"True\" result=\"{0}\" success=\"{1}\" time=\"{2}\" asserts=\"0\" />", finalResult, finalSuccess ? "True" : "False", totalTime));
var results = XElement.Parse("<results/>");
results.Add(suites.ToArray());
project.Add(results);
var now = DateTime.Now;
var trfinal = XElement.Parse(String.Format("<test-results name=\"Merged results\" total=\"{0}\" errors=\"{1}\" failures=\"{2}\" not-run=\"{3}\" inconclusive=\"{4}\" ignored=\"{5}\" skipped=\"{6}\" invalid=\"{7}\" date=\"{8}\" time=\"{9}\" />", total, errors, failures, notrun, inconclusive, ignored, skipped, invalid, now.ToString("yyyy-MM-dd"), now.ToString("HH:mm:ss")));
trfinal.Add(new[] { environment, culture, project });
trfinal.Save(output);
return finalSuccess;
}
}
}
I read on the web that Nunit result files are XML so i guess you can merge the file with an ordinary merge software as WinMerge