Can Python's selenium library play a test case saved as HTML - python

I'd like to be able to write a Django LiveServerTestCase which runs a Selenium test that has been saved as HTML using the Selenium IDE. The code might look something like this:
from django.test import LiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver
class TestUserStories(LiveServerTestCase):
#classmethod
def setUpClass(cls):
cls.selenium = WebDriver()
super(MySeleniumTests, cls).setUpClass()
def test_registration(self):
# Note - 'run_html_test' doesn't exist
self.selenium.run_html_test('selenium/registration.html')
This would allow our QA team (who don't speak python) to write tests using the Firefox Selenium IDE and save them as HTML. Is this possible?
As far as I can tell, HTML is the best format to save the tests in as it allows them to be edited in the IDE later on - exporting to python doesn't allow this and also generates python that needs converting to work with the Django LiveServerTestCase.

I started a project myself to build this sort of shim: to wrap existing HTML-based Selenium tests with Python, without having to convert the existing tests. It was for the same reason you state: a (client) testing team wanted to write HTML Selenium tests, but we wanted to run them using Selenium RC. Here's the link:
https://github.com/jpstacey/PySelenese
However, we mothballed the specific sub-project it was built for, so it hasn't had any attention for a long time.
With regards to your specific request, writing a standalone LiveServerTestCase isn't optimal, because you then lose Selenium's idea of having many test cases within a suite, and a suite index.html to define it. PySelenese instead wraps the whole test suite and runs all test cases within it, in the order that the Selenium IDE would run it; but I admit that the code to do that isn't currently very pretty and could be more Pythonic.
But this in theory could do what you want, so feel free to try it out, fork the github project, make your own changes etc. The PySelenese layer currently has limited support for many Selenium commands, but that's fairly extensible.
(Explicit disclaimer: PySelenese started as my own personal Github project.)

Related

Import python projects to a HTML page

Supose I have a python game and I want to "post" it on a site like Friv that I am making. Is there any way
for me import the "game.py" to the "site.html" and it show when I enter the site? I made a search and found to use django, but I would need to pass all the html code that I already have to other aplication.
The language of browsers is JavaScript.
There is a project called PyJs which translates Python code to JavaScript and is useful in your case that you want to run Python code inside web browsers.
Finally you can use your resulting JavaScript files to fill up your HTML page.
In addition to PyJs, there are numerous other projects that "run Python code in a browser" like Brython. However, any of them have not been standardized and if you want a robust game in your browser, use JavaScript!
There are number of projects that compile python into JavaScript in order to be run on browser.
Here are two links that might help
Web Browser Programming: https://wiki.python.org/moin/WebBrowserProgramming
PyGame Trinket: https://trinket.io/features/pygame
The way I integrate python code in an html is to use templating language like jinja2 but if you want to write full python code in html then use need to use a transpiler like PyJS but since you want to integrate the same code in multiple program, why not use FLASK it is much more easier.
and make an api. Django is an option but it has a steep learning curve. you can make the UI using HTML and get the data from python using API.

Using RobotFramework APIs for creating the testcases in Python

I have Automation Repository coded in Python. Now i want to use some of the RobotFramework features like, html for logs and output, xml creation. Will it be possible to use somehow the Robot features in my existing testcases written in Python Unittest library without re-writing these. Please let me know, if its the wrong way to approach this
Yes #rjha,
You can use your testcases written in python. Generally in robot framework we will import the libraries which are written in Python. Using the same concept we can use your testcases which are written in Python.
Here I'm using RED Editor in Eclipse, according to my experience to use modules which are created should be imported to your red.xml file and each method name would be your keyword and when you completed running execution from testsuite file, log.html and report.html will be generated which you want for results generation.
For Better testcase execution results import "Logging" module where you can use log.info, log.warn etc., in your testcases which will be displayed in generated html reports
enter image description here

Selenium+python Reporting

I am doing some R&D on selenium+python. I wrote some test cases in python using selenium webdriver and unittest module. I want to know how can I create report of the test cases. Is there inbuilt solution available in selenium or I need to code to generate file.
Or is there any other web testing framework with javascript support available in python which have reporting functionality.
I am basically new to python as well as selenium. Just trying to explore.
To start building test reports on top of Selenium+Python, I would leverage the python unittest module. You will get a basic sample in Selenium documentation here.
Then HTMLTestRunner module combined with unittest provides basic but robust HTML reports.
Use HTMLTestRunner
Go to below URL :
http://tungwaiyip.info/software/HTMLTestRunner.html
Click on HTMLTestRunner.py
Copy all code
Create a file in your project with name HTMLTestRunner.py and dump the code
Now import that file in your script using import keyword
In main method call HTMLTestRunner
Example code:
from selenium import webdriver
import unittest
import HTMLTestRunner
class LoginTest(unittest.TestCase):
def setUp(self):
print driverpath
self.driver = webdriver.Chrome(driverpath + "chromedriver.exe")
self.driver.get("http://google.com/")
def testPythonScript(self):
driver=self.driver
driver.maximize_window()
driver.implicitly_wait(60)
driver.get_screenshot_as_file(screenshotpath + "testPngFunction.png")
driver.find_element_by_xpath("(//a[contains(#href,'contact-us')])[1]").click()
driver.find_element_by_name("name").send_keys("shubham")
driver.find_element_by_id("contactemail").send_keys("shubham.xyz#abc.com")
driver.find_element_by_css_selector("#contact_form > div:nth-child(3) > div:nth-child(3) > input").send_keys(
"389198318312")
driver.find_element_by_name("company").send_keys("myname")
driver.get_screenshot_as_file(screenshotpath + "ConatctUs.png")
print driver.title
assert "Hello" in driver.title
print "execution ends"
def testPythonFailScript(self):
driver=self.driver
driver.find_element_by_name("notExist").send_keys("done")
def tearDown(self):
driver = self.driver
driver.quit();
if __name__ == "__main__":
HTMLTestRunner.main()
Now open terminal and fire below command
python scriptFileName.py > TestReport.HTML
Note: scriptFileName is a python file name and TestReport is html report name. you can name it as you want
My experience has been that any sufficiently useful test framework will end up needing a customized logging solution. You are going to end up wanting domain specific and context relevant information, and the pre-baked solutions never really fit the bill by virtue of being specifically designed to be generic and broadly applicable. If you are already using Python, I'd suggest looking in to the logging module and learning how to write Handlers and Formatters. It's actually pretty straight forward, and you will end up getting better results than trying to shoehorn the logging you need in to some selenium-centric module.
Consider using the robot framework. It has a plugin for selenium, and robot produces very nice logs and reports. With robot you don't directly write your tests in python (though, I suppose you can). Instead, robot is a keyword-based testing system built on top of python.
Robot Framework is a functional test framework that makes it possible for its users to:
Write tests in easily understood language
Organize what tests are run for specific purposes
Generate both high level and detailed test results
RF results file
RF log file
HTML page
In my specific application I use the Nose unittest extension for writing and running test suites.
On top of that I use an html-reporting plugin that produces nice reports from my test cycles.

Does Python have anything Like Capybara/Cucumber?

Ruby has this great abstraction layer on top of Selenium called Capybara, which you can use do functional/acceptance/integration testing. It also has another library called Cucumber which takes this a step further and lets you actually write tests in English.
Both libraries are built on top of Selenium, and can be used to test against any major browser, but because of their abstraction layers it's super easy to write tests using them (well, as easy as functional testing gets at least).
My question is: does Python have anything like that? I have found Pythonistas doing functional testing with various tools but ...
A) Splinter: doesn't use Selenium (and doesn't have an IE driver)
-EDIT-
It appears Spliter now does use Selenium (see answers below).
B) Alfajor: hasn't been updated in over a year; looks dead
C) Selenium (raw): a lot of people seem to be using Selenium directly, but it seems like an abstraction layer could make it a lot easier to use
So, does anyone know of anything Capybara-like, or better yet Cucumber-like, for Python (it doesn't have to actually use Selenium, but it needs to support all major browsers)?
* EDIT *
For those that aren't familiar with Capybara, it basically just adds an API so that instead of the normal Selenium API you can do something like this:
When /I sign in/ do
within("#session") do
fill_in 'Login', :with => 'user#example.com'
fill_in 'Password', :with => 'password'
end
click_link 'Sign in'
end
It's used by Cucumber, which let's you further abstract (almost to English):
Scenario Outline: Add two numbers
Given I have entered <input_1> into the calculator
And I have entered <input_2> into the calculator
When I press <button>
Then the result should be <output> on the screen
Examples:
| input_1 | input_2 | button | output |
| 20 | 30 | add | 50 |
I would LOVE a Python Cucumber equivalent, but even just a Capybara equivalent would be helpful.
You can test Python code using Cucumber - see the Cucumber wiki on github for more information.
If you want a pure Python solution, check out Lettuce. I've never used it, but there is a fairly useful looking blog entry about it and splinter here.
A. Cucumber like: ( English like)
Lettuce (Approach Gherkin) or
Behave (Approach Gherkin) or
Robotframework (Approach keyword based)
(Additional Info: RF is larger than English Like criteria. Its keyword-based and offers loads of helper method and inbuilt libraries. Great eco-sysstem for external libraries. Any python script can also be modified and used along with RF)
Freshen (Approach Gherkin) or
Pea (Approach Gherkin) or
RedwoodHQ (Approach keyword based)
(RedwoodHQ has features larger than 'English-Like' criteria and encapsulates the following features: Keyword based, web-based test-framework, supports python as one of languages and much more.
Additional info on RedwoodHQ: Theoretically its possible, all the existing robot-framework inbuilt libraries and all robot-framework external test-libraries or for that matter any python library, can be called or used from this web based test framework with little modification)
Gauge (Gherkin approach): Reference for python: (https://gauge-python.readthedocs.io/en/latest/index.html)
Underneath Cucumber, one could have Capybara like abstraction layer that hides/ groups many of selenium actions
B. Capybara like: ( Abstraction: hides / groups action)
As one e.g to click an element, its sufficient to provide command like click(locator) instead of working with raw selenium api, where one needs to find an element and then click. Many more such abstraction exist in the optional libraries below
Option-1 (see below)
Option-2 (see below)
Option-3 (see below)
Option-4 (see below)
Option-5 (see below)
Option-6 : Helium (from others Answer/comment)
Option-7 : (see below)
Option-8 : (see below)
Option-9: (see below)
Option-10: (see below)
Option-11: (see below)
Option-12: (see below)
Option-13: (see below)
My research: There exist almost half a dozen a. active, b. mature c.developed options.
python comes with variety of batteries included !!
Option-1: Selenium2Library
Github url: https://github.com/rtomac/robotframework-selenium2library
Developement:
Active
Purpose:
one of the many libraries of robotframework, can also be used as "standalone" library for your framework (Check e.g below for usage).
Thoughts:
It provides an abstraction over selenium
input of arguments to methods in this library are lot simpler. Abstraction provided by library, one e.g, hides many of the unnecessary details for finding elements. For more details one needs to understand the library
It is possible to use this library outside robot-framework context as such without any modification, though it could be using utilities of robot package. (Its your homework to do further experiments with this lib, on this note!)
Therefore, can be used as a standalone library for your framework.
Usage:
pip install robotframework-selenium2library
import in your ipython or idle console and start playing
e.g:
>>from Selenium2Library import Selenium2Library
>>start_testing= Selenium2Library()
>>start_testing.create_webdriver("Firefox")
>>start_testing.go_to("http://www.google.com")
>>.
...so on
Option-2: Pageobjects
Github url:
https://github.com/ncbi/robotframework-pageobjects
Development:
InActive (no show stoppers with latest release)
Purpose:
One of the libraries of robotframework. Provides a page object abstraction over Selenium2Library. Can be used as Standalone for your framework (Check e.g below for usage) or can be used along with robotframework.
Thoughts:
It provides a "pageobject abstraction" support on top of Selenium2Library
It is possible to use this library outside robot-framework context as such without any modification, though it could be using utilities of robot package. (Its your homework to do further experiments on this note!)
Therefore, can be used as a standalone library
Usage:
pip install robotframework-pageobjects
e.g:
in ipython or idle do:
>>from robotpageobjects import Page
>>start_testing=Page()
>>start_testing.create_webdriver("Firefox")
>>start_testing.go_to("http://google.com")
Option-3: robotframework-pageobjectlibrary
Github Url:
https://github.com/boakley/robotframework-pageobjectlibrary
Development:
Active
Hopefully Author supports LTS (Long Term Support) : )) , Fingers crossed !!
Usage:
pip install robotframework-pageobjectlibrary
Thoughts:
It is NOT possible to use this library outside robot-framework context. A minor change to how the page context is handled would help this library to be used outside robot-framework context (Its your homework to find out how!)
Option-4: Splinter
Github url:
https://github.com/cobrateam/splinter
Developement:
Active
Usage:
splinter.readthedocs.org/en/latest/index.html
pip install splinter
On ipython or idle do:
>>from splinter import Browser
>>browser = Browser()
>>browser.visit('http://google.com')
>>browser.fill('q', 'splinter - python acceptance testing for web applications')
>>browser.find_by_name('btnG').click()
Option-5: SST library
Github url:
https://github.com/Work4Labs/selenium-simple-test
Development:
Feature complete / Active
Usage:
testutils.org/sst/
pip install -U sst
on ipython or idle do:
>>> from sst.actions import *
>>> start()
Starting Firefox
>>> go_to('http://google.com')
Going to... http://google.com
Waiting for get_element
Option-6: helium
Not open source (Commercial)
Option-7: holmium.core
Github url:
https://github.com/alisaifee/holmium.core
Option-8: wtframework
Github url:
https://github.com/wiredrive/wtframework
Option-9: webium
Github url:
https://github.com/wgnet/webium
Option-10: elementium
Github url:
https://github.com/actmd/elementium
Option-11: saunter
Github url:
https://github.com/Element-34/py.saunter
Usage:
saunter
Option-12: webdriverplus
Github url:
https://github.com/tomchristie/webdriverplus
Usage:
webdriverplus
Comments:
repository not maintained but decent reference
Option-12: Simple-Pageobject
Github url:
https://github.com/rama-bornfree/simple-pageobject/tree/master/PageObjectLibrary
Comments:
Simplest pageobject wrapper built around selenium2library. I am the owner of the repo
Test-setup:
"All" the Test libraries in Option-1-13; can be run using any of the following framework: Lettuce, Behave, Robotframework or for that matter, any unit test framework(e.g PyUnit, Nose)...so on .
Test Framework is in general used to manage test-cases e.g
English formats like gherkin, keyword, tabular so on ...
reporting a test-run
hooking to CI
set-up/tear-down of test-cases and test-suites
tagging of test-cases
other functionalities that one could think on about any test-framework
What matters is how comfortable one gets with libraries in above options.
Option-5: As far as SST is concerned, it has features of a framework itself, e.g it can generate report and do many more things.
So the definition of library and framework in the case of SST is blurred, depending on the extent of features one would like to use from that package
Some Math for Fun:
Total number of ways one could have a good, bad, and ugly Test-setup = (Test framework AND Test library + your custom code sandwiched b/w the framework and library ):
7 * 13 = 91 Ways
Choose the best combination (of Test Framework And Test library) that suits ones need !!
I would personally go for Robot-framework with Selenium2Library or Robot-framework with some pageobject library
ofcourse, I am leaned and positively biased in my post about robot-framework and Selenium2Library
While the OP was happy with finding a Python Cucumber equivalent, what led me here was the question title: a Python equivalent of Capybara. While Cucumber uses Capybara, Cucumber itself is a whole different "solution" that is only incidentally related to Capybara.
If you're looking for something Capybara-like without having to deal with Cucumber, check out splinter. I don't know what was true when the question was posted, but Splinter is now built on Selenium, and supports other engines as well (Webkit, PhantomJS, zope.browsertest, and others), and supports both visual and headless testing.
How about Robot Framework. It's pretty awesome. And with Selenium2Library it works really well with SE2. http://robotframework.org/
There does now exist a port of Capybara itself to Python:
https://github.com/elliterate/capybara.py
You can find its documentation here:
https://elliterate.github.io/capybara.py/
Capybara helps you test web applications by simulating how a real user would interact with your app. It is agnostic about the driver running your tests and comes with Selenium support built in.
Have you checked freshen, or pea?
Pea does not use the syntax of cucumber, but the author says that is easier
https://github.com/gfxmonk/pea
And Freshen is trying to clone Cucumber's syntax and functionalities
https://github.com/rlisagor/freshen
The OP asked for Python implementations of Cucumber or Capybara but as Jim Stewart pointed out in his answer, Cucumber and Capybara are very different things. Since the title of the question is about Capybara, that's what I will answer.
I am one of the developers of a commercial Selenium wrapper called Helium. Like Capybara, it offers a very high-level API for web automation. For example, here is a script that updates your Facebook status:
from helium.api import *
start_chrome("facebook.com")
write(your_fb_email, into="Email or Phone")
write(your_fb_password, into="Password")
click("Log In")
write("Test", into="Update Status")
click("Post")
Calls to Helium can freely be mixed with calls to Selenium. Eg. we could extend the above script by:
# get_driver() returns the WebDriver created by start_chrome() above.
chrome = get_driver()
chrome.find_element_by_id('btnG').click()

