DEV Community

Cover image for Why I'm switching from C# to Python with Selenium
tswiftma
tswiftma

Posted on

Why I'm switching from C# to Python with Selenium

I was recently tasked with automating our product's new login wrapper. This involved hitting the server UI page, redirecting to a login page and validating if the login succeeds or fails. Another requirement was to have the ability to run the tests in Azure DevOps pipelines.

I'm typically not a UI automation guy, I usually focus on Rest APIs and code in C#. So I started with Selenium C#. While it was fairly easy to automate the login steps I was immediately blocked when I found out that I need to support host headers to run the tests in a Kubernetes (K8S) environment. Well Selenium out of the box doesn't support host headers...

I stared searching for possible solutions and the best one I found by far was Seleniumwire. Seleniumwire supports access to underlying requests/responses. You can modify them and get http response codes as well. I felt like I was back in my API testing world! The only difference was that Seleniumwire only supports PYTHON and not C#. But I had to have the Seleniumwire functionality even if my Python skills were somewhat noob-ish.

Lets look how easy it is to set a host header with Seleniumwire

import pytest
from seleniumwire import webdriver

def test_isAlive(url, hostheader):
    web_driver = webdriver.Chrome()
    web_driver.maximize_window()
    # check to set host header    
    if hostheader != 'none':
            web_driver.header_overrides = {'Host' : hostheader}

    isAliveUrl = '/api/isAlive'
    UIEndpoint = url
    loginURL = UIEndpoint + isAliveUrl
    web_driver.get(loginURL)

Enter fullscreen mode Exit fullscreen mode

Now the above isn't the whole script but you get the picture. This solved a huge issue that wasn't possible with Selenium C#. Note that I check for a host header value of "none" if I don't want to use a host header.

Another cool Seleniumwire feature is to grab an http response code which I can then use in an assert to check that the page loaded. This can be an additional test to the builtin Selenium page load response check.

# Access requests via the `requests` attribute
    for request in web_driver.requests:
        if request.response:
            print(
                request.url,
                request.response.status_code,
                request.headers                
            )    

    assert request.response.status_code == 200
Enter fullscreen mode Exit fullscreen mode

These Seleniumwire features might seem minor but they are actually huge helps in UI Automation. Selenium should get off of it's high "we need to act like a browser" horse and incorporate this library in all versions! Until they do I'm now a Python automation guy :)

Top comments (0)