Can we generate random unique alphabets for a textfield in katalon studio? - katalon-studio

Does anybody know how to generate unique alphabets for text fields in Katalon studio in each new run? Is this done using custom keywords or the codes are written under the Script section?
I tried to create a custom keyword and kept the following code in the keyword but have no idea how to call the function in my test case. Please help
Code under my custom keyword:
public class testkeyword {
#Keyword
def testkeyword() {
String chars = "abcdefghijklmnopqrstuvwxyz"
println randomString(chars, 10)
}
public static String randomString(String chars, int length) {
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(chars.charAt(rand.nextInt(chars.length())));
}
return sb.toString();
}
}

Your 'testkeyword' class is probably inside of a package (I will call it 'testpackage') you can see in the test explorer on the left-hand side:
Keywords
+ 'testpackage'
+'testkeyword.groovy'
In order to use it in another test case, you will need to import the said package. Add the following import statement at the top of the test case file:
import testpackage.testkeyword
And then call the function with
testkeyword.testkeyword()
inside of the test case.

Related

TextCellEditor with autocomplete in Eclipse SWT/JFace?

I'd like a TextCellEditor with the standard auto-complete behaviour, that that any user nowadays expects when typing inside an input cell with a list of suggested strings. For a good working example of what I'm after, in Javascript, see this jQuery autocomplete widget.
I couldn't find a good example.
I only found (aside from some tiny variations) this TextCellEditorWithContentProposal snippet. But that leaves a lot to be desired:
It lists all the words, irrespective of the "partial word" typed in the cell (no partial matching)
When the desired word is selected, it is appended to the partial word, instead of replacing it
The interaction is ugly and non-intuitive. For example, one would expect the
Escape key to tear off the list of suggestions; again, see the Javascript example; here, it also removes the typed letters.
It looks strange to me that such an standard and useful component is not available. Or perhaps it is available? Can someone point to me to a more apt snippet or example?
The example you are linking to is a code snippet intended to showcase the API and guide you toward customizing the control to your preference.
Some of your complaints are either invalid or can easily be fixed using public API.
Let's go through them in detail.
All proposals are listed, irrespective of typed text
Note that in the snippet an org.eclipse.jface.fieldassist.SimpleContentProposalProvider is used:
IContentProposalProvider contentProposalProvider = new SimpleContentProposalProvider(new String[] { "red",
"green", "blue" });
cellEditor = new TextCellEditorWithContentProposal(viewer.getTable(), contentProposalProvider, null, null);
As suggested in its javadoc it is:
designed to map a static list of Strings to content proposals
To enable a simple filtering of the contents for the snippet, you could call: contentProposalProvider.setFiltering(true);
For anything more complex you will have to replace this with your own implementation of org.eclipse.jface.fieldassist.IContentProposalProvider.
Selection is appended to cell contents, instead of replacing it
The content proposal behavior is defined in the org.eclipse.jface.fieldassist.ContentProposalAdapter. Again a simple method call to org.eclipse.jface.fieldassist.ContentProposalAdapter.setProposalAcceptanceStyle(int) will achieve your target behavior:
contentProposalAdapter = new ContentProposalAdapter(text, new TextContentAdapter(), contentProposalProvider, keyStroke, autoActivationCharacters);
contentProposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
Cancelling the proposal should not remove typed content
This is hard to do using just the API, since the ContentProposalAdapter does only propagate the key strokes to the opened ContentProposalPopup without storing them.
You would have to subclass ContentProposalAdapter, in order to have access to ContentProposalAdapter.ContentProposalPopup.filterText.
Most of the functionality in this snippet with sensible defaults can also be obtained in a more simple way by using an org.eclipse.jface.fieldassist.AutoCompleteField.
Here is a snippet showing you a simple implementation. You have to customize it but it give you the way.
Note, this is not a generic copy/paste of the documentation or an explanation about the doc.
String[] contentProposals = {"text", "test", "generated"};
// simple content provider based on string array
SimpleContentProposalProvider provider = new SimpleContentProposalProvider(contentProposals);
// enable filtering or disabled it if you are using your own implementation
provider.setFiltering(false);
// content adapter with no keywords and caracters filtering
ContentProposalAdapter adapter = new ContentProposalAdapter(yourcontrolswt, new TextContentAdapter(), provider, null, null);
// you should not replace text content, you will to it bellow
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_IGNORE);
// now just put your implementation
adapter.addContentProposalListener(new IContentProposalListener() {
#Override
public void proposalAccepted(IContentProposal proposal) {
if(proposal != null && StringUtils.isNotBlank(proposal.getContent())){
// you need filter with blank spaces
String contentTextField = getFilterControl().getText();
String[] currentWords = getFilterControl().getText().split(" ");
StringBuilder textToDisplay = new StringBuilder();
if(currentWords.length > 1) {
// delete and replace last word
String lastWord = currentWords[currentWords.length-1];
textToDisplay.append(contentTextField.substring(0, contentTextField.length()-1-lastWord.length()));
textToDisplay.append(" ");
}
// add current proposal to control text content
textToDisplay.append(proposal.getContent());
yourcontrolswt.setText(textToDisplay.toString());
}
}
});
If you want more you can also have your own content proposal provider If you need a particular object instead of string or something like.
public class SubstringMatchContentProposalProvider implements IContentProposalProvider {
private List<String> proposals = Collections.emptyList();
#Override
public IContentProposal[] getProposals(String contents, int position) {
if (position == 0) {
return null;
}
String[] allWords = contents.split(" ");
// no words available
if(allWords.length == 0 || StringUtils.isBlank(allWords[allWords.length-1]))
return null;
// auto completion on last word found
String lastWordFound = allWords[allWords.length-1];
Pattern pattern = Pattern.compile(lastWordFound,
Pattern.LITERAL | Pattern.CASE_INSENSITIVE /*| Pattern.UNICODE_CASE*/); // this should be not used for better performances
IContentProposal[] filteredProposals = proposals.stream()
.filter(proposal -> proposal.length() >= lastWordFound.length() && pattern.matcher(proposal).find())
.map(ContentProposal::new).toArray(IContentProposal[]::new);
// no result
return filteredProposals.length == 0 ? null : filteredProposals;
}
public void setProposals(List<String> proposals) {
this.proposals = proposals;
}
}

