• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 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.android.downloader;
16 
17 import static com.google.common.truth.Truth.assertThat;
18 import static java.nio.charset.StandardCharsets.UTF_8;
19 import static org.junit.Assert.assertThrows;
20 
21 import com.google.common.io.Files;
22 import java.io.File;
23 import java.nio.ByteBuffer;
24 import java.nio.channels.FileChannel;
25 import java.nio.channels.SocketChannel;
26 import java.nio.file.StandardOpenOption;
27 import org.junit.Rule;
28 import org.junit.Test;
29 import org.junit.rules.TemporaryFolder;
30 import org.junit.runner.RunWith;
31 import org.junit.runners.JUnit4;
32 
33 /** Unit tests for IOUtil. */
34 @RunWith(JUnit4.class)
35 public class IOUtilTest {
36   @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
37 
38   @Test
validateChannel_nonBlocking()39   public void validateChannel_nonBlocking() throws Exception {
40     SocketChannel channel = SocketChannel.open();
41     channel.configureBlocking(false);
42     assertThrows(IllegalStateException.class, () -> IOUtil.validateChannel(channel));
43   }
44 
45   @Test
validateChannel_notOpen()46   public void validateChannel_notOpen() throws Exception {
47     File testFile = temporaryFolder.newFile();
48     FileChannel channel = FileChannel.open(testFile.toPath());
49     channel.close();
50 
51     assertThrows(IllegalStateException.class, () -> IOUtil.validateChannel(channel));
52   }
53 
54   @Test
validateChannel_valid()55   public void validateChannel_valid() throws Exception {
56     File testFile = temporaryFolder.newFile();
57     FileChannel channel = FileChannel.open(testFile.toPath());
58     IOUtil.validateChannel(channel);
59   }
60 
61   @Test
blockingWrite()62   public void blockingWrite() throws Exception {
63     String message = "hello world";
64     File testFile = temporaryFolder.newFile();
65 
66     FileChannel channel = FileChannel.open(testFile.toPath(), StandardOpenOption.WRITE);
67     ByteBuffer buffer = ByteBuffer.wrap(message.getBytes(UTF_8));
68     IOUtil.blockingWrite(buffer, channel);
69     channel.close();
70 
71     assertThat(Files.asCharSource(testFile, UTF_8).read()).isEqualTo(message);
72   }
73 }
74