Django channels tests fails - python

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

Related

AttributeError: 'PythonOrgSearch' object has no attribute '_testMethodName'

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'

How to get name of the browser for using with pywinauto?

I'm trying use pywinauto to start browser, Chrome or FireFox. But I can`t find the name of application:
from pywinauto.application import Application
if self.browser == "chrome":
app = Application(backend="uia").start ("C:\Program Files\Google\Chrome\Application\chrome.exe --force-renderer-accessibility")
time.sleep(10)
app["Кто использует Chrome?"].print_control_identifiers()
I use inspcet.exe to get elements name:
inspect.exe data:
Name: "Кто использует Chrome?" (cyrylic/russian name)
ControlType: UIA_PaneControlTypeId (0xC371)
LocalizedControlType: "панель"
BoundingRectangle: {l:388 t:141 r:1428 b:938}
IsEnabled: true
ProcessId: 61944
RuntimeId: [2A.3206BA]
FrameworkId: "Win32"
ClassName: "Chrome_WidgetWin_1"
...
The window is open normally - it's the Chrome pane for chooosing user-profile.
But error:
Traceback (most recent call last):
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\application.py", line 258, in __resolve_control
criteria)
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/shulya403/Shulya403_works/all_gid_2/Scraper/ya_scrape_experiment1.py", line 346, in <module>
CromeWindwow = WinChrome(browser="chrome")
File "C:/Users/shulya403/Shulya403_works/all_gid_2/Scraper/ya_scrape_experiment1.py", line 333, in __init__
app[r"Кто использует Chrome?"].print_control_identifiers()
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\application.py", line 613, in print_control_identifiers
this_ctrl = self.__resolve_control(self.criteria)[-1]
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\application.py", line 261, in __resolve_control
raise e.original_exception
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
func_val = func(*args, **kwargs)
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\application.py", line 203, in __get_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\findwindows.py", line 87, in find_element
raise ElementNotFoundError(kwargs)
pywinauto.findwindows.ElementNotFoundError: {'best_match': 'Кто использует Chrome?', 'backend': 'uia', 'process': 65412}
One time it has no timeout, and it show English alternative of names [u'Кто использует Chrome?', 'Pane', '...']
variant:
app.Pane.print_control_identifiers()
worked one time only. But next run returned to the error.
I try with FireFox window too, with same result.

How to handle errors: Pyntc ssh to network device

I am new to network automation, and trying to use pyntc to ssh to the device. I am not sure how to write the code correctly to handle the ssh timeout or authentication error, etc.
My code is as below:
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios$
try:
DEVICE.open()
except Exception:
print('Error')
continue
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
I manually turned off this device, and then I found python code was quit:
root#Network-Automation:~/Pyntc# python3 pyntc_error_handling.py
Backing up ESW1
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 884, in establish_connection
self.remote_conn_pre.connect(**ssh_connect_params)
File "/usr/local/lib/python3.5/dist-packages/paramiko/client.py", line 368, in connect
raise NoValidConnectionsError(errors)
paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 192.168.122.72
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pyntc_error_handling.py", line 8, in <module>
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios_ssh')
File "/usr/local/lib/python3.5/dist-packages/pyntc/__init__.py", line 38, in ntc_device
return device_class(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 42, in __init__
self.open()
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 300, in open
verbose=False,
File "/usr/local/lib/python3.5/dist-packages/netmiko/ssh_dispatcher.py", line 246, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 317, in __init__
self._open()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 322, in _open
self.establish_connection()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 890, in establish_connection
raise NetMikoTimeoutException(msg)
netmiko.ssh_exception.NetMikoTimeoutException: Connection to device timed-out: cisco_ios 192.168.122.72:22
Looks like there are more than 1 errors ...
You are doing a minor mistake here, you are expecting an error than trying to same the output. In case of error, the script will through an error. Try it this way.
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
try:
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios')
DEVICE.open()
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
except Exception as Err:
print(Err)

Error when importing webdriver from selenium

I'm trying to get all results from a predefined google search, but I'm stuck at the following error:
Traceback (most recent call last):
File "C:\python36\lib\site-packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
File "C:\python36\lib\subprocess.py", line 707, in __init__
restore_signals, start_new_session)
File "C:\python36\lib\subprocess.py", line 992, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\amzar\Desktop\pyscripts\selen.py", line 23, in <module>
get_results("dog")
File "C:\Users\amzar\Desktop\pyscripts\selen.py", line 6, in get_results
browser = webdriver.Firefox()
File "C:\python36\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 142, in __init__
self.service.start()
File "C:\python36\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
I checked for 30 minutes all possibilities with importing, but I can't figured it out.
from selenium import webdriver
def get_results(search_term):
url = "http://startpage.com"
browser = webdriver.Firefox()
browser.get(url)
search_box = browser.find_element_by_id("query")
search_box.send_keys(search_term)
search_box.submit()
try:
links = browser.find_elements_by_xpath("/ol[#class='web_regular_results']//h3//a")
except:
links = browser.find_elements_by_xpath("//h3//a")
results = []
for link in links:
href = link.get_attribute("href")
printf(href)
results.append(href)
browser.close()
return results
get_results("dog")

