import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class GroceryStoreTest {
public static void main(String[] args) {
// Set ChromeDriver path
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
// Optional: Add ChromeOptions to disable extensions and hide the popup "Chrome is being controlled by automated test software"
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-extensions");
options.addArguments("disable-infobars");
// Initialize WebDriver
WebDriver driver = new ChromeDriver(options);
// Test steps
try {
// Navigate to the Grocery Store website
driver.get("https://localhost:8000");
// Assert URL contains "http://localhost:8000"
if (!driver.getCurrentUrl().contains("http://localhost:8000")) {
throw new AssertionError("URL assertion failed");
}
// Assert title contains "Grocery Store"
if (!driver.getTitle().contains("Grocery Store")) {
throw new AssertionError("Title assertion failed");
}
// Find all buttons using XPath
java.util.List<WebElement> buttons = driver.findElements(By.xpath("//figcaption/button"));
// Output the number of buttons found
System.out.println("Number of buttons: " + buttons.size());
// Iterate through each button and perform actions
for (int i = 1; i <= buttons.size(); i++) {
// Click on the i-th button
WebElement button = buttons.get(i - 1); // Index in Java List is 0-based
button.click();
// Handle the alert
Alert alert = driver.switchTo().alert();
alert.sendKeys("1");
alert.accept();
}
// Get the text of element with id 'total'
WebElement totalElement = driver.findElement(By.xpath("//*[@id='total']"));
String totalText = totalElement.getText();
System.out.println("Total text: " + totalText);
} catch (Exception e) {
System.err.println("Test failed: " + e.getMessage());
} finally {
// Close the browser
driver.quit();
}
}
}