Thursday, September 26, 2019

SpecFlow - Table

using TechTalk.SpecFlow.Assist
1. CreateInstance<T>
| LanguageName | LanguageLevel|

| Indian  | Basic            |

var lan = table.CreateInstance<Languages>();

2. CreateSet<T> - horizontal data

| LanguageName | LanguageLevel|
| Indian  | Basic            |
| French   | Conversational   |
| Spanish  | Fluent           |
| Mandarin | Native/Bilingual |

Create a class, table header must match with the members
public class Languages
{
 public string LanguageName{get;set;}
 public string LanguageLevel{get;set}
}

In Step Definition
var languages = table.CreateSet<Languages>();
foreach(var lan in languages)
{
lan.LanguageName
lan.LanguageLevel

}
3.Dynamic
using Specflow.Assist.Dynamic, Install nuget package first

dynamic credentials = table.CreateDynamicInstance();
IEnumerable <dynamic> credentials = table.CreateDynamicSet();

Wednesday, September 25, 2019

Selenium-screenshot,extent report



  • C#- TakeScreenShot
https://www.guru99.com/take-screenshot-selenium-webdriver.html

public void TakeScreenshot()
{
    try
    {         
        Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
        ss.SaveAsFile(@"D:\Screenshots\SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        throw;
    }
}


  • Extent Report 2.41
https://extentreports.com/docs/versions/2/net/

public class BasicReport
    {
        public ExtentReports extent;
        public ExtentTest test;

        [OneTimeSetUp]
        public void StartReport()
        {
            string projectPath=".......";
           string reportPath = @"E:Reports\MyOwnReport.html";

            extent = new ExtentReports(reportPath, true);
            extent
            .AddSystemInfo("Host Name", "Krishna")
            .AddSystemInfo("Environment", "QA")
            .AddSystemInfo("User Name", "Krishna Sakinala");
            extent.LoadConfig(projectPath + "extent-config.xml");
        }
       
        [Test]
        public void DemoReportPass()
        {
            test = extent.StartTest("DemoReportPass");
            Assert.IsTrue(true);
            test.Log(LogStatus.Pass, "Assert Pass as condition is True");
        }

        [Test]
        public void DemoReportFail()
        {
            test = extent.StartTest("DemoReportFail");
            Assert.IsTrue(false);
            test.Log(LogStatus.Pass, "Assert Fail as condition is False");
        }

        [TearDown]
        public void GetResult()
        {
            var status = TestContext.CurrentContext.Result.Outcome.Status;
            var stackTrace = "<pre>" + TestContext.CurrentContext.Result.StackTrace + "</pre>";
            var errorMessage = TestContext.CurrentContext.Result.Message;

            if (status == TestStatus.Failed)
            {
                test.Log(LogStatus.Fail, stackTrace + errorMessage);
            }
            extent.EndTest(test);
        }

        [OneTimeTearDown]
        public void EndReport()
        {
            extent.Flush();
            extent.Close();
        }

    }
ExtentReports extent = new ExtentReports(file-path, false);

// new instance
var extent = new ExtentReports(file-path);

// starting test
var test = extent.StartTest("Test Name", "Sample description");

// step log
test.Log(LogStatus.PASS, "Step details");

// ending test
extent.EndTest(test);

// writing everything to document

extent.Flush();


  1. ExtentReports will create the report file.
  2. ExtentTest will log the information in the report.
  3. StartTest() method of ExtentReports class is the starting point of the test and it will return the ExtentTest object.
  4. We need to capture that object into ExtentTest object.
  5. Used this reference to log the information into the report.
  6. ExtentReports object will be used to add the report information like Title, Header and Theme etc..
  7. And the above configuration need to passed from the external XML file using LoadConfig() method of ExtentReports class. It will take the XML file path as argument.
  8. EndTest() method of ExtentReports will stop capturing information about the test log.
  9. Flush() method of ExtentReports will push/write everything to the document.
  10. Close() method of ExtentReports will clear/close all resource of the ExtentReports object


  • Extent Report 4

public class Main {
    public static void main(String[] args) {
        // start reporters
        var reporter = new ExtentHtmlReporter("path/to/directory/");

        // create ExtentReports and attach reporter(s)
        var extent = new ExtentReports();
        extent.AttachReporter(htmlReporter);

        // creates a test
        var test = extent.CreateTest("MyFirstTest", "Sample description");

        // log(Status, details)
        test.Log(Status.Info, "This step shows usage of log(status, details)");

        // info(details)
        test.Info("This step shows usage of info(details)");

        // log with snapshot
        test.Fail("details",
MediaEntityBuilder.CreateScreenCaptureFromPath("screenshot.png").Build());

        // test with snapshot
        test.AddScreenCaptureFromPath("screenshot.png");

        // calling flush writes everything to the log file
        extent.Flush();
    }
}




Tuesday, September 24, 2019

Selenium - Configuration


  • Read Configuration using ConnectionStrings from App.Config
  • Read Configuration using AppSettings from App.Config
  • Read Configuration from External Config file

using System.Configuration;
ConfigurationManager provides two properties:
AppSettings: Gets the AppSettingsSection data for the current application’s default configuration. 
ConnectionStrings: Gets the ConnectionStringsSection data for the current application’s default configuration. ConnectionString is basically meant to store DataBase connection strings.
App.config File
How to Read Connection String in C# using ConfigurationManager

<configuration>
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False"/>
</connectionStrings>
</configuration>

var dbString = ConfigurationManager.ConnectionStrings[“DBConnection”].ConnectionString;

How to Read AppSettings in C# using ConfigurationManager

<configuration>
    <appSettings>
          <add key="URL" value="http://www.store.demoqa.com"/>
  <add key="FolderPath"="C:\Users\lakshay.sharma\Downloads\"/>
    </appSettings>
</configuration>

To read the Url from the above config file, use the below code:

var url = ConfigurationManager.AppSettings[“URL”];

var folderPath = ConfigurationManager.AppSettings[“FolderPath”];

NOte: Folderpath could be any path which is needed in the framework, for example path to save the reports or the screenshot.  

Steps to read ConnectionString from External Config File using ConfigurationManager

App.config File

  <configuration>
<connectionStrings configSource="DBConnectionStrings.config" />
  </configuration>

Create another config file and name it DBConnectionString.config under the same project.

DBConnectionString.config File

<connectionStrings>
<add name="DataBaseName" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False/>
</connectionStrings>

var connString= ConfigurationManager.ConnectionStrings[“DataBaseName”].ConnectionString;


  • Steps to read AppSettings from External Config File using ConfigurationManager


App.config File

<configuration>
<appSettings configSource="Configurations\Environment.config" />
</configuration>

Create another config file and name it Environment.config under the same project.

Environment.config File

<appSettings>
<add key="URL" value="http://www.store.demoqa.com"/>
</appSettings>

To read the app setting from the above config file, use the below code:

var url = ConfigurationManager.AppSettings[“URL”];


Create Configuration Folder
Right click on the project and create one new folder. Name it as Configurations.

Create Environment Config file
In the configurations folder, create one config file and name it as Environment.config. Paste the below code in the Environment file.

<appSettings>
<add key="URL" value="http://www.store.demoqa.com"/>
</appSettings>

Modify App.config File
<configuration>
               <appSettings configSource="Configurations\Environment.config" />
</configuration>

Add Reference to ConfigurationManager
Right Click on the References and select Add Reference... Now search for System.ConfigurationManager. Select it and this will add to your Project References

Environment file in Visual Studio there is a property called Copy to Output Directory that can be used to copy the configuration file automatically: Change it to Copy Always.

Thursday, September 19, 2019

Specflow - specflow outline, excel data,file genrator


  • Specflow single file generator
using the MSBuild integration to generate your code behind file
To use the MSBuild integration, you need to disable this legacy support in the options in Visual Studio. To do so:

Select Tools | Options from the menu in Visual Studio.
Browse to SpecFlow | General in the list on the left (you can use the search field to restrict the options).
Set Enable SpecFlowSingleFileGenerator CustomTool to false under Legacy.
Click OK.
You also need to ensure that SpecFlowSingleFileGenerator is not entered in the Custom Tool field of your feature files.
  • Scenario Outine, the same test with different data


Scenario Outline: Register with valid details
    Given I am on the registration page
        And I have completed the form with <email> <organisation> <password> and <passwordConfirmation>
    When I have clicked on the register button
    Then I will be logged in as <username>
        And my account will be assigned the role of <role>

        Examples: 
        | email     | organisation | password  | passwordConfirmation | username  | role  |
        | usernamea | Bytes        | password1 | password1            | usernamea | Admin |
        | usernameb | Bytes        | password2 | password2            | usernameb | Admin |
        | usernamec | Bytes        | password3 | password3            | usernamec | Admin |
        | usernamed | Bytes        | password4 | password4            | usernamed | Admin |
        | usernamee | Bytes        | password5 | password5            | usernamee | Admin |

Scenario outlines can be used to define data-driven acceptance tests.

  • Excel data
@source:xxx.xlsx:sheet1
 Examples:
        | email     | organisation | password  | passwordConfirmation | username  | role  |
        | usernamea | Bytes        | password1 | password1            | usernamea | Admin |
        | usernameb | Bytes        | password2 | password2            | usernameb | Admin |
        | usernamec | Bytes        | password3 | password3            | usernamec | Admin |
        | usernamed | Bytes        | password4 | password4            | usernamed | Admin |
        | usernamee | Bytes        | password5 | password5            | usernamee | Admin |


Saturday, September 14, 2019

api testing - postman

https://blog.getpostman.com/2017/07/28/api-testing-tips-from-a-postman-professional/
  • Rembember to Save before exit
  • Variable
1. Collection level, C level: pm.collectionVariables.get("variable_key");pm.collectionVariables.set("variable_key","value");
2. Environment Level: pm.environment.get("variable_key");pm.environment.set("variable_key","value");
3. Global Level: pm.globals.get("variable_key","value");pm.globals.set("variable_key","value");

pm.variables.get(); to get the variable value
  • match with soap UI level
Project->Collection
Test Suite-> Folder Resources, etc
Test Case-> Folder Endpoint
Test Steps->Request
  • Organize tests into folders
As your API grows in complexity, it will become important to organize your tests so they make sense and can be found easily. I suggest that you use folders to group requests by 
Collection
resource
test suite
workflows.
  •  maintain separate collections for testing and documentation
  • Data driven csv file,json file
Collection run, load data
  • Script: Javascript. On each level
Prerequest script: Run before request. Dynamically set or change variables.
Test: Run after getting response. To Validate the result.

  • How to chain API requests
Get data from one API and refer in another API

Environment Variable
pm.environment.set("key",value)

var jsonData = JSON.parse(responseBody);
pm.environment.set("key", jsonData.key);

output variable on Console
console.log(pm.environment.get("xxx"))

  • Run post from command line

1. Check if node.js and npm is already installed"node -v" "npm -v")
2. Install node.js and npm
3. Install NewMan ("npm intall -g newman")
4. Export collection as Json file
5. newman run colllection.json

