How to navigate to a URL by calling on a method? Java - java

I am having issues implementing a way to navigate a URL where the user simply needs to try and change a variable.
I am unable to use the navigate().to() method as it expects a string but want to know if there is a way around this to be able to navigate to a url?
Code below:
steps page - steps.java
#Given("^I navigate to test website$")
public void i_navigate_to_test_website() throws Throwable {
driver.navigate().to(test.setEnvironment("testEnvironment"));
}
class page - test.java
public void setEnvironment(String platform) {
if(platform.equalsIgnoreCase("testEnvironment"))
{
env= Env1;
}
EnvUsed.add(env);
}
public static String Env1 = "http://www.test1.com";
public static String Env2 = "http://www.test2.com";
public static String Env3 = "http://www.test3.com";

Below answer might help you to navigate url with a variable ( parametric ).
steps page - steps.java
#And("^I navigate to test website$")
public void navigateTestEnv(DataTable testEnv) {
List<List<String>> data = testEnv.raw();
classpage.navigateTestEnv(data.get(1).get(1));
}
class page - test.java
public ProductPage navigateTestEnv(String testEnv) {
driver.navigate().to(testEnv);
}
Cucumber Feature page - test.feature
And I navigate to test website
| Fields | Values |
| testEnv | http://www.test1.com |

Related

Spring Boot Web RestTemplate Send Object as Query Param

I want to make a POST request with URL Query Params set to the values of an object.
For example
http://test/data?a=1&b=2&c=3
I want to make a post request to this URL with a class like this:
public class Data {
private Integer a;
private Integer b;
private Integer c;
}
I do NOT want to do each field manually, like this:
public void sendRequest(Data data) {
String url = UriComponentsBuilder.fromHttpUrl("http://test/")
.queryParam("a", data.getA())
.queryParam("b", data.getB())
.queryParam("c", data.getC())
.toUriString();
restTemplate.postForObject(url, body, Void.class);
}
Instead, I want to use the entire object:
public void sendRequest(Data data) {
String url = UriComponentsBuilder.fromHttpUrl("http://test/")
.queryParamsAll(data) //pseudo
.toUriString();
restTemplate.postForObject(url, body, Void.class);
}
Your requirement is like QS in js. Thx qianshui423/qs . It is implementation QS in java. It is coded by a Chinese guy. At first git clone it and use below cmd to build. You will get a jar called "qs-1.0.0.jar" in build/libs (JDK required version 8)
# cd qs directory
./gradlew build -x test
Import it, I do a simple demo as below. For your requirement, you can build class to transfer your Obj into QSObject. Besides toQString, QS can parse string to QSObject. I think it powerful.
import com.qs.core.QS;
import com.qs.core.model.QSObject;
public class Demo {
public static void main(String[] args) throws Exception{
QSObject qsobj = new QSObject();
qsobj.put("a",1);
qsobj.put("b",2);
qsobj.put("c",3);
String str = QS.toQString(qsobj);
System.out.println(str); // output is a=1&b=2&c=3
}
}

Examples are not executing in Cucumber,Web Page is not Initiated

public class Login_Applicant_StepDef {
WebDriver driver;
#Given("^the URL$")
public void the_URL() throws Throwable {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\SSMP\\Downloads\\chromedriver_win32\\ChromeDriver.exe");
driver = new ChromeDriver();
driver.get("http://localhost:4200/app-home");
}
#When("^Click on the Applicant Click here button$")
public void click_on_the_Applicant_Click_here_button() {
driver.findElement(By.xpath("//a[contains(text(),'Candidate click here')]")).click();;
//JavascriptExecutor jvs= (JavascriptExecutor)driver;
//jvs.executeScript("argumnets[0].click()",emailBtn);
}
#Then("^user will navigate to login Page$")
public void user_will_navigate_to_login_Page() {
driver.navigate().to("http://localhost:4200/candidate");
}
#Then("^enter valid \"([^\"]*)\"$")
public void enter_valid_email(String email) {
driver.findElement(By.xpath("//input[#id='mat-input-0']")).sendKeys(email);
}
#Then("^click on Submit button$")
public void click_on_Submit_button() {
driver.findElement(By.xpath("//span[#class='mat-button-wrapper']")).click();
//JavascriptExecutor js= (JavascriptExecutor)driver;
//js.executeScript("argumnets[0]..click()",loginBtn);
}
}
I've created two feature files and step definitions and right now 1 feature file, and step definition linked to TestRunner.How to link multiple FF and Stepdefs to the Test runner
also, Programme is not running with examples though I've added
Applicant login
Test Runner
#App_login
Feature: Optevus Applicant Login Feature
Scenario Outline: login with valid Credentials
Given the URL
When Click on the Applicant Click here button
Then user will navigate to login Page
Then enter valid "<email>"
Then click on Submit button
Examples:
| email |
| kallursh#gmail.com |
| kallurishar#gmail.com |
You didn't state which language you use, buty I'm assuming Java. I have answered some questions about this here and here. That should help you with multiple feature files. I'm not sure you can have multiple glue files/step definitions. But you can use your step definitions to invoke methods in other class files.
In #CucumberOptions, provide folder path where feature files resides in feature option and stepdef folder path in glue option.

Passing String from Jenkins to Java code

