• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.adservices.shared.testing.util;
17 
18 import java.io.ByteArrayOutputStream;
19 import java.io.IOException;
20 import java.io.PrintStream;
21 import java.io.PrintWriter;
22 import java.io.StringWriter;
23 import java.util.Objects;
24 
25 /** Helper class for IO-related stuff. */
26 public final class IoHelper {
27 
28     /**
29      * Converts the contents of a {@link PrintWriter} to a string.
30      *
31      * <p>Typically used to test {@code dump()} methods.
32      */
printWriterToString(ThrowingConsumer<PrintWriter, IOException> consumer)33     public static String printWriterToString(ThrowingConsumer<PrintWriter, IOException> consumer)
34             throws IOException {
35         Objects.requireNonNull(consumer, "consumer cannot be null");
36         try (StringWriter sw = new StringWriter()) {
37             PrintWriter pw = new PrintWriter(sw);
38             consumer.accept(pw);
39             pw.flush();
40             return sw.toString();
41         }
42     }
43 
44     /**
45      * Converts the contents of a {@link PrintStream} to a string.
46      *
47      * <p>Typically used to test {@code dump()} methods.
48      */
printStreamToString(ThrowingConsumer<PrintStream, IOException> consumer)49     public static String printStreamToString(ThrowingConsumer<PrintStream, IOException> consumer)
50             throws IOException {
51         Objects.requireNonNull(consumer, "consumer cannot be null");
52         try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
53             PrintStream ps = new PrintStream(baos, /* autoFlush= */ true);
54             consumer.accept(ps);
55             return baos.toString();
56         }
57     }
58 
IoHelper()59     private IoHelper() {
60         throw new UnsupportedOperationException("Provides only static methods");
61     }
62 }
63