using pycharm (python 3) to write a python program,there are part of the program:
class GraphAPI(object):
...
def get_version(self):
'''Fetch the current version number of the Graph API being used'''
args = {"access_token":self.access_token}
try:
response = self.request(
"GET",
FACEBOOK_GRAPH_URL + self.version + "/me",
params = args,
timeout = self.timeout,
proxies = self.proxies
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
However, the "e.read()" is in yellow color, when moving mouse on it, it shows:
Unresolved attribute reference 'read' for class 'HTTPError',This inspection
detected names that should resolve but don't. Due to dynamic dispatch and
duck typing, this is possible in a limited but useful number of cases.Top-
level and class-level items are supported better than instance items
pycharm tells you that it doesn't understand that this "e" of type requests.HTTPError does have a read() method.
So, most likely, you are simply missing the correct import statement. You have to make sure that the "name" requests.HTTPError is known to your IDE.
(and just for the record: pycharm is usually correct about such assignments, so when pycharm gives you an error for that line, your code has in fact a problem and will fail at runtime)
Related
So I'm working with jira using their module, trying to execute issue transitions and sometimes I get this error. It happens when there are more than 2 issues in a queue (and works fine when there is one in queue)
My code is:
def task2(self):
while True:
project.task1(self)
time.sleep(20)
def task1(self):
user = **
pass = **
jira_url = "jira.example.com"
try:
jira_options = ('server': JIRA_URL)
jql_string = jira.search_issue("project = AB")
logging.basicConfig(filename='log-file.log', filemode = '+a', level=DEBUG)
for is_num in jql_string:
issue_num = jira.issue(is_num)
summ = issue.summary
descr = issue.description
//some other code that has nothing to do with jira//
jira.add_comment(issue_num, "Добавить комментарий")
jira.transition_issue(issue_num, "1", fields={'customfield_1':'text1', 'customfield_2':'text2'})
print('well done')
jira.close()
time.sleep(5)
except TypeError as te:
jira.add_comment(issue_num, "Добавить комментарий")
jira.transition_issue(issue_num, "1", fields={'customfield_1':'text1', 'customfield_2':'text2'})
except Exception as exc: #for connection time out
pass
What can be the problem? It happens on second issue in a queue. Without transitions it works perfectly (some other code)
And it's not crashing even when there is only print('smth') in except Exception, traceback not logging neither with Error nor debug level
In debug log only 201 and 204 status responses
Added log. I'm trying to add comments in russian, and even though the error - it still adds commentary to request. IDK... Guess some encoding error.
Error:
File "C:\script\task-jira.py", line 231 in add_comm
jira.add_comment(issue, 'xc07 xE0 xFF xE2')
Then errors in client.py in wrapper and add_comment.
In add_comment
r = self._session.post(AttributeError: 'NoneType' object has no attribute 'post'
FIgured it out. The problem was in commentary text.
I am attempting to modify the extremely helpful open keynotes button script to create a 'reload keynotes' button.
Currently i am trying to use the Reload Method of the KeyBasedTreeEntryTable class.
kt = DB.KeynoteTable.GetKeynoteTable(revit.doc)
kt_ref = kt.GetExternalFileReference()
path = DB.ModelPathUtils.ConvertModelPathToUserVisiblePath(
kt_ref.GetAbsolutePath()
)
reloader = DB.KeyBasedTreeEntryTable.Reload()
if not path:
forms.alert('No keynote file is assigned.')
else:
reloader
This is the error message that i am receiving.
TypeError: Reload() takes exactly 2 arguments (0 given)
I am stuck here and appreciate any help.
You can use Revit API to reload the keynotes, the method KeyBasedTreeEntryTable.Reload just needs a parameter to store warnings thrown during operation, this parameter can be None to make it easy.
Also KeyBasedTreeEntryTable should be an instance, the reload method is not static.
The cool thing is that you don't need to find any KeyBasedTreeEntryTable instance, because the KeynoteTable class inherits from KeyBasedTreeEntryTable, so the Reload method is already available with the kt instance in your script.
(This operation needs a transaction context too, like in the following examples)
Simple way
kt = DB.KeynoteTable.GetKeynoteTable(revit.doc)
t = DB.Transaction(revit.doc)
t.Start('Keynote Reload')
try:
result = kt.Reload(None)
t.Commit()
except:
t.RollBack()
forms.alert('Keynote Reloading : {}'.format(result))
# result can be 'Success', 'ResourceAlreadyCurrent' or 'Failure'
Complete way
kt = DB.KeynoteTable.GetKeynoteTable(revit.doc)
# create results object
res = DB.KeyBasedTreeEntriesLoadResults()
t = DB.Transaction(revit.doc)
t.Start('Keynote Reload')
try:
result = kt.Reload(res) # pass results object
t.Commit()
except:
t.RollBack()
# read results
failures = res.GetFailureMessages()
syntax_err = res.GetFileSyntaxErrors()
entries_err = res.GetKeyBasedTreeEntryErrors()
# res.GetFileReadErrors() returns files errors, should be already in failures Messages
warnings = ''
warnings += '\n'.join([message.GetDescriptionText() for message in failures])
if syntax_err:
warnings += '\n\nSyntax errors in the files :\n'
warnings += '\n'.join(syntax_err)
if entries_err:
warnings += '\nEntries with error :\n'
warnings += '\n'.join([key.GetEntry().Key for key in entries_err])
forms.alert('Keynote Reloading : {}\n{}'.format(result, warnings))
I've been thinking about switching from nose to behave for testing (mocha/chai etc have spoiled me). So far so good, but I can't seem to figure out any way of testing for exceptions besides:
#then("It throws a KeyError exception")
def step_impl(context):
try:
konfigure.load_env_mapping("baz", context.configs)
except KeyError, e:
assert (e.message == "No baz configuration found")
With nose I can annotate a test with
#raises(KeyError)
I can't find anything like this in behave (not in the source, not in the examples, not here). It sure would be grand to be able to specify exceptions that might be thrown in the scenario outlines.
Anyone been down this path?
I'm pretty new to BDD myself, but generally, the idea would be that the tests document what behaves the client can expect - not the step implementations. So I'd expect the canonical way to test this would be something like:
When I try to load config baz
Then it throws a KeyError with message "No baz configuration found"
With steps defined like:
#when('...')
def step(context):
try:
# do some loading here
context.exc = None
except Exception, e:
context.exc = e
#then('it throws a {type} with message "{msg}"')
def step(context, type, msg):
assert isinstance(context.exc, eval(type)), "Invalid exception - expected " + type
assert context.exc.message == msg, "Invalid message - expected " + msg
If that's a common pattern, you could just write your own decorator:
def catch_all(func):
def wrapper(context, *args, **kwargs):
try:
func(context, *args, **kwargs)
context.exc = None
except Exception, e:
context.exc = e
return wrapper
#when('... ...')
#catch_all
def step(context):
# do some loading here - same as before
This try/catch approach by Barry works, but I see some issues:
Adding a try/except to your steps means that errors will be hidden.
Adding an extra decorator is inelegant. I would like my decorator to be a modified #where
My suggestion is to
have the expect exception before the failing statement
in the try/catch, raise if the error was not expected
in the after_scenario, raise error if expected error not found.
use the modified given/when/then everywhere
Code:
def given(regexp):
return _wrapped_step(behave.given, regexp) #pylint: disable=no-member
def then(regexp):
return _wrapped_step(behave.then, regexp) #pylint: disable=no-member
def when(regexp):
return _wrapped_step(behave.when, regexp) #pylint: disable=no-member
def _wrapped_step(step_function, regexp):
def wrapper(func):
"""
This corresponds to, for step_function=given
#given(regexp)
#accept_expected_exception
def a_given_step_function(context, ...
"""
return step_function(regexp)(_accept_expected_exception(func))
return wrapper
def _accept_expected_exception(func):
"""
If an error is expected, check if it matches the error.
Otherwise raise it again.
"""
def wrapper(context, *args, **kwargs):
try:
func(context, *args, **kwargs)
except Exception, e: #pylint: disable=W0703
expected_fail = context.expected_fail
# Reset expected fail, only try matching once.
context.expected_fail = None
if expected_fail:
expected_fail.assert_exception(e)
else:
raise
return wrapper
class ErrorExpected(object):
def __init__(self, message):
self.message = message
def get_message_from_exception(self, exception):
return str(exception)
def assert_exception(self, exception):
actual_msg = self.get_message_from_exception(exception)
assert self.message == actual_msg, self.failmessage(exception)
def failmessage(self, exception):
msg = "Not getting expected error: {0}\nInstead got{1}"
msg = msg.format(self.message, self.get_message_from_exception(exception))
return msg
#given('the next step shall fail with')
def expect_fail(context):
if context.expected_fail:
msg = 'Already expecting failure:\n {0}'.format(context.expected_fail.message)
context.expected_fail = None
util.show_gherkin_error(msg)
context.expected_fail = ErrorExpected(context.text)
I import my modified given/then/when instead of behave, and add to my environment.py initiating context.expected fail before scenario and checking it after:
def after_scenario(context, scenario):
if context.expected_fail:
msg = "Expected failure not found: %s" % (context.expected_fail.message)
util.show_gherkin_error(msg)
The try / except approach you show is actually completely correct because it shows the way that you would actually use the code in real life. However, there's a reason that you don't completely like it. It leads to ugly problems with things like the following:
Scenario: correct password accepted
Given that I have a correct password
When I attempt to log in
Then I should get a prompt
Scenario: incorrect password rejected
Given that I have an incorrect password
When I attempt to log in
Then I should get an exception
If I write the step definition without try/except then the second scenario will fail. If I write it with try/except then the first scenario risks hiding an exception, especially if the exception happens after the prompt has already been printed.
Instead those scenarios should, IMHO, be written as something like
Scenario: correct password accepted
Given that I have a correct password
When I log in
Then I should get a prompt
Scenario: correct password accepted
Given that I have a correct password
When I try to log in
Then I should get an exception
The "I log in" step should not use try; The "I try to log in" matches neatly to try and gives away the fact that there might not be success.
Then there comes the question about code reuse between the two almost, but not quite identical steps. Probably we don't want to have two functions which both login. Apart from simply having a common other function you call, you could also do something like this near the end of your step file.
#when(u'{who} try to {what}')
def step_impl(context):
try:
context.execute_steps("when" + who + " " + what)
context.exception=None
except Exception as e:
context.exception=e
This will automatically convert all steps containing the word "try to" into steps with the same name but with try to deleted and then protect them with a try/except.
There are some questions about when you actually should deal with exceptions in BDD since they aren't user visible. It's not part of the answer to this question though so I've put them in a separate posting.
Behave is not in the assertion matcher business. Therefore, it does not provide a solution for this. There are already enough Python packages that solve this problem.
SEE ALSO: behave.example: Select an assertion matcher library
I'd like to embed pylint in a program. The user enters python programs (in Qt, in a QTextEdit, although not relevant) and in the background I call pylint to check the text he enters. Finally, I print the errors in a message box.
There are thus two questions: First, how can I do this without writing the entered text to a temporary file and giving it to pylint ? I suppose at some point pylint (or astroid) handles a stream and not a file anymore.
And, more importantly, is it a good idea ? Would it cause problems for imports or other stuffs ? Intuitively I would say no since it seems to spawn a new process (with epylint) but I'm no python expert so I'm really not sure. And if I use this to launch pylint, is it okay too ?
Edit:
I tried tinkering with pylint's internals, event fought with it, but finally have been stuck at some point.
Here is the code so far:
from astroid.builder import AstroidBuilder
from astroid.exceptions import AstroidBuildingException
from logilab.common.interface import implements
from pylint.interfaces import IRawChecker, ITokenChecker, IAstroidChecker
from pylint.lint import PyLinter
from pylint.reporters.text import TextReporter
from pylint.utils import PyLintASTWalker
class Validator():
def __init__(self):
self._messagesBuffer = InMemoryMessagesBuffer()
self._validator = None
self.initValidator()
def initValidator(self):
self._validator = StringPyLinter(reporter=TextReporter(output=self._messagesBuffer))
self._validator.load_default_plugins()
self._validator.disable('W0704')
self._validator.disable('I0020')
self._validator.disable('I0021')
self._validator.prepare_import_path([])
def destroyValidator(self):
self._validator.cleanup_import_path()
def check(self, string):
return self._validator.check(string)
class InMemoryMessagesBuffer():
def __init__(self):
self.content = []
def write(self, st):
self.content.append(st)
def messages(self):
return self.content
def reset(self):
self.content = []
class StringPyLinter(PyLinter):
"""Does what PyLinter does but sets checkers once
and redefines get_astroid to call build_string"""
def __init__(self, options=(), reporter=None, option_groups=(), pylintrc=None):
super(StringPyLinter, self).__init__(options, reporter, option_groups, pylintrc)
self._walker = None
self._used_checkers = None
self._tokencheckers = None
self._rawcheckers = None
self.initCheckers()
def __del__(self):
self.destroyCheckers()
def initCheckers(self):
self._walker = PyLintASTWalker(self)
self._used_checkers = self.prepare_checkers()
self._tokencheckers = [c for c in self._used_checkers if implements(c, ITokenChecker)
and c is not self]
self._rawcheckers = [c for c in self._used_checkers if implements(c, IRawChecker)]
# notify global begin
for checker in self._used_checkers:
checker.open()
if implements(checker, IAstroidChecker):
self._walker.add_checker(checker)
def destroyCheckers(self):
self._used_checkers.reverse()
for checker in self._used_checkers:
checker.close()
def check(self, string):
modname = "in_memory"
self.set_current_module(modname)
astroid = self.get_astroid(string, modname)
self.check_astroid_module(astroid, self._walker, self._rawcheckers, self._tokencheckers)
self._add_suppression_messages()
self.set_current_module('')
self.stats['statement'] = self._walker.nbstatements
def get_astroid(self, string, modname):
"""return an astroid representation for a module"""
try:
return AstroidBuilder().string_build(string, modname)
except SyntaxError as ex:
self.add_message('E0001', line=ex.lineno, args=ex.msg)
except AstroidBuildingException as ex:
self.add_message('F0010', args=ex)
except Exception as ex:
import traceback
traceback.print_exc()
self.add_message('F0002', args=(ex.__class__, ex))
if __name__ == '__main__':
code = """
a = 1
print(a)
"""
validator = Validator()
print(validator.check(code))
The traceback is the following:
Traceback (most recent call last):
File "validator.py", line 16, in <module>
main()
File "validator.py", line 13, in main
print(validator.check(code))
File "validator.py", line 30, in check
self._validator.check(string)
File "validator.py", line 79, in check
self.check_astroid_module(astroid, self._walker, self._rawcheckers, self._tokencheckers)
File "c:\Python33\lib\site-packages\pylint\lint.py", line 659, in check_astroid_module
tokens = tokenize_module(astroid)
File "c:\Python33\lib\site-packages\pylint\utils.py", line 103, in tokenize_module
print(module.file_stream)
AttributeError: 'NoneType' object has no attribute 'file_stream'
# And sometimes this is added :
File "c:\Python33\lib\site-packages\astroid\scoped_nodes.py", line 251, in file_stream
return open(self.file, 'rb')
OSError: [Errno 22] Invalid argument: '<?>'
I'll continue digging tomorrow. :)
I got it running.
the first one (NoneType …) is really easy and a bug in your code:
Encountering an exception can make get_astroid “fail”, i.e. send one syntax error message and return!
But for the secong one… such bullshit in pylint’s/logilab’s API… Let me explain: Your astroid object here is of type astroid.scoped_nodes.Module.
It’s also created by a factory, AstroidBuilder, which sets astroid.file = '<?>'.
Unfortunately, the Module class has following property:
#property
def file_stream(self):
if self.file is not None:
return open(self.file, 'rb')
return None
And there’s no way to skip that except for subclassing (Which would render us unable to use the magic in AstroidBuilder), so… monkey patching!
We replace the ill-defined property with one that checks an instance for a reference to our code bytes (e.g. astroid._file_bytes) before engaging in above default behavior.
def _monkeypatch_module(module_class):
if module_class.file_stream.fget.__name__ == 'file_stream_patched':
return # only patch if patch isn’t already applied
old_file_stream_fget = module_class.file_stream.fget
def file_stream_patched(self):
if hasattr(self, '_file_bytes'):
return BytesIO(self._file_bytes)
return old_file_stream_fget(self)
module_class.file_stream = property(file_stream_patched)
That monkeypatching can be called just before calling check_astroid_module. But one more thing has to be done. See, there’s more implicit behavior: Some checkers expect and use astroid’s file_encoding field. So we now have this code in the middle of check:
astroid = self.get_astroid(string, modname)
if astroid is not None:
_monkeypatch_module(astroid.__class__)
astroid._file_bytes = string.encode('utf-8')
astroid.file_encoding = 'utf-8'
self.check_astroid_module(astroid, self._walker, self._rawcheckers, self._tokencheckers)
One could say that no amount of linting creates actually good code. Unfortunately pylint unites enormous complexity with a specialization of calling it on files. Really good code has a nice native API and wraps that with a CLI interface. Don’t ask me why file_stream exists if internally, Module gets built from but forgets the source code.
PS: i had to change sth else in your code: load_default_plugins has to come before some other stuff (maybe prepare_checkers, maybe sth. else)
PPS: i suggest subclassing BaseReporter and using that instead of your InMemoryMessagesBuffer
PPPS: this just got pulled (3.2014), and will fix this: https://bitbucket.org/logilab/astroid/pull-request/15/astroidbuilderstring_build-was/diff
4PS: this is now in the official version, so no monkey patching required: astroid.scoped_nodes.Module now has a file_bytes property (without leading underscore).
Working with an unlocatable stream may definitly cause problems in case of relative imports, since the location is then needed to find the actually imported module.
Astroid support building an AST from a stream, but this is not used/exposed through Pylint which is a level higher and designed to work with files. So while you may acheive this it will need a bit of digging into the low-level APIs.
The easiest way is definitly to save the buffer to the file then to use the SA answer to start pylint programmatically if you wish (totally forgot this other account of mine found in other responses ;). Another option being to write a custom reporter to gain more control.
I have been trying to control a camera through a wsdl file using SUDS. I have got the code working but I want to place error handling into the script. I have tried different exceptions but am unable to get the script working. When I enter an invalid coordinate I get an error. The code I am using is below followed by the error I am recieving.
#!/home/build/Python-2.6.4/python
import suds
from suds.client import Client
####################################################################
#
# Python SUDS Script that controls movement of Camera
#
####################################################################
#
# Absolute Move Function
#
####################################################################
def absoluteMove():
# connects to WSDL file and stores location in variable 'client'
client = Client('http://file.wsdl')
# Create 'token' object to pass as an argument using the 'factory' namespace
token = client.factory.create('ns4:ReferenceToken')
print token
# Create 'dest' object to pass as an argument and values passed to this object
dest = client.factory.create('ns4:PTZVector')
dest.PanTilt._x=400
dest.PanTilt._y=0
dest.Zoom._x=1
print dest
# Create 'speed' object to pass as an argument and values passed to this object
speed = client.factory.create('ns4:PTZSpeed')
speed.PanTilt._x=0
speed.PanTilt._y=0
speed.Zoom._x=1
print speed
# 'AbsoluteMove' method invoked passing in the new values entered in the above objects
try:
result = client.service.AbsoluteMove(token, dest, speed)
except RuntimeError as detail:
print 'Handling run-time error:', detail
print "absoluteMove result ", result
result = absoluteMove()
The error is below:
No handlers could be found for logger "suds.client"
Traceback (most recent call last):
File "ptztest.py", line 48, in <module>
if __name__ == '__main__': result = absoluteMove()
File "ptztest.py", line 42, in absoluteMove
result = client.service.AbsoluteMove(token, dest, speed)
File "build/bdist.linux-i686/egg/suds/client.py", line 537, in __call__
File "build/bdist.linux-i686/egg/suds/client.py", line 597, in invoke
File "build/bdist.linux-i686/egg/suds/client.py", line 632, in send
File "build/bdist.linux-i686/egg/suds/client.py", line 683, in failed
File "build/bdist.linux-i686/egg/suds/bindings/binding.py", line 235, in get_fault
suds.WebFault: Server raised fault: 'Error setting requested pan'
I am not sure which exception I should be using here. Does anyone know how to catch this error. The x coordinate with the value 400 is in degree's that is why the error happens.
Thanks
Okay I have found the solution. In SUDS if you enter:
faults=False
into the client definition, this catches faults and gives the reason why the fault happened. The line should read:
client = Client('http://file.wsdl', faults=False)
The post that I have marked as the correct answer also is able to catch that a problem has happened.
Thanks all
If you handled all exceptions and errors in your code and your code is working fine but still you are getting below message with your correct output.
Msg : "No handlers could be found for logger suds.client "
Then a simple solution is to add this line
logging.getLogger('suds.client').setLevel(logging.CRITICAL)
in yourclient.py file just after all import statement.
If you want to catch that exception you should put
try:
result = client.service.AbsoluteMove(token, dest, speed)
except suds.WebFault as detail:
...
You need to catch suds.WebFault by the looks of that traceback. The error itself seems legitimate, IE, your requests are being executed correctly, but perhaps your parameters are wrong in the given context.
I believe you refer to a harmless diagnostic message in your comment. I could suppress messages from suds calling logging.error() by assigning logging.INFO to basicConfig and logging.CRITICAL to suds.client.
https://fedorahosted.org/suds/wiki/Documentation