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);
Related
I am facing a problem with registration and login flow where it is required to generate an email and get token for verification. I need a service which allows user to generate n numbers of disposable emails with email data access that can self-destructs max 24 hours. Could anyone please share the service code to use in selenium java automation?
The QA teams leave such tasks for manual testing instead of writing automation tests for these scenarios. \
But, all communication from the email can be automated by the disposable email service. This article will describe how to use this service within the automation suite using Nightwatch.js (Node).
Registration and Login automation
You can use this code as well to automate such things:
2. Write down the logic of getEmail in common-function class and add dependencies in pom.xml file :
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
We will use Unirest for handling the Mail7 API code. it is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.
Create a mail7.java file with below code
import org.apcahe.commons.lang3.RandomStringUtils;
public class mail7{
private static final String EMAIL-DOMAIN = ‘mail.io’;
private static final String EMAIL_APIKEY = ‘mail7_api_key’;
private static final String EMAIL_APISecret = ‘mail7_api_secret’;
private String emailid;
public usernameGenerator(){
String username = RandomStringUtils.randomAlphanumeric(8).toLowerCase();
System.out. println(“Random Username is ” + username);
return username;
}
public getInbox(String username){
HttpResponse <String> httpResponse = Unirest.get(“"https://api.mail7.io/inbox?apikey=" + EMAIL_APIKEY + "&apisecret=" + EMAIL_APISecret + "&to=" + username”)
.asString();
System.out.println( httpResponse.getHeaders().get("Content-Type"));
System.out.println(httpResponse.getBody());
return httpResponse.getBody();
}
3. Create a class file for Test Script of Register and Login event :
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class TestEmail throws IOException, UnirestException
{
public static void main(String[] args) {
//create a Selenium WebDriver instance
System.setProperty("webdriver.gecko.driver","dir_path\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//launch the Firefox browser and navigate to the website
driver.get(“YOUR_TEST_URL");
//puts an implicit wait for 10 seconds before throwing exceptions
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//locate the email field
WebElement email = driver.findElement(By.xpath("//input[#type='email']"));
// create a random email address
String username = usernameGenerator();
String emailID = username.concat(“#”+EMAIL_DOMIAN);
//set the field's value
email.sendKeys(emailID);
//locate the password field
WebElement password = driver.findElement(By.xpath("//input[#type='password']"));
//set the password's value
password.sendKeys("password");
//locate and click the submit button
driver.findElement(By.xpath("//input[#type='submit']")).click();
//check if the mail has been received or not
String response = getInbo(username );
if(response.isEmpty()) {
System.out.println("Test not passed");
}else {
System.out.println("Test passed");
}
//close the Firefox browser.
driver.close();
}
}
}
}
After (foolishly) upgrading Appium Server along with various project libraries, such that I cannot tell which, if any, caused the problem, my previously running Appium framework suddenly started failing upon attempting to locate any elements.
The server starts (either manually via desktop or through the java code) and it launches my emulator (if not already loaded), makes the connection, opens the app (in the case show, simply settings) and fails as soon as it tries to validate that the settings main page is displayed by checking the existence of the "Settings" text:
Given the settings app is displayed (FAILED)
(java.lang.IllegalArgumentException: Can not set
io.appium.java_client.android.AndroidElement field
com.mindtree.pageobjects.SettingsMainPage.header to
org.openqa.selenium.remote.RemoteWebElement$$EnhancerByCGLIB$$d27c0df4)
The Appium server versions for both desktop and nodeJS is currently 1.7.2 I believe the problem started when I was originally at 1.7.1 or 1.7.2 and it succeeded in doing an auto-update on the desktop version to 1.8.1.
Selenium version is 3.11.0 (tried various flavors from 3.9.0 through 3.13.0)
Appium Java client is 6.0.0-BETA5 (tried 6.0.0-BETA4, 6.0.0, 6.1.0)
Java is 1.8
The JBehave test step that reports the error:
#Given("the settings app is displayed")
public void givenTheSettingsAppIsDisplayed() {
main = new SettingsMainPage(driver);
if (main.pageLoaded())
test.logGivenPass("the settings app is displayed");
else {
test.logGivenFail("the settings app is displayed");
fail();
}
}
The corresponding page object snippet:
public class SettingsMainPage extends MobilePageObject {
public SettingsMainPage(AndroidDriver<AndroidElement> driver) {
super(driver);
System.out.println("Settings Main page class has been initialized");
}
#AndroidFindBy(xpath = "//android.widget.TextView[#text='Settings']")
AndroidElement header;
#AndroidFindBy(id= "android:id/title")
List<AndroidElement> titles;
#AndroidFindBy(id= "android:id/summary")
List<AndroidElement> summaries;
public Boolean pageLoaded() {
return helper.isDisplayed(header);
}
}
Googling this particular error returns a few hits, but no offered solutions.
Any guidance appreciated.
edit: I should add that the failure seems to happen upon initialization of the page object via the page factory, since the text "initialized" is never shown, it fails while trying to initialize all the page elements, specifically the first one, at least according to the error message.
My base page object is below:
import java.time.Duration;
import org.openqa.selenium.support.PageFactory;
import com.mindtree.helpers.AppiumUtils;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
public class MobilePageObject {
AndroidDriver<AndroidElement> driver;
AppiumUtils helper;
public MobilePageObject(AndroidDriver<AndroidElement> driver) {
this.driver = driver;
PageFactory.initElements(new AppiumFieldDecorator(driver, Duration.ofSeconds(15)), this);
helper = new AppiumUtils();
}
}
Edit Update: Downgraded the Appium Server through NodeJS from 1.7.2 to
1.7.1. Result: no change, same error reported.
I am using Appium server 1.8.1, selenium 3.13.0 and java client 6.1.0. I use the page object model like following and it works fine.
public class SettingsMainPage{
public SettingsMainPage(AndroidDriver<AndroidElement> driver) {
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
System.out.println("Settings Main page class has been initialized");
}
#AndroidFindBy(xpath = "//android.widget.TextView[#text='Settings']")
AndroidElement header;
#AndroidFindBy(id= "android:id/title")
List<AndroidElement> titles;
#AndroidFindBy(id= "android:id/summary")
List<AndroidElement> summaries;
public boolean pageLoaded() {
try{
(new WebDriverWait(driver, 20)).until(ExpectedConditions.visibilityOfElementLocated(header));
return header.isDisplayed();
}
catch(Exception e){
return false;
}
}
}
And you must define your desiredCapabilities like following:
public static AppiumDriver<MobileElement> driver;
public static AppiumDriver<MobileElement> setupDesiredCapabilities(String appPackage, String appActivity,
String udid, String platformVersion, boolean noReset) {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("deviceName", "Android phone"); //any name
caps.setCapability("udid", udid);
caps.setCapability("platformName", "Android");
caps.setCapability("platformVersion", platformVersion);
caps.setCapability("appPackage", appPackage);
caps.setCapability("appActivity", appActivity);
caps.setCapability("noReset", noReset); //optional
try {
driver = new AndroidDriver<MobileElement>(new URL(
"http://127.0.0.1:4723/wd/hub"), caps);
} catch (MalformedURLException e) {
//
} catch (Exception ex) {
//
}
return driver;
}
Make sure you have define static AppiumDriver and use the same
driver object to call constructor of each page.
I am trying to generate Extent Report in selenium. I have written the exact code for generating report , but the folder in which the report must be saved is empty, I have refreshed the project as well but still not able to produce report.Please let me know if I have done any thing wrong in the coding part. Here is my code:
public class ContactUsTestCase {
ExtentHtmlReporter htmlReporter;
ExtentReports extent;
ExtentTest test;
static WebDriver driver;
UtilityMethods util = new UtilityMethods();
#BeforeClass
public void launchBrowser() {
driver = UtilityMethods.openBrowser(Constants.BROWSER_NAME);
UtilityMethods.launchWebsite(Constants.URL);
}
#BeforeTest
public void startReport() {
htmlReporter = new ExtentHtmlReporter("D:\\ExtentReport");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("OS", "win 10");
extent.setSystemInfo("Host Name", "Stewart");
extent.setSystemInfo("Environment", "Chrome");
htmlReporter.config().setDocumentTitle("Automation testig report");
htmlReporter.config().setReportName("Your Logo Report Name");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
#Test(priority = 1)
public void ContactUs() {
test = extent.createTest("ContactUs", "This wil check status for Conatct us page");
// util.clickElement(Constants.OPEN_CONTACTUS);
driver.findElement(By.id("email")).sendKeys("stewart****#yahoo.com");
driver.findElement(By.id("pass")).sendKeys("******");
driver.findElement(By.xpath("//input[#value='Log In']")).click();
test.log(Status.PASS, MarkupHelper.createLabel("PASS", ExtentColor.GREEN));
}
#AfterClass
public void teardown() {
extent.flush();
}
}
You have mentioned the folder name alone. Change this line
htmlReporter = new ExtentHtmlReporter("D:\\ExtentReport");
in your code to
htmlReporter = new ExtentHtmlReporter("D:\\ExtentReport\\nameOfTheReport.html");
You have missed extension for html report,
Your path should be "D:\\Demo_ExtentReport.html"
I have problem with testing my app which is intended for online shopping. I noticed that all buttons from application working but I have problem with system buttons(look at the picture). I’m using to recognize the button UiAutomatorViewer.
At the picture I’m trying add product to cart but when I’m click button “Dodaj”(means Add) the window closes but there are any actions in application, the product should be added to cart. I tested this application manually and everything work correct.
I tried to operate the button in many ways but still nothing. Does anyone know how to solve it? It’s very important functions to testing for me.
public class Product extends MainPage {
private AndroidDriver<AndroidElement> driver;
#FindBy(id = "com.mec.leroy:id/product_add_to_cart")
private WebElement addToCart;
#FindBy(xpath = "//android.widget.Button[#index='1']") //problem with button
private WebElement buttonAdd;
#FindBy(id = "com.mec.leroy:id/product_name")
private WebElement productName;
public Product(AndroidDriver driver) {
super(driver);
this.driver = driver;
}
public Product addProduct() throws InterruptedException {
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView(text(\"do koszyka\"));");
addToCart.click();
buttonAdd.click();
Thread.sleep(5000);
return new Product(driver);
}
public boolean productName() throws InterruptedException {
Thread.sleep(2000);
try {
productName.getText();
return true;
} catch (ElementNotVisibleException e) {
return false;
}
}
public class Connector {
public AndroidDriver Settings() throws IOException, InterruptedException {
runAppium();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "33004db396a6c2d1"); // nazwa urządzenia
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");
capabilities.setCapability("noRest", "true");
capabilities.setCapability("fullReset", "false");
// capabilities.setCapability("useKeystore", "true");
//uruchomienie aplikacji z poziomu telefonu
capabilities.setCapability("appPackage", "com.mec.leroy");
capabilities.setCapability("appActivity", "com.mec.leroy.main.activity.MainActivity");
//inicjalizacja połączenia z Appium Server
AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);
return driver;
}
You are using UiAutomatorViewer (that uses old UiAutomator), but in your tests you are providing UiAutomator2: important to know that these frameworks build snapshot xml in a different way, so your locator might be incorrect.
I suggest to try inspect and interact with your button using official appium-desktop:
Install & launch it
Run the server via appium-desktop
Set exact the same capabilities you have in the code, create new session
Now you can inspect your elements and try to click your button from inspector.
I'm trying to get an item from local storage using Selenium Webdriver.
I followed this site but when I run my code I get NullPointerException.
When I debug the code I see the function: getItemFromLocalStorage returns NULL for some reason.
Here is my code:
public class storage
{
public static WebDriver driver;
public static JavascriptExecutor js;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D://chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://html5demos.com/storage");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("local")).sendKeys("myLocal");
driver.findElement(By.id("session")).sendKeys("mySession");
driver.findElement(By.tagName("code")).click(); // just to escape textbox
String sItem = getItemFromLocalStorage("value");
System.out.println(sItem);
}
public static String getItemFromLocalStorage(String key)
{
return (String) js.executeScript(String.format(
"return window.localStorage.getItem('%s');", key));
}
}
That is because you forgot to instantiate js object correctly. Add below line after driver = new ChromeDriver();.
js = ((JavascriptExecutor)driver);
It will work.
I assume you have NPE on your driver instance.
You can setup driver location property while driver instance creating:
final ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("D://chromedriver.exe")).build();
driver = new ChromeDriver(chromeDriverService);
BTW, I used selenium 2.44.0
Use this Code
WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);
LocalStorage localStorage = webStorage.getLocalStorage();
String user_data_remember = localStorage.getItem("user_data_remember");
String emailAfterLogout;
String passwordAfterLogout;
if (!user_data_remember.equals("")) {
JSONObject jsonObject = new JSONObject(user_data_remember);
Boolean remember = jsonObject.getBoolean("remember");
if (remember) {
emailAfterLogout = jsonObject.getString("email");
passwordAfterLogout = jsonObject.getString("password");
if (emailAfterLogout.equals(email) && passwordAfterLogout.equals(password)) {
System.out.println("Remember me is working properly.");
} else {
System.out.println("Remember me is not working.");
}
}
} else {
System.out.println("Remember me checkbox is not clicked.");
}