Go to collection folder
npm run collection.json -e environment.json -r xxx.html
  • Run Postman in Jenkins
1.Setup a new job item "Postmanrun" in Jenkin
2.Build -> running bat, or shell script (adding command for running newman)
3.Apply, Save
4.Run the Job
  • JSON Schema validation


  • reuse code



  • Issues:

When I parse this little piece of JSON

{ "value" : 9223372036854775807 }
that's what I get

{ hello: 9223372036854776000 }
Is there any way to parse it properly?



In JavaScript, one has at most 53 bits for integers. This blog post explains how to work with large integers, by encoding them in strings.

1) Use a parsing library that supports bignumbers
2) Treat numbers as strings





Friday, September 13, 2019

API Testing - how to test

How to do API testing design

Testers are in charge of testing both individual functionality and a series/chain of functionality
1. Isolation of each request
test the positive and negative
##boundary value analysis
### ching for every kind of wrong input the user can possibly supplyeck
###create test cases for all possible input combinations of the API.

2. End to End test
mock the real use work flow


Remember
1. make sure it does what it's supposed to do
2. make sure it can handle the load
3. find all the way users can mess things up, negative testing
4. make sure your apis work across devices,browsers and operating system



manual test for exploratory testing, usability testing, ad-hoc testing


Best 10 practice for api testing

  1.  Test for the typical and expected result first (positive)
  2.  On top of each test, include the declarations of the APIs being called.
  3. Parameters selection should be explicitly mentioned in the test case itself
  4. Each test case should be as self-contained and independent from dependencies as possible.Avoid "test chaining" in your development.Limit the tests from as many variables as possible by keeping it as isolated as possible
  5. Group test cases by category
  6. Prioritize API function calls
  7. For complete test coverage, create test cases for all possible API input combination
  8. Call sequencing should be performed and well planned
  9. Add stress to the system through a series of API load testing.
  10.  Test for failure. Make sure you understand how the api will fail.See how it handles unforseen problems and loads by throwing as much as you can at it.