My framework consists of TestNG + Cucumber +Jenkins , I'm running the job using bat file configuration in jenkins.
My doubt is , I have a class file to launch the browser and I pass string value to if loop saying ,
if string equals "chrome" then launch the Chrome browser and soon.
Is there a way to pass the chrome value from jenkins into class file ?
example :
public class launch(){
public static String browser ="chrome"
public void LaunchBrowser() throws Exception{
if (browser.equalsIgnoreCase("chrome"))
{
launch chrome driver
}
}
Now i would like to pass the static string value from jenkins ,
Help is appreciated.
Thanks in advance.
You can do something like below
public class Launch {
//You would be passing the Browser flavor using -Dbrowser
//If you don't pass any browser name, then the below logic defaults to chrome
private static String browser =System.getProperty("browser", "chrome");
public void LaunchBrowser() throws Exception {
if (browser.equalsIgnoreCase("chrome")) {
//launch chrome driver
}
}
}

Convert First Letter to Capital using String Template

I am using String template file to generate java files. For that i am using ANTLR. Code for One of the string template file is shown below:
package framework;
public abstract class Listener$GUIdriver.name$ {
$GUIdriver.commands:{ command |
public abstract void onNew$command.name;format="capital"$Command
($command.allParameter:{ param | $param.type.name$ newValue};separator=" , "$);
}; separator="\n"$
$GUIdriver.allDataAccess:{ dataAccess |
public abstract void onNew$dataAccess.dataAccessName;format="capital"$Request(String request);
}; separator="\n"$
}
But it doesnot produce effect of format="capital".How to incorporate such changes?Should i need to include any package or file?I am new to String Template & ANTLR.
The format string you want to use is "cap"
format="cap"
You'll need to register the StringRenderer first, however :-)
stGroup.registerRenderer(String.class, new StringRenderer());
More detail
Here's an example group file, testGroup.stg:
group testGroup;
test(text) ::= <<
<text; format="cap">
>>
and here's an example of using it:
import org.stringtemplate.v4.*;
public class Test {
public static void main(String[] args) {
STGroup stGroup = new STGroupFile("testGroup.stg");
ST st = stGroup.getInstanceOf("test");
stGroup.registerRenderer(String.class, new StringRenderer());
st.add("text", "helloWorld"); // note lower case 'h'
System.out.println(st.render());
}
}
This renders:
HelloWorld
method(item) ::= <<
<item.name; format="cap">Value
>>

How to make comment on facebook post using selenium

public class testngprj {
public String baseurl="https://www.facebook.com/";
public WebDriver dv= new FirefoxDriver();
#Test (priority=0) public void gettitleverified() {
String expectedTitle="Facebook - Log In or Sign Up";
String actualtitle=dv.getTitle();
AssertJUnit.assertEquals(expectedTitle, actualtitle);
}
#Test (priority=1) public void validlogin() {
dv.findElement(By.id("email")).sendKeys("username");
dv.findElement(By.id("pass")).sendKeys("pass");
dv.findElement(By.id("loginbutton")).click();
}
#Test (priority=2) public void makecomment() {
//JavascriptExecutor jse = (JavascriptExecutor)dv;
//jse.executeScript("window.scrollBy(0,2000)", "");
dv.findElement(By.xpath("/html/body/div[1]/div[1]/div/div/div/div[1]/div/div/div[2]/ul/li[1]/a/span")).click();
dv.findElement(By.className("_209g _2vxa")).sendKeys("Nice one");
dv.findElement(By.className("_209g _2vxa")).sendKeys(Keys.ENTER);
}
#BeforeTest public void beforeTest() {
dv.get(baseurl);
}
#AfterTest public void afterTest()
{
}
}
Finally I did it ! Check this chunk of code in python.
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
firefox_options = Options()
firefox_options.add_argument('--dns-prefetch-disable')
firefox_options.add_argument('--no-sandbox')
firefox_options.add_argument('--lang=en-US')
browser = webdriver.Firefox(executable_path='/home/coder/Documents/Projects/socialbot/geckodriver', firefox_options=firefox_options)
browser.get('https://www.facebook.com/')
signup_elem = browser.find_element_by_id('email')
signup_elem.send_keys('EMAILHERE')
login_elem = browser.find_element_by_id('pass')
login_elem.send_keys('PASSHERE')
ins = browser.find_elements_by_tag_name('input')
for x in ins:
if x.get_attribute('value') == 'Log In':
x.click() # here logged in
break
#then key here move to mobile version as that doesn't support javascript
browser.get('https://m.facebook.com')
el = browser.find_element_by_name('query')
el.send_keys('antony white')
el.send_keys(Keys.ENTER)
sleep(3)
temp= ''
ak = browser.find_elements_by_tag_name('a')
for a in ak:
if a.get_attribute('href').endswith('search'):
a.click()
temp = a.get_attribute('href')[:a.get_attribute('href').find("?")]
break
# CLICK TIMELINE
browser.get(temp+'?v=timeline')
sleep(10)
# find last post (occurance of comment)
as_el = browser.find_elements_by_tag_name('a')
for a in as_el:
print(a.text)
if 'omment' in a.text.strip():
a.click()
break
sleep(10)
# do actual comment
ins = browser.find_element_by_id('composerInput')
ins.send_keys('Best cars !')
# submit input
ins = browser.find_elements_by_tag_name('input')
for x in ins:
if 'omment' in x.get_attribute('value'):
x.click()
break
Move to mobile facebook version saved my life. The last. I tried to do that with facebook api. But their Api REALLY SUCKS ! I did, waste a lot of time on their graph api, that was a disaster. And I think facebook want to kill somebody with their graph api.
Try this:
dv.findElement(By.xpath("//a[#class='UFILikeLink']")).click();
Thread.sleep(2000);
dv.findElement(By.xpath("//a[#class='comment_link']")).click();
dv.findElement(By.className("_54-z")).sendKeys("hgfghjkj");
Thread.sleep(2000);
dv.findElement(By.className("_54-z")).sendKeys(Keys.RETURN);

Categories

Resources