Dynamically setting content in Geb - xpath

I want to define a method in a groovy class that I can pass an xpath to on the fly(in order for the same method to be reusable depending on the application). The code snippet below is just a proof of concept, however I would eventually like to build a library of re-usable commands/components, which is why I would like to learn how to dynamically define page content.
If I try this:
import geb.Page;
class oneStepDefMethodClass extends Page {
static url = 'http://www.google.com'
static content = {
queryInput { $("input", id: "gbqfq") }
queryButton { $("button",name: "btnG") }
//songLink { $("span._BZ")}
}
....
void assertSongInResults2(String xpathOfSongLink){
println "Waiting on video link "+ xpathOfSongLink
songLink { $(xpathOfSongLink)}
waitFor {
songLink.displayed
}
}
}
I get this error :groovy.lang.MissingMethodException: No signature of method: geb.navigator.NonEmptyNavigator.songLink() is applicable for argument types: (oneStepDefMethodClass$_assertSongInResults2_closure3) values: [oneStepDefMethodClass$_assertSongInResults2_closure3#7c455e96]
If I throw a
content={songLink {$(xpathOfSongLink)}
}
block in the assertSongInResults2 method, I get this error:
geb.error.UnresolvablePropertyException: Unable to resolve songLink as content for oneStepDefMethodClass, or as a property on its Navigator context. Is songLink a class you forgot to import?
So, yeah is there a way to dynamically define page content like that? The program executes fine if I define it statically up top with the rest of the content , but that is not the point, I want to create re-usable resources instead of redefining the wheel every time I want to use geb.

Solved as I was writing the question, but thought I would post in case anyone else has a similar problem
static String someXpath
static content = {
queryInput { $("input", id: "gbqfq") } //
queryButton { $("button",name: "btnG") } //
songLink { $(someXpath) } //syntax element.className
}
....
void assertSongInResults2(String xpathOfSongLink){
println "Waiting on video link "+ xpathOfSongLink
someXpath=xpathOfSongLink
waitFor {
songLink.displayed
}
}

Related

I wanted to make a separate method for listeners in the root view but it throws NPE

I have a borderpane as the root view and it was getting kind of big so I wanted to divide them into small chunks… with Views there is no problem, I can easily separate them into files and classes.
The problem I am having is that when I want to make a separate method for root view's listeners, it is throwing NPE.
This was my original code:
override val root = borderpane {
addClass(rootStyle)
paddingAll = 10.0
// listeners
setOnMouseEntered { scaleUp() }
setOnMouseExited { scaleDown() }
// end listeners
center {...}
}
}
This is my current code that throws NPE:
override val root = borderpane {
addClass(rootStyle)
paddingAll = 10.0
setListeners() // I added this
center {...}
}
}
private fun setListeners(){
with(root) {
setOnMouseEntered { scaleUp() }
setOnMouseExited { scaleDown() }
}
}
I tried it without with(root) but IDE highlighted them as errors.
I also tried to call the method in onBeforeShow(), it didn't throw any exceptions but listeners didn't work.
What is a proper way to handle this? In Android I easily make setListeners() method and call it from onCreate(). What would be an optimal equivalent of this in TornadoFX?
Edited:
I found a working code but still I am not sure if it is an optimal way... if you have better ways to handle this type of situations, feel free to add your answer.
Wheeee, it was right under my nose. I passed this (borderpane) into a method and it worked as expected.
override val root = borderpane{
setListeners(this)
}
private fun setListeners(borderPane: BorderPane) {
with(borderPane) {
setOnMouseEntered { scaleUp() }
setOnMouseExited { scaleDown() }
}
}

How to know the size of payload in response interceptor using grails