Thursday, September 12, 2019

api testing - http status

Get to know the http status code
1. 405
https://docs.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

Method Not Allowed"the method specified in the Request-Line is not allowed for the resource identified by the Request-URI."

2. 400
400 (Bad Request)
400 is the generic client-side error status, used when no other 4xx error code is appropriate. Errors can be like malformed request syntax, invalid request message parameters, or deceptive request routing etc.


The client SHOULD NOT repeat the request without modifications.

3. 404

404 (Not Found)

The 404 error status code indicates that the REST API can’t map the client’s URI to a resource but may be available in the future.


Testing REST API Manually




Wednesday, September 11, 2019

API


  • API
Application Program Interface
API is an messenger

take the request, what you want to do
take the response back to you

e.g.  end user<->search airflghts from travel agent< - > air line company


  • API types

API : methods (parameters)
between software, operation system and harware
API (local)
Web API, web services(Web)


  • Web API / Web Serivices 
Services on Web for apps  (no UI)
myapp
---> Google service, Facebook services, Twitter services  (api)
many apis are available to use


  • API protocol -- extrange data between applications
Formatted structure of request and response, HTTP

Soap is a protocol, simple object access protocol.
Two major fuctions GET and POST
invoke calling by RPC method
XML used as data format on the request and the response side. The amount of data transferred within the SOAP structure was enormous, thus requiring more resources and slowing down the communication.
difficult to call from javascript
Strong data typing
Safe

