• Background Image

    News & Updates

    admin

July 23, 2018

Sample java program for PhantomJS

PhantomJs Driver Executable

Download PhantomJs driver here

Sample Java Program:

  • 
    package com.test.phantomjs;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.phantomjs.PhantomJSDriver;
    import org.openqa.selenium.phantomjs.PhantomJSDriverService;
    import org.openqa.selenium.remote.DesiredCapabilities;
    
    public class Test {
    
    public static void main(String[] args) throws InterruptedException {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setJavascriptEnabled(true);
    caps.setCapability("takesScreenshot", true);
    caps.setCapability(
    PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
    "/Users/yosuvaarulanthu/Downloads/phantomjs-2.1.1-macosx/bin/phantomjs"
    );
    WebDriver driver = new PhantomJSDriver(caps);
    
    String baseUrl = "http://demo.guru99.com/test/upload/";
    
    driver.get(baseUrl);
    WebElement uploadElement = driver.findElement(By.id("uploadfile_0"));
    
    // enter the file path onto the file-selection input field
    uploadElement.sendKeys("/Users/yosuvaarulanthu/Downloads/sample.txt");
    
    // check the "I accept the terms of service" check box
    driver.findElement(By.id("terms")).click();
    
    // click the "UploadFile" button
    driver.findElement(By.name("send")).click();
    System.out.println("done"+driver.getTitle());
    Thread.sleep(3000);
    System.out.println("Succes Msg:"+driver.findElement(By.xpath("//h3/center")).getText());
    driver.quit();
    }
    
    }
    
    

POM.xml
  • <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>PhantomJS</groupId>
      <artifactId>PhantomJS</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <dependencies>
      	<dependency>
        <groupId>com.github.detro.ghostdriver</groupId>
        <artifactId>phantomjsdriver</artifactId>
        <version>1.1.0</version>
    	</dependency>
      </dependencies>
      <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
              <release>10</release>
            </configuration>
          </plugin>
        </plugins>
      </build>
      
    </project>
    

January 19, 2018

Writing Your First Selenium Test Script

Fundamentally, Selenium works with two pieces of information — the element on a page you want to interact with and what you want to do with it. This one-two punch will be repeated over and over until you achieve the outcome you want in your application, at which point you will perform an assertion to confirm that the result is what you intended.

Let’s take logging into a website as an example. With Selenium you would:

  1. Visit the login page of a site
  2. Find the login form’s username field and input the username
  3. Find the login form’s password field and input the password
  4. Find the submit button and click it

Selenium is able to find and interact with elements on a page by way of various “locator strategies”. The list includes (sorted alphabetically):

  • Class
  • CSS Selector
  • ID
  • Link Text
  • Name
  • Partial Link Text
  • Tag Name
  • XPath

While each serves a purpose, you only need to know a few to start writing effective tests.

How To Find Locators

The simplest way to find locators is to inspect the elements on a page. The best way to do this is from within your web browser. Fortunately, popular browsers come pre-loaded with development tools that make this easy to accomplish.

When viewing the page, right-click on the element you want to interact with and click Inspect Element. This will bring up a small window with all of the markups for the page but zoomed into your highlighted selection. From here you can see if there are unique or descriptive attributes you can work with to write a locator.

How To Find Quality Elements

You want to find an element that is uniquedescriptive, and unlikely to change.

Ripe candidates for this are id and class attributes. Whereas copy (e.g., text, or the text of a link) is less ideal since it is more apt to change. This may not hold true for when you make assertions, but it’s a good goal to strive for.

If the elements you are attempting to work with don’t have unique id or class attributes directly on them, look at the element that houses them (a.k.a. the parent element). Often-times the parent element has a unique element that you can use to start with and drill down to the child or descendent element you want to use.

When you can’t find any unique elements, have a conversation with your development team letting them know what you are trying to accomplish. It’s generally a trivial thing for them to add helpful, semantic markup to make the application more testable. This is especially true when they know the use case you’re trying to automate. The alternative is for you to muddle through it in a lengthy, painful process which will probably yield working test code (but it will be brittle and hard to maintain test code).

Once you’ve identified the target elements for your test, you need to craft a locator using one of Selenium‘s strategies. Let’s step through an example of this as we write our first test.

An Example

Part 1: Find The Elements And Write The Test

Here’s the markup for a standard login form (pulled from the login example on the-internet).


<form name="login" id="login" action="/authenticate" method="post">
   