I am using grails spring boot for my project. and I am also using interceptors and filters. Currently, I have a test case to include the size of response data. For this, in interceptor, I have integrated the after method of grails interceptor. while debugging, I didn't found any method to know the data size which i sent from my controller. e.g
class RestController {
def show {
def data = [:]
data.put("object", "some data objects " );
withFormat {
json {
render wrapper as JSON
}
}
}
}
// interceptor.
class RestInterceptor {
RestInterceptor(){
match(controller:"rest", action:"*")
}
boolean before() {
println( request)
true }
boolean after() {
println response
true
}
void afterView() {
// no-op
}
}
In response object, Their is not any method to know the content length. However, I can see the same in request object. please give suggestion.
The after method is executed after the controller action is invoked and before the view is rendered. If you want to inspect something in the model, you can do that in the after method but that doesn't really tell you the size of what is written the response. If you want the latter, you probably want to use afterView instead of after.

How can I attach a header to all published messages?

I have a particular header that I'd like to attach to all messages that I publish. I can attach this header on a case-by-case basis by specifying it in the Publish call:
_bus.Publish(myMessage, context => context.SetHeader("my key", "my value"));
This works fine but it becomes a chore to maintain this SetHeader call for every publish. Is there a way, during bus configuration or anywhere else, to specify a header that will be attached to all messages? That is, is there a way to do something like the following?
ServiceBusFactory.New(sbc =>
{
sbc.UseRabbitMq();
sbc.ReceiveFrom(hdoQueue);
// This is what I'd like to be able to do:
sbc.BeforePublish(context => context.SetHeader("my key", "my value"));
});
I believe there is a solution that involves implementing IOutboundMessageInterceptor but I can't find a way to attach my interceptor. There is a ServiceBusConfigurator.AddInboundInterceptor method but not a ServiceBusConfigurator.AddOutboundInterceptor method.
My intuition was correct, I was able to do what I wanted by implementing IOutboundMessageInterceptor:
public class AttachHeadersOutboundInterceptor : IOutboundMessageInterceptor
{
public void PreDispatch(ISendContext context)
{
context.SetHeader("my key", "my value");
}
public void PostDispatch(ISendContext context)
{
}
}
Oddly there is no ServiceBusConfigurator.AddOutboundInterceptor method, so I just created one (by copying the code for AddInboundInterceptor from github):
public static class MassTransitExtensions
{
public static void AddOutboundInterceptor(this ServiceBusConfigurator configurator,
IOutboundMessageInterceptor interceptor)
{
var builderConfigurator = new PostCreateBusBuilderConfigurator(bus =>
{
var interceptorConfigurator = new OutboundMessageInterceptorConfigurator(bus.OutboundPipeline);
interceptorConfigurator.Create(interceptor);
});
configurator.AddBusConfigurator(builderConfigurator);
}
}
And then I attach it during bus configuration:
ServiceBusFactory.New(sbc =>
{
sbc.UseRabbitMq();
sbc.ReceiveFrom(hdoQueue);
sbc.AddOutboundInterceptor(new AttachHeadersOutboundInterceptor());
});
Problem solved.

lwuit change UI language

I use codenameone to develop my mobile application. In this application I implement some classes and codes manually for instance create all forms by hard coding not using codenameone designer for some reason.
By the way I wanted to navigate in forms like what codenameone use, so I use one variable from type of Form called it prevForm and when I want to open a form I set it to current form and then I show new form.
Ok, that is main scenario. In this application I wanna implement internationalization too, so I create my own hashtable (Farsi and English) for this application.
This is my problem:
How can I set or change language and apply it to forms that I opened?
Is my method for navigate between forms are good?
Here is my code:
public class BaseForm extends Form implements ActionListener {
public BaseForm(){
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
}
Command exit, ok, back;
Form prevForm;
protected void initForm(){
}
protected void showForm(){
}
protected void showForm(final Form prevForm){
//String name = this.getName();
//if("Reminder".equals(name) || "3Transaction".equals(name))
{
this.prevForm = prevForm;
Form f = this;
back = new Command("Back");
//ok = new Command("Ok");
//delete = new Command("Delete");;
Button button = new Button("Button");
f.addCommand(back);
//f.addCommand(ok);
//f.addCommand(delete);
//f.addComponent(button);
f.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getCommand().equals(back)) {
//Do Exit command code
System.out.println("Back pressed");
prevForm.showBack();
} else if (ae.getCommand().equals(ok)) {
//Do Start command code
System.out.println("Ok pressed");
}
}
});
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
//Do button code
System.out.println("Action performed");
}
});
}
showForm();
}}
for open nested form I use this code:
LanguageUI lang = new LanguageUI();
lang.showForm(this);
change language [form]:
protected boolean onBtnSave() {
if(isRbFarsiSelected()){
UIManager.getInstance().setResourceBundle(new CommonSettings().getFarsi());
}
else {
UIManager.getInstance().setResourceBundle(new CommonSettings().getEnglish());
}
return false;
}
I also hard code my UI on lwuit, and i have a variable parentForm on every class so i can easily show previous form. For language change i know there is Localization in the resource editor that you can make use of. Below is how you can access it. I guess the trick is how to set the content of the L10N in the res file in code? On the other hand you can create your own helper classes that mirror the methods below.
Resources theme = Resources.open("/theme.res");
theme.getL10N(id, locale);
theme.getL10NResourceNames();
theme.isL10N(name);
theme.listL10NLocales(id)