REST is an architectural style, Representational State Transfer
over HTTP only
call services via make request to URL
GET, POST, PUT,DELETE
request simple. return all properties, server defines which data is to be returned,
use XML or JSON to send or receive data
Easy to call from javascript
Weak data typing
REST + JSON



URL Uniform Resource Locator 

  • WEB API life cycle:

design and mock -> debug -> Automation Testing ->document->monitor->publish


  • API testing




No GUI, test business logic
Test Tool to drive test
Write test scripts
  • Types of Bugs that API testing detects
Fails to handle error conditions gracefully
    Unused flags
      Missing or duplicate functionality
        Reliability Issues. Difficulty in connecting and getting a response from API.
          Security Issues
            Multi-threading issues
              Performance Issues. API response time is very high.
                Improper errors/warning to a caller
                  Incorrect handling of valid argument values
                    Response Data is not structured correctly (JSON or XML)


                    Tuesday, September 10, 2019

                    Git - workflow


                    Centralized
                    • Someone created central repo
                    • Devs Clone central repo to local machines
                    • Make commits locally
                    • Push to central repo "git push origin master"
                    • Manage "diverge" or "merge conflict "if someone else push before you
                    • Rebase first "git pull --rebase origin master" conflict will show
                    • Make some edits, then "git add <some-file>"
                    • git rebase --continue
                    • Then push
                    Feature Branch Workflow
                    • Central - Official code
                    • Start from master branch 
                    git checkout master
                      git fetch origin
                        git reset --hard origin/master
                        • Create a new branch locally

                        git checkout -b new-feature, -b create a new branch

                        • Make changes on the new branch locally
                        git add
                        git commit -m

                        • Push to github
                        git push -u origin new-feature, -u add it as remote tracking branch, next time just do" git push "

                        • After push, create "pull request", open for review
                        • After pull request is approved and conflict free, do "Merge" from pull request
                        • Like Centralized workflow
                        • Synchronize the local master first, Merge your local feature branch to master, Then push



                        Monday, September 9, 2019

                        C#- string,enum

                        String To Enum Conversion [C#]

                        This example shows how to convert enum values to string and reversely.

                        Enum to string

                        To convert enum to string use simply Enum.ToString method.
                        [C#]
                        Animal animal = Animal.Cat;
                        string str = animal.ToString();  // "Cat"
                        
                        

                        String to enum

                        To convert string to enum use static method Enum.Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.
                        [C#]
                        string str = "Dog";
                        Animal animal = (Animal)Enum.Parse(typeof(Animal), str);  // Animal.Dog
                        Animal animal = (Animal)Enum.Parse(typeof(Animal), str, true); // case insensitive

                        Nunit - setup,teardown

                        For NUnit 3.0 we standardized the use of attributes for setup and teardown and renamed some of them to make their function clearer.

                        Attribute Usage

                        C#-Isnullorempty

                        IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.Empty (A constant for empty strings)

                        Syntax:
                        public static bool IsNullOrEmpty(String str)  
                        
                        Explanation: This method will take a parameter which is of type System.String and this method will returns a boolean value. If the str parameter is null or an empty string (“”) then return True otherwise return False.
                        Example:
                        Input : str  = null         // initialize by null value
                                String.IsNullOrEmpty(str)
                        Output: True
                        
                        Input : str  = String.Empty  // initialize by empty value
                                String.IsNullOrEmpty(str)
                        Output: True

                        Tuesday, September 3, 2019

                        selenium - excel data reader

                        Steps to implementa excel data reader

                        1 Install Excel Data Reader Nuget package
                        2 Create a class in your Utilities/Helpers directories
                        3 Define the class
                        4 create a excel sheet with test data
                        5 use the method PopulateInCollection to populate collections
                        6 use the method ReadData to read data from excel sheet


                        Monday, September 2, 2019

                        C# access modifier

                        6. Access modifier in C#
                        A way to control access to a class and or its members

                        public
                        The type or member can be accessed by any other code in the same assembly or another assembly that references it.

                        private
                        The type or member can be accessed only by code in the same class or struct.

                        protected
                        The type or member can be accessed only by code in the same class, or in a class that is derived from that class.

                        internal
                        The type or member can be accessed by any code in the same assembly, but not from another assembly.

                        protected internal
                        The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly.

                        Type Access Modifier
                                             | Default   | Permitted declared accessibilities
                        ------------------------------------------------------------------
                        namespace            | public    | none (always implicitly public)
                        
                        enum                 | public    | none (always implicitly public)
                        
                        interface            | internal  | public, internal
                        
                        class                | internal  | public, internal
                        
                        struct               | internal  | public, internal
                        
                        delegate             | internal  | public, internal

                        Member accesss modifier
                                            | Default   | Permitted declared accessibilities
                        ------------------------------------------------------------------
                        namespace            | public    | none (always implicitly public)
                        
                        enum                 | public    | none (always implicitly public)
                        
                        interface            | public    | none
                        
                        class                | private   | All¹
                        
                        struct               | private   | public, internal, private²
                        
                        delegate             | private   | All¹
                        
                        constructor          | private   | All¹
                        
                        interface member     | public    | none (always implicitly public)
                        
                        method               | private   | All¹
                        
                        field                | private   | All¹
                        
                        user-defined operator| none      | public (must be declared public)

                        API interview questions

                          https://www.katalon.com/resources-center/blog/web-api-testing-interview-questions/ Top 50+ Web API Testing Interview Questions [Ultimate l...