Drools/Scala - Create var/val inside DRL

I'm trying to use Drools with Scala and i would like to know if it is possible to call a chain of events and create var/val when the function has a return.
Here is what i'm trying but i'm stuck:
import com.models.*
import com.service.*
rule "First Fule"
when
person:Person(name == 'aa')
then
//Here should return a string
//and i should set this string
//something like:
//var x = new Person(ServiceLongDong.sayHello(), person.age, person.name)
//or var y = ServiceLongDong.sayHello();
ServiceLongDong.sayHello();
ServiceLongDong.finish(x);
end
Is possible to create varl/vals and pass it to another function?
Thank in advance.
Rules aren't functions (or methods) and don't "return" values or objects. The right hand side is just Java code. You can call static methods, but stick to correct Java syntax:
Person p = new Person(ServiceLongDong.sayHello(),
person.age, person.name);
ServiceLongDong.sayHello();
ServiceLongDong.finish(x);
This can't be correct Java if ServiceLongDong is a class:
... = ServiceLongDong().sayHello();

ReSharper 8 - Live Template Macros - HotspotItems

I am currently using ReSharper V8.1. I've only recently began using ReSharper and have found some interest in their LiveTemplate Macros. I've conjured up a solution to return a list of HotspotItems from a constant, similar to ReSharper's predefined macro "Comma-delimited list of values". In the method I take the constant variable of the template parameter and do a split string on them to provide a collection of HotSpotItems. Unfortunately it doesn't work if I use the macro more than one time within a template. Below is an extreme hack job showing my implementation of the method HotspotItems of IMacroImplementation.
I am hoping that someone out there may have done some work in this area and could possibly provide an example of how they've implemented IMacroImplementation which provides a list of items from a constant and also allows for multiple uses within a single template.
Thank you.
public override HotspotItems GetLookupItems(IHotspotContext context)
{
HotspotItems hotSpotItems = null;
foreach (var hotspot in context.HotspotSession.Hotspots)
{
if (hotspot.Expression != null && ((MacroCallExpressionNew)hotspot.Expression).Definition is Macros.DisplayMultipleItems)
{
//hotspot.CurrentValue
var multiItems = ((MacroCallExpressionNew) hotspot.Expression).Definition as DisplayMultipleItems;
if (!multiItems.ItemSet)
{
var expression = hotspot.Expression as MacroCallExpressionNew;
IMacroParameterValueNew baseValue = expression.Parameters[0].GetValue(context.SessionContext.Solution.GetLifetime(), context.HotspotSession);
string templateValue = baseValue.GetValue();
multiItems.ItemSet = true;
if (!string.IsNullOrEmpty(templateValue) && templateValue.Split(',').Any())
{
var lookupItems = templateValue.Split(',').Select(param => new TextLookupItem(param)).Cast<ILookupItem>().ToList();
if (hotSpotItems == null)
hotSpotItems = new HotspotItems(lookupItems);
else
{
foreach (var item in lookupItems)
{
hotSpotItems.Items.Add(item);
}
}
}
}
}
}
return hotSpotItems;
}
You should fire up dotPeek and point it to the ReSharper bin directory and take a look at ListMacroDef and ListMacroImpl, which is the implementation for the comma-delimited list macro.
The definition derives from SimpleMacroDefinition. It gets given the parameters in the call to GetPlaceholder, looks at the first and splits it by comma, returning the first item as the placeholder.
ListMacroImpl is just as simple. Its constructor has an [Optional] parameter of type MacroParameterValueCollection. This is the list of parameter values specified in the hotspot editor. You'll want to check for null and take the first parameter, which will be your delimited list. It then overrides GetLookupItems and returns HotspotItems.Empty if the parameter value is null, or parses the value and returns a list of TextLookupItem.
You don't need to look at the session and list of hotspots - that will get you all hotspots in the session, when you're only interested in the current hotspot, and ReSharper will create a new IMacroImplementation for each hotspot and give you those values in your constructor.

