Monday, January 30, 2023

app

import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class GmailAppTest {
    private AndroidDriver<MobileElement> driver;

    @BeforeMethod
    public void setUp() throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("deviceName", "Android Device");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("appPackage", "com.google.android.gm");
        capabilities.setCapability("appActivity", "com.google.android.gm.ConversationListActivityGmail");
        driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Test
    public void testGmailApp() {
        // Login to Gmail
        MobileElement emailTextBox = driver.findElement(By.id("com.google.android.gm:id/account_address"));
        emailTextBox.sendKeys("your.email@gmail.com");
        MobileElement nextButton = driver.findElement(By.id("com.google.android.gm:id/next_button"));
        nextButton.click();
        MobileElement passwordTextBox = driver.findElement(By.id("com.google.android.gm:id/password_field"));
        passwordTextBox.sendKeys("yourpassword");
        MobileElement signInButton = driver.findElement(By.id("com.google.android.gm:id/sign_in"));
        signInButton.click();

        // Compose and send an email
        MobileElement composeButton = driver.findElement(By.id("com.google.android.gm:id/compose_button"));
        composeButton.click();
        MobileElement toTextBox = driver.findElement(By.id("com.google.android.gm:id/to"));
        toTextBox.sendKeys("recipient.email@gmail.com");
        MobileElement subjectTextBox = driver.findElement(By.id("com.google.android.gm:id/subject"));
        subjectTextBox.sendKeys("Test Email Subject");
        MobileElement bodyTextBox = driver.findElement(By.id("com.google.android.gm:id/body"));
        bodyTextBox.sendKeys("Test Email Body");
        MobileElement sendButton = driver.findElement(By.id("com.google.android.gm:id/send"));
        sendButton.click();

        // Logout from Gmail
        MobileElement drawerButton = driver.

scroll up and down using appium

import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class NaukriAppTest {
    private AndroidDriver<MobileElement> driver;

    @BeforeMethod
    public void setUp() throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("deviceName", "Android Device");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("appPackage", "com.naukri.fragement");
        capabilities.setCapability("appActivity", "com.naukri.fragement.NaukriSplashScreen");
        driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Test
    public void testNaukriApp() {
        // Scroll down
        Dimension size = driver.manage().window().getSize();
        int x = size.width / 2;
        int startY = (int) (size.height * 0.8);
        int endY = (int) (size.height * 0.2);
        new TouchAction(driver).press(x, startY).waitAction().moveTo(x, endY).release().perform();

        // Scroll up
        new TouchAction(driver).press(x, endY).waitAction().moveTo(x, startY).release().perform();

        // Tap on an element
        MobileElement element = driver.findElementById("com.naukri.fragement:id/element_id");
        new TouchAction(driver).tap(element).perform();

        // Double tap on an element
        new TouchAction(driver).tap(element).waitAction(1000).tap(element).perform();
    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
    }
}

Appium code for Naukari app

import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class NaukriAppTest {
    private AndroidDriver<MobileElement> driver;

    @BeforeMethod
    public void setUp() throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("deviceName", "Android Device");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("appPackage", "com.naukri.fragement");
        capabilities.setCapability("appActivity", "com.naukri.fragement.NaukriSplashScreen");
        driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Test
    public void testNaukriApp() {
        // Find and click the 'Login' button
        MobileElement loginButton = driver.findElementById("com.naukri.fragement:id/naukri_login");
        loginButton.click();

        // Enter username and password
        MobileElement username = driver.findElementById("com.naukri.fragement:id/username");
        username.sendKeys("your_username");
        MobileElement password = driver.findElementById("com.naukri.fragement:id/password");
        password.sendKeys("your_password");

        // Find and click the 'Sign In' button
        MobileElement signInButton = driver.findElementById("com.naukri.fragement:id/login");
        signInButton.click();

        // Verify if the user is logged in successfully
        MobileElement profile = driver.findElementById("com.naukri.fragement:id/myProfile");
        assert profile.isDisplayed();
    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
    }
}

customized reports in bdd cucumber framework in c#

[Binding]
public class CustomReportSteps
{
    [AfterTestRun]
    public static void AfterTestRun()
    {
        var jsonFiles = Directory.GetFiles(Path.GetFullPath("TestResult"), "*.json", SearchOption.AllDirectories);

        var reports = new List<Report>();
        foreach (var jsonFile in jsonFiles)
        {
            var content = File.ReadAllText(jsonFile);
            var report = JsonConvert.DeserializeObject<Report>(content);
            reports.Add(report);
        }

        var htmlReport = GenerateHtmlReport(reports);
        File.WriteAllText("CustomReport.html", htmlReport);
    }

    private static string GenerateHtmlReport(List<Report> reports)
    {
        var builder = new StringBuilder();
        builder.Append("<html><head><title>Custom Cucumber Report</title></head><body>");
        builder.Append("<table><tr><th>Feature</th><th>Scenario</th><th>Result</th><th>Time</th></tr>");

        foreach (var report in reports)
        {
            foreach (var feature in report.Features)
            {
                foreach (var scenario in feature.Elements)
                {
                    var result = scenario.Steps.All(step => step.Result.Status == "passed") ? "Passed" : "Failed";
                    var time = scenario.Steps.Sum(step => step.Result.Duration);

                    builder.Append("<tr>");
                    builder.Append($"<td>{feature.Name}</td>");
                    builder.Append($"<td>{scenario.Name}</td>");
                    builder.Append($"<td>{result}</td>");
                    builder.Append($"<td>{time}</td>");
                    builder.Append("</tr>");
                }
            }
        }

        builder.Append("</table></body></html>");
        return builder.ToString();
    }
}

public class Report
{
    public List<Feature> Features { get; set; }
}

public class Feature
{
    public string Name { get; set; }
    public List<Element> Elements { get; set; }
}

public class Element
{
    public string Name { get; set; }
    public List<Step> Steps { get; set; }
}

public class Step
{
    public Result Result { get; set; }
}

public class Result
{
    public string Status { get; set; }
    public int Duration { get; set; }
}

Cypress Facebook

describe('Facebook Register and Post', function() {
  it('Visits Facebook and registers', function() {
    cy.visit('https://www.facebook.com/')
    cy.get('input[name="firstname"]').type('FirstName')
    cy.get('input[name="lastname"]').type('LastName')
    cy.get('input[name="reg_email__"]').type('email@example.com')
    cy.get('input[name="reg_passwd__"]').type('password')
    cy.get('select[name="birthday_month"]').select('Jan')
    cy.get('select[name="birthday_day"]').select('1')
    cy.get('select[name="birthday_year"]').select('2000')
    cy.get('input[type="radio"][value="1"]').check()
    cy.get('button[name="websubmit"]').click()
  })
  
  it('Posts a message', function() {
    cy.get('textarea[name="xhpc_message"]').type('Hello, cypress test!')
    cy.get('button[data-testid="react-composer-post-button"]').click()
  })
})

cucumber reports in selenium using c#

// Feature file
Feature: Login to the website
  As a user
  I want to login to the website
  So that I can access my account
  
  Scenario: Successful login
    Given I am on the login page
    When I enter valid username and password
    Then I should be redirected to the home page
    
// Step definition
using TechTalk.SpecFlow;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

[Binding]
public class LoginSteps
{
    private IWebDriver driver;

    [Given(@"I am on the login page")]
    public void GivenIAmOnTheLoginPage()
    {
        driver = new ChromeDriver();
        driver.Navigate().GoToUrl("https://www.example.com/login");
    }

    [When(@"I enter valid username and password")]
    public void WhenIEnterValidUsernameAndPassword()
    {
        // code to enter username and password
    }

    [Then(@"I should be redirected to the home page")]
    public void ThenIShouldBeRedirectedToTheHomePage()
    {
        // code to verify redirection
        driver.Quit();
    }

    [BeforeTestRun]
    public static void BeforeTestRun()
    {
        var configuration = new SpecFlow.Configuration.SpecFlowConfiguration();
        configuration.Plugins.Add(new SpecFlow.Cucumber.Reports.CucumberReportPlugin(
            new SpecFlow.Cucumber.Reports.Configuration
            {
                OutputFolder = "cucumber-reports"
            }));
    }
}

Sunday, January 29, 2023

Excel data in parallel

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestClass {
  
  @DataProvider(name = "excelData", parallel = true)
  public Object[][] dataFromExcel() {
    // Code to read data from Excel
    // and return a 2D array
  }
  
  @Test(dataProvider = "excelData")
  public void testWithExcelData(String data1, String data2, ...) {
    // Selenium test code that uses the data from the data provider
  }
}

Gmail with nunit

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Threading;

[TestFixture]
[Parallelizable(ParallelScope.Fixtures)]
public class GmailAutomation
{
    private IWebDriver driver;

    [SetUp]
    public void SetUp()
    {
        driver = new ChromeDriver();
    }

    [Test]
    public void TestGmailLogin()
    {
        driver.Navigate().GoToUrl("https://gmail.com");
        driver.FindElement(By.Id("identifierId")).SendKeys("username");
        driver.FindElement(By.Id("identifierNext")).Click();
        Thread.Sleep(1000);
        driver.FindElement(By.Name("password")).SendKeys("password");
        driver.FindElement(By.Id("passwordNext")).Click();
        Thread.Sleep(5000);
        Assert.AreEqual("Inbox", driver.FindElement(By.XPath("//a[@title='Inbox']")).Text);
    }

    [TearDown]
    public void TearDown()
    {
        driver.Quit();
    }
}

Excel read and write in Python

import openpyxl
from selenium import webdriver

def test_excel_data_read_write():
    driver = webdriver.Chrome()
    file_path = r"C:\example.xlsx"
    workbook = openpyxl.load_workbook(file_path)
    sheet = workbook.get_sheet_by_name("Sheet1")

    # Read data from Excel
    for row in sheet.iter_rows():
        print(row[0].value, row[1].value)

    # Write data to Excel
    sheet.append(["Data1", "Data2"])
    workbook.save(file_path)

    driver.quit()

if __name__ == '__main__':
    test_excel_data_read_write()

Excel read and write in selenium using c#

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using System.IO;
using System.Data.OleDb;

namespace SeleniumTestProject
{
    [TestClass]
    public class ExcelDataReadWrite
    {
        private IWebDriver driver;

        [TestMethod]
        public void TestExcelDataReadWrite()
        {
            driver = new ChromeDriver();
            string filePath = @"C:\example.xlsx";
            string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", filePath);

            // Read data from Excel
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);
                using (OleDbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(reader[0].ToString() + " " + reader[1].ToString());
                    }
                }
            }

            // Write data to Excel
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                using (OleDbCommand command = new OleDbCommand())
                {
                    command.Connection = connection;
                    command.CommandText = "INSERT INTO [Sheet1$] (Column1, Column2) VALUES ('Data1', 'Data2')";
                    command.ExecuteNonQuery();
                }
            }

            driver.Quit();
        }
    }
}

