merge with feature/ui-extensions branch

This commit is contained in:
Sebastian Sdorra
2018-08-30 12:15:17 +02:00
1508 changed files with 29291 additions and 203236 deletions

View File

@@ -0,0 +1,51 @@
package sonia.scm;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.junit.Assert.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ForwardingPushStateDispatcherTest {
@Mock
private HttpServletRequest request;
@Mock
private RequestDispatcher requestDispatcher;
@Mock
private HttpServletResponse response;
private ForwardingPushStateDispatcher dispatcher = new ForwardingPushStateDispatcher();
@Test
public void testDispatch() throws ServletException, IOException {
when(request.getRequestDispatcher("/index.html")).thenReturn(requestDispatcher);
dispatcher.dispatch(request, response, "/something");
verify(requestDispatcher).forward(request, response);
}
@Test(expected = IOException.class)
public void testWrapServletException() throws ServletException, IOException {
when(request.getRequestDispatcher("/index.html")).thenReturn(requestDispatcher);
doThrow(ServletException.class).when(requestDispatcher).forward(request, response);
dispatcher.dispatch(request, response, "/something");
}
}

View File

@@ -0,0 +1,174 @@
package sonia.scm;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ProxyPushStateDispatcherTest {
private ProxyPushStateDispatcher dispatcher;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private HttpURLConnection connection;
@Before
public void setUp() {
dispatcher = new ProxyPushStateDispatcher("http://hitchhiker.com", url -> connection);
}
@Test
public void testWithGetRequest() throws IOException {
// configure request mock
when(request.getMethod()).thenReturn("GET");
when(request.getHeaderNames()).thenReturn(toEnum("Content-Type"));
when(request.getHeaders("Content-Type")).thenReturn(toEnum("application/json"));
// configure proxy url connection mock
byte[] data = "hitchhicker".getBytes(Charsets.UTF_8);
when(connection.getErrorStream()).thenReturn(null);
when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(data));
Map<String, List<String>> headerFields = new HashMap<>();
headerFields.put("Content-Type", Lists.newArrayList("application/yaml"));
when(connection.getHeaderFields()).thenReturn(headerFields);
when(connection.getResponseCode()).thenReturn(200);
when(connection.getContentLength()).thenReturn(data.length);
// configure response mock
DevServletOutputStream output = new DevServletOutputStream();
when(response.getOutputStream()).thenReturn(output);
dispatcher.dispatch(request, response, "/people/trillian");
// verify connection
verify(connection).setRequestMethod("GET");
verify(connection).setRequestProperty("Content-Type", "application/json");
// verify response
verify(response).setStatus(200);
verify(response).addHeader("Content-Type", "application/yaml");
assertEquals("hitchhicker", output.stream.toString());
}
@Test
public void testGetNotFound() throws IOException {
// configure request mock
when(request.getMethod()).thenReturn("GET");
when(request.getHeaderNames()).thenReturn(toEnum("Content-Type"));
when(request.getHeaders("Content-Type")).thenReturn(toEnum("application/json"));
// configure proxy url connection mock
byte[] data = "hitchhicker".getBytes(Charsets.UTF_8);
when(connection.getErrorStream()).thenReturn(new ByteArrayInputStream(data));
Map<String, List<String>> headerFields = new HashMap<>();
headerFields.put("Content-Type", Lists.newArrayList("application/yaml"));
when(connection.getHeaderFields()).thenReturn(headerFields);
when(connection.getResponseCode()).thenReturn(404);
when(connection.getContentLength()).thenReturn(data.length);
// configure response mock
DevServletOutputStream output = new DevServletOutputStream();
when(response.getOutputStream()).thenReturn(output);
dispatcher.dispatch(request, response, "/people/trillian");
// verify connection
verify(connection).setRequestMethod("GET");
verify(connection).setRequestProperty("Content-Type", "application/json");
// verify response
verify(response).setStatus(404);
verify(response).addHeader("Content-Type", "application/yaml");
assertEquals("hitchhicker", output.stream.toString());
}
@Test
public void testWithPOSTRequest() throws IOException {
// configure request mock
when(request.getMethod()).thenReturn("POST");
when(request.getHeaderNames()).thenReturn(toEnum());
when(request.getInputStream()).thenReturn(new DevServletInputStream("hitchhiker"));
when(request.getContentLength()).thenReturn(1);
// configure proxy url connection mock
Map<String, List<String>> headerFields = new HashMap<>();
when(connection.getHeaderFields()).thenReturn(headerFields);
when(connection.getResponseCode()).thenReturn(204);
ByteArrayOutputStream output = new ByteArrayOutputStream();
when(connection.getOutputStream()).thenReturn(output);
dispatcher.dispatch(request, response, "/people/trillian");
// verify connection
verify(connection).setRequestMethod("POST");
assertEquals("hitchhiker", output.toString());
// verify response
verify(response).setStatus(204);
}
private Enumeration<String> toEnum(String... values) {
Set<String> set = ImmutableSet.copyOf(values);
return toEnum(set);
}
private <T> Enumeration<T> toEnum(Collection<T> collection) {
return new Vector<>(collection).elements();
}
private class DevServletInputStream extends ServletInputStream {
private InputStream inputStream;
private DevServletInputStream(String content) {
inputStream = new ByteArrayInputStream(content.getBytes(Charsets.UTF_8));
}
@Override
public int read() throws IOException {
return inputStream.read();
}
}
private class DevServletOutputStream extends ServletOutputStream {
private ByteArrayOutputStream stream = new ByteArrayOutputStream();
@Override
public void write(int b) {
stream.write(b);
}
}
}

