how to set HTTP_HOST for WebTestCases in Symfony2 - testing

My application is generating some absolute links via $this->get('request')->getHost().
Problem is: when I try to run testcases, I get following error message:
[exception] 500 | Internal Server Error | Twig_Error_Runtime
[message] An exception has been thrown during the rendering of a template ("Undefined index: HTTP_HOST") in "::base.html.twig" at line 69.
Somehow it's clear to me that there is no host when calling my app via CLI, but I think there must be a way to prevent Symfony2 from throwing that error.
Anyone knows how to get rid of it?

You could create the request like this:
$request = Request::create('http://example.com/path');
That will make the HTTP host be set.

Maybe what you could do is to inject the host you need directly in the request headers before calling the getter. The host is retrieved by looking at various parameter values. First, the headers parameter X_FORWARDED_HOST is checked to see if it is set. If it is set, it is returned otherwise the method getHost checks if the headers parameter HOST is set then the if the server parameter SERVER_NAME is set and finally if the server parameter SERVER_ADDR is set.
What you could try is to set the header parameter HOST like this before calling the getHost method:
$request = $this->get('request');
$request->headers->set('HOST', 'yourhosthere');
$request->getHost(); // Should return yourhosthere
That being said, I'm not sure this will solve the problem because the error you mentioning tells us that the template tries to retrieve the value of the index HTTP_HOST but it is not defined. Looking at the methods $request->getHost and $request->getHttpHost, I don't see anything trying to retrieve a value having HTTP_HOST as the index but I could have missed it. Could you post the file ::base.html.twig to see if the problem could be lying there.
Regards,
Matt

Thanks guys- your answers lead me into the right direction.
This is no Symfony2 issue, as i figured out:
It's just the facebook API PHP wrapper which directly accesses the SERVER parameters. This code solved my issue:
$facebook = $this->container->get('facebook');
$returnUrl = 'http://'.$request->getHost();
$returnUrl .= $this->container->get('router')->generate('_validate_facebook');
$_SERVER['HTTP_HOST'] = $request->getHost();
$_SERVER['REQUEST_URI'] = $request->getRequestUri();
$loginUrl = $facebook->getLoginUrl(array(
'req_perms' => 'publish_stream',
'next' => $returnUrl,
));
return $loginUrl;
now my app runs from web and CLI again

Related

In karate mocking (karate-netty), how can we override request header value?

