How to handle 404 errors using webdriver code - webdriver

Could you please help us how to handle 404 errors using WebDriver code?

Since you haven't provided enough information, I'm assuming that you want to check if request results into 404 then raise an error or display some message.
In following code, I'm requesting for 'Search' link on 'http://www.google.com':
require 'selenium-webdriver'
require 'open-uri'
driver = Selenium::WebDriver.for :firefox
driver.get "http://www.google.com"
search_link = driver.find_element(:link, "Search").attribute("href")
io = open search_link
status = io.status
if status == ["404", "Not Found"]
puts "Request is resulting into 404"
end
Let me know this is what you're looking for or not.

There are multiple ways (using Java), for a URL such as https://www.google.com/sdfsdsdfs :
String actualTitle = driver.getTitle();
assertEquals(actualTitle, "Error 404 (Not Found)!!1" );
or
String pageSource = driver.getPageSource();
if ( pageSource.contains("404") ) assertTrue(true, "404 not found error." );

Related

Passing files in POST using Requests in Python

I'm getting below error when making a requests call post method
{'detail': [{'loc': ['body', 'files'], 'msg': 'field required', 'type': 'value_error.missing'}]}
I tried
response = requests.post("url",headers={mytoken},params=p,files=files)
files = { "file 1": open("sample.pdf",'rb'), "file 2":open("sample11.pdf",'rb')}
I want to get 200 status but I'm getting 422 validation error. Any Idea Why? Its for API Testing purpose, Im new to this I've been debugging this for whole day but still couldn't figure out.
It is not clear from the question what kind of a request the server is expecting. Also, its not clear the exact code snippet you are using too.
From the question, the snippet looks like as follows,
response = requests.post("url",headers={mytoken},params=p,files=files)
files = { "file 1": open("sample.pdf",'rb'), "file 2":open("sample11.pdf",'rb')}
if so, that means you are reading files after you send the request, may be thats why the server complained about missing files field.
See the below example on how you can send two files to an endpoint expecting files.
import requests
import logging
logger = logging.getLogger(__name__)
post_url = "https://exampledomain.local/upload"
file1 = open("sample1.pdf", "rb")
file2 = open("sample2.pdf", "rb")
files = {"file1": file1, "file2": file2}
headers = {"Authorization": "Bearer <your_token_here>"}
params = {"file_type": "pdf"}
response = requests.post(post_url, files=files, headers=headers, params=params)
file1.close()
file2.close()
logger.debug(response.text)

Getting a 403 response code error from ExoPlayer

I am randomly getting 403 error from google DAI url. Sometime no issue the whole day. Sometime it happens when start playing, sometime it happens after several minutes playing. This happens on live streaming and full screen live streaming.
Here are the logs:
onLoadError() called with: eventTime = [com.google.android.exoplayer2.analytics.AnalyticsListener$EventTime#c2e375b], loadEventInfo = [com.google.android.exoplayer2.source.MediaSourceEventListener$LoadEventInfo#fed7bf8], mediaLoadData = [com.google.android.exoplayer2.source.MediaSourceEventListener$MediaLoadData#db388d1], error = [com.google.android.exoplayer2.upstream.HttpDataSource$InvalidResponseCodeException: Response code: 403], wasCanceled = [false]
ExoAnalyticsLogger: onLoadStarted() called with: eventTime = [com.google.android.exoplayer2.analytics.AnalyticsListener$EventTime#bc71f36], loadEventInfo = [com.google.android.exoplayer2.source.MediaSourceEventListener$LoadEventInfo#90eee37], mediaLoadData = [com.google.android.exoplayer2.source.MediaSourceEventListener$MediaLoadData#d7a5fa4]
ExoPlayerImplInternal: Source error.
com.google.android.exoplayer2.upstream.HttpDataSource$InvalidResponseCodeException: Response code: 403
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:211)
at com.google.android.exoplayer2.upstream.DefaultDataSource.open(DefaultDataSource.java:147)
at com.google.android.exoplayer2.source.hls.HlsMediaChunk.loadMedia(HlsMediaChunk.java:267)
at com.google.android.exoplayer2.source.hls.HlsMediaChunk.load(HlsMediaChunk.java:214)
at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:320)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
ExoAnalyticsLogger: onLoadError() called with: eventTime = [com.google.android.exoplayer2.analytics.AnalyticsListener$EventTime#65df8c2], loadEventInfo = [com.google.android.exoplayer2.source.MediaSourceEventListener$LoadEventInfo#fda36d3], mediaLoadData = [com.google.android.exoplayer2.source.MediaSourceEventListener$MediaLoadData#6cfd210], error = [com.google.android.exoplayer2.upstream.HttpDataSource$InvalidResponseCodeException: Response code: 403], wasCanceled = [false]
Encountered error
com.google.android.exoplayer2.ExoPlaybackException
at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:349)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
Caused by: com.google.android.exoplayer2.upstream.HttpDataSource$InvalidResponseCodeException: Response code: 403
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:211)
at com.google.android.exoplayer2.upstream.DefaultDataSource.open(DefaultDataSource.java:147)
at com.google.android.exoplayer2.source.hls.HlsMediaChunk.loadMedia(HlsMediaChunk.java:267)
at com.google.android.exoplayer2.source.hls.HlsMediaChunk.load(HlsMediaChunk.java:214)
at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:320)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Based from this thread, there might be an issue with the cookie handler/manager. Make sure that you are using the same CookieHandler in both your okhttp service class and the exo player activity. You may also check this link for additional reference.
Check out this thread regarding storing cookies. Assuming you're streaming with Akamai url, the solution solved the 403 issue for me.
Note you'll need to implement
com.squareup.okhttp3:okhttp-urlconnection:4.6.0
com.google.android.exoplayer:extension-okhttp:2.11.4
to get JavaNetCookieJar and OkHttpDataSourceFactory.

