Line data Source code
1 : // Copyright (C) 2017 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.extensions.restapi.testing; 16 : 17 : import static com.google.common.truth.Truth.assertAbout; 18 : 19 : import com.google.common.truth.FailureMetadata; 20 : import com.google.common.truth.PrimitiveByteArraySubject; 21 : import com.google.common.truth.StringSubject; 22 : import com.google.common.truth.Subject; 23 : import com.google.gerrit.extensions.restapi.BinaryResult; 24 : import com.google.gerrit.truth.OptionalSubject; 25 : import java.io.ByteArrayOutputStream; 26 : import java.io.IOException; 27 : import java.util.Optional; 28 : 29 : public class BinaryResultSubject extends Subject { 30 : 31 : public static BinaryResultSubject assertThat(BinaryResult binaryResult) { 32 1 : return assertAbout(binaryResults()).that(binaryResult); 33 : } 34 : 35 : private static Subject.Factory<BinaryResultSubject, BinaryResult> binaryResults() { 36 4 : return BinaryResultSubject::new; 37 : } 38 : 39 : public static OptionalSubject<BinaryResultSubject, BinaryResult> assertThat( 40 : Optional<BinaryResult> binaryResultOptional) { 41 3 : return OptionalSubject.assertThat(binaryResultOptional, binaryResults()); 42 : } 43 : 44 : private final BinaryResult binaryResult; 45 : 46 : private BinaryResultSubject(FailureMetadata failureMetadata, BinaryResult binaryResult) { 47 4 : super(failureMetadata, binaryResult); 48 4 : this.binaryResult = binaryResult; 49 4 : } 50 : 51 : public StringSubject asString() throws IOException { 52 3 : isNotNull(); 53 : // We shouldn't close the BinaryResult within this method as it might still 54 : // be used afterwards. Besides, closing it doesn't have an effect for most 55 : // implementations of a BinaryResult. 56 3 : return check("asString()").that(binaryResult.asString()); 57 : } 58 : 59 : public PrimitiveByteArraySubject bytes() throws IOException { 60 1 : isNotNull(); 61 : // We shouldn't close the BinaryResult within this method as it might still 62 : // be used afterwards. Besides, closing it doesn't have an effect for most 63 : // implementations of a BinaryResult. 64 1 : ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 65 1 : binaryResult.writeTo(byteArrayOutputStream); 66 1 : byte[] bytes = byteArrayOutputStream.toByteArray(); 67 1 : return check("bytes()").that(bytes); 68 : } 69 : }