View File

@@ -0,0 +1,31 @@
package sonia.scm;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.*;
public class PushStateDispatcherProviderTest {
private PushStateDispatcherProvider provider = new PushStateDispatcherProvider();
@Test
public void testGetProxyPushStateWithPropertySet() {
System.setProperty(PushStateDispatcherProvider.PROPERTY_TARGET, "http://localhost:9966");
PushStateDispatcher dispatcher = provider.get();
Assertions.assertThat(dispatcher).isInstanceOf(ProxyPushStateDispatcher.class);
}
@Test
public void testGetProxyPushStateWithoutProperty() {
PushStateDispatcher dispatcher = provider.get();
Assertions.assertThat(dispatcher).isInstanceOf(ForwardingPushStateDispatcher.class);
}
@After
public void cleanupSystemProperty() {
System.clearProperty(PushStateDispatcherProvider.PROPERTY_TARGET);
}
}

View File

@@ -0,0 +1,126 @@
package sonia.scm;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import sonia.scm.plugin.PluginLoader;
import sonia.scm.plugin.UberWebResourceLoader;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class WebResourceServletTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private PluginLoader pluginLoader;
@Mock
private UberWebResourceLoader webResourceLoader;
@Mock
private PushStateDispatcher pushStateDispatcher;
private WebResourceServlet servlet;
@Before
public void setUpMocks() {
when(pluginLoader.getUberWebResourceLoader()).thenReturn(webResourceLoader);
when(request.getContextPath()).thenReturn("/scm");
servlet = new WebResourceServlet(pluginLoader, pushStateDispatcher);
}
@Test
public void testPattern() {
assertTrue("/some/resource".matches(WebResourceServlet.PATTERN));
assertTrue("/favicon.ico".matches(WebResourceServlet.PATTERN));
assertTrue("/other.html".matches(WebResourceServlet.PATTERN));
assertFalse("/api/v2/repositories".matches(WebResourceServlet.PATTERN));
// exclude old style ui template servlets
assertTrue("/".matches(WebResourceServlet.PATTERN));
assertTrue("/index.html".matches(WebResourceServlet.PATTERN));
assertTrue("/error.html".matches(WebResourceServlet.PATTERN));
assertTrue("/plugins/resources/js/sonia/scm/hg.config-wizard.js".matches(WebResourceServlet.PATTERN));
}
@Test
public void testDoGetWithNonExistingResource() throws IOException {
when(request.getRequestURI()).thenReturn("/scm/awesome.jpg");
servlet.doGet(request, response);
verify(pushStateDispatcher).dispatch(request, response, "/awesome.jpg");
}
@Test
public void testDoGet() throws IOException {
when(request.getRequestURI()).thenReturn("/scm/README.txt");
TestingOutputServletOutputStream output = new TestingOutputServletOutputStream();
when(response.getOutputStream()).thenReturn(output);
File file = temporaryFolder.newFile();
Files.write("hello".getBytes(Charsets.UTF_8), file);
when(webResourceLoader.getResource("/README.txt")).thenReturn(file.toURI().toURL());
servlet.doGet(request, response);
assertEquals("hello", output.buffer.toString());
}
@Test
public void testDoGetWithError() throws IOException {
when(request.getRequestURI()).thenReturn("/scm/README.txt");
ServletOutputStream output = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(output);
File file = temporaryFolder.newFile();
assertTrue(file.delete());
when(webResourceLoader.getResource("/README.txt")).thenReturn(file.toURI().toURL());
servlet.doGet(request, response);
verify(output, never()).write(anyInt());
verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
@Test
public void testDoGetWithDispatcherException() throws IOException {
when(request.getRequestURI()).thenReturn("/scm/awesome.jpg");
doThrow(IOException.class).when(pushStateDispatcher).dispatch(request, response, "/awesome.jpg");
servlet.doGet(request, response);
verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
private static class TestingOutputServletOutputStream extends ServletOutputStream {
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
@Override
public void write(int b) {
buffer.write(b);
}
}
}

View File

@@ -28,6 +28,8 @@ public class ResourceLinksMock {
when(resourceLinks.branch()).thenReturn(new ResourceLinks.BranchLinks(uriInfo));
when(resourceLinks.repositoryType()).thenReturn(new ResourceLinks.RepositoryTypeLinks(uriInfo));
when(resourceLinks.repositoryTypeCollection()).thenReturn(new ResourceLinks.RepositoryTypeCollectionLinks(uriInfo));
when(resourceLinks.uiPluginCollection()).thenReturn(new ResourceLinks.UIPluginCollectionLinks(uriInfo));
when(resourceLinks.uiPlugin()).thenReturn(new ResourceLinks.UIPluginLinks(uriInfo));
return resourceLinks;
}

View File

@@ -0,0 +1,200 @@
package sonia.scm.api.v2.resources;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.util.Providers;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import sonia.scm.plugin.*;
import sonia.scm.web.VndMediaType;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.Silent.class)
public class UIRootResourceTest {
private final Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
@Mock
private PluginLoader pluginLoader;
@Mock
private HttpServletRequest request;
private final URI baseUri = URI.create("/");
private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri);
@Before
public void setUpRestService() {
UIPluginDtoMapper mapper = new UIPluginDtoMapper(resourceLinks, request);
UIPluginDtoCollectionMapper collectionMapper = new UIPluginDtoCollectionMapper(resourceLinks, mapper);
UIPluginResource pluginResource = new UIPluginResource(pluginLoader, collectionMapper, mapper);
UIRootResource rootResource = new UIRootResource(Providers.of(pluginResource));
dispatcher.getRegistry().addSingletonResource(rootResource);
}
@Test
public void shouldHaveVndCollectionMediaType() throws URISyntaxException {
MockHttpRequest request = MockHttpRequest.get("/v2/ui/plugins");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_OK, response.getStatus());
String contentType = response.getOutputHeaders().getFirst("Content-Type").toString();
assertThat(VndMediaType.UI_PLUGIN_COLLECTION, equalToIgnoringCase(contentType));
}
@Test
public void shouldReturnNotFoundIfPluginNotAvailable() throws URISyntaxException {
MockHttpRequest request = MockHttpRequest.get("/v2/ui/plugins/awesome");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_NOT_FOUND, response.getStatus());
}
@Test
public void shouldReturnNotFoundIfPluginHasNoResources() throws URISyntaxException {
mockPlugins(mockPlugin("awesome"));
MockHttpRequest request = MockHttpRequest.get("/v2/ui/plugins/awesome");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_NOT_FOUND, response.getStatus());
}
@Test
public void shouldReturnPlugin() throws URISyntaxException {
mockPlugins(mockPlugin("awesome", "Awesome", createPluginResources("my/awesome.bundle.js")));
MockHttpRequest request = MockHttpRequest.get("/v2/ui/plugins/awesome");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_OK, response.getStatus());
assertTrue(response.getContentAsString().contains("Awesome"));
assertTrue(response.getContentAsString().contains("my/awesome.bundle.js"));
}
@Test
public void shouldReturnPlugins() throws URISyntaxException {
mockPlugins(
mockPlugin("awesome", "Awesome", createPluginResources("my/awesome.bundle.js")),
mockPlugin("special", "Special", createPluginResources("my/special.bundle.js"))
);
MockHttpRequest request = MockHttpRequest.get("/v2/ui/plugins");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_OK, response.getStatus());
assertTrue(response.getContentAsString().contains("Awesome"));
assertTrue(response.getContentAsString().contains("my/awesome.bundle.js"));
assertTrue(response.getContentAsString().contains("Special"));
assertTrue(response.getContentAsString().contains("my/special.bundle.js"));
}
@Test
public void shouldNotReturnPluginsWithoutResources() throws URISyntaxException {
mockPlugins(
mockPlugin("awesome", "Awesome", createPluginResources("my/awesome.bundle.js")),
mockPlugin("special")
);
MockHttpRequest request = MockHttpRequest.get("/v2/ui/plugins");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_OK, response.getStatus());
assertTrue(response.getContentAsString().contains("Awesome"));
assertTrue(response.getContentAsString().contains("my/awesome.bundle.js"));
assertFalse(response.getContentAsString().contains("Special"));
}
@Test
public void shouldHaveSelfLink() throws Exception {
mockPlugins(mockPlugin("awesome", "Awesome", createPluginResources("my/bundle.js")));
String uri = "/v2/ui/plugins/awesome";
MockHttpRequest request = MockHttpRequest.get(uri);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_OK, response.getStatus());
assertTrue(response.getContentAsString().contains("\"self\":{\"href\":\"" + uri + "\"}"));
}
@Test
public void shouldHaveBundleWithContextPath() throws Exception {
when(request.getContextPath()).thenReturn("/scm");
mockPlugins(mockPlugin("awesome", "Awesome", createPluginResources("my/bundle.js")));
String uri = "/v2/ui/plugins/awesome";
MockHttpRequest request = MockHttpRequest.get(uri);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_OK, response.getStatus());
System.out.println();
assertTrue(response.getContentAsString().contains("/scm/my/bundle.js"));
}
private void mockPlugins(PluginWrapper... plugins) {
when(pluginLoader.getInstalledPlugins()).thenReturn(Lists.newArrayList(plugins));
}
private PluginResources createPluginResources(String... bundles) {
HashSet<String> scripts = Sets.newHashSet(bundles);
HashSet<String> styles = Sets.newHashSet();
return new PluginResources(scripts, styles);
}
private PluginWrapper mockPlugin(String id) {
return mockPlugin(id, id, null);
}
private PluginWrapper mockPlugin(String id, String name, PluginResources pluginResources) {
PluginWrapper wrapper = mock(PluginWrapper.class);
when(wrapper.getId()).thenReturn(id);
Plugin plugin = mock(Plugin.class);
when(wrapper.getPlugin()).thenReturn(plugin);
when(plugin.getResources()).thenReturn(pluginResources);
PluginInformation information = mock(PluginInformation.class);
when(plugin.getInformation()).thenReturn(information);
when(information.getName()).thenReturn(name);
return wrapper;
}
}

