diff options
Diffstat (limited to 'src/test/java/com/gitblit')
20 files changed, 2046 insertions, 93 deletions
diff --git a/src/test/java/com/gitblit/tests/AuthenticationManagerTest.java b/src/test/java/com/gitblit/tests/AuthenticationManagerTest.java index 0cdee6cb..f8dc8885 100644 --- a/src/test/java/com/gitblit/tests/AuthenticationManagerTest.java +++ b/src/test/java/com/gitblit/tests/AuthenticationManagerTest.java @@ -15,15 +15,44 @@ */ package com.gitblit.tests; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.AsyncContext; +import javax.servlet.DispatcherType; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionContext; +import javax.servlet.http.HttpUpgradeHandler; +import javax.servlet.http.Part; import org.junit.Test; +import com.gitblit.IUserService; +import com.gitblit.Keys; import com.gitblit.manager.AuthenticationManager; import com.gitblit.manager.IAuthenticationManager; -import com.gitblit.manager.IUserManager; +import com.gitblit.manager.IRuntimeManager; import com.gitblit.manager.RuntimeManager; import com.gitblit.manager.UserManager; +import com.gitblit.models.TeamModel; import com.gitblit.models.UserModel; import com.gitblit.tests.mock.MemorySettings; import com.gitblit.utils.XssFilter; @@ -35,35 +64,647 @@ import com.gitblit.utils.XssFilter.AllowXssFilter; * @author James Moger * */ +@SuppressWarnings("deprecation") public class AuthenticationManagerTest extends GitblitUnitTest { - IUserManager users; + UserManager users; + + private static final class DummyHttpServletRequest implements HttpServletRequest { + + @Override + public Object getAttribute(String name) { + return null; + } + + @Override + public Enumeration<String> getAttributeNames() { + return null; + } + + @Override + public String getCharacterEncoding() { + return null; + } + + @Override + public void setCharacterEncoding(String env) + throws UnsupportedEncodingException { + } + + @Override + public int getContentLength() { + return 0; + } + + @Override + public long getContentLengthLong() { + return 0; + } + + @Override + public String getContentType() { + return null; + } + + @Override + public ServletInputStream getInputStream() throws IOException { + return null; + } + + @Override + public String getParameter(String name) { + return null; + } + + @Override + public Enumeration<String> getParameterNames() { + return null; + } + + @Override + public String[] getParameterValues(String name) { + return null; + } + + @Override + public Map<String, String[]> getParameterMap() { + return null; + } + + @Override + public String getProtocol() { + return null; + } + + @Override + public String getScheme() { + return null; + } + + @Override + public String getServerName() { + return null; + } + + @Override + public int getServerPort() { + return 0; + } + + @Override + public BufferedReader getReader() throws IOException { + return null; + } + + @Override + public String getRemoteAddr() { + return null; + } + + @Override + public String getRemoteHost() { + return null; + } + + @Override + public void setAttribute(String name, Object o) { + } + + @Override + public void removeAttribute(String name) { + } + + @Override + public Locale getLocale() { + return null; + } + + @Override + public Enumeration<Locale> getLocales() { + return null; + } + + @Override + public boolean isSecure() { + return false; + } + + @Override + public RequestDispatcher getRequestDispatcher(String path) { + return null; + } + + @Override + public String getRealPath(String path) { + return null; + } + + @Override + public int getRemotePort() { + return 0; + } + + @Override + public String getLocalName() { + return null; + } + + @Override + public String getLocalAddr() { + return null; + } + + @Override + public int getLocalPort() { + return 0; + } + + @Override + public ServletContext getServletContext() { + return null; + } + + @Override + public AsyncContext startAsync() throws IllegalStateException { + return null; + } + + @Override + public AsyncContext startAsync(ServletRequest servletRequest, + ServletResponse servletResponse) + throws IllegalStateException { + return null; + } + + @Override + public boolean isAsyncStarted() { + return false; + } + + @Override + public boolean isAsyncSupported() { + return false; + } + + @Override + public AsyncContext getAsyncContext() { + return null; + } + + @Override + public DispatcherType getDispatcherType() { + return null; + } + + @Override + public String getAuthType() { + return null; + } + + @Override + public Cookie[] getCookies() { + return null; + } + + @Override + public long getDateHeader(String name) { + return 0; + } + + @Override + public String getHeader(String name) { + return null; + } + + @Override + public Enumeration<String> getHeaders(String name) { + return null; + } + + @Override + public Enumeration<String> getHeaderNames() { + return null; + } + + @Override + public int getIntHeader(String name) { + return 0; + } + + @Override + public String getMethod() { + return null; + } + + @Override + public String getPathInfo() { + return null; + } + + @Override + public String getPathTranslated() { + return null; + } + + @Override + public String getContextPath() { + return null; + } + + @Override + public String getQueryString() { + return null; + } + + @Override + public String getRemoteUser() { + return null; + } + + @Override + public boolean isUserInRole(String role) { + if(role != null && "admin".equals(role)) { + return true; + } + return false; + } + + @Override + public Principal getUserPrincipal() { + return new Principal(){ + @Override + public String getName() { + return "sunnyjim"; + } + + }; + } + + @Override + public String getRequestedSessionId() { + return null; + } + + @Override + public String getRequestURI() { + return null; + } + + @Override + public StringBuffer getRequestURL() { + return null; + } + + @Override + public String getServletPath() { + return null; + } + + @Override + public HttpSession getSession(boolean create) { + return null; + } + + final Map<String, Object> sessionAttributes = new HashMap<String, Object>(); + @Override + public HttpSession getSession() { + return new HttpSession() { + + @Override + public long getCreationTime() { + return 0; + } + + @Override + public String getId() { + return null; + } + + @Override + public long getLastAccessedTime() { + return 0; + } - MemorySettings getSettings() { - return new MemorySettings(new HashMap<String, Object>()); - } + @Override + public ServletContext getServletContext() { + return null; + } - IAuthenticationManager newAuthenticationManager() { - XssFilter xssFilter = new AllowXssFilter(); - RuntimeManager runtime = new RuntimeManager(getSettings(), xssFilter, GitBlitSuite.BASEFOLDER).start(); - users = new UserManager(runtime, null).start(); - AuthenticationManager auth = new AuthenticationManager(runtime, users).start(); - return auth; - } + @Override + public void setMaxInactiveInterval(int interval) { + } - @Test - public void testAuthenticate() throws Exception { - IAuthenticationManager auth = newAuthenticationManager(); + @Override + public int getMaxInactiveInterval() { + return 0; + } - UserModel user = new UserModel("sunnyjim"); + @Override + public HttpSessionContext getSessionContext() { + return null; + } + + @Override + public Object getAttribute(String name) { + return sessionAttributes.get(name); + } + + @Override + public Object getValue(String name) { + return null; + } + + @Override + public Enumeration<String> getAttributeNames() { + return Collections.enumeration(sessionAttributes.keySet()); + } + + @Override + public String[] getValueNames() { + return null; + } + + @Override + public void setAttribute(String name, + Object value) { + } + + @Override + public void putValue(String name, Object value) { + } + + @Override + public void removeAttribute(String name) { + } + + @Override + public void removeValue(String name) { + } + + @Override + public void invalidate() { + } + + @Override + public boolean isNew() { + return false; + } + + }; + } + + @Override + public String changeSessionId() { + return null; + } + + @Override + public boolean isRequestedSessionIdValid() { + return false; + } + + @Override + public boolean isRequestedSessionIdFromCookie() { + return false; + } + + @Override + public boolean isRequestedSessionIdFromURL() { + return false; + } + + @Override + public boolean isRequestedSessionIdFromUrl() { + return false; + } + + @Override + public boolean authenticate(HttpServletResponse response) + throws IOException, ServletException { + return false; + } + + @Override + public void login(String username, String password) + throws ServletException { + } + + @Override + public void logout() throws ServletException { + } + + @Override + public Collection<Part> getParts() throws IOException, + ServletException { + return null; + } + + @Override + public Part getPart(String name) throws IOException, + ServletException { + return null; + } + + @Override + public <T extends HttpUpgradeHandler> T upgrade( + Class<T> handlerClass) throws IOException, + ServletException { + return null; + } + + } + + HashMap<String, Object> settings = new HashMap<String, Object>(); + + MemorySettings getSettings() { + return new MemorySettings(settings); + } + + IAuthenticationManager newAuthenticationManager() { + XssFilter xssFilter = new AllowXssFilter(); + RuntimeManager runtime = new RuntimeManager(getSettings(), xssFilter, GitBlitSuite.BASEFOLDER).start(); + users = new UserManager(runtime, null).start(); + final Map<String, UserModel> virtualUsers = new HashMap<String, UserModel>(); + users.setUserService(new IUserService() { + + @Override + public void setup(IRuntimeManager runtimeManager) { + } + + @Override + public String getCookie(UserModel model) { + return null; + } + + @Override + public UserModel getUserModel(char[] cookie) { + return null; + } + + @Override + public UserModel getUserModel(String username) { + return virtualUsers.get(username); + } + + @Override + public boolean updateUserModel(UserModel model) { + virtualUsers.put(model.username, model); + return true; + } + + @Override + public boolean updateUserModels(Collection<UserModel> models) { + return false; + } + + @Override + public boolean updateUserModel(String username, UserModel model) { + virtualUsers.put(username, model); + return true; + } + + @Override + public boolean deleteUserModel(UserModel model) { + return false; + } + + @Override + public boolean deleteUser(String username) { + return false; + } + + @Override + public List<String> getAllUsernames() { + return null; + } + + @Override + public List<UserModel> getAllUsers() { + return null; + } + + @Override + public List<String> getAllTeamNames() { + return null; + } + + @Override + public List<TeamModel> getAllTeams() { + return null; + } + + @Override + public List<String> getTeamNamesForRepositoryRole(String role) { + return null; + } + + @Override + public TeamModel getTeamModel(String teamname) { + return null; + } + + @Override + public boolean updateTeamModel(TeamModel model) { + return false; + } + + @Override + public boolean updateTeamModels(Collection<TeamModel> models) { + return false; + } + + @Override + public boolean updateTeamModel(String teamname, TeamModel model) { + return false; + } + + @Override + public boolean deleteTeamModel(TeamModel model) { + return false; + } + + @Override + public boolean deleteTeam(String teamname) { + return false; + } + + @Override + public List<String> getUsernamesForRepositoryRole(String role) { + return null; + } + + @Override + public boolean renameRepositoryRole(String oldRole, + String newRole) { + return false; + } + + @Override + public boolean deleteRepositoryRole(String role) { + return false; + } + + }); + AuthenticationManager auth = new AuthenticationManager(runtime, users).start(); + return auth; + } + + @Test + public void testAuthenticate() throws Exception { + IAuthenticationManager auth = newAuthenticationManager(); + + UserModel user = new UserModel("sunnyjim"); user.password = "password"; users.updateUserModel(user); - assertNotNull(auth.authenticate(user.username, user.password.toCharArray())); + assertNotNull(auth.authenticate(user.username, user.password.toCharArray(), null)); user.disabled = true; users.updateUserModel(user); - assertNull(auth.authenticate(user.username, user.password.toCharArray())); + assertNull(auth.authenticate(user.username, user.password.toCharArray(), null)); users.deleteUserModel(user); - } + } + + @Test + public void testContenairAuthenticate() throws Exception { + settings.put(Keys.realm.container.autoCreateAccounts, "true"); + settings.put(Keys.realm.container.autoAccounts.displayName, "displayName"); + settings.put(Keys.realm.container.autoAccounts.emailAddress, "emailAddress"); + settings.put(Keys.realm.container.autoAccounts.adminRole, "admin"); + settings.put(Keys.realm.container.autoAccounts.locale, "locale"); + + DummyHttpServletRequest request = new DummyHttpServletRequest(); + request.sessionAttributes.put("displayName", "Sunny Jim"); + request.sessionAttributes.put("emailAddress", "Jim.Sunny@gitblit.com"); + request.sessionAttributes.put("locale", "it"); + + IAuthenticationManager auth = newAuthenticationManager(); + + UserModel user = auth.authenticate(request); + + assertTrue(user.canAdmin); + assertEquals("Sunny Jim", user.displayName); + assertEquals("Jim.Sunny@gitblit.com", user.emailAddress); + assertEquals(Locale.ITALIAN, user.getPreferences().getLocale()); + } + + @Test + public void testContenairAuthenticateEmpty() throws Exception { + settings.put(Keys.realm.container.autoCreateAccounts, "true"); + settings.put(Keys.realm.container.autoAccounts.displayName, "displayName"); + settings.put(Keys.realm.container.autoAccounts.emailAddress, "emailAddress"); + settings.put(Keys.realm.container.autoAccounts.adminRole, "notAdmin"); + + DummyHttpServletRequest request = new DummyHttpServletRequest(); + + IAuthenticationManager auth = newAuthenticationManager(); + + UserModel user = auth.authenticate(request); + + assertFalse(user.canAdmin); + assertEquals("sunnyjim", user.displayName); + assertNull(user.emailAddress); + assertNull(user.getPreferences().getLocale()); + } + } diff --git a/src/test/java/com/gitblit/tests/DiffUtilsTest.java b/src/test/java/com/gitblit/tests/DiffUtilsTest.java index 9d627b80..e8e839a5 100644 --- a/src/test/java/com/gitblit/tests/DiffUtilsTest.java +++ b/src/test/java/com/gitblit/tests/DiffUtilsTest.java @@ -23,6 +23,7 @@ import org.junit.Test; import com.gitblit.models.AnnotatedLine;
import com.gitblit.utils.DiffUtils;
+import com.gitblit.utils.DiffUtils.DiffComparator;
import com.gitblit.utils.DiffUtils.DiffOutputType;
import com.gitblit.utils.JGitUtils;
@@ -40,7 +41,7 @@ public class DiffUtilsTest extends GitblitUnitTest { Repository repository = GitBlitSuite.getHelloworldRepository();
RevCommit commit = JGitUtils.getCommit(repository,
"1d0c2933a4ae69c362f76797d42d6bd182d05176");
- String diff = DiffUtils.getCommitDiff(repository, commit, DiffOutputType.PLAIN).content;
+ String diff = DiffUtils.getCommitDiff(repository, commit, DiffComparator.SHOW_WHITESPACE, DiffOutputType.PLAIN, 3).content;
repository.close();
assertTrue(diff != null && diff.length() > 0);
String expected = "- system.out.println(\"Hello World\");\n+ System.out.println(\"Hello World\"";
@@ -54,7 +55,7 @@ public class DiffUtilsTest extends GitblitUnitTest { "8baf6a833b5579384d9b9ceb8a16b5d0ea2ec4ca");
RevCommit commit = JGitUtils.getCommit(repository,
"1d0c2933a4ae69c362f76797d42d6bd182d05176");
- String diff = DiffUtils.getDiff(repository, baseCommit, commit, DiffOutputType.PLAIN).content;
+ String diff = DiffUtils.getDiff(repository, baseCommit, commit, DiffComparator.SHOW_WHITESPACE, DiffOutputType.PLAIN, 3).content;
repository.close();
assertTrue(diff != null && diff.length() > 0);
String expected = "- system.out.println(\"Hello World\");\n+ System.out.println(\"Hello World\"";
@@ -66,7 +67,7 @@ public class DiffUtilsTest extends GitblitUnitTest { Repository repository = GitBlitSuite.getHelloworldRepository();
RevCommit commit = JGitUtils.getCommit(repository,
"1d0c2933a4ae69c362f76797d42d6bd182d05176");
- String diff = DiffUtils.getDiff(repository, commit, "java.java", DiffOutputType.PLAIN).content;
+ String diff = DiffUtils.getDiff(repository, commit, "java.java", DiffComparator.SHOW_WHITESPACE, DiffOutputType.PLAIN, 3).content;
repository.close();
assertTrue(diff != null && diff.length() > 0);
String expected = "- system.out.println(\"Hello World\");\n+ System.out.println(\"Hello World\"";
diff --git a/src/test/java/com/gitblit/tests/FilestoreManagerTest.java b/src/test/java/com/gitblit/tests/FilestoreManagerTest.java new file mode 100644 index 00000000..c76e9dd6 --- /dev/null +++ b/src/test/java/com/gitblit/tests/FilestoreManagerTest.java @@ -0,0 +1,547 @@ +package com.gitblit.tests; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.Date; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.gitblit.Constants.AccessPermission; +import com.gitblit.Constants.AccessRestrictionType; +import com.gitblit.Constants.AuthorizationControl; +import com.gitblit.Keys; +import com.gitblit.models.FilestoreModel.Status; +import com.gitblit.models.RepositoryModel; +import com.gitblit.models.UserModel; +import com.gitblit.utils.FileUtils; + + +/** + * Test of the filestore manager and confirming filesystem updated + * + * @author Paul Martin + * + */ +public class FilestoreManagerTest extends GitblitUnitTest { + + private static final AtomicBoolean started = new AtomicBoolean(false); + + private static final BlobInfo blob_zero = new BlobInfo(0); + private static final BlobInfo blob_512KB = new BlobInfo(512*FileUtils.KB); + private static final BlobInfo blob_6MB = new BlobInfo(6*FileUtils.MB); + + private static int download_limit_default = -1; + private static int download_limit_test = 5*FileUtils.MB; + + private static final String invalid_hash_empty = ""; + private static final String invalid_hash_major = "INVALID_HASH"; + private static final String invalid_hash_regex_attack = blob_512KB.hash.replace('a', '*'); + private static final String invalid_hash_one_long = blob_512KB.hash.concat("a"); + private static final String invalid_hash_one_short = blob_512KB.hash.substring(1); + + + + @BeforeClass + public static void startGitblit() throws Exception { + started.set(GitBlitSuite.startGitblit()); + } + + @AfterClass + public static void stopGitblit() throws Exception { + if (started.get()) { + GitBlitSuite.stopGitblit(); + } + } + + + + @Test + public void testAdminAccess() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + RepositoryModel r = new RepositoryModel("myrepo.git", null, null, new Date()); + ByteArrayOutputStream streamOut = new ByteArrayOutputStream(); + + UserModel u = new UserModel("admin"); + u.canAdmin = true; + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, download_limit_default); + + //Invalid hash tests + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_major, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_regex_attack, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_one_long, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_one_short, u, r, streamOut)); + + // Download prior to upload + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Bad input is rejected with no upload taking place + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_empty, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_major, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_regex_attack, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_one_long, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_one_short, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Invalid_Size, filestore().uploadBlob(blob_512KB.hash, -1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, 0, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length-1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length+1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Hash_Mismatch, filestore().uploadBlob(blob_zero.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + //Confirm no upload with bad input + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Good input will accept the upload + assertEquals(Status.Available, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + assertArrayEquals(blob_512KB.blob, streamOut.toByteArray()); + + //Subsequent failed uploads do not affect file + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length-1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length+1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + assertArrayEquals(blob_512KB.blob, streamOut.toByteArray()); + + //Zero length upload is valid + assertEquals(Status.Available, filestore().uploadBlob(blob_zero.hash, blob_zero.length, u, r, new ByteArrayInputStream(blob_zero.blob))); + + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_zero.hash, u, r, streamOut)); + assertArrayEquals(blob_zero.blob, streamOut.toByteArray()); + + + //Pre-informed upload identifies identical errors as immediate upload + assertEquals(Status.Upload_Pending, filestore().addObject(blob_6MB.hash, blob_6MB.length, u, r)); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_empty, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_major, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_regex_attack, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_one_long, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_one_short, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_6MB.hash, 0, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length-1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length+1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + //Good input will accept the upload + assertEquals(Status.Available, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + assertArrayEquals(blob_6MB.blob, streamOut.toByteArray()); + + //Confirm the relevant files exist + assertTrue("Admin did not save zero length file!", filestore().getStoragePath(blob_zero.hash).exists()); + assertTrue("Admin did not save 512KB file!", filestore().getStoragePath(blob_512KB.hash).exists()); + assertTrue("Admin did not save 6MB file!", filestore().getStoragePath(blob_6MB.hash).exists()); + + //Clear the files and cache to test upload limit property + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + settings().overrideSetting(Keys.filestore.maxUploadSize, download_limit_test); + + assertEquals(Status.Available, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + assertArrayEquals(blob_512KB.blob, streamOut.toByteArray()); + + assertEquals(Status.Error_Exceeds_Size_Limit, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + assertTrue("Admin did not save 512KB file!", filestore().getStoragePath(blob_512KB.hash).exists()); + assertFalse("Admin saved 6MB file despite (over filesize limit)!", filestore().getStoragePath(blob_6MB.hash).exists()); + + } + + @Test + public void testAuthenticatedAccess() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + RepositoryModel r = new RepositoryModel("myrepo.git", null, null, new Date()); + r.authorizationControl = AuthorizationControl.AUTHENTICATED; + r.accessRestriction = AccessRestrictionType.VIEW; + + ByteArrayOutputStream streamOut = new ByteArrayOutputStream(); + + UserModel u = new UserModel("test"); + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, download_limit_default); + + //Invalid hash tests + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_major, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_regex_attack, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_one_long, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_one_short, u, r, streamOut)); + + // Download prior to upload + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Bad input is rejected with no upload taking place + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_empty, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_major, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_regex_attack, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_one_long, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_one_short, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Invalid_Size, filestore().uploadBlob(blob_512KB.hash, -1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, 0, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length-1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length+1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Hash_Mismatch, filestore().uploadBlob(blob_zero.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + //Confirm no upload with bad input + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Good input will accept the upload + assertEquals(Status.Available, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + assertArrayEquals(blob_512KB.blob, streamOut.toByteArray()); + + //Subsequent failed uploads do not affect file + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length-1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length+1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + assertArrayEquals(blob_512KB.blob, streamOut.toByteArray()); + + //Zero length upload is valid + assertEquals(Status.Available, filestore().uploadBlob(blob_zero.hash, blob_zero.length, u, r, new ByteArrayInputStream(blob_zero.blob))); + + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_zero.hash, u, r, streamOut)); + assertArrayEquals(blob_zero.blob, streamOut.toByteArray()); + + + //Pre-informed upload identifies identical errors as immediate upload + assertEquals(Status.Upload_Pending, filestore().addObject(blob_6MB.hash, blob_6MB.length, u, r)); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_empty, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_major, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_regex_attack, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_one_long, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Invalid_Oid, filestore().uploadBlob(invalid_hash_one_short, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_6MB.hash, 0, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length-1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Size_Mismatch, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length+1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + //Good input will accept the upload + assertEquals(Status.Available, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + assertArrayEquals(blob_6MB.blob, streamOut.toByteArray()); + + //Confirm the relevant files exist + assertTrue("Authenticated user did not save zero length file!", filestore().getStoragePath(blob_zero.hash).exists()); + assertTrue("Authenticated user did not save 512KB file!", filestore().getStoragePath(blob_512KB.hash).exists()); + assertTrue("Authenticated user did not save 6MB file!", filestore().getStoragePath(blob_6MB.hash).exists()); + + //Clear the files and cache to test upload limit property + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + settings().overrideSetting(Keys.filestore.maxUploadSize, download_limit_test); + + assertEquals(Status.Available, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + streamOut.reset(); + assertEquals(Status.Available, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + assertArrayEquals(blob_512KB.blob, streamOut.toByteArray()); + + assertEquals(Status.Error_Exceeds_Size_Limit, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + assertTrue("Authenticated user did not save 512KB file!", filestore().getStoragePath(blob_512KB.hash).exists()); + assertFalse("Authenticated user saved 6MB file (over filesize limit)!", filestore().getStoragePath(blob_6MB.hash).exists()); + + } + + @Test + public void testAnonymousAccess() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + RepositoryModel r = new RepositoryModel("myrepo.git", null, null, new Date()); + r.authorizationControl = AuthorizationControl.NAMED; + r.accessRestriction = AccessRestrictionType.CLONE; + + ByteArrayOutputStream streamOut = new ByteArrayOutputStream(); + + UserModel u = UserModel.ANONYMOUS; + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, download_limit_default); + + //Invalid hash tests + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_major, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_regex_attack, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_one_long, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_one_short, u, r, streamOut)); + + // Download prior to upload + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Bad input is rejected with no upload taking place + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_empty, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_major, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_regex_attack, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_one_long, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_one_short, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_512KB.hash, -1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_512KB.hash, 0, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length-1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length+1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_zero.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + //Confirm no upload with bad input + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Good input will accept the upload + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Subsequent failed uploads do not affect file + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length-1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length+1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Zero length upload is valid + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_zero.hash, blob_zero.length, u, r, new ByteArrayInputStream(blob_zero.blob))); + + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_zero.hash, u, r, streamOut)); + + + //Pre-informed upload identifies identical errors as immediate upload + assertEquals(Status.AuthenticationRequired, filestore().addObject(blob_6MB.hash, blob_6MB.length, u, r)); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_empty, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_major, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_regex_attack, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_one_long, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(invalid_hash_one_short, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_6MB.hash, -1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_6MB.hash, 0, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length-1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length+1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + //Good input will accept the upload + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + //Confirm the relevant files do not exist + assertFalse("Anonymous user saved zero length file!", filestore().getStoragePath(blob_zero.hash).exists()); + assertFalse("Anonymous user 512KB file!", filestore().getStoragePath(blob_512KB.hash).exists()); + assertFalse("Anonymous user 6MB file!", filestore().getStoragePath(blob_6MB.hash).exists()); + + //Clear the files and cache to test upload limit property + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + settings().overrideSetting(Keys.filestore.maxUploadSize, download_limit_test); + + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + assertEquals(Status.AuthenticationRequired, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + assertFalse("Anonymous user saved 512KB file!", filestore().getStoragePath(blob_512KB.hash).exists()); + assertFalse("Anonymous user saved 6MB file (over filesize limit)!", filestore().getStoragePath(blob_6MB.hash).exists()); + + } + + @Test + public void testUnauthorizedAccess() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + RepositoryModel r = new RepositoryModel("myrepo.git", null, null, new Date()); + r.authorizationControl = AuthorizationControl.NAMED; + r.accessRestriction = AccessRestrictionType.VIEW; + + ByteArrayOutputStream streamOut = new ByteArrayOutputStream(); + + UserModel u = new UserModel("test"); + u.setRepositoryPermission(r.name, AccessPermission.CLONE); + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, download_limit_default); + + //Invalid hash tests + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_major, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_regex_attack, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_one_long, u, r, streamOut)); + assertEquals(Status.Error_Invalid_Oid, filestore().downloadBlob(invalid_hash_one_short, u, r, streamOut)); + + // Download prior to upload + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Bad input is rejected with no upload taking place + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_major, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_regex_attack, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_one_long, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_empty, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_one_short, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_512KB.hash, -1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_512KB.hash, 0, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length-1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length+1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_zero.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + //Confirm no upload with bad input + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Good input will accept the upload + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Subsequent failed uploads do not affect file + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length-1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length+1, u, r, new ByteArrayInputStream(blob_512KB.blob))); + + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + //Zero length upload is valid + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_zero.hash, blob_zero.length, u, r, new ByteArrayInputStream(blob_zero.blob))); + + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_zero.hash, u, r, streamOut)); + + + //Pre-informed upload identifies identical errors as immediate upload + assertEquals(Status.Error_Unauthorized, filestore().addObject(blob_6MB.hash, blob_6MB.length, u, r)); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_empty, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_major, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_regex_attack, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_one_long, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(invalid_hash_one_short, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_6MB.hash, -1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_6MB.hash, 0, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length-1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length+1, u, r, new ByteArrayInputStream(blob_6MB.blob))); + + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + //Good input will accept the upload + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + //Confirm the relevant files exist + assertFalse("Unauthorized user saved zero length file!", filestore().getStoragePath(blob_zero.hash).exists()); + assertFalse("Unauthorized user saved 512KB file!", filestore().getStoragePath(blob_512KB.hash).exists()); + assertFalse("Unauthorized user saved 6MB file!", filestore().getStoragePath(blob_6MB.hash).exists()); + + //Clear the files and cache to test upload limit property + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + settings().overrideSetting(Keys.filestore.maxUploadSize, download_limit_test); + + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_512KB.hash, blob_512KB.length, u, r, new ByteArrayInputStream(blob_512KB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_512KB.hash, u, r, streamOut)); + + assertEquals(Status.Error_Unauthorized, filestore().uploadBlob(blob_6MB.hash, blob_6MB.length, u, r, new ByteArrayInputStream(blob_6MB.blob))); + streamOut.reset(); + assertEquals(Status.Unavailable, filestore().downloadBlob(blob_6MB.hash, u, r, streamOut)); + + assertFalse("Unauthorized user saved 512KB file!", filestore().getStoragePath(blob_512KB.hash).exists()); + assertFalse("Unauthorized user saved 6MB file (over filesize limit)!", filestore().getStoragePath(blob_6MB.hash).exists()); + + } + +} + +/* + * Test helper structure to create blobs of a given size + */ +final class BlobInfo { + public byte[] blob; + public String hash; + public int length; + + public BlobInfo(int nBytes) { + blob = new byte[nBytes]; + new java.util.Random().nextBytes(blob); + hash = DigestUtils.sha256Hex(blob); + length = nBytes; + } +}
\ No newline at end of file diff --git a/src/test/java/com/gitblit/tests/FilestoreServletTest.java b/src/test/java/com/gitblit/tests/FilestoreServletTest.java new file mode 100644 index 00000000..4e4b056a --- /dev/null +++ b/src/test/java/com/gitblit/tests/FilestoreServletTest.java @@ -0,0 +1,355 @@ +package com.gitblit.tests; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.ByteArrayEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.gitblit.Keys; +import com.gitblit.manager.FilestoreManager; +import com.gitblit.models.RepositoryModel; +import com.gitblit.models.UserModel; +import com.gitblit.models.FilestoreModel.Status; +import com.gitblit.servlet.FilestoreServlet; +import com.gitblit.utils.FileUtils; + +public class FilestoreServletTest extends GitblitUnitTest { + + private static final AtomicBoolean started = new AtomicBoolean(false); + + private static final String SHA256_EG = "9a712c5d4037503a2d5ee1d07ad191eb99d051e84cbb020c171a5ae19bbe3cbd"; + + private static final String repoName = "helloworld.git"; + + private static final String repoLfs = "/r/" + repoName + "/info/lfs/objects/"; + + @BeforeClass + public static void startGitblit() throws Exception { + started.set(GitBlitSuite.startGitblit()); + } + + @AfterClass + public static void stopGitblit() throws Exception { + if (started.get()) { + GitBlitSuite.stopGitblit(); + } + } + + + @Test + public void testRegexGroups() throws Exception { + + Pattern p = Pattern.compile(FilestoreServlet.REGEX_PATH); + + String basicUrl = "https://localhost:8080/r/test.git/info/lfs/objects/"; + String batchUrl = basicUrl + "batch"; + String oidUrl = basicUrl + SHA256_EG; + + Matcher m = p.matcher(batchUrl); + assertTrue(m.find()); + assertEquals("https://localhost:8080", m.group(FilestoreServlet.REGEX_GROUP_BASE_URI)); + assertEquals("r", m.group(FilestoreServlet.REGEX_GROUP_PREFIX)); + assertEquals("test.git", m.group(FilestoreServlet.REGEX_GROUP_REPOSITORY)); + assertEquals("batch", m.group(FilestoreServlet.REGEX_GROUP_ENDPOINT)); + + m = p.matcher(oidUrl); + assertTrue(m.find()); + assertEquals("https://localhost:8080", m.group(FilestoreServlet.REGEX_GROUP_BASE_URI)); + assertEquals("r", m.group(FilestoreServlet.REGEX_GROUP_PREFIX)); + assertEquals("test.git", m.group(FilestoreServlet.REGEX_GROUP_REPOSITORY)); + assertEquals(SHA256_EG, m.group(FilestoreServlet.REGEX_GROUP_ENDPOINT)); + } + + @Test + public void testRegexGroupsNestedRepo() throws Exception { + + Pattern p = Pattern.compile(FilestoreServlet.REGEX_PATH); + + String basicUrl = "https://localhost:8080/r/nested/test.git/info/lfs/objects/"; + String batchUrl = basicUrl + "batch"; + String oidUrl = basicUrl + SHA256_EG; + + Matcher m = p.matcher(batchUrl); + assertTrue(m.find()); + assertEquals("https://localhost:8080", m.group(FilestoreServlet.REGEX_GROUP_BASE_URI)); + assertEquals("r", m.group(FilestoreServlet.REGEX_GROUP_PREFIX)); + assertEquals("nested/test.git", m.group(FilestoreServlet.REGEX_GROUP_REPOSITORY)); + assertEquals("batch", m.group(FilestoreServlet.REGEX_GROUP_ENDPOINT)); + + m = p.matcher(oidUrl); + assertTrue(m.find()); + assertEquals("https://localhost:8080", m.group(FilestoreServlet.REGEX_GROUP_BASE_URI)); + assertEquals("r", m.group(FilestoreServlet.REGEX_GROUP_PREFIX)); + assertEquals("nested/test.git", m.group(FilestoreServlet.REGEX_GROUP_REPOSITORY)); + assertEquals(SHA256_EG, m.group(FilestoreServlet.REGEX_GROUP_ENDPOINT)); + } + + @Test + public void testDownload() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + RepositoryModel r = gitblit().getRepositoryModel(repoName); + + UserModel u = new UserModel("admin"); + u.canAdmin = true; + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, FilestoreManager.UNDEFINED_SIZE); + + final BlobInfo blob = new BlobInfo(512*FileUtils.KB); + + //Emulate a pre-existing Git-LFS repository by using using internal pre-tested methods + assertEquals(Status.Available, filestore().uploadBlob(blob.hash, blob.length, u, r, new ByteArrayInputStream(blob.blob))); + + final String downloadURL = GitBlitSuite.url + repoLfs + blob.hash; + + HttpClient client = HttpClientBuilder.create().build(); + HttpGet request = new HttpGet(downloadURL); + + // add request header + request.addHeader(HttpHeaders.ACCEPT, FilestoreServlet.GIT_LFS_META_MIME); + HttpResponse response = client.execute(request); + + assertEquals(200, response.getStatusLine().getStatusCode()); + + String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); + + String expectedContent = String.format("{%s:%s,%s:%d,%s:{%s:{%s:%s}}}", + "\"oid\"", "\"" + blob.hash + "\"", + "\"size\"", blob.length, + "\"actions\"", + "\"download\"", + "\"href\"", "\"" + downloadURL + "\""); + + assertEquals(expectedContent, content); + + + //Now try the binary download + request.removeHeaders(HttpHeaders.ACCEPT); + response = client.execute(request); + + assertEquals(200, response.getStatusLine().getStatusCode()); + + byte[] dlData = IOUtils.toByteArray(response.getEntity().getContent()); + + assertArrayEquals(blob.blob, dlData); + + } + + @Test + public void testDownloadMultiple() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + RepositoryModel r = gitblit().getRepositoryModel(repoName); + + UserModel u = new UserModel("admin"); + u.canAdmin = true; + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, FilestoreManager.UNDEFINED_SIZE); + + final BlobInfo blob = new BlobInfo(512*FileUtils.KB); + + //Emulate a pre-existing Git-LFS repository by using using internal pre-tested methods + assertEquals(Status.Available, filestore().uploadBlob(blob.hash, blob.length, u, r, new ByteArrayInputStream(blob.blob))); + + final String batchURL = GitBlitSuite.url + repoLfs + "batch"; + final String downloadURL = GitBlitSuite.url + repoLfs + blob.hash; + + HttpClient client = HttpClientBuilder.create().build(); + HttpPost request = new HttpPost(batchURL); + + // add request header + request.addHeader(HttpHeaders.ACCEPT, FilestoreServlet.GIT_LFS_META_MIME); + request.addHeader(HttpHeaders.CONTENT_ENCODING, FilestoreServlet.GIT_LFS_META_MIME); + + String content = String.format("{%s:%s,%s:[{%s:%s,%s:%d},{%s:%s,%s:%d}]}", + "\"operation\"", "\"download\"", + "\"objects\"", + "\"oid\"", "\"" + blob.hash + "\"", + "\"size\"", blob.length, + "\"oid\"", "\"" + SHA256_EG + "\"", + "\"size\"", 0); + + HttpEntity entity = new ByteArrayEntity(content.getBytes("UTF-8")); + request.setEntity(entity); + + HttpResponse response = client.execute(request); + + String responseMessage = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); + assertEquals(200, response.getStatusLine().getStatusCode()); + + String expectedContent = String.format("{%s:[{%s:%s,%s:%d,%s:{%s:{%s:%s}}},{%s:%s,%s:%d,%s:{%s:%s,%s:%d}}]}", + "\"objects\"", + "\"oid\"", "\"" + blob.hash + "\"", + "\"size\"", blob.length, + "\"actions\"", + "\"download\"", + "\"href\"", "\"" + downloadURL + "\"", + "\"oid\"", "\"" + SHA256_EG + "\"", + "\"size\"", 0, + "\"error\"", + "\"message\"", "\"Object not available\"", + "\"code\"", 404 + ); + + assertEquals(expectedContent, responseMessage); + } + + @Test + public void testDownloadUnavailable() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, FilestoreManager.UNDEFINED_SIZE); + + final BlobInfo blob = new BlobInfo(512*FileUtils.KB); + + final String downloadURL = GitBlitSuite.url + repoLfs + blob.hash; + + HttpClient client = HttpClientBuilder.create().build(); + HttpGet request = new HttpGet(downloadURL); + + // add request header + request.addHeader(HttpHeaders.ACCEPT, FilestoreServlet.GIT_LFS_META_MIME); + HttpResponse response = client.execute(request); + + assertEquals(404, response.getStatusLine().getStatusCode()); + + String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); + + String expectedError = String.format("{%s:%s,%s:%d}", + "\"message\"", "\"Object not available\"", + "\"code\"", 404); + + assertEquals(expectedError, content); + } + + @Test + public void testUpload() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + RepositoryModel r = gitblit().getRepositoryModel(repoName); + + UserModel u = new UserModel("admin"); + u.canAdmin = true; + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, FilestoreManager.UNDEFINED_SIZE); + + final BlobInfo blob = new BlobInfo(512*FileUtils.KB); + + final String expectedUploadURL = GitBlitSuite.url + repoLfs + blob.hash; + final String initialUploadURL = GitBlitSuite.url + repoLfs + "batch"; + + HttpClient client = HttpClientBuilder.create().build(); + HttpPost request = new HttpPost(initialUploadURL); + + // add request header + request.addHeader(HttpHeaders.ACCEPT, FilestoreServlet.GIT_LFS_META_MIME); + request.addHeader(HttpHeaders.CONTENT_ENCODING, FilestoreServlet.GIT_LFS_META_MIME); + + String content = String.format("{%s:%s,%s:[{%s:%s,%s:%d}]}", + "\"operation\"", "\"upload\"", + "\"objects\"", + "\"oid\"", "\"" + blob.hash + "\"", + "\"size\"", blob.length); + + HttpEntity entity = new ByteArrayEntity(content.getBytes("UTF-8")); + request.setEntity(entity); + + HttpResponse response = client.execute(request); + String responseMessage = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); + assertEquals(200, response.getStatusLine().getStatusCode()); + + String expectedContent = String.format("{%s:[{%s:%s,%s:%d,%s:{%s:{%s:%s}}}]}", + "\"objects\"", + "\"oid\"", "\"" + blob.hash + "\"", + "\"size\"", blob.length, + "\"actions\"", + "\"upload\"", + "\"href\"", "\"" + expectedUploadURL + "\""); + + assertEquals(expectedContent, responseMessage); + + + //Now try to upload the binary download + HttpPut putRequest = new HttpPut(expectedUploadURL); + putRequest.setEntity(new ByteArrayEntity(blob.blob)); + response = client.execute(putRequest); + + responseMessage = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); + + assertEquals(200, response.getStatusLine().getStatusCode()); + + //Confirm behind the scenes that it is available + ByteArrayOutputStream savedBlob = new ByteArrayOutputStream(); + assertEquals(Status.Available, filestore().downloadBlob(blob.hash, u, r, savedBlob)); + assertArrayEquals(blob.blob, savedBlob.toByteArray()); + } + + @Test + public void testMalformedUpload() throws Exception { + + FileUtils.delete(filestore().getStorageFolder()); + filestore().clearFilestoreCache(); + + //No upload limit + settings().overrideSetting(Keys.filestore.maxUploadSize, FilestoreManager.UNDEFINED_SIZE); + + final BlobInfo blob = new BlobInfo(512*FileUtils.KB); + + final String initialUploadURL = GitBlitSuite.url + repoLfs + "batch"; + + HttpClient client = HttpClientBuilder.create().build(); + HttpPost request = new HttpPost(initialUploadURL); + + // add request header + request.addHeader(HttpHeaders.ACCEPT, FilestoreServlet.GIT_LFS_META_MIME); + request.addHeader(HttpHeaders.CONTENT_ENCODING, FilestoreServlet.GIT_LFS_META_MIME); + + //Malformed JSON, comma instead of colon and unquoted strings + String content = String.format("{%s:%s,%s:[{%s:%s,%s,%d}]}", + "operation", "upload", + "objects", + "oid", blob.hash, + "size", blob.length); + + HttpEntity entity = new ByteArrayEntity(content.getBytes("UTF-8")); + request.setEntity(entity); + + HttpResponse response = client.execute(request); + String responseMessage = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); + assertEquals(400, response.getStatusLine().getStatusCode()); + + String expectedError = String.format("{%s:%s,%s:%d}", + "\"message\"", "\"Malformed Git-LFS request\"", + "\"code\"", 400); + + assertEquals(expectedError, responseMessage); + } + +} diff --git a/src/test/java/com/gitblit/tests/GitBlitSuite.java b/src/test/java/com/gitblit/tests/GitBlitSuite.java index 5a7dcea1..b01c82c4 100644 --- a/src/test/java/com/gitblit/tests/GitBlitSuite.java +++ b/src/test/java/com/gitblit/tests/GitBlitSuite.java @@ -63,9 +63,10 @@ import com.gitblit.utils.JGitUtils; GitBlitTest.class, FederationTests.class, RpcTests.class, GitServletTest.class, GitDaemonTest.class,
SshDaemonTest.class, GroovyScriptTest.class, LuceneExecutorTest.class, RepositoryModelTest.class,
FanoutServiceTest.class, Issue0259Test.class, Issue0271Test.class, HtpasswdAuthenticationTest.class,
- ModelUtilsTest.class, JnaUtilsTest.class, LdapSyncServiceTest.class, FileTicketServiceTest.class, + ModelUtilsTest.class, JnaUtilsTest.class, LdapSyncServiceTest.class, FileTicketServiceTest.class,
BranchTicketServiceTest.class, RedisTicketServiceTest.class, AuthenticationManagerTest.class,
- SshKeysDispatcherTest.class }) + SshKeysDispatcherTest.class, UITicketTest.class, PathUtilsTest.class, SshKerberosAuthenticationTest.class,
+ GravatarTest.class, FilestoreManagerTest.class, FilestoreServletTest.class })
public class GitBlitSuite {
public static final File BASEFOLDER = new File("data");
@@ -110,11 +111,11 @@ public class GitBlitSuite { return getRepository("test/gitective.git");
}
- public static Repository getTicketsTestRepository() { - JGitUtils.createRepository(REPOSITORIES, "gb-tickets.git").close(); - return getRepository("gb-tickets.git"); - } - + public static Repository getTicketsTestRepository() {
+ JGitUtils.createRepository(REPOSITORIES, "gb-tickets.git").close();
+ return getRepository("gb-tickets.git");
+ }
+
private static Repository getRepository(String name) {
try {
File gitDir = FileKey.resolve(new File(REPOSITORIES, name), FS.DETECTED);
diff --git a/src/test/java/com/gitblit/tests/GitBlitTest.java b/src/test/java/com/gitblit/tests/GitBlitTest.java index 9eaae7f8..e873ced2 100644 --- a/src/test/java/com/gitblit/tests/GitBlitTest.java +++ b/src/test/java/com/gitblit/tests/GitBlitTest.java @@ -176,7 +176,7 @@ public class GitBlitTest extends GitblitUnitTest { @Test
public void testAuthentication() throws Exception {
- assertTrue(authentication().authenticate("admin", "admin".toCharArray()) != null);
+ assertTrue(authentication().authenticate("admin", "admin".toCharArray(), null) != null);
}
@Test
diff --git a/src/test/java/com/gitblit/tests/GitblitUnitTest.java b/src/test/java/com/gitblit/tests/GitblitUnitTest.java index 9dceaaf4..58bc60e4 100644 --- a/src/test/java/com/gitblit/tests/GitblitUnitTest.java +++ b/src/test/java/com/gitblit/tests/GitblitUnitTest.java @@ -18,6 +18,7 @@ package com.gitblit.tests; import com.gitblit.IStoredSettings; import com.gitblit.manager.IAuthenticationManager; import com.gitblit.manager.IFederationManager; +import com.gitblit.manager.IFilestoreManager; import com.gitblit.manager.IGitblit; import com.gitblit.manager.INotificationManager; import com.gitblit.manager.IProjectManager; @@ -64,4 +65,8 @@ public class GitblitUnitTest extends org.junit.Assert { public static IGitblit gitblit() { return GitblitContext.getManager(IGitblit.class); } + + public static IFilestoreManager filestore() { + return GitblitContext.getManager(IFilestoreManager.class); + } } diff --git a/src/test/java/com/gitblit/tests/GravatarTest.java b/src/test/java/com/gitblit/tests/GravatarTest.java new file mode 100644 index 00000000..ba989d56 --- /dev/null +++ b/src/test/java/com/gitblit/tests/GravatarTest.java @@ -0,0 +1,74 @@ +package com.gitblit.tests; + +import org.junit.Test; + +import com.gitblit.AvatarGenerator; +import com.gitblit.GravatarGenerator; +import com.gitblit.IStoredSettings; +import com.gitblit.Keys; +import com.gitblit.guice.AvatarGeneratorProvider; +import com.gitblit.manager.IRuntimeManager; +import com.gitblit.manager.RuntimeManager; +import com.gitblit.tests.mock.MemorySettings; +import com.gitblit.utils.ActivityUtils; +import com.gitblit.utils.XssFilter; +import com.gitblit.utils.XssFilter.AllowXssFilter; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Injector; + +public class GravatarTest extends GitblitUnitTest { + + public static class AvatarModule extends AbstractModule { + private final IStoredSettings settings; + + AvatarModule(IStoredSettings settings) { + this.settings = settings; + } + + @Override + protected void configure() { + bind(IStoredSettings.class).toInstance(settings); + bind(XssFilter.class).to(AllowXssFilter.class); + bind(IRuntimeManager.class).to(RuntimeManager.class); + bind(AvatarGenerator.class).toProvider(AvatarGeneratorProvider.class); + } + } + + @Test + public void gravatarIdenticonTest() { + IStoredSettings settings = new MemorySettings(); + settings.overrideSetting(Keys.web.avatarClass, GravatarGenerator.class.getName()); + + Injector injector = Guice.createInjector(new AvatarModule(settings)); + AvatarGenerator avatarGenerator = injector.getInstance(AvatarGenerator.class); + + String username = "username"; + String emailAddress = "emailAddress"; + int width = 10; + + String url = avatarGenerator.getURL(username, emailAddress, true, width); + assertNotNull(url); + + assertEquals(ActivityUtils.getGravatarIdenticonUrl(emailAddress, width), url); + } + + @Test + public void gravatarThumbnailTest() { + IStoredSettings settings = new MemorySettings(); + settings.overrideSetting(Keys.web.avatarClass, GravatarGenerator.class.getName()); + + Injector injector = Guice.createInjector(new AvatarModule(settings)); + AvatarGenerator avatarGenerator = injector.getInstance(AvatarGenerator.class); + + String username = "username"; + String emailAddress = "emailAddress"; + int width = 10; + + String url = avatarGenerator.getURL(username, emailAddress, false, width); + assertNotNull(url); + + assertEquals(ActivityUtils.getGravatarThumbnailUrl(emailAddress, width), url); + } + +} diff --git a/src/test/java/com/gitblit/tests/HtpasswdAuthenticationTest.java b/src/test/java/com/gitblit/tests/HtpasswdAuthenticationTest.java index e2bb764e..26a49b24 100644 --- a/src/test/java/com/gitblit/tests/HtpasswdAuthenticationTest.java +++ b/src/test/java/com/gitblit/tests/HtpasswdAuthenticationTest.java @@ -200,43 +200,43 @@ public class HtpasswdAuthenticationTest extends GitblitUnitTest { public void testAuthenticationManager() { MS.put(KEY_SUPPORT_PLAINTEXT_PWD, "true"); - UserModel user = auth.authenticate("user1", "pass1".toCharArray()); + UserModel user = auth.authenticate("user1", "pass1".toCharArray(), null); assertNotNull(user); assertEquals("user1", user.username); - user = auth.authenticate("user2", "pass2".toCharArray()); + user = auth.authenticate("user2", "pass2".toCharArray(), null); assertNotNull(user); assertEquals("user2", user.username); // Test different encryptions - user = auth.authenticate("plain", "passWord".toCharArray()); + user = auth.authenticate("plain", "passWord".toCharArray(), null); assertNotNull(user); assertEquals("plain", user.username); MS.put(KEY_SUPPORT_PLAINTEXT_PWD, "false"); - user = auth.authenticate("crypt", "password".toCharArray()); + user = auth.authenticate("crypt", "password".toCharArray(), null); assertNotNull(user); assertEquals("crypt", user.username); - user = auth.authenticate("md5", "password".toCharArray()); + user = auth.authenticate("md5", "password".toCharArray(), null); assertNotNull(user); assertEquals("md5", user.username); - user = auth.authenticate("sha", "password".toCharArray()); + user = auth.authenticate("sha", "password".toCharArray(), null); assertNotNull(user); assertEquals("sha", user.username); // Test leading and trailing whitespace - user = auth.authenticate("trailing", "whitespace".toCharArray()); + user = auth.authenticate("trailing", "whitespace".toCharArray(), null); assertNotNull(user); assertEquals("trailing", user.username); - user = auth.authenticate("tabbed", "frontAndBack".toCharArray()); + user = auth.authenticate("tabbed", "frontAndBack".toCharArray(), null); assertNotNull(user); assertEquals("tabbed", user.username); - user = auth.authenticate("leading", "whitespace".toCharArray()); + user = auth.authenticate("leading", "whitespace".toCharArray(), null); assertNotNull(user); assertEquals("leading", user.username); } @@ -323,55 +323,55 @@ public class HtpasswdAuthenticationTest extends GitblitUnitTest { { UserModel user = null; MS.put(KEY_SUPPORT_PLAINTEXT_PWD, "true"); - user = auth.authenticate("user1", "".toCharArray()); + user = auth.authenticate("user1", "".toCharArray(), null); assertNull("User 'user1' falsely authenticated.", user); - user = auth.authenticate("user1", "pass2".toCharArray()); + user = auth.authenticate("user1", "pass2".toCharArray(), null); assertNull("User 'user1' falsely authenticated.", user); - user = auth.authenticate("user2", "lalala".toCharArray()); + user = auth.authenticate("user2", "lalala".toCharArray(), null); assertNull("User 'user2' falsely authenticated.", user); - user = auth.authenticate("user3", "disabled".toCharArray()); + user = auth.authenticate("user3", "disabled".toCharArray(), null); assertNull("User 'user3' falsely authenticated.", user); - user = auth.authenticate("user4", "disabled".toCharArray()); + user = auth.authenticate("user4", "disabled".toCharArray(), null); assertNull("User 'user4' falsely authenticated.", user); - user = auth.authenticate("plain", "text".toCharArray()); + user = auth.authenticate("plain", "text".toCharArray(), null); assertNull("User 'plain' falsely authenticated.", user); - user = auth.authenticate("plain", "password".toCharArray()); + user = auth.authenticate("plain", "password".toCharArray(), null); assertNull("User 'plain' falsely authenticated.", user); MS.put(KEY_SUPPORT_PLAINTEXT_PWD, "false"); - user = auth.authenticate("crypt", "".toCharArray()); + user = auth.authenticate("crypt", "".toCharArray(), null); assertNull("User 'cyrpt' falsely authenticated.", user); - user = auth.authenticate("crypt", "passwd".toCharArray()); + user = auth.authenticate("crypt", "passwd".toCharArray(), null); assertNull("User 'crypt' falsely authenticated.", user); - user = auth.authenticate("md5", "".toCharArray()); + user = auth.authenticate("md5", "".toCharArray(), null); assertNull("User 'md5' falsely authenticated.", user); - user = auth.authenticate("md5", "pwd".toCharArray()); + user = auth.authenticate("md5", "pwd".toCharArray(), null); assertNull("User 'md5' falsely authenticated.", user); - user = auth.authenticate("sha", "".toCharArray()); + user = auth.authenticate("sha", "".toCharArray(), null); assertNull("User 'sha' falsely authenticated.", user); - user = auth.authenticate("sha", "letmein".toCharArray()); + user = auth.authenticate("sha", "letmein".toCharArray(), null); assertNull("User 'sha' falsely authenticated.", user); - user = auth.authenticate(" tabbed", "frontAndBack".toCharArray()); + user = auth.authenticate(" tabbed", "frontAndBack".toCharArray(), null); assertNull("User 'tabbed' falsely authenticated.", user); - user = auth.authenticate(" leading", "whitespace".toCharArray()); + user = auth.authenticate(" leading", "whitespace".toCharArray(), null); assertNull("User 'leading' falsely authenticated.", user); } diff --git a/src/test/java/com/gitblit/tests/JGitUtilsTest.java b/src/test/java/com/gitblit/tests/JGitUtilsTest.java index c2cfb331..c273e860 100644 --- a/src/test/java/com/gitblit/tests/JGitUtilsTest.java +++ b/src/test/java/com/gitblit/tests/JGitUtilsTest.java @@ -476,6 +476,15 @@ public class JGitUtilsTest extends GitblitUnitTest { }
@Test
+ public void testFilesInPath2() throws Exception {
+ assertEquals(0, JGitUtils.getFilesInPath2(null, null, null).size());
+ Repository repository = GitBlitSuite.getHelloworldRepository();
+ List<PathModel> files = JGitUtils.getFilesInPath2(repository, null, null);
+ repository.close();
+ assertTrue(files.size() > 10);
+ }
+
+ @Test
public void testDocuments() throws Exception {
Repository repository = GitBlitSuite.getTicgitRepository();
List<String> extensions = Arrays.asList(new String[] { ".mkd", ".md" });
@@ -576,16 +585,16 @@ public class JGitUtilsTest extends GitblitUnitTest { @Test
public void testZip() throws Exception {
- assertFalse(CompressionUtils.zip(null, null, null, null));
+ assertFalse(CompressionUtils.zip(null, null, null, null, null));
Repository repository = GitBlitSuite.getHelloworldRepository();
File zipFileA = new File(GitBlitSuite.REPOSITORIES, "helloworld.zip");
FileOutputStream fosA = new FileOutputStream(zipFileA);
- boolean successA = CompressionUtils.zip(repository, null, Constants.HEAD, fosA);
+ boolean successA = CompressionUtils.zip(repository, null, null, Constants.HEAD, fosA);
fosA.close();
File zipFileB = new File(GitBlitSuite.REPOSITORIES, "helloworld-java.zip");
FileOutputStream fosB = new FileOutputStream(zipFileB);
- boolean successB = CompressionUtils.zip(repository, "java.java", Constants.HEAD, fosB);
+ boolean successB = CompressionUtils.zip(repository, null, "java.java", Constants.HEAD, fosB);
fosB.close();
repository.close();
diff --git a/src/test/java/com/gitblit/tests/LdapAuthenticationTest.java b/src/test/java/com/gitblit/tests/LdapAuthenticationTest.java index 7c84ecc2..84dd138d 100644 --- a/src/test/java/com/gitblit/tests/LdapAuthenticationTest.java +++ b/src/test/java/com/gitblit/tests/LdapAuthenticationTest.java @@ -240,23 +240,23 @@ public class LdapAuthenticationTest extends GitblitUnitTest { @Test public void testAuthenticationManager() { - UserModel userOneModel = auth.authenticate("UserOne", "userOnePassword".toCharArray()); + UserModel userOneModel = auth.authenticate("UserOne", "userOnePassword".toCharArray(), null); assertNotNull(userOneModel); assertNotNull(userOneModel.getTeam("git_admins")); assertNotNull(userOneModel.getTeam("git_users")); assertTrue(userOneModel.canAdmin); - UserModel userOneModelFailedAuth = auth.authenticate("UserOne", "userTwoPassword".toCharArray()); + UserModel userOneModelFailedAuth = auth.authenticate("UserOne", "userTwoPassword".toCharArray(), null); assertNull(userOneModelFailedAuth); - UserModel userTwoModel = auth.authenticate("UserTwo", "userTwoPassword".toCharArray()); + UserModel userTwoModel = auth.authenticate("UserTwo", "userTwoPassword".toCharArray(), null); assertNotNull(userTwoModel); assertNotNull(userTwoModel.getTeam("git_users")); assertNull(userTwoModel.getTeam("git_admins")); assertNotNull(userTwoModel.getTeam("git admins")); assertTrue(userTwoModel.canAdmin); - UserModel userThreeModel = auth.authenticate("UserThree", "userThreePassword".toCharArray()); + UserModel userThreeModel = auth.authenticate("UserThree", "userThreePassword".toCharArray(), null); assertNotNull(userThreeModel); assertNotNull(userThreeModel.getTeam("git_users")); assertNull(userThreeModel.getTeam("git_admins")); @@ -269,10 +269,10 @@ public class LdapAuthenticationTest extends GitblitUnitTest { settings.put(Keys.realm.ldap.username, ""); settings.put(Keys.realm.ldap.password, ""); - UserModel userOneModel = auth.authenticate("UserOne", "userOnePassword".toCharArray()); + UserModel userOneModel = auth.authenticate("UserOne", "userOnePassword".toCharArray(), null); assertNotNull(userOneModel); - UserModel userOneModelFailedAuth = auth.authenticate("UserOne", "userTwoPassword".toCharArray()); + UserModel userOneModelFailedAuth = auth.authenticate("UserOne", "userTwoPassword".toCharArray(), null); assertNull(userOneModelFailedAuth); } diff --git a/src/test/java/com/gitblit/tests/PathUtilsTest.java b/src/test/java/com/gitblit/tests/PathUtilsTest.java new file mode 100644 index 00000000..209b8ee6 --- /dev/null +++ b/src/test/java/com/gitblit/tests/PathUtilsTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2011 gitblit.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitblit.tests; + +import com.gitblit.utils.PathUtils; +import org.junit.Test; + +import java.util.Arrays; + +public class PathUtilsTest extends GitblitUnitTest { + + private static final String[][][] testData = { + + { + // Folder contents + {".gitignore","src/main/java/a.java", "src/main/java/b.java", "docs/c.md"}, + // Expected after compressing + {".gitignore", "src/main/java/", "docs/"} + }, + + { + {".gitignore","src/main/java/a.java", "src/main/b.java", "docs/c.md"}, + {".gitignore", "src/main/", "docs/"} + }, + + { + {".gitignore","src/x.java","src/main/java/a.java", "src/main/java/b.java", "docs/c.md"}, + {".gitignore", "src/", "docs/"} + }, + }; + + + + + @Test + public void testCompressPaths() throws Exception { + + for (String[][] test : testData ) { + assertArrayEquals(test[1], PathUtils.compressPaths(Arrays.asList(test[0])).toArray(new String[]{})); + } + + } + + @Test + public void testGetLastPathComponent() { + assertEquals(PathUtils.getLastPathComponent("/a/b/c/d/e.out"), "e.out"); + assertEquals(PathUtils.getLastPathComponent("e.out"), "e.out"); + assertEquals(PathUtils.getLastPathComponent("/a/b/c/d/"), "d"); + assertEquals(PathUtils.getLastPathComponent("/a/b/c/d"), "d"); + assertEquals(PathUtils.getLastPathComponent("/"), "/"); + } + +}
\ No newline at end of file diff --git a/src/test/java/com/gitblit/tests/RedmineAuthenticationTest.java b/src/test/java/com/gitblit/tests/RedmineAuthenticationTest.java index ad773b7a..7136fa79 100644 --- a/src/test/java/com/gitblit/tests/RedmineAuthenticationTest.java +++ b/src/test/java/com/gitblit/tests/RedmineAuthenticationTest.java @@ -65,7 +65,7 @@ public class RedmineAuthenticationTest extends GitblitUnitTest { @Test public void testAuthenticationManager() throws Exception { AuthenticationManager auth = newAuthenticationManager(); - UserModel userModel = auth.authenticate("RedmineAdminId", "RedmineAPIKey".toCharArray()); + UserModel userModel = auth.authenticate("RedmineAdminId", "RedmineAPIKey".toCharArray(), null); assertThat(userModel.getName(), is("redmineadminid")); assertThat(userModel.getDisplayName(), is("baz foo")); assertThat(userModel.emailAddress, is("baz@example.com")); diff --git a/src/test/java/com/gitblit/tests/SshDaemonTest.java b/src/test/java/com/gitblit/tests/SshDaemonTest.java index dcaeaff8..c5deb7d5 100644 --- a/src/test/java/com/gitblit/tests/SshDaemonTest.java +++ b/src/test/java/com/gitblit/tests/SshDaemonTest.java @@ -19,8 +19,8 @@ import java.io.File; import java.text.MessageFormat; import java.util.List; -import org.apache.sshd.ClientSession; -import org.apache.sshd.SshClient; +import org.apache.sshd.client.SshClient; +import org.apache.sshd.client.session.ClientSession; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.revwalk.RevCommit; diff --git a/src/test/java/com/gitblit/tests/SshKerberosAuthenticationTest.java b/src/test/java/com/gitblit/tests/SshKerberosAuthenticationTest.java new file mode 100644 index 00000000..4ba16b67 --- /dev/null +++ b/src/test/java/com/gitblit/tests/SshKerberosAuthenticationTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2015 gitblit.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitblit.tests; + +import org.apache.sshd.server.auth.gss.GSSAuthenticator; +import org.apache.sshd.server.session.ServerSession; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.gitblit.manager.AuthenticationManager; +import com.gitblit.manager.IRuntimeManager; +import com.gitblit.manager.IUserManager; +import com.gitblit.models.UserModel; +import com.gitblit.tests.mock.MemorySettings; +import com.gitblit.transport.ssh.SshDaemonClient; +import com.gitblit.transport.ssh.SshKrbAuthenticator; + +public class SshKerberosAuthenticationTest extends GitblitUnitTest { + + private static class UserModelWrapper { + public UserModel um; + } + + @Test + public void testUserManager() { + IRuntimeManager rm = Mockito.mock(IRuntimeManager.class); + + //Build an UserManager that can build a UserModel + IUserManager im = Mockito.mock(IUserManager.class); + Mockito.doAnswer(new Answer<Object>() { + @Override + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + String user = (String) args[0]; + return new UserModel(user); + } + }).when(im).getUserModel(Mockito.anyString()); + + AuthenticationManager am = new AuthenticationManager(rm, im); + + GSSAuthenticator gssAuthenticator = new SshKrbAuthenticator(new MemorySettings(), am); + + ServerSession session = Mockito.mock(ServerSession.class); + + //Build an SshDaemonClient that can set and get the UserModel + final UserModelWrapper umw = new UserModelWrapper(); + SshDaemonClient client = Mockito.mock(SshDaemonClient.class); + Mockito.when(client.getUser()).thenReturn(umw.um); + Mockito.doAnswer(new Answer<Object>() { + @Override + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + UserModel um = (UserModel) args[0]; + umw.um = um; + return null; + } + }).when(client).setUser(Mockito.any(UserModel.class)); + + Mockito.when(session.getAttribute(SshDaemonClient.KEY)).thenReturn(client); + Assert.assertTrue(gssAuthenticator.validateIdentity(session, "jhappy")); + + } +} diff --git a/src/test/java/com/gitblit/tests/SshUnitTest.java b/src/test/java/com/gitblit/tests/SshUnitTest.java index 43b51b74..27b4ec73 100644 --- a/src/test/java/com/gitblit/tests/SshUnitTest.java +++ b/src/test/java/com/gitblit/tests/SshUnitTest.java @@ -26,10 +26,10 @@ import java.security.KeyPairGenerator; import java.security.PublicKey; import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.sshd.ClientChannel; -import org.apache.sshd.ClientSession; -import org.apache.sshd.SshClient; import org.apache.sshd.client.ServerKeyVerifier; +import org.apache.sshd.client.SshClient; +import org.apache.sshd.client.channel.ClientChannel; +import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.util.SecurityUtils; import org.junit.After; import org.junit.AfterClass; diff --git a/src/test/java/com/gitblit/tests/StringUtilsTest.java b/src/test/java/com/gitblit/tests/StringUtilsTest.java index 0fd42aad..7176b88c 100644 --- a/src/test/java/com/gitblit/tests/StringUtilsTest.java +++ b/src/test/java/com/gitblit/tests/StringUtilsTest.java @@ -50,7 +50,7 @@ public class StringUtilsTest extends GitblitUnitTest { public void testEscapeForHtml() throws Exception {
String input = "& < > \" \t";
String outputNoChange = "& < > " \t";
- String outputChange = "& < > " ";
+ String outputChange = "& < > " ";
assertEquals(outputNoChange, StringUtils.escapeForHtml(input, false));
assertEquals(outputChange, StringUtils.escapeForHtml(input, true));
}
diff --git a/src/test/java/com/gitblit/tests/TicketServiceTest.java b/src/test/java/com/gitblit/tests/TicketServiceTest.java index 1676e341..c654383d 100644 --- a/src/test/java/com/gitblit/tests/TicketServiceTest.java +++ b/src/test/java/com/gitblit/tests/TicketServiceTest.java @@ -293,9 +293,47 @@ public abstract class TicketServiceTest extends GitblitUnitTest { assertTrue("failed to delete label " + label.name, service.deleteLabel(getRepository(), label.name, "lucifer"));
}
}
-
-
-
+
+ @Test
+ public void testPriorityAndSeverity() throws Exception {
+ // C1: create and insert a ticket
+ Change c1 = newChange("testPriorityAndSeverity() " + Long.toHexString(System.currentTimeMillis()));
+ TicketModel ticket = service.createTicket(getRepository(), c1);
+ assertTrue(ticket.number > 0);
+ assertEquals(TicketModel.Priority.Normal, ticket.priority);
+ assertEquals(TicketModel.Severity.Unrated, ticket.severity);
+
+ TicketModel constructed = service.getTicket(getRepository(), ticket.number);
+ compare(ticket, constructed);
+
+ // C2: Change Priority max
+ Change c2 = new Change("C2");
+ c2.setField(Field.priority, TicketModel.Priority.Urgent);
+ constructed = service.updateTicket(getRepository(), ticket.number, c2);
+ assertNotNull(constructed);
+ assertEquals(2, constructed.changes.size());
+ assertEquals(TicketModel.Priority.Urgent, constructed.priority);
+ assertEquals(TicketModel.Severity.Unrated, constructed.severity);
+
+ // C3: Change Severity max
+ Change c3 = new Change("C3");
+ c3.setField(Field.severity, TicketModel.Severity.Catastrophic);
+ constructed = service.updateTicket(getRepository(), ticket.number, c3);
+ assertNotNull(constructed);
+ assertEquals(3, constructed.changes.size());
+ assertEquals(TicketModel.Priority.Urgent, constructed.priority);
+ assertEquals(TicketModel.Severity.Catastrophic, constructed.severity);
+
+ // C4: Change Priority min
+ Change c4 = new Change("C3");
+ c4.setField(Field.priority, TicketModel.Priority.Low);
+ constructed = service.updateTicket(getRepository(), ticket.number, c4);
+ assertNotNull(constructed);
+ assertEquals(4, constructed.changes.size());
+ assertEquals(TicketModel.Priority.Low, constructed.priority);
+ assertEquals(TicketModel.Severity.Catastrophic, constructed.severity);
+ }
+
private Change newChange(String summary) {
Change change = new Change("C1");
change.setField(Field.title, summary);
diff --git a/src/test/java/com/gitblit/tests/UITicketTest.java b/src/test/java/com/gitblit/tests/UITicketTest.java new file mode 100644 index 00000000..54aa1e1e --- /dev/null +++ b/src/test/java/com/gitblit/tests/UITicketTest.java @@ -0,0 +1,151 @@ +/* + * Copyright 2014 gitblit.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitblit.tests; + +import java.io.File; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.io.FileUtils; +import org.bouncycastle.util.Arrays; +import org.eclipse.jgit.lib.Repository; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.gitblit.IStoredSettings; +import com.gitblit.Keys; +import com.gitblit.manager.INotificationManager; +import com.gitblit.manager.IPluginManager; +import com.gitblit.manager.IRepositoryManager; +import com.gitblit.manager.IRuntimeManager; +import com.gitblit.manager.IUserManager; +import com.gitblit.manager.NotificationManager; +import com.gitblit.manager.PluginManager; +import com.gitblit.manager.RepositoryManager; +import com.gitblit.manager.RuntimeManager; +import com.gitblit.manager.UserManager; +import com.gitblit.models.Mailing; +import com.gitblit.models.RepositoryModel; +import com.gitblit.models.TicketModel; +import com.gitblit.models.TicketModel.Attachment; +import com.gitblit.models.TicketModel.Change; +import com.gitblit.models.TicketModel.Field; +import com.gitblit.models.TicketModel.Patchset; +import com.gitblit.models.TicketModel.Priority; +import com.gitblit.models.TicketModel.Severity; +import com.gitblit.models.TicketModel.Status; +import com.gitblit.models.TicketModel.Type; +import com.gitblit.tests.mock.MemorySettings; +import com.gitblit.tickets.ITicketService; +import com.gitblit.tickets.ITicketService.TicketFilter; +import com.gitblit.tickets.QueryResult; +import com.gitblit.tickets.TicketIndexer.Lucene; +import com.gitblit.tickets.BranchTicketService; +import com.gitblit.tickets.TicketLabel; +import com.gitblit.tickets.TicketMilestone; +import com.gitblit.tickets.TicketNotifier; +import com.gitblit.utils.JGitUtils; +import com.gitblit.utils.XssFilter; +import com.gitblit.utils.XssFilter.AllowXssFilter; + +/** + * Generates the range of tickets to ease testing of the look and feel of tickets + */ +public class UITicketTest extends GitblitUnitTest { + + private ITicketService service; + final String repoName = "UITicketTest.git"; + final RepositoryModel repo = new RepositoryModel(repoName, null, null, null); + + protected ITicketService getService(boolean deleteAll) throws Exception { + + IStoredSettings settings = getSettings(deleteAll); + XssFilter xssFilter = new AllowXssFilter(); + IRuntimeManager runtimeManager = new RuntimeManager(settings, xssFilter).start(); + IPluginManager pluginManager = new PluginManager(runtimeManager).start(); + INotificationManager notificationManager = new NotificationManager(settings).start(); + IUserManager userManager = new UserManager(runtimeManager, pluginManager).start(); + IRepositoryManager repositoryManager = new RepositoryManager(runtimeManager, pluginManager, userManager).start(); + + BranchTicketService service = new BranchTicketService( + runtimeManager, + pluginManager, + notificationManager, + userManager, + repositoryManager).start(); + + if (deleteAll) { + service.deleteAll(repo); + } + return service; + } + + protected IStoredSettings getSettings(boolean deleteAll) throws Exception { + File dir = new File(GitBlitSuite.REPOSITORIES, repoName); + if (deleteAll) { + FileUtils.deleteDirectory(dir); + JGitUtils.createRepository(GitBlitSuite.REPOSITORIES, repoName).close(); + } + + File luceneDir = new File(dir, "tickets/lucene"); + luceneDir.mkdirs(); + + Map<String, Object> map = new HashMap<String, Object>(); + map.put(Keys.git.repositoriesFolder, GitBlitSuite.REPOSITORIES.getAbsolutePath()); + map.put(Keys.tickets.indexFolder, luceneDir.getAbsolutePath()); + + IStoredSettings settings = new MemorySettings(map); + return settings; + } + + @Before + public void setup() throws Exception { + service = getService(true); + } + + @After + public void cleanup() { + service.stop(); + } + + @Test + public void UITicketOptions() throws Exception { + + for (TicketModel.Type t : TicketModel.Type.values()) + { + for (TicketModel.Priority p : TicketModel.Priority.values()) + { + for (TicketModel.Severity s : TicketModel.Severity.values()) + { + assertNotNull(service.createTicket(repo, newChange(t, p, s))); + } + } + } + } + + private Change newChange(Type type, Priority priority, Severity severity) { + Change change = new Change("JUnit"); + change.setField(Field.title, String.format("Type: %s | Priority: %s | Severity: %s", type, priority, severity)); + change.setField(Field.type, type); + change.setField(Field.severity, severity); + change.setField(Field.priority, priority); + return change; + } + +}
\ No newline at end of file diff --git a/src/test/java/com/gitblit/tests/mock/MockRuntimeManager.java b/src/test/java/com/gitblit/tests/mock/MockRuntimeManager.java index 7b563622..8897ef7e 100644 --- a/src/test/java/com/gitblit/tests/mock/MockRuntimeManager.java +++ b/src/test/java/com/gitblit/tests/mock/MockRuntimeManager.java @@ -30,6 +30,7 @@ import com.gitblit.models.ServerStatus; import com.gitblit.models.SettingModel; import com.gitblit.utils.XssFilter; import com.gitblit.utils.XssFilter.AllowXssFilter; +import com.google.inject.Injector; public class MockRuntimeManager implements IRuntimeManager { @@ -59,6 +60,11 @@ public class MockRuntimeManager implements IRuntimeManager { } @Override + public Injector getInjector() { + return null; + } + + @Override public void setBaseFolder(File folder) { this.baseFolder = folder; } @@ -79,26 +85,6 @@ public class MockRuntimeManager implements IRuntimeManager { } @Override - public boolean isServingRepositories() { - return true; - } - - @Override - public boolean isServingHTTP() { - return true; - } - - @Override - public boolean isServingGIT() { - return true; - } - - @Override - public boolean isServingSSH() { - return true; - } - - @Override public boolean isDebugMode() { return true; } |