Angular 2 POST Request

While doing the POST request in Angular 2, I am getting:
"EXCEPTION: Response with status: 404 Not Found for URL:" .
However, while accessing the URL directly, I am getting the response page.
Also in my backend code, I can see my data getting passed from client side to server side:
Response_body: "{"Message":"Not able to add Language = A"}"
headers: Headersok: false
status: 404
statusText: "Not Found"
type: 2
url: "http://localhost:1109/api/Language/AddLanguage"
onSubmit(val){
console.log(val);
this.languageService.testPost(val)
.subscribe(
(res:response) => console.log(res);
);
}
testPost(newVal) : Observable<any>{
let body = JSON.stringify(newVal);
console.log(body);
let headers = new Headers({'Content-Type' : 'application/json'});
let options = new RequestOptions({headers : headers});
return this.http.post(this.logUrl,body,options)
.map((res : Response) => res.json());
}
Yes Rachit,I think you are correct.While Debugging,In my Server side Code I found an Exception mentioning Too many Arguments while saving Data To Database.
There's the culprit I believe, this error generally occurs if you supply more than required params to an SP. So in your DB implementation if you are using SP(s) kindly check them one by one which one is supplying extra parameters. And if nothing else is the problem you should have this issue resolved.

Ruby http Get returning truncated response

I tried sending a HTTP Get to a device's Restful API via Postman and it worked fine returning all text I was expecting. Postman suggested Ruby code for the request was the following:
url = URI('http://192.168.1.5/rest/op/BD1FD3D893613E79')
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
request.basic_auth 'admin', 'admin'
request["accept"] = 'Application/json'
response = http.request(request)
puts response.read_body
but when I tried that in my code, it is returning a truncated response (missing lines) and I have to resend the same Get multiple times to get the entire text response response.
Is there anything missing in the Ruby code above that's causing this truncated response?
Update 1
I tried this
url = URI('http://192.168.1.5/rest/op/BD1FD3D893613E79')
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
request.basic_auth 'admin', 'admin'
request["accept"] = 'Application/json'
response = http.request(request)
puts response.read_body
response.read_body do |segment|
puts segment.to_s
end
and that generated this error
IOError (Net::HTTPOK#read_body called twice):
Update 2
I tried this
1073 url = URI('http://192.168.1.5/rest/op/BD1FD3D893613E79')
1074 http = Net::HTTP.new(url.host, url.port)
1075 request = Net::HTTP::Get.new(url.to_s)
1076 request.basic_auth 'admin', 'admin'
1077 request["accept"] = 'Application/json'
1078 response = http.request(request)
1079 response.read_body do |segment|
1080 puts segment.to_s
1081 end
and got this error
IOError (Net::HTTPOK#read_body called twice):
app/controllers/Apps_controller.rb:1079:in `block in get_config'
app/controllers/Apps_controller.rb:1045:in `each'
app/controllers/Apps_controller.rb:1045:in `get_config'
Based on: http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTPResponse.html#method-i-read_body
read_body returns the body as stream, so you should iterate it, something like:
response.read_body do |segment|
puts segment
end
If you want to get the full body just use: response.body
Looks very similar....
We are getting truncated responses when pulling a set of artifacts (zip files) from a Bamboo server and writing to local storage. It happens inconsistently, on only one of 8 servers, and not always the same file. Seems always to be the last portion of the file that is missing.
Using Ruby 2.0.0p598 and net/http.
The zip files range in size from 2 mb to 34 mb.
While we haven't figured out why the response body has been truncated, our workaround is to compare the expected content length (in the response header), to the response body size. If they don't match, try it again. Example code:
package = "packages/applicationname.zip"
def retrieve(package)
# generates the Bamboo url for the given package
sourceURL = package_url package
expectedLength = 0
bodyLength = 1
# Try to catch the bad download and re-issue the GET request,
while expectedLength != bodyLength do
# add a counter if worried about getting stuck
# issue the request to get the current package zip file
response = my_request_wrapper sourceURL
expectedLength = response['content-length'].to_i
theBody = response.body
bodyLength = theBody.size
if expectedLength != bodyLength then
puts "!! SIZE MISMATCH !!"
else
# the response body is good, process as needed
open package, 'wb' do |io|
io.write theBody
end
end
end
end
def my_request_wrapper(url)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Get.new(uri.request_uri)
req.basic_auth("user", "pwd")
return http.request req
end
I was using OSX Sierra, rvm, and ruby 2.3.0
Updating my rvm, ruby, and gems seems to have fixed the problem for me
I think you must call http.start before you call http.request.
Not sure why, but I see the same.

Create Custom Json Error in Asp.NET MVC

I am using a JavaScript plug-in and if there is an error it expects format like;
{error: 'You are not allowed to upload such a file.'}
In my MVC Web API I am throwing error like;
var error = string.Format("An error has been occured. Please try again later.");
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
and it is represented in HTTP response like below;
{"Message":"An error has been occured. Please try again later."}
how can I achieve to return in first way?
You can create an anonymous object
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError,new { error = "your error message here!"}));

Resources