Writing Test Cases using Python with Selenium
Tags: webdev, testing, python, beginners
Published: 2020-02-24 14:51:01

# Introduction
![undraw welcome cats thqn][1]

How would you test a UI that mimics an actual user? Well, there are tons of front-end testing framework like [Cypress][2], [TestCafe][3], [Protractor][4].

What I am going to introduce to you is something is considered the industry standard for front-end testing and is quite popular among testers for websites. Which mimics an actual user to interact with your UI without the need to learn another programming language to just get started.

Do note that there are subtle differences between each programming languages when you are using Selenium. Because the library is created and maintained by multiple open-source contributors. Which may not be affiliated to the main Selenium contributor besides using Selenium and building wrappers for their specific programming language.

# Why Selenium?
![undraw sorting thoughts 6d48][5]

Selenium is the tool of choice for not just website UI testing. Instead, it is used for **data scrapping** & **automation** because it mimics an actual user. 

As the difficulty arise when you try to scrape data from a website which uses javascript to display data. You need to configure a browser to execute the javascript code. Which could be circumvented by using [Splash][6] but this comes with additional configuration to extract data.

# Writing Test Case
![undraw completed steps yurw][7]

To write test cases, my choice of testing framework is [Pytest][8] as it makes it easy for anyone to get started to create test cases and the [fixtures][9]. Which allow quick loading of states or environment before executing a test case for a website.

This allows you to create a [user journey][10]. Which automatically tests how a user navigates or interacts with the website. This can be integrated into your CI/CD process to catch user interaction or UI errors. Before an actual deployment to the production server and making it live for anyone to use it.
  
## CSS vs Xpath
![undraw connection b38q][11]

To write test cases for a website using Selenium. The first thing that you need to do. Besides starting a browser instance and redirecting the browser instance to the website link. It is finding a specific html element on the website. 

So that Selenium could do something with it. Which could be used by either initiating a click, waiting for the element to load or extract data of that html element to check if you had the correct value.

There are multiple ways for you to do it. The most common way for you to do it is using a [selector][12] using either [CSS][13] or [Xpath][14] paths. 

My personal preference is using the **Xpath** of the html element you would like to select. Because seldom do the html element contain a **class id** or **name attribute** to represent that element in the webpage.

Which you can get it easily if you are using either Firefox or Chrome by right-clicking your mouse to display builtin developer tool. Once you select "inspect", now right-click again to **copy** the XPath of the element that you would like to select to locate the element when you are running the test case.

![inspect element][15]

![copy xpath][16]
# Writing Test cases for Front-end Web Framework
![undraw detailed analysis xn7y][17]

Before you write your test cases, ensure that you had installed following python packages and chromium using a Linux machine.:

```bash
pip install pytest selenium
sudo apt update
sudo apt install chromium-chromedriver
``` 

To write the test case first create a file called `test_user_flow.py` then use the code below:


```python
from selenium import webdriver  # imports the selenium webdriver


def test_get_title():
    path = "http://www.python.org"  # the starting url
    driver = webdriver.Chrome()  # initialise a driver that is using the chrome driver for selenium
    driver.get(path)  # redirects the driver to that url path

    assert "Python" in driver.title  # a test case which checks if the title contains the "Python"

    driver.close()  # closes the browser once it has completed


test_get_title()

```

Now let us run the test case, it should pop up a chrome browser and run twice for your code shows a pass for your test case:

```bash
pytest -v
```

![test case][18]

# Conclusion
![undraw feeling proud qne1][19]

I hope the article is useful for you and introduces you to selenium. Which is used not mainly for UI testing? But in data scrapping and automation because of convenience to display data for javascript heavy websites with wide support of multiple programming languages.

I had also listed down the reason why you should choose to use `Xpath` for selecting an html element. You use it when it does not contain any `class attributes` or `id` to identify the element within the webpage.

