Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Using Python Selenium to Write Tests

Users can write test cases using Python's unittest module. In this article, we use unittest as the test framework for Python Selenium WebDriver. This test is for http://demo.mahara.org login functionality. 

Test Case: authorized users are able to login Mahara Demo site. Here are test steps. 

1. Navigate to demo.mahara.org and verify that web page title "Home-Mahara" displays. 

2. Enter "student2" in the Username filed. 

3. Enter "Testing1" in the Password field. 

4. Click on the Login button

5. Assert that Logout link is present. 

Python Code for Test Implementation

Run Python GUI (IDLE) and write the following code. 


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

class DemoMaharaOrgLogin(unittest.TestCase):

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

    def test_login_in_demo_mahara_org(self):
        driver = self.driver
        driver.get("http://demo.mahara.org/")
        self.assertIn("Home - Mahara", driver.title)
        username = driver.find_element_by_id("login_login_username")
        username.send_keys("student2")
        password=driver.find_element_by_id("login_login_password")
        password.send_keys("Testing1")
        loginbutton=driver.find_element_by_id("login_submit")
        loginbutton.click()
        self.assertTrue(driver.find_element_by_link_text("Logout"),"Logout link")

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

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

Save the code as DemoMaharaOrgLogin.py and then click on "Run Module F5" under Run menu to execute the test. Here is the test result. This result indicated that the test passed. 

Ran 1 test in 14.662s

OK

You can also run the above test case from a shell like this:

python DemoMaharaOrgLogin.py