How can i get html headers with phpunit using Selenium2? - selenium

public function testheaders()
{
$url=$this->url('http://www.example.com/index.php');
$kur = get_headers($url);
var_dump($kur);
}
I got the error : get_headers(): Filename cannot be empty.
My class extends PHPUnit_Extensions_Selenium2TestCase like my all my other tests.

get_headers() is a PHP function that will give you the headers return by an HTTP request to a specified url. The parameter you need to give is a string, but $this->url() return an PHPUnit_Selenium-object.
If you want the headers of that known URL, why not do directly?
$kur = get_headers('http://www.example.com/index.php');

Related

How to make a MultiMock Http Callout Test for Salesforce?

If I have an Apex function that is named authorize() that just gets a username, password, and session token, and another function called getURL('id#', 'key'), that takes an id# for the record as a string and a key for the image to return as a string as parameters. getURL calls the authorize function inside it in order to get the credentials for its callout. The authorize is a post request, and the getURL is a get request.
I am trying to figure out how to test both of these callouts just so I can make sure that getURL is returning the proper JSON as a response. It doesn't even have to be the URL yet which is its intention eventually. But I just need to test it to make sure these callouts are working and that I am getting a response back for the 75% code coverage that it needs.
I made a multiRequestMock class that looks like this:
public class MultiRequestMock implements HttpCalloutMock {
Map<String, HttpCalloutMock> requests;
public MultiRequestMock(Map<String, HttpCalloutMock> requests) {
this.requests = requests;
}
public HTTPResponse respond(HTTPRequest req) {
HttpCalloutMock mock = requests.get(req.getEndpoint());
if (mock != null) {
return mock.respond(req);
} else {
throw new MyCustomException('HTTP callout not supported for test methods');
}
}
public void addRequestMock(String url, HttpCalloutMock mock) {
requests.put(url, mock);
}
}
I then began to write a calloutTest.cls file but wasn't sure how to use this mock class in order to test my original functions. Any clarity or assistance on this would be helpful Thank you.
I believe in your calloutTest class you use Test.setMock(HttpCalloutMock.class, new MultiRequestMock(mapOfRequests)); then call the getUrl and/or authorize methods and instead of the request really executing the response returned will be that which is specified in the response(HttpRequest) method you have implemented in the MultiRequestMock class. That is basically how I see it working, for more info and an example you can see this resource on testing callout classes. This will get you the code coverage you need but unfortunately cannot check you are getting the correct JSON response. For this, you may be able to use the dev console and Execute Anonymous?
You may want to look at simplifying your HttpCalloutMock Implementation and think about removing the map from the constructor as this class really only needs to return a simple response then your calloutTest class can be where you make sure the returned response is correct.
Hope this helps

How to write a PHPUnit test for a SOAP server?

UPD. Sorry, guys.
I have an application that acts as a SOAP server, how do I write a PHPUnit test to test it?
SOAP extension is reading data from PHP input stream. You just provide your own data there and create some integration/unit tests for your API.
Take a look at the signature of SoapServer::handle() method. It takes as an argument a string which is a request itself. This parameter is optional and if you don't pass anything in, PHP will just read the data itself. But you can simply override it.
I used streams to do it. First you wrap the SoapServer with your own class like this:
class MyServer
{
/** \SoapServer */
private $soapServer;
public function __construct(\SoapServer $soapServer)
{
$this->soapServer = $soapServer;
}
public function handle(Psr\Http\Message\StreamInterface $inputStream): void
{
$this->soapServer->handle($inputStream->getContent());
}
}
Now you are ready to mock the request.
In your test you can do:
class MyTest extends TestCase
{
public function testMyRequest(): void
{
$mySoapServer = $this->createMySoapServer();
$request = $this->createRequest();
$mySoapServer->handle($request);
}
private function createRequest(): StreamInterface
{
$requestString = '<soap:Envelope></soap:Envelope>';
$fh = fopen('php://temp', 'rw');
fwrite($fh, $requestString);
fseek($fh, SEEK_SET);
return new Psr\Http\Message\StreamInterface\Stream($fh);
}
private function createMySoapServer(): MyServer
{
return new MyServer(new \SoapServer());
}
}
One thing to keep in mind - this test will generate output. You may want to test this output or ignore it. Depends on your use case.
Another side note. What you are asking for has really nothing to do with PHPUnit. It just a matter of designing your SOAP server correctly.
If you are wondering how to set up the stream when you have a live request, this is really simple:
$server->handle(new Psr\Http\Message\StreamInterface\Stream(fopen('php://input', 'r+')));