View File

@@ -36,6 +36,7 @@ package sonia.scm.plugin;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.collect.Lists;
import org.assertj.core.api.Assertions;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -52,9 +53,8 @@ import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
//~--- JDK imports ------------------------------------------------------------
@@ -143,8 +143,7 @@ public class DefaultUberWebResourceLoaderTest extends WebResourceLoaderTestBase
when(servletContext.getResource("/myresource")).thenReturn(SCM_MANAGER);
WebResourceLoader resourceLoader =
new DefaultUberWebResourceLoader(servletContext,
new ArrayList<PluginWrapper>());
new DefaultUberWebResourceLoader(servletContext, new ArrayList<>());
URL resource = resourceLoader.getResource("/myresource");
assertSame(SCM_MANAGER, resource);
@@ -173,6 +172,50 @@ public class DefaultUberWebResourceLoaderTest extends WebResourceLoaderTestBase
containsInAnyOrder(file.toURI().toURL(), BITBUCKET));
}
@Test
public void shouldReturnNullForDirectoryFromServletContext() throws IOException {
URL url = temp.newFolder().toURI().toURL();
when(servletContext.getResource("/myresource")).thenReturn(url);
WebResourceLoader resourceLoader =
new DefaultUberWebResourceLoader(servletContext, new ArrayList<>());
assertNull(resourceLoader.getResource("/myresource"));
}
@Test
public void shouldReturnNullForDirectoryFromPlugin() throws IOException {
URL url = temp.newFolder().toURI().toURL();
WebResourceLoader loader = mock(WebResourceLoader.class);
when(loader.getResource("/myresource")).thenReturn(url);
PluginWrapper pluginWrapper = mock(PluginWrapper.class);
when(pluginWrapper.getWebResourceLoader()).thenReturn(loader);
WebResourceLoader resourceLoader =
new DefaultUberWebResourceLoader(servletContext, Lists.newArrayList(pluginWrapper));
assertNull(resourceLoader.getResource("/myresource"));
}
@Test
public void shouldReturnNullForDirectories() throws IOException {
URL url = temp.newFolder().toURI().toURL();
when(servletContext.getResource("/myresource")).thenReturn(url);
WebResourceLoader loader = mock(WebResourceLoader.class);
when(loader.getResource("/myresource")).thenReturn(url);
PluginWrapper pluginWrapper = mock(PluginWrapper.class);
when(pluginWrapper.getWebResourceLoader()).thenReturn(loader);
UberWebResourceLoader resourceLoader =
new DefaultUberWebResourceLoader(servletContext, Lists.newArrayList(pluginWrapper));
List<URL> resources = resourceLoader.getResources("/myresource");
Assertions.assertThat(resources).isEmpty();
}
/**
* Method description
*

View File

@@ -54,15 +54,18 @@ import java.net.URL;
public class PathWebResourceLoaderTest extends WebResourceLoaderTestBase
{
/**
* Method description
*
*
* @throws IOException
*/
@Test
public void testGetResource() throws IOException
{
public void testGetNullForDirectories() throws IOException {
File directory = temp.newFolder();
assertTrue(new File(directory, "awesome").mkdir());
WebResourceLoader resourceLoader = new PathWebResourceLoader(directory.toPath());
assertNull(resourceLoader.getResource("awesome"));
}
@Test
public void testGetResource() throws IOException {
File directory = temp.newFolder();
URL url = file(directory, "myresource").toURI().toURL();
@@ -74,7 +77,4 @@ public class PathWebResourceLoaderTest extends WebResourceLoaderTestBase
assertNull(resourceLoader.getResource("other"));
}
//~--- fields ---------------------------------------------------------------
}