Excel read in selenium using java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelHandler {

    public void readDataFromExcel(String filePath, String sheetName) {
        try {
            FileInputStream file = new FileInputStream(new File(filePath));
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheet(sheetName);
            Iterator<Row> rowIterator =

 sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        default :
                    }
                }
                System.out.println("");
            }
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void writeDataToExcel(String filePath, String sheetName, String[] dataToWrite) {
        try {
            FileInputStream file = new FileInputStream(new File(filePath));
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheet(sheetName);
            int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
            XSSFRow row = sheet.createRow(++rowCount);
            int columnCount = 0;
            for (String cellValue : dataToWrite) {
                XSSFCell cell = row.createCell(columnCount++);
                cell.setCellValue(cellValue);
            }
            file.close();
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


subprocess in python code for opening ms SQL ui

import subprocess

def open_msn_sql_ui():
    subprocess.run(["ssms.exe"])

if __name__ == '__main__':
    open_msn_sql_ui()

Gmail with unittest

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_gmail_login_and_count_inbox():
    # Initialize the webdriver
    driver = webdriver.Firefox()
    driver.get("https://gmail.com")
    
    # Enter the username and password
    username = driver.find_element(By.ID, "identifierId")
    username.send_keys("your_email@gmail.com")
    next_button = driver.find_element(By.ID, "identifierNext")
    next_button.click()
    password = driver.find_element(By.NAME, "password")
    password.send_keys("your_password")
    next_button = driver.find_element(By.ID, "passwordNext")
    next_button.click()
    
    # Wait for the page to load and count the number of emails in the inbox
    driver.implicitly_wait(10)
    inbox_count = len(driver.find_elements(By.XPATH, "//table[@role='grid']/tbody/tr"))
    print(f"Number of emails in the inbox: {inbox_count}")
    
    # Close the webdriver
    driver.quit()

Gmail with pytest

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_gmail_login_and_count_inbox():
    # Initialize the webdriver
    driver = webdriver.Firefox()
    driver.get("https://gmail.com")
    
    # Enter the username and password
    username = driver.find_element(By.ID, "identifierId")
    username.send_keys("your_email@gmail.com")
    next_button = driver.find_element(By.ID, "identifierNext")
    next_button.click()
    password = driver.find_element(By.NAME, "password")
    password.send_keys("your_password")
    next_button = driver.find_element(By.ID, "passwordNext")
    next_button.click()
    
    # Wait for the page to load and count the number of emails in the inbox
    driver.implicitly_wait(10)
    inbox_count = len(driver.find_elements(By.XPATH, "//table[@role='grid']/tbody/tr"))
    print(f"Number of emails in the inbox: {inbox_count}")
    
    # Close the webdriver
    driver.quit()

Friday, January 27, 2023

t+2 days in Java

import java.time.LocalDate;
import java.time.DayOfWeek;

public class DateFetcher {

    public static void main(String[] args) {

        LocalDate currentDate = LocalDate.now();

        LocalDate tPlusTwoDate = currentDate;
        int counter = 0;

        while (counter < 2) {
            tPlusTwoDate = tPlusTwoDate.plusDays(1);
            if (tPlusTwoDate.getDayOfWeek() != DayOfWeek.SATURDAY && tPlusTwoDate.getDayOfWeek() != DayOfWeek.SUNDAY) {
                counter++;
            }
        }

        System.out.println("T+2 date (excluding weekends): " + tPlusTwoDate);
    }
}

t+2 days in c#

using System;

class Program
{
    static void Main(string[] args)
    {
        DateTime currentDate = DateTime.Now;
        DateTime tPlus2Date = currentDate.AddDays(2);

        // Check if the date is a weekend day
        while (tPlus2Date.DayOfWeek == DayOfWeek.Saturday || tPlus2Date.DayOfWeek == DayOfWeek.Sunday)
        {
            // If it is a weekend day, add another day
            tPlus2Date = tPlus2Date.AddDays(1);
        }

        Console.WriteLine("T+2 date without weekend: " + tPlus2Date.ToString("dd-MM-yyyy"));
    }
}



using System;

class DateFetcher
{
    static void Main(string[] args)
    {
        DateTime currentDate = DateTime.Now;

        DateTime tPlusTwoDate = currentDate;
        int counter = 0;

        while (counter < 2)
        {
            tPlusTwoDate = tPlusTwoDate.AddDays(1);
            if (tPlusTwoDate.DayOfWeek != DayOfWeek.Saturday && tPlusTwoDate.DayOfWeek != DayOfWeek.Sunday)
            {
                counter++;
            }
        }

        Console.WriteLine("T+2 date (excluding weekends): " + tPlusTwoDate.ToString("MMM dd yyyy"));
    }
}

Thursday, January 26, 2023

Gmail automation using Cypress

describe('Gmail Automation', () => {
  beforeEach(() => {
    // Visit the Gmail login page
    cy.visit('https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin')
  })

  it('should be able to login and send an email', () => {
    // Enter email address and click next
    cy.get('#identifierId').type('your_email@gmail.com')
    cy.get('.VfPpkd-RLmnJb').click()

    // Enter password and click next
    cy.get('input[name="password"]').type('your_password')
    cy.get('.VfPpkd-RLmnJb').click()

    // Wait for the page to load
    cy.wait(3000)

    // Click compose button
    cy.get('.T-I.J-J5-Ji.T-I-KE.L3').click()

    // Wait for the compose window to load
    cy.wait(3000)

    // Fill in recipient, subject and body
    cy.get('.wO.nr.l1 textarea[name="to"]').type('recipient@email.com')
    cy.get('.aoT').type('Test email')
    cy.get('.Am.Al.editable.LW-avf').type('This is a test email sent using Cypress automation.')

    // Click send button
    cy.get('.T-I.J-J5-Ji.aoO.T-I-atl.L3').click()

    // Wait for the email to be sent
    cy.wait(3000)

    // Assert that the email was sent successfully
    cy.get('.Kj-JD-K7-K0').contains('Your message has been sent.')
  })
})

Friday, January 20, 2023

allure reports

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.qameta.allure.Allure;
import io.qameta.allure.Step;
import io.qameta.allure.model.Status;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class SeleniumAllureTest {
    WebDriver driver;

    @BeforeClass
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        driver = new ChromeDriver();
    }

    @Test
    public void testGoogleSearch() {
        // Allure report at the class level
        Allure.createTest("Search Google for Allure")
                .description("This test searches for the Allure framework on Google")
                .startStep("Open Google home page")
                .addAttachment("Google home page", "image/png", driver.getScreenshotAs(OutputType.BYTES))
                .step("Search for Allure")
                .step("Validate search results")
                .status(Status.PASSED)
                .startStep("Open Google home page")
                .addAttachment("Google home page", "image/png", driver.getScreenshotAs(OutputType.BYTES))
                .step("Search for Allure")
                .step("Validate search results")
                .status(Status.PASSED);

        driver.get("https://www.google.com");

        // Allure report at the page level
        Allure.step("Open Google home page", () -> {
            Allure.addAttachment("Google home page", "image/png", driver.getScreenshotAs(OutputType.BYTES));
        });

        Allure.step("Search for Allure", () -> {
            // perform search
        });

        Allure.step("Validate search results", () -> {
            // validate search results
        });
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }
}

api automation

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;

public class RestAssuredAPITest {
    ExtentHtmlReporter htmlReporter;
    ExtentReports extent;
    ExtentTest test;
    RequestSpecification request;
    Response response;
    SoftAssert softAssert = new SoftAssert();

    @BeforeTest
    public void setUp() {
        // initialize the HtmlReporter
        htmlReporter = new ExtentHtmlReporter("extent.html");
        
        // initialize ExtentReports and attach the HtmlReporter
        extent = new ExtentReports();
        extent.attachReporter(htmlReporter);
    }

    @Test
    public void testAPI() {
        test = extent.createTest("Test API");
        request = RestAssured.given();
        response = request.get("https://jsonplaceholder.typicode.com/posts");
        int statusCode = response.getStatusCode();
        test.log(Status.INFO, "API responded with status code: " + statusCode);
        softAssert.assertEquals(statusCode, 200);
        String responseBody = response.getBody().asString();
        test.log(Status.INFO, "API response body: " + responseBody);
        softAssert.assertTrue(responseBody.contains("title"));
        softAssert.assertTrue(responseBody.contains("body"));
        softAssert.assertAll();
    }

    @AfterTest
    public void tearDown() {
        extent.flush();
    }
}

Thursday, January 19, 2023

db

import java.sql.*;

public class MySQLTest {
    public static void main(String[] args) {
        try {
            // Connect to the database
            Connection conn = DriverManager.getConnection("jdbc:mysql://hostname:port/database", "username", "password");

            // Create a statement
            Statement stmt = conn.createStatement();

            // Execute the command
            String sql = "SELECT * FROM table_name";
            ResultSet rs = stmt.executeQuery(sql);

            // Process the result set
            while (rs.next()) {
                // Retrieve data by column name
                int id = rs.getInt("id");
                String name = rs.getString("name");

                // Display values
                System.out.print("ID: " + id);
                System.out.println(", Name: " + name);
            }

            // Close the resources
            rs.close();
            stmt.close();
            conn.close();

        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



import java.sql.*;
import java.util.ArrayList;

public class MySQLCommandExecutor {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<String> columnValues = new ArrayList<String>();

    try {
        // Connect to the MySQL database
        conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname", "username", "password");

        // Create a statement
        stmt = conn.createStatement();

        // Execute the command and get the result set
        rs = stmt.executeQuery("SELECT column_name FROM table_name WHERE condition");

        // Iterate through the result set and add the column values to the list
        while (rs.next()) {
            columnValues.add(rs.getString("column_name"));
        }

        // Print the list of column values
        for (String value : columnValues) {
            System.out.println(value);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            // Close the result set, statement, and connection
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Wednesday, January 18, 2023

Read date as string and add to days to it

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateString = "2022-01-01";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(dateString, formatter);
        LocalDate tenDaysLater = date.plusDays(10);
        System.out.println(tenDaysLater);
    }
}

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse("2022-01-01");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, 10);
        System.out.println(sdf.format(cal.getTime()));
    }
}


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse("2022-01-01");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, 10);
        System.out.println(sdf.format(cal.getTime()));
    }
}


