• 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 
22 import com.google.common.base.Charsets;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.testing.NullPointerTester;
25 import java.io.ByteArrayInputStream;
26 import java.io.ByteArrayOutputStream;
27 import java.io.DataInputStream;
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.net.URL;
32 import java.net.URLClassLoader;
33 import java.util.ArrayList;
34 import java.util.List;
35 import junit.framework.TestSuite;
36 
37 /**
38  * Unit test for {@link Resources}.
39  *
40  * @author Chris Nokleberg
41  */
42 
43 public class ResourcesTest extends IoTestCase {
44 
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 
testToToByteArray()65   public void testToToByteArray() throws IOException {
66     byte[] data = Resources.toByteArray(classfile(Resources.class));
67     assertEquals(0xCAFEBABE, new DataInputStream(new ByteArrayInputStream(data)).readInt());
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     try {
109       Resources.getResource("no such resource");
110       fail();
111     } catch (IllegalArgumentException e) {
112       assertThat(e).hasMessageThat().isEqualTo("resource no such resource not found.");
113     }
114   }
115 
testGetResource()116   public void testGetResource() {
117     assertNotNull(Resources.getResource("com/google/common/io/testdata/i18n.txt"));
118   }
119 
testGetResource_relativePath_notFound()120   public void testGetResource_relativePath_notFound() {
121     try {
122       Resources.getResource(getClass(), "com/google/common/io/testdata/i18n.txt");
123       fail();
124     } catch (IllegalArgumentException e) {
125       assertThat(e)
126           .hasMessageThat()
127           .isEqualTo(
128               "resource com/google/common/io/testdata/i18n.txt"
129                   + " relative to com.google.common.io.ResourcesTest not found.");
130     }
131   }
132 
testGetResource_relativePath()133   public void testGetResource_relativePath() {
134     assertNotNull(Resources.getResource(getClass(), "testdata/i18n.txt"));
135   }
136 
testGetResource_contextClassLoader()137   public void testGetResource_contextClassLoader() throws IOException {
138     // Check that we can find a resource if it is visible to the context class
139     // loader, even if it is not visible to the loader of the Resources class.
140 
141     File tempFile = createTempFile();
142     PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
143     writer.println("rud a chur ar an méar fhada");
144     writer.close();
145 
146     // First check that we can't find it without setting the context loader.
147     // This is a sanity check that the test doesn't spuriously pass because
148     // the resource is visible to the system class loader.
149     try {
150       Resources.getResource(tempFile.getName());
151       fail("Should get IllegalArgumentException");
152     } catch (IllegalArgumentException expected) {
153     }
154 
155     // Now set the context loader to one that should find the resource.
156     URL baseUrl = tempFile.getParentFile().toURI().toURL();
157     URLClassLoader loader = new URLClassLoader(new URL[] {baseUrl});
158     ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
159     try {
160       Thread.currentThread().setContextClassLoader(loader);
161       URL url = Resources.getResource(tempFile.getName());
162       String text = Resources.toString(url, Charsets.UTF_8);
163       assertEquals("rud a chur ar an méar fhada\n", text);
164     } finally {
165       Thread.currentThread().setContextClassLoader(oldContextLoader);
166     }
167   }
168 
testGetResource_contextClassLoaderNull()169   public void testGetResource_contextClassLoaderNull() {
170     ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
171     try {
172       Thread.currentThread().setContextClassLoader(null);
173       assertNotNull(Resources.getResource("com/google/common/io/testdata/i18n.txt"));
174       try {
175         Resources.getResource("no such resource");
176         fail("Should get IllegalArgumentException");
177       } catch (IllegalArgumentException expected) {
178       }
179     } finally {
180       Thread.currentThread().setContextClassLoader(oldContextLoader);
181     }
182   }
183 
testNulls()184   public void testNulls() {
185     new NullPointerTester()
186         .setDefault(URL.class, classfile(ResourcesTest.class))
187         .testAllPublicStaticMethods(Resources.class);
188   }
189 
classfile(Class<?> c)190   private static URL classfile(Class<?> c) {
191     return c.getResource(c.getSimpleName() + ".class");
192   }
193 }
194