Objective:
We want few API calls should go to mock-server(https://192.x.x.x:8001) and others should go to an actual downstream application server(https://dev.api.acme.com).
Setup :
On local, mock server is up with standalone jar on port 8001. e.g https://192.x.x.x:8001
In application config file (config.property)downstream system(which need to mock) defined with mockserver IP i.e https://192.x.x.x:8001
Testing scenario and problem:
1.
Scenario: pathMatches('/profile/v1/users/{id}/user')
* karate.proceed('https://dev.api.acme.com')
* def response = read ('findScope.json')
* def responseStatus = 200ˀˀ
* print 'created response is: ' + response
Now, when we hit API request via postman or feature file then it does karate.proceed properly to https://dev.api.acme.com/profile/v1/users/123/user instead of 192.x.x.x. However, in this request, host is referring to https://192.x.x.x:8001 instead of https://dev.api.acme.com which create a problem for us.
How can we override request header in this case? I did try with karate.set and also with header host=https://192.x.x.x:8001 but no luck.
Thanks!
Please see if the 1.0 version works: https://github.com/intuit/karate/wiki/1.0-upgrade-guide
Unfortunately https proxying may not work as mentioned. If you are depending on this, we may need your help (code contribution) to get this working
If the Host header is still not mutable, that also can be considered a feature request, and here also I'd request you to consider contributing code

Why do I need to use a Postman pre-request for variables to work in the request body?

In Postman 7.13.0 on Ubuntu, I have variables in one of my collections. They are defined at collection level, not global level, and work perfectly everywhere except in the request body of my POST requests. For example:
"{{name}}" in the request body ends up as "" (the variable is not being substituted). This throws 500 errors from my API as it is expecting a value to be passed. The request I'm looking at is within the same collection that has the variable.
However, if I use a pre-request script like the following, the collection variables work as expected.
var vm_name = pm.variables.get("vm_name");
var cluster_uuid = pm.variables.get("cluster_uuid");
var cluster_name = pm.variables.get("cluster_name");
postman.setEnvironmentVariable("vm_name", vm_name)
postman.setEnvironmentVariable("cluster_name", cluster_name)
postman.setEnvironmentVariable("cluster_uuid", cluster_uuid)
Also, when creating the request body, typing {{ does not begin the autocomplete sequence I'm used to seeing when using the variables elsewhere. This suggests a scope issue although I'm sure that's being done correctly.
I've looked at the Postman docs and I'm sure the scope is correct.
What am I doing wrong that means I must use a pre-request script?
Thanks

Google Sheet API batchUpdateByDataFilter PHP Function

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdateByDataFilter
We have used above function in our code, while we are passing the more than 50 or 100 records within the array records then given 400 bad request array in response.
Can anyone describe the limit of the total values that we are going to pass within the above function?
Here is my code:
$batchupdate = array("valueInputOption" => "RAW", "data" => $dataarray);
try {
$requestBody = new Google_Service_Sheets_BatchUpdateValuesByDataFilterRequest($batchupdate);
$response = $service->spreadsheets_values->BatchUpdateByDataFilter($spreadsheetId, $requestBody);
}
catch(Exception $e) {
echo 'Message: ' . $e->getMessage();
}
Troubleshooting:
Problems with the Request
Until you attach a sanitized version of your Request body we cannot be sure about the root-cause of the problem you are facing.
However, an error 400 means that the request you did is invalid. So, most likely, the problem is in that.
Check if your request object is formatted as detailed on the documentation.
Problems with the Client
If you are able to use the Try this API sidebar with the same Request Body then it could be related to the PHP client.
Note: This is language independent. Create a JSON Object that has the same structure as your request body.
If that's the case, we will need to see more of your code to verify that you are not using your valid Request body in an invalid way (eg. sending it encapsulated in another object).
By referencing the PHP Library documentation you can see the properties of the objects you can use.

Post method gets converted to GET after redirection

I have one POST call related to search.It is like I am sending some data as parameters to call and some in payload.after getting 302 it gets redirected.But the issue is once it gets redirected,POST call gets converted to GET call and payload is lost.As a result I am unable to get desired search result.Is there anything related to config that I might be missing??
Yes this is the correct behavior. Sounds like you need to disable automatic re-directs for this test, see configure. You can do:
* configure followRedirects = false
And then get the redirect location manually as follows:
* def location = responseHeaders['Location'][0]
Refer to this test for an example: redirect.feature

Problems Connecting to MtGox API 2 with Python

I am writing a trading program that I need to connect to MtGox (a bitcoin exchange) through the API v2. But I keep getting the following error:
URL: 1 https://data.mtgox.com/api/2/BTCUSD/money/bitcoin/address
HTTP Error 403: Forbidden.
Most of my script is a direct copy from here (that is a pastebin link). I just had to change it to work with Python 3.3.
I suspect that it has to do with the part of script where I use base64.b64encode. In my code, I have to encode my strings to utf-8 to use base64.b64encode:
url = self.__url_parts + '2/' + path
api2postdatatohash = (path + chr(0) + post_data).encode('utf-8') #new way to hash for API 2, includes path + NUL
ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()).encode('utf-8'))
# Create header for auth-requiring operations
header = {
"User-Agent": 'Arbitrater',
"Rest-Key": self.key,
"Rest-Sign": ahmac
}
However, with the other guy's script, he doesn't have too:
url = self.__url_parts + '2/' + path
api2postdatatohash = path + chr(0) + post_data #new way to hash for API 2, includes path + NUL
ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()))
# Create header for auth-requiring operations
header = {
"User-Agent": 'genBTC-bot',
"Rest-Key": self.key,
"Rest-Sign": ahmac
}
I'm wondering if that extra encoding is causing my header credentials to be incorrect. I think this is another Python 2 v. Python 3 problem. I don't know how the other guy got away without changing to utf-8, because the script won't run if you try to pass a string to b64encode or hmac. Do you guys see any problems with what I am doing? Is out code equivalent?
This line specifically seems to be the problem -
ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()).encode('utf-8'))
To clarify, hmac.new() creates an object to which you then call digest(). Digest returns a bytes object such as
b.digest()
b'\x92b\x129\xdf\t\xbaPPZ\x00.\x96\xf8%\xaa'
Now, when you call str on this, it turns to
b'\\x92b\\x129\\xdf\\t\\xbaPPZ\\x00.\\x96\\xf8%\\xaa'
So, see what happens there? The byte indicator is now part of the string itself, which you then call encode() on.
str(b.digest()).encode("utf-8")
b"b'\\x92b\\x129\\xdf\\t\\xbaPPZ\\x00.\\x96\\xf8%\\xaa'"
To fix this, as turning bytes into a string back into bytes was unnecessary anyhow(besides problematic), I believe this will work -
ahmac = base64.b64encode(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest())
I believe you are likely to find help in a related question of mine although it deals with the WebSocket API:
Authenticated call to MtGox WebSocket API in Python 3
Also, the HTTP 403 error seems to indicate that there is something fundamentally wrong with the request. Even if you threw the wrong authentication info at the API you should have gotten an error message as a response and not a 403. My best guess is that you are using the wrong HTTP method so check if you are using the appropriate one (GET/POST).