<div class="row">
    
<div class="large-6 small-12 columns">
      <label for="username">Username</label>
      <input type="text" name="username" id="username">
    </div>

  </div>

  
<div class="row">
    
<div class="large-6 small-12 columns">
      <label for="password">Password</label>
      <input type="password" name="password" id="password">
    </div>

  </div>

    <button class="radius" type="submit"><i class="icon-2x icon-signin"> Login</i></button>
</form>

Note the unique elements on the form. The username input field has a unique id, as does the password input field. The submit button doesn’t, but it’s the only button on the page, so we can easily find it and click it.

  • Coming Soon…
  • Let’s put these elements to use in our first testFirst, we’ll need to create a folder called Tests in our project. Then let’s add a test file to the package called LoginTest.cs. When we’re done our directory structure should look like this.

     

    ├── Tests
    │   └── LoginTest.cs
    └── packages.config
    

    NOTE: Other items in the directory have been omitted for brevity (and will continue to be omitted for the remainder of the course). Things like the Properties directory (and its AssemblyInfo.cs file) as well as the project and solutions files (e.g., SeleniumGuidebookExamples.csprojand SeleniumGuidebookExamples.sln. The name for your project may be different depending on what you named it.

    And here is the code we will add to the test file for our Selenium commands, locators, etc.

    //filename: Tests/LoginTest.cs
    using NUnit.Framework;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Firefox;
    
    namespace Tests
    {
        [TestFixture]
        class LoginTest
        {
            IWebDriver Driver;
    
            [SetUp]
            public void SetUp()
            {
                Driver = new FirefoxDriver();
            }
    
            [TearDown]
            public void TearDown()
            {
                Driver.Quit();
            }
    
            [Test]
            public void ValidAccount()
            {
                Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/login");
                Driver.FindElement(By.Id("username")).SendKeys("tomsmith");
                Driver.FindElement(By.Id("password")).SendKeys("SuperSecretPassword!");
                Driver.FindElement(By.CssSelector("button")).Click();
            }
        }
    }
    

    After including the requisite classes for NUnit and Selenium we declare a class (e.g., public class LoginTest and add an attribute to it that denotes that this is a test class (e.g., [TestFixtures]). We then declare a field variable to store and reference an instance of Selenium WebDriver (e.g., IWebDriver Driver;).

    Next we add setup and teardown methods with the attributes [SetUp] and [TearDown]. In them we’re creating an instance of Selenium (storing it in Driver) and closing it (e.g., Driver.Quit();). Because of the [SetUp] attribute, the public void SetUp() method will load before our test and the [TearDown] attribute will make the public void TearDown() method load after the test. This abstraction enables us to write our test with a focus on the behavior we want to exercise in the browser, rather than clutter it up with setup and teardown details.

    Our test is a method as well (public void ValidAccount()). NUnit knows this is a test because of the [Test] attribute. In this test we’re visiting the login page by its URL (with Driver.Navigate().GoToUrl()), finding the input fields by their ID (with Driver.FindElement(By.Id())), inputting text into them (with .SendKeys();), and submitting the form by clicking the submit button (e.g., By.CssSelector("button")).Click();).

    If we save this and run it (by clicking TestRunAll Tests or CTRLRA), it will run and pass. But there’s one thing missing — an assertion. In order to find an element to write an assertion against we need to see what the markup of the page is after submitting the login form.

  • Coming Soon…
  • Coming Soon…

Part 2: Figure Out What To Assert

Here is the markup that renders on the page after logging in.

<div class="row">
  
<div id="flash-messages" class="large-12 columns">
    
<div data-alert="" id="flash" class="flash success">
      You logged into a secure area!
      <a href="#" class="close">x</a>
    </div>

  </div>

</div>



<div id="content" class="large-12 columns">
  
<div class="example">
    
<h2><i class="icon-lock"></i> Secure Area</h2>

    
<h4 class="subheader">Welcome to the Secure Area. When you are done click logout below.</h4>

    <a class="button secondary radius" href="/logout"><i class="icon-2x icon-signout"> Logout</i></a>
  </div>

</div>

There are a couple of elements we can use for our assertions in this markup. There’s the flash message class (most appealing), the logout button (appealing), or the copy from the h2 or the flash message (least appealing).

Since the flash message class name is descriptive, denotes a successful login, and is less likely to change than the copy, let’s go with that.

class="flash success"

When we try to access an element like this (e.g., with a multi-worded class) we will need to use a CSS selector or an XPath.

NOTE: Both CSS selectors and XPath work well, but the examples throughout this course will focus on how to use CSS selectors.

A Quick Primer on CSS Selectors

In web design, CSS (Cascading Style Sheets) are used to apply styles to the markup (HTML) on a page. CSS is able to do this by declaring which bits of the markup it wants to alter through the use of selectors. Selenium operates in a similar manner but instead of changing the style of elements, it interacts with them by clicking, getting values, typing, sending keys, etc.

CSS selectors are a pretty straightforward and handy way to write locators, especially for hard to reach elements.

For right now, here’s what you need to know. In CSS, class names start with a dot (.). For classes with multiple words, put a dot in front of each word, and remove the spaces (e.g., .flash.success for class='flash success').

For a good resource on CSS Selectors, I encourage you to check out Sauce Labs’ write up on them.

Part 3: Write The Assertion And Verify It
Now that we have our locator, let’s add an assertion that uses it.

  • Coming Soon…
  • //filename: tests/LoginTest.cs
    // ...
            [Test]
            public void ValidAccount()
            {
                Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/login");
                Driver.FindElement(By.Id("username")).SendKeys("tomsmith");
                Driver.FindElement(By.Id("password")).SendKeys("SuperSecretPassword!");
                Driver.FindElement(By.CssSelector("button")).Click();
                Assert.That(Driver.FindElement(By.CssSelector(".flash.success")).Displayed);
            }
        }
    }

    With Assert.That we are checking for a true Boolean response. If one is not received the test will fail. With Selenium we are seeing if the success message element is displayed on the page (with .Displayed). This Selenium command returns a Boolean. So if the element is rendered on the page and is visible (e.g., not hidden or covered up by an overlay), true will be returned, and our test will pass.

    When we save this and run it it will run and pass just like before, but now there is an assertion which will catch a failure if something is amiss.

    Just To Make Sure

    Just to make certain that this test is doing what we think it should, let’s change the locator in the assertion to attempt to force a failure and run it again. A simple fudging of the locator will suffice.

    Assert.That(Driver.FindElement(By.CssSelector(".flash.successasdf")).Displayed);

    If it fails then we can feel reasonably confident that the test is doing what we expect and we can change the assertion back to normal before committing our code. This trick will save you more trouble that you know. Practice it often.

  • Coming Soon…
  • Coming Soon…
