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'
Related
I am trying to create a python script file with multiple functions and pass 3 arguments to the main functions. These parameters are also passed onto other functions with the script. My code looks somewhat like this:
import benepar
import spacy
import json
import gc
import typer
from spacy.tokens import Doc,DocBin
from typing import Tuple, List
from pathlib import Path
def main(nlp_dir: Path,inp_File:Path,out_File:Path):
try:
seg_obj=load_nlp_object(nlp_dir)
print('Loaded nlp obj')
doc_train=DocBin().from_disk(inp_File)
docs=get_list_of_docs(doc_train,nlp_dir)
data=[]
except Exception as e:
print(e)
chunk_count=0
for d in docs:
try:
temp=seg_obj(d)
chunk_count=chunk_count+1
if chunk_count%5 == 0:
seg_obj=load_nlp_object(nlp_dir)
gc.collect()
#Other code
except Exception as e:
print(e)
#Saving linker data
for val in data:
with open(out_File,'a',encoding='utf8') as f:
json.dump(val,f)
f.write(",\n")
print('Data created successfully.')
def load_nlp_object(nlp_dir):
#Code
return nlp
def get_list_of_docs(bin_obj,nl):
n=load_nlp_object(nl)
dcs=list(bin_obj.get_docs(n.vocab))
return dcs
def benepar_split(doc: Doc) -> List[Tuple]:
#Code
return split_indices
if __name__=='__main__':
typer.run(main)
While running I get the following error:
Traceback (most recent call last):
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\Project\create_linker_data.py", line 96, in <module>
typer.run(main)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\typer\main.py", line 864, in run
app()
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\typer\main.py", line 214, in __call__
return get_command(self)(*args, **kwargs)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\click\core.py", line 1128, in __call__
return self.main(*args, **kwargs)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\click\core.py", line 1053, in main
rv = self.invoke(ctx)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\click\core.py", line 1395, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\click\core.py", line 754, in invoke
return __callback(*args, **kwargs)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\typer\main.py", line 500, in wrapper
return callback(**use_params) # type: ignore
TypeError: main() got an unexpected keyword argument 'inp_file'
I have debugged by code but I am unable to find the root cause. My command line command is python create_linker_data.py "Entity Linker\\ner_obj\\" "Named Entity Recognition\\sentiment_data\\3\\3.spacy" "Entity Linker\\data\\entity_linker_3.txt"
I have followed the tutorial from readthedocs: https://channels.readthedocs.io/en/stable/tutorial/index.html
for django channels. Everything worked fine until the last part of the tutorial, about testing.
Here is the test file as well as the traceback.
# chat/tests.py
from channels.testing import ChannelsLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
class ChatTests(ChannelsLiveServerTestCase):
serve_static = True # emulate StaticLiveServerTestCase
#classmethod
def setUpClass(cls):
super().setUpClass()
try:
# NOTE: Requires "chromedriver" binary to be installed in $PATH
cls.driver = webdriver.Chrome()
except:
super().tearDownClass()
raise
#classmethod
def tearDownClass(cls):
cls.driver.quit()
super().tearDownClass()
def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self):
try:
self._enter_chat_room('room_1')
self._open_new_window()
self._enter_chat_room('room_1')
self._switch_to_window(0)
self._post_message('hello')
WebDriverWait(self.driver, 2).until(lambda _:
'hello' in self._chat_log_value,
'Message was not received by window 1 from window 1')
self._switch_to_window(1)
WebDriverWait(self.driver, 2).until(lambda _:
'hello' in self._chat_log_value,
'Message was not received by window 2 from window 1')
finally:
self._close_all_new_windows()
def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self):
try:
self._enter_chat_room('room_1')
self._open_new_window()
self._enter_chat_room('room_2')
self._switch_to_window(0)
self._post_message('hello')
WebDriverWait(self.driver, 2).until(lambda _:
'hello' in self._chat_log_value,
'Message was not received by window 1 from window 1')
self._switch_to_window(1)
self._post_message('world')
WebDriverWait(self.driver, 2).until(lambda _:
'world' in self._chat_log_value,
'Message was not received by window 2 from window 2')
self.assertTrue('hello' not in self._chat_log_value,
'Message was improperly received by window 2 from window 1')
finally:
self._close_all_new_windows()
# === Utility ===
def _enter_chat_room(self, room_name):
self.driver.get(self.live_server_url + '/chat/')
ActionChains(self.driver).send_keys(room_name + '\n').perform()
WebDriverWait(self.driver, 2).until(lambda _:
room_name in self.driver.current_url)
def _open_new_window(self):
self.driver.execute_script('window.open("about:blank", "_blank");')
self.driver.switch_to_window(self.driver.window_handles[-1])
def _close_all_new_windows(self):
while len(self.driver.window_handles) > 1:
self.driver.switch_to_window(self.driver.window_handles[-1])
self.driver.execute_script('window.close();')
if len(self.driver.window_handles) == 1:
self.driver.switch_to_window(self.driver.window_handles[0])
def _switch_to_window(self, window_index):
self.driver.switch_to_window(self.driver.window_handles[window_index])
def _post_message(self, message):
ActionChains(self.driver).send_keys(message + '\n').perform()
#property
def _chat_log_value(self):
return self.driver.find_element_by_css_selector('#chat-log').get_property('value')
PS C:\Users\regis\PycharmProjects\mysite> py manage.py test chat.tests
Found 2 test(s).
Creating test database for alias 'default'...
Destroying old test database for alias 'default'...
System check identified no issues (0 silenced).
DevTools listening on ws://127.0.0.1:8872/devtools/browser/6bb10b6b-1101-4147-8f75-bc0b54800912
EETraceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 107, in spawn_main
new_handle = reduction.duplicate(pipe_handle,
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 79, in duplicate
return _winapi.DuplicateHandle(
OSError: [WinError 6] The handle is invalid
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 109, in spawn_main
fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY)
OSError: [Errno 9] Bad file descriptor
======================================================================
ERROR: test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room (chat.tests.ChatTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\regis\PycharmProjects\mysite\env\lib\site-packages\django\test\testcases.py", line 266, in _setup_and_call
self._pre_setup()
File "C:\Users\regis\PycharmProjects\mysite\env\lib\site-packages\channels\testing\live.py", line 52, in _pre_setup
self._server_process.start()
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 327, in _Popen
return Popen(process_obj)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'convert_exception_to_response.<locals>.inner'
======================================================================
ERROR: test_when_chat_message_posted_then_seen_by_everyone_in_same_room (chat.tests.ChatTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\regis\PycharmProjects\mysite\env\lib\site-packages\django\test\testcases.py", line 266, in _setup_and_call
self._pre_setup()
File "C:\Users\regis\PycharmProjects\mysite\env\lib\site-packages\channels\testing\live.py", line 52, in _pre_setup
self._server_process.start()
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 327, in _Popen
return Popen(process_obj)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'convert_exception_to_response.<locals>.inner'
----------------------------------------------------------------------
Ran 0 tests in 3.753s
FAILED (errors=2)
Destroying test database for alias 'default'...
I am newbie to channels. So far I have only focused on the first error message for the spawn.py file on line 107 but I didn't find out much. Some posts are mentioning forking with multiprocessing not working on Windows but I have no idea what it means.
Thanks for help
I have a program, which starts a tweepy streamListener, which adds new tweets to a database and starts another process which monitors said database for tweets older than X and does something with them.
The code below is structurally similar, just without the database interaction code, as it is not the thing causing my problem.
The problem, from what I understand is, that you can't share python modules that hold some kind of state between the different processes.
How do I work around this? I need both processes to have access to tweepy for twitter interaction.
Any help or ideas are much appreciated!
import multiprocessing
import time
import tweepy
class App():
def __init__(self):
keys = {
"consumer_key": "",
"consumer_secret": "",
"access_token": "",
"access_token_secret": ""
}
auth = tweepy.OAuthHandler(keys['consumer_key'], keys['consumer_secret'])
auth.set_access_token(keys['access_token'], keys['access_token_secret'])
self.api = tweepy.API(auth)
self.worker = Worker(self.api)
def run(self):
self.worker.start()
myStreamListener = MyStreamListener()
stream = tweepy.Stream(auth=self.api.auth, listener=myStreamListener)
stream.filter(track=['python'], async=True)
class Worker(multiprocessing.Process):
def __init__(self, api):
multiprocessing.Process.__init__(self)
self.api = api
def run(self):
# Filler for debugging purposes
print(self.api.me(), flush=True)
time.sleep(1)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
# Filler for debugging purposes
print(status.text, flush=True)
if __name__ == "__main__":
APP = App()
APP.run()
Running this produces the following error
Traceback (most recent call last):
File "[PATH_REMOVED]", line 46, in <module>
APP.run()
File "[PATH_REMOVED]", line 22, in run
self.worker.start()
File "E:\Programs\Python 3.x\lib\multiprocessing\process.py", line 105, in start
self._popen = self._Popen(self)
File "E:\Programs\Python 3.x\lib\multiprocessing\context.py", line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "E:\Programs\Python 3.x\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
File "E:\Programs\Python 3.x\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
reduction.dump(process_obj, to_child)
File "E:\Programs\Python 3.x\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: can't pickle module objects
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "E:\Programs\Python 3.x\lib\multiprocessing\spawn.py", line 99, in spawn_main
new_handle = reduction.steal_handle(parent_pid, pipe_handle)
File "E:\Programs\Python 3.x\lib\multiprocessing\reduction.py", line 87, in steal_handle
_winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE)
PermissionError: [WinError 5] Access is denied
This is the error log:
[I 160308 11:09:59 web:1908] 200 GET /admin/realtime (117.93.180.216) 107.13ms
[E 160308 11:09:59 http1connection:54] Uncaught exception
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/tornado/http1connection.py", line 238, in _read_message
delegate.finish()
File "/usr/local/lib/python3.4/dist-packages/tornado/httpserver.py", line 290, in finish
self.delegate.finish()
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 1984, in finish
self.execute()
File "/usr/local/lib/python3.4/dist-packages/blueware-1.0.10/blueware/hooks/framework_tornado/web.py", line 480, in _bw_wrapper__RequestDispatcher_execute
future = wrapped(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 2004, in execute
**self.handler_kwargs)
File "/usr/local/lib/python3.4/dist-packages/blueware-1.0.10/blueware/hooks/framework_tornado/web.py", line 448, in _bw_wrapper_RequestHandler___init___
return wrapped(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 185, in init
self.initialize(**kwargs)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 2714, in wrapper
self.redirect(url)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 671, in redirect
self.finish()
File "/usr/local/lib/python3.4/dist-packages/blueware-1.0.10/blueware/hooks/framework_tornado/web.py", line 309, in _bw_wrapper_RequestHandler_finish_
return wrapped(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 934, in finish
self.flush(include_footers=True)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 870, in flush
for transform in self._transforms:
TypeError: 'NoneType' object is not iterable
[I 160308 11:10:00 web:1908] 200 GET /admin/order?order_type=1&order_status=1&page=0&action=allreal (49.89.27.173) 134.53ms
Can anyone tell me how to solve this problem? Thank you very much
I assume that OneAPM (blueware agent) is compatible with your python and Tornado version, however it's can be tricky.
Solution
Move self.redirect(url) from your handler initialize method to get method, like this
class MyHandler(tornado.web.RequestHandler):
def get(self):
self.redirect('/some_url')
or use RedirectHandler.
Every action that could finish request needs to be called in context of http-verb method (get, post, put and so on). The common mistake is making authetication/authorization in __init__ or initialize.
More detail
In Tornado's source there is a note about _transforms that is initialized in the constructor with None and set in_execute (oversimplifying - after headers_received).
A transform modifies the result of an HTTP request (e.g., GZip encoding).
Applications are not expected to create their own OutputTransforms
or interact with them directly; the framework chooses which transforms
(if any) to apply.
Reproduce
Sample that triggers this error. I'm including this only as a cross-check that blueware is not the cause:
import tornado.ioloop
import tornado.web
class SomeHandler(tornado.web.RequestHandler):
def initialize(self, *args, **kwargs):
url = '/some'
self.redirect(url)
# ^ this is wrong
def get(self):
# redirect should be here
self.write("Hello")
def make_app():
return tornado.web.Application([
(r"/", SomeHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
And stacktrace:
ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
File "/tmp/py3/lib/python3.4/site-packages/tornado/http1connection.py", line 238, in _read_message
delegate.finish()
File "/tmp/py3/lib/python3.4/site-packages/tornado/httpserver.py", line 289, in finish
self.delegate.finish()
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 2022, in finish
self.execute()
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 2042, in execute
**self.handler_kwargs)
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 183, in __init__
self.initialize(**kwargs)
File "test.py", line 8, in initialize
self.redirect(url)
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 666, in redirect
self.finish()
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 932, in finish
self.flush(include_footers=True)
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 868, in flush
for transform in self._transforms:
TypeError: 'NoneType' object is not iterable
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)