Are there page checkers in WATIN which execute on each page load?

I am writing automation scripts using WATIR and WATIN. Watir has something called page checkers, which are code snippets that run on each page load. Is there something similar in WATIN ? I want a piece of code to run on each page load. Generally this is used to check for page errors or page loading images.
It is not really that easy to tell when page loads. I quickly googled about that page checkers in Watir, that you mentioned and found an article about page checkers in Watir. See first comment bellow the article. AFAIK it's really similar in WatiN.
Unfortunately, I don't see any similar functionality in WatiN (no event is fired after internal call to WaitForComplete. The easiest thing you could do is to subclass eg. IE class:
class MyIE : IE
{
public MyIE(string url) : base(url) { } //TODO: add constructors
public override void WaitForComplete(int waitForCompleteTimeOut)
{
base.WaitForComplete(waitForCompleteTimeOut);
Console.WriteLine("Page has been loaded");
}
}
However, the situation will be similar to described in mentioned comment (runs a lot more regularly than just page load).
I think that better approach would be using Page class from WatiN library. It is well documented. Example for watin.org webpage:
var ie = new MyIE("http://watin.org/");
var homePage = ie.Page<HomePage>();
Console.WriteLine(homePage.FirstFeature);
homePage.DocumentationLink.Click();
var documentationPage = ie.Page<DocumentationPage>();
Console.WriteLine(documentationPage.FAQLink.Url);
To run that code you need following classes:
abstract class WatiNBasePage : Page
{
[FindBy(Id = "header")]
public Div HeaderDiv { get; set; }
public Link HomeLink { get { return HeaderDiv.Link(Find.ByText("Home")); } }
public Link DocumentationLink { get { return HeaderDiv.Link(Find.ByText("Documentation")); } }
protected override void InitializeContents()
{
base.InitializeContents();
VerifyDocumentProperties(UnverifiedDocument, errorMessage => { throw new Exception(errorMessage); }); //TODO: modify if needed
}
protected override void VerifyDocumentProperties(Document document, Page.ErrorReporter errorReporter)
{
base.VerifyDocumentProperties(document, errorReporter);
if (!HomeLink.Exists)
errorReporter("HomeLink not exists");
//TODO: more checks here
}
}
class HomePage : WatiNBasePage
{
[FindBy(Id = "features")]
public Table FeatureTable { get; set; }
public string FirstFeature { get { return FeatureTable.Span(Find.First()).Text; } }
}
class DocumentationPage : WatiNBasePage
{
[FindBy(Text = "Frequently Asked Questions")]
public Link FAQLink { get; set; }
}
Basically you need to implement VerifyDocumentProperties. Above code will check if HomeLink exists, but maybe you would like to check if DocumentationLink exists etc. The second thing is to modify call to VerifyDocumentProperties. Now, if verification fails, Exception will be thrown after calling ie.Page<T>() (where T is a subclass of WatinBaseClass).
In my opinion, even if you don't need to use "page checkers", using Page class is still really useful and clarifies the code, so I really recommend using it. I regret that I haven't discovered it when I was starting work with WatiN.

Resources