View File

@@ -1,95 +0,0 @@
/***
* Copyright (c) 2015, Sebastian Sdorra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of SCM-Manager; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* https://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.resources;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.Matchers.*;
import org.mockito.junit.MockitoJUnitRunner;
import sonia.scm.plugin.PluginLoader;
/**
* Unit tests for {@link AbstractResourceManager}.
*
* @author Sebastian Sdorra
*/
@RunWith(MockitoJUnitRunner.class)
public class AbstractResourceManagerTest extends ResourceManagerTestBase
{
private DummyResourceManager resourceManager;
@Before
public void setUp()
{
Set<ResourceHandler> resourceHandlers = ImmutableSet.of(resourceHandler);
resourceManager = new DummyResourceManager(pluginLoader, resourceHandlers);
}
/**
* Test {@link AbstractResourceManager#getScriptResources()} in the correct order.
*
* @throws java.io.IOException
*
* @see <a href="https://goo.gl/ok03l4">Issue 809</a>
*/
@Test
public void testGetScriptResources() throws IOException
{
appendScriptResources("a/b.js", "z/a.js", "a/a.js");
List<String> scripts = resourceManager.getScriptResources();
assertThat(scripts, contains("a/a.js", "a/b.js", "z/a.js"));
}
private static class DummyResourceManager extends AbstractResourceManager
{
public DummyResourceManager(PluginLoader pluginLoader, Set<ResourceHandler> resourceHandlers)
{
super(pluginLoader, resourceHandlers);
}
@Override
protected void collectResources(Map<ResourceKey, Resource> resourceMap)
{
}
}
}

