URLFetcher { public String fetch(@NotNull final String url) throws IOException { return fetch(url, CONNECTION_READ_TIMEOUT); }  String fetchSafely(@NotNull final String url); String fetch(@NotNull final String url);  }
@Test( expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "no protocol: hello_world") public void checkUnsafeGetUrlFileIsInvalid() throws Exception { String result = urlFetcher.fetch("hello_world"); assertNull(result); }
@Test( expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = ".*url_fetcher_test_resource.json-invalid \\(No such file or directory\\)") public void checkMissingContentUnsafeGet() throws Exception { URL urlJson = getClass().getClassLoader().getResource("devfile/url_fetcher_test_resource.json"); Assert.assertNotNull(urlJson); String content = urlFetcher.fetch(urlJson.toString() + "-invalid"); assertNull(content); }
@Test public void checkDefaultPartialContent() throws IOException { URLConnection urlConnection = Mockito.mock(URLConnection.class); String originalContent = Strings.padEnd("", (int) MAXIMUM_READ_BYTES, 'a'); String extraContent = originalContent + "----"; when(urlConnection.getInputStream()) .thenReturn(new ByteArrayInputStream(extraContent.getBytes(UTF_8))); String readcontent = urlFetcher.fetch(urlConnection); assertEquals(readcontent, originalContent); }
@Test public void testDefaultFetchTimeoutIsSet() throws IOException { URLFetcher fetcher = new TimeoutCheckURLFetcher( timeout -> assertEquals(timeout.intValue(), CONNECTION_READ_TIMEOUT)); fetcher.fetch("http: }
@Test public void testFetchTimeoutIsSet() throws IOException { URLFetcher fetcher = new TimeoutCheckURLFetcher(timeout -> assertEquals(timeout.intValue(), 123)); fetcher.fetch("http: }
@Test(expectedExceptions = IOException.class) public void testExceptionIsThrownOnTimeout() throws IOException { URLFetcher fetcher = new URLFetcher(); URLConnection connection = new URLConnection(new URL("http: @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { throw new SocketTimeoutException("yes"); } }; fetcher.fetch(connection); }