Adding 10 days to current date

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 10);
        System.out.println(cal.getTime());
    }
}

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate tenDaysLater = today.plusDays(10);
        System.out.println(tenDaysLater);
    }
}

Wednesday, January 11, 2023

Kill Chrome Browser & driver in local using batch file

Create Batch file with below code , it works in windows only  



@echo off

taskkill /F /IM chrome.exe

@echo off

taskkill /F /IM chromedriver.exe


Wednesday, January 4, 2023

Karate Sample code with accepting cookies button in shadow dom

 


Feature: Login Test
This is Login Test

Scenario: Login with valid login credential testing

Given driver 'https://gpconnect.qa.stonex.com/'
#Given driver 'https://fxonline-demo.stonex.com/'
# we can inspect the page and get the locators in different variations like xPath:
# (don't forget to re-arrange the locator's quotes: double outside, single inside)
* delay(9000)
And input("//input[@name='identifier']","muraligandham437@gmail.com")
* delay(9000)
When click("//input[@value='Next']")
* delay(9000)
And input("//input[@id='input53']","Welcometostonex2029!")
When click("//input[@value='Verify']")
* delay(9000)
* delay(9000)

And script("#cmpwrapper", "_.shadowRoot.querySelector('#cmpbntyestxt').click()")


* delay(9000)
* delay(9000)

