how to add string to PHPUnit failure message universally - phpunit

I am testing with phpunit and I would like to add the string "**** " to all of the failure message that the developers type in so the message will be easier to identify in the failures. Now there is the information about which test failed and which assertion failed surrounding the message so you have to work a little harder to find the message - I want to make our messages easier to spot.
I could have the developers just add the string to each message - but that's not very DRY. Is there a way to universally reformat the failure messages?

I think you will want to modify the PHPUnit_TextUI_ResultPrinter class.
https://github.com/sebastianbergmann/phpunit/blob/master/src/TextUI/ResultPrinter.php
Have a look at the printDefect... methods. You should be able to prefix something to the output.

Related

Symfony PHPUnit integration test not able to check full body text

My use case is simple: I am sending text emails, i am trying to make integrations tests in order to check the full text body of the message, please note I don't want to check if message contain a string, i am looking for format and structure. No fancy check since it is just text.
The current public API, as in documentation, and as I see in code allows me to check only whether the message contains a string assertEmailTextBodyContains().
I did read: https://symfony.com/doc/current/mailer.html#write-a-functional-test, from MailerAssertionsTrait can only get a RawMessage, i tried, but did not get a strait way to wrap it within an Email.
What am I missing?
Is there any technical/non technical issue preventing to have such Constraint implemented?
Something like: assertEmailTextBodySameAs() for example.
Just for the sake of documentation.
After informing my self more, i realise that in my ignorance i was looking for an idiomatic syntax in the MailerAssertionsTrait instead what i needed was just to use the IsIdentical constraint from phpunit.
$this->assertThat($email->getTextBody(), new IsIdentical($expectedText), 'Mail body are not the same');
Why such assertion is not built in in trait i did assume it is just to keep it simple allowing others like me to extend later on easily, it is just an speculation though.

Diferentiate user not found from wrong credentials

When calling loginWithPassword I receive an error with code 403 in both cases: when the user doesn't exist and when the password is wrong. I know that theirs messages/reasons are different, but I think that comparing with string is not a good practice. Is there a different way of differentiating these cases?
UPDATE Using accounts-password
No real way of differentiating other than checking the error description string (that is what it is for).
You can always implement your own mechanism server-side (e.g, a method), but the default one sends a numeric error code (normally corresponding to the HTTP code - in this case, 403 forbidden), accompanied by a string.
They have not changed recently and it is fairly safe to depend on them, especially if it is not something mission-critical.
You could implement a method that checks for the existence of a user and then call that after a failed login attempt. If the user exists then you can display a bad password warning.
You could even check existence before the password is typed and put a green checkmark next to the username field if the user is found or a red X otherwise.
There are many ways to do this.

HttpsURLConnection.getResponseCode() returning -1 instead 1001 or 1002 or 1003

