Home | History | Annotate | Download | only in io
      1 /*
      2  * Copyright (C) 2012 The Guava Authors
      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 
     17 package com.google.common.io;
     18 
     19 import com.google.common.collect.ImmutableSet;
     20 
     21 import java.io.ByteArrayOutputStream;
     22 import java.io.IOException;
     23 import java.io.OutputStream;
     24 
     25 /**
     26  * A byte sink for testing that has configurable behavior.
     27  *
     28  * @author Colin Decker
     29  */
     30 public class TestByteSink extends ByteSink implements TestStreamSupplier {
     31 
     32   private final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     33   private final ImmutableSet<TestOption> options;
     34 
     35   private boolean outputStreamOpened;
     36   private boolean outputStreamClosed;
     37 
     38   public TestByteSink(TestOption... options) {
     39     this.options = ImmutableSet.copyOf(options);
     40   }
     41 
     42   byte[] getBytes() {
     43     return bytes.toByteArray();
     44   }
     45 
     46   @Override
     47   public boolean wasStreamOpened() {
     48     return outputStreamOpened;
     49   }
     50 
     51   @Override
     52   public boolean wasStreamClosed() {
     53     return outputStreamClosed;
     54   }
     55 
     56   @Override
     57   public OutputStream openStream() throws IOException {
     58     outputStreamOpened = true;
     59     bytes.reset(); // truncate
     60     return new Out();
     61   }
     62 
     63   private final class Out extends TestOutputStream {
     64 
     65     public Out() throws IOException {
     66       super(bytes, options);
     67     }
     68 
     69     @Override
     70     public void close() throws IOException {
     71       outputStreamClosed = true;
     72       super.close();
     73     }
     74   }
     75 }
     76