January 18, 2018

How to update test run status using vba/vbs script

Sample 1
 ' Set the Test Object
        Set tstInstance = TestList(i)
        tstInstance.Status = "No Run" 
        tstInstance.Post 
         'Create a run of the test instance 
        'runName = testName
        Set RunF = tstInstance.RunFactory 
        Set theRun = RunF.AddItem(Null) 
        theRun.Status = testStatus
        theRun.Name = testName
        theRun.Post 
         'Get the design step created above for the test 
         ' to be associated with this test run 
        theRun.CopyDesignSteps 
        theRun.Post 
         'Add the steps to run and fail them 
        Set runStepF = theRun.StepFactory 
        Set lst = runStepF.NewList("") 
        For Each Item In lst 
            Set runStep2 = Item 
            runStep2.Status = testStatus 
            runStep2.Post 
        Next 
sample 2
Sub ConnectToQualityCenter()


'-----------------------------------------------------Connect to Quality Center --------------------------------------------------------


MsgBox "Starting Connectinon"
Dim qcURL As String
Dim qcID As String
Dim qcPWD As String
Dim qcDomain As String
Dim qcProject As String
Dim tdConnection As Object
Dim TestSetFact, tsTreeMgr, tSetFolder, TestSetsList, theTestSet
Dim TestSetIdentifier, TSTestFact, TestSetTestsList, testInstanceF, aFilter
Dim lst, tstInstance

On Error GoTo err
   qcURL = "Server Details/qcbin"
   qcID = "UserName"
   qcPWD = "Password"
   qcDomain = ""
   qcProject = ""

'Display a message in Status bar
 Application.StatusBar = "Connecting to Quality Center.. Wait..."
'Create a Connection object to connect to Quality Center
  Set tdConnection = CreateObject("TDApiOle80.TDConnection")
'Initialise the Quality center connection
   tdConnection.InitConnectionEx qcURL
'Authenticating with username and password
   tdConnection.Login qcID, qcPWD
