Friday, May 19, 2023

FB in C#

 using NUnit.Framework;

using OpenQA.Selenium;

using OpenQA.Selenium.Chrome;

using OpenQA.Selenium.Support.UI;

using System;

using AventStack.ExtentReports;

using AventStack.ExtentReports.Reporter;

using AventStack.ExtentReports.MarkupUtils;


namespace FacebookAutomation

{

    [TestFixture]

    [Parallelizable(ParallelScope.Fixtures)]

    public class FacebookPostTest

    {

        private IWebDriver driver;

        private WebDriverWait wait;

        private ExtentTest test;

        private static ExtentReports extent;


        [OneTimeSetUp]

        public void BeforeClass()

        {

            // Create an instance of ExtentReports

            extent = new ExtentReports();


            // Create an HTML report and attach to ExtentReports

            var htmlReporter = new ExtentHtmlReporter("TestReport.html");

            extent.AttachReporter(htmlReporter);

        }


        [SetUp]

        public void Setup()

        {

            // Set up ChromeDriver and initialize driver and wait

            driver = new ChromeDriver();

            wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));


            // Maximize the browser window

            driver.Manage().Window.Maximize();


            // Create a new ExtentTest for the test case

            test = extent.CreateTest(TestContext.CurrentContext.Test.Name);


            // Navigate to Facebook login page

            driver.Navigate().GoToUrl("https://www.facebook.com/");

        }


        [Test]

        public void PostOnFacebook()

        {

            // Login to Facebook

            var loginPage = new FacebookLoginPage(driver, wait, test);

            loginPage.Login("your_username", "your_password");


            // Write a post on the timeline

            string postText = "Hello, this is a test post!";

            var homePage = new FacebookHomePage(driver, wait, test);

            homePage.WritePost(postText);


            // Assert that the post is successfully posted

            bool isPostDisplayed = homePage.IsPostDisplayed(postText);

            Assert.IsTrue(isPostDisplayed, "The post was not successfully posted.");

        }


        [TearDown]

        public void Teardown()

        {

            // Quit the browser

            driver.Quit();


            // Mark the test as pass or fail in the Extent report

            var status = TestContext.CurrentContext.Result.Outcome.Status;

            var stackTrace = TestContext.CurrentContext.Result.StackTrace;

            var errorMessage = TestContext.CurrentContext.Result.Message;


            Status logStatus;


            switch (status)

            {

                case NUnit.Framework.Interfaces.TestStatus.Failed:

                    logStatus = Status.Fail;

                    test.Fail(MarkupHelper.CreateLabel("Test Failed", ExtentColor.Red));

                    if (!string.IsNullOrEmpty(stackTrace))

                        test.Error(stackTrace + errorMessage);

                    break;

                case NUnit.Framework.Interfaces.TestStatus.Passed:

                    logStatus = Status.Pass;

                    test.Pass(MarkupHelper.CreateLabel("Test Passed", ExtentColor.Green));

                    break;

                default:

                    logStatus = Status.Warning;

                    test.Skip(MarkupHelper.CreateLabel("Test Skipped", ExtentColor.Orange));

                    break;

            }


            // Log the final status in the Extent report

            test.Log(logStatus, "Test ended with " + logStatus);

        }


        [OneTimeTearDown]

        public void AfterClass()

        {

            // Flush the Extent report to generate the report

            extent.Flush();

        }

    }


    public class SeleniumActions

    {

        protected readonly IWebDriver driver;

        protected readonly WebDriverWait wait;

        protected ExtentTest test;


        public SeleniumActions(IWebDriver driver, WebDriverWait wait, ExtentTest test)

        {

            this.driver = driver;

            this.wait = wait;

            this.test = test;

        }


        protected IWebElement FindElement(By locator)

        {

            try

            {

                return wait.Until(ExpectedConditions.ElementIsVisible(locator));

            }

            catch (Exception ex)

            {

                test.Fail(ex.Message);

                throw;

            }

        }


        protected void Click(By locator)

        {

            try

            {

                FindElement(locator).Click();

            }

            catch (Exception ex)

            {

                test.Fail(ex.Message);

                throw;

            }

        }


        protected void SendKeys(By locator, string text)

        {

            try

            {

                FindElement(locator).SendKeys(text);

            }

            catch (Exception ex)

            {

                test.Fail(ex.Message);

                throw;

            }

        }


        protected void Submit(By locator)

        {

            try

            {

                FindElement(locator).Submit();

            }

            catch (Exception ex)

            {

                test.Fail(ex.Message);

                throw;

            }

        }


        protected bool IsDisplayed(By locator)

        {

            try

            {

                return FindElement(locator).Displayed;

            }

            catch (NoSuchElementException)

            {

                return false;

            }

            catch (Exception ex)

            {

                test.Fail(ex.Message);

                throw;

            }

        }

    }


    public class FacebookLoginPage : SeleniumActions

    {

        private readonly By emailField = By.Id("email");

        private readonly By passwordField = By.Id("pass");

        private readonly By loginButton = By.Name("login");


        public FacebookLoginPage(IWebDriver driver, WebDriverWait wait, ExtentTest test) : base(driver, wait, test)

        {

        }


        public void Login(string username, string password)

        {

            // Enter username and password

            SendKeys(emailField, username);

            SendKeys(passwordField, password);


            // Click on the login button

            Click(loginButton);

        }

    }


    public class FacebookHomePage : SeleniumActions

    {

        private readonly By createPostField = By.XPath("//textarea[contains(@aria-label, 'Create a post')]");


        public FacebookHomePage(IWebDriver driver, WebDriverWait wait, ExtentTest test) : base(driver, wait, test)

        {

        }


        public void WritePost(string text)

        {

            // Click on the create post field

            Click(createPostField);


            // Write the post text

            SendKeys(createPostField, text);


            // Submit the post

            Submit(createPostField);

        }


        public bool IsPostDisplayed(string text)

        {

            // Wait for the post to appear on the timeline

            By postLocator = By.XPath($"//div[contains(text(), '{text}')]");


            // Check if the post is displayed

            return IsDisplayed(postLocator);

        }

    }

}


