I have a functional test 'y1.py' which I am trying to call from within a python/django function. Inside the calling function I have:
import unittest
import ft1.y1
unittest.main(module=ft1.y1.py)
y1.py:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re
class Y1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.yahoo.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_y1(self):
driver = self.driver
driver.get(self.base_url)
driver.find_element_by_link_text("Weather").click()
driver.save_screenshot('out11.png')
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
Exception Type: AttributeError at /runtest/
Exception Value: 'module' object has no attribute 'runserver'
How can I fix this?
edit:
I tried:
unittest.main(module=ft1.y1, argv=[])
and got:
Traceback:
File "F:\envs\r1\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\envs\r1\driver1\driver\views.py" in runtest
31. unittest.main(module=ft1.y1, argv=[])
File "f:\ppython275\App\Lib\unittest\main.py" in __init__
93. self.progName = os.path.basename(argv[0])
Exception Type: IndexError at /runtest/
Exception Value: list index out of range
edit 2:
I'm confused it says test OK , but there is an error:
A server error occurred. Please contact the administrator.
Validating models...
0 errors found
January 31, 2014 - 14:42:50
Django version 1.6.1, using settings 'driver1.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
.
----------------------------------------------------------------------
Ran 1 test in 6.286s
OK
Traceback (most recent call last):
File "f:\ppython275\App\Lib\wsgiref\handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "F:\envs\r1\lib\site-packages\django\contrib\staticfiles\handlers.py", line 67, in __call__
return self.application(environ, start_response)
File "F:\envs\r1\lib\site-packages\dj_static.py", line 59, in __call__
return self.application(environ, start_response)
File "F:\envs\r1\lib\site-packages\django\core\handlers\wsgi.py", line 206, in __call__
response = self.get_response(request)
File "F:\envs\r1\lib\site-packages\django\core\handlers\base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\envs\r1\driver1\driver\views.py", line 32, in runtest
unittest.main(module=ft1.y1, argv=sys.argv[:1])
File "f:\ppython275\App\Lib\unittest\main.py", line 95, in __init__
self.runTests()
File "f:\ppython275\App\Lib\unittest\main.py", line 234, in runTests
sys.exit(not self.result.wasSuccessful())
SystemExit: False
[31/Jan/2014 14:43:03] "GET /runtest/ HTTP/1.1" 500 59
Are you trying to run unitest and selenium from a view? You should consider launching a second process for that. This gives you better separation between your django modules and tested modules. If you insist on using unittest.main(), pass the argv and exit params.
import sys
unittest.main(module=ft.gtest, argv=sys.argv[:1], exit=False)
See also:
TextTestRunner
Ghost.py
Celery
(Edited)
Related
I am trying to run this basic test case with selenium but I keep getting an AttributeError and I am not really sure on what to do.
import unittest
from selenium import webdriver
class PythonOrgSearch(unittest.TestCase):
def setup(self):
self.driver = webdriver.Chrome("C:\Program Files (x86)\chromdriver.exe")
self.driver.get("http://www.python.org")
def test_example(self):
print("test")
assert True
def not_a_test(self):
print('this wont print')
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
I keep getting this error:
ERROR: test_example (__main__.PythonOrgSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\jbene\OneDrive\Documents\Selenium\testcases\main.py", line 26, in tearDown
self.driver.close()
AttributeError: 'PythonOrgSearch' object has no attribute 'driver'
I tried adding an init fucntion to see if it would fix the problem and it did, but then I end up getting a different AttributeError which is the reason why I am stuck.
import unittest
from selenium import webdriver
class PythonOrgSearch(unittest.TestCase):
def __init__(self, driver = None):
if driver is not None:
self.driver = driver
else:
self.setup()
def setup(self):
self.driver = webdriver.Chrome("C:\Program Files (x86)\chromdriver.exe")
self.driver.get("http://www.python.org")
def test_example(self):
print("test")
assert True
def not_a_test(self):
print('this wont print')
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
this is the error i get
Traceback (most recent call last):
File "C:\Users\jbene\OneDrive\Documents\Selenium\testcases\main.py", line 29, in <module>
unittest.main()
File "C:\Python310\lib\unittest\main.py", line 101, in __init__
self.runTests()
File "C:\Python310\lib\unittest\main.py", line 271, in runTests
self.result = testRunner.run(self.test)
File "C:\Python310\lib\unittest\runner.py", line 184, in run
test(result)
File "C:\Python310\lib\unittest\suite.py", line 84, in __call__
return self.run(*args, **kwds)
File "C:\Python310\lib\unittest\suite.py", line 122, in run
test(result)
File "C:\Python310\lib\unittest\suite.py", line 84, in __call__
return self.run(*args, **kwds)
File "C:\Python310\lib\unittest\suite.py", line 122, in run
test(result)
File "C:\Python310\lib\unittest\case.py", line 650, in __call__
return self.run(*args, **kwds)
File "C:\Python310\lib\unittest\case.py", line 569, in run
testMethod = getattr(self, self._testMethodName)
AttributeError: 'PythonOrgSearch' object has no attribute '_testMethodName'
I am trying to create Django middleware that logs specific information about exceptions that are raised from within views. I am having trouble getting the line number on which the exception was raised.
Specifically, the end of the traceback shows File "<string>", line None. Where is this "<string>" coming from, and why does it show line number None? I get this same result whether I navigate to /view_raises_exception/ through my tests or through a browser window. I'm sure I could probably dig through the traceback in my process_exception() method to get the line number, but I'm wondering why exception.lineno isn't giving me the result I expect.
My setup:
Ubuntu 14.04.3 LTS (Cloud9)
Python 3.4.3
Django 1.9
View:
def exception_view(request):
raise SyntaxError('Custom error message...')
Urls:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^view_raises_exception/', views.exception_view),
url(r'^view_raises_no_exceptions/', views.no_exception_view),
]
Middleware file:
from django.http import HttpResponse
class ExceptionLoggingMiddleware(object):
def process_exception(self, request, exception):
name = type(exception).__name__
message = str(exception)
line_no = exception.lineno
print('***INSIDE PROCESS_EXCEPTIONS***')
print('Name:', name)
print('Message:', message)
print('Line Number:', line_no)
# return HttpResponse('Exception handled.')
Server log:
System check identified no issues (0 silenced).
September 09, 2016 - 22:58:40
Django version 1.9, using settings 'middlewares_library.settings'
Starting development server at http://0.0.0.0:8080/
Quit the server with CONTROL-C.
***INSIDE PROCESS_EXCEPTIONS***
Name: SyntaxError
Message: Custom error message...
Line Number: None
Internal Server Error: /view_raises_exception/
Traceback (most recent call last):
File "/home/ubuntu/.virtualenvs/env3/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ubuntu/.virtualenvs/env3/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/workspace/middlewares_library/library/views.py", line 6, in exception_view
raise SyntaxError('Custom error message...')
File "<string>", line None
SyntaxError: Custom error message...
[09/Sep/2016 22:58:43] "GET /view_raises_exception/ HTTP/1.1" 500 68472
Thanks in advance!
I am starting to learn how to become a better test driven developer when creating web applications in Django. I am trying to use Selenium to open a browser, but I am getting an error.
selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /var/folders/xn/bvyw0fm97j1_flsyggj0xn9r0000gp/T/tmptoxt890d If you specified a log_file in the FirefoxBinary constructor, check it for details.
I read that by "Installing the FF extension "Disable Add-on Compatibility Checks" skips this and everything is fine." selenium.common.exceptions.WebDriverException: Message: Can't load the profile. I did this, but It is still not working. I used Python2.7 and Python3.5 with Selenium version 2.53.6.
Python file
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import unittest
caps = DesiredCapabilities.FIREFOX
caps["marionette"] = True
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox(capabilities=caps)
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)
if __name__ == '__main__':
unittest.main(warnings='ignore')
Stack Trace
Creating test database for alias 'default'...
EException ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x103f652b0>>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 151, in __del__
self.stop()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 123, in stop
if self.process is None:
AttributeError: 'Service' object has no attribute 'process'
======================================================================
ERROR: test_can_start_a_list_and_retrieve_it_later (functional_tests.NewVisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/timothybaney/Treehouse/TDD/superlists/functional_tests.py", line 13, in setUp
self.browser = webdriver.Firefox(capabilities=caps)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 82, in __init__
self.service.start()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 62, in start
stdout=self.log_file, stderr=self.log_file)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
NotADirectoryError: [Errno 20] Not a directory
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
Destroying test database for alias 'default'...
That error is because you are using FF 48. For FF>=47 FirefoxDriver stop working. You must use the new MarionetteDriver
Set up this:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
caps["marionette"] = True
browser = webdriver.Firefox(capabilities=caps)
browser.get('http://localhost:8000')
assert 'Django' in browser.title
I'm trying to run some tests for my Django-Rest-Framework API but am stuck on an error. When I run the following tests, I get the following errors.
Traceback (most recent call last):
File "C:\Users\Bill\SD\DjangoApps\vidapp\startapp\tests.py", line 21, in test_get_user
response = self.client.get('/user/1/')
File "C:\Anaconda\lib\site-packages\django\test\client.py", line 473, in get
response = super(Client, self).get(path, data=data, **extra)
File "C:\Anaconda\lib\site-packages\django\test\client.py", line 280, in get
return self.request(**r)
File "C:\Anaconda\lib\site-packages\rest_framework\test.py", line 143, in request
return super(APIClient, self).request(**kwargs)
File "C:\Anaconda\lib\site-packages\rest_framework\test.py", line 95, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "C:\Anaconda\lib\site-packages\django\test\client.py", line 444, in request
six.reraise(*exc_info)
File "C:\Anaconda\lib\site-packages\django\core\handlers\base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes exactly 1 argument (2 given)
Test Cases:
class UserTestCase(APITestCase):
def setUp(self):
helper.reset_test_db()
def test_get_user(self):
response = self.client.get('/user/1/')
print response.content
self.assertEqual(response.data, {'fname':'Generic','lname':'Name','token':'token1'})
URL Config:
url(r'^user/new/$', 'startapp.views.new_user'),
url(r'^user/1/$', 'startapp.views.get_1'),
Views:
class get_1(APIView):
def get(self, request):
user = db_models.User.objects.get(pk=1)
if(user is not None):
serial_user = serial.UserSerializer(user)
return Response(serial_user.data)
else:
return Response(status.HTTP_404_NOT_FOUND)
I know the view itself works because I tested that separately. The data is definitely present since helper.reset_test_db() puts it there (I know I should be using fixtures but this is for testing so I went with the simple route). The same error occurs for POST and other commands or when I use Django's TestCase instead of APITestCase. While this is my first time using Django's TestCase, I read both the Django and Django rest documents but can't seem to figure out this issue.
The view in your case is a class-based view.
So you have to add it to the urlconfig with as_view:
url(r'^user/1/$', startapp.views.get_1.as_view()),
I've got a problem... we're writing project using django, and i'm trying to use django.test.client with nose test-framework for tests.
Our code is like this:
from simplejson import loads
from urlparse import urljoin
from django.test.client import Client
TEST_URL = "http://smakly.localhost:9090/"
def test_register():
cln = Client()
ref_data = {"email": "unique#mail.com", "name": "Василий", "website": "http://hot.bear.com", "xhr": "true"}
print urljoin(TEST_URL, "/accounts/register/")
response = loads(cln.post(urljoin(TEST_URL, "/accounts/register/"), ref_data))
print response["message"]
and in nose output I catch:
Traceback (most recent call last):
File "/home/psih/work/svn/smakly/eggs/nose-0.11.1-py2.6.egg/nose/case.py", line 183, in runTest
self.test(*self.arg)
File "/home/psih/work/svn/smakly/src/smakly.tests/smakly/tests/frontend/test_profile.py", line 25, in test_register
response = loads(cln.post(urljoin(TEST_URL, "/accounts/register/"), ref_data))
File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 313, in post
response = self.request(**r)
File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 225, in request
response = self.handler(environ)
File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 69, in __call__
response = self.get_response(request)
File "/home/psih/work/svn/smakly/parts/django/django/core/handlers/base.py", line 78, in get_response
urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
File "/home/psih/work/svn/smakly/parts/django/django/utils/functional.py", line 273, in __getattr__
return getattr(self._wrapped, name)
AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'
My settings.py file does have this attribute.
If I get the data from the server with standard urllib2.urllopen().read() it works in the proper way.
Any ideas how I can solve this case?
Probably want django-nose if you want to use nose.
http://github.com/jbalogh/django-nose
I would recommend using the TestCase class
http://docs.djangoproject.com/en/dev/topics/testing/
http://www.djangoproject.com/documentation/models/test_client/
Shameless self-promotion: exactly for those reasons I made test library that enables you to test application with urllib2.
Docs are there: http://readthedocs.org/docs/django-sane-testing/en/latest/
Example of what You might want to do is, for example, in django-http-digest-tests