Akka-http custom 404 page

I'd like to create a custom 404 page in akka-http (high level DSL). This basically means:
Return a page from my static folder (e.g. resources/www/404.html)
Set the result code to ResultCodes.NOT_FOUND
What I tried so far:
getFromResource - I can return the entity, but I can't figure out how to override the HTTP result code for the response, so I can set it to '404'.
complete() - I can return the right code, but I need to read the html page in manually, and build the HttpResponse from ground up. It eventually works, but it's a bit cumbersome.
Am I missing something? Is there an easier way to return a page and customize the result code?
The static page can be returned as the entity of an HttpResponse.
Assuming you have some function of the form
def someFunctionThatCanFail() : Try[HttpResponse] = ???
You will want to use your static page in the event of a failure. You'll first need to create a Source that is based on the static page:
import akka.stream.scaladsl._
import akka.http.scaladsl.model.HttpEntity.Chunked
def createStaticSource(fileName : String) =
FileIO
.fromPath(Paths get fileName)
.map(ChunkStreamPart.apply)
def createChunkedSource(fileName : String) =
Chunked(ContentTypes.`text/html(UTF-8)`, createStaticSource(fileName))
This source can then be placed inside of a response:
def staticResponse =
HttpResponse(status = StatusCodes.NotFound,
entity = createChunkedSource("resources/www/404.html"))
The only thing left to do is to either return the result of the function if it was valid or the static response in the case of a failure:
val route =
get {
complete(someFunctionThatCanFail() getOrElse staticResponse)
}
To expand on Ramon's excellent answer, this works inside a jar file as well:
def createChunkedSource(fileName : String): Chunked = {
def createStaticSource(fileName : String) : Source[ChunkStreamPart, Any] = {
val classLoader = getClass.getClassLoader
StreamConverters.fromInputStream(() => classLoader.getResourceAsStream(fileName)).map(ChunkStreamPart.apply)
}
Chunked(ContentTypes.`text/html(UTF-8)`, createStaticSource(fileName))
}

Accept header precedence with spring-data-rest

I am trying spring-data-rest with mithril.js. However, I keep getting xml response from the repository instead of json.
I have this repository:
#RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends JpaRepository<Person, Long> {
And request with this:
var users = m.request({method: "GET", url: "/api/people/"});
However, I just got a list of string in xml response.
I tried to check the source as below, though I may mislook and point out the wrong source:
Found that mithril set the accept header as
xhr.setRequestHeader("Accept", "application/json, text/*")
mithril source: line 1079
However, it sounds spring-data-rest handle the request with
#ResponseBody
#SuppressWarnings({ "unchecked" })
#RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET, produces = {
"application/x-spring-data-compact+json", "text/uri-list" })
public Resources<?> getCollectionResourceCompact(RootResourceInformation repoRequest, DefaultedPageable pageable,
spring-data-rest source: line 171-173
instead of
#ResponseBody
#RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET)
public Resources<?> getCollectionResource(final RootResourceInformation resourceInformation,
on spring-data-rest source: line 210-213
Is anything wrong on my ajax request?
Use curl to create the request and get that working the way you think it should. After that works, tackle the mithril part.

Request and Response Headers Override using Restler

I am new to restler and trying to do the following things, can't seem to get hold of it
I have this class and method exposed via Restler
class Account {
protected $Api_Version = array('version' => "1.0.2.1234", 'href' => "/");
// Returns the version of the service
// Content-Type: application/vnd.cust.version+json
function version() {
return json_encode($this->version);
}
// Accepts only Content Type: application/vnd.cust.account+json
function postCreate() {
}
}
1) I want to return my own Content-Type to client like in the 'version' method instead of default application/json. In my case its 'application/vnd.cust.version+json'
2) Method postCreate should only accept the request if the Contet-Type is set to 'application/vnd.cust.account+json'. How to check if that header is set in the request.
3) Also in the restler API Explorer, for methond name, how can I show only the method name instead of the 'version.json'. I want to show just 'version' like the method name
Thank you for your help.
Narsi
1) maybe Write your own format? Take a Look at
http://restler3.luracast.com/examples/_003_multiformat/readme.html
2) you could check the headers and throw Exception on wrong one.
Take a Look at this link
http://stackoverflow.com/questions/541430/how-do-i-read-any-request-header-in-php
3) have you tried to and the following line to your Index.php?
Resources::$useFormatAsExtension = false
Hope takes you further on :)
CU
Inge