How do I create a web interface to a simple python script?

I am learning python. I have created some scripts that I use to parse various websites that I run daily (as their stats are updated), and look at the output in the Python interpreter. I would like to create a website to display the results. What I want to do is run my script when I go to the site, and display a sortable table of the results.
I have looked at Django and am part way through the tutorial, but it seems like an awful lot of overhead for what should be a simple problem. I know that I could just write a Python script to output simple HTML, but is that really the best way? I would like to be able to sort the table by various columns.
I have years of programming experience (C, Java, etc.), but have very little web development experience.
Thanks in advance.
Have you considered Flask? Like Tornado, it is both a "micro-framework" and a simple web server, so it has everything you need right out of the box. http://flask.pocoo.org/
This example (right off the homepage) pretty much sums up how simple the code can be:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
If you are creating non-interactive pages, you can easily setup any modern web server to execute your python script as a CGI. Instead of loading a static file, your web server will return the output of your python script.
This isn't very sophisticated, but if you are simply returning the output without needing browser submitted date, this is the easiest way (scaling under load is a different story).
You don't even need the "cgi" module from python, if you aren't receiving any data from the browser. Anything more complicated than this and you should use a web framework.
Examples and other methods
Simple Example: hardest part is webserver configuration
mod_python: Cut down on CGI overhead (otherwise, apache execs the python interpreter for each hit)
python module cgi: sending data to your python script from the browser.
Sorting
Javascript side sorting: I've used this javascript library to add sortable tables. This is the easiest way to add sorting without requiring additional work or another HTTP GET.
Instructions:
Download this file
Add to your HTML
Add class="sortable" to any table you'd like to make sortable
Click on the headers to sort
You might consider Tornado if Django is too much overhead. I've used both and agree that, if you have something simple/small to do and don't already know Django, it's going to exponentially increase your time to production. On the other hand, you can 'get' Tornado in a couple of hours and get something relatively simple done in a day or two with no prior experience with it. At least, that's been my experience with it.
Note that Tornado is still a tradeoff: you get a lot of simplicity in exchange for the huge cornucopia of features and shortcuts you get w/ Django.
PS - in addition to being a 'micro-framework', Tornado is also its own web server, so there's no mucking with wsgi/mod-cgi/fcgi.... just write your request handlers and run it. Be sure to see the demos included in the distribution.
Have you seen bottle framework? It is a micro framework and very simple.
If I correctly understood your requirements you might find Wooey very interesting.
Wooey is a A Django app that creates automatic web UIs for Python scripts:
http://wooey.readthedocs.org
Here you can check a demo:
https://wooey.herokuapp.com/
Django is a big webframework, meant to include loads of things becaus eyou often needs them, even though sometimes you don't.
Look at Pyramid, earlier known as BFG. It's much smaller.
http://pypi.python.org/pypi/pyramid/1.0a1
Other microframeworks to check out are here: http://wiki.python.org/moin/WebFrameworks
On the other hand, in this case it's probably also overkill. sounds like you can run the script once every ten minites, and write a static HTML file, and just use Apache.
If you are not willing to write your own tool, there is a pretty advanced tool for executing your scripts: http://rundeck.org/
It's pretty simple to start and can be configured for complex scenarios as well.
For the requirement of custom view (with sortable results), I believe you can implement a simple plugin for translating script output into html elements.
Also, for simple setups I could recommend my own tool: https://github.com/bugy/script-server. It doesn't have tons of features, but very easy for end-users and supports interactive execution.
If you don't need any input from the browser, this sounds like an almost-static webpage that just happens to change once a day. You'll only need some way to get html out of your script, in a place where your webserver can access it.)
So you'd use some form of templating; if you'll need some structure above the single page, there's static site / blog generators that you can feed your output in, say, Markdown format, and call their make html or the like.
You can use DicksonUI https://dicksonui.gitbook.io
DicksonUI is better
Or Remi gui(search in google)
DicksonUI is better.
I am the author of DicksonUI

Categories

Resources