I am following the book TDD with Python. In chapter 1 there is a piece of code
from selenium import webdriver
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(5)
def tearDown(self):
self.browser.quit()
def test_can_start_a_list_and_retrieve_it_later(self):
self.browser.get('http://localhost:8000')
self.assertIn('To-Do', self.browser.title)
self.fail('Finish the test!')
if __name__ == '__main__':
unittest.main(warnings='ignore')
The file is called functional_tests.py. I have django 1.7 and selenium installed globally on Ubuntu 14.04. I also started fresh project superlists. I run the server before I try the tests. When I run the test with
python3 functional_tests.py
Firefox window opens up and loads the default Django startup page and the window stays open even though it should close after the test runs. Also there is no output from the tests at all. I was expecting something like this:
F
======================================================================
FAIL: test_can_start_a_list_and_retrieve_it_later (__main__.NewVisitorTest)
---------------------------------------------------------------------
Traceback (most recent call last):
File "functional_tests.py", line 18, in
test_can_start_a_list_and_retrieve_it_later
self.assertIn('To-Do', self.browser.title)
AssertionError: 'To-Do' not found in 'Welcome to Django'
---------------------------------------------------------------------
Ran 1 test in 1.747s
FAILED (failures=1)
What could be the problem? Thanks
Have you installed recent version of Selenium? As mentioned in the book, you should have matching version of Firefox and Selenium.
Related
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)
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.
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.
Following the test driven development with python book I got stuck
I have tried several different imports but still nothing.. anyone?
Error
$python manage.py test functional_tests
ERROR: test_can_start_a_list_and_retrieve_it_later (functional_tests.tests.NewVisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/coelhao/DjangoProjects/superlists/functional_tests/tests.py", line 45, in
test_can_start_a_list_and_retrieve_it_later
self.assertRegex(edith_list_url, '/lists/.+') AttributeError: 'NewVisitorTest' object has no attribute 'assertRegex'
Code
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest
class NewVisitorTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_can_start_a_list_and_retrieve_it_later(self):
# .....
# When she hits enter, the page updates, and now the page lists
# "1: Buy peacock feathers" as an item in a to-do list table
inputbox.send_keys(Keys.ENTER)
edith_list_url = self.browser.current_url
self.assertRegex(edith_list_url, '/lists/.+')
self.check_for_row_in_list_table('1: Buy peacock feathers')
# ....
I'm assuming you are on Python 2 - then use assertRegexpMatches instead of assertRegex.
assertRegex was introduced in Python 3:
Changed in version 3.2: The method assertRegexpMatches() has been
renamed to assertRegex().
There is no such assertion as assertRegex - perhaps you mean assertRegexMatches?
The unittest docs are here: http://docs.python.org/2.7/library/unittest.html#unittest.TestCase
I am totally new to functional testing with using Python WebTest, please bear with me
I was looking at https://webtest.readthedocs.org/en/latest/webtest.html, so I tried out the code as suggested to make a request:
app.get('/path', [params], [headers], [extra_environ], ...)
Ok, looks simple enough to me. I create a file called test_demo.py in myapp folder:
from webtest import TestApp
class MyTests():
def test_admin_login(self):
resp = self.TestApp.get('/admin')
print (resp.request)
Now this is where I am stuck with, how should I run this test_demo.py?
I've tried typing in bash
$ bin/python MyCart/mycart/test_demo.py test_admin_login
But it isn't showing any result.
I bet I got something all wrong, but the docs isn't helping much or I'm just plain slow.
Whoops, you're missing a few steps.
Your program doesn't do anything because you didn't tell it to do anything, you just defined a class. So let's tell it to do something. We'll use the unittest package to make things a bit more automated.
import unittest
from webtest import TestApp
class MyTests(unittest.TestCase):
def test_admin_login(self):
resp = self.TestApp.get('/admin')
print (resp.request)
if __name__ == '__main__':
unittest.main()
Run that, and we see:
E
======================================================================
ERROR: test_admin_login (__main__.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_foo.py", line 6, in test_admin_login
resp = self.TestApp.get('/admin')
AttributeError: 'MyTests' object has no attribute 'TestApp'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Ok, so we need an app to test. Where to get one? You would typically want the WSGI app that you are creating in your main via config.make_wsgi_app(). The easiest way is to load it up, just like pserve development.ini does when you run your app. We can do this via pyramid.paster.get_app().
import unittest
from pyramid.paster import get_app
from webtest import TestApp
class MyTests(unittest.TestCase):
def test_admin_login(self):
app = get_app('testing.ini')
test_app = TestApp(app)
resp = test_app.get('/admin')
self.assertEqual(resp.status_code, 200)
if __name__ == '__main__':
unittest.main()
Now all that's needed is an INI file similar to your development.ini, but for testing purposes. You can just copy development.ini until you need to set any settings just for testing.
Hopefully that gives you a starting point to learn more about the unittest package.