Thursday, May 18, 2023

API in C# 1

 using System;

using System.Data;

using System.IO;

using NUnit.Framework;

using RestSharp;

using Newtonsoft.Json;

using AventStack.ExtentReports;

using AventStack.ExtentReports.Reporter;

using ExcelDataReader;


namespace APITesting

{

    [TestFixture]

    [Parallelizable(ParallelScope.Fixtures)]

    public class APITest

    {

        private static ExtentReports extent;

        private ExtentTest test;

        private RestClient client;


        [OneTimeSetUp]

        public static void Setup()

        {

            // Initialize Extent Reports

            extent = new ExtentReports();

            var htmlReporter = new ExtentHtmlReporter("extent-report.html");

            extent.AttachReporter(htmlReporter);

        }


        [SetUp]

        public void BeforeTest()

        {

            // Create a new test in the Extent Report

            test = extent.CreateTest(TestContext.CurrentContext.Test.Name);


            // Set the base URL of the API

            string baseUrl = "https://api.example.com";


            // Create a RestSharp client

            client = new RestClient(baseUrl);

        }


        [Test]

        [TestCaseSource(nameof(UserData))]

        public void TestAPI(UserDataModel data)

        {

            // Create a RestSharp request

            RestRequest request = new RestRequest("/endpoint", Method.POST);

            

            // Set the request body using the data model

            string requestBody = JsonConvert.SerializeObject(data);

            request.AddParameter("application/json", requestBody, ParameterType.RequestBody);


            // Send the request and get the response

            IRestResponse response = client.Execute(request);


            // Extract the response details

            int statusCode = (int)response.StatusCode;

            string content = response.Content;


            // Deserialize the response content to a data model

            var responseModel = JsonConvert.DeserializeObject<ResponseModel>(content);


            // Log the response details in the extent report

            test.Log(Status.Info, $"API Response Code: {statusCode}");

            test.Log(Status.Info, $"API Response Content: {content}");


            // Perform assertions or further processing on the response

            Assert.AreEqual(200, statusCode, "Unexpected status code");


            // Add a pass status to the extent report

            test.Pass("API test passed");

        }


        [TearDown]

        public void AfterTest()

        {

            // End the test in the extent report

            extent.EndTest(test);

        }


        [OneTimeTearDown]

        public static void TearDown()

        {

            // Flush and close the extent report

            extent.Flush();

            extent.Close();

        }


