Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

How to Test JSON with Selenium Python

Many web applications provide API for external clients to use in their internal applications. When testing APIs with json response, QA engineers need to verify that what UI displayed should be equal to the API response for the same request input. In this article, we use the Open Weather API as an example to test the web response for this url "api.openweathermap.org/data/2.5/weather?q=London,uk" should be the same as the API response. For verifying UI with API response, please visit related articles on this website. 

The purpose of this example is to teach you how to parse Json response and assert on the content of Json response. For Example:

(1) when we navigate to this page "api.openweathermap.org/data/2.5/weather?q=London,uk" on web browser , we will see the following response. 

{"coord":{"lon":-0.13,"lat":51.51},"sys":{"type":1,"id":5187,"message":0.1923,"country":"GB","sunrise":1414565376,"sunset":1414600727},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50n"},{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09n"},{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"cmc stations","main":{"temp":288.14,"pressure":1011,"humidity":93,"temp_min":288.05,"temp_max":288.15},"wind":{"speed":4.6,"deg":240},"clouds":{"all":92},"dt":1414547621,"id":2643743,"name":"London","cod":200}

(2) when we navigate to this page "api.openweathermap.org/data/2.5/weather?q=Bristol,uk" on web browser , we will see the following response. 

{"coord":{"lon":-2.6,"lat":51.46},"sys":{"type":1,"id":5076,"message":0.0434,"country":"GB","sunrise":1414565962,"sunset":1414601327},"weather":[{"id":741,"main":"Fog","description":"fog","icon":"50n"},{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"cmc stations","main":{"temp":287.43,"pressure":1013,"humidity":93,"temp_min":287.15,"temp_max":288.15},"wind":{"speed":4.1,"deg":270},"clouds":{"all":90},"dt":1414547400,"id":2654675,"name":"Bristol","cod":200}

In the above Json responses, in both cases, the name key should contain "London" or "Bristol" depending on the city we pass to the API. 

Test Case: verify that weather API JSON response in the UI should contain city name.  see the python code and execution result below. 

 

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import json

class PythonSeleniumJsonParsing(unittest.TestCase):

    def setUp(self):
        self.driver= webdriver.Firefox()
        

        
    def test_verify_city_json_response_London(self):
    
        self.driver.get("http://api.openweathermap.org/data/2.5/weather?q=London,uk")
        elem=self.driver.find_element_by_tag_name("pre")
        content=elem.text
        print(content)
        j=json.loads(content)
        city=j["name"]
        self.assertEqual(city,'London')
           
    def test_verify_city_json_response_Bristol(self):
        self.driver.get("http://api.openweathermap.org/data/2.5/weather?q=Bristol,uk")
        elem=self.driver.find_element_by_tag_name("pre")
        content=elem.text
        print(content)
        j=json.loads(content)
        city=j["name"]
        self.assertEqual(city,'Bristol')
        
    def test_verify_city_json_response_fail(self):
    
        self.driver.get("http://api.openweathermap.org/data/2.5/weather?q=Bristol,uk")
        elem=self.driver.find_element_by_tag_name("pre")
        content=elem.text
        print(content)
        j=json.loads(content)
        city=j["name"]
        self.assertEqual(city,'London') 

    def tearDown(self):
    
        self.driver.close()

if __name__ == "__main__":
    unittest.main()


When running the python code, two positive tests passed and one negative test failed (this is expected because expected result was Bristol, but we set it to "London"). 

 

Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
{"coord":{"lon":-2.6,"lat":51.46},"sys":{"type":1,"id":5076,"message":0.0434,"country":"GB","sunrise":1414565962,"sunset":1414601327},"weather":[{"id":741,"main":"Fog","description":"fog","icon":"50n"},{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"cmc stations","main":{"temp":287.43,"pressure":1013,"humidity":93,"temp_min":287.15,"temp_max":288.15},"wind":{"speed":4.1,"deg":270},"clouds":{"all":90},"dt":1414547400,"id":2654675,"name":"Bristol","cod":200}
.{"coord":{"lon":-0.13,"lat":51.51},"sys":{"type":1,"id":5187,"message":0.1923,"country":"GB","sunrise":1414565376,"sunset":1414600727},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50n"},{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09n"},{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"cmc stations","main":{"temp":288.14,"pressure":1011,"humidity":93,"temp_min":288.05,"temp_max":288.15},"wind":{"speed":4.6,"deg":240},"clouds":{"all":92},"dt":1414547621,"id":2643743,"name":"London","cod":200}
.{"coord":{"lon":-2.6,"lat":51.46},"sys":{"type":1,"id":5076,"message":0.0434,"country":"GB","sunrise":1414565962,"sunset":1414601327},"weather":[{"id":741,"main":"Fog","description":"fog","icon":"50n"},{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"cmc stations","main":{"temp":287.43,"pressure":1013,"humidity":93,"temp_min":287.15,"temp_max":288.15},"wind":{"speed":4.1,"deg":270},"clouds":{"all":90},"dt":1414547400,"id":2654675,"name":"Bristol","cod":200}
F
======================================================================
FAIL: test_verify_city_json_response_fail (__main__.PythonSeleniumJsonParsing)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Python27\seleniumjsonexample.py", line 40, in test_verify_city_json_response_fail
    self.assertEqual(city,'London')
AssertionError: u'Bristol' != 'London'

----------------------------------------------------------------------
Ran 3 tests in 28.517s

FAILED (failures=1)

When parsing JSON in Python, we can use json package. Here are the steps in the code implementation. 

1. Use Selenium Web Driver to navigate to the API URL and obtain JSON string from the UI. 
2. Use json.loads to read the JSON string. 
3. Use jsonvariable["name"] to read the name key. In this example, jasonvariable is "j".
4. Run the test and observer the result. This test uses unittest Python framework.