selenium test not opening a browser django - python

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.

Related

Python Selenium test does not run when using absolute path to Firefox geckodriver

I am trying to run Selenium test in Python on Linux Ubuntu environment.
Geckodriver is located in my project root folder.
I run the file named siteTest.py from PyCharm command line:
python3 siteTest.py
However, I do not see any output from Selenium.
The test worked before I divided it into setUp, test and tearDown and added self as a parameter.
Any suggestions what I am doing wrong?
Thanks in advance.
import os
import unittest
from selenium import webdriver
class siteTest:
def setUp(self):
ROOT_DIR = os.path.abspath(os.curdir)
self.driver = webdriver.Firefox(executable_path=ROOT_DIR + '/geckodriver')
def test(self):
driver = self.driver
driver.get('https://google.com/')
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()
Your program was near perfect. You just need to annotate the siteTest class as unittest.TestCase. So effectively, you need to rewrite the line:
class siteTest:
as:
class siteTest(unittest.TestCase):
You probably need to annotate your set up and tear down methods.
#classmethod
def setUp(self)
.
.
#classmethod
def tearDown(self)
.
.
Here, I have annotated as class method so it will run only once for the class.

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()

Python-Selenium-Webdriver

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)

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.

Closing the webdriver instance automatically after the test failed

My English is very poor but I'll try my best to describe the problem I encountered.
I used selenium webdriver to test a web site and the language that I used to write my script is python.Because of this,I used Pyunit.
I know that if my test suite have no exceptions,the webdriver instance will be closed correctly,(by the way, I used chrome) however,once a exception was threw,the script will be shut down and I have to close chrome manually.
I wonder that how can I achieved that when a python process quits , any remaining open WebDriver instances will also be closed.
By the way, I used Page Object Design Pattern,and the code below is a part of my script:
class personalcenter(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.page = personalCenter(self.driver,"admin","123456")
def testAddWorkExp(self):
blahblahblah...
def tearDown(self):
self.page.quit()
self.driver.quit()
if __name__ == "__main__":
unittest.main()
I haved searched the solution of this problem for a long time ,but almost every answer is depended on java and junit or testNG.How can I deal with this issue with Pyunit?
Thanks for every answer.
From the tearDown() documentation:
Method called immediately after the test method has been called and
the result recorded. This is called even if the test method raised an
exception, so the implementation in subclasses may need to be
particularly careful about checking internal state. Any exception
raised by this method will be considered an error rather than a test
failure. This method will only be called if the setUp() succeeds,
regardless of the outcome of the test method. The default
implementation does nothing.
So, the only case where tearDown will not be called is when setUp fails.
Therefore I would simply catch the exception inside setUp, close the driver, and re-raise it:
def setUp(self):
self.driver = webdriver.Chrome()
try:
self.page = personalCenter(self.driver,"admin","123456")
except Exception:
self.driver.quit()
raise
Hope!! this will help you. you might need to close the driver with boolean expression as False
from selenium import webdriver
import time
class Firefoxweb(object):
def __init__(self):
print("this is to run the test")
def seltest(self):
driver=webdriver.Chrome(executable_path="C:\\Users\Admin\PycharmProjects\Drivers\chromedriver.exe")
driver.get("URL")
driver.find_element_by_xpath("//*[#id='btnSkip']").click()
driver.find_element_by_xpath("//*[#id='userInput']").send_keys("ABC")
driver.find_element_by_xpath("//*[#id='passwordInput']").send_keys("*******")
driver.find_element_by_xpath("//*[#id='BtnLogin']").click()
driver.close(False)
FF=Firefoxweb()
FF.seltest()

Categories