How to dynamically add a key:value property to c++ class, then make it accessible as class.property

In Python I have a flag class that I have found very useful. I'm newbe to c++, and can not seem to replicate this python functionality in c++. Rather than put up c++ code that didn't work, here's what I am looking to replicate, and I need some suggestions on where to go, templates, virtual, or ??
The requirement is being able to dynamically alter the members of the class, in python it's modifying the dict element of the class it's self that enables this.
In python:
import sys
args = []
... loads up args[] with keys:values looping through sys.argv[] ... blah blah blah
class Flag:
def __ init __(self, **args):
self. __ dict __.update(args)
now we enable flag.dynamicproperty
flag = Flag(**dict(args))
An example of use:
$ python script.py somedesc1 someval1 somedesc2 someval2
What this does is enables me to pass in parameters, as above, from the command-line and assign any number of them on-the-fly, and make then accessible by a flag.property (eg flag.somedesc1) call which returns somval1. Another way to maybe think about this is dynamically adding a key:value property to a C++ class.
An example of use in python code :
if flag.somedesc1 != '10': print someval1
I can't seem to make a comparable c++ work. I've looked into polymorphism, but these have to be assigned dynamically and then be accessible as a property of the class.
Ideas??? Surely c++ can do this, I'm just not sure where to start.
Okay, here is the solution I worked out; haven't tested it yet, but should work close enough to fit my needs using this format
flag.find(filename)
enum { filename, workers, runtime };
class flag {
vector<string> helplist;
public:
int add(int argc, char *argv[], string flag, string value, string description) {
string flagvalue;
flagvalue = value;
helplist.push_back(description);
for (int i; i < argv.length(); i++) {
if (argv[i]==flag) {
flagvalue = argv[i+1];
}
}
}
void showhelp() {
for (int i; i < helplist.length(); i++) {
cout << helplist[i] << endl;
}
}
};
No, you can't do this in C++. In C++, the members of a class are defined 100% at compile time. You cannot add any at runtime. The way to do this in C++ would be to have a member variable that's a map<string,string> that holds the key/value pairs, and then have a function string getVariable(string) that returns the value in the dictionary for that key.