        private static IEnumerable UserData()

        {

            // Path to the Excel file

            string excelFilePath = "data.xlsx";


            // Open the Excel file

            using (var stream = File.Open(excelFilePath, FileMode.Open, FileAccess.Read))

            {

                // Create the ExcelDataReader

                using (var reader = ExcelReaderFactory.CreateReader(stream))

                {

                    // Read the Excel data into a DataTable

                    var result = reader.AsDataSet(new ExcelDataSetConfiguration()

                    {

                        ConfigureDataTable = (_) => new ExcelDataTableConfiguration()

                        {

                            UseHeaderRow = true

                        }

                    });


                    // Get the first DataTable from the result

                    var dataTable = result.Tables[0];


                    // Iterate over each row in the DataTable

                    foreach (DataRow row in dataTable.Rows)

                    {

                        // Map the row data to the UserDataModel

                        var data = new UserDataModel()

                        {

                            Username = row["Username"].ToString(),

                            Password = row["Password"].ToString()

                        };


                        // Yield the data for each test case

                        yield return new TestCaseData(data);

                    }

                }

            }

        }

    }


    public class UserDataModel

    {

        public string Username { get; set; }

        public string Password { get; set; }

    }


    public class ResponseModel

    {

        // Define properties for the response data

        [JsonProperty("id")]

        public int Id { get; set; }


        [JsonProperty("name")]

        public string Name { get; set; }


        // Add other properties as needed

    }

}


api in c#

 using System;

using NUnit.Framework;

using RestSharp;

using Newtonsoft.Json;

using AventStack.ExtentReports;

using AventStack.ExtentReports.Reporter;


namespace APITesting

{

    [TestFixture]

    [Parallelizable(ParallelScope.Fixtures)]

    public class APITest

    {

        private static ExtentReports extent;

        private ExtentTest test;

        private RestClient client;


        [OneTimeSetUp]

        public static void Setup()

        {

            // Initialize Extent Reports

            extent = new ExtentReports();

            var htmlReporter = new ExtentHtmlReporter("extent-report.html");

            extent.AttachReporter(htmlReporter);

        }


        [SetUp]

        public void BeforeTest()

        {

            // Create a new test in the Extent Report

            test = extent.CreateTest(TestContext.CurrentContext.Test.Name);


            // Set the base URL of the API

            string baseUrl = "https://api.example.com";

            

            // Create a RestSharp client

            client = new RestClient(baseUrl);

        }


        [Test]

        [TestCaseSource(nameof(UserData))]

        public void TestAPI(string username, string password)

        {

            // Create a RestSharp request

            RestRequest request = new RestRequest("/endpoint", Method.GET);


            // Add any necessary headers, parameters, or body to the request

            // request.AddHeader("Authorization", "Bearer <token>");

            // request.AddParameter("paramName", "paramValue");


            // Send the request and get the response

            IRestResponse response = client.Execute(request);


            // Extract the response details

            int statusCode = (int)response.StatusCode;

            string content = response.Content;


            // Deserialize the response content to a data model

            var responseModel = JsonConvert.DeserializeObject<ResponseModel>(content);


            // Log the response details in the extent report

            test.Log(Status.Info, $"API Response Code: {statusCode}");

            test.Log(Status.Info, $"API Response Content: {content}");


            // Perform assertions or further processing on the response

            Assert.AreEqual(200, statusCode, "Unexpected status code");


            // Add a pass status to the extent report

            test.Pass("API test passed");

        }


        [TearDown]

        public void AfterTest()

        {

            // End the test in the extent report

            extent.EndTest(test);

        }


        [OneTimeTearDown]

        public static void TearDown()

        {

            // Flush and close the extent report

            extent.Flush();

            extent.Close();

        }


        private static object[] UserData()

        {

            return new object[]

            {

                new object[] { "user1", "password1" },

                new object[] { "user2", "password2" },

                new object[] { "user3", "password3" },

                new object[] { "user4", "password4" },

                new object[] { "user5", "password5" }

            };

        }

    }


    public class ResponseModel

    {

        // Define properties for the response data

        [JsonProperty("id")]

        public int Id { get; set; }


        [JsonProperty("name")]

        public string Name { get; set; }


        // Add other properties as needed

    }

}