'connecting to the domain and project
   tdConnection.Connect qcDomain, qcProject
'On successfull login display message in Status bar
  Application.StatusBar = "........QC Connection is done Successfully"
  MsgBox "Connection Established"


'---------------------------------------Connection Established --------------------------------------------------------------------------

'
' Get the test set tree manager from the test set factory
'tdconnection is the global TDConnection object.
Set TSetFact = tdConnection.TestSetFactory
Set tsTreeMgr = tdConnection.testsettreemanager
' Get the test set folder passed as an argument to the example code
nPath = Trim("Your Test Set Folder Path")

Set tsFolder = tsTreeMgr.NodeByPath(nPath)
--------------------------------Check if the Path Exists or NOt ---------------------------------------------------------------------
If tsFolder Is Nothing Then  
Msgbox "Error"
End If

' Search for the test set passed as an argument to the example code
Set tsList = tsFolder.FindTestSets("Test Set Name")
----------------------------------Check if the Test Set Exists --------------------------------------------------------------------
If tsList Is Nothing Then
Msgbox "Error"
End If

'---------------------------------------------Check if the TestSetExists or is Duplicated ----------------------------------------------

If tsList.Count > 1 Then
MsgBox "FindTestSets found more than one test set: refine search"
Exit Sub
ElseIf tsList.Count < 1 Then
MsgBox "FindTestSets: test set not found"
Exit Sub
End If

-------------------------------------------Access the Test Cases inside the Test SEt -------------------------------------------------

Set theTestSet = tsList.Item(1)

For Each testsetfound In tsList
Set tsFolder = testsetfound.TestSetFolder
Set tsTestFactory = testsetfound.tsTestFactory
Set tsTestList = tsTestFactory.NewList("")

For Each tsTest In tsTestList
MsgBox tsTest.Name
testrunname = "Test Case name"
If tsTest.Name = "Test case Name" Then

--------------------------------------------Accesss the Run Factory --------------------------------------------------------------------
Set RunFactory = tsTest.RunFactory
Set obj_theRun = RunFactory.AddItem(CStr(testrunname))
obj_theRun.Status = "Passed" '-- Status to be updated
obj_theRun.Post
End If
Next tsTest
Next testsetfound
'

'------------------------------------------------------Disconnect Quality Center -----------------------------------------------------------------

tdConnection.Disconnect
tdConnection.Logout
tdConnection.ReleaseConnection
MsgBox ("Logged Out")

-----------------------------------------Error Function to Display the Error in teh Excel Status Bar ---------------------------------------------

err:
'Display the error message in Status bar
Application.StatusBar = err.Description
 MsgBox "Some Error Pleas see ExcelSheet"


End Sub
December 31, 2017

The First Things You Need To Know

Selenium is really good at a specific set of things. If you know what those are and stick to them then you will be able to easily write reliable, scalable, and maintainable tests that you and your team can trust.

But before we dig in, there are a few things you’ll want to know before you write your first test.

Define a Test Strategy

A great way to increase your chances of automated web testing success is to focus your efforts by mapping out a testing strategy. The best way to do that is to answer four questions:

  1. How does your business make money (or generate value for the end-user)?
  2. How do your users use your application?
  3. What browsers are your users using?
  4. What things have broken in the application before?

After answering these, you will have a good understanding of the functionality and browsers that matter most for the application you’re testing. This will help you narrow down your initial efforts to the most important things.

From the answers you should be able to build a prioritized list (or backlog) of critical business functionality, a short list of the browsers to focus on, and include the risky parts of your application to watch out for. This prioritized list will help you make sure you’re on the right track (e.g., focusing on things that matter for the business and its users).

Pick a Programming Language

In order to work well with Selenium, you need to choose a programming language to write your acceptance tests in.

Conventional wisdom will tell you to choose the same language as what the application is written in. That way if you get stuck you can ask the developers on your team for help. But if you’re not proficient in this language (or new to development) then your progress will be slow and you’ll likely end up asking for more developer help than they have time for — hindering your automation efforts and setting you up for failure.

A great way to determine which language to go with is to answer one simple question: Who will own the automated tests?

Also, as you are considering which language to go with, consider what open source frameworks already exist for the languages you’re eyeing. Going with one can save you a lot of time and give you a host of functionality out of the box that you would otherwise have to build and maintain yourself — and it’s FREE.

You can see a list of available open source Selenium frameworks here.