Working with Java; HashMaps and ArrayLists not compiling in Eclipse or BlueJay

I am having trouble getting HashMaps and ArrayLists to work correctly on my computer. I have tried using my own code, and copying samples from textbooks and online to make sure my syntax is correct, but thus far neither Eclipse or BlueJay will let me "add" or "put" things into these data structures. Here are some examples of what I have done.
package issues;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;
public class StructureIssues {
/*
* HashMap Attempt
*/
HashMap<Integer, String> numberNames = new HashMap<Integer, String>();
numberNames.put(new Integer(1), "hi");// here, I have syntax errors asking me to
// delete the (), and I have misplaced
// constructs on the dot.
//When the above line didn't work, I tried creating the objects
//outside of the parameter list...
Integer one = new Integer(1);
String myString = "hi";
numberNames.put(one, myString); //here it just complains about the parenthesis
//similar results for <String,String> and generic
/*
* ArrayList Attempt
*/
ArrayList<String> tryStrings = new ArrayList<String>();
String tryOne = "one";
tryStrings.add(tryOne);//Syntax error on tryOne; variable declarator ID expected
//also, syntax error on the dot; misplaced constructs
ArrayList<Integer> tryInts = new ArrayList<Integer>();
tryInts.add(new Integer(4));//Syntax error on add; expected "=" after it.
//Below, I have copied two lines from Big Java by Horstmann.
//The results are the same as my first String ArrayList attempt.
ArrayList<String> friends = new ArrayList<String>();
friends.add("Cindy");
}
I did find one or two questions similar to mine, and I followed their advice, but so far I've had no luck. Here is what I have tried to far to figure this out:
-Reinstalled my JDK package several times, trying both 64 and 32-bit
-Reinstalled eclipse Indigo several times, trying both 64 and 32-bit
-In eclipse, gone to Project->Properties->Java Compiler. My java compliance is JavaSE-1.7
-In eclipse, gone to Window->Preferences->InstalledJREs. I have jre7 with Standard VM.
-I have tried right clicking on my jre System Library in my packages, and changing to JavaSE-1.6, 1.7, and checking the default workspace box for jre7.
-I have tried similar code in BlueJay because I wanted to try another IDE to see if it was eclipse or my computer. I received: "identifier" expected. It highlighted tryStrings.add("one");
Am I doing something silly here? Any advice you guys could offer would be greatly appreciated. Thank you for your time.
Your code is not in any method. You may declare and initialize fields in a class. But using these fields should be done in methods (or constructors).
Problem is that the code is not in any method. Where you are calling the put method is the area where you declare the variables. see this modified code. I made the variable static so that it can be called from the main method.
public class StructureIssues {
/*
* HashMap Attempt
*/
static HashMap<Integer, String> numberNames = new HashMap<Integer, String>();
public static void main(String args[]) {
numberNames.put(new Integer(1), "hi");// here, I have syntax errors
// asking me to
// delete the (), and I have
// misplaced
// constructs on the dot.
// When the above line didn't work, I tried creating the objects
// outside of the parameter list...
Integer one = new Integer(1);
String myString = "hi";
numberNames.put(one, myString); // here it just complains about the
// parenthesis
// similar results for <String,String>
// and generic
/*
* ArrayList Attempt
*/
ArrayList<String> tryStrings = new ArrayList<String>();
String tryOne = "one";
tryStrings.add(tryOne);// Syntax error on tryOne; variable declarator ID
// expected
// also, syntax error on the dot; misplaced
// constructs
ArrayList<Integer> tryInts = new ArrayList<Integer>();
tryInts.add(new Integer(4));// Syntax error on add; expected "=" after
// it.
// Below, I have copied two lines from Big Java by Horstmann.
// The results are the same as my first String ArrayList attempt.
ArrayList<String> friends = new ArrayList<String>();
friends.add("Cindy");
}
}