1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.util;
15
16 import java.io.BufferedReader;
17 import java.io.File;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.io.PrintWriter;
22 import java.net.MalformedURLException;
23 import java.net.URL;
24
25 import org.junit.jupiter.api.Assertions;
26 import org.junit.jupiter.api.Test;
27
28
29
30
31
32
33 public class LocationUtilTest {
34
35 private static final String TEST_CLASSPATH_RESOURCE = "util/testResource.txt";
36 private static final String TEST_PATTERN = "TEST RESOURCE";
37
38 @Test
39 public void testImplicitClasspathUrl() throws Exception {
40 URL url = LocationUtil.urlForResource(TEST_CLASSPATH_RESOURCE);
41 validateResource(url);
42 }
43
44 @Test
45 public void testExplicitClasspathUrl() throws Exception {
46 URL url = LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + TEST_CLASSPATH_RESOURCE);
47 validateResource(url);
48 }
49
50 @Test
51 public void testExplicitClasspathUrlWithLeadingSlash() throws Exception {
52 URL url = LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + "/" + TEST_CLASSPATH_RESOURCE);
53 validateResource(url);
54 }
55
56 @Test
57 public void testExplicitClasspathUrlEmptyPath() throws Exception {
58 Assertions.assertThrows(MalformedURLException.class, () -> {
59 LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME);
60 });
61 }
62
63 @Test
64 public void testExplicitClasspathUrlWithRootPath() throws Exception {
65 Assertions.assertThrows(MalformedURLException.class, () -> {
66 LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + "/");
67 });
68 }
69
70 @Test
71 public void testFileUrl() throws Exception {
72 File file = File.createTempFile("testResource", ".txt");
73 file.deleteOnExit();
74 PrintWriter writer = new PrintWriter(file);
75 writer.println(TEST_PATTERN);
76 writer.close();
77 URL url = file.toURI().toURL();
78 validateResource(url);
79 }
80
81 private void validateResource(URL url) throws IOException {
82 InputStream inputStream = url.openStream();
83 try {
84 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
85 String line = reader.readLine();
86 Assertions.assertEquals(TEST_PATTERN, line);
87 } finally {
88 try {
89 inputStream.close();
90 } catch (IOException ex) {
91
92 ex.printStackTrace(System.err);
93 }
94 }
95 }
96
97 }