July 28, 2010 0

Run Selenium Cases Through A Web Interface

By Anthony in Python, QA, Selenium, Snippets, Test Automation, Testing

I’ve heard a couple of people ask how to run Selenium test cases through a web interface with python. Here is how you do it.

I do not recommend this. Some cases can take over 30-60 seconds to run, and would cause the browser to time out before it finished, which would render the case, and this mechanism useless.

However if you still want to give this a shot, here is some sample code to get you started.

from selenium import selenium
from flask import Flask
from flask import render_template
import unittest
SERVER_SETUP = ["ip_for_selenium_server", 4444, "*firefox", "your_base_url"]

app = Flask(__name__)

@app.route("/")
def index():
    return render_template('template.html', name='index')

@app.route("/Test_1/")
def test_1():
    selenium.selenium = selenium(*SERVER_SETUP)
    selenium.selenium.start()
    selenium.selenium.open("http://example.com/")
    selenium.selenium.click("link=ishjdf")

if __name__ == "__main__":
    app.run(debug=True)

Everything in the above script should be obvious. The cool part about app.run() is it has debug=True, which will restart the server whenever you edit and save the code.

Here is the template.html.

<!DOCTYPE html>
<html>
<head>
<style>
body{ font-size: 12px; font-family: Arial; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>

<b><h1>Some Text Here</b></h1>
<script>
function test(url) {
	alert(url);
   $('#result').load(url);
}
$(document).ready(function() {
   $("a").click(function(e) {
       e.preventDefault();
       var url = $(this).attr("href");
       test(url);
   });
});
</script>

<a href="/Test_1/">Perform Test 1</a>
<div id="result"></div>
</body>
</html>

Add this inside a folder within your root, called templates/. You should have root/ and root/templates.

Enjoy.