If you like this article do **sign up** for my [Adventurer's Newsletter](https://maxongzb.activehosted.com/f/1) for my **Adventurer's newsletter** which contains interesting content I stumble across over the week in the area of **Python**, **Web Development**, **Startup** .

You can also **follow** me to get the **latest** update of my article on **Dev**
The original post was on [Writing Test Cases using Python with Selenium - Reading Time: 4 Mins](https://www.maxongzb.com/writing-test-cases-using-python-with-selenium-reading-time-4-mins/) and cover image by [Daniel Korpai on Unsplash](https://unsplash.com/photos/mxPiMiz7KCo)

# Reference
* [Cypress][2]
* [TestCafe][3]
* [Protractor][4]
* [Selenium Python][20]
* [Splash][6]
* [Web Automation With Selenium][21]
* [Advanced Python Programming: Browser Automation with Selenium][22]
* [PyTest][8]
* [Fixtures][9]
* [User Journey][10]
* [Selector][12]
* [CSS][13]
* [Xpath][14]
* [Obey the Testing Goat][23]
* [Python Testing with Pytest][24]
* [The power of Headless Chrome and Browser Automation][25]
* [Getting Started with Selenium - Using Selenium to write tests][26]
* [Undraw][27]


[1]: //images.ctfassets.net/ly2f59p4unnn/34lOB5oA2JdeeXYQ95kSai/38e3bca4afe952da5392336dd30d18a5/undraw_welcome_cats_thqn.png
[2]: https://www.cypress.io/
[3]: https://testcafe.devexpress.com/Documentation/
[4]: https://www.protractortest.org/#/
[5]: //images.ctfassets.net/ly2f59p4unnn/3NiWT43nSWTzhoL97Z2tax/3d852b470fa9074178175b70a961b719/undraw_sorting_thoughts_6d48.png
[6]: https://scrapinghub.com/splash
[7]: //images.ctfassets.net/ly2f59p4unnn/269uzT9eTBL59CLMR33qND/266a3e86efe82dccdb0a8f05628d7f0d/undraw_completed_steps_yurw.png
[8]: https://docs.pytest.org/en/latest/
[9]: https://docs.pytest.org/en/latest/fixture.html#fixture
[10]: https://uxplanet.org/a-beginners-guide-to-user-journey-mapping-bd914f4c517c
[11]: //images.ctfassets.net/ly2f59p4unnn/5H8bYBOCX2RyaRxcS6rvGa/1034f708c4989284c998b87f470f3915/undraw_connection_b38q.png
[12]: https://selenium-python.readthedocs.io/locating-elements.html#
[13]: https://saucelabs.com/resources/articles/selenium-tips-css-selectors
[14]: https://developer.mozilla.org/en-US/docs/Web/XPath
[15]: //images.ctfassets.net/ly2f59p4unnn/5lTH78VNxK5EQiLdfFL4ET/c96ffe08ffba7f6ecbc167860c873249/inspect_element.png
[16]: //images.ctfassets.net/ly2f59p4unnn/WquCCcavzB1XvkcMkPYtE/a2211152421745d64380328c7a359f3d/copy_xpath.png
[17]: //images.ctfassets.net/ly2f59p4unnn/3L5RywisX6LGZYz6092sv1/8a86eb1ab8c59888640edb67c872f264/undraw_detailed_analysis_xn7y.png
[18]: //images.ctfassets.net/ly2f59p4unnn/4SpgwXlpctLGmsjR76brhY/d892204306a77ab5d6e76c165e53abe5/test_case.png
[19]: //images.ctfassets.net/ly2f59p4unnn/2mWSoUJulxg4YcTUUM9Ukq/d12a690633e76cdf039e4f303a48c096/undraw_feeling_proud_qne1.png
[20]: https://selenium-python.readthedocs.io/
[21]: https://realpython.com/modern-web-automation-with-python-and-selenium/
[22]: https://youtu.be/GJjMjB3rkJM
[23]: https://www.obeythetestinggoat.com/
[24]: https://pragprog.com/book/bopytest/python-testing-with-pytest
[25]: https://youtu.be/lhZOFUY1weo
[26]: https://selenium-python.readthedocs.io/getting-started.html#using-selenium-to-write-tests
[27]: https://undraw.co/