I have small web server on my host. And I try to connect them with https.
I have next test function
request2(Host)->
ssl:start(),
{ok, Socket} = ssl:connect(Host, 8013, [{active, false},{certfile,"/home/user/sipo.pem"}], 10000),
ssl:close(Socket).
and in repl we have next:
(emacs#host-15)112> ssl:start().
ok
(emacs#host-15)113> test:request2("192.168.31.57").
ok
(emacs#host-15)114> test:request2("192.168.31.57").
** exception error: no match of right hand side value {error,closed}
in function test:request2/1 (/home/user/src/test.erl, line 78)
(emacs#host-15)117> ssl:stop().
ok
(emacs#host-15)118> ssl:start().
ok
(emacs#host-15)119> test:request2("192.168.31.57").
ok
(emacs#host-15)120> test:request2("192.168.31.57").
** exception error: no match of right hand side value {error,closed}
in function test:request2/1 (/home/user/src/test.erl, line 78)
(emacs#host-15)121>
Why the call request2 is work fine only once and afrer that I have error {error,closed}. Whot is happend?
Related
I'm trying to use Plug.Test to test error handling implemented with Plug.ErrorHandler -- with assert conn.status == 406 and alike.
I have the defp handle_errors (containing a single send_resp statement) and it seems to be called, however, my tests fail with the same exception still (as if handle_errors has no effect).
A reference to a sample advanced Plug (not Phoenix) app will also be appreciated.
Try something like this (not tested):
defmodule NotAcceptableError do
defexception plug_status: 406, message: "not_acceptable"
end
defmodule Router do
use Plug.Router
use Plug.ErrorHandler
plug :match
plug :dispatch
get "/hello" do
raise NotAcceptableError
send_resp(conn, 200, "world")
end
def handle_errors(conn, %{kind: _kind, reason: reason, stack: _stack}) do
send_resp(conn, conn.status, reason.message)
end
end
test "error" do
conn = conn(:get, "/hello")
assert_raise Plug.Conn.WrapperError, "** (NotAcceptableError not_acceptable)", fn ->
Router.call(conn, [])
end
assert_received {:plug_conn, :sent}
assert {406, _headers, "not_acceptable"} = sent_resp(conn)
end
Use assert_error_sent/2 to assert that you raised an error and it was wrapped and sent with a particular status. Match against its {status, headers, body} return value to assert the rest of the HTTP response met your expectations.
response = assert_error_sent 404, fn ->
get(build_conn(), "/users/not-found")
end
assert {404, [_h | _t], "Page not found"} = response
I'm trying to use rabbitmq-erlang-client, and confused about errors throwed by program.
I fllowed system_SUITE:queue_unbind/1 But errors are throwed when setting Exchange and Queue :
%% code
amqp_channel:call(Channel, #'exchange.declare'{exchange = X}),
amqp_channel:call(Channel, #'queue.declare'{queue = Q}),
%% it throw me same errors again and again:
** Last message in was setup_exchange_queue
** When Server state == {state,
{amqp_params_network,<<"username">>,<<"password">>,
<<"/">>,"192.168.1.173",5672,0,0,10,infinity,
none,
[#Fun<amqp_auth_mechanisms.plain.3>,
#Fun<amqp_auth_mechanisms.amqplain.3>],
[],[]},
<0.74.0>,<0.83.0>,<<"amq.direct">>,<<"queue">>,
<<"my_queue">>,undefined,undefined}
** Reason for termination ==
** {{noproc,{gen_server,call,[<0.83.0>,{close,200,<<"Goodbye">>},infinity]}},
[{gen_server,call,3,[{file,"gen_server.erl"},{line,212}]},
{mrbq,terminate,2,[{file,"src/mrbq.erl"},{line,244}]},
{gen_server,try_terminate,3,[{file,"gen_server.erl"},{line,643}]},
{gen_server,terminate,7,[{file,"gen_server.erl"},{line,809}]},
{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,240}]}]}
** exception exit: {noproc,
{gen_server,call,
[<0.83.0>,{close,200,<<"Goodbye">>},infinity]}}
code review amqp_channel.erl
%% call
call/2 -> gen_server:call/2
handle_call/3 -> handle_method_to_server/6
goto line 573, then line 888 ,and {noreply, State} returned for call as a result!!
What's wrong with above steps?
What should do to make it OK?
I have had tried cast/2,and no errors occur. But this is not what I need.
#!/usr/bin/tclsh
proc test {} {
aaa
}
test
When I run this script I get error message:
invalid command name "aaa"
while executing
"aaa"
(procedure "test" line 2)
invoked from within
"test"
(file "./a.tcl" line 7)
If I run test command in catch I get only first line of error message.
#!/usr/bin/tclsh
proc test {} {
aaa
}
catch test msg
puts $msg
This prints:
invalid command name "aaa"
Is it possible to get full error message (file, line, procedure) in catch command? My program has many files and by getting just one line of error message it is difficult to find from where is it.
The short answer is to look at the value of errorInfo which will contain the stack trace.
The more complete answer is to look at the catch and the return manual pages and make use of the -optionsVarName parameter to the catch statement to collect the more detailed information provided. The return manual page gives some information on using this. But a rough example from an interactive session:
% proc a {} { catch {funky} err detail; return $detail }
% a
-code 1 -level 0 -errorstack {INNER {invokeStk1 funky} CALL a} -errorcode NONE -errorinfo {invalid command name "funky"
while executing
"funky"} -errorline 1
%
The detail variable is a dictionary, so use dict get $detail -errorinfo to get that particular item.
I have a simple automation to fill login form fields. Actually, it passes good, but there's the problem. I need to see actual output in my console after the script filled fields, like "Logged in successfully" or "Username not found". I tried many stuff, but nothing worked this way, my last try was while loop and it works great, but only when I have positive result. I wrote a second condition, but when I type incorrect data, it drives me crazy to see all these errors in my console. So here's the code and part of output.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
baseurl = "http://www.somesite/login"
email = input("Type an email: ")
password = input("Type a password: ")
xpaths = { 'loginBox' : "//input[#id='session_email']",
'passwordBox' : "//input[#id='session_password']",
'submitButton' : "//input[#class='ufs-but']",
'success' : "//div[#class='flash-message success']",
'error' : "//span[#class='form_error']"
}
mydriver = webdriver.Firefox()
mydriver.get(baseurl)
mydriver.find_element_by_xpath(xpaths['loginBox']).send_keys(email)
mydriver.find_element_by_xpath(xpaths['passwordBox']).send_keys(password)
mydriver.find_element_by_xpath(xpaths['submitButton']).click()
while mydriver.find_element_by_xpath(xpaths['success']):
print("Success")
if mydriver.find_element_by_xpath(xpaths['error']):
print("No")
And there's what I got when I try to interrupt an error:
File "ab.py", line 32, in <module>
while mydriver.find_element_by_xpath(xpaths['success']):
File "/usr/local/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/webdriver/remote/webdriver.py", line 230, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "/usr/local/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/webdriver/remote/webdriver.py", line 662, in find_element
{'using': by, 'value': value})['value']
File "/usr/local/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/webdriver/remote/webdriver.py", line 173, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/webdriver/remote/errorhandler.py", line 166, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate element: {"method":"xpath","selector":"//div[#class=\'flash-message success\']"}' ; Stacktrace:
at FirefoxDriver.prototype.findElementInternal_ (file:///tmp/tmpjax8kj1u/extensions/fxdriver#googlecode.com/components/driver-component.js:9618:26)
at FirefoxDriver.prototype.findElement (file:///tmp/tmpjax8kj1u/extensions/fxdriver#googlecode.com/components/driver-component.js:9627:3)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpjax8kj1u/extensions/fxdriver#googlecode.com/components/command-processor.js:11612:16)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpjax8kj1u/extensions/fxdriver#googlecode.com/components/command-processor.js:11617:7)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpjax8kj1u/extensions/fxdriver#googlecode.com/components/command-processor.js:11559:5)
As I said, successfull result ain't a problem.
UPD. I corrected the last part of my code a little bit and now I have this:
while mydriver.find_element_by_xpath(xpaths['success']):
print("Success")
break
while mydriver.find_element_by_xpath(xpaths['error']):
print("No")
break
And it works, but not like I want, the output when I want a negative result:
Type an email: w
Type a password: wer
Success
No
As you see, I wanna see 'success' when result is positive and 'no' when it's negative, but I don't want to see them at the same time.
UPD. Props to Macro Giancarli for huge help, so that's how I got what I exactly want:
try:
success = True
success_element = mydriver.find_element_by_xpath(xpaths['success'])
except NoSuchElementException:
success = False
print("Can't log in. Check email and/or password")
try:
failure = True
failure_element = mydriver.find_element_by_xpath(xpaths['error'])
except NoSuchElementException :
failure = False
print("Logged in successfully")
The problem looks like it's in the way you structure your while loop at the end. You shouldn't need to loop in order to check for success or failure.
Consider that there are four outcomes, assuming that you input the login data. You could either find the element that determines success, find the element that determines failure, find both (should be impossible), or find neither (probably in the case of an unexpected screen, or a failure to load the page).
Instead of expecting some values to be returned from the webdriver queries, try putting them in a try block to catch a NoSuchElementException and checking for non-None contents. Also, try handling each of the four cases so that your program will crash less often.
Edit:
Try this.
try:
success = True
success_element = mydriver.find_element_by_xpath(xpaths['success'])
except NoSuchElementException:
success = False
try:
failure = True
failure_element = mydriver.find_element_by_xpath(xpaths['error'])
except NoSuchElementException :
failure = False
# now handle the four possibilities
I have a small web server written using Twisted. One of the things I want to do is have it return a result from another web server as the response to loading a page. That is, the response to render_GET() at server A (via http://A.com/resource) should be the content of a different URL at server B (via http://B.com/resource2). The content returned by server B is dynamic, so I can't just cache it.
Right now, server A can render pages just fine, it just can't render this remote resource. I've tried with Agent(), but I can't seem to get the response from B let alone forward it to A. I know that somewhere I have to take that request from the render_GET and later write() and finish() it. That's done in the cbBody callback, which get called but can't get to the original request to populate it.
Here's a piece of the code for server A's resource handler:
def render_GET(self,request):
# try with canned content just to test the whole thing
bmpServer = BMPServer(ServerBURL,
"xyzzy",
"plugh")
d= bmpServer.postNotification({"a":123},request)
print "Deferred", d
return NOT_DONE_YET
And this is the other code at server A:
theRequest = None
def cbRequest(response,args):
print "response called"
print response
print args
print 'Response version:', response.version
print 'Response code:', response.code
print 'Response phrase:', response.phrase
print 'Response headers:'
print pformat(list(response.headers.getAllRawHeaders()))
d = readBody(response)
d.addCallback(cbBody)
return d
def cbBody(body):
print "Response body:"
print body
theRequest.write(body)
theRequest.finish()
theRequest = None
def cbError(failure):
print type(failure.value), failure # catch error here
print failure.value.reasons[0].printTraceback()
class BMPServer(object):
def __init__(self,url,arg1,arg2):
self.url = url
self.arg1 = arg1
self.arg2 = arg2
def postNotification(self,message,request):
theRequest = request
bmpMessage = {'arg1':self.token,
'arg2':self.appID,
'message':message}
print "Sending request to %s"%self.url
print "Create agent"
agent = Agent(reactor)
print "create request deferred"
print "url = %s" % self.url
d = agent.request('POST', self.url,
Headers({'User-Agent': ['Twisted Web Client Example']}),
MessageProducer(bmpMessage))
print "adding callback"
d.addCallbacks(cbRequest,cbError)
print "returning deferred"
return d
When I run this as a standalone code (outside of the resource, using react() for example), it works fine. However, when I try to include it as shown above it just never seems to receive the data. I've got WireShark running so I can see the response is being returned from Server B, but the data never shows up in cbRequest().
For example, here's the output I see:
Sending request to http://localhost:8888/postMGCMNotificationService
Create agent
create request deferred
url = http://serverB:8888/postService
Message producer: body = {"arg2": "plugh", "arg1": "xyzzy", "message": {"a": 1}}
adding callback
returning deferred
testAgent: returning deferred
<Deferred at 0x10b54d290>
Writing body now
response called
<twisted.web._newclient.Response object at 0x1080753d0>
Response version: ('HTTP', 1, 1)
Response code: 200
Response phrase: OK
Response headers:
Response body:
{"result": false}
^CUnhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/Twisted-13.1.0_r39314-py2.7-macosx-10.8-intel.egg/twisted/web/_newclient.py", line 1151, in _bodyDataFinished_CONNECTED
self._bodyProtocol.connectionLost(reason)
File "/Library/Python/2.7/site-packages/Twisted-13.1.0_r39314-py2.7-macosx-10.8-intel.egg/twisted/web/client.py", line 1793, in connectionLost
self.deferred.callback(b''.join(self.dataBuffer))
File "/Library/Python/2.7/site-packages/Twisted-13.1.0_r39314-py2.7-macosx-10.8-intel.egg/twisted/internet/defer.py", line 382, in callback
self._startRunCallbacks(result)
File "/Library/Python/2.7/site-packages/Twisted-13.1.0_r39314-py2.7-macosx-10.8-intel.egg/twisted/internet/defer.py", line 490, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/Library/Python/2.7/site-packages/Twisted-13.1.0_r39314-py2.7-macosx-10.8-intel.egg/twisted/internet/defer.py", line 577, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "AServer.py", line 85, in cbBody
print theRequest
exceptions.UnboundLocalError: local variable 'theRequest' referenced before assignment
Looking at this a little more, it seems that if I could figure out a way to get the request over to cbBody() this would all work just fine.
You can pass extra arguments to callbacks on a Deferred:
d.addCallback(f, x)
When d fires, the result is f(result of d, x). You can pass as many positional or keyword arguments as you like this way. See the API documentation for Deferred for more details.