# retrieve the ShadowRoot of an element
#* def shadowRoot = driver.executeScript("return arguments[0].host", '#cmpwrapper')

# retrieve an element inside the ShadowRoot
# * def shadowElement = driver.executeScript("return arguments[0].querySelector('#cmpwelcomebtnyes')", shadowRoot)

# interact with the element
# * driver.click(shadowElement)


And script("#cmpwrapper", "_.shadowRoot.querySelector('#cmpbntyestxt').click()

* driver.maximize()
And input("//input[@id='companyLogin']","SFG_BA")
And input("//input[@id='userName']","sfgapprover")
And input("//input[@id='password']","Ndsb$1234")
# action
When click("//span[normalize-space()='Login']")
# We need to verify: For example webpage we logged in:
Then match driver.title == "StoneX | FXOnline"
* delay(9000)
And match
driver.url == 'https://fxonline-demo.stonex.com/Dashboard'

Karate Sample code

 


Feature: Login Test
This is Login Test

Scenario: Login with valid login credential testing

Given driver 'https://'
# we can inspect the page and get the locators in different variations like xPath:
# (don't forget to re-arrange the locator's quotes: double outside, single inside)
* driver.maximize()
And input("//input[@id='companyLogin']","SFG_BA")
And input("//input[@id='userName']","sfgapprover")
And input("//input[@id='password']","Ndsb$1234")
# action
When click("//span[normalize-space()='Login']")
# We need to verify: For example webpage we logged in:
Then match driver.title == "StoneX | FXOnline"
* delay(9000)
And match driver.url == 'https://fxonline-demo.stonex.com/Dashboard'
* delay(9000)
And click('{}Initiate Transaction')
* delay(9000)
* delay(9000)
#And match driver.url=='https://fxonline-demo.stonex.com/NewTrade'
And input("//input[@name='amountOne']","777")
* delay(9000)
And leftOf('{}Importation of Goods').click()
And input("//*[@id='inputInternalRef']","sfgapprover")
And click("//a[@href='#']/div[1]")
* delay(9000)
And input("//input[@type='file']", 'C:\Users\murali.gandham\Desktop\Testdata.xlsx')
#* driver.inputFile(//input[@type='file'],'C:\Users\murali.gandham\Desktop\Testdata.xlsx')
And click('{}Continue')
* delay(9000)
And click("//button[@id='btnSave']")
* delay(9000)