View File

@@ -1,78 +0,0 @@
/***
* Copyright (c) 2015, Sebastian Sdorra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of SCM-Manager; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* https://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.resources;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for {@link DefaultResourceManager}.
*
* @author Sebastian Sdorra
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class DefaultResourceManagerTest extends ResourceManagerTestBase {
private DefaultResourceManager resourceManager;
/**
* Set up {@link DefaultResourceManager} for tests.
*/
@Before
public void setUp()
{
Set<ResourceHandler> resourceHandlers = ImmutableSet.of(resourceHandler);
resourceManager = new DefaultResourceManager(pluginLoader, resourceHandlers);
}
/**
* Test {@link DefaultResourceManager#getResources(sonia.scm.resources.ResourceType)} method.
* @throws java.io.IOException
*/
@Test
public void testGetResources() throws IOException
{
appendScriptResources("a/b.js", "z/a.js", "a/a.js");
List<Resource> resources = resourceManager.getResources(ResourceType.SCRIPT);
assertEquals(1, resources.size());
}
}

View File

@@ -1,112 +0,0 @@
/***
* Copyright (c) 2015, Sebastian Sdorra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of SCM-Manager; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* https://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.resources;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletContext;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import sonia.scm.plugin.Plugin;
import sonia.scm.plugin.PluginCondition;
import sonia.scm.plugin.PluginInformation;
import sonia.scm.plugin.PluginLoader;
import sonia.scm.plugin.PluginResources;
import sonia.scm.plugin.PluginWrapper;
import sonia.scm.plugin.WebResourceLoader;
/**
* Base class for {@link ResourceManager} tests.
*
* @author Sebastian Sdorra
*/
public abstract class ResourceManagerTestBase
{
@Mock
protected ServletContext servletContext;
@Mock
protected PluginLoader pluginLoader;
@Mock
protected ResourceHandler resourceHandler;
@Mock
protected WebResourceLoader webResourceLoader;
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
/**
* Append scripts resources to plugin loader.
*
* @param resources resource names
*
* @throws IOException
*/
protected void appendScriptResources(String... resources) throws IOException
{
Set<String> scripts = Sets.newHashSet(resources);
Set<String> styles = Sets.newHashSet();
Set<String> dependencies = Sets.newHashSet();
Plugin plugin = new Plugin(
2,
new PluginInformation(),
new PluginResources(scripts, styles),
new PluginCondition(),
false,
dependencies
);
Path pluginPath = tempFolder.newFolder().toPath();
PluginWrapper wrapper = new PluginWrapper(
plugin,
Thread.currentThread().getContextClassLoader(),
webResourceLoader,
pluginPath
);
List<PluginWrapper> plugins = ImmutableList.of(wrapper);
when(pluginLoader.getInstalledPlugins()).thenReturn(plugins);
}
}