Use Dryscrape to login to Facebook

I'm trying to use Drcscrape to login to Facebook but I get this error.
I'm using OSX
Traceback (most recent call last):
File "/Users/noppanit/.virtualenvs/envpy3/lib/python3.4/site-packages/webkit_server.py", line 420, in __init__
self._port = int(re.search(b"port: (\d+)", output).group(1))
AttributeError: 'NoneType' object has no attribute 'group'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "facebook_scraper.py", line 40, in <module>
sess = dryscrape.Session(base_url = 'https://www.facebook.com')
File "/Users/noppanit/.virtualenvs/envpy3/lib/python3.4/site-packages/dryscrape/session.py", line 22, in __init__
self.driver = driver or DefaultDriver()
File "/Users/noppanit/.virtualenvs/envpy3/lib/python3.4/site-packages/dryscrape/driver/webkit.py", line 30, in __init__
super(Driver, self).__init__(**kw)
File "/Users/noppanit/.virtualenvs/envpy3/lib/python3.4/site-packages/webkit_server.py", line 230, in __init__
self.conn = connection or ServerConnection()
File "/Users/noppanit/.virtualenvs/envpy3/lib/python3.4/site-packages/webkit_server.py", line 507, in __init__
self._sock = (server or get_default_server()).connect()
File "/Users/noppanit/.virtualenvs/envpy3/lib/python3.4/site-packages/webkit_server.py", line 450, in get_default_server
_default_server = Server()
File "/Users/noppanit/.virtualenvs/envpy3/lib/python3.4/site-packages/webkit_server.py", line 427, in __init__
raise WebkitServerError("webkit-server failed to start. Output:\n" + err)
webkit_server.WebkitServerError: webkit-server failed to start. Output:
dyld: Library not loaded: #rpath/./libQtWebKit.4.dylib
Referenced from: /Users/noppanit/.virtualenvs/envpy3/lib/python3.4/site-packages/webkit_server
Reason: image not found
This is the snippet code.
import dryscrape
# make sure you have xvfb installed
dryscrape.start_xvfb()
# set up a web scraping session
sess = dryscrape.Session(base_url = 'https://www.facebook.com')
# we don't need images
sess.set_attribute('auto_load_images', False)
# visit homepage and search for a term
sess.visit('/')
q = sess.at_xpath('//*[#id="email"]')
q.set('email')
q = sess.at_xpath('//*[#id="pass"]')
q.set("password")
login_button = sess.at_xpath('//*[#id="u_0_x"]')
login_button.click()
# save a screenshot of the web page
sess.render('facebook.png')
print("Screenshot written to 'facebook.png'")
Try with input name it is working perfectly because id changed every time when page refreshing

Categories