Choosing a programming language for automated testing is not a decision that should be taken lightly. If you’re just starting out (or looking to port your tests) then considering and discussing these things will help position you for long term success.

Installation

  • Here are some installation instructions to help you get started quickly.

  • Here are some installation instructions to help you get started quickly.

  • There’s a great guide on “Properly Installing Python” which you can find here. It covers Mac OSX, Windows, and Ubuntu.

    NOTE: For doing proper software development in Python you’d want to consider something like Virtual Environments to effectively manage third-party dependencies. But for the needs of the examples in this book, it’s not necessary.

    Installing Third-Party Libraries

    There are over 84,000 third-party libraries (a.k.a. “packages”) available for Python through PyPI (the Python Package Index). To install packages from it you use a program called pip.

    To install them you use pip install package-name from the command-line.

    Here is a list of the packages that will be used throughout the bootcamp.

  • Here are some installation instructions to help you get started quickly.

December 30, 2017

How To Take a Screenshot on Failure with Selenium

The Problem

With browser tests it can often be challenging to track down the issue that caused a failure. By itself a failure message along with a stack trace is hardly enough to go on. Especially when you run the test again and it passes.

A Solution

A simple way to gain insight into your test failures is to capture screenshots at the moment of a failure. And it’s a quick and easy thing to add to your tests.

Let’s dig in with an example.