View File

@@ -0,0 +1,113 @@
package sonia.scm.security;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import sonia.scm.config.ScmConfiguration;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class AccessTokenCookieIssuerTest {
private ScmConfiguration configuration;
private AccessTokenCookieIssuer issuer;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private AccessToken accessToken;
@Captor
private ArgumentCaptor<Cookie> cookieArgumentCaptor;
@Before
public void setUp() {
configuration = new ScmConfiguration();
issuer = new AccessTokenCookieIssuer(configuration);
}
@Test
public void testContextPath() {
assertContextPath("/scm", "/scm");
assertContextPath("/", "/");
assertContextPath("", "/");
assertContextPath(null, "/");
}
@Test
public void httpOnlyShouldBeEnabledIfXsrfProtectionIsDisabled() {
configuration.setEnabledXsrfProtection(false);
Cookie cookie = authenticate();
assertTrue(cookie.isHttpOnly());
}
@Test
public void httpOnlyShouldBeDisabled() {
Cookie cookie = authenticate();
assertFalse(cookie.isHttpOnly());
}
@Test
public void secureShouldBeSetIfTheRequestIsSecure() {
when(request.isSecure()).thenReturn(true);
Cookie cookie = authenticate();
assertTrue(cookie.getSecure());
}
@Test
public void secureShouldBeDisabledIfTheRequestIsNotSecure() {
when(request.isSecure()).thenReturn(false);
Cookie cookie = authenticate();
assertFalse(cookie.getSecure());
}
@Test
public void testInvalidate() {
issuer.invalidate(request, response);
verify(response).addCookie(cookieArgumentCaptor.capture());
Cookie cookie = cookieArgumentCaptor.getValue();
assertEquals(0, cookie.getMaxAge());
}
private Cookie authenticate() {
when(accessToken.getExpiration()).thenReturn(new Date());
issuer.authenticate(request, response, accessToken);
verify(response).addCookie(cookieArgumentCaptor.capture());
return cookieArgumentCaptor.getValue();
}
private void assertContextPath(String contextPath, String expected) {
when(request.getContextPath()).thenReturn(contextPath);
assertEquals(expected, issuer.contextPath(request));
}
}