• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 static com.google.common.base.CharMatcher.whitespace;
20 import static com.google.common.truth.Truth.assertThat;
21 import static org.junit.Assert.assertThrows;
22 
23 import com.google.common.base.Charsets;
24 import com.google.common.collect.ImmutableList;
25 import com.google.common.testing.NullPointerTester;
26 import java.io.ByteArrayOutputStream;
27 import java.io.File;
28 import java.io.IOException;
29 import java.io.PrintWriter;
30 import java.net.URL;
31 import java.net.URLClassLoader;
32 import java.util.ArrayList;
33 import java.util.List;
34 import junit.framework.TestSuite;
35 
36 /**
37  * Unit test for {@link Resources}.
38  *
39  * @author Chris Nokleberg
40  */
41 
42 public class ResourcesTest extends IoTestCase {
43 
44   @AndroidIncompatible // wouldn't run anyway, but strip the source entirely because of b/230620681
suite()45   public static TestSuite suite() {
46     TestSuite suite = new TestSuite();
47     suite.addTest(
48         ByteSourceTester.tests(
49             "Resources.asByteSource[URL]", SourceSinkFactories.urlByteSourceFactory(), true));
50     suite.addTest(
51         CharSourceTester.tests(
52             "Resources.asCharSource[URL, Charset]",
53             SourceSinkFactories.urlCharSourceFactory(),
54             false));
55     suite.addTestSuite(ResourcesTest.class);
56     return suite;
57   }
58 
testToString()59   public void testToString() throws IOException {
60     URL resource = getClass().getResource("testdata/i18n.txt");
61     assertEquals(I18N, Resources.toString(resource, Charsets.UTF_8));
62     assertThat(Resources.toString(resource, Charsets.US_ASCII)).isNotEqualTo(I18N);
63   }
64 
testToByteArray()65   public void testToByteArray() throws IOException {
66     URL resource = getClass().getResource("testdata/i18n.txt");
67     assertThat(Resources.toByteArray(resource)).isEqualTo(I18N.getBytes(Charsets.UTF_8));
68   }
69 
testReadLines()70   public void testReadLines() throws IOException {
71     // TODO(chrisn): Check in a better resource
72     URL resource = getClass().getResource("testdata/i18n.txt");
73     assertEquals(ImmutableList.of(I18N), Resources.readLines(resource, Charsets.UTF_8));
74   }
75 
testReadLines_withLineProcessor()76   public void testReadLines_withLineProcessor() throws IOException {
77     URL resource = getClass().getResource("testdata/alice_in_wonderland.txt");
78     LineProcessor<List<String>> collectAndLowercaseAndTrim =
79         new LineProcessor<List<String>>() {
80           List<String> collector = new ArrayList<>();
81 
82           @Override
83           public boolean processLine(String line) {
84             collector.add(whitespace().trimFrom(line));
85             return true;
86           }
87 
88           @Override
89           public List<String> getResult() {
90             return collector;
91           }
92         };
93     List<String> result =
94         Resources.readLines(resource, Charsets.US_ASCII, collectAndLowercaseAndTrim);
95     assertEquals(3600, result.size());
96     assertEquals("ALICE'S ADVENTURES IN WONDERLAND", result.get(0));
97     assertEquals("THE END", result.get(result.size() - 1));
98   }
99 
testCopyToOutputStream()100   public void testCopyToOutputStream() throws IOException {
101     ByteArrayOutputStream out = new ByteArrayOutputStream();
102     URL resource = getClass().getResource("testdata/i18n.txt");
103     Resources.copy(resource, out);
104     assertEquals(I18N, out.toString("UTF-8"));
105   }
106 
testGetResource_notFound()107   public void testGetResource_notFound() {
108     IllegalArgumentException e =
109         assertThrows(
110             IllegalArgumentException.class, () -> Resources.getResource("no such resource"));
111     assertThat(e).hasMessageThat().isEqualTo("resource no such resource not found.");
112   }
113 
testGetResource()114   public void testGetResource() {
115     assertNotNull(Resources.getResource("com/google/common/io/testdata/i18n.txt"));
116   }
117 
testGetResource_relativePath_notFound()118   public void testGetResource_relativePath_notFound() {
119     IllegalArgumentException e =
120         assertThrows(
121             IllegalArgumentException.class,
122             () -> Resources.getResource(getClass(), "com/google/common/io/testdata/i18n.txt"));
123     assertThat(e)
124         .hasMessageThat()
125         .isEqualTo(
126             "resource com/google/common/io/testdata/i18n.txt"
127                 + " relative to com.google.common.io.ResourcesTest not found.");
128   }
129 
testGetResource_relativePath()130   public void testGetResource_relativePath() {
131     assertNotNull(Resources.getResource(getClass(), "testdata/i18n.txt"));
132   }
133 
testGetResource_contextClassLoader()134   public void testGetResource_contextClassLoader() throws IOException {
135     // Check that we can find a resource if it is visible to the context class
136     // loader, even if it is not visible to the loader of the Resources class.
137 
138     File tempFile = createTempFile();
139     PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
140     writer.println("rud a chur ar an méar fhada");
141     writer.close();
142 
143     // First check that we can't find it without setting the context loader.
144     // This is a sanity check that the test doesn't spuriously pass because
145     // the resource is visible to the system class loader.
146     assertThrows(IllegalArgumentException.class, () -> Resources.getResource(tempFile.getName()));
147 
148     // Now set the context loader to one that should find the resource.
149     URL baseUrl = tempFile.getParentFile().toURI().toURL();
150     URLClassLoader loader = new URLClassLoader(new URL[] {baseUrl});
151     ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
152     try {
153       Thread.currentThread().setContextClassLoader(loader);
154       URL url = Resources.getResource(tempFile.getName());
155       String text = Resources.toString(url, Charsets.UTF_8);
156       assertEquals("rud a chur ar an méar fhada" + System.lineSeparator(), text);
157     } finally {
158       Thread.currentThread().setContextClassLoader(oldContextLoader);
159     }
160   }
161 
testGetResource_contextClassLoaderNull()162   public void testGetResource_contextClassLoaderNull() {
163     ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
164     try {
165       Thread.currentThread().setContextClassLoader(null);
166       assertNotNull(Resources.getResource("com/google/common/io/testdata/i18n.txt"));
167       assertThrows(IllegalArgumentException.class, () -> Resources.getResource("no such resource"));
168     } finally {
169       Thread.currentThread().setContextClassLoader(oldContextLoader);
170     }
171   }
172 
173   @AndroidIncompatible // .class files aren't available
testNulls()174   public void testNulls() {
175     new NullPointerTester()
176         .setDefault(URL.class, classfile(ResourcesTest.class))
177         .testAllPublicStaticMethods(Resources.class);
178   }
179 
classfile(Class<?> c)180   private static URL classfile(Class<?> c) {
181     return c.getResource(c.getSimpleName() + ".class");
182   }
183 }
184