An Example


  • Let’s start by importing our requisite classes (for annotations (e.g., org.junit.After, etc.), driving the browser with Selenium (e.g., org.openqa.selenium.WebDriver, etc.), and matchers for our assertions (e.g., org.hamcrest.CoreMatchers, etc.)) and start our class with a setup method.

    // filename: Screenshot.java
    import org.junit.Before;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.TestRule;
    import org.junit.rules.TestWatcher;
    import org.junit.runner.Description;
    import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import java.io.File;
    import java.io.IOException;
    import org.apache.commons.io.FileUtils;
    import static org.hamcrest.CoreMatchers.*;
    import static org.hamcrest.MatcherAssert.assertThat;
    
    public class Screenshot {
    WebDriver driver;
    
    @Before
    public void setUp() throws Exception {
    driver = new FirefoxDriver();
    }
    // ...
    

    We still need to handle our teardown. But in order to get the timing right withscreenshots on failure we’ll need to break from the norm of a simple @After annotation. For this we’ll look to a JUnit Rule, specifically the TestWatcher.

    // filename: Screenshot.java
    // ...
        @Rule
        public TestRule watcher = new TestWatcher() {
            @Override
            protected void failed(Throwable throwable, Description description) {
                File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
                try {
                    FileUtils.copyFile(scrFile,
                            new File("failshot_"
                                    + description.getClassName()
                                    + "_" + description.getMethodName()
                                    + ".png"));
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
    
            @Override
            protected void finished(Description description) {
                driver.quit();
            }
        };
    

    With a TestWatcher we easily gain access to a test after it’s failed (e.g., in the failed method) and when the test completes regardless of it’s outcome (e.g., the finished method). So for our teardown we issue driver.quit(); in finished. And when there’s a failure we capture ascreenshot and write it to disk (in the current working directory) in failed.

    There are numerous ways to make the filename unique (e.g., unique ID, timestamp, etc.). The simplest way to get started is with the test class name and the test method name, which we’ve done.

    Now let’s wire up our test with a forced failure.

    // filename: Screenshot.java
    // ...
        @Test
        public void OnError() {
            driver.get("http://the-internet.herokuapp.com");
            assertThat(false, is(true));
        }
    
    }
    

    Expected Behavior

    When you save this file and run it (mvn clean test from the command-line) here is what will happen:

    • Open the browser
    • Visit the page
    • Fail
    • Capture a screenshot in the current working directory with the name failshot_Screenshot_OnError.png
    • Close the browser

  • Let’s start by including our requisite classes for our test framework (e.g., NUnit.Framework), driving the browser with Selenium (e.g., OpenQA.Selenium, etc.), accessing C#’s image functionality (e.g., System.Drawing.Imaging), and start our class off with some setup and teardown methods.

    // filename: Screenshot.cs
    using NUnit.Framework;
    using NUnit.Framework.Interfaces;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Firefox;
    using System.Drawing.Imaging;
    
    public class Screenshot
    {
        IWebDriver Driver;
    
        [SetUp]
        public void SetUp()
        {
            Driver = new FirefoxDriver();
        }
    
        [TearDown]
        public void TearDown()
        {
            if (TestContext.CurrentContext.Result.Outcome.Status.Equals(TestStatus.Failed))
                TakeScreenshot();
    
            Driver.Quit();
        }
    // ...
    

    Notice in the teardown we have a conditional statement before we call Driver.Quit();. It’s checking to see if the test failed, if it has then it will take a screenshot. Right now the method we’re referencing isn’t declared. Let’s add it now.

    There are numerous ways to make the filename unique for the screenshot(e.g., unique ID, timestamp, etc.). The simplest way to get started is with the full test name (e.g., test class name and test method name), which we’ve done. We also specified the save location on disk using a string literal (e.g., @"C:\Temp"), feel free to change it to suit your needs.

    The rest is a simple matter of casting the Driver as an ITakeScreenshot object and calling GetScreenshot().SaveAsFile(specifying the save location and image format — which is PNG in this case).

    Now let’s wire up our test with a forced failure.

    // filename: Screenshot.cs
    // ...
        private void TakeScreenshot()
        {
            string SaveLocation = @"C:\Temp\" +
                                   "failshot_" +
                                   TestContext.CurrentContext.Test.FullName +
                                   ".png";
            ITakesScreenshot ScreenshotDriver = (ITakesScreenshot) Driver;
            ScreenshotDriver.GetScreenshot().SaveAsFile(SaveLocation, ImageFormat.Png);
        }
    // ...
    

    There are numerous ways to make the filename unique for the screenshot(e.g., unique ID, timestamp, etc.). The simplest way to get started is with the full test name (e.g., test class name and test method name), which we’ve done. We also specified the save location on disk using a string literal (e.g., @"C:\Temp"), feel free to change it to suit your needs.

    The rest is a simple matter of casting the Driver as an ITakeScreenshot object and calling GetScreenshot().SaveAsFile(specifying the save location and image format — which is PNG in this case).

    Now let’s wire up our test with a forced failure.

    
    // filename: Screenshot.cs
    // ...
    [Test]
    public void ScreenShotOnFailure()
    {
    Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com");
    Assert.That(false.Equals(true));
    }
    }
    

    Expected Behavior

    When you save this file and run it (nunit3-console.exe .\Screenshot.sln from the command-line) here is what will happen:

    • Open the browser
    • Visit the page
    • Test Fails
    • Selenium Captures a screenshot in C:\Temp with the name failshot_Screenshot.ScreenShotOnFailure.png
    • Close the browser

  • Let’s start by importing our requisite libraries (import unittest for our test framework, from selenium import webdriver to drive the browser, and import sys to determine when there’s a test failure), declare our test class, and wire up some test setUp and tearDown methods.

    # filename: screenshot.py
    import sys
    import unittest
    from selenium import webdriver
    
    
    class ScreenShotOnFailure(unittest.TestCase):
    
        def setUp(self):
            self.driver = webdriver.Firefox()
    
        def tearDown(self):
            if sys.exc_info()[0]:
                self.driver.save_screenshot("failshot_%s.png" % self._testMethodName)
            self.driver.quit()
    # ...
    

    In tearDown we check to see if sys.exc_info()[0] exists. If it does, then there’s been a test failure and we capture a screenshot through the help of Selenium‘s .save_screenshot method. .save_screenshot accepts a filename as a string (e.g., 'failshot.png'). To make the filename unique we use the test method name (e.g., self._testMethodName). When this command executes it will save an image file to the local system in the current working directory.

    Now to wire up a test which will fail.

    # filename: screenshot.py
    # ...
        def test_example_1(self):
            driver = self.driver
            driver.get('http://the-internet.herokuapp.com')
            assert driver.title == 'blah blah blah'
    
    if __name__ == "__main__":
        unittest.main()
    

    Expected Behavior

    When we save this file and run it (python screenshot.py from the command-line) here is what will happen:

    • Open the browser
    • Load the homepage of the-internet
    • Check the text of the page header and fail
    • Output a failure message in the terminal
    • Capture a screenshot in the current working directory
    • Close the browser

 

December 28, 2017

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start writing!

April 30, 2015

How to build a stylish landing page in minutes.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam.

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi.

Read More

April 30, 2015

What’s the deal with Backface Visibility?

small6

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam.

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi.

Read More

March 19, 2015

HTML Testing

The following post is testing the basic HTML elements that can be used in WordPress Easily.

Read More