Python-Selenium-Webdriver - python

I have a little issue with webdriver.My machine run windows 7 and successfuly install python and selenium webdriver.Here is the problem
When i run this file
from selenium import webdriver
import HTMLTestRunner
import unittest
class nexmo(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.get("http://wwww.facebook.com")
def test_login(self):
emailFieldId = "email"
el = self.driver.find_element_by_id(emailFieldId)
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
The test give me
Ran 0
OK But the Firefox doesnt start and do the things i tell him.
When I run
from selenium import webdriver
self.driver = webdriver.Firefox()
self.driver.get("http://wwww.facebook.com")
emailFieldId = "email"
el = self.driver.find_element_by_id(emailFieldId)
self.driver.quit()
Everything is OK.The browser starts and find the element.

I took your code and copy/pasted it into my Eclipse and it ran fine.
By chance did you re-type this code into SO rather than copy paste? Is it possible that there is a typo in your "def test_login(self):" line such that unittest can't identify it as a test case? This is my best guess. Since unittest first checks to see if you have any unit tests (identified as a function with the pre-fix "test_". If and only if it finds a test case will it run setUp and tearDown.
Also, the point of unit testing is to actually test that you received a valid value. Can I recommend adding this to the end of "def test_login":
self.assertIsNotNone(el)

Related

Even after executing the code successfully pytest says empty suite and is not printing the print statements

I am trying to run one method from a different module in pytest using import. It runs correctly but in the report it says empty suite. Its not printing the print statements.
roboForm.py -
import unittest
from selenium import webdriver
from selenium.webdriver.support.select import Select
class Roboform(unittest.TestCase):
def setUp(self):
# create a new Chrome session
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(10)
self.driver.maximize_window()
self.driver.get("https://www.roboform.com/filling-tests")
def click_Custom_Form(self):
# get the xpath of the link and page
title = self.driver.title
assert title== "RoboForm Form Filling Tests"
print("We are on the right page")
#click on custom form link
self.custom_form = self.driver.find_element_by_xpath("//*[contains(text(),'Custom')]").click()
def close_browser(self):
self.driver.quit()
I am running the below code in pytest - test_classB.py
import self as self
from roboForm import Roboform
class Test():
Roboform.setUp(self)
print ("Browser and page launched from RoboForm")
self.driver.find_element_by_xpath("//*[contains(text(),'Custom')]").click()
print ("Test Passed")
Roboform.close_browser(self)
Getting the below error :
======================== no tests ran in 11.53 seconds ========================
Process finished with exit code 0
Empty suite
Empty suite
Agreed with #Corey Goldberg.
Try
def test_click_Custom_Form(self):
instead
def click_Custom_Form(self):

How to pass an url as argument through commandline to run selenium python test cases

Is there any proper way to using getting url in cmd as argument along testcases.py file?
I am running below commmand in cmd to run test cases of python file:
testcases.py "any url"
testcases.py have coding:
class JSAlertCheck(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome("E:\chromedriver.exe")
self.url = sys.argv[1]
def test_Case1(self):
driver = self.driver
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main(sys.argv[1])
As per the discussion Python unittest passing arguments the Python Pundits seems to convey that:
Unit tests should be stand-alone which will have no dependencies outside of their setUp() and tearDown() methods. This is to make sure that each tests has minimal side-effects and reactions to the other test. Passing in a parameter defeats this property of unittest and thus makes them sort of invalid. Using a Test Configuration would have been the easiest way and more appropiate as a unittest should never rely on foreign data to perform the test.
If you still want to do so, here is one of the working solution:
Code Block:
from selenium import webdriver
import unittest
import sys
class MyTest(unittest.TestCase):
URL = "foo"
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver = self.driver
driver.get(self.URL)
def test_Case1(self):
driver = self.driver
print(driver.title)
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
if len(sys.argv) > 1:
MyTest.URL = sys.argv.pop()
unittest.main()
CLI Command:
python unittest_cmdline_urlASarguments.py http://www.python.org
Output:
C:\Users\AtechM_03\LearnAutmation\PythonProject\readthedocs>python unittest_cmdline_urlASarguments.py http://www.python.org
[4448:5632:0606/205445.017:ERROR:install_util.cc(589)] Unable to create registry key HKLM\SOFTWARE\Policies\Google\Chrome for reading result=2
DevTools listening on ws://127.0.0.1:5634/devtools/browser/40cc6c16-1e52-4f49-a54f-08fac3ff7abc
Welcome to Python.org
.
----------------------------------------------------------------------
Ran 1 test in 9.534s
OK
C:\Users\AtechM_03\LearnAutmation\PythonProject\readthedocs>
Commandline Snapshot:

Trouble getting python selenium tests to run

I am creating an automation framework from scratch using selenium with python and would really like some input and advice on the best way to do so.
So far I have the following but my test script will not run. Please help!
script.py
from selenium import webdriver
class WebDriver(object):
def __init__(self, driver=None):
"""
__init__ setup webdriver test script class
"""
self.driver = driver
def setup(self):
self.driver = webdriver.Chrome()
def teardown(self):
self.driver.quit()
test.py
import script
class Test(script.WebDriver):
def search(self):
self.driver.get("www.google.com")
self.driver.find_element_by_id("lst-ib").clear()
I'm assuming you are trying to run this with python unittest. If so, your class should inherit from unittest.TestCase in order to mark that it contains test cases:
class WebDriver(unittest.TestCase)
...
class Test(script.WebDriver)
And second missing piece is "boiler plate code to run the test suite" (see explanation here) in test.py:
if __name__ == "__main__":
test.main()

Django: Second Selenium Test Failing with 500 Server Error

I am trying to add some selenium tests to my Django project, but the second test always fails with a Server Error (500) . Since both tests start exactly the same, I figure it must have something to do with the setUp and tearDown methods. Can someone help? Thanks.
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.contrib.auth.models import User
from selenium.webdriver.support.ui import Select
class UserTest(LiveServerTestCase):
def setUp(self):
User.objects.create_user(username='user', password='pass', email='test#test.com')
self.browser = webdriver.Chrome()
def tearDown(self):
self.browser.quit()
def changeSelector(self, browser, value):
mealSelector = Select(browser.find_element_by_id('mealsToday'))
mealSelector.select_by_visible_text(str(value))
def login_user(self):
self.browser.get(self.live_server_url)
self.timeout(5)
self.assertIn('Animals', self.browser.title)
# Log in
login_button = self.browser.find_element_by_id('login').click()
self.browser.find_element_by_id('id_username').send_keys('user')
self.browser.find_element_by_id('id_password').send_keys('pass')
def timeout(self, time_to_sleep):
import time
time.sleep(time_to_sleep)
def test_one_test(self):
self.login_user()
def test_two_test(self):
self.login_user()
Edit: I should mention that the first test works fine and returns success. Any test after the first one fails right on starting up with the 500 error.
Edit 2: What I see when I run my tests:
======================================================================
FAIL: test_two_test (functional_tests.tests.UserTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/functional_tests/tests.py", line 34, in test_two_test
self.login_user()
File "/functional_tests/tests.py", line 20, in login_user
self.assertIn('Animals', self.browser.title)
AssertionError: 'Animals' not found in 'http://localhost:8081/'
Even this minimal code fails:
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.contrib.auth.models import User
from selenium.webdriver.support.ui import Select
class UserTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Chrome()
def tearDown(self):
self.browser.quit()
def login_user(self):
self.browser.get(self.live_server_url)
self.assertIn('Animals', self.browser.title)
def test_one_test(self):
self.login_user()
def test_two_test(self):
self.login_user()
The second time the get is called in the second method I can see that the 500 Error is there and that nothing is correctly loaded. Why would this be?
After some code to be able to show me errors (the testing suite sets DEBUG=False to closer simulate the real env) by setting DEBUG=True
Then I saw that the code was bombing because a row wasn't there that the system expected. This is because I add this row in a migration script. This passes the first test because all migration scripts are run at the beginning of testing, but after all data is deleted after the first test, it is never added again.
It's difficult to say without seeing the complete traceback, but, it could be because of the create_user() call - it fails to create a user with an existing username. Try moving the create_user() under the setUpClass():
class UserTest(LiveServerTestCase):
#classmethod
def setUpClass(cls):
User.objects.create_user(username='user', password='pass', email='test#test.com')
super(UserTest, cls).setUpClass()
def setUp(self):
self.browser = webdriver.Chrome()
Maybe, it will be useful for somebody.
I have problems with testing with Selenium using LiveServerTestCase, Debug was True, all about last answers were about was OK.
But, earlier I tried to deploy my web-application on Heroku, and I have such line of code in my settings.py:
django_heroku.settings(locals())
But when I removed it, I didn't catch this error.

selenium test not opening a browser django

I am trying to run a selenium test and this seems nothing happening. I tested the following code to make sure the setting was working: the firefox browser loaded as it is expected.
In functional_tests.py
browser = webdriver.Firefox()
broswer.get('http://localhost:8000')
But when I changed it to as follows:
import unittest
from selenium import webdriver
class NewVistorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
self.browser.quit()
def test_can_open_browser(self):
self.browser.get('http://localhost:8000')
self.assertIn('Test', self.browser.title)
It was not opening the browser, nothing was happening. I ran this python functional_tests.py
What is the best way to organize unit tests and selenium tests. I'd like to run it by module name, not all in tests.py or test_abc.py, not by nose.
How do you expect it to run? Python won't automatically run tests, just because they're in a class. You need to add a couple more lines to the end of your file:
class NewVistorTest(unittest.TestCase):
...
if __name__ == '__main__':
unittest.main(warnings='ignore')
This conditional is how a Python script checks if it has been executed from the command line, rather than just imported by another script. We call unittest.main() to launch the unittest test runner, which will automatically find test and methods in the file and run them.
Without that block, as you've seen, nothing happens.

Categories