Remove the use of InjectRule in UrlFetchUtilsTest

Random used to be a static variable which requires InjectRule to mock it in unit tests. It is now a singleton, which ensures that the same instance is called every time and Random.nextBytes() generates results that distribute uniformly between each call.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=217592767
This commit is contained in:
jianglai 2018-10-17 14:53:23 -07:00
parent 84c3544097
commit 4140ef6315
5 changed files with 35 additions and 12 deletions

View file

@ -35,9 +35,6 @@ import java.util.Random;
/** Helper methods for the App Engine URL fetch service. */
public final class UrlFetchUtils {
@NonFinalForTesting
private static Random random = new Random();
/** Returns value of first header matching {@code name}. */
public static Optional<String> getHeaderFirst(HTTPResponse rsp, String name) {
return getHeaderFirstInternal(rsp.getHeadersUncombined(), name);
@ -63,11 +60,16 @@ public final class UrlFetchUtils {
*
* <p>This is equivalent to running the command: {@code curl -F fieldName=@payload.txt URL}
*
* @see <a href="http://www.ietf.org/rfc/rfc2388.txt"> RFC2388 - Returning Values from Forms</a>
* @see <a href="http://www.ietf.org/rfc/rfc2388.txt">RFC2388 - Returning Values from Forms</a>
*/
public static void setPayloadMultipart(
HTTPRequest request, String name, String filename, MediaType contentType, String data) {
String boundary = createMultipartBoundary();
HTTPRequest request,
String name,
String filename,
MediaType contentType,
String data,
Random random) {
String boundary = createMultipartBoundary(random);
checkState(
!data.contains(boundary),
"Multipart data contains autogenerated boundary: %s", boundary);
@ -87,7 +89,7 @@ public final class UrlFetchUtils {
request.setPayload(payload);
}
private static String createMultipartBoundary() {
private static String createMultipartBoundary(Random random) {
// Generate 192 random bits (24 bytes) to produce 192/log_2(64) = 192/6 = 32 base64 digits.
byte[] rand = new byte[24];
random.nextBytes(rand);