I am using HttpsURLConnection call to get the response from HTTP servlet with message and error code. Following is some code snippet from my code:-
connection = (HttpsURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Headers
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "text/xml");
connection.setRequestProperty("Accept", "text/plain");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Authorization", authorization);
connection.connect();
From HTTPServlet side, i am setting statuscode and description:-
response.setStatus(code);
response.getWriter().write(returnDescription);
All the above code is existing code and it is working fine except. It should return status code as response code. But few codes are not working like 1001,1002 or 1003. i.e if i set response.setStatus(1001) it returns -1 as responseCode() at client side with "java.io.IOException: Invalid Http response". For any other integer value like 1101,1102, 1232 etc it works fine. I debugged the code and found servlet is setting correct values but client is not able to parse response. And as you change status code with some other numeric value, it get started working correctly! I am getting same behavior in HTTP as well as with HTTPS.
It seems like these non working codes are predefined codes with specific objective and can not be used as status code but i didnt find anything on web. Did anyone experienced the same and what could be the reason.
Thanks in advance! :)
Short version: OpenJDK and others have a parseHttpHeader method that parses exactly three chars of the HTTP status code number, and anything starting with the string '100' is treated as an HTTP continue. The non-continued nature of this servlet conversation confused the client, so it couldn't open the output stream and gave up.
WAAAAY long version:
This one kinda bugged me, because only 100-599 (ish, actually fewer than this) status codes should really work at all. RFC2616 says codes must be three digits and (paraphrasing) you need necessarily only understand the class of the first digit (to allow for extensions).
OpenJDK 6's HttpURLConnection implementation was the first I checked (since you didn't specify) and the code basically does:
grab the first line of the response.
look for HTTP/1. (Doesn't care about 0.9 apparently, and ignores the second digit).
look for everything at the end for the text reason.
try to parse whatever int is in the middle.
GNU Classpath does pretty much the same.
Notably, OpenJDK doesn't particularly vet that against the RFC rules. You could put a billion in there and it would be more-or-less OK with that (at least as far as getResponseCode() cares, anyway...it looks like getInputStream() will barf on any code >=400 in the concrete implementation in sun.net.www.protocol...).
In any case, that didn't answer why you were seeing this oddball behavior for only 100x. OpenJDK looks like it should have thrown IOException of the form "Server returned HTTP 1234...
...or so I thought. HttpURLConnection is abstract, and so a concrete implementation must override at least the abstract methods. Well, the concrete implementation of HttpURLConnection, the abstract's version of getResponseCode() is sorta ignored. Kinda. This implementation calls sun.net.www.http.HttpClient's parseHTTP as part of opening the input stream, which parses out the HTTP/1. and then exactly THREE characters of the code (and then does convoluted things to massage the input stream to having all that stuff retroactively shoved back in in something called an HttpCapture. Yuck.). And if that three chars happens to come out to 100, then the client thinks it has to continue the conversation to get a working InputStream.
Since your servlet is actually done with the transaction already and it's not continuing, the client is getting confused about WTF your servlet is doing and is therefore returning an error (as it should per RFC).
So mystery solved I think. You could put pretty much anything beginning with "100" and get the same behavior (even "100xyz" if your servlet API lets you).
(Android, btw, also does this three-char parse.)
This all technically violates RFC (though, honestly, it's kind of a silly bug). Strictly speaking, only 2xx codes should be treated as totally OK to pass unmolested, but probably you could use a "000" status and pass OK (again, assuming your API lets you put an arbitrary string in there).
Hope that answers your question!

Running Go from the command line nested JSON

I can think of workarounds on how to get this working however I'm interested in finding out if there's a solution to this specific problem.
I've got a go program which requires a json string arguement:
go run main.go "{ \"field\" : \"value\" }"
No problems so far. However, am I able to run from the command line if one of the json values is another json string?
go run main.go "{ \"json-string\" : \"{\"nestedfield\" : \"nestedvalue\"}\" }"
It would seem that adding escape characters incorrectly matches up the opening and closing quotes. Am I minuderstanding how this is done or is it (and this is the side I'm coming down on) simply not possible?
To reiterate, this is a question that has piqued my curiosity - I'm aware of alternative approaches - I'm hoping for input related to this specific problem.
Why don't you just put your json config to the file and provide config file name to your application using flag package
Based on the feedback from wiredeye I went down the argument route instead. I've modified the program to run on:
go run main.go field:value field2:value json-string:"{\"nestedfield\":nestedvalue}"
I can then iterate over the os.Args and get the nested json within my program. I'm not using flags directly as I don't know the amount of inputs into the program which would have required me to use duplicate flags (not supported) or parse the flag to a collection (doesn't seem to be supported).
Thanks wiredeye

Custom text for HTTP API status code

I am writing a new endpoint in my HTTP service that is built on the Play framework, and am returning a custom status code for a particular error (442 in this case). When I test the endpoint with cURL, I receive the error code as expected:
...
< HTTP/1.1 442 Client Error (442)
....
And the same with Postman REST Client:
What I would like to do is customize the "Client Error" text, such that the response would actually read something like:
442 Forced Password Reset
Is this possible, or is it in the spec somewhere that any custom status codes of the 4xx class are to be interpreted by all clients simply as "Client Error"?
(I have been looking through the relevant Play documentation on Statuses but don't see any option to customize the text—only the status code integer itself.)
Looking through the source code it didn't take me long to find the following:
Play just stores the status code in the RepsonseHeader, not the string
Play uses Netty, and turns the status code into a HttpResponseStatus using valueOf, which is basically just a case statement over the status codes, with defaults based on the range if it isn't standard.
Although you could define a new Netty HttpResponseStatus with the reason phrase you want, there isn't any way to add it to the valueOf method (it's static).
So, there isn't any really good solution without rewriting some parts of Play!.
You might be able to use some sort of post-filter to modify the response and change the reason phrase, but I don't know how that would work, or even if it is possible to write those kinds of filters in Play!.
Finally, the reason phrase isn't really that important, as clients generally don't (and shouldn't) actually parse it.

Resources