I have a little script that runs every day by cron and has been working for the last 3 months.
On 30th September it stopped working with the following error:
File "NumberChecker.py", line 32, in start_server
os.startfile(startfile[0])
AttributeError: 'module' object has no attribute 'startfile'
here is the code for that bit:
def start_server(xml):
startfile = xml.xpath('/config/files/startfile/text()')
try:
driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT)
driver.get('http://www.google.com')
except:
print('no server')
server_status = 'down'
os.startfile(startfile[0])
while server_status == 'down':
try :
driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT)
driver.get('http://www.google.com')
server_status = 'running'
except :
pass
It just tests to see if the selenium server is up or not by requesting google and if not calls a bash script that starts it.
Why would os.startfile suddenly stop working?
I have tried at the command line this:
import os
os.startfile(home/adam/file/start_server.sh)
and I get
File "< stdin >", line 1, in
AttributeError: 'module' object has no attribute 'startfile'
I just can't work out why it has just stopped working?
It is python 3.3 in an virtual environment and the os is ubuntu server 12.04
os.startfile is a Windows specific method, it won't work on linux.
Related
Debugging Selenium script with EventFiringWebDriver in PyCharm, cause exception to be logged:
'WebDriver' object has no attribute '__len__'
It slows down IDE but do not break (stop) the script.
Here is full code:
from selenium import webdriver
from selenium.webdriver.support.event_firing_webdriver import EventFiringWebDriver
from selenium.webdriver.support.events import AbstractEventListener
class ScreenshotListener(AbstractEventListener):
def on_exception(self, exception, driver):
print(exception)
driver = webdriver.Chrome('chromedriver.exe')
ef_driver = EventFiringWebDriver(driver, ScreenshotListener())
ef_driver.get('https://google.com/')
title = ef_driver.title
driver.quit()
assert "Google", title
When I run attached script in standard mode everything is OK.
But running with PyCharm Debug (here is output from beginning of Debug console):
C:\Pro\selenium-debug\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 59668 --file C:/Pro/selenium-debug/simple_test.py
I get those exceptions (every time when I call ef_driver):
'WebDriver' object has no attribute '__len__'
'WebDriver' object has no attribute '__len__'
It not stopping the script, it just cause debugger to be slow (it updates driver and focus is set to the browser).
Any idea why it is triggered and logged?
Bonus: Running debugging in console with pdb is OK, so this looks like strictly PyCharm Debug connected thing
Looks like PyCharm debug checks if an object has a __len__ attribute:
elif hasattr(v, "__len__")
and the object WebDriver has no __len__.
A solution could be (from the link below) to warp with try\catch:
try:
if is_numeric_container(type_qualifier, typeName, v):
xml_shape = ' shape="%s"' % make_valid_xml_value(str(v.shape))
elif hasattr(v, "__len__") and not is_string(v):
try:
xml_shape = ' shape="%s"' % make_valid_xml_value("%s" % str(len(v)))
except:
pass
except KeyError:
pass
Please check this track:
https://youtrack.jetbrains.com/issue/PY-39954
I'm trying to run a test in a docker container, which runs locally with no issues:
I want to upload a correct.csv file from 'correct' directory
*** Keyword ***
Upload file
[Arguments] ${directory} ${file}
Choose File ${choose_file_input} ${EXECDIR}/Files/${directory}/${file}
** Test case ***
Upload
Upload file correct correct.csv
But when running test in docker I get a FAIL with the AttributeError: module 'base64' has no attribute 'encodestring'. Is it because there is no GUI in docker? or the encoding needs to be fixed? Or eventually maybe there is another solution I can use for uploading files?
15:20:01.250 INFO Sending /App/Files/correct/correct.csv to browser.
15:20:01.251 DEBUG POST http://192.168.1.29:4444/wd/hub/session/4b6d453b394adaaa51bb4149e9ba8678/elements {"using": "xpath", "value": "//div[#id=\"upload\"]//input"}
15:20:01.252 DEBUG Starting new HTTP connection (1): 192.168.1.29:4444
15:20:01.305 DEBUG http://192.168.1.29:4444 "POST /wd/hub/session/4b6d453b394adaaa51bb4149e9ba8678/elements HTTP/1.1" 200 90
15:20:01.305 DEBUG Finished Request
15:20:01.618 FAIL AttributeError: module 'base64' has no attribute 'encodestring'
15:20:01.619 DEBUG Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/SeleniumLibrary/__init__.py", line 490, in run_keyword
return DynamicCore.run_keyword(self, name, args, kwargs)
File "/usr/local/lib/python3.9/site-packages/robotlibcore.py", line 103, in run_keyword
return self.keywords[name](*args, **(kwargs or {}))
File "/usr/local/lib/python3.9/site-packages/SeleniumLibrary/keywords/formelement.py", line 224, in choose_file
self.find_element(locator).send_keys(file_path)
File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webelement.py", line 475, in send_keys
value = self._upload(local_file)
File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webelement.py", line 695, in _upload
content = base64.encodestring(fp.getvalue())
Based on the traceback you have found this issue:
Selenium 3 is incompatible with Python 3.9
This is the fix for the issue: DeprecationWarning of base64.encodestring().
They won't back port this fix:
Thanks for the issue. We won't be releasing another version 3 as we're
heading to finishing off Selenium 4. It is a drop in replacement to
use Selenium 4.0.0.a5 so should work the same. There should not be any
breaking changes.
So you could upgrade selenium to Selenium 4.0.0.a5 or
Downgrade Python to 3.7 for example. I suppose locally you do not run 3.9.
We were running into this issue as well, but going back to an older version of Python was not an option due to incompatibilities with other libraries. If you find yourself in the same spot, you can re-create the alias like so:
import base64
base64.encodestring = base64.encodebytes
In whatever your entry-point is.
I am trying to automate a windows GUI machine.exe using pywinauto. I used the command app = Application().start("machine.exe") which throws this error after opening the machine.exe GUI
error: (0, 'WaitForInputIdle', 'No error message is available') in line 901 of application.py. I would like to understand the cause of the error message
I have tried to start the Gui using os.startfile and then connect to the gui using connect ()method
I am using python 2.6.6, OS is windows 7
from pywinauto.application import Application
def test():
app = Application().start("machine.exe")
app.connect(title="machine.exe")
I expected it to just open the gui without any issues.
I'm doing a testing unit that requires the tests to be run via web browser. I'm using Ubuntu VPS 14 with LAMP stack installed, mod_wsgi, selenium 2.44 and PhantomJS 1.9. I'm testing with the very simple code first:
from flask import Flask, request
from selenium import webdriver
app = Flask(__name__)
app.debug = True
#app.route("/test")
def test():
url = "http://www.google.com"
driver = webdriver.PhantomJS('./phantomjs')
driver.get(url)
result = driver.page_source
driver.close()
return result
if __name__ == "__main__":
app.run()
The code runs very smoothly on my local Ubuntu, it prints out the google page when I connect to: 127.0.0.1:5000/test . On my Ubuntu VPS, my have my flask already setup and running. Now i use the same code to be the index file (supposed all configs are OK and 'hello world' runs), I have 500 Internal Server Error when connecting to http://xxx.xxx.xxx.xxx/test
Apache log sends out the following error:
... service_args=service_args, log_path=service_log_path File
"/usr/local/lib/python2.7/ddist-packages/selenium/webdriver/phantomjs/service.py",
line 53, in init
self._log = open(log_path, 'w') in > ignored Exception AttributeError: "'Service' object
has no attribute '_log'" in > ignored
I changed the log_path for phatomJS but still have the same problem. However, if I open python console, doing line by line as following:
from selenium import webdriver
br = webdriver.PhantomJS('./phantomjs')
....
I got no error. It took me the whole day to fin the problem but I could't be able to fix it. Any ideas how to solve this problem?
Figure out the problem, current phantomjs and init.py don't have enough permission to manipulate the service.py of ghostdriver. Here is the fix:
Add a new user: "add username", then set "add username sudo"
Login to the new user, make sure every command you run from now on starts with "sudo"
In your flask application where init.py resides, create "ghostdriver.log" and "phantomjs" which is an executable file.
Chmod both of them to 777 : init.py, ghostdriver.log and phantomjs
Set the custom config in init.py for phantomjs:
br = webdriver.PhantomJS(service_log_path='./ghostdriver.log', executable_path='./phantomjs')
That's it, now your selenium + flask + phantomjs is now working correctly.
THIS OCCURS IN FIREFOX ONLY: In a previous question, I had run into the issue where SST 0.2.4 is not compatible with Selenium 2.44.0. So I downgraded to Selenium 2.43.0. I now have a new issue that I'm confused about. I'm receiving the following error message:
_StringException: Traceback (most recent call last):
File "C:\Python27\lib\site-packages\sst\cases.py", line 75, in setUp
self.start_browser()
File "C:\Python27\lib\site-packages\sst\cases.py", line 107, in start_browser
logger.debug('Browser started: %s' % (self.browser.name))
AttributeError: 'NoneType' object has no attribute 'name'
The code that it is referencing in the cases.py file in the Lib/SST folder is below:
def start_browser(self):
max_attempts = 5
for nb_attempts in range(1, max_attempts):
try:
logger.debug('Starting browser (attempt: %d)' % (nb_attempts,))
self._start_browser()
break
except exceptions.WebDriverException:
if nb_attempts >= max_attempts:
raise
logger.debug('Browser started: %s' % (self.browser.name))
My code looks like the following:
import unittest
from sst.actions import *
from sst import cases, config, browsers
class TestMyTest(cases.SSTTestCase):
def test_mytestcase_home_page(self):
config.results_directory = "C:/Users/Brenda/test/SST-Test-Project/results"
go_to('http://www.myhomepage.com')
assert_title_contains('My Home Page')
take_screenshot(filename='home_page.png',add_timestamp=True)
assert_element(tag='a', text='Log in')
I keep thinking that the solution to this is fairly simple, but I can't seem to wrap my head around it.
I'll also add the note that when running sst-run MySSTTest in the command line, it looks like it is attempting to start the browser without success. My code was working prior to the holiday break at which time it seems to have broken.
EDITED 3-Dec-2014: I wanted to add that I can successfully execute the test in Chrome and IE. This issue is with Firefox ONLY in a Windows 7 environment. It was successfully executed on a Mac OS in all 3 browsers.
I think cases.py codes has possibility cannot get browser object when it runs _start_browser
method
def _start_browser(self):
self.browser_factory.setup_for_test(self)
self.browser = self.browser_factory.browser()
def start_browser(self):
max_attempts = 5
for nb_attempts in range(1, max_attempts):
try:
logger.debug('Starting browser (attempt: %d)' % (nb_attempts,))
self._start_browser()
break
except exceptions.WebDriverException:
if nb_attempts >= max_attempts:
raise
logger.debug('Browser started: %s' % (self.browser.name))
The main problem: if nb_attempts >= max_attempts: has no effect. nb_attempts only goes up to max_attempts-1. I would use continue and re-raise the exception in an else clause instead:
logger.debug('Starting browser')
e = None
for _ in range(max_attempts):
try:
self._start_browser()
break
except exceptions.WebDriverException,e:
continue
else:
raise e
("_" is an idiom for an unused variable)
Even with that fix, self.browser can still be None if browser_factory.browser() returns None.