repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/parenmatch/ParenMatchHighlighterTests.java
javatests/com/google/collide/client/code/parenmatch/ParenMatchHighlighterTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.parenmatch; import static com.google.collide.client.editor.search.SearchTestsUtil.createMockViewport; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.client.editor.search.SearchTask.SearchDirection; import com.google.collide.client.editor.selection.SelectionModel.CursorListener; import com.google.collide.client.testing.StubIncrementalScheduler; import com.google.collide.client.util.IncrementalScheduler; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerRegistrar; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import junit.framework.TestCase; import org.easymock.EasyMock; /** * Tests the ParenMatchHighlighter's ability to find the correct match * */ public class ParenMatchHighlighterTests extends TestCase { private Document document; private ParenMatchHighlighter parenMatchHighlighter; private AnchorManager mockAnchorManager; public void customSetUp(ImmutableList<String> lines) { document = Document.createFromString(Joiner.on('\n').join(lines)); mockAnchorManager = EasyMock.createMock(AnchorManager.class); ParenMatchHighlighter.Css mockCss = EasyMock.createNiceMock(ParenMatchHighlighter.Css.class); expect(mockCss.match()).andReturn("whatever"); replay(mockCss); ParenMatchHighlighter.Resources mockResources = EasyMock.createNiceMock(ParenMatchHighlighter.Resources.class); expect(mockResources.parenMatchHighlighterCss()).andReturn(mockCss); replay(mockResources); Renderer mockRenderer = EasyMock.createNiceMock(Renderer.class); replay(mockRenderer); IncrementalScheduler stubScheduler = new StubIncrementalScheduler(10, 1000); ListenerRegistrar<CursorListener> listenerRegistrar = ListenerManager.create(); parenMatchHighlighter = new ParenMatchHighlighter(document, createMockViewport(document, lines.size()), mockAnchorManager, mockResources, mockRenderer, stubScheduler, listenerRegistrar); } public void testMatchDownSameLine() { customSetUp(ImmutableList.of("(text {in} between)")); LineInfo startLineInfo = document.getFirstLineInfo(); // should find the match on line 1, at column 16 expect( mockAnchorManager.createAnchor(EasyMock.eq(ParenMatchHighlighter.MATCH_ANCHOR_TYPE), EasyMock.eq(startLineInfo.line()), EasyMock.eq(0), EasyMock.eq(18))).andReturn(null); replay(mockAnchorManager); parenMatchHighlighter.search(SearchDirection.DOWN, ')', '(', startLineInfo, 1); verify(mockAnchorManager); } public void testMatchUpSameLine() { customSetUp(ImmutableList.of("<img src='img.jpg' name='test'>")); LineInfo startLineInfo = document.getFirstLineInfo(); // should fine the match one line 1, column 0 expect( mockAnchorManager.createAnchor(EasyMock.eq(ParenMatchHighlighter.MATCH_ANCHOR_TYPE), EasyMock.eq(startLineInfo.line()), EasyMock.eq(0), EasyMock.eq(0))).andReturn(null); replay(mockAnchorManager); parenMatchHighlighter.search(SearchDirection.UP, '<', '>', startLineInfo, 31); verify(mockAnchorManager); } /** * Starts after first { and searches down for } <code> * function foo() { * var temp = 1; * } * </code> */ public void testMatchDownDifferentLines() { customSetUp(ImmutableList.of("function foo() {", " var temp = 1;", "}")); Line startLine = document.getFirstLine(); Line matchLine = document.getLastLine(); // should find the match on line 3, column 0 expect( mockAnchorManager.createAnchor(EasyMock.eq(ParenMatchHighlighter.MATCH_ANCHOR_TYPE), EasyMock.eq(matchLine), EasyMock.eq(3), EasyMock.eq(0))).andReturn(null); replay(mockAnchorManager); parenMatchHighlighter.search(SearchDirection.DOWN, '}', '{', new LineInfo(startLine, 1), 16); verify(mockAnchorManager); } /** * Starts after last ] and searches up for [ <code> * var list = ['str1', * 'str2', * 'str3'] * </code> */ public void testMatchUpDifferentLines() { final ImmutableList<String> documentText = ImmutableList.of("var list = ['str1',", " 'str2',", " 'str3']"); customSetUp(documentText); LineInfo startLineInfo = document.getLastLineInfo(); Line matchLine = document.getFirstLine(); // should find the match on line 1, column 11 expect( mockAnchorManager.createAnchor(EasyMock.eq(ParenMatchHighlighter.MATCH_ANCHOR_TYPE), EasyMock.eq(matchLine), EasyMock.eq(0), EasyMock.eq(11))).andReturn(null); replay(mockAnchorManager); parenMatchHighlighter.search(SearchDirection.UP, '[', ']', startLineInfo, 10); verify(mockAnchorManager); } /** * Starts after the first [ and searches down for the closing ]. It should * skip the open and close brackets in between. <code> * var list = ['str1', * 'str2', * ['sub1','sub2'], * 'str3'] * </code> */ public void testMatchWithFalseMatches() { final ImmutableList<String> documentText = ImmutableList.of("var list = ['str1',", "'str2',", " ['sub1','sub2'],", " 'str3']"); customSetUp(documentText); Line startLine = document.getFirstLine(); Line matchLine = document.getLastLine(); // should find match on line 4, column 11 expect( mockAnchorManager.createAnchor(EasyMock.eq(ParenMatchHighlighter.MATCH_ANCHOR_TYPE), EasyMock.eq(matchLine), EasyMock.eq(4), EasyMock.eq(9))).andReturn(null); replay(mockAnchorManager); parenMatchHighlighter.search(SearchDirection.DOWN, ']', '[', new LineInfo(startLine, 1), 12); verify(mockAnchorManager); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/debugging/DebuggingSidebarBreakpointsPaneTest.java
javatests/com/google/collide/client/code/debugging/DebuggingSidebarBreakpointsPaneTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.debugging; import com.google.collide.client.testing.MockAppContext; import com.google.collide.client.util.PathUtil; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.gwt.junit.client.GWTTestCase; /** * Tests for {@link DebuggingSidebarBreakpointsPane}. */ public class DebuggingSidebarBreakpointsPaneTest extends GWTTestCase { private JsonArray<String> viewMessages; private int breakpointCount; private DebuggingSidebarBreakpointsPane debuggingSidebarBreakpointsPane; @Override protected void gwtSetUp() { viewMessages = JsonCollections.createArray(); breakpointCount = 0; DebuggingSidebarBreakpointsPane.View viewDecorator = new DebuggingSidebarBreakpointsPane.View(new MockAppContext().getResources()) { @Override void addBreakpointSection(int sectionIndex) { viewMessages.add("add section " + sectionIndex); super.addBreakpointSection(sectionIndex); } @Override void removeBreakpointSection(int sectionIndex) { viewMessages.add("remove section " + sectionIndex); super.removeBreakpointSection(sectionIndex); } @Override void addBreakpoint(int sectionIndex, int breakpointIndex) { ++breakpointCount; viewMessages.add("add breakpoint " + sectionIndex + ":" + breakpointIndex); super.addBreakpoint(sectionIndex, breakpointIndex); } @Override void removeBreakpoint(int sectionIndex, int breakpointIndex) { --breakpointCount; viewMessages.add("remove breakpoint " + sectionIndex + ":" + breakpointIndex); super.removeBreakpoint(sectionIndex, breakpointIndex); } }; debuggingSidebarBreakpointsPane = new DebuggingSidebarBreakpointsPane(viewDecorator); } @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testAddAndRemoveBreakpoint() { assertAddBreakpoint("/js/foo.js", 10, "add section 0,add breakpoint 0:0"); assertEquals(1, breakpointCount); assertRemoveBreakpoint("/js/foo.js", 10, "remove breakpoint 0:0,remove section 0"); assertEquals(0, breakpointCount); } public void testAddBreakpointsForOneFile() { assertAddBreakpoint("/js/foo.js", 10, "add section 0,add breakpoint 0:0"); assertAddBreakpoint("/js/foo.js", 20, "add breakpoint 0:1"); assertAddBreakpoint("/js/foo.js", 30, "add breakpoint 0:2"); assertAddBreakpoint("/js/foo.js", 5, "add breakpoint 0:0"); assertAddBreakpoint("/js/foo.js", 0, "add breakpoint 0:0"); assertAddBreakpoint("/js/foo.js", 15, "add breakpoint 0:3"); assertEquals(6, breakpointCount); assertRemoveBreakpoint("/js/foo.js", 15, "remove breakpoint 0:3"); assertRemoveBreakpoint("/js/foo.js", 30, "remove breakpoint 0:4"); assertAddBreakpoint("/js/foo.js", 35, "add breakpoint 0:4"); assertRemoveBreakpoint("/js/foo.js", 5, "remove breakpoint 0:1"); assertRemoveBreakpoint("/js/foo.js", 0, "remove breakpoint 0:0"); assertRemoveBreakpoint("/js/foo.js", 35, "remove breakpoint 0:2"); assertRemoveBreakpoint("/js/foo.js", 10, "remove breakpoint 0:0"); assertRemoveBreakpoint("/js/foo.js", 20, "remove breakpoint 0:0,remove section 0"); assertEquals(0, breakpointCount); } public void testAddBreakpointsForUniqueFiles() { assertAddBreakpoint("/a/c/foo4.js", 10, "add section 0,add breakpoint 0:0"); assertAddBreakpoint("/a/c/foo6.js", 10, "add section 1,add breakpoint 1:0"); assertAddBreakpoint("/a/c/foo1.js", 10, "add section 0,add breakpoint 0:0"); assertAddBreakpoint("/a/b/zzz4.js", 10, "add section 0,add breakpoint 0:0"); assertAddBreakpoint("/a/d/aaa4.js", 10, "add section 4,add breakpoint 4:0"); assertEquals(5, breakpointCount); assertRemoveBreakpoint("/a/c/foo6.js", 10, "remove breakpoint 3:0,remove section 3"); assertRemoveBreakpoint("/a/b/zzz4.js", 10, "remove breakpoint 0:0,remove section 0"); assertRemoveBreakpoint("/a/d/aaa4.js", 10, "remove breakpoint 2:0,remove section 2"); assertRemoveBreakpoint("/a/c/foo4.js", 10, "remove breakpoint 1:0,remove section 1"); assertRemoveBreakpoint("/a/c/foo1.js", 10, "remove breakpoint 0:0,remove section 0"); assertEquals(0, breakpointCount); } public void testAddBreakpointsForMixedFiles() { assertAddBreakpoint("/js/foo.js", 10, "add section 0,add breakpoint 0:0"); assertAddBreakpoint("/js/bar.js", 10, "add section 0,add breakpoint 0:0"); assertAddBreakpoint("/js/foo.js", 20, "add breakpoint 1:1"); assertAddBreakpoint("/js/bar.js", 20, "add breakpoint 0:1"); assertAddBreakpoint("/js/foo.js", 30, "add breakpoint 1:2"); assertAddBreakpoint("/js/bar.js", 30, "add breakpoint 0:2"); assertEquals(6, breakpointCount); assertRemoveBreakpoint("/js/bar.js", 20, "remove breakpoint 0:1"); assertRemoveBreakpoint("/js/foo.js", 10, "remove breakpoint 1:0"); assertRemoveBreakpoint("/js/bar.js", 10, "remove breakpoint 0:0"); assertRemoveBreakpoint("/js/bar.js", 30, "remove breakpoint 0:0,remove section 0"); assertRemoveBreakpoint("/js/foo.js", 20, "remove breakpoint 0:0"); assertRemoveBreakpoint("/js/foo.js", 30, "remove breakpoint 0:0,remove section 0"); assertEquals(0, breakpointCount); } public void testAddBreakpointsBetweenSections() { assertAddBreakpoint("/js/bar.js", 10, "add section 0,add breakpoint 0:0"); assertAddBreakpoint("/js/bar.js", 20, "add breakpoint 0:1"); assertAddBreakpoint("/js/bar.js", 30, "add breakpoint 0:2"); assertAddBreakpoint("/js/foo.js", 10, "add section 1,add breakpoint 1:0"); assertAddBreakpoint("/js/foo.js", 20, "add breakpoint 1:1"); assertAddBreakpoint("/js/foo.js", 30, "add breakpoint 1:2"); assertAddBreakpoint("/js/baz.js", 10, "add section 1,add breakpoint 1:0"); assertRemoveBreakpoint("/js/baz.js", 10, "remove breakpoint 1:0,remove section 1"); assertAddBreakpoint("/js/baa.js", 10, "add section 0,add breakpoint 0:0"); assertRemoveBreakpoint("/js/baa.js", 10, "remove breakpoint 0:0,remove section 0"); assertAddBreakpoint("/js/zoo.js", 10, "add section 2,add breakpoint 2:0"); assertRemoveBreakpoint("/js/zoo.js", 10, "remove breakpoint 2:0,remove section 2"); assertRemoveBreakpoint("/js/foo.js", 30, "remove breakpoint 1:2"); assertRemoveBreakpoint("/js/foo.js", 20, "remove breakpoint 1:1"); assertRemoveBreakpoint("/js/foo.js", 10, "remove breakpoint 1:0,remove section 1"); assertRemoveBreakpoint("/js/bar.js", 30, "remove breakpoint 0:2"); assertRemoveBreakpoint("/js/bar.js", 20, "remove breakpoint 0:1"); assertRemoveBreakpoint("/js/bar.js", 10, "remove breakpoint 0:0,remove section 0"); assertEquals(0, breakpointCount); } public void testAddBreakpointsInSubfolders() { assertAddBreakpoint("/bar.js", 10, "add section 0,add breakpoint 0:0"); assertAddBreakpoint("/test.html", 10, "add section 1,add breakpoint 1:0"); assertAddBreakpoint("/test.js", 10, "add section 2,add breakpoint 2:0"); assertAddBreakpoint("/folder/foo.js", 10, "add section 3,add breakpoint 3:0"); assertAddBreakpoint("/folder/sub/zoo.js", 10, "add section 4,add breakpoint 4:0"); assertRemoveBreakpoint("/bar.js", 10, "remove breakpoint 0:0,remove section 0"); assertRemoveBreakpoint("/test.html", 10, "remove breakpoint 0:0,remove section 0"); assertRemoveBreakpoint("/test.js", 10, "remove breakpoint 0:0,remove section 0"); assertRemoveBreakpoint("/folder/foo.js", 10, "remove breakpoint 0:0,remove section 0"); assertRemoveBreakpoint("/folder/sub/zoo.js", 10, "remove breakpoint 0:0,remove section 0"); assertEquals(0, breakpointCount); } private void assertAddBreakpoint(String path, int lineNumber, String message) { Breakpoint breakpoint = new Breakpoint.Builder(new PathUtil(path), lineNumber).build(); debuggingSidebarBreakpointsPane.addBreakpoint(breakpoint); assertEquals(path + ":" + lineNumber, message, viewMessages.join(",")); assertEquals(path + ":" + lineNumber, breakpointCount, debuggingSidebarBreakpointsPane.getBreakpointCount()); viewMessages.clear(); } private void assertRemoveBreakpoint(String path, int lineNumber, String message) { Breakpoint breakpoint = new Breakpoint.Builder(new PathUtil(path), lineNumber).build(); debuggingSidebarBreakpointsPane.removeBreakpoint(breakpoint); assertEquals(path + ":" + lineNumber, message, viewMessages.join(",")); assertEquals(path + ":" + lineNumber, breakpointCount, debuggingSidebarBreakpointsPane.getBreakpointCount()); viewMessages.clear(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/debugging/DebuggerChromeApiUtilsTest.java
javatests/com/google/collide/client/code/debugging/DebuggerChromeApiUtilsTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.debugging; import com.google.collide.client.code.debugging.DebuggerApiTypes.CssStyleSheetHeader; import com.google.collide.client.code.debugging.DebuggerApiTypes.Location; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnAllCssStyleSheetsResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnBreakpointResolvedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnEvaluateExpressionResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnRemoteObjectPropertiesResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnScriptParsedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.PropertyDescriptor; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectSubType; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectType; import com.google.collide.json.client.Jso; import com.google.collide.json.shared.JsonArray; import com.google.gwt.junit.client.GWTTestCase; /** * Tests for {@link DebuggerChromeApiUtils}. * */ public class DebuggerChromeApiUtilsTest extends GWTTestCase { @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } /* // TODO: Update the test when the protocol is stable. public void testParseOnPausedResponse() { String serializedResponse = "{\"id\":null,\"method\":\"Debugger.paused\"," + "\"target\":\"505600000\",\"result\":{\"details\":{\"callFrames\":[{\"functionName\":" + "\"\",\"id\":\"{\\\"ordinal\\\":0,\\\"injectedScriptId\\\":1}\",\"location\":" + "{\"columnNumber\":8,\"lineNumber\":9,\"scriptId\":\"32\"},\"scopeChain\":[{\"object\":" + "{\"className\":\"DOMWindow\",\"description\":\"DOMWindow\",\"objectId\":" + "\"{\\\"injectedScriptId\\\":1,\\\"id\\\":1}\",\"type\":\"object\"},\"type\":" + "\"global\"}],\"this\":{\"className\":\"DOMWindow\",\"description\":\"DOMWindow\"," + "\"objectId\":\"{\\\"injectedScriptId\\\":1,\\\"id\\\":2}\",\"type\":\"object\"}}]," + "\"eventData\":{},\"eventType\":0}}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); OnPausedResponse parsedResponse = DebuggerChromeApiUtils.parseOnPausedResponse(result); assertNotNull(parsedResponse); JsonArray<CallFrame> callFrames = parsedResponse.getCallFrames(); assertNotNull(callFrames); assertEquals(1, callFrames.size()); // First call frame. CallFrame callFrame = callFrames.get(0); assertEquals("", callFrame.getFunctionName()); assertEquals("{\"ordinal\":0,\"injectedScriptId\":1}", callFrame.getId()); assertLocation(9, 8, "32", callFrame.getLocation()); assertRemoteObject("DOMWindow", true, "{\"injectedScriptId\":1,\"id\":2}", RemoteObjectType.OBJECT, null, callFrame.getThis()); JsonArray<Scope> scopeChain = callFrame.getScopeChain(); assertNotNull(scopeChain); assertEquals(1, scopeChain.size()); assertEquals(ScopeType.GLOBAL, scopeChain.get(0).getType()); assertRemoteObject("DOMWindow", true, "{\"injectedScriptId\":1,\"id\":1}", RemoteObjectType.OBJECT, null, scopeChain.get(0).getObject()); } */ public void testParseOnBreakpointResolvedResponse() { String serializedResponse = "{\"id\":null,\"method\":\"Debugger.breakpointResolved\"," + "\"target\":\"48715528\",\"result\":{\"breakpointId\":" + "\"http://closure-library.googlecode.com/svn/trunk/closure/goog/base.js:317:0\"," + "\"location\":{\"columnNumber\":4,\"lineNumber\":317,\"scriptId\":\"33\"}}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); OnBreakpointResolvedResponse parsedResponse = DebuggerChromeApiUtils.parseOnBreakpointResolvedResponse(request, result); assertNotNull(parsedResponse); assertEquals("http://closure-library.googlecode.com/svn/trunk/closure/goog/base.js:317:0", parsedResponse.getBreakpointId()); assertNull(parsedResponse.getBreakpointInfo()); JsonArray<Location> locations = parsedResponse.getLocations(); assertNotNull(locations); assertEquals(1, locations.size()); assertLocation(317, 4, "33", locations.get(0)); } public void testParseOnRemoveBreakpoint() { String serializedResponse = "{\"id\":4,\"method\":\"Debugger.removeBreakpoint\"," + "\"target\":\"48715528\",\"request\":{\"breakpointId\":" + "\"http://closure-library.googlecode.com/svn/trunk/closure/goog/base.js:317:0\"}," + "\"result\":{}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); String breakpointId = DebuggerChromeApiUtils.parseOnRemoveBreakpointResponse(request); assertEquals("http://closure-library.googlecode.com/svn/trunk/closure/goog/base.js:317:0", breakpointId); } public void testParseOnScriptParsedResponse() { String serializedResponse = "{\"id\":null,\"method\":\"Debugger.scriptParsed\"," + "\"target\":\"48715528\",\"result\":{\"endColumn\":1,\"endLine\":1502," + "\"scriptId\":\"33\",\"startColumn\":0,\"startLine\":0,\"url\":" + "\"http://closure-library.googlecode.com/svn/trunk/closure/goog/base.js\"}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); OnScriptParsedResponse parsedResponse = DebuggerChromeApiUtils.parseOnScriptParsedResponse( result); assertNotNull(parsedResponse); assertEquals(0, parsedResponse.getStartLine()); assertEquals(0, parsedResponse.getStartColumn()); assertEquals(1502, parsedResponse.getEndLine()); assertEquals(1, parsedResponse.getEndColumn()); assertEquals("33", parsedResponse.getScriptId()); assertEquals("http://closure-library.googlecode.com/svn/trunk/closure/goog/base.js", parsedResponse.getUrl()); assertFalse(parsedResponse.isContentScript()); } public void testParseOnScriptParsedResponseForContentScript() { String serializedResponse = "{\"id\":null,\"method\":\"Debugger.scriptParsed\"," + "\"target\":\"48715528\",\"result\":{\"endColumn\":511,\"endLine\":18," + "\"isContentScript\":true,\"scriptId\":\"32\",\"startColumn\":0,\"startLine\":0," + "\"url\":\"chrome-extension://plcnnpdmhobdfbponjpedobekiogmbco/content/main.js\"}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); OnScriptParsedResponse parsedResponse = DebuggerChromeApiUtils.parseOnScriptParsedResponse( result); assertNotNull(parsedResponse); assertEquals(0, parsedResponse.getStartLine()); assertEquals(0, parsedResponse.getStartColumn()); assertEquals(18, parsedResponse.getEndLine()); assertEquals(511, parsedResponse.getEndColumn()); assertEquals("32", parsedResponse.getScriptId()); assertEquals("chrome-extension://plcnnpdmhobdfbponjpedobekiogmbco/content/main.js", parsedResponse.getUrl()); assertTrue(parsedResponse.isContentScript()); } public void testParseOnRemoteObjectPropertiesResponse() { String serializedResponse = "{\"id\":5,\"method\":\"Runtime.getProperties\"," + "\"target\":\"292044344\",\"request\":{\"objectId\":\"{\\\"injectedScriptId\\\":1," + "\\\"id\\\":13}\",\"ignoreHasOwnProperty\":false},\"result\":{\"result\":" + "[{\"name\":\"msg\",\"value\":{\"description\":\"onTimer callback\"," + "\"type\":\"string\"}},{\"name\":\"logs\",\"value\":{\"className\":" + "\"HTMLDivElement\",\"description\":\"HTMLDivElement\",\"hasChildren\":true," + "\"objectId\":\"{\\\"injectedScriptId\\\":1,\\\"id\\\":19}\",\"type\":\"object\"," + "\"subtype\":\"node\"}}]}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); OnRemoteObjectPropertiesResponse parsedResponse = DebuggerChromeApiUtils.parseOnRemoteObjectPropertiesResponse(request, result); assertNotNull(parsedResponse); assertEquals("{\"injectedScriptId\":1,\"id\":13}", parsedResponse.getObjectId().toString()); JsonArray<PropertyDescriptor> properties = parsedResponse.getProperties(); assertNotNull(properties); assertEquals(2, properties.size()); PropertyDescriptor propertyDescriptor = properties.get(0); assertNull(propertyDescriptor.getGetterFunction()); assertNull(propertyDescriptor.getSetterFunction()); assertEquals("msg", propertyDescriptor.getName()); assertRemoteObject("onTimer callback", false, null, RemoteObjectType.STRING, null, propertyDescriptor.getValue()); assertFalse(propertyDescriptor.wasThrown()); propertyDescriptor = properties.get(1); assertNull(propertyDescriptor.getGetterFunction()); assertNull(propertyDescriptor.getSetterFunction()); assertEquals("logs", propertyDescriptor.getName()); assertRemoteObject("HTMLDivElement", true, "{\"injectedScriptId\":1,\"id\":19}", RemoteObjectType.OBJECT, RemoteObjectSubType.NODE, propertyDescriptor.getValue()); assertFalse(propertyDescriptor.wasThrown()); } public void testParseOnEvaluateExpressionResponse() { String serializedResponse = "{\"id\":8,\"method\":\"Debugger.evaluateOnCallFrame\"," + "\"target\":\"400060083\",\"request\":{\"callFrameId\":\"{\\\"ordinal\\\":0," + "\\\"injectedScriptId\\\":1}\",\"expression\":\"myArray\"},\"result\":{\"result\":{" + "\"className\":\"Array\",\"description\":\"Array[4]\",\"hasChildren\":true,\"objectId\":" + "\"{\\\"injectedScriptId\\\":1,\\\"id\\\":12}\",\"type\":\"object\"," + "\"subtype\":\"array\"}}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); OnEvaluateExpressionResponse parsedResponse = DebuggerChromeApiUtils.parseOnEvaluateExpressionResponse(request, result); assertNotNull(parsedResponse); assertEquals("{\"ordinal\":0,\"injectedScriptId\":1}", parsedResponse.getCallFrameId()); assertEquals("myArray", parsedResponse.getExpression()); assertRemoteObject("Array[4]", true, "{\"injectedScriptId\":1,\"id\":12}", RemoteObjectType.OBJECT, RemoteObjectSubType.ARRAY, parsedResponse.getResult()); assertFalse(parsedResponse.wasThrown()); } public void testParseOnEvaluateExpressionResponseWasThrown() { String serializedResponse = "{\"id\":9,\"method\":\"Debugger.evaluateOnCallFrame\"," + "\"target\":\"400060083\",\"request\":{\"callFrameId\":\"{\\\"ordinal\\\":0," + "\\\"injectedScriptId\\\":1}\",\"expression\":\"myArray1\"},\"result\":{\"result\":{" + "\"className\":\"ReferenceError\",\"description\":\"ReferenceError\"," + "\"hasChildren\":true,\"objectId\":\"{\\\"injectedScriptId\\\":1,\\\"id\\\":13}\"," + "\"type\":\"object\"},\"wasThrown\":true}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); OnEvaluateExpressionResponse parsedResponse = DebuggerChromeApiUtils.parseOnEvaluateExpressionResponse(request, result); assertNotNull(parsedResponse); assertEquals("{\"ordinal\":0,\"injectedScriptId\":1}", parsedResponse.getCallFrameId()); assertEquals("myArray1", parsedResponse.getExpression()); assertRemoteObject("ReferenceError", true, "{\"injectedScriptId\":1,\"id\":13}", RemoteObjectType.OBJECT, null, parsedResponse.getResult()); assertTrue(parsedResponse.wasThrown()); } public void testParseOnAllCssStyleSheetsResponse() { String serializedResponse = "{\"id\":9,\"method\":\"CSS.getAllStyleSheets\"," + "\"target\":\"400060083\",\"result\":{\"headers\":[{\"disabled\":false," + "\"sourceURL\":\"http://localhost/test.css\",\"styleSheetId\":\"2\",\"title\":\"\"}]}}"; Jso response = Jso.deserialize(serializedResponse); Jso request = response.getJsObjectField("request").cast(); Jso result = response.getJsObjectField("result").cast(); OnAllCssStyleSheetsResponse parsedResponse = DebuggerChromeApiUtils.parseOnAllCssStyleSheetsResponse(result); assertNotNull(parsedResponse); JsonArray<CssStyleSheetHeader> headers = parsedResponse.getHeaders(); assertNotNull(headers); assertEquals(1, headers.size()); CssStyleSheetHeader header = headers.get(0); assertFalse(header.isDisabled()); assertEquals("2", header.getId()); assertEquals("", header.getTitle()); assertEquals("http://localhost/test.css", header.getUrl()); } private void assertLocation(int lineNumber, int columnNumber, String scriptId, Location loc) { assertEquals(lineNumber, loc.getLineNumber()); assertEquals(columnNumber, loc.getColumnNumber()); assertEquals(scriptId, loc.getScriptId()); } private void assertRemoteObject(String description, boolean hasChildren, String objectId, RemoteObjectType type, RemoteObjectSubType subtype, RemoteObject object) { assertEquals(description, object.getDescription()); assertEquals(hasChildren, object.hasChildren()); if (objectId == null) { assertNull(object.getObjectId()); } else { assertNotNull(object.getObjectId()); assertEquals(objectId, object.getObjectId().toString()); } assertEquals(type, object.getType()); assertEquals(subtype, object.getSubType()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/debugging/DebuggerApiUtilsTest.java
javatests/com/google/collide/client/code/debugging/DebuggerApiUtilsTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.debugging; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectId; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectSubType; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectType; import com.google.collide.json.client.Jso; import com.google.gwt.junit.client.GWTTestCase; /** * Tests for {@link DebuggerApiUtils}. * */ public class DebuggerApiUtilsTest extends GWTTestCase { private static class RemoteObjectImpl implements RemoteObject { private final String description; private final RemoteObjectType type; private final RemoteObjectSubType subType; public RemoteObjectImpl(String description, RemoteObjectType type) { this(description, type, null); } public RemoteObjectImpl(String description, RemoteObjectType type, RemoteObjectSubType subType) { this.description = description; this.type = type; this.subType = subType; } @Override public String getDescription() { return description; } @Override public boolean hasChildren() { return false; } @Override public RemoteObjectId getObjectId() { return null; } @Override public RemoteObjectType getType() { return type; } @Override public RemoteObjectSubType getSubType() { return subType; } } private static final RemoteObject NAN_REMOTE_OBJECT = new RemoteObjectImpl("NaN", RemoteObjectType.NUMBER); private static final RemoteObject POSITIVE_INFINITY_REMOTE_OBJECT = new RemoteObjectImpl("Infinity", RemoteObjectType.NUMBER); private static final RemoteObject NEGATIVE_INFINITY_REMOTE_OBJECT = new RemoteObjectImpl("-Infinity", RemoteObjectType.NUMBER); private static final RemoteObject NULL_REMOTE_OBJECT = new RemoteObjectImpl("null", RemoteObjectType.OBJECT, RemoteObjectSubType.NULL); private static final RemoteObject BOOLEAN_TRUE_REMOTE_OBJECT = new RemoteObjectImpl("true", RemoteObjectType.BOOLEAN); private static final RemoteObject BOOLEAN_FALSE_REMOTE_OBJECT = new RemoteObjectImpl("false", RemoteObjectType.BOOLEAN); private static final RemoteObject UNDEFINED_REMOTE_OBJECT = DebuggerApiTypes.UNDEFINED_REMOTE_OBJECT; @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testAddPrimitiveJsoFieldForNumber() { final RemoteObject remoteNumber = new RemoteObjectImpl("123", RemoteObjectType.NUMBER); Jso jso = Jso.create(); assertTrue(DebuggerApiUtils.addPrimitiveJsoField(jso, "key", remoteNumber)); String serializedJso = Jso.serialize(jso); assertEquals("{\"key\":123}", serializedJso); } public void testAddPrimitiveJsoFieldForNonFiniteNumbers() { Jso jso = Jso.create(); assertFalse(DebuggerApiUtils.addPrimitiveJsoField(jso, "key", NAN_REMOTE_OBJECT)); assertFalse(DebuggerApiUtils.addPrimitiveJsoField(jso, "key", POSITIVE_INFINITY_REMOTE_OBJECT)); assertFalse(DebuggerApiUtils.addPrimitiveJsoField(jso, "key", NEGATIVE_INFINITY_REMOTE_OBJECT)); } public void testAddPrimitiveJsoFieldForNull() { Jso jso = Jso.create(); assertTrue(DebuggerApiUtils.addPrimitiveJsoField(jso, "key", NULL_REMOTE_OBJECT)); String serializedJso = Jso.serialize(jso); assertEquals("{\"key\":null}", serializedJso); } public void testAddPrimitiveJsoFieldForBoolean() { Jso jso = Jso.create(); assertTrue(DebuggerApiUtils.addPrimitiveJsoField(jso, "key1", BOOLEAN_TRUE_REMOTE_OBJECT)); assertTrue(DebuggerApiUtils.addPrimitiveJsoField(jso, "key2", BOOLEAN_FALSE_REMOTE_OBJECT)); String serializedJso = Jso.serialize(jso); assertEquals("{\"key1\":true,\"key2\":false}", serializedJso); } public void testAddPrimitiveJsoFieldForString() { final RemoteObject empty = new RemoteObjectImpl("", RemoteObjectType.STRING); final RemoteObject nonEmpty = new RemoteObjectImpl("abc", RemoteObjectType.STRING); Jso jso = Jso.create(); assertTrue(DebuggerApiUtils.addPrimitiveJsoField(jso, "key1", empty)); assertTrue(DebuggerApiUtils.addPrimitiveJsoField(jso, "key2", nonEmpty)); String serializedJso = Jso.serialize(jso); assertEquals("{\"key1\":\"\",\"key2\":\"abc\"}", serializedJso); } public void testAddPrimitiveJsoFieldForUndefined() { Jso jso = Jso.create(); assertTrue(DebuggerApiUtils.addPrimitiveJsoField(jso, "key", UNDEFINED_REMOTE_OBJECT)); String serializedJso = Jso.serialize(jso); assertTrue(jso.hasOwnProperty("key")); assertEquals("{}", serializedJso); } public void testCastToBooleanForNumber() { final RemoteObject zero = new RemoteObjectImpl("0", RemoteObjectType.NUMBER); final RemoteObject nonZero = new RemoteObjectImpl("123", RemoteObjectType.NUMBER); assertFalse("Zero should cast to false", DebuggerApiUtils.castToBoolean(zero)); assertTrue("Non-zero should cast to true", DebuggerApiUtils.castToBoolean(nonZero)); } public void testCastToBooleanForNonFiniteNumbers() { assertFalse("NaN should cast to false", DebuggerApiUtils.castToBoolean(NAN_REMOTE_OBJECT)); assertTrue("Infinity should cast to true", DebuggerApiUtils.castToBoolean(POSITIVE_INFINITY_REMOTE_OBJECT)); assertTrue("-Infinity should cast to true", DebuggerApiUtils.castToBoolean(NEGATIVE_INFINITY_REMOTE_OBJECT)); } public void testCastToBooleanForNull() { assertFalse("Null should cast to false", DebuggerApiUtils.castToBoolean(NULL_REMOTE_OBJECT)); } public void testCastToBooleanForBoolean() { assertTrue(DebuggerApiUtils.castToBoolean(BOOLEAN_TRUE_REMOTE_OBJECT)); assertFalse(DebuggerApiUtils.castToBoolean(BOOLEAN_FALSE_REMOTE_OBJECT)); } public void testCastToBooleanForString() { final RemoteObject empty = new RemoteObjectImpl("", RemoteObjectType.STRING); final RemoteObject nonEmpty = new RemoteObjectImpl("abc", RemoteObjectType.STRING); assertFalse("Empty string should cast to false", DebuggerApiUtils.castToBoolean(empty)); assertTrue("Non-empty string should cast to true", DebuggerApiUtils.castToBoolean(nonEmpty)); } public void testCastToBooleanForUndefined() { assertFalse("Undefined should cast to false", DebuggerApiUtils.castToBoolean(UNDEFINED_REMOTE_OBJECT)); } public void testIsNonFiniteNumber() { assertTrue(DebuggerApiUtils.isNonFiniteNumber(NAN_REMOTE_OBJECT)); assertTrue(DebuggerApiUtils.isNonFiniteNumber(POSITIVE_INFINITY_REMOTE_OBJECT)); assertTrue(DebuggerApiUtils.isNonFiniteNumber(NEGATIVE_INFINITY_REMOTE_OBJECT)); assertFalse(DebuggerApiUtils.isNonFiniteNumber(NULL_REMOTE_OBJECT)); assertFalse(DebuggerApiUtils.isNonFiniteNumber(UNDEFINED_REMOTE_OBJECT)); assertFalse(DebuggerApiUtils.isNonFiniteNumber(BOOLEAN_TRUE_REMOTE_OBJECT)); final RemoteObject zero = new RemoteObjectImpl("0", RemoteObjectType.NUMBER); final RemoteObject nonZero = new RemoteObjectImpl("123", RemoteObjectType.NUMBER); assertFalse(DebuggerApiUtils.isNonFiniteNumber(zero)); assertFalse(DebuggerApiUtils.isNonFiniteNumber(nonZero)); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/debugging/DebuggerStateTest.java
javatests/com/google/collide/client/code/debugging/DebuggerStateTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.debugging; import com.google.collide.client.code.debugging.DebuggerApiTypes.Location; import com.google.collide.client.code.debugging.DebuggerState.BreakpointInfoImpl; import com.google.collide.client.util.PathUtil; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.regexp.shared.RegExp; /** * Tests for {@link DebuggerState}. */ public class DebuggerStateTest extends GWTTestCase { private static final String SESSION_ID = "123456"; private static final String BASE_URI = "http://www.example.com:2020"; private static final int BREAKPOINT_LINE_NUMBER = 123; private static final String BREAKPOINT_CONDITION = "foo==12 || bar<5"; private PathUtil applicationPath; private DebuggerApiStub debuggerApiStub; private DebuggerState debuggerState; private SourceMapping sourceMapping; @Override protected void gwtSetUp() { applicationPath = new PathUtil("/my_path/index.html"); debuggerApiStub = new DebuggerApiStub(); debuggerState = DebuggerState.createForTest(SESSION_ID, debuggerApiStub); sourceMapping = StaticSourceMapping.create(BASE_URI); } @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testRunDebugger() { assertTrue(debuggerState.isDebuggerAvailable()); assertFlags(false, false); doRunDebugger(); } public void testRunDebuggerAfterPaused() { doRunDebugger(); doPauseDebugger(); doRunDebugger(); assertFlags(true, false); } public void testPauseAndResume() { doRunDebugger(); doPauseDebugger(); doResumeDebugger(); // Pause debugger on another session. debuggerApiStub.pause(SESSION_ID + "-FOO"); assertFlags(true, false); } public void testOnAttachAndOnDetach() { doRunDebugger(); doAttachDebugger(); doDetachDebugger(); // Run, pause, attach doRunDebugger(); doPauseDebugger(); doAttachDebugger(); // Run, pause, detach doRunDebugger(); doPauseDebugger(); doDetachDebugger(); } public void testSetBreakpointWhenNotActive() { Breakpoint breakpoint = createBreakpoint(); debuggerState.setBreakpoint(breakpoint); BreakpointInfoImpl breakpointInfo = debuggerState.findBreakpointInfo(breakpoint); assertNull(breakpointInfo); debuggerState.removeBreakpoint(breakpoint); assertFlags(false, false); } public void testSetBreakpoint() { doRunDebugger(); doSetBreakpoint(); } public void testRemoveBreakpoint() { doRunDebugger(); BreakpointInfoImpl breakpointInfo = doSetBreakpoint(); doRemoveBreakpoint(breakpointInfo.getBreakpoint()); } public void testUpdateBreakpoint() { doRunDebugger(); BreakpointInfoImpl breakpointInfo = doSetBreakpoint(); JsonArray<Location> locations = JsonCollections.createArray(); final Location location1 = createLocation(1, 10, "source_id_1"); final Location location2 = createLocation(2, 20, "source_id_2"); locations.add(location1); locations.add(location2); debuggerApiStub.dispatchOnBreakpointResolvedEvent(SESSION_ID, breakpointInfo, locations); assertEquals(2, breakpointInfo.getLocations().size()); assertEquals(location1, breakpointInfo.getLocations().get(0)); assertEquals(location2, breakpointInfo.getLocations().get(1)); // Update with no breakpointInfo. locations = JsonCollections.createArray(); final Location location3 = createLocation(3, 30, "source_id_3"); locations.add(location3); debuggerApiStub.dispatchOnBreakpointResolvedEvent(SESSION_ID, null, breakpointInfo.getBreakpointId(), locations); assertEquals(3, breakpointInfo.getLocations().size()); assertEquals(location3, breakpointInfo.getLocations().get(2)); } public void testSetInactiveBreakpoint() { doRunDebugger(); Breakpoint breakpoint = new Breakpoint.Builder(createBreakpoint()) .setActive(false) .build(); debuggerState.setBreakpoint(breakpoint); assertNull(debuggerState.findBreakpointInfo(breakpoint)); } private void doRunDebugger() { debuggerState.runDebugger(sourceMapping, sourceMapping.getRemoteSourceUri(applicationPath)); assertFlags(true, false); } private void doPauseDebugger() { debuggerApiStub.pause(SESSION_ID); assertFlags(true, true); } private void doResumeDebugger() { debuggerApiStub.resume(SESSION_ID); assertFlags(true, false); } private void doAttachDebugger() { boolean paused = debuggerState.isPaused(); debuggerApiStub.dispatchOnDebuggerAttachedEvent(SESSION_ID); assertFlags(true, paused); } private void doDetachDebugger() { debuggerApiStub.dispatchOnDebuggerDetachedEvent(SESSION_ID); assertFlags(false, false); } private BreakpointInfoImpl doSetBreakpoint() { Breakpoint breakpoint = createBreakpoint(); debuggerState.setBreakpoint(breakpoint); BreakpointInfoImpl breakpointInfo = debuggerState.findBreakpointInfo(breakpoint); assertNotNull(breakpointInfo); assertEquals(breakpoint, breakpointInfo.getBreakpoint()); assertNotNull(breakpointInfo.getBreakpointId()); assertEquals(BREAKPOINT_LINE_NUMBER, breakpointInfo.getLineNumber()); assertEquals(BREAKPOINT_CONDITION, breakpointInfo.getCondition()); assertEquals(0, breakpointInfo.getLocations().size()); String url = breakpointInfo.getUrl(); String urlRegex = breakpointInfo.getUrlRegex(); if (url != null) { assertNull(urlRegex); assertEquals(BASE_URI + applicationPath.getPathString(), breakpointInfo.getUrl()); } else { assertNotNull(urlRegex); assertTrue(RegExp.compile(urlRegex).test(BASE_URI + applicationPath.getPathString())); } return breakpointInfo; } private void doRemoveBreakpoint(Breakpoint breakpoint) { debuggerState.removeBreakpoint(breakpoint); assertNull(debuggerState.findBreakpointInfo(breakpoint)); } private Breakpoint createBreakpoint() { return new Breakpoint.Builder(applicationPath, BREAKPOINT_LINE_NUMBER) .setCondition(BREAKPOINT_CONDITION) .build(); } private Location createLocation(final int lineNumber, final int columnNumber, final String scriptId) { return new Location() { @Override public int getColumnNumber() { return columnNumber; } @Override public int getLineNumber() { return lineNumber; } @Override public String getScriptId() { return scriptId; } }; } private void assertFlags(boolean active, boolean paused) { assertEquals(active, debuggerState.isActive()); assertEquals(paused, debuggerState.isPaused()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/debugging/EvaluableExpressionFinderTest.java
javatests/com/google/collide/client/code/debugging/EvaluableExpressionFinderTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.debugging; import junit.framework.TestCase; /** * Tests for {@link EvaluableExpressionFinder}. */ public class EvaluableExpressionFinderTest extends TestCase { private EvaluableExpressionFinder expressionFinder; private String lineText; @Override protected void setUp() { expressionFinder = new EvaluableExpressionFinder(); lineText = "" // start offset = 0 + "var a = myArray[foo.Bar[baz]][123].qwe_; " // start offset = 41 + "var b = FOO['my[]]]\\'\\\\\\' \"string()']; " // start offset = 80 + "var c = this._foo_[\"asd\"][array[0][1].ssd[sdar[\"string\"]]];"; } public void testNotFound() { doTestNotFound(-1, 3, 5, 6, 7, 39, 40, lineText.length(), lineText.length() + 1); } public void testSingleVariable() { doTest("myArray", range(8, 14)); doTest("foo", range(16, 18)); doTest("baz", range(24, 26)); doTest("FOO", range(49, 51)); doTest("var", range(0, 2)); doTest("var", range(41, 43)); doTest("var", range(80, 82)); doTest("a", 4); // var a = ... doTest("b", 45); // var b = ... doTest("c", 84); // var c = ... } public void testSingleProperty() { doTest("foo.Bar", range(19, 22)); } public void testSingleArrayProperty() { doTest("foo.Bar[baz]", 23, 27); } public void testDoubleArrayProperty() { doTest("myArray[foo.Bar[baz]]", 15, 28); } public void testConsecutiveArrayProperties() { doTest("myArray[foo.Bar[baz]][123]", range(29, 33)); } public void testMixedProperties() { doTest("myArray[foo.Bar[baz]][123].qwe_", range(34, 38)); } public void testQuotesInsideProperties() { doTest("FOO['my[]]]\\'\\\\\\' \"string()']", 52, 53, 76, 77); doTestNotFound(range(58, 67)); doTest("string", range(68, 73)); doTestNotFound(74, 75); } public void testLongComplexExpression() { doTest("this._foo_[\"asd\"][array[0][1].ssd[sdar[\"string\"]]]", 105, 137); doTest("this", range(88, 91)); doTest("this._foo_", range(92, 97)); doTest("this._foo_[\"asd\"]", 98, 99, 103, 104); doTest("array", range(106, 110)); doTest("array[0]", range(111, 113)); doTest("array[0][1]", range(114, 116)); doTest("array[0][1].ssd", range(117, 120)); doTest("array[0][1].ssd[sdar[\"string\"]]", 121, 136); doTest("sdar", range(122, 125)); doTest("sdar[\"string\"]", 126, 127, 134, 135); doTest("string", range(128, 133)); } private void doTest(String expected, int... columns) { for (int column : columns) { final String assertMessage = "Testing column " + column + ", char=" + lineText.substring(column, column + 1); EvaluableExpressionFinder.Result result = expressionFinder.find(lineText, column); assertNotNull(assertMessage + ", expected a not NULL result", result); assertEquals(assertMessage, expected, result.getExpression()); } } private void doTestNotFound(int... columns) { for (int column : columns) { EvaluableExpressionFinder.Result result = expressionFinder.find(lineText, column); if (result != null) { fail("Expected NULL result for column " + column + ", but got: " + result.getExpression()); } } } private static int[] range(int start, int end) { int[] result = new int[end - start + 1]; for (int i = start; i <= end; ++i) { result[i - start] = i; } return result; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/debugging/DebuggerChromeApiTest.java
javatests/com/google/collide/client/code/debugging/DebuggerChromeApiTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.debugging; import com.google.gwt.junit.client.GWTTestCase; /** * Tests for {@link DebuggerChromeApi}. */ public class DebuggerChromeApiTest extends GWTTestCase { private DebuggerChromeApi debuggerChromeApi; @Override protected void gwtSetUp() { debuggerChromeApi = new DebuggerChromeApi(); } @Override protected void gwtTearDown() { debuggerChromeApi.teardown(); } @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testIsDebuggerAvailable() { assertFalse(debuggerChromeApi.isDebuggerAvailable()); setDebuggerExtensionInstalled(true); assertTrue(debuggerChromeApi.isDebuggerAvailable()); setDebuggerExtensionInstalled(false); assertFalse(debuggerChromeApi.isDebuggerAvailable()); } private native void setDebuggerExtensionInstalled(boolean value) /*-{ top["__DebuggerExtensionInstalled"] = value; }-*/; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/debugging/DebuggerApiStub.java
javatests/com/google/collide/client/code/debugging/DebuggerApiStub.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.debugging; import com.google.collide.client.code.debugging.DebuggerApiTypes.BreakpointInfo; import com.google.collide.client.code.debugging.DebuggerApiTypes.CallFrame; import com.google.collide.client.code.debugging.DebuggerApiTypes.Location; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnBreakpointResolvedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnPausedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.PauseOnExceptionsState; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectId; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * Stub implementation of the {@link DebuggerApi} for testing. */ public class DebuggerApiStub implements DebuggerApi { private final JsonArray<DebuggerResponseListener> debuggerResponseListeners = JsonCollections.createArray(); @Override public boolean isDebuggerAvailable() { return true; } @Override public String getDebuggingExtensionUrl() { return null; } @Override public void runDebugger(final String sessionId, String url) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onDebuggerAttached(sessionId); } }); } @Override public void shutdownDebugger(String sessionId) { dispatchOnDebuggerDetachedEvent(sessionId); } @Override public void setBreakpointByUrl(final String sessionId, final BreakpointInfo breakpointInfo) { dispatchOnBreakpointResolvedEvent( sessionId, breakpointInfo, JsonCollections.<Location>createArray()); } @Override public void removeBreakpoint(final String sessionId, final String breakpointId) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onBreakpointRemoved(sessionId, breakpointId); } }); } @Override public void setBreakpointsActive(String sessionId, boolean active) { throw new UnsupportedOperationException("setBreakpointsActive"); } @Override public void setPauseOnExceptions(String sessionId, PauseOnExceptionsState state) { throw new UnsupportedOperationException("setPauseOnExceptions"); } @Override public void pause(final String sessionId) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onPaused(sessionId, new OnPausedResponse() { @Override public JsonArray<CallFrame> getCallFrames() { return JsonCollections.createArray(); } }); } }); } @Override public void resume(final String sessionId) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onResumed(sessionId); } }); } @Override public void stepInto(String sessionId) { throw new UnsupportedOperationException("stepInto"); } @Override public void stepOut(String sessionId) { throw new UnsupportedOperationException("stepOut"); } @Override public void stepOver(String sessionId) { throw new UnsupportedOperationException("stepOver"); } @Override public void requestRemoteObjectProperties(String sessionId, RemoteObjectId remoteObjectId) { throw new UnsupportedOperationException("requestRemoteObjectProperties"); } @Override public void setRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression) { throw new UnsupportedOperationException("setRemoteObjectProperty"); } @Override public void setRemoteObjectPropertyEvaluatedOnCallFrame(String sessionId, CallFrame callFrame, RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression) { throw new UnsupportedOperationException("setRemoteObjectPropertyEvaluatedOnCallFrame"); } @Override public void removeRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String propertyName) { throw new UnsupportedOperationException("removeRemoteObjectProperty"); } @Override public void renameRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String oldName, String newName) { throw new UnsupportedOperationException("renameRemoteObjectProperty"); } @Override public void evaluateExpression(String sessionId, String expression) { throw new UnsupportedOperationException("evaluateExpression"); } @Override public void evaluateExpressionOnCallFrame(String sessionId, CallFrame callFrame, String expression) { throw new UnsupportedOperationException("evaluateExpressionOnCallFrame"); } @Override public void requestAllCssStyleSheets(String sessionId) { throw new UnsupportedOperationException("requestAllCssStyleSheets"); } @Override public void setStyleSheetText(String sessionId, String styleSheetId, String text) { throw new UnsupportedOperationException("setStyleSheetText"); } @Override public void sendCustomMessage(String sessionId, String message) { throw new UnsupportedOperationException("sendCustomMessage"); } @Override public void addDebuggerResponseListener(DebuggerResponseListener debuggerResponseListener) { debuggerResponseListeners.add(debuggerResponseListener); } @Override public void removeDebuggerResponseListener(DebuggerResponseListener debuggerResponseListener) { debuggerResponseListeners.remove(debuggerResponseListener); } public void dispatchOnDebuggerAttachedEvent(final String sessionId) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onDebuggerAttached(sessionId); } }); } public void dispatchOnDebuggerDetachedEvent(final String sessionId) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onDebuggerDetached(sessionId); } }); } public void dispatchOnBreakpointResolvedEvent(String sessionId, BreakpointInfo breakpointInfo, JsonArray<Location> locations) { String breakpointId = String.valueOf(breakpointInfo.hashCode()); dispatchOnBreakpointResolvedEvent(sessionId, breakpointInfo, breakpointId, locations); } public void dispatchOnBreakpointResolvedEvent(final String sessionId, final BreakpointInfo breakpointInfo, final String breakpointId, final JsonArray<Location> locations) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onBreakpointResolved(sessionId, new OnBreakpointResolvedResponse() { @Override public BreakpointInfo getBreakpointInfo() { return breakpointInfo; } @Override public String getBreakpointId() { return breakpointId; } @Override public JsonArray<Location> getLocations() { return locations; } }); } }); } private interface DebuggerResponseDispatcher { void dispatch(DebuggerResponseListener responseListener); } private void dispatchDebuggerResponse(DebuggerResponseDispatcher dispatcher) { JsonArray<DebuggerResponseListener> copy = debuggerResponseListeners.copy(); for (int i = 0, n = copy.size(); i < n; i++) { dispatcher.dispatch(copy.get(i)); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/gotodefinition/AnchorTagParserTests.java
javatests/com/google/collide/client/code/gotodefinition/AnchorTagParserTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.gotodefinition; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.testing.StubIncrementalScheduler; import com.google.collide.client.testutil.CodeMirrorTestCase; import com.google.collide.client.util.PathUtil; import com.google.collide.codemirror2.CodeMirror2; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; public class AnchorTagParserTests extends CodeMirrorTestCase { private static final String SOURCE = "" + "<html>\n" + " <body>\n" + " <a></a>\n" + " <a \n" + " name=\"aName1\"/>\n" // name attribute with quotes + " <a name=aName2/>\n" // name attribute without quotes + " <a id=\"aId1\"/>\n" // id attribute + " <a id=\"\"/>\n" // empty id + " <div id=\"aId1\"/>\n" // not A tag + " </body>\n" + "</html>\n"; @Override public String getModuleName() { return "com.google.collide.client.code.gotodefinition.GoToDefinitionTestModule"; } public void testCollectedAnchors() { PathUtil filePath = new PathUtil("index.html"); Document document = Document.createFromString(SOURCE); DocumentParser parser = DocumentParser.create( document, CodeMirror2.getParser(filePath), new StubIncrementalScheduler(50, 50)); AnchorTagParser anchorParser = new AnchorTagParser(parser); parser.begin(); JsonArray<AnchorTagParser.AnchorTag> anchorTags = anchorParser.getAnchorTags(); assertEquals(3, anchorTags.size()); assertAnchorTag(anchorTags.get(0), "aName1", 4, 13); assertAnchorTag(anchorTags.get(1), "aName2", 5, 12); assertAnchorTag(anchorTags.get(2), "aId1", 6, 11); } private void assertAnchorTag(AnchorTagParser.AnchorTag a, String name, int lineNumber, int column) { assertEquals(name, a.getName()); assertEquals(lineNumber, a.getLineNumber()); assertEquals(column, a.getColumn()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/gotodefinition/DynamicReferenceProviderTest.java
javatests/com/google/collide/client/code/gotodefinition/DynamicReferenceProviderTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.gotodefinition; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.testing.StubIncrementalScheduler; import com.google.collide.client.testutil.CodeMirrorTestCase; import com.google.collide.client.util.PathUtil; import collide.client.filetree.FileTreeModel; import collide.client.filetree.FileTreeNode; import com.google.collide.client.workspace.MockOutgoingController; import com.google.collide.codemirror2.CodeMirror2; import com.google.collide.codemirror2.Token; import com.google.collide.dto.DirInfo; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineInfo; import com.google.gwt.regexp.shared.MatchResult; import javax.annotation.Nullable; /** * Tests for {@link AnchorTagParser}. * */ public class DynamicReferenceProviderTest extends CodeMirrorTestCase { private Document document; private DocumentParser parser; @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } private DynamicReferenceProvider createDynamicReferenceProvider(String path, String source) { PathUtil filePath = new PathUtil(path); document = Document.createFromString(source); parser = DocumentParser.create( document, CodeMirror2.getParser(filePath), new StubIncrementalScheduler(50, 50)); FileTreeNode root = FileTreeNode.transform(buildSimpleTree()); FileTreeModel model = new FileTreeModel(new MockOutgoingController()); model.replaceNode(PathUtil.WORKSPACE_ROOT, root, "1"); return new DynamicReferenceProvider(path, new DeferringLineParser(parser), model, null); } public void testLocalAndAbsoluteFileReferences() { // Some PathUtil sanity tests. String contextPath = "/src/index.html"; PathUtil contextDir = PathUtil.createExcludingLastN(new PathUtil(contextPath), 1); assertEquals("/src", contextDir.getPathString()); PathUtil filePathInContextDir = PathUtil.concatenate(contextDir, new PathUtil("foo.js")); assertEquals("/src/foo.js", filePathInContextDir.getPathString()); DynamicReferenceProvider provider = createDynamicReferenceProvider("/index.html", ""); tryFindFileNode(provider, "/asdf.js", null); tryFindFileNode(provider, "asdf.js", null); tryFindFileNode(provider, "/foo.js", "/foo.js"); tryFindFileNode(provider, "foo.js", "/foo.js"); tryFindFileNode(provider, "/src/world.js", "/src/world.js"); tryFindFileNode(provider, "src/world.js", "/src/world.js"); provider = createDynamicReferenceProvider("/src/index.html", ""); tryFindFileNode(provider, "/asdf.js", null); tryFindFileNode(provider, "asdf.js", null); tryFindFileNode(provider, "/foo.js", "/foo.js"); tryFindFileNode(provider, "foo.js", null); tryFindFileNode(provider, "world.js", "/src/world.js"); tryFindFileNode(provider, "/src/world.js", "/src/world.js"); tryFindFileNode(provider, "src/world.js", null); } private void tryFindFileNode(DynamicReferenceProvider provider, String displayPath, @Nullable String expectedFileNodePath) { FileTreeNode fileNode = provider.findFileNode(displayPath); if (expectedFileNodePath == null) { assertNull(fileNode); } else { assertEquals(expectedFileNodePath, fileNode.getNodePath().getPathString()); } } public void testUrlReference() { String url1 = "http://www.google.com/"; String url2 = "http://www.ru/?q=1&p=2"; String url3 = "https://somesafeurl.com"; String beforeUrl1Text = "/* start "; String middleText = " text "; DynamicReferenceProvider dynamicReferenceProvider = createDynamicReferenceProvider("test.js", "" + beforeUrl1Text + url1 + middleText + url2 + ". */\n" + "var a = 5;\n" + "// " + url3 + ".\n"); int url1StartColumn = beforeUrl1Text.length(); tryDynamicUrlReference(dynamicReferenceProvider, 0, url1StartColumn - 1, -1, null); tryDynamicUrlReference(dynamicReferenceProvider, 0, url1StartColumn, url1StartColumn, url1); tryDynamicUrlReference( dynamicReferenceProvider, 0, url1StartColumn + url1.length() - 1, url1StartColumn, url1); tryDynamicUrlReference(dynamicReferenceProvider, 0, url1StartColumn + url1.length(), -1, null); int url2StartColumn = url1StartColumn + url1.length() + middleText.length(); tryDynamicUrlReference(dynamicReferenceProvider, 0, url2StartColumn - 1, -1, null); tryDynamicUrlReference(dynamicReferenceProvider, 0, url2StartColumn, url2StartColumn, url2); tryDynamicUrlReference( dynamicReferenceProvider, 0, url2StartColumn + url2.length() - 1, url2StartColumn, url2); tryDynamicUrlReference(dynamicReferenceProvider, 0, url2StartColumn + url2.length(), -1, null); // Need to parse line 1 (second line), otherwise parseLineSync returns null for line 2. tryDynamicUrlReference(dynamicReferenceProvider, 1, 0, -1, null); int url3StartColumn = 3; tryDynamicUrlReference(dynamicReferenceProvider, 2, url3StartColumn - 1, -1, null); tryDynamicUrlReference(dynamicReferenceProvider, 2, url3StartColumn, url3StartColumn, url3); tryDynamicUrlReference( dynamicReferenceProvider, 2, url3StartColumn + url3.length() - 1, url3StartColumn, url3); tryDynamicUrlReference(dynamicReferenceProvider, 2, url3StartColumn + url3.length(), -1, null); } private void tryDynamicUrlReference(DynamicReferenceProvider provider, int lineNumber, int column, int referenceStartColumn, @Nullable String url) { LineInfo lineInfo = document.getLineFinder().findLine(lineNumber); assertNotNull(lineInfo); JsonArray<Token> tokens = parser.parseLineSync(lineInfo.line()); if (tokens == null) { throw new RuntimeException(lineInfo.line().getText()); } assertNotNull(tokens); NavigableReference.UrlReference reference = (NavigableReference.UrlReference) provider.getReferenceAt(lineInfo, column, tokens); if (url == null) { assertNull(reference); } else { assertNotNull(reference); assertEquals(lineNumber, reference.getLineNumber()); assertEquals(referenceStartColumn, reference.getStartColumn()); assertEquals(url, reference.getUrl()); } } public void testLocalFileReference() { DynamicReferenceProvider dynamicReferenceProvider = createDynamicReferenceProvider("test.html", "<script src=\"foo.js\"></script>"); tryDynamicFileReference(dynamicReferenceProvider, 0, 12, -1, null); tryDynamicFileReference(dynamicReferenceProvider, 0, 13, 13, "/foo.js"); tryDynamicFileReference(dynamicReferenceProvider, 0, 18, 13, "/foo.js"); tryDynamicFileReference(dynamicReferenceProvider, 0, 19, -1, null); dynamicReferenceProvider = createDynamicReferenceProvider("/src/test.html", "<script src=\"world.js\"></script>"); tryDynamicFileReference(dynamicReferenceProvider, 0, 12, -1, null); tryDynamicFileReference(dynamicReferenceProvider, 0, 13, 13, "/src/world.js"); tryDynamicFileReference(dynamicReferenceProvider, 0, 20, 13, "/src/world.js"); tryDynamicFileReference(dynamicReferenceProvider, 0, 21, -1, null); } private void tryDynamicFileReference(DynamicReferenceProvider provider, int lineNumber, int column, int referenceStartColumn, @Nullable String filePath) { LineInfo lineInfo = document.getLineFinder().findLine(lineNumber); JsonArray<Token> tokens = parser.parseLineSync(lineInfo.line()); NavigableReference.FileReference reference = (NavigableReference.FileReference) provider.getReferenceAt(lineInfo, column, tokens); if (filePath == null) { assertNull(reference); } else { assertNotNull(reference); assertEquals(lineNumber, reference.getLineNumber()); assertEquals(referenceStartColumn, reference.getStartColumn()); assertEquals(filePath, reference.getTargetFilePath()); } } public void testUrlMatches() { tryMatchUrl("sdf http://www.google.com/ alsg", "http://www.google.com/"); tryMatchUrl("http://www.google.com.", "http://www.google.com"); tryMatchUrl("a www.google.com", null); tryMatchUrl("ftp://192.168.1.1:23/somepath/.", "ftp://192.168.1.1:23/somepath/"); tryMatchUrl("adflkhttp://www.google.com/asdg", null); tryMatchUrl("http://www.ru?1=2&2=3 text", "http://www.ru?1=2&2=3"); tryMatchUrl("text1.http://go/someplace#url=test.", "http://go/someplace#url=test"); tryMatchUrl("<a href='ftp://myawesomeftp.com/'>link</a>", "ftp://myawesomeftp.com/"); tryMatchUrl("<img src=\"http://somedomain.com/somepath/someimage.jpg\">", "http://somedomain.com/somepath/someimage.jpg"); tryMatchUrl("many whitespaces http://www.com/path/foo ", "http://www.com/path/foo"); tryMatchUrl("many whitespaces http://www.com/path/img.png text", "http://www.com/path/img.png"); // THE FOLLOWING TEST CASE DOES NOT WORK YET! It takes the end of comment ("*/") as URL. // tryMatchUrl("/* Go to http://www.google.com/.*/", "http://www.google.com/"); } private void tryMatchUrl(String text, @Nullable String url) { DynamicReferenceProvider.REGEXP_URL.setLastIndex(0); MatchResult matchResult = DynamicReferenceProvider.REGEXP_URL.exec(text); if (url == null) { assertNull(matchResult); return; } assertNotNull(matchResult); assertEquals(url, matchResult.getGroup(0)); } /** * Stole from TreeWalkFileNameSearchImpltest */ private final native DirInfo buildSimpleTree() /*-{ return { // Root node is magic nodeType : @com.google.collide.dto.TreeNodeInfo::DIR_TYPE, id : "1", originId : "1", name : "root", files : [ { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "5", originId : "5", name : "foo.js", rootId : "2", path : "/foo.js", size : "1234" } ], isComplete : true, subDirectories : [ { nodeType : @com.google.collide.dto.TreeNodeInfo::DIR_TYPE, id : "2", originId : "2", name : "src", path : "/src", files : [ { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "7", originId : "7", name : "world.js", rootId : "2", path : "/src/world.js", size : "1234" } ], isComplete : true, subDirectories : [] } ] }; }-*/; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/gotodefinition/ReferenceStoreTest.java
javatests/com/google/collide/client/code/gotodefinition/ReferenceStoreTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.code.gotodefinition; import com.google.collide.client.AppContext; import com.google.collide.client.codeunderstanding.CodeGraphTestUtils.MockCubeClient; import com.google.collide.client.codeunderstanding.CubeData; import com.google.collide.client.editor.Editor; import com.google.collide.client.testing.MockAppContext; import com.google.collide.client.testutil.SynchronousTestCase; import com.google.collide.client.util.PathUtil; import com.google.collide.dto.CodeReference; import com.google.collide.dto.CodeReferences; import com.google.collide.dto.client.DtoClientImpls; import com.google.collide.json.client.JsoArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineInfo; /** * Tests for {@link GoToDefinitionHandler}. */ public class ReferenceStoreTest extends SynchronousTestCase { @Override public String getModuleName() { return "com.google.collide.TestCode"; } public void testFindReferenceInFileAfterEdit() { // Test data. PathUtil filePath = new PathUtil("/foo.js"); Document document = Document.createFromString("" + "var defvar = 5;\n" + "var myvar = defvar;\n"); CodeReference codeReference = DtoClientImpls.MockCodeReferenceImpl.make() .setReferenceStart(DtoClientImpls.FilePositionImpl.make() .setLineNumber(1).setColumn(12)) .setReferenceEnd(DtoClientImpls.FilePositionImpl.make() .setLineNumber(1).setColumn(17)) .setTargetFilePath(filePath.getPathString()) .setTargetStart(DtoClientImpls.FilePositionImpl.make() .setLineNumber(0).setColumn(4)) .setTargetEnd(DtoClientImpls.FilePositionImpl.make() .setLineNumber(0).setColumn(9)) .setReferenceType(CodeReference.Type.VAR); JsoArray<CodeReference> codeReferences = JsoArray.from(codeReference); CodeReferences fileReferences = DtoClientImpls.CodeReferencesImpl.make().setReferences(codeReferences); // Environment. AppContext appContext = new MockAppContext(); Editor editor = Editor.create(appContext); editor.setDocument(document); MockCubeClient cubeClient = MockCubeClient.create(); cubeClient.setPath(filePath.getPathString()); ReferenceStore referenceStore = null; try { referenceStore = new ReferenceStore(cubeClient); referenceStore.onDocumentChanged(document, null); referenceStore.updateReferences( new CubeData(filePath.getPathString(), null, null, null, null, fileReferences)); LineInfo line1 = document.getLineFinder().findLine(1); // Check that there's reference at positions 12 to 17 inclusive (line 2). assertNotNull(referenceStore.findReference(line1, 12, true)); assertNotNull(referenceStore.findReference(line1, 17, true)); // Make some edits. Just insert some whitespaces before reference. // Now the second line is: "var myvar = defvar;\n" document.insertText(document.getFirstLine().getNextLine(), 3, " "); // Test! // Now there's nothing at position 13. assertNull(referenceStore.findReference(line1, 13, true)); // And there's reference at 18. assertNotNull(referenceStore.findReference(line1, 18, true)); // Make some more edits, add whitespace inside reference. // This should break it. // Now the second line is: "var myvar = d efvar;\n" document.insertText(document.getFirstLine().getNextLine(), 16, " "); // Now there should be nothing at positions 15-23. assertNull(referenceStore.findReference(line1, 15, true)); assertNull(referenceStore.findReference(line1, 18, true)); assertNull(referenceStore.findReference(line1, 21, true)); referenceStore.onDocumentChanged(Document.createEmpty(), null); } finally { if (referenceStore != null) { referenceStore.cleanup(); } cubeClient.cleanup(); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/workspace/MockOutgoingController.java
javatests/com/google/collide/client/workspace/MockOutgoingController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.workspace; import collide.client.filetree.FileTreeModel; import collide.client.filetree.FileTreeModel.NodeRequestCallback; import collide.client.filetree.FileTreeModelNetworkController.OutgoingController; import collide.client.filetree.FileTreeNode; import com.google.collide.client.util.PathUtil; /** * A no-op mock of {@link OutgoingController}. */ public class MockOutgoingController extends OutgoingController { public MockOutgoingController() { super(null); } void requestWorkspaceNode( FileTreeModel fileTreeModel, PathUtil path, NodeRequestCallback callback) { } void requestDirectoryChildren( FileTreeModel fileTreeModel, FileTreeNode node, NodeRequestCallback callback) { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/workspace/TestUtils.java
javatests/com/google/collide/client/workspace/TestUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.workspace; /** * Shared utility code for workspace tests. */ public class TestUtils { /** * This is the GWT Module used for these tests. */ public static final String BUILD_MODULE_NAME = "com.google.collide.client.TestCode"; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/workspace/outline/CssOutlineParserTest.java
javatests/com/google/collide/client/workspace/outline/CssOutlineParserTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.workspace.outline; import static com.google.collide.client.workspace.outline.CssOutlineParser.findCutTailIndex; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.FUNCTION; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.gwt.junit.client.GWTTestCase; /** * Tests for {@link CssOutlineParser}. */ public class CssOutlineParserTest extends GWTTestCase { @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testCutTail() { JsonArray<OutlineNode> nodes = JsonCollections.createArray(); for (int i = 1; i <= 7; i++) { for (int j = 0; j < i; j++) { nodes.add(new OutlineNode("", FUNCTION, null, i, 0)); } } assertEquals(0, findCutTailIndex(nodes, 0)); // f(x) = x * (x - 1) / 2 assertEquals(0, findCutTailIndex(nodes, 1)); assertEquals(1, findCutTailIndex(nodes, 2)); assertEquals(3, findCutTailIndex(nodes, 3)); assertEquals(6, findCutTailIndex(nodes, 4)); assertEquals(10, findCutTailIndex(nodes, 5)); assertEquals(15, findCutTailIndex(nodes, 6)); assertEquals(21, findCutTailIndex(nodes, 7)); assertEquals(28, findCutTailIndex(nodes, 8)); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/CoordinateMapTests.java
javatests/com/google/collide/client/editor/CoordinateMapTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor; import com.google.collide.client.editor.CoordinateMap.DocumentSizeProvider; import com.google.collide.shared.document.Document; import com.google.common.base.Joiner; import junit.framework.TestCase; import org.easymock.EasyMock; import org.easymock.IMocksControl; /** * Tests for {@link CoordinateMap}. * */ public class CoordinateMapTests extends TestCase { private static final int LINE_HEIGHT = 10; // 100 cols FTW private static final String[] LINES = { "About Google\n", "\n", "The Beginning\n", "\n", "Beginning in 1996, Stanford University graduate students Larry Page and " + "Sergey Brin built a\n", "search engine called 'BackRub' that used links to determine the importance of " + "individual\n", "web pages. By 1998 they had formalized their work, creating the company you know " + "today as Google."}; private CoordinateMap coordMap; private Document doc; private final DocumentSizeProvider documentSizeProvider = new DocumentSizeProvider() { @Override public void handleSpacerHeightChanged(Spacer s, int i) { } @Override public int getEditorLineHeight() { return LINE_HEIGHT; } @Override public float getEditorCharacterWidth() { return (float) 7.0; } }; private Buffer mockBuffer; @Override protected void setUp() throws Exception { doc = Document.createFromString(Joiner.on("").join(LINES)); IMocksControl control = EasyMock.createControl(); control.resetToNice(); mockBuffer = control.createMock(Buffer.class); control.replay(); coordMap = new CoordinateMap(documentSizeProvider); coordMap.handleDocumentChange(doc); } public void testNoSpacers() { assertNoSpacers(); } private void assertNoSpacers() { for (int i = 0; i < doc.getLineCount(); i++) { assertEquals(i * LINE_HEIGHT, coordMap.convertLineNumberToY(i)); if (i > 0) { assertNotSame(i, coordMap.convertYToLineNumber(i * LINE_HEIGHT - 1)); } assertEquals(i, coordMap.convertYToLineNumber(i * LINE_HEIGHT)); assertEquals(i, coordMap.convertYToLineNumber(i * LINE_HEIGHT + 1)); assertEquals(i, coordMap.convertYToLineNumber(i * LINE_HEIGHT + LINE_HEIGHT / 2)); assertEquals(i, coordMap.convertYToLineNumber((i + 1) * LINE_HEIGHT - 1)); assertNotSame(i, coordMap.convertYToLineNumber((i + 1) * LINE_HEIGHT)); } } public void testLine0SpacerCreation() { coordMap.createSpacer(doc.getLineFinder().findLine(0), 30, mockBuffer, ""); assertEquals(30, coordMap.convertLineNumberToY(0)); assertEquals(0, coordMap.convertYToLineNumber(0)); assertEquals(0, coordMap.convertYToLineNumber(15)); assertEquals(0, coordMap.convertYToLineNumber(30)); assertEquals(0, coordMap.convertYToLineNumber(30 + LINE_HEIGHT - 1)); assertNotSame(0, coordMap.convertYToLineNumber(30 + LINE_HEIGHT)); } public void testMultipleSpacers() { Spacer spacerOnLine0 = coordMap.createSpacer(doc.getLineFinder().findLine(0), 30, mockBuffer, ""); assertEquals(30, coordMap.convertLineNumberToY(0)); assertEquals(40, coordMap.convertLineNumberToY(1)); assertEquals(0, coordMap.convertYToLineNumber(0)); assertEquals(0, coordMap.convertYToLineNumber(30)); assertEquals(0, coordMap.convertYToLineNumber(39)); assertEquals(1, coordMap.convertYToLineNumber(40)); assertEquals(1, coordMap.convertYToLineNumber(49)); Spacer spacerOnLine2 = coordMap.createSpacer(doc.getLineFinder().findLine(2), 40, mockBuffer, ""); assertEquals(90, coordMap.convertLineNumberToY(2)); assertEquals(2, coordMap.convertYToLineNumber(50)); assertEquals(2, coordMap.convertYToLineNumber(51)); assertEquals(2, coordMap.convertYToLineNumber(89)); assertEquals(2, coordMap.convertYToLineNumber(90)); assertNotSame(2, coordMap.convertYToLineNumber(100)); Spacer spacerOnLine3 = coordMap.createSpacer(doc.getLineFinder().findLine(3), 10, mockBuffer, ""); assertEquals(110, coordMap.convertLineNumberToY(3)); assertEquals(120, coordMap.convertLineNumberToY(4)); assertEquals(3, coordMap.convertYToLineNumber(100)); assertEquals(3, coordMap.convertYToLineNumber(119)); assertEquals(4, coordMap.convertYToLineNumber(120)); assertEquals(4, coordMap.convertYToLineNumber(129)); assertNotSame(4, coordMap.convertYToLineNumber(130)); Spacer spacerOnLine5 = coordMap.createSpacer(doc.getLineFinder().findLine(5), 60, mockBuffer, ""); assertEquals(190, coordMap.convertLineNumberToY(5)); assertEquals(5, coordMap.convertYToLineNumber(130)); assertEquals(5, coordMap.convertYToLineNumber(131)); assertEquals(5, coordMap.convertYToLineNumber(190)); assertEquals(5, coordMap.convertYToLineNumber(199)); assertNotSame(5, coordMap.convertYToLineNumber(200)); // Test invalidation Spacer spacerOnLine1 = coordMap.createSpacer(doc.getLineFinder().findLine(1), 10, mockBuffer, ""); assertEquals(130, coordMap.convertLineNumberToY(4)); assertEquals(200, coordMap.convertLineNumberToY(5)); assertEquals(0, coordMap.convertYToLineNumber(0)); assertEquals(0, coordMap.convertYToLineNumber(30)); assertEquals(0, coordMap.convertYToLineNumber(39)); assertEquals(1, coordMap.convertYToLineNumber(50)); assertEquals(1, coordMap.convertYToLineNumber(59)); assertEquals(2, coordMap.convertYToLineNumber(60)); assertEquals(2, coordMap.convertYToLineNumber(61)); assertEquals(2, coordMap.convertYToLineNumber(99)); assertEquals(2, coordMap.convertYToLineNumber(100)); assertEquals(3, coordMap.convertYToLineNumber(110)); assertEquals(3, coordMap.convertYToLineNumber(129)); assertEquals(4, coordMap.convertYToLineNumber(130)); assertEquals(4, coordMap.convertYToLineNumber(139)); assertEquals(5, coordMap.convertYToLineNumber(140)); assertEquals(5, coordMap.convertYToLineNumber(141)); assertEquals(5, coordMap.convertYToLineNumber(200)); assertEquals(5, coordMap.convertYToLineNumber(209)); assertNotSame(5, coordMap.convertYToLineNumber(210)); // Test deletion coordMap.removeSpacer(spacerOnLine1); assertEquals(30, coordMap.convertLineNumberToY(0)); assertEquals(40, coordMap.convertLineNumberToY(1)); assertEquals(90, coordMap.convertLineNumberToY(2)); assertEquals(110, coordMap.convertLineNumberToY(3)); assertEquals(120, coordMap.convertLineNumberToY(4)); assertEquals(190, coordMap.convertLineNumberToY(5)); assertEquals(0, coordMap.convertYToLineNumber(0)); assertEquals(0, coordMap.convertYToLineNumber(30)); assertEquals(0, coordMap.convertYToLineNumber(39)); assertEquals(1, coordMap.convertYToLineNumber(40)); assertEquals(1, coordMap.convertYToLineNumber(49)); assertEquals(2, coordMap.convertYToLineNumber(50)); assertEquals(2, coordMap.convertYToLineNumber(51)); assertEquals(2, coordMap.convertYToLineNumber(89)); assertEquals(2, coordMap.convertYToLineNumber(90)); assertEquals(3, coordMap.convertYToLineNumber(100)); assertEquals(3, coordMap.convertYToLineNumber(119)); assertEquals(4, coordMap.convertYToLineNumber(120)); assertEquals(4, coordMap.convertYToLineNumber(129)); assertEquals(5, coordMap.convertYToLineNumber(130)); assertEquals(5, coordMap.convertYToLineNumber(131)); assertEquals(5, coordMap.convertYToLineNumber(190)); assertEquals(5, coordMap.convertYToLineNumber(199)); assertNotSame(5, coordMap.convertYToLineNumber(200)); coordMap.removeSpacer(spacerOnLine5); coordMap.removeSpacer(spacerOnLine0); coordMap.removeSpacer(spacerOnLine3); coordMap.removeSpacer(spacerOnLine2); assertNoSpacers(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/TextActionsTest.java
javatests/com/google/collide/client/editor/TextActionsTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor; import static com.google.collide.client.code.autocomplete.TestUtils.createDocumentParser; import com.google.collide.client.autoindenter.Autoindenter; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.input.TestSignalEvent; import com.google.collide.client.testing.MockAppContext; import com.google.collide.client.testutil.SynchronousTestCase; import com.google.collide.client.testutil.TestSchedulerImpl; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.input.ModifierKeys; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.document.Position; import com.google.collide.shared.util.JsonCollections; import com.google.gwt.core.client.Scheduler; import org.waveprotocol.wave.client.common.util.SignalEvent; import elemental.events.KeyboardEvent; /** * Tests for {@link TextActions} and their bindings in * {@link com.google.collide.client.editor.input.DefaultScheme}. */ public class TextActionsTest extends SynchronousTestCase { @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testSplitLine() { final TestSignalEvent ctrlEnter = new TestSignalEvent(KeyboardEvent.KeyCode.ENTER, SignalEvent.KeySignalType.INPUT, ModifierKeys.ACTION); String text = " color: black;"; String expected = " color: \n black;"; checkAction(ctrlEnter, text, expected, 0, 9, 0, 9, 0, 9); } public void testSplitLineWithSelection() { final TestSignalEvent ctrlEnter = new TestSignalEvent(KeyboardEvent.KeyCode.ENTER, SignalEvent.KeySignalType.INPUT, ModifierKeys.ACTION); String text = " color: black;"; String expected = " color\n black;"; checkAction(ctrlEnter, text, expected, 0, 7, 0, 9, 0, 7); } public void testSplitLineWithReverseSelection() { final TestSignalEvent ctrlEnter = new TestSignalEvent(KeyboardEvent.KeyCode.ENTER, SignalEvent.KeySignalType.INPUT, ModifierKeys.ACTION); String text = " color: black;"; String expected = " color\n black;"; checkAction(ctrlEnter, text, expected, 0, 9, 0, 7, 0, 7); } public void testStartNewLine() { final TestSignalEvent shiftEnter = new TestSignalEvent(KeyboardEvent.KeyCode.ENTER, SignalEvent.KeySignalType.INPUT, ModifierKeys.SHIFT); String text = " color: black;"; String expected = " color: black;\n "; checkAction(shiftEnter, text, expected, 0, 8, 0, 8, 1, 2); } public void testStartNewLineWithSelection() { final TestSignalEvent shiftEnter = new TestSignalEvent(KeyboardEvent.KeyCode.ENTER, SignalEvent.KeySignalType.INPUT, ModifierKeys.SHIFT); String text = " color: black;"; String expected = " color: black;\n "; checkAction(shiftEnter, text, expected, 0, 0, 0, 8, 1, 2); } private void checkAction(final SignalEvent trigger, String text, String expected, int line1, int column1, int line2, int column2, int expectedLine, int expectedColumn) { Document document = Document.createFromString(text); final Editor editor = Editor.create(new MockAppContext()); editor.setDocument(document); editor.getInput().getActionExecutor().addDelegate(TextActions.INSTANCE); PathUtil path = new PathUtil("test.css"); DocumentParser documentParser = createDocumentParser(path); Autoindenter autoindenter = Autoindenter.create(documentParser, editor); LineFinder lineFinder = editor.getDocument().getLineFinder(); editor.getSelection().setSelection( lineFinder.findLine(line1), column1, lineFinder.findLine(line2), column2); final JsonArray<Scheduler.ScheduledCommand> scheduled = JsonCollections.createArray(); TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() { @Override public void scheduleDeferred(ScheduledCommand scheduledCommand) { // Do nothing } @Override public void scheduleFinally(ScheduledCommand scheduledCommand) { scheduled.add(scheduledCommand); } }; Runnable triggerClicker = new Runnable() { @Override public void run() { editor.getInput().processSignalEvent(trigger); } }; try { TestSchedulerImpl.runWithSpecificScheduler(triggerClicker, scheduler); } finally { autoindenter.teardown(); } if (scheduled.size() != 1) { fail("exactly 1 scheduled command expected"); } scheduled.get(0).execute(); String result = editor.getDocument().asText(); assertEquals("textual result", expected, result); Position[] selectionRange = editor.getSelection().getSelectionRange(false); assertFalse("no selection", editor.getSelection().hasSelection()); assertEquals("cursor line", expectedLine, selectionRange[0].getLineNumber()); assertEquals("cursor column", expectedColumn, selectionRange[0].getColumn()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/EditorTests.java
javatests/com/google/collide/client/editor/EditorTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.testing.MockAppContext; import com.google.collide.client.testutil.SynchronousTestCase; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.document.anchor.AnchorUtils; import com.google.collide.shared.document.anchor.InsertionPlacementStrategy; /** * Various test cases for {@link Editor}. */ public class EditorTests extends SynchronousTestCase { @Override public String getModuleName() { return "com.google.collide.client.editor.EditorTestModule"; } /** * Tests that selection do not affect break replacement. * * @see AnchorUtils#setTextBetweenAnchors */ public void testSetTextBetweenAnchors() { AnchorType bottomType = AnchorType.create(EditorTests.class, "bottom"); AnchorType topType = AnchorType.create(EditorTests.class, "top"); Document doc = Document.createFromString("qwerty\nasdfgh\nzxcvbn\n"); LineFinder lineFinder = doc.getLineFinder(); AnchorManager anchorManager = doc.getAnchorManager(); LineInfo lineInfo = lineFinder.findLine(1); Editor editor = Editor.create(new MockAppContext()); editor.setDocument(doc); Anchor topAnchor = anchorManager.createAnchor(topType, lineInfo.line(), lineInfo.number(), AnchorManager.IGNORE_COLUMN); topAnchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); topAnchor.setInsertionPlacementStrategy(InsertionPlacementStrategy.EARLIER); Anchor bottomAnchor = anchorManager.createAnchor(bottomType, lineInfo.line(), lineInfo.number(), AnchorManager.IGNORE_COLUMN); bottomAnchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); bottomAnchor.setInsertionPlacementStrategy(InsertionPlacementStrategy.LATER); SelectionModel selection = editor.getSelection(); selection.setSelection(lineInfo, 1, lineInfo, 4); AnchorUtils.setTextBetweenAnchors( "bugaga", topAnchor, bottomAnchor, editor.getEditorDocumentMutator()); assertEquals("qwerty\nbugaga\nzxcvbn\n", doc.asText()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/input/InputModeTest.java
javatests/com/google/collide/client/editor/input/InputModeTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.input; import com.google.collide.client.util.input.KeyCodeMap; import com.google.collide.client.util.input.ModifierKeys; import com.google.gwt.junit.client.GWTTestCase; import elemental.events.KeyboardEvent.KeyCode; import org.waveprotocol.wave.client.common.util.SignalEvent; /** * Test cases for input handling, switching between input modes+schemes, and * stream+event shortcut callbacks to keyboard events. * * */ public class InputModeTest extends GWTTestCase { private TestScheme inputScheme; class TestScheme extends InputScheme { private int flag = 0; private int flagVal = 1; public int getFlag() { return flag; } /** * The value to set flag to when setFlag() is called */ public void initFlag(int val, int i) { flagVal = i; flag = val; } public void initFlag(int i) { flagVal = i; } // should only be called by test subclasses protected void setFlag() { flag = flagVal; } protected void setFlag(int i) { flag = i; } public void setup() {} public void teardown() {} } /** * Used to record internal function calls */ public abstract class TestMode extends InputMode { private int flag = 0; private int flagVal = 1; public int getFlag() { return flag; } /** * The value to set flag to when setFlag() is called */ public void initFlag(int val, int i) { flagVal = i; flag = val; } public void initFlag(int i) { flagVal = i; } // should only be called by test subclasses protected void setFlag() { flag = flagVal; } protected void setFlag(int i) { flag = i; } } /** * Test mode 1 to install into TestScheme * * Sets internal flag to the signal's keycode and returns true for defaultInput */ public class TestMode1 extends TestMode { public void setup() { setFlag(); } public void teardown() { setFlag(); } public boolean onDefaultInput(SignalEvent e, char text) { setFlag(e.getKeyCode()); return true; } public boolean onDefaultPaste(SignalEvent e, String text) { return false; } } /** * Test mode 2 to install into TestScheme * * Returns false on defaultInput */ public class TestMode2 extends TestMode { public void setup() { setFlag(); } public void teardown() { setFlag(); } public boolean onDefaultInput(SignalEvent e, char text) { return false; } public boolean onDefaultPaste(SignalEvent e, String text) { return false; } } /** * Test mode 3 to install into TestScheme * * defaultInput sets flag equal to -1 and returns true * defaultInputMulti sets flag equal to length of event string and returns false */ public class TestMode3 extends TestMode { public void setup() { setFlag(); } public void teardown() { setFlag(); } public boolean onDefaultInput(SignalEvent e, char text) { setFlag(-1); return true; } public boolean onDefaultPaste(SignalEvent e, String text) { setFlag(text.length()); return false; } } /* (non-Javadoc) * @see com.google.gwt.junit.client.GWTTestCase#getModuleName() */ @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } /** * Setup client environment */ @Override protected void gwtSetUp() throws Exception { super.gwtSetUp(); inputScheme = new TestScheme(); } /** * Tests a scheme with no modes installed */ public void testNoModes() { SignalEvent sig = new TestSignalEvent('a'); // user typed an "a" character assertFalse(sendSignal(sig)); // returns false when no modes are installed } /** * Test mode switching */ public void testModeSwitch() { TestMode mode1 = new TestMode1(); mode1.initFlag(2); inputScheme.addMode(1, mode1); assertEquals(inputScheme.getMode(), null); inputScheme.switchMode(1); // mode1.setup() should have been called assertEquals(mode1.getFlag(), 2); TestMode mode2 = new TestMode2(); mode1.initFlag(3); mode2.initFlag(4); inputScheme.addMode(2, mode2); // should still be in mode1 assertEquals(inputScheme.getMode(), mode1); inputScheme.switchMode(2); // see if mode1.teardown() and mode2.setup() were called assertEquals(inputScheme.getMode(), mode2); assertEquals(mode1.getFlag(), 3); assertEquals(mode2.getFlag(), 4); } /** * Test signal handling */ public void testSignalHandle() { TestMode mode1 = new TestMode1(); inputScheme.addMode(1, mode1); inputScheme.switchMode(1); TestSignalEvent sig = new TestSignalEvent('a'); assertTrue(sendSignal(sig)); // mode1.defaultInput() should return true assertEquals(mode1.getFlag(), 'a'); // flag should be set to the keyCode } /** * Test shortcuts * * All TestSignalEvents should be intialized with uppercase letters or constants * from KeyCode.* to simulate keyboard input */ public void testShortcuts() { TestMode mode2 = new TestMode2(); inputScheme.addMode(2, mode2); inputScheme.switchMode(2); // CMD+ALT+s mode2.addShortcut(new EventShortcut(ModifierKeys.ACTION | ModifierKeys.ALT, 's') { @Override public boolean event(InputScheme scheme, SignalEvent event) { // callback in here ((TestScheme) scheme).setFlag(); return true; } } ); // SHIFT+TAB mode2.addShortcut(new EventShortcut(ModifierKeys.SHIFT, KeyCodeMap.TAB) { @Override public boolean event(InputScheme scheme, SignalEvent event) { // callback in here ((TestScheme) scheme).setFlag(); return true; } } ); // CMD+\ mode2.addShortcut(new EventShortcut(ModifierKeys.ACTION, '\\') { @Override public boolean event(InputScheme scheme, SignalEvent event) { // callback in here ((TestScheme) scheme).setFlag(); return true; } } ); // ; mode2.addShortcut(new EventShortcut(ModifierKeys.NONE, ';') { @Override public boolean event(InputScheme scheme, SignalEvent event) { // callback in here ((TestScheme) scheme).setFlag(); return true; } } ); // . mode2.addShortcut(new EventShortcut(ModifierKeys.ALT, '.') { @Override public boolean event(InputScheme scheme, SignalEvent event) { // callback in here ((TestScheme) scheme).setFlag(); return true; } } ); // PAGE_UP mode2.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.PAGE_UP) { @Override public boolean event(InputScheme scheme, SignalEvent event) { // callback in here ((TestScheme) scheme).setFlag(); return true; } } ); // feed in javascript keycode representations TestSignalEvent evt1 = new TestSignalEvent('A'); TestSignalEvent evt2 = new TestSignalEvent('A', ModifierKeys.ACTION, ModifierKeys.ALT); TestSignalEvent evt3 = new TestSignalEvent('S'); TestSignalEvent evt4 = new TestSignalEvent('S', ModifierKeys.ACTION, ModifierKeys.ALT); TestSignalEvent evt5 = new TestSignalEvent(KeyCode.TAB, ModifierKeys.SHIFT); TestSignalEvent evt6 = new TestSignalEvent(KeyCode.BACKSLASH, ModifierKeys.ACTION); TestSignalEvent evt7 = new TestSignalEvent(KeyCode.SEMICOLON); TestSignalEvent evt8 = new TestSignalEvent(KeyCode.PERIOD, ModifierKeys.ALT); TestSignalEvent evt9 = new TestSignalEvent(KeyCode.PAGE_UP); // evt1..3 shouldn't fire the callback, only evt4..6 should inputScheme.initFlag(0, 1); assertFalse(sendSignal(evt1)); assertEquals(inputScheme.getFlag(), 0); assertFalse(sendSignal(evt2)); assertEquals(inputScheme.getFlag(), 0); assertFalse(sendSignal(evt3)); assertEquals(inputScheme.getFlag(), 0); assertTrue(sendSignal(evt4)); assertEquals(inputScheme.getFlag(), 1); inputScheme.initFlag(0, 2); assertTrue(sendSignal(evt5)); assertEquals(inputScheme.getFlag(), 2); inputScheme.initFlag(0, 3); assertTrue(sendSignal(evt6)); assertEquals(inputScheme.getFlag(), 3); inputScheme.initFlag(0, 4); assertTrue(sendSignal(evt7)); assertEquals(inputScheme.getFlag(), 4); inputScheme.initFlag(0, 5); assertTrue(sendSignal(evt8)); assertEquals(inputScheme.getFlag(), 5); inputScheme.initFlag(0, 6); assertTrue(sendSignal(evt9)); assertEquals(inputScheme.getFlag(), 6); // now try out StreamShortcuts, such as vi quit: ":q!" mode2.addShortcut(new StreamShortcut(":q!") { @Override public boolean event(InputScheme scheme, SignalEvent event) { // callback in here ((TestScheme) scheme).setFlag(); return true; } }); TestSignalEvent x = new TestSignalEvent('X'); TestSignalEvent excl = new TestSignalEvent('1', ModifierKeys.SHIFT); // ! TestSignalEvent q = new TestSignalEvent('Q'); TestSignalEvent upperQ = new TestSignalEvent('Q', ModifierKeys.SHIFT); TestSignalEvent colon = new TestSignalEvent(KeyCode.SEMICOLON, null, ModifierKeys.SHIFT); inputScheme.initFlag(0, 2); assertFalse(sendSignal(x)); // random entry assertEquals(inputScheme.getFlag(), 0); assertTrue(sendSignal(colon)); // beginning of command assertEquals(inputScheme.getFlag(), 0); assertFalse(sendSignal(upperQ)); // test uppercase vs lowercase assertEquals(inputScheme.getFlag(), 0); assertFalse(sendSignal(excl)); assertEquals(inputScheme.getFlag(), 0); // do the combo :q! assertTrue(sendSignal(colon)); assertTrue(sendSignal(q)); assertTrue(sendSignal(excl)); assertEquals(inputScheme.getFlag(), 2); // triggers callback assertFalse(sendSignal(x)); // should reset } /** * Test defaultMultiInput for longer strings * * All strings > 1 char should skip shortcut system entirely */ /*public void testMultiInput() { TestMode mode3 = new TestMode3(); inputScheme.addMode(3, mode3); inputScheme.switchMode(3); TestSignalEvent paste = new TestSignalEvent('p', ModifierKeys.CMD); String text = "Test multi char paste"; assertFalse(sendStringEvent(paste, text)); assertEquals(inputScheme.getFlag(), text.length()); String oneletter = "A"; assertTrue(sendStringEvent(paste, oneletter)); assertEquals(inputScheme.getFlag(), -1); }*/ /** * Sends the signal to the current installed InputScheme */ private boolean sendSignal(SignalEvent sig) { return inputScheme.handleEvent(sig, ""); } private boolean sendStringEvent(SignalEvent sig, String text) { return inputScheme.handleEvent(sig, text); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/input/DefaultSchemeTest.java
javatests/com/google/collide/client/editor/input/DefaultSchemeTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.input; import static org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType.NAVIGATION; import com.google.collide.client.editor.Editor; import com.google.collide.client.testing.MockAppContext; import com.google.collide.client.util.input.KeyCodeMap; import com.google.collide.client.util.input.ModifierKeys; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineInfo; import com.google.gwt.junit.client.GWTTestCase; /** * Test cases for {@link DefaultScheme}. */ public class DefaultSchemeTest extends GWTTestCase { @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testAltMovementIsNotCosumed() { DefaultScheme scheme = new DefaultScheme(new InputController()); int[] keys = new int[] { KeyCodeMap.ARROW_LEFT, KeyCodeMap.ARROW_RIGHT, KeyCodeMap.ARROW_UP, KeyCodeMap.ARROW_DOWN}; int[][] modifiers = new int[][] {{ModifierKeys.ALT}, {ModifierKeys.ALT, ModifierKeys.ACTION}, {ModifierKeys.ALT, ModifierKeys.SHIFT}, {ModifierKeys.ALT, ModifierKeys.ACTION, ModifierKeys.SHIFT}}; for (int i = 0; i < keys.length; i++) { for (int j = 0; j < modifiers.length; j++) { TestSignalEvent event = new TestSignalEvent(keys[i], NAVIGATION, modifiers[j]); assertFalse("i = " + i + "; j = " + j, scheme.defaultMode.onDefaultInput(event, (char) 0)); } } } public void testCutWithoutSelectionAtLastEmptyLine() { String text = "first\nsecond\n"; checkCut(text, 2, 0, text); // Assert: still alive. } private void checkCut(String text, int line, int column, String expected) { Document document = Document.createFromString(text); final Editor editor = Editor.create(new MockAppContext()); editor.setDocument(document); LineInfo lineInfo = document.getLineFinder().findLine(line); editor.getSelection().setSelection(lineInfo, column, lineInfo, column); editor.getInput().processSignalEvent(TestCutPasteEvent.create(null)); assertEquals(expected, document.asText()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/input/TestCutPasteEvent.java
javatests/com/google/collide/client/editor/input/TestCutPasteEvent.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.input; import com.google.collide.json.client.Jso; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.Event; import org.waveprotocol.wave.client.common.util.SignalEvent; import javax.annotation.Nullable; /** * Implementation that simulates paste event. */ public class TestCutPasteEvent extends Jso implements SignalEvent { protected TestCutPasteEvent() { } public static native TestCutPasteEvent create(@Nullable String data) /*-{ if (data) { return {'clipboardData' : {'getData': function() {return data;}}}; } else { return {}; } }-*/; @Override public final String getType() { return null; } @Override public final Element getTarget() { return null; } @Override public final boolean isKeyEvent() { return false; } @Override public final boolean isCompositionEvent() { return false; } @Override public final boolean isImeKeyEvent() { return false; } @Override public final boolean isMouseEvent() { return false; } @Override public final boolean isMouseButtonEvent() { return false; } @Override public final boolean isMouseButtonlessEvent() { return false; } @Override public final boolean isClickEvent() { return false; } @Override public final boolean isMutationEvent() { return false; } @Override public final boolean isClipboardEvent() { return false; } @Override public final boolean isFocusEvent() { return false; } @Override public final boolean isPasteEvent() { return this.hasOwnProperty("clipboardData"); } @Override public final boolean isCutEvent() { return !isPasteEvent(); } @Override public final boolean isCopyEvent() { return false; } @Override public final boolean getCommandKey() { return false; } @Override public final boolean getCtrlKey() { return false; } @Override public final boolean getMetaKey() { return false; } @Override public final boolean getAltKey() { return false; } @Override public final boolean getShiftKey() { return false; } @Override public final Event asEvent() { return (Event) ((Object) this); } @Override public final MoveUnit getMoveUnit() { return null; } @Override public final boolean isUndoCombo() { return false; } @Override public final boolean isRedoCombo() { return false; } @Override public final boolean isCombo(int letter, KeyModifier modifier) { return false; } @Override public final boolean isOnly(int letter) { return false; } @Override public final int getKeyCode() { return 0; } @Override public final int getMouseButton() { return 0; } @Override public final KeySignalType getKeySignalType() { return null; } @Override public final void stopPropagation() { } @Override public final void preventDefault() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/input/TestSignalEvent.java
javatests/com/google/collide/client/editor/input/TestSignalEvent.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.input; import com.google.collide.client.util.input.ModifierKeys; import com.google.common.collect.Sets; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.Event; import org.waveprotocol.wave.client.common.util.SignalEvent; import java.util.Set; /** * Test wrapper for keyboard inputs. * */ public class TestSignalEvent implements SignalEvent { private final Set<Integer> modifiers = Sets.newHashSet(); private final int key; private final KeySignalType signalType; public TestSignalEvent(int key) { this(key, new int[]{}); } public TestSignalEvent(int key, KeySignalType signalType, int... modifiers) { for (int mod : modifiers) { this.modifiers.add(mod); } this.key = key; this.signalType = signalType; } public TestSignalEvent(int key, int... modifiers) { this(key, null, modifiers); } @Override public Event asEvent() { return null; } @Override public boolean getAltKey() { return modifiers.contains(ModifierKeys.ALT); } @Override public boolean getCommandKey() { return modifiers.contains(ModifierKeys.ACTION); } @Override public boolean getCtrlKey() { return modifiers.contains(ModifierKeys.ACTION); } @Override public int getKeyCode() { return key; } @Override public KeySignalType getKeySignalType() { return signalType; } @Override public boolean getMetaKey() { return false; } @Override public int getMouseButton() { return 0; } @Override public MoveUnit getMoveUnit() { return null; } @Override public boolean getShiftKey() { return modifiers.contains(ModifierKeys.SHIFT); } @Override public Element getTarget() { return null; } @Override public String getType() { return "keydown"; } @Override public boolean isClickEvent() { return false; } @Override public boolean isClipboardEvent() { return false; } @Override public boolean isCombo(int letter, KeyModifier modifier) { return false; } @Override public boolean isCompositionEvent() { return false; } @Override public boolean isCopyEvent() { return false; } @Override public boolean isCutEvent() { return false; } @Override public boolean isFocusEvent() { return false; } @Override public boolean isImeKeyEvent() { return false; } @Override public boolean isKeyEvent() { return (key != 0); } @Override public boolean isMouseButtonEvent() { return false; } @Override public boolean isMouseButtonlessEvent() { return false; } @Override public boolean isMouseEvent() { return false; } @Override public boolean isMutationEvent() { return false; } @Override public boolean isOnly(int letter) { return (letter == key); } @Override public boolean isPasteEvent() { return false; } @Override public boolean isRedoCombo() { return false; } @Override public boolean isUndoCombo() { return false; } @Override public void preventDefault() { } @Override public void stopPropagation() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/search/SearchTestsUtil.java
javatests/com/google/collide/client/editor/search/SearchTestsUtil.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.search; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.DocumentMutator; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import org.easymock.EasyMock; import org.easymock.IAnswer; /** */ public class SearchTestsUtil { // I needed some lines for searching public static final ImmutableList<String> DOCUMENT_LINES = ImmutableList.of("What do tigers dream of?", "When they take a little tiger snooze", "Do they dream of mauling zebras", "Or halli Barry in her catwoman suit.", "Don't you worry you're pretty striped head", "Were gonna get you back to Tyson and your cozy tiger bed", "And then were gonna find our best friend Doug", "And then were gonna give him a best friend hug", "Doug Doug Oh Doug Doug Dougie Doug Doug", "But if he's been murdered by crystal meth tweekers...", "Well then were shit outta luck.", "Awesome Awesome"); /** * Mocks a document with the util document lines, does not replay the document * before returning. */ public static Document createDocument() { return Document.createFromString(Joiner.on('\n').join(DOCUMENT_LINES)); } /** * Creates a viewport from a document * * @param lines Number of lines to include in viewport */ public static ViewportModel createMockViewport(Document document, int lines) { ViewportModel mockViewport = EasyMock.createMock(ViewportModel.class); Line curLine = document.getFirstLine(); expect(mockViewport.getTopLine()).andReturn(curLine).anyTimes(); expect(mockViewport.getTopLineNumber()).andReturn(0).anyTimes(); expect(mockViewport.getTopLineInfo()).andAnswer(lineInfoFactory(curLine, 0)).anyTimes(); for (int i = 0; i < lines - 1 && curLine.getNextLine() != null; i++) { curLine = curLine.getNextLine(); } expect(mockViewport.getBottomLine()).andReturn(curLine).anyTimes(); expect(mockViewport.getBottomLineNumber()).andReturn(lines - 1).anyTimes(); expect(mockViewport.getBottomLineInfo()).andAnswer( lineInfoFactory(curLine, lines - 1)).anyTimes(); replay(mockViewport); return mockViewport; } /** * Retrieves the line info of a given line */ public static LineInfo gotoLineInfo(Document document, int line) { Line curLine = document.getFirstLine(); for (int i = 0; curLine != null && i < line; i++) { curLine = curLine.getNextLine(); } return new LineInfo(curLine, line); } /** * Produces a new line info with the given parameters everytime it is called. * This is required due to LineInfo being mutable. */ public static IAnswer<LineInfo> lineInfoFactory(final Line line, final int number) { return new IAnswer<LineInfo>() { @Override public LineInfo answer() throws Throwable { return new LineInfo(line, number); } }; } /** * Stub of a mock manager that easily keeps track of the number of matches * added without a bunch of other logic. Don't call methods such as findNext * or findPrevious matches it won't appreciate it. * */ public static class StubMatchManager extends SearchMatchManager { public StubMatchManager(Document document) { super(document, EasyMock.createNiceMock(SelectionModel.class), EasyMock.createNiceMock( DocumentMutator.class), EasyMock.createNiceMock(SearchTask.class)); } @Override public void addMatches(LineInfo line, int matches) { totalMatches += matches; } @Override public void clearMatches() { totalMatches = 0; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/search/SearchMatchManagerTests.java
javatests/com/google/collide/client/editor/search/SearchMatchManagerTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.search; import static com.google.collide.client.editor.search.SearchTestsUtil.createDocument; import static com.google.collide.client.editor.search.SearchTestsUtil.createMockViewport; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.Buffer.MouseDragListener; import com.google.collide.client.editor.search.SearchModel.MatchCountListener; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.testing.StubIncrementalScheduler; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.collide.shared.util.ListenerManager; import com.google.gwt.regexp.shared.RegExp; import junit.framework.TestCase; import org.easymock.EasyMock; public class SearchMatchManagerTests extends TestCase { private Document document; private SelectionModel model; @Override public void setUp() { document = createDocument(); createSelectionModel(document); } private void createSelectionModel(Document document) { Buffer buffer = EasyMock.createNiceMock(Buffer.class); ListenerManager<MouseDragListener> listener = ListenerManager.create(); expect(buffer.getMouseDragListenerRegistrar()).andReturn(listener).anyTimes(); replay(buffer); model = SelectionModel.create(document, buffer); model.setSelection(document.getFirstLineInfo(), 0, document.getFirstLineInfo(), 0); } public void testTotalMatchesChangedListener() { SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("doug")); MatchCountListener callback = EasyMock.createMock(MatchCountListener.class); callback.onMatchCountChanged(10); callback.onMatchCountChanged(15); callback.onMatchCountChanged(0); replay(callback); manager.getMatchCountChangedListenerRegistrar().add(callback); LineInfo line = document.getFirstLineInfo(); manager.addMatches(line, 10); manager.addMatches(line, 5); manager.clearMatches(); } public void testAddGetAndClearMatches() { SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("testing")); LineInfo line = document.getFirstLineInfo(); manager.addMatches(line, 5); line.moveToNext(); manager.addMatches(line, 5); line.moveToNext(); manager.addMatches(line, 5); line.moveToNext(); manager.addMatches(line, 5); assertEquals(20, manager.getTotalMatches()); manager.clearMatches(); assertEquals(0, manager.getTotalMatches()); manager.addMatches(line, 10); manager.addMatches(line, 10); assertEquals(20, manager.getTotalMatches()); } public void testSelectMatchOnAddMatches() { SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("do")); // Should end up only selecting the first match in line 0 LineInfo line = document.getFirstLineInfo(); manager.addMatches(line, 3); assertSelection(document.getFirstLineInfo(), 5, 7); line.moveToNext(); manager.addMatches(line, 2); assertSelection(document.getFirstLineInfo(), 5, 7); } public void testFindNextMatchOnLine() { LineInfo lineEight = SearchTestsUtil.gotoLineInfo(document, 8); SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("doug", "gi")); // Select the first match then move forward two manager.addMatches(lineEight, 7); manager.selectNextMatch(); assertSelection(lineEight, 5, 9); manager.selectNextMatch(); assertSelection(lineEight, 13, 17); } public void testFindPreviousMatchOnLine() { LineInfo lineEight = SearchTestsUtil.gotoLineInfo(document, 8); SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("doug", "gi")); // Select the first match then move forward two manager.addMatches(lineEight, 7); manager.selectNextMatch(); manager.selectNextMatch(); // Go back a few matches manager.selectPreviousMatch(); assertSelection(lineEight, 5, 9); manager.selectPreviousMatch(); assertSelection(lineEight, 0, 4); } public void testFindPreviousMatchOnPreviousLine() { LineInfo lineSix = SearchTestsUtil.gotoLineInfo(document, 6); LineInfo lineEight = SearchTestsUtil.gotoLineInfo(document, 8); SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("doug", "gi")); manager.addMatches(lineEight, 7); manager.addMatches(lineSix, 1); // we should be on the very first match, go back and find the prev match manager.selectPreviousMatch(); assertSelection(lineSix, 41, 45); manager.selectPreviousMatch(); assertSelection(lineEight, 35, 39); } public void testFindNextMatchOnNextLine() { LineInfo lineSix = SearchTestsUtil.gotoLineInfo(document, 6); LineInfo lineEight = SearchTestsUtil.gotoLineInfo(document, 8); SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("doug", "gi")); manager.addMatches(lineSix, 1); manager.addMatches(lineEight, 7); // There is one match on line six so this will move us to line eight manager.selectNextMatch(); assertSelection(lineEight, 0, 4); // Now let's iterate through matches and wrap around for (int i = 0; i < 6; i++) { manager.selectNextMatch(); } manager.selectNextMatch(); assertSelection(lineSix, 41, 45); } public void testFindMatchAfterAndBeforePosition() { LineInfo lineSix = SearchTestsUtil.gotoLineInfo(document, 6); LineInfo lineEight = SearchTestsUtil.gotoLineInfo(document, 8); SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("doug", "gi")); manager.addMatches(lineSix, 1); manager.addMatches(lineEight, 7); manager.selectNextMatchFromPosition(lineEight, 20); assertSelection(lineEight, 23, 27); manager.selectPreviousMatchFromPosition(lineEight, 10); assertSelection(lineEight, 5, 9); } public void testWrapFindNextWhenMatchesOnSameLine() { LineInfo lineEleven = SearchTestsUtil.gotoLineInfo(document, 11); SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("Awesome", "gi")); manager.addMatches(lineEleven, 1); assertSelection(lineEleven, 0, 7); manager.selectNextMatch(); assertSelection(lineEleven, 8, 15); manager.selectNextMatch(); assertSelection(lineEleven, 0, 7); } public void testWrapFindPreviousWhenMatchesOnSameLine() { LineInfo lineEleven = SearchTestsUtil.gotoLineInfo(document, 11); SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("Awesome", "gi")); manager.addMatches(lineEleven, 1); assertSelection(lineEleven, 0, 7); manager.selectPreviousMatch(); assertSelection(lineEleven, 8, 15); } public void testReplaceMatch() { LineInfo lineThree = SearchTestsUtil.gotoLineInfo(document, 3); LineInfo lineSix = SearchTestsUtil.gotoLineInfo(document, 6); LineInfo lineEight = SearchTestsUtil.gotoLineInfo(document, 8); SearchMatchManager manager = createMatchManager(document, model); manager.setSearchPattern(RegExp.compile("doug", "gi")); // NOTE! Since this a not an editor mutator, selection won't be replaced // so you will get newtextoldtext when calling replace. manager.addMatches(lineSix, 1); assertTrue(manager.replaceMatch("boug")); assertEquals("boug", document.getText(lineSix.line(), 41, 4)); document.deleteText(lineSix.line(), 45, 4); assertTrue(manager.replaceMatch("soug")); assertEquals("soug", document.getText(lineEight.line(), 0, 4)); model.setSelection(lineThree, 0, lineThree, 0); manager.setSearchPattern(RegExp.compile("catwoman")); manager.addMatches(lineThree, 1); assertTrue(manager.replaceMatch("dogwoman")); assertEquals("dogwoman", document.getText(lineThree.line(), 22, 8)); } public void testReplaceAll() { SearchTask task = new SearchTask( document, createMockViewport(document, 3), new StubIncrementalScheduler(50, 50)); SearchMatchManager manager = new SearchMatchManager(document, model, document, task); manager.setSearchPattern(RegExp.compile("doug", "gi")); LineInfo lineSix = SearchTestsUtil.gotoLineInfo(document, 6); manager.addMatches(lineSix, 1); manager.replaceAllMatches("boug"); assertNull(manager.selectNextMatch()); } public void testReplaceAllOnlyOneMatch() { document = Document.createFromString("foo"); createSelectionModel(document); SearchTask task = new SearchTask(document, createMockViewport(document, 1), new StubIncrementalScheduler( 50, 50)); SearchMatchManager manager = new SearchMatchManager(document, model, document, task); manager.setSearchPattern(RegExp.compile("foo", "gi")); LineInfo lineOne = document.getFirstLineInfo(); manager.addMatches(lineOne, 1); manager.replaceAllMatches("notit"); assertNull(manager.selectNextMatch()); } public void testReplaceRecursive() { document = Document.createFromString("foo"); createSelectionModel(document); SearchTask task = new SearchTask(document, createMockViewport(document, 1), new StubIncrementalScheduler( 50, 50)); SearchMatchManager manager = new SearchMatchManager(document, model, document, task); manager.setSearchPattern(RegExp.compile("foo", "gi")); LineInfo lineOne = document.getFirstLineInfo(); manager.addMatches(lineOne, 1); manager.replaceAllMatches("foofoo"); assertNotNull(manager.selectNextMatch()); } void assertSelection(LineInfo line, int start, int end) { Position[] selection = model.getSelectionRange(false); assertEquals(line, selection[0].getLineInfo()); assertEquals(line, selection[1].getLineInfo()); assertEquals(start, selection[0].getColumn()); assertEquals(end, selection[1].getColumn()); } /** * Covers the 99% case when creating, only replaceAll relies on searchTask. */ static SearchMatchManager createMatchManager(Document document, SelectionModel selection) { return new SearchMatchManager( document, selection, document, EasyMock.createNiceMock(SearchTask.class)); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/search/SearchModelTests.java
javatests/com/google/collide/client/editor/search/SearchModelTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.search; import static com.google.collide.client.editor.search.SearchTestsUtil.createDocument; import static com.google.collide.client.editor.search.SearchTestsUtil.createMockViewport; import static com.google.collide.client.editor.search.SearchTestsUtil.gotoLineInfo; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.not; import static org.easymock.EasyMock.or; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import com.google.collide.client.AppContext; import com.google.collide.client.Resources; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.renderer.LineRenderer; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.client.editor.search.SearchMatchRenderer.Css; import com.google.collide.client.editor.search.SearchModel.SearchProgressListener; import com.google.collide.client.editor.search.SearchTestsUtil.StubMatchManager; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.testing.StubIncrementalScheduler; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineInfo; import com.google.gwt.regexp.shared.RegExp; import junit.framework.TestCase; import org.easymock.EasyMock; /** * Tests the search model */ public class SearchModelTests extends TestCase { private static AppContext createMockContext() { AppContext mockContext = EasyMock.createMock(AppContext.class); Resources mockResources = EasyMock.createMock(Resources.class); Css mockCss = EasyMock.createMock(Css.class); expect(mockContext.getResources()).andReturn(mockResources).anyTimes(); expect(mockResources.searchMatchRendererCss()).andReturn(mockCss).anyTimes(); expect(mockCss.match()).andReturn("match").anyTimes(); replay(mockCss, mockResources, mockContext); return mockContext; } private static SelectionModel createMockSelectionModel(Document document) { SelectionModel selection = EasyMock.createMock(SelectionModel.class); expect(selection.getCursorLine()).andReturn(document.getFirstLine()).anyTimes(); expect(selection.getCursorLineNumber()).andReturn(0).anyTimes(); replay(selection); return selection; } public void testSetQueryNullOrEmpty() { Document document = createDocument(); // Setup the renderer Renderer mockRenderer = EasyMock.createNiceMock(Renderer.class); mockRenderer.addLineRenderer(anyObject(LineRenderer.class)); mockRenderer.removeLineRenderer(anyObject(LineRenderer.class)); replay(mockRenderer); AppContext mockContext = createMockContext(); ViewportModel mockView = createMockViewport(document, 4); SearchModel model = SearchModel.createWithManagerAndScheduler(mockContext, document, mockRenderer, mockView, new StubMatchManager(document), new StubIncrementalScheduler(10, 1000), createMockSelectionModel(document)); // Almost nothing is performed here since there was no previous query model.setQuery(""); model.setQuery("a"); model.setQuery(""); try { model.setQuery(null); fail("Did not throw Illegal Argument Exception on Null"); } catch (IllegalArgumentException e) { } // verify verify(mockRenderer, mockView, mockContext); } public void testSetQueryReturnsNumberOfMatches() { Document document = createDocument(); AppContext mockContext = createMockContext(); ViewportModel mockView = createMockViewport(document, 4); StubMatchManager mockMatchManager = new StubMatchManager(document); // Setup Callback SearchProgressListener callback = EasyMock.createMock(SearchProgressListener.class); callback.onSearchBegin(); callback.onSearchDone(); callback.onSearchBegin(); callback.onSearchDone(); callback.onSearchBegin(); callback.onSearchDone(); callback.onSearchBegin(); callback.onSearchDone(); replay(callback); // None of these get called during this test Renderer mockRenderer = EasyMock.createNiceMock(Renderer.class); replay(mockRenderer); SearchModel model = SearchModel.createWithManagerAndScheduler(mockContext, document, mockRenderer, mockView, mockMatchManager, new StubIncrementalScheduler(10, 1000), createMockSelectionModel(document)); model.setQuery("when", callback); assertEquals(1, mockMatchManager.getTotalMatches()); model.setQuery("When", callback); assertEquals(1, mockMatchManager.getTotalMatches()); model.setQuery("Doug", callback); assertEquals(8, mockMatchManager.getTotalMatches()); model.setQuery("tiger", callback); assertEquals(3, mockMatchManager.getTotalMatches()); model.setQuery("", callback); assertEquals(0, mockMatchManager.getTotalMatches()); // verify verify(callback, mockRenderer, mockView, mockContext); } public void testCallbackCalledWhenAllLinesFitInViewport() { Document document = createDocument(); AppContext mockContext = createMockContext(); ViewportModel mockView = createMockViewport(document, SearchTestsUtil.DOCUMENT_LINES.size() - 1); StubMatchManager mockMatchManager = new StubMatchManager(document); // Setup Callback SearchProgressListener callback = EasyMock.createMock(SearchProgressListener.class); callback.onSearchBegin(); callback.onSearchDone(); callback.onSearchBegin(); callback.onSearchDone(); replay(callback); // None of these get called during this test Renderer mockRenderer = EasyMock.createNiceMock(Renderer.class); replay(mockRenderer); SearchModel model = SearchModel.createWithManagerAndScheduler(mockContext, document, mockRenderer, mockView, mockMatchManager, new StubIncrementalScheduler(10, 1000), createMockSelectionModel(document)); model.setQuery("when", callback); model.setQuery("Doug", callback); // verify callback is called verify(callback, mockRenderer, mockView, mockContext); } public void testMatchManagerIsCalledCorrectly() { Document document = createDocument(); AppContext mockContext = createMockContext(); ViewportModel mockView = createMockViewport(document, 4); // Let's test the behavior towards match manager this time SearchMatchManager mockMatchManager = EasyMock.createMock(SearchMatchManager.class); mockMatchManager.clearMatches(); expectLastCall().times(2); expect(mockMatchManager.getTotalMatches()).andReturn(8).times(2); mockMatchManager.setSearchPattern(anyObject(RegExp.class)); // Mocking the behavior of addMatches is a bit more difficult... LineInfo lineSixInfo = gotoLineInfo(document, 6); LineInfo lineEightInfo = gotoLineInfo(document, 8); mockMatchManager.addMatches(lineSixInfo, 1); mockMatchManager.addMatches(lineEightInfo, 7); mockMatchManager.addMatches(not(or(eq(lineSixInfo), eq(lineEightInfo))), eq(0)); expectLastCall().times(10); replay(mockMatchManager); // None of these get called during this test Renderer mockRenderer = EasyMock.createNiceMock(Renderer.class); replay(mockRenderer); SearchModel model = SearchModel.createWithManagerAndScheduler(mockContext, document, mockRenderer, mockView, mockMatchManager, new StubIncrementalScheduler(10, 1000), createMockSelectionModel(document)); model.setQuery("Doug"); // verify callback is called verify(mockRenderer, mockView, mockContext); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/search/SearchMatchRendererTests.java
javatests/com/google/collide/client/editor/search/SearchMatchRendererTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.search; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import com.google.collide.client.Resources; import com.google.collide.client.editor.renderer.LineRenderer.Target; import com.google.collide.client.editor.search.SearchMatchRenderer.Css; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.RegExpUtils; import com.google.common.collect.ImmutableList; import junit.framework.TestCase; import org.easymock.EasyMock; /** * TODO: when single matches can be highlighted separately implement * tests for this, the current stuff is very basic * */ public class SearchMatchRendererTests extends TestCase { private static final String MATCH_CSS = "match"; private Resources createMockResource() { Resources mockResource = EasyMock.createMock(Resources.class); Css mockCss = EasyMock.createMock(Css.class); expect(mockCss.match()).andReturn(MATCH_CSS).anyTimes(); expect(mockResource.searchMatchRendererCss()).andReturn(mockCss).anyTimes(); replay(mockCss, mockResource); return mockResource; } /** * Creates a mock target expecting render events for lengths in lengthList * * @param startInMatch if true starts expecting MATCH_CSS * @param selectedMatchIndex will use selected_match_css for the item at this * lengthList index if >= 0 and is inMatch at that index */ private Target createMockTarget(ImmutableList<Integer> lengthList, boolean startInMatch) { Target mockTarget = EasyMock.createMock(Target.class); boolean inMatch = startInMatch; for (int i = 0; i < lengthList.size(); i++) { mockTarget.render(lengthList.get(i), inMatch ? MATCH_CSS : null); inMatch = !inMatch; } replay(mockTarget); return mockTarget; } public void testRegularMatchHighlight() { SearchMatchManager mockMatchManager = EasyMock.createNiceMock(SearchMatchManager.class); replay(mockMatchManager); SearchModel mockSearchModel = EasyMock.createMock(SearchModel.class); expect(mockSearchModel.getQuery()).andReturn("Doug").anyTimes(); expect(mockSearchModel.getSearchPattern()).andReturn( RegExpUtils.createRegExpForWildcardPattern("Doug", "gi")).anyTimes(); expect(mockSearchModel.getMatchManager()).andReturn(mockMatchManager).anyTimes(); replay(mockSearchModel); Resources mockResources = createMockResource(); SearchMatchRenderer renderer = new SearchMatchRenderer(mockResources, mockSearchModel); // Now ask it about each line in our document and check to see if its right Document doc = SearchTestsUtil.createDocument(); LineInfo lineInfo = doc.getFirstLineInfo(); for (int i = 0; i < 6; i++) { assertFalse(renderer.resetToBeginningOfLine(lineInfo.line(), lineInfo.number())); lineInfo.moveToNext(); } // Check that this line is parsed correctly ImmutableList<Integer> lengthList = ImmutableList.of(41, 4); Target mockTarget = createMockTarget(lengthList, false); assertTrue(renderer.resetToBeginningOfLine(lineInfo.line(), lineInfo.number())); for (int i = 0; i < lengthList.size(); i++) { renderer.renderNextChunk(mockTarget); } lineInfo.moveToNext(); verify(mockTarget); assertFalse(renderer.resetToBeginningOfLine(lineInfo.line(), lineInfo.number())); lineInfo.moveToNext(); // The next fun line lengthList = ImmutableList.of(4,1,4,4,4,1,4,1,4,3,4,1,4); mockTarget = createMockTarget(lengthList, true); assertTrue(renderer.resetToBeginningOfLine(lineInfo.line(), lineInfo.number())); for (int i = 0; i < lengthList.size(); i++) { renderer.renderNextChunk(mockTarget); } lineInfo.moveToNext(); verify(mockTarget); assertFalse(renderer.resetToBeginningOfLine(lineInfo.line(), lineInfo.number())); lineInfo.moveToNext(); assertFalse(renderer.resetToBeginningOfLine(lineInfo.line(), lineInfo.number())); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/editor/search/SearchTaskTests.java
javatests/com/google/collide/client/editor/search/SearchTaskTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.editor.search; import static com.google.collide.client.editor.search.SearchTestsUtil.createDocument; import static com.google.collide.client.editor.search.SearchTestsUtil.createMockViewport; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.search.SearchTask.SearchDirection; import com.google.collide.client.editor.search.SearchTask.SearchTaskExecutor; import com.google.collide.client.testing.StubIncrementalScheduler; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import junit.framework.TestCase; import org.easymock.EasyMock; /** * Tests for the revamped Search Task. */ public class SearchTaskTests extends TestCase { private Document document; private StubIncrementalScheduler scheduler; @Override public void setUp() { document = createDocument(); scheduler = new StubIncrementalScheduler(10, 1000); } public void testDocumentFitsInViewport() { SearchTask task = new SearchTask(document, createMockViewport(document, 12), scheduler); SearchTaskExecutor executor = EasyMock.createMock(SearchTaskExecutor.class); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(true))) .andReturn(true).times(12); replay(executor); task.searchDocument(executor, null); verify(executor); } public void testSchedulerRunsThroughDocument() { SearchTask task = new SearchTask(document, createMockViewport(document, 5), scheduler); SearchTaskExecutor executor = EasyMock.createMock(SearchTaskExecutor.class); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(true))) .andReturn(true).times(5); expect(executor.onSearchLine( EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(false))) .andReturn(true).times(7); replay(executor); task.searchDocument(executor, null); verify(executor); } public void testDirectionDownWorks() { ViewportModel viewport = createMockViewport(document, 5); SearchTask task = new SearchTask(document, viewport, scheduler); SearchTaskExecutor executor = EasyMock.createMock(SearchTaskExecutor.class); expect(executor.onSearchLine(viewport.getTopLine(), 0, true)).andReturn(true); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(true))) .andReturn(true).times(3); expect(executor.onSearchLine(viewport.getBottomLine(), 4, true)).andReturn(true); expect(executor.onSearchLine( EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(false))) .andReturn(true).times(7); replay(executor); task.searchDocument(executor, null, SearchDirection.DOWN); verify(executor); } public void testDirectionUpWorks() { ViewportModel viewport = createMockViewport(document, 5); SearchTask task = new SearchTask(document, viewport, scheduler); SearchTaskExecutor executor = EasyMock.createMock(SearchTaskExecutor.class); expect(executor.onSearchLine(viewport.getBottomLine(), 4, true)).andReturn(true); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(true))) .andReturn(true).times(3); expect(executor.onSearchLine(viewport.getTopLine(), 0, true)).andReturn(true); expect(executor.onSearchLine(document.getLastLine(), 11, false)).andReturn(true); expect(executor.onSearchLine( EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(false))) .andReturn(true).times(6); replay(executor); task.searchDocument(executor, null, SearchDirection.UP); verify(executor); } public void testStartingAtLineWorks() { ViewportModel viewport = createMockViewport(document, 5); SearchTask task = new SearchTask(document, viewport, scheduler); LineInfo lineInfo = viewport.getTopLineInfo(); lineInfo.moveToNext(); SearchTaskExecutor executor = EasyMock.createMock(SearchTaskExecutor.class); expect(executor.onSearchLine(lineInfo.line(), 1, true)).andReturn(true); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(true))) .andReturn(true).times(2); expect(executor.onSearchLine(viewport.getBottomLine(), 4, true)).andReturn(true); expect(executor.onSearchLine( EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(false))) .andReturn(true).times(7); expect(executor.onSearchLine(viewport.getTopLine(), 0, false)).andReturn(true); replay(executor); task.searchDocumentStartingAtLine(executor, null, SearchDirection.DOWN, lineInfo); verify(executor); } public void testNoWrapWorks() { ViewportModel viewport = createMockViewport(document, 5); SearchTask task = new SearchTask(document, viewport, scheduler); SearchTaskExecutor executor = EasyMock.createMock(SearchTaskExecutor.class); expect(executor.onSearchLine(viewport.getBottomLine(), 4, true)).andReturn(true); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(true))) .andReturn(true).times(3); expect(executor.onSearchLine(viewport.getTopLine(), 0, true)).andReturn(true); replay(executor); task.setShouldWrapDocument(false); task.searchDocument(executor, null, SearchDirection.UP); verify(executor); } public void testHaltViewportSearch() { ViewportModel viewport = createMockViewport(document, 5); SearchTask task = new SearchTask(document, viewport, scheduler); SearchTaskExecutor executor = EasyMock.createMock(SearchTaskExecutor.class); expect(executor.onSearchLine(viewport.getTopLine(), 0, true)).andReturn(true); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(true))) .andReturn(true).times(3); expect(executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.eq(4), EasyMock.eq(true))) .andReturn(false); replay(executor); task.searchDocument(executor, null); verify(executor); } public void testHaltSchedulerSearch() { ViewportModel viewport = createMockViewport(document, 5); SearchTask task = new SearchTask(document, viewport, scheduler); SearchTaskExecutor executor = EasyMock.createMock(SearchTaskExecutor.class); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.anyInt(), EasyMock.eq(true))) .andReturn(true).times(5); expect( executor.onSearchLine(EasyMock.anyObject(Line.class), EasyMock.eq(5), EasyMock.eq(false))) .andReturn(false); replay(executor); task.searchDocument(executor, null); verify(executor); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/filehistory/MockTimeline.java
javatests/com/google/collide/client/filehistory/MockTimeline.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.filehistory; import com.google.collide.client.AppContext; /** * Mock Timeline used for testing, with a set interval for testing timeline math * dragging logic and stubbing out several methods related to updating the diff * editor. * * */ public class MockTimeline extends Timeline { final static int TIMELINE_INTERVAL = 100; public MockTimeline(FileHistory fileHistory, Timeline.View view, AppContext context) { super(fileHistory, view, context); } @Override public int intervalInPx() { return TIMELINE_INTERVAL; } @Override public void setDiffForRevisions() { // Do nothing } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/filehistory/MockFileHistory.java
javatests/com/google/collide/client/filehistory/MockFileHistory.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.filehistory; import com.google.collide.client.AppContext; /** * Mock FileHistory used for testing. */ public class MockFileHistory extends FileHistory{ public MockFileHistory(AppContext context) { super(new FileHistory.View(context.getResources()), FileHistoryPlace.PLACE, context); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/filehistory/TimelineTest.java
javatests/com/google/collide/client/filehistory/TimelineTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.filehistory; import com.google.collide.client.AppContext; import com.google.collide.client.testing.MockAppContext; import com.google.collide.dto.Revision.RevisionType; import com.google.collide.dto.client.DtoClientImpls.RevisionImpl; import com.google.gwt.junit.client.GWTTestCase; import java.util.Date; /** * */ public class TimelineTest extends GWTTestCase{ Timeline timeline; AppContext context; @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } @Override public void gwtSetUp() throws Exception{ super.gwtSetUp(); context = new MockAppContext(); timeline = new MockTimeline(new MockFileHistory(context), new FileHistory.View(context.getResources()).timelineView, context); FileHistoryApi api = new FileHistoryApi(context, null, timeline, null); timeline.setApi(api); RevisionImpl revision = RevisionImpl.make(); revision.setNodeId("12345"); revision.setTimestamp(Long.toString(new Date().getTime())); revision.setRevisionType(RevisionType.AUTO_SAVE); revision.setHasUnresolvedConflicts(false); revision.setIsFinalResolution(false); revision.setPreviousNodesSkipped(0); // Add 4 fake timeline nodes TimelineNode node = new TimelineNode( new TimelineNode.View(context.getResources()), 0, revision, timeline); timeline.nodes.add(node); node = new TimelineNode( new TimelineNode.View(context.getResources()), 1, revision, timeline); timeline.nodes.add(node); node = new TimelineNode( new TimelineNode.View(context.getResources()), 2, revision, timeline); timeline.nodes.add(node); node = new TimelineNode( new TimelineNode.View(context.getResources()), 3, revision, timeline); timeline.nodes.add(node); node = new TimelineNode( new TimelineNode.View(context.getResources()), 4, revision, timeline); timeline.nodes.add(node); timeline.numNodes = 5; timeline.setActiveRange(timeline.nodes.get(0), timeline.nodes.get(4)); } /** * Test that you can't drag a range line past the left edge */ public void testDragLeftPastEdge() { timeline.moveRange(-MockTimeline.TIMELINE_INTERVAL); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); } /** * Test that you can't drag a range line past the right edge */ public void testDragRightPastEdge() { timeline.moveRange(MockTimeline.TIMELINE_INTERVAL); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); } /** * Test that you can't drag the left side of the timeline past the left edge */ public void testResizeLeftPastEdges() { timeline.moveRangeEdge(timeline.nodes.get(0), -MockTimeline.TIMELINE_INTERVAL); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); } /** * Test that you can't drag the right side of the timeline past the right edge */ public void testResizeRightPastEdges() { timeline.moveRangeEdge(timeline.nodes.get(3), MockTimeline.TIMELINE_INTERVAL); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); } /** * Test that you can't resize the range line smaller than length of 1 */ public void testResize() { // Don't allow dragging the left edge to the right or the right // edge to the left if length = 1 timeline.setActiveRange(timeline.nodes.get(1), timeline.nodes.get(2)); timeline.moveRangeEdge(timeline.nodes.get(1), MockTimeline.TIMELINE_INTERVAL); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); mouseUp(); timeline.setActiveRange(timeline.nodes.get(1), timeline.nodes.get(2)); timeline.moveRangeEdge(timeline.nodes.get(2), -MockTimeline.TIMELINE_INTERVAL); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); } /** * Test snap-to resizing features */ public void testSnapToResizeLeft() { // Move more than 2/3 the way to the next node, should increment timeline.moveRangeEdge(timeline.nodes.get(0), 3 * MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); // Move less than 2/3 the way to the next node, should not increment timeline.moveRangeEdge(timeline.nodes.get(0), 1); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); // Move less than 2/3 the way to the next node, should not increment timeline.moveRangeEdge(timeline.nodes.get(0), MockTimeline.TIMELINE_INTERVAL/3); timeline.moveRangeEdge(timeline.nodes.get(0), MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); resetSnapRange(3, 4); // Move more than 2/3 the way to the next node, should decrement timeline.moveRangeEdge(timeline.nodes.get(3), -( 3 * MockTimeline.TIMELINE_INTERVAL/4)); assertEquals(timeline.tempLeftRange, timeline.nodes.get(2)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); resetSnapRange(2, 4); // Move less than 2/3 the way to the next node, should not decrement timeline.moveRangeEdge(timeline.nodes.get(2), -1); assertEquals(timeline.tempLeftRange, timeline.nodes.get(2)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); mouseUp(); // Move less than 2/3 the way to the next node, should not decrement timeline.moveRangeEdge(timeline.nodes.get(1), -MockTimeline.TIMELINE_INTERVAL/3); timeline.moveRangeEdge(timeline.nodes.get(1), -MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(2)); assertEquals(timeline.tempRightRange, timeline.nodes.get(4)); } /** * Test snap-to resizing features */ public void testSnapToResizeRight() { // Move more than 2/3 the way to the next node, should decrement timeline.moveRangeEdge(timeline.nodes.get(4), -3 * MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(3)); // Move less than 2/3 the way to the next node, should not decrement timeline.moveRangeEdge(timeline.nodes.get(4), -1); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(3)); // Move less than 2/3 the way to the next node, should not decrement timeline.moveRangeEdge(timeline.nodes.get(4), -MockTimeline.TIMELINE_INTERVAL/3); timeline.moveRangeEdge(timeline.nodes.get(4), -MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(3)); resetSnapRange(0, 1); // Move more than 2/3 the way to the next node, should increment timeline.moveRangeEdge(timeline.nodes.get(1), 3 * MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); resetSnapRange(0, 2); // Move less than 2/3 the way to the next node, should not increment timeline.moveRangeEdge(timeline.nodes.get(1), 1); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); mouseUp(); // Move less than 2/3 the way to the next node, should not increment timeline.moveRangeEdge(timeline.nodes.get(3), MockTimeline.TIMELINE_INTERVAL/3); timeline.moveRangeEdge(timeline.nodes.get(3), MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); } /** * Test snap-to dragging features */ public void testSnapToDrag() { timeline.setActiveRange(timeline.nodes.get(1), timeline.nodes.get(2)); // Move more than 2/3 the way to the next node, should increment timeline.moveRange(3 * MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(2)); assertEquals(timeline.tempRightRange, timeline.nodes.get(3)); resetSnapRange(1, 2); // Move more than 2/3 the way to the next node, should increment timeline.moveRange(((int) ((2.0/3.0) * MockTimeline.TIMELINE_INTERVAL)) + 1); assertEquals(timeline.tempLeftRange, timeline.nodes.get(2)); assertEquals(timeline.tempRightRange, timeline.nodes.get(3)); resetSnapRange(1, 2); // Move less than 2/3 the way to the next node, should not increment timeline.moveRange(1); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); resetSnapRange(1, 2); // Move less than 2/3 the way to the next node, should not increment timeline.moveRange(MockTimeline.TIMELINE_INTERVAL/3); timeline.moveRange(MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); resetSnapRange(1, 2); // Move more than 2/3 the way to the next node, should increment timeline.moveRange(-(3 * MockTimeline.TIMELINE_INTERVAL/4)); assertEquals(timeline.tempLeftRange, timeline.nodes.get(0)); assertEquals(timeline.tempRightRange, timeline.nodes.get(1)); resetSnapRange(1, 2); // Move less than 2/3 the way to the next node, should not increment timeline.moveRange(-1); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); resetSnapRange(1, 2); // Move less than 2/3 the way to the next node, should not increment timeline.moveRange(-MockTimeline.TIMELINE_INTERVAL/3); timeline.moveRange(-MockTimeline.TIMELINE_INTERVAL/4); assertEquals(timeline.tempLeftRange, timeline.nodes.get(1)); assertEquals(timeline.tempRightRange, timeline.nodes.get(2)); } public void resetSnapRange(int left, int right) { timeline.setActiveRange(timeline.nodes.get(left), timeline.nodes.get(right)); mouseUp(); } public void mouseUp() { timeline.setCurrentDragX(0); timeline.resetCatchUp(); timeline.resetLeftRange(); timeline.resetRightRange(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/history/PlaceTest.java
javatests/com/google/collide/client/history/PlaceTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.history; import static com.google.collide.client.history.MockPlaces.CHILD_A; import static com.google.collide.client.history.MockPlaces.CHILD_A_NAV; import static com.google.collide.client.history.MockPlaces.GRANDCHILD_A; import static com.google.collide.client.history.MockPlaces.GRANDCHILD_A_NAV; import static com.google.collide.client.history.MockPlaces.PARENT_A; import static com.google.collide.client.history.MockPlaces.PARENT_A_NAV; import static com.google.collide.client.history.MockPlaces.PARENT_B; import static com.google.collide.client.history.MockPlaces.PARENT_B_NAV; import com.google.collide.client.history.MockPlaces.MockChildPlaceA; import com.google.collide.client.history.MockPlaces.MockParentPlaceA; import com.google.collide.client.history.MockPlaces.MockParentPlaceB; import com.google.collide.clientlibs.navigation.NavigationToken; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.gwt.junit.client.GWTTestCase; /** * Tests our implementation of Hierarchical history as implemented in * {@link Place}. */ public class PlaceTest extends GWTTestCase { @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } @Override protected void gwtSetUp() throws Exception { super.gwtSetUp(); // Reset the Root scope, since that isn't done automatically. RootPlace.PLACE.resetScope(); // Reset the handler invocation counts. MockPlaces.resetCounts(); RootPlace.PLACE.registerChildHandler(PARENT_A, PARENT_A_NAV); RootPlace.PLACE.registerChildHandler(PARENT_B, PARENT_B_NAV); } /** * Tests that we can dispatch a line of {@link NavigationToken}s parsed from the * History string */ public void testDispatchHistory() { // Build up a History String of Root/ParentA/ChildA, that looks like // "/h/mockparenta=(someString=foo)/mockchilda=(someString=foo,someNumber=42)/" String historyString = HistoryUtils.createHistoryString(JsonCollections.<NavigationToken>createArray( PARENT_A.createNavigationEvent("foo"), CHILD_A.createNavigationEvent("foo", 42), GRANDCHILD_A.createNavigationEvent())); JsonArray<NavigationToken> historyPieces = HistoryUtils.parseHistoryString(historyString); // Bring the state of the app in line with the History String. RootPlace.PLACE.dispatchHistory(historyPieces); // Examine the state of the world. assertTrue(RootPlace.PLACE.isActive()); assertTrue(PARENT_A.isActive()); assertFalse(PARENT_B.isActive()); assertEquals(1, PARENT_A_NAV.getEnterCount()); assertEquals(0, PARENT_A_NAV.getReEnterCount()); assertEquals(0, PARENT_B_NAV.getEnterCount()); assertEquals(0, PARENT_B_NAV.getReEnterCount()); assertTrue(CHILD_A.isActive()); assertEquals(1, CHILD_A_NAV.getEnterCount()); assertEquals(0, CHILD_A_NAV.getReEnterCount()); assertTrue(GRANDCHILD_A.isActive()); assertEquals(1, GRANDCHILD_A_NAV.getEnterCount()); assertEquals(0, GRANDCHILD_A_NAV.getReEnterCount()); } public void testMultipleHandlers() { MockParentPlaceA.NavigationHandler nav2 = new MockParentPlaceA.NavigationHandler(); RootPlace.PLACE.registerChildHandler(PARENT_A, nav2); MockParentPlaceA.NavigationEvent navEvent = PARENT_A.createNavigationEvent("asdf"); RootPlace.PLACE.fireChildPlaceNavigation(navEvent); // Verify both handlers got called assertTrue(PARENT_A.isActive()); assertEquals(1, PARENT_A_NAV.getEnterCount()); assertEquals(0, PARENT_A_NAV.getReEnterCount()); assertEquals(0, PARENT_A_NAV.getCleanupCount()); assertEquals(1, nav2.getEnterCount()); // Navigate away MockParentPlaceB.NavigationEvent parentBNavEvent = PARENT_B.createNavigationEvent(); RootPlace.PLACE.fireChildPlaceNavigation(parentBNavEvent); // Verify that both cleanup handlers were called assertFalse(PARENT_A.isActive()); assertEquals(1, PARENT_A_NAV.getCleanupCount()); assertEquals(1, nav2.getCleanupCount()); } /** * Tests navigating to a child Place. */ public void testNavigateToChildPlace() { String someString = "foo"; int someNumber = 42; // Lets trigger a navigation to Parent B. MockParentPlaceB.NavigationEvent parentBNavEvent = PARENT_B.createNavigationEvent(); RootPlace.PLACE.fireChildPlaceNavigation(parentBNavEvent); // Verify we went to Parent B from Root. assertTrue(PARENT_B.isActive()); assertEquals(1, PARENT_B_NAV.getEnterCount()); assertEquals(0, PARENT_B_NAV.getReEnterCount()); assertEquals(0, PARENT_B_NAV.getCleanupCount()); // Try to get to Child A from Parent B. We know that this should not be // possible. MockChildPlaceA.NavigationEvent childNavEvent = CHILD_A.createNavigationEvent(someString, someNumber); PARENT_B.fireChildPlaceNavigation(childNavEvent); // We should still have not done the navigation. assertFalse(CHILD_A.isActive()); assertEquals(0, CHILD_A_NAV.getEnterCount()); assertEquals(0, CHILD_A_NAV.getReEnterCount()); // Lets trigger a navigation to Parent A. MockParentPlaceA.NavigationEvent parentANavEvent = PARENT_A.createNavigationEvent(someString); RootPlace.PLACE.fireChildPlaceNavigation(parentANavEvent); // Verify we are no longer in B and that we did not change any of the // handler invocation counts assertFalse(PARENT_B.isActive()); assertEquals(1, PARENT_B_NAV.getCleanupCount()); assertFalse(CHILD_A.isActive()); assertEquals(1, PARENT_B_NAV.getEnterCount()); assertEquals(0, CHILD_A_NAV.getEnterCount()); assertEquals(0, CHILD_A_NAV.getReEnterCount()); // Verify that we are in Parent A. assertTrue(PARENT_A.isActive()); assertEquals(1, PARENT_A_NAV.getEnterCount()); // Try to get to Child A from Parent A. PARENT_A.fireChildPlaceNavigation(childNavEvent); // We should now be in A. assertTrue(CHILD_A.isActive()); assertEquals(1, CHILD_A_NAV.getEnterCount()); assertEquals(0, CHILD_A_NAV.getReEnterCount()); // Verify the other Places did not get weird. assertTrue(RootPlace.PLACE.isActive()); assertTrue(PARENT_A.isActive()); assertFalse(PARENT_B.isActive()); assertEquals(1, PARENT_A_NAV.getEnterCount()); assertEquals(0, PARENT_A_NAV.getReEnterCount()); assertEquals(1, PARENT_B_NAV.getEnterCount()); assertEquals(0, PARENT_B_NAV.getReEnterCount()); assertEquals(1, PARENT_B_NAV.getCleanupCount()); } /** * Tests navigating to a child Place when on a Parent place is not active. */ public void testNavigateToChildPlaceNotActive() { // Try to get to Child A from Parent A when Parent A is not active. MockChildPlaceA.NavigationEvent childNavEvent = CHILD_A.createNavigationEvent("foo", 42); PARENT_A.fireChildPlaceNavigation(childNavEvent); // We should have not done the navigation. assertEquals(0, CHILD_A_NAV.getEnterCount()); assertEquals(0, CHILD_A_NAV.getReEnterCount()); } public void testNavigateToSamePlace() { // Lets trigger a navigation to Parent B. MockParentPlaceA.NavigationEvent parentANavEvent = PARENT_A.createNavigationEvent("foo"); RootPlace.PLACE.fireChildPlaceNavigation(parentANavEvent); // Verify we went to Parent B from Root. assertTrue(PARENT_A.isActive()); assertEquals(1, PARENT_A_NAV.getEnterCount()); assertEquals(0, PARENT_A_NAV.getReEnterCount()); assertEquals(0, PARENT_A_NAV.getCleanupCount()); RootPlace.PLACE.fireChildPlaceNavigation(PARENT_A.createNavigationEvent("foo")); // Verify that we didn't double navigate, but rather did a re-entrant // dispatch that did not deliver any new state. assertTrue(PARENT_A.isActive()); assertEquals(1, PARENT_A_NAV.getEnterCount()); assertEquals(1, PARENT_A_NAV.getReEnterCount()); assertFalse(PARENT_A_NAV.hadNewState()); assertEquals(0, PARENT_A_NAV.getCleanupCount()); // Now try again with different params to the event RootPlace.PLACE.fireChildPlaceNavigation(PARENT_A.createNavigationEvent("bar")); // Verify that we re-entrantly dispatched and had some new state. assertTrue(PARENT_A.isActive()); assertEquals(1, PARENT_A_NAV.getEnterCount()); assertEquals(2, PARENT_A_NAV.getReEnterCount()); assertTrue(PARENT_A_NAV.hadNewState()); assertEquals(0, PARENT_A_NAV.getCleanupCount()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/history/HistoryUtilsTest.java
javatests/com/google/collide/client/history/HistoryUtilsTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.history; import static com.google.collide.client.history.MockPlaces.PARENT_A; import com.google.collide.client.history.HistoryUtils.SetHistoryListener; import com.google.collide.client.history.HistoryUtils.ValueChangeListener; import com.google.collide.json.client.JsoArray; import com.google.gwt.junit.client.GWTTestCase; /** * These test cases exercise the static methods in {@link HistoryUtils} for * encoding and decoding History information. */ public class HistoryUtilsTest extends GWTTestCase { // A test times out in 2 seconds. static final int WAIT_TIMEOUT_MILLIS = 2000; @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } private static class MockUrlListener implements SetHistoryListener, ValueChangeListener { int callCount = 0; @Override public void onHistorySet(String historyString) { callCount++; } @Override public void onValueChanged(String historyString) { callCount++; } } /** * Tests that we get notified of changes to the History token that we made. */ public void testSetHistoryListener() { boolean called = false; final MockUrlListener urlListener = new MockUrlListener(); HistoryUtils.addSetHistoryListener(urlListener); // It should be called once immediately to snapshot the current URL. assertEquals(1, urlListener.callCount); JsoArray<PlaceNavigationEvent<?>> snapshot = JsoArray.create(); snapshot.add(PARENT_A.createNavigationEvent("foo")); // Change history. It should inform the UrlListener. HistoryUtils.createHistoryEntry(snapshot); assertEquals(2, urlListener.callCount); // Make a change outside of HistoryUtils. It should NOT fire the listener. // TODO: Forge uses FF3.5, which doesnt allow the following to // pass. Once forge gets a recent version of firefox, we should turn this // test // code back on. // Browser.getWindow().getLocation().setHash("setexternally"); // // Browser.getWindow().setTimeout(new TimerCallback() { // @Override // public void fire() { // assertEquals(2, urlListener.callCount); // finishTest(); // } // }, 100); // // delayTestFinish(WAIT_TIMEOUT_MILLIS); } /** * Tests that we get notified of changes to the History token that were made * externally (like from the back and forward button). */ public void testValueChangeListener() { final MockUrlListener urlListener = new MockUrlListener(); HistoryUtils.addValueChangeListener(urlListener); assertEquals(0, urlListener.callCount); // TODO: Forge uses FF3.5, which doesnt allow the following to // pass. Once forge gets a recent version of firefox, we should turn this // test // code back on. // Browser.getWindow().getLocation().setHash("setexternallyAgain"); // // Browser.getWindow().setTimeout(new TimerCallback() { // @Override // public void fire() { // // It should inform the UrlListener. // assertEquals(1, urlListener.callCount); // // JsoArray<PlaceNavigationEvent<?>> snapshot = JsoArray.create(); // snapshot.add(PARENT_A.createNavigationEvent("foo")); // // // Change history. It should NOT inform the UrlListener. // HistoryUtils.createHistoryEntry(snapshot); // assertEquals(1, urlListener.callCount); // finishTest(); // } // }, 100); // // delayTestFinish(WAIT_TIMEOUT_MILLIS); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/history/MockPlaces.java
javatests/com/google/collide/client/history/MockPlaces.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.history; import com.google.collide.json.client.JsoStringMap; import com.google.collide.json.shared.JsonStringMap; /** * Mock {@link Place}s used for testing. * */ public class MockPlaces { /** * A Mock Child. * * Lets call him "Child A". */ public static class MockChildPlaceA extends MockPlace { /** * The {@link PlaceNavigationEvent} for Child A. */ public class NavigationEvent extends PlaceNavigationEvent<MockChildPlaceA> { int someNumber; String someString; protected NavigationEvent() { super(MockChildPlaceA.this); } @Override public JsonStringMap<String> getBookmarkableState() { JsoStringMap<String> keyValues = JsoStringMap.create(); keyValues.put(SOME_STRING_KEY, someString); keyValues.put(SOME_NUMBER_KEY, someNumber + ""); return keyValues; } } /** * The {@link PlaceNavigationHandler} for Child A. */ public static class NavigationHandler extends MockPlaceNavigationHandler< MockChildPlaceA.NavigationEvent> { @Override protected void enterPlace(MockChildPlaceA.NavigationEvent navigationEvent) { super.enterPlace(navigationEvent); navigationEvent.getPlace().registerChildHandler(GRANDCHILD_A, GRANDCHILD_A_NAV); } } protected MockChildPlaceA() { super("MockChildPlaceA"); } @Override public MockChildPlaceA.NavigationEvent createNavigationEvent( JsonStringMap<String> decodedState) { // If this decoded string is not a valid integer, this will throw. Which // is fine. Let it break the test. return createNavigationEvent( decodedState.get(SOME_STRING_KEY), Integer.parseInt(decodedState.get(SOME_NUMBER_KEY))); } public MockChildPlaceA.NavigationEvent createNavigationEvent( String someString, int someNumber) { MockChildPlaceA.NavigationEvent navEvent = new MockChildPlaceA.NavigationEvent(); navEvent.someString = someString; navEvent.someNumber = someNumber; return navEvent; } } /** * A Mock Child with no bookmarkable state. * * Lets call him "GrandChild B". */ public static class MockGrandChildPlaceA extends MockPlace { /** * The {@link PlaceNavigationEvent} for GrandChild B. */ public class NavigationEvent extends PlaceNavigationEvent<MockGrandChildPlaceA> { protected NavigationEvent() { super(MockGrandChildPlaceA.this); } @Override public JsonStringMap<String> getBookmarkableState() { return JsoStringMap.create(); } } /** * The {@link PlaceNavigationHandler} for Child B. */ public static class NavigationHandler extends MockPlaceNavigationHandler< MockGrandChildPlaceA.NavigationEvent> { } protected MockGrandChildPlaceA() { super("MockGrandChildPlaceA"); } @Override public MockGrandChildPlaceA.NavigationEvent createNavigationEvent( JsonStringMap<String> decodedState) { return new MockGrandChildPlaceA.NavigationEvent(); } } /** * A Mock Parent. * * Lets call him "A". */ public static class MockParentPlaceA extends MockPlace { /** * The {@link PlaceNavigationEvent} for A. */ public class NavigationEvent extends PlaceNavigationEvent<MockParentPlaceA> { String someString; protected NavigationEvent() { super(MockParentPlaceA.this); } @Override public JsonStringMap<String> getBookmarkableState() { JsoStringMap<String> keyValues = JsoStringMap.create(); keyValues.put(SOME_STRING_KEY, someString); return keyValues; } } /** * The {@link PlaceNavigationHandler} for A. */ public static class NavigationHandler extends MockPlaceNavigationHandler< MockParentPlaceA.NavigationEvent> { @Override protected void enterPlace(MockParentPlaceA.NavigationEvent navigationEvent) { super.enterPlace(navigationEvent); // Add a Child to ParentA. navigationEvent.getPlace().registerChildHandler(MockPlaces.CHILD_A, CHILD_A_NAV); } } protected MockParentPlaceA() { super("MockParentPlaceA"); } @Override public MockParentPlaceA.NavigationEvent createNavigationEvent( JsonStringMap<String> decodedState) { return createNavigationEvent(decodedState.get(SOME_STRING_KEY)); } public MockParentPlaceA.NavigationEvent createNavigationEvent(String someString) { MockParentPlaceA.NavigationEvent navEvent = new MockParentPlaceA.NavigationEvent(); navEvent.someString = someString; return navEvent; } } /** * A Mock Parent. * * Lets call him "B". */ public static class MockParentPlaceB extends MockPlace { /** * The {@link PlaceNavigationEvent} for B. */ public class NavigationEvent extends PlaceNavigationEvent<MockParentPlaceB> { protected NavigationEvent() { super(MockParentPlaceB.this); } @Override public JsonStringMap<String> getBookmarkableState() { // We keep no state. return JsoStringMap.create(); } } /** * The {@link PlaceNavigationHandler} for B. */ public static class NavigationHandler extends MockPlaceNavigationHandler< MockParentPlaceB.NavigationEvent> { } protected MockParentPlaceB() { super("MockParentPlaceB"); } @Override public MockParentPlaceB.NavigationEvent createNavigationEvent() { return new MockParentPlaceB.NavigationEvent(); } @Override public MockParentPlaceB.NavigationEvent createNavigationEvent( JsonStringMap<String> decodedState) { return createNavigationEvent(); } } /** * Base class for all mock Places. */ public abstract static class MockPlace extends Place { protected MockPlace(String placeName) { super(placeName); } } /** * Base class for mock PlaceNavigationHandlers. Lets us track invocation * counts. */ abstract static class MockPlaceNavigationHandler<E extends PlaceNavigationEvent<?>> extends PlaceNavigationHandler<E> { private int enterCount; private int cleanupCount; private int reEnterCount; private boolean hadNewState; MockPlaceNavigationHandler() { } @Override protected void cleanup() { cleanupCount++; } @Override protected void enterPlace(E navigationEvent) { enterCount++; } @Override protected void reEnterPlace(E navigationEvent, boolean newState) { reEnterCount++; hadNewState = newState; } public boolean hadNewState() { return hadNewState; } public int getEnterCount() { return enterCount; } public int getCleanupCount() { return cleanupCount; } public int getReEnterCount() { return reEnterCount; } public void resetCounts() { enterCount = 0; cleanupCount = 0; reEnterCount = 0; } } public static final MockChildPlaceA CHILD_A = new MockChildPlaceA(); public static final MockChildPlaceA.NavigationHandler CHILD_A_NAV = new MockChildPlaceA.NavigationHandler(); public static final MockGrandChildPlaceA GRANDCHILD_A = new MockGrandChildPlaceA(); public static final MockGrandChildPlaceA.NavigationHandler GRANDCHILD_A_NAV = new MockGrandChildPlaceA.NavigationHandler(); public static final MockParentPlaceA PARENT_A = new MockParentPlaceA(); public static final MockParentPlaceA.NavigationHandler PARENT_A_NAV = new MockParentPlaceA.NavigationHandler(); public static final MockParentPlaceB PARENT_B = new MockParentPlaceB(); public static final MockParentPlaceB.NavigationHandler PARENT_B_NAV = new MockParentPlaceB.NavigationHandler(); public static final String SOME_NUMBER_KEY = "someNumber"; public static final String SOME_STRING_KEY = "someString"; public static void resetCounts() { CHILD_A_NAV.resetCounts(); CHILD_A.setIsActive(false, null); GRANDCHILD_A_NAV.resetCounts(); GRANDCHILD_A.setIsActive(false, null); PARENT_A_NAV.resetCounts(); PARENT_A.setIsActive(false, null); PARENT_B_NAV.resetCounts(); PARENT_B.setIsActive(false, null); } private MockPlaces() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/diff/DeltaInfoBarTest.java
javatests/com/google/collide/client/diff/DeltaInfoBarTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.diff; import com.google.collide.client.diff.DeltaInfoBar.Css; import com.google.collide.dto.client.DtoClientImpls.DiffStatsDtoImpl; import com.google.gwt.core.client.GWT; import com.google.gwt.junit.client.GWTTestCase; import elemental.html.DivElement; /** * Tests the {@link DeltaInfoBar} * */ public class DeltaInfoBarTest extends GWTTestCase { private static final int ADDED_LINES = 20; private static final int LARGE_TOTAL = 1000; private static final int CHANGED_LINES = 50; private static final int DELETED_LINES = 49; private static final int UNCHANGED_LINES = 1; @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } public void testAtLeastOne() { assertEquals(1, DeltaInfoBar.calculateBars(1, LARGE_TOTAL)); } public void testBarCount() { DiffStatsDtoImpl diffStats = (DiffStatsDtoImpl) DiffStatsDtoImpl.create(); diffStats .setAdded(ADDED_LINES) .setChanged(CHANGED_LINES) .setDeleted(DELETED_LINES) .setUnchanged(UNCHANGED_LINES); DeltaInfoBar.Resources res = (DeltaInfoBar.Resources) GWT.create(DeltaInfoBar.Resources.class); DeltaInfoBar deltaInfoBar = DeltaInfoBar.create(res, diffStats, false); DivElement barsDiv = deltaInfoBar.getView().barsDiv; Css css = res.deltaInfoBarCss(); int addedBars = barsDiv.getElementsByClassName(css.added()).getLength(); int removedBars = barsDiv.getElementsByClassName(css.deleted()).getLength(); int modifiedBars = barsDiv.getElementsByClassName(css.modified()).getLength(); int unmodifiedBars = barsDiv.getElementsByClassName(css.unmodified()).getLength(); // verify the total count assertEquals(DeltaInfoBar.BAR_COUNT, addedBars + removedBars + modifiedBars + unmodifiedBars); // Because BAR_COUNT can change, and testing the exact amounts involves // re-implementing calculateBars here, we verify that the ordering of // amounts is sane. assertTrue(unmodifiedBars <= addedBars); assertTrue(addedBars <= removedBars); assertTrue(removedBars <= modifiedBars); assertEquals(DeltaInfoBar.BAR_COUNT - (addedBars + removedBars + modifiedBars), unmodifiedBars); } public void testZero() { assertEquals(0, DeltaInfoBar.calculateBars(0, LARGE_TOTAL)); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/xhrmonitor/XhrWardenTests.java
javatests/com/google/collide/client/xhrmonitor/XhrWardenTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.xhrmonitor; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import com.google.collide.client.xhrmonitor.XhrWarden.WardenXhrRequest; import junit.framework.TestCase; import org.easymock.EasyMock; import elemental.xml.XMLHttpRequest; import java.util.ArrayList; import java.util.List; /** * Tests the warden. */ public class XhrWardenTests extends TestCase { private static final int TEST_WARNING_LIMIT = 7; private static final int TEST_ERROR_LIMIT = 8; /** * Creates a mock request but does not automatically replay it! */ private static WardenXhrRequest createRequest(int id, double timestamp) { WardenXhrRequest request = EasyMock.createNiceMock(WardenXhrRequest.class); expect(request.getId()).andReturn(String.valueOf(id)).anyTimes(); expect(request.getTime()).andReturn(timestamp).anyTimes(); return request; } /** * Creates a number of warden http requests starting with start id and at * timestamp. For each created request start id and timestamp will be * incremented by 1. * * Request mocks are automatically replayed. */ private static List<WardenXhrRequest> createMultipleRequests( int number, int startid, int timestamp) { List<WardenXhrRequest> requests = new ArrayList<WardenXhrRequest>(); for (int i = 0; i < number; i++) { WardenXhrRequest request = createRequest(startid++, timestamp++); replay(request); requests.add(request); } return requests; } /** * Creates multiple WardenHttpRequests starting at id 1 and timestamp 1. * * Request mocks are automatically replayed. */ private static List<WardenXhrRequest> createMultipleRequests(int number) { return createMultipleRequests(number, 1, 1); } private XhrWarden.WardenListener listener; private XhrWarden.WardenImpl warden; @Override public void setUp() { listener = EasyMock.createMock(XhrWarden.WardenListener.class); warden = new XhrWarden.WardenImpl(TEST_WARNING_LIMIT, TEST_ERROR_LIMIT, listener); } public void testDontKillRequestsWhenUnderLimit() { List<WardenXhrRequest> requests = createMultipleRequests(XhrWarden.WARDEN_WARNING_THRESHOLD - 1); replay(listener); for (WardenXhrRequest request : requests) { warden.onRequestOpening(request); warden.onRequestOpen(request); } assertEquals(requests.size(), warden.getRequestCount()); // Effectively nothing special should have occurred for (WardenXhrRequest request : requests) { verify(request); } verify(listener); } public void testLongestIdleIsCorrect() { List<WardenXhrRequest> requests = createMultipleRequests(XhrWarden.WARDEN_WARNING_THRESHOLD - 1); replay(listener); for (WardenXhrRequest request : requests) { warden.onRequestOpening(request); warden.onRequestOpen(request); } assertSame(requests.get(0), warden.getLongestIdleRequest()); verify(listener); } public void testRequestsAreRemovedWhenFinished() { List<WardenXhrRequest> requests = createMultipleRequests(XhrWarden.WARDEN_WARNING_THRESHOLD - 1); replay(listener); for (WardenXhrRequest request : requests) { warden.onRequestOpening(request); warden.onRequestOpen(request); warden.onRequestDone(request); } assertEquals(0, warden.getRequestCount()); verify(listener); } public void testWarningAreIssuesWhenRequestLimitIsHit() { List<WardenXhrRequest> requests = createMultipleRequests(TEST_WARNING_LIMIT); // Mock up listener behavior listener.onWarning(warden); expectLastCall().times(2); replay(listener); // Add 7 Requests which will trigger the limit for (WardenXhrRequest request : requests) { warden.onRequestOpening(request); warden.onRequestOpen(request); } warden.onRequestDone(requests.get(TEST_WARNING_LIMIT - 1)); // This will cause another log to the listener warden.onRequestOpening(requests.get(TEST_WARNING_LIMIT - 1)); warden.onRequestOpen(requests.get(TEST_WARNING_LIMIT - 1)); // This should not trigger another warning since we are still over the limit WardenXhrRequest lastRequest = createRequest(TEST_WARNING_LIMIT, TEST_WARNING_LIMIT); replay(lastRequest); warden.onRequestOpen(lastRequest); assertEquals(TEST_WARNING_LIMIT, warden.getRequestCount()); verify(listener); } public void testErrorsAreIssuedWhenRequestHitRequestLimit() { List<WardenXhrRequest> requests = createMultipleRequests(TEST_ERROR_LIMIT, 2, 2); WardenXhrRequest killedRequest = createRequest(1, 1); killedRequest.kill(); replay(killedRequest); // Mock up listener behavior listener.onWarning(warden); listener.onEmergency(warden, killedRequest); replay(listener); // Add 9 Requests which will trigger the over-limit warden.onRequestOpening(killedRequest); warden.onRequestOpen(killedRequest); for (WardenXhrRequest request : requests) { warden.onRequestOpening(request); warden.onRequestOpen(request); } assertEquals(8, warden.getRequestCount()); verify(listener, killedRequest); } public void testCustomHeadersInserted() { XhrWarden.WardenListener listener = EasyMock.createMock(XhrWarden.WardenListener.class); replay(listener); XMLHttpRequest mockXHR = EasyMock.createMock(XMLHttpRequest.class); mockXHR.setRequestHeader("X-Test", "test"); replay(mockXHR); WardenXhrRequest request = createRequest(1, 1); expect(request.getRequest()).andReturn(mockXHR).anyTimes(); replay(request); warden.addCustomHeader("X-Test", "test"); warden.onRequestOpen(request); verify(mockXHR); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/collaboration/CollaborationTestUtils.java
javatests/com/google/collide/client/collaboration/CollaborationTestUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.collaboration; import com.google.collide.client.collaboration.IncomingDocOpDemultiplexer.Receiver; import com.google.collide.client.collaboration.cc.RevisionProvider; import com.google.collide.client.communication.MessageFilter; import com.google.collide.client.testing.MockFrontendApi; import com.google.collide.client.testing.MockFrontendApi.MockApi; import com.google.collide.dto.DocOp; import com.google.collide.dto.RecoverFromMissedDocOps; import com.google.collide.dto.RecoverFromMissedDocOpsResponse; import com.google.collide.dto.ServerToClientDocOp; import com.google.collide.dto.client.DtoClientImpls.ClientToServerDocOpImpl; import com.google.collide.dto.client.DtoClientImpls.DocOpImpl; import com.google.collide.dto.client.DtoClientImpls.MockRecoverFromMissedDocOpsResponseImpl; import com.google.collide.dto.client.DtoClientImpls.MockServerToClientDocOpImpl; import com.google.collide.dto.client.DtoClientImpls.RecoverFromMissedDocOpsImpl; import com.google.collide.dto.client.DtoClientImpls.RecoverFromMissedDocOpsResponseImpl; import com.google.collide.dto.client.DtoClientImpls.ServerToClientDocOpImpl; import com.google.collide.dto.client.ClientDocOpFactory; import com.google.collide.json.client.JsoArray; import com.google.collide.shared.ot.DocOpBuilder; import com.google.collide.shared.util.ErrorCallback; import com.google.collide.shared.util.Reorderer.TimeoutCallback; import junit.framework.Assert; /** * Test utilities for that are generally applicable to many different types of collaboration tests. */ public class CollaborationTestUtils { static class ReceiverListener implements DocOpReceiver.Listener<DocOp>, RevisionProvider { private int revision; ReceiverListener(int startingRevision) { revision = startingRevision; } @Override public int revision() { return revision; } @Override public void onMessage(int resultingRevision, String sid, DocOp mutation) { Assert.assertEquals(++revision, resultingRevision); } @Override public void onError(Throwable e) { Assert.fail(); } } static class Objects { final DocOpReceiver receiver; final IncomingDocOpDemultiplexer.Receiver transportSink; final MockLastClientToServerDocOpProvider sender; final DocOpRecoverer recoverer; final RevisionProvider version; final MockApi<RecoverFromMissedDocOps, RecoverFromMissedDocOpsResponse> api; final ReceiverListener receiverListener; public Objects(DocOpReceiver receiver, Receiver transportSink, MockApi<RecoverFromMissedDocOps, RecoverFromMissedDocOpsResponse> api, ReceiverListener receiverListener, MockLastClientToServerDocOpProvider sender, DocOpRecoverer recoverer, @SuppressWarnings("unused") MessageFilter messageFilter) { this.receiver = receiver; this.transportSink = transportSink; this.api = api; this.recoverer = recoverer; version = this.receiverListener = receiverListener; this.sender = sender; } } public static final String FILE_EDIT_SESSION_KEY = "2"; public static final ErrorCallback FAIL_ERROR_CALLBACK = new ErrorCallback() { @Override public void onError() { Assert.fail(); } }; public static final TimeoutCallback FAIL_TIMEOUT_CALLBACK = new TimeoutCallback() { @Override public void onTimeout(int lastVersionDispatched) { Assert.fail(); } }; static final DocOpImpl DOC_OP = (DocOpImpl) new DocOpBuilder(ClientDocOpFactory.INSTANCE, false).insert("a") .retainLine(1).build(); static ClientToServerDocOpImpl newOutgoingDocOpMsg(int version, int docOpCount) { return ClientToServerDocOpImpl.make() .setFileEditSessionKey(FILE_EDIT_SESSION_KEY) .setCcRevision(version) .setSelection(null) .setDocOps2(getRepeatedDocOps(docOpCount)); } static ServerToClientDocOpImpl newIncomingDocOpMsg(int appliedVersion) { return MockServerToClientDocOpImpl.make().setAppliedCcRevision(appliedVersion).setDocOp2(DOC_OP) .setFileEditSessionKey(FILE_EDIT_SESSION_KEY); } static RecoverFromMissedDocOpsImpl newRecoverMsg(int version, int unackedDocOpCount) { return RecoverFromMissedDocOpsImpl.make() .setCurrentCcRevision(version) .setDocOps2(getRepeatedDocOps(unackedDocOpCount)) .setFileEditSessionKey(FILE_EDIT_SESSION_KEY); } static RecoverFromMissedDocOpsResponseImpl newRecoverResponseMsg( int appliedVersion, int historyDocOpCount) { JsoArray<ServerToClientDocOp> docOpMsgs = JsoArray.create(); for (int i = 0; i < historyDocOpCount; i++) { docOpMsgs.add(MockServerToClientDocOpImpl.make() .setFileEditSessionKey(FILE_EDIT_SESSION_KEY) .setDocOp2(DOC_OP) .setAppliedCcRevision(appliedVersion++)); } return MockRecoverFromMissedDocOpsResponseImpl.make().setDocOps(docOpMsgs); } private static JsoArray<String> getRepeatedDocOps(int count) { JsoArray<String> docOps = JsoArray.create(); while (docOps.size() < count) { docOps.add(DOC_OP.serialize()); } return docOps; } static Objects createObjects( int startVersion, TimeoutCallback outOfOrderTimeoutCallback, int outOfOrderTimeoutMs) { MessageFilter messageFilter = new MessageFilter(); DocOpReceiver docOpReceiver = new DocOpReceiver( IncomingDocOpDemultiplexer.create(messageFilter), FILE_EDIT_SESSION_KEY, outOfOrderTimeoutCallback, outOfOrderTimeoutMs); MockApi<RecoverFromMissedDocOps, RecoverFromMissedDocOpsResponse> api = (MockApi<RecoverFromMissedDocOps, RecoverFromMissedDocOpsResponse>) new MockFrontendApi().RECOVER_FROM_MISSED_DOC_OPS; ReceiverListener receiverListener = new ReceiverListener(startVersion); docOpReceiver.setRevisionProvider(receiverListener); MockLastClientToServerDocOpProvider lastDocOpProvider = new MockLastClientToServerDocOpProvider(); DocOpRecoverer docOpRecoverer = new DocOpRecoverer(FILE_EDIT_SESSION_KEY, api, docOpReceiver, lastDocOpProvider, receiverListener); docOpReceiver.connect(startVersion, receiverListener); return new Objects(docOpReceiver, docOpReceiver.unorderedDocOpReceiver, api, receiverListener, lastDocOpProvider, docOpRecoverer, messageFilter); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/collaboration/DocOpRecovererTests.java
javatests/com/google/collide/client/collaboration/DocOpRecovererTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.collaboration; import static com.google.collide.client.collaboration.CollaborationTestUtils.*; import com.google.collide.shared.util.Reorderer.TimeoutCallback; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.user.client.Timer; /** * General tests for recovering from missed doc op scenarios. * * This mocks out a few classes, but purposefully does not mock out {@link DocOpReceiver} since it * is a critical component of recovery too. * */ public class DocOpRecovererTests extends GWTTestCase { private final TimeoutCallback finishTestTimeoutCallback = new TimeoutCallback() { @Override public void onTimeout(int lastVersionDispatched) { finishTest(); } }; /** * Non-collaborative session where a single user is typing and gets his acks out-of-order. */ public void testAcksOutOfOrderWithoutCollaborators() { final int startVersion = 1, docOpCount = 3; CollaborationTestUtils.Objects o = CollaborationTestUtils.createObjects(startVersion, FAIL_TIMEOUT_CALLBACK, 1); // User types something o.sender.set(newOutgoingDocOpMsg(startVersion, docOpCount)); // Receives acks, but out-of-order o.transportSink.onDocOpReceived(newIncomingDocOpMsg(3), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(4), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(2), DOC_OP); // Ensure doc op receiver is fed the right data assertEquals(startVersion + 3, o.receiverListener.revision()); } /** * Non-collaborative session where a single user is typing and his client doesn't get an ack. */ public void testAckNotReceivedWithoutCollaborators() { final int startVersion = 1, docOpCount = 3; CollaborationTestUtils.Objects o = CollaborationTestUtils.createObjects(startVersion, FAIL_TIMEOUT_CALLBACK, 1); // User types something o.sender.set(newOutgoingDocOpMsg(startVersion, docOpCount)); // Imagine we never received an ack, trigger recovery o.api.expectAndReturn(newRecoverMsg(startVersion, docOpCount), newRecoverResponseMsg(startVersion + 1, docOpCount)); o.recoverer.recover(FAIL_ERROR_CALLBACK); // Ensure doc op receiver is fed the right data assertEquals(startVersion + 3, o.receiverListener.revision()); } /** * Non-collaborative session where a single user is typing and his client doesn't get an ack so he * does a recovery. However, after the recovery, the slow ack finally arrives, so make sure it * doesn't blow up because it's already seen the doc op by then. */ public void testAckReceivedAfterRecoveryWithoutCollaborators() { final int startVersion = 1, docOpCount = 3; CollaborationTestUtils.Objects o = CollaborationTestUtils.createObjects(startVersion, FAIL_TIMEOUT_CALLBACK, 1); // User types something o.sender.set(newOutgoingDocOpMsg(startVersion, docOpCount)); // Imagine we never received an ack, trigger recovery o.api.expectAndReturn(newRecoverMsg(startVersion, docOpCount), newRecoverResponseMsg(startVersion + 1, docOpCount)); o.recoverer.recover(FAIL_ERROR_CALLBACK); // Ensure doc op receiver is fed the right data assertEquals(startVersion + 3, o.receiverListener.revision()); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(2), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(3), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(4), DOC_OP); } /** * Collaborative session where a user is typing and his client doesn't get an ack. While he is * recovering, he gets collaborator doc ops. */ public void testAckNotReceivedWithCollaboratorsTypingDuringRecovery() { final int startVersion = 1, userDocOpCount = 3, collaboratorsDocOpCount = 6; final CollaborationTestUtils.Objects o = CollaborationTestUtils.createObjects(startVersion, FAIL_TIMEOUT_CALLBACK, 1); // User types something o.sender.set(newOutgoingDocOpMsg(startVersion, userDocOpCount)); // Imagine we never received an ack, trigger recovery o.api.expectAndReturnAsync(newRecoverMsg(startVersion, userDocOpCount), newRecoverResponseMsg(2, userDocOpCount + collaboratorsDocOpCount)); o.recoverer.recover(FAIL_ERROR_CALLBACK); // Recover is waiting on XHR response, imagine the collaborator doc ops arrive right now o.transportSink.onDocOpReceived(newIncomingDocOpMsg(2), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(3), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(4), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(5), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(6), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(7), DOC_OP); delayTestFinish(100); new Timer() { @Override public void run() { // By now, the recovery XHR response should have come back // Ensure doc op receiver is fed the right data assertEquals( startVersion + userDocOpCount + collaboratorsDocOpCount, o.receiverListener.revision()); finishTest(); } }.schedule(1); } /** * Collaborative session where a user is typing and his client doesn't get an ack. While he is * recovering, he gets collaborator doc ops, but they are out-of-order. All of the collaborator * doc ops arrive in the recovery response (imagine they had been applied before the server got * the recovery XHR). */ public void testAckNotReceivedWithCollaboratorsTypingButOutOfOrderDuringRecovery() { final int startVersion = 1, userDocOpCount = 3, collaboratorsDocOpCount = 6; final CollaborationTestUtils.Objects o = CollaborationTestUtils.createObjects(startVersion, FAIL_TIMEOUT_CALLBACK, 1); // User types something o.sender.set(newOutgoingDocOpMsg(startVersion, userDocOpCount)); // Imagine we never received an ack, trigger recovery o.api.expectAndReturnAsync(newRecoverMsg(startVersion, userDocOpCount), newRecoverResponseMsg(2, userDocOpCount + collaboratorsDocOpCount)); o.recoverer.recover(FAIL_ERROR_CALLBACK); // Recover is waiting on XHR response, imagine the collaborator doc ops arrive right now o.transportSink.onDocOpReceived(newIncomingDocOpMsg(2), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(5), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(7), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(3), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(4), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(6), DOC_OP); delayTestFinish(100); new Timer() { @Override public void run() { // By now, the recovery XHR response should have come back // Ensure doc op receiver is fed the right data assertEquals( startVersion + userDocOpCount + collaboratorsDocOpCount, o.receiverListener.revision()); finishTest(); } }.schedule(1); } /** * Non-collaborative session where a single user is typing and gets his acks out-of-order but is * missing one, so it times out. */ public void testAcksOutOfOrderAndTimesOutWithoutCollaborators() { final int startVersion = 1, docOpCount = 3; CollaborationTestUtils.Objects o = CollaborationTestUtils.createObjects(startVersion, finishTestTimeoutCallback, 1); // User types something o.sender.set(newOutgoingDocOpMsg(startVersion, docOpCount)); // Receives acks, but out-of-order o.transportSink.onDocOpReceived(newIncomingDocOpMsg(4), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(2), DOC_OP); delayTestFinish(100); } /** * Collaborative session where a user is typing and his client doesn't get an ack. While he is * recovering, he gets collaborator doc ops, but they are out-of-order. Some of the collaborator * doc ops were applied after the XHR got to the server, but suppose some weird network latency * existed so those arrived before the client got the XHR. One of those was dropped, so it should * timeout. */ public void testAckNotReceivedWithCollaboratorsTypingButOutOfOrderWithDropDuringRecovery() { final int startVersion = 1, userDocOpCount = 3, collaboratorsDocOpDuringXhrCount = 4; final CollaborationTestUtils.Objects o = CollaborationTestUtils.createObjects(startVersion, finishTestTimeoutCallback, 1); // User types something o.sender.set(newOutgoingDocOpMsg(startVersion, userDocOpCount)); // Imagine we never received an ack, trigger recovery o.api.expectAndReturnAsync(newRecoverMsg(startVersion, userDocOpCount), newRecoverResponseMsg(2, userDocOpCount + collaboratorsDocOpDuringXhrCount)); o.recoverer.recover(FAIL_ERROR_CALLBACK); // Recover is waiting on XHR response, imagine the collaborator doc ops arrive right now o.transportSink.onDocOpReceived(newIncomingDocOpMsg(2), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(5), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(3), DOC_OP); o.transportSink.onDocOpReceived(newIncomingDocOpMsg(4), DOC_OP); /* * Server gets XHR, it applies my 3 doc ops (v6, v7, v8), and also 2 more collaborator doc ops * (v9, v10). Imagine one of the collaborator doc ops is dropped (v9). Like we mentioned in * javadoc, client<->server has weird latency issues so the XHR response arrives later than the * collaborator doc ops. */ o.transportSink.onDocOpReceived(newIncomingDocOpMsg(10), DOC_OP); delayTestFinish(100); new Timer() { @Override public void run() { // By now, the recovery XHR response should have come back // Ensure doc op receiver is fed the right data assertTrue(startVersion + userDocOpCount + collaboratorsDocOpDuringXhrCount <= o.receiverListener.revision()); // We will now wait for the timeout (waiting for v6) to finish the test } }.schedule(1); } @Override public String getModuleName() { return "com.google.collide.client.collaboration.TestCollaboration"; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/collaboration/MockLastClientToServerDocOpProvider.java
javatests/com/google/collide/client/collaboration/MockLastClientToServerDocOpProvider.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.collaboration; import com.google.collide.dto.client.DtoClientImpls.ClientToServerDocOpImpl; /** * Mock implementation of {@link LastClientToServerDocOpProvider}. */ public class MockLastClientToServerDocOpProvider implements LastClientToServerDocOpProvider { private ClientToServerDocOpImpl lastClientToServerDocOpMsg; @Override public ClientToServerDocOpImpl getLastClientToServerDocOpMsg() { return lastClientToServerDocOpMsg; } @Override public void clearLastClientToServerDocOpMsg( ClientToServerDocOpImpl clientToServerDocOpMsgToDelete) { if (clientToServerDocOpMsgToDelete.equals(lastClientToServerDocOpMsg)) { lastClientToServerDocOpMsg = null; } } void set(ClientToServerDocOpImpl clientToServerDocOpMsg) { lastClientToServerDocOpMsg = clientToServerDocOpMsg; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/autoindenter/PyAutoindenterTest.java
javatests/com/google/collide/client/autoindenter/PyAutoindenterTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.autoindenter; import static com.google.collide.client.code.autocomplete.TestUtils.createDocumentParser; import com.google.collide.client.code.autocomplete.TestUtils; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.Editor; import com.google.collide.client.testing.MockAppContext; import com.google.collide.client.testutil.CodeMirrorTestCase; import com.google.collide.client.util.PathUtil; import com.google.collide.shared.document.Document; import org.waveprotocol.wave.client.common.util.SignalEvent; /** * Tests for {@link Autoindenter} for python files. */ public class PyAutoindenterTest extends CodeMirrorTestCase { @Override public String getModuleName() { return "com.google.collide.client.autoindenter.TestModule"; } public void testIndentClass() { String text = "class Foo:"; String expected = "class Foo:\n "; checkAutoindenter(text, 0, 10, 0, 10, AutoindenterTest.TRIGGER_ENTER, expected, true); } public void testIndentMethod() { String text = "class Foo:\n def bar:"; String expected = "class Foo:\n def bar:\n "; checkAutoindenter(text, 1, 10, 1, 10, AutoindenterTest.TRIGGER_ENTER, expected, true); } public void testNoIndentEmptyLine() { String text = "class Foo:\n def bar:\n"; String expected = "class Foo:\n def bar:\n\n"; checkAutoindenter(text, 2, 0, 2, 0, AutoindenterTest.TRIGGER_ENTER, expected, false); } public void testNoIndentWhitespaceLine() { String text = "class Foo:\n def bar:\n "; String expected = "class Foo:\n def bar:\n \n"; checkAutoindenter(text, 2, 2, 2, 2, AutoindenterTest.TRIGGER_ENTER, expected, false); } private static void checkAutoindenter(String text, int line1, int column1, int line2, int column2, final SignalEvent trigger, String expected, boolean allowScheduling) { PathUtil path = new PathUtil("test.py"); TestUtils.MockIncrementalScheduler parseScheduler = new TestUtils.MockIncrementalScheduler(); Document document = Document.createFromString(text); DocumentParser documentParser = createDocumentParser(path, true, parseScheduler, document); Editor editor = Editor.create(new MockAppContext()); editor.setDocument(document); documentParser.begin(); assertEquals(1, parseScheduler.requests.size()); parseScheduler.requests.pop().run(300); AutoindenterTest.checkAutoindenter(line1, column1, line2, column2, trigger, expected, allowScheduling, documentParser, document, editor); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/autoindenter/AutoindenterTest.java
javatests/com/google/collide/client/autoindenter/AutoindenterTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.autoindenter; import static com.google.collide.client.code.autocomplete.TestUtils.createDocumentParser; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.input.TestCutPasteEvent; import com.google.collide.client.editor.input.TestSignalEvent; import com.google.collide.client.testing.MockAppContext; import com.google.collide.client.testutil.SynchronousTestCase; import com.google.collide.client.testutil.TestSchedulerImpl; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.input.KeyCodeMap; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.util.JsonCollections; import com.google.gwt.core.client.Scheduler; import org.waveprotocol.wave.client.common.util.SignalEvent; /** * Tests for {@link Autoindenter}. */ public class AutoindenterTest extends SynchronousTestCase { static final SignalEvent TRIGGER_ENTER = new TestSignalEvent( KeyCodeMap.ENTER, SignalEvent.KeySignalType.INPUT, 0); @Override public String getModuleName() { return "com.google.collide.client.autoindenter.TestModule"; } public void testAtStart() { String text = " A\n B"; String expected = "\n A\n B"; checkAutoindenter(text, 0, 0, 0, 0, TRIGGER_ENTER, expected, false); } public void testAfterSpace() { String text = " A\n B"; String expected = " \n A\n B"; checkAutoindenter(text, 0, 1, 0, 1, TRIGGER_ENTER, expected, true); } public void testAfterText() { String text = " A.B"; String expected = " A.\n B"; checkAutoindenter(text, 0, 6, 0, 6, TRIGGER_ENTER, expected, true); } public void testAtEol() { String text = " A;"; String expected = " A;\n "; checkAutoindenter(text, 0, 6, 0, 6, TRIGGER_ENTER, expected, true); } public void testSourceLine() { String text = " A;\n B;\n C;\n"; String expected = " A;\n B;\n \n C;\n"; checkAutoindenter(text, 1, 6, 1, 6, TRIGGER_ENTER, expected, true); } public void testEnterOnSelection() { String text = " hello\n\n world\n"; checkAutoindenter(text, 1, 0, 2, 0, TRIGGER_ENTER, text, false); } public void testInsertLine() { String text = " ThreadUtils.runInParallel(\n function() {\n },\n );\n"; SignalEvent trigger = TestCutPasteEvent.create(" driverF.login(LOGIN_F, PASS);\n"); String expected = " ThreadUtils.runInParallel(\n function() {\n" + " driverF.login(LOGIN_F, PASS);\n },\n );\n"; checkAutoindenter(text, 2, 0, 2, 0, trigger, expected, false); } private static void checkAutoindenter(String text, int line1, int column1, int line2, int column2, final SignalEvent trigger, String expected, boolean allowScheduling) { PathUtil path = new PathUtil("test.js"); DocumentParser documentParser = createDocumentParser(path); Document document = Document.createFromString(text); Editor editor = Editor.create(new MockAppContext()); editor.setDocument(document); checkAutoindenter(line1, column1, line2, column2, trigger, expected, allowScheduling, documentParser, document, editor); } static void checkAutoindenter(int line1, int column1, int line2, int column2, final SignalEvent trigger, String expected, boolean allowScheduling, DocumentParser documentParser, Document document, final Editor editor) { Autoindenter autoindenter = Autoindenter.create(documentParser, editor); LineFinder lineFinder = document.getLineFinder(); editor.getSelection().setSelection( lineFinder.findLine(line1), column1, lineFinder.findLine(line2), column2); Runnable triggerClicker = new Runnable() { @Override public void run() { editor.getInput().processSignalEvent(trigger); } }; final JsonArray<Scheduler.ScheduledCommand> scheduled = JsonCollections.createArray(); TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() { @Override public void scheduleDeferred(ScheduledCommand scheduledCommand) { // Do nothing } @Override public void scheduleFinally(ScheduledCommand scheduledCommand) { scheduled.add(scheduledCommand); } }; try { TestSchedulerImpl.runWithSpecificScheduler(triggerClicker, scheduler); } finally { autoindenter.teardown(); } if (!allowScheduling) { if (scheduled.size() > 0) { fail("unexpected scheduling"); } } else { if (scheduled.size() != 1) { fail("exactly 1 scheduled command expected, but " + scheduled.size() + " were scheduled"); } scheduled.get(0).execute(); } assertEquals(expected, document.asText()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/BootstrappedGwtTestCase.java
javatests/com/google/collide/client/testing/BootstrappedGwtTestCase.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.dto.Participant; import com.google.collide.dto.client.DtoClientImpls.ParticipantImpl; import com.google.gwt.junit.client.GWTTestCase; /** * A variant of GWTTestCase providing baked-in mockery of the bootstrap code * injected onto our hosting page, such that code like * {@link com.google.collide.client.bootstrap.BootstrapSession * BootstrapSession} can work in tests. * */ public abstract class BootstrappedGwtTestCase extends GWTTestCase { public static final String TESTUSER_EMAIL = "testuser@test.org"; public static final String TESTUSER_USERID = "12345"; public static Participant makeParticipant() { return makeParticipant(TESTUSER_USERID); } public static Participant makeParticipant(String userId) { ParticipantImpl result = ParticipantImpl.make(); result.setUserId(userId); return result; } protected void assertVisibility(boolean visibility, com.google.gwt.dom.client.Element elem) { assertVisibility(visibility, Elements.asJsElement(elem)); } protected void assertVisibility(boolean visibility, elemental.dom.Element elem) { assertEquals(visibility, CssUtils.isVisible(elem)); } @Override protected void gwtSetUp() throws Exception { super.gwtSetUp(); injectBootstrapSession(); } protected native void injectBootstrapSession() /*-{ var email = @com.google.collide.client.testing.BootstrappedGwtTestCase::TESTUSER_EMAIL; var userId = @com.google.collide.client.testing.BootstrappedGwtTestCase::TESTUSER_USERID; $wnd['__session'] = { "activeClient": userId + "345", "userId": userId, "email": email, "isAdmin": false, }; $wnd['__channelKeepAliveIntervalMs'] = 10000; }-*/; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/FrontendExpectation.java
javatests/com/google/collide/client/testing/FrontendExpectation.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.collide.client.communication.FrontendApi.ApiCallback; import com.google.collide.client.testing.MockFrontendApi.MockApi; import com.google.collide.dto.ServerError; import com.google.collide.dto.ServerError.FailureReason; import com.google.collide.dtogen.shared.ClientToServerDto; import com.google.collide.dtogen.shared.RoutableDto; import com.google.collide.dtogen.shared.ServerToClientDto; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; /** * Canned expectations, pairing an expected message with either a simulated * response ({@link FrontendExpectation.Response}), simulated server failure * ({@link FrontendExpectation.Fail}), or a simulated client-side exception * ({@link FrontendExpectation.Throw}). * * These are used in the {@link MockApi} class. * * * @param <REQ> request type for the expectation * @param <RESP> correct response type for the expectation */ abstract class FrontendExpectation< REQ extends ClientToServerDto, RESP extends ServerToClientDto> extends Expectation<REQ, RESP> { /** * Expectation for a server-side error instead of a correct message. * * @param <REQ> request type * @param <RESP> correct response type (of the contract, not the thrown * exception type) */ public static class Fail<REQ extends ClientToServerDto, RESP extends ServerToClientDto> extends FrontendExpectation<REQ, RESP> { @SuppressWarnings("unused") private ServerError error; public Fail(REQ req, ServerError error) { super(req); this.error = error; } @Override public void doCallback(final ApiCallback<RESP> callback) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { // did we really mean to lose our thrown info? callback.onFail(FailureReason.COMMUNICATION_ERROR); } }); } } /** * Expectation for a server-side error due to a communication error. * * @param <REQ> request type */ public static class CommunicationFailure< REQ extends ClientToServerDto, RESP extends ServerToClientDto> extends FrontendExpectation< REQ, RESP> { public CommunicationFailure(REQ request) { super(request); } @Override public void doCallback(final ApiCallback<RESP> callback) { callback.onFail(FailureReason.COMMUNICATION_ERROR); } } /** * Expectation for a correct message response. * * @param <REQ> request type * @param <RESP> response type */ public static class Response<REQ extends ClientToServerDto, RESP extends ServerToClientDto> extends FrontendExpectation<REQ, RESP> { private RESP response; public Response(REQ req, RESP response) { super(req); this.response = response; } @Override public void doCallback(final ApiCallback<RESP> callback) { callback.onMessageReceived(response); } } /** * Expectation for a correct message response, delivered asynchronously. * * @param <REQ> request type * @param <RESP> response type */ public static class AsyncResponse<REQ extends ClientToServerDto, RESP extends ServerToClientDto> extends FrontendExpectation<REQ, RESP> { private RESP response; public AsyncResponse(REQ req, RESP response) { super(req); this.response = response; } @Override public void doCallback(final ApiCallback<RESP> callback) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { callback.onMessageReceived(response); } }); } } /** * Expectation for a thrown exception instead of a correct message. * * @param <REQ> request type * @param <RESP> correct response type (of the contract, not the thrown * exception type) */ public static class Throw<REQ extends ClientToServerDto, RESP extends ServerToClientDto> extends FrontendExpectation<REQ, RESP> { @SuppressWarnings("unused") private Throwable response; public Throw(REQ req, Throwable response) { super(req); this.response = response; } @Override public void doCallback(final ApiCallback<RESP> callback) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { // did we really mean to lose our thrown info? callback.onFail(FailureReason.COMMUNICATION_ERROR); } }); } } public FrontendExpectation(REQ request) { super(request); } /** * Throws a runtime exception if the given request isn't the expected value. * * @param request actual request to test against expection */ public void checkExpectation(REQ request) { String check = checkMatch(this.request, request); if (check.length() > 0) { throw new ExpectationViolation(check); } } /** * Does whatever this expectation type does with the callback object. * * @param callback */ public abstract void doCallback(ApiCallback<RESP> callback); /** * Tests two message objects for "equality," not identity or class-identity, * by checking that all the object fields match except Chrome's __gwt_ObjectId * * To allow some looseness in the matching, the check is not symmetric. Any * properties set in the first, pattern object must match those in the second, * target argument, but the reverse is not true. * * @param pattern the "pattern" objects, the properties of which have to * match those in the {@code target} object. * @param target the "actual" object in the comparison. This may have extra * properties not checked by the {@code pattern}, but where they do overlap, * the {@code target} properties must match the {@code pattern}. * @return an empty string if the objects do match, or a text identifying the * mismatch(es) if they do not. */ @VisibleForTesting static native String checkMatch(RoutableDto pattern, RoutableDto target) /*-{ var result = new Array(); // some special handling for arrays, for which we don't want "extra is okay" if (pattern instanceof Array) { if (! target instanceof Array) { result.push("expected array, got non-array object"); } else if (pattern.length != target.length) { result.push("expected array length " + pattern.length + ", got array of length " + target.length); } } for (prop in pattern) { if (pattern.hasOwnProperty(prop)) { if (typeof(pattern[prop]) == 'object') { if (typeof(target[prop]) != 'object') { result.push(" field " + prop + " is not an object, but " + typeof(target[prop])); } else { // using a simple != fails, it gives identity not equivalence. // so we recurse checking property equivalence: var fail = @com.google.collide.client.testing.FrontendExpectation::checkMatch(Lcom/google/collide/dtogen/shared/RoutableDto;Lcom/google/collide/dtogen/shared/RoutableDto;) (pattern[prop], target[prop]); if (fail != "") { result.push("in field " + prop + ": " + fail); } } } else if (typeof(target[prop]) == 'undefined' || pattern[prop] != target[prop]) { result.push(" field " + prop + " does not match: " + pattern[prop] + " != " + target[prop]); } } } return result.toString(); }-*/; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/Expectation.java
javatests/com/google/collide/client/testing/Expectation.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import junit.framework.AssertionFailedError; /** * An expectation mechanism for any object type. See {@link FrontendExpectation} for * DTO-specific utility. * * * @param <REQ> * @param <RESP> */ public class Expectation<REQ, RESP> { public static class ExpectationViolation extends AssertionFailedError { public ExpectationViolation(String diff) { super("difference detected: " + diff); } } public static class LeftoverExpectations extends AssertionFailedError { public LeftoverExpectations(int remaining, Expectation<?, ?> first) { super("there are " + remaining + " unmet expectations, starting with one for " + first.request.toString()); } } protected REQ request; public Expectation(REQ request) { this.request = request; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/StubProjectInfo.java
javatests/com/google/collide/client/testing/StubProjectInfo.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.collide.dto.ProjectInfo; import com.google.collide.dto.Role; /** * A {@link ProjectInfo} which can be customized for testing. * */ public class StubProjectInfo implements ProjectInfo { public static StubProjectInfo make() { String idAndName = String.valueOf(ID++); return new StubProjectInfo(idAndName, idAndName); } public static StubProjectInfo make(String idAndName) { return new StubProjectInfo(idAndName, idAndName); } /** * Static field to get an id and name from. */ private static int ID = 10; private final String id; private String name; private StubProjectInfo(String id, String name) { this.id = id; this.name = name; } @Override public Role getCurrentUserRole() { // if you need this add it throw new UnsupportedOperationException(); } @Override public String getId() { return id; } @Override public String getLogoUrl() { // if you need this add it throw new UnsupportedOperationException(); } @Override public String getName() { return name; } @Override public String getRootWsId() { // if you need this add it throw new UnsupportedOperationException(); } @Override public String getSummary() { // if you need this add it throw new UnsupportedOperationException(); } public StubProjectInfo setName(String name) { this.name = name; return this; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/StubWorkspaceInfo.java
javatests/com/google/collide/client/testing/StubWorkspaceInfo.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.collide.clientlibs.model.Workspace; import com.google.collide.clientlibs.network.shared.WorkspaceImpl; import com.google.collide.dto.Role; import com.google.collide.dto.RunTarget; import com.google.collide.dto.UserDetails; import com.google.collide.dto.Visibility; import com.google.collide.dto.WorkspaceInfo; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * A stub workspace info which behaves just nice enough to be inserted and used. * */ public class StubWorkspaceInfo implements WorkspaceInfo { public static StubWorkspaceInfo make() { String idAndTime = String.valueOf(ID++); return new StubWorkspaceInfo( idAndTime, idAndTime, DEFAULT_PROJECT_ID, WorkspaceType.ACTIVE, Visibility.PRIVATE); } public static JsonArray<WorkspaceInfo> createMultiple(int mocks) { JsonArray<WorkspaceInfo> workspaces = JsonCollections.createArray(); for (int i = 0; i < mocks; i++) { workspaces.add(StubWorkspaceInfo.make()); } return workspaces; } public static JsonArray<Workspace> createMultipleAsWorkspace(int mocks) { JsonArray<Workspace> workspaces = JsonCollections.createArray(); for (int i = 0; i < mocks; i++) { workspaces.add(StubWorkspaceInfo.make().asWorkspace()); } return workspaces; } public static final String DEFAULT_PROJECT_ID = "TEST_PROJECT"; public static final String DEFAULT_NAME = "stub"; public static final String DEFAULT_DESCRIPTION = "stub branch"; /** * Static field to get an id and a time from. Just increases forever. */ private static int ID = 10; private String id; private String time; private String projectId; private String name = DEFAULT_NAME; private String description = DEFAULT_DESCRIPTION; private String parentId; private WorkspaceType workspaceType; private Role role; private Role parentRole; private Visibility visibility; private StubWorkspaceInfo(String id, String time, String projectId, WorkspaceType workspaceType, Visibility visibility) { this.id = id; this.time = time; this.projectId = projectId; this.workspaceType = workspaceType; this.visibility = visibility; } @Override public String getArchivedTime() { throw new UnsupportedOperationException(); } @Override public String getCreatedTime() { throw new UnsupportedOperationException(); } @Override public String getDescription() { return description; } @Override public String getId() { return id; } @Override public String getName() { return name; } @Override public String getOwningProjectId() { return projectId; } @Override public String getParentId() { return parentId; } @Override public Role getCurrentUserRole() { return role; } @Override public Role getCurrentUserRoleForParent() { return parentRole; } @Override public RunTarget getRunTarget() { throw new UnsupportedOperationException(); } @Override public String getSortTime() { return time; } @Override public String getSubmissionTime() { throw new UnsupportedOperationException(); } @Override public Visibility getVisibility() { return visibility; } @Override public UserDetails getSubmitter() { throw new UnsupportedOperationException(); } @Override public WorkspaceType getWorkspaceType() { return workspaceType; } @Override public int getType() { return 0; } public StubWorkspaceInfo setId(String id) { this.id = id; return this; } public StubWorkspaceInfo setTime(String time) { this.time = time; return this; } public StubWorkspaceInfo setWorkspaceType(WorkspaceType type) { this.workspaceType = type; return this; } public StubWorkspaceInfo setProjectId(String projectId) { this.projectId = projectId; return this; } public StubWorkspaceInfo setName(String name) { this.name = name; return this; } public StubWorkspaceInfo setDescription(String description) { this.description = description; return this; } public StubWorkspaceInfo setRole(Role role) { this.role = role; return this; } public StubWorkspaceInfo setParentRole(Role parentRole) { this.parentRole = parentRole; return this; } public StubWorkspaceInfo setVisibility(Visibility visibility) { this.visibility = visibility; return this; } public StubWorkspaceInfo setParentId(String parentId) { this.parentId = parentId; return this; } public WorkspaceImpl asWorkspace() { // TODO: something real? return new WorkspaceImpl(null); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/PlaceGwtTestCase.java
javatests/com/google/collide/client/testing/PlaceGwtTestCase.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import collide.client.util.Elements; import com.google.collide.client.AppContext; import com.google.collide.client.TestHelper; import com.google.collide.dto.ProjectInfo; import com.google.collide.dto.client.DtoClientImpls.ProjectInfoImpl; import com.google.collide.json.client.JsoArray; import com.google.collide.json.client.JsoStringMap; import elemental.html.DivElement; /** * A base class for tests exploiting Collide's Place infrastructure. */ public abstract class PlaceGwtTestCase extends CommunicationGwtTestCase { private static final String PROJECT_ID = "projectid"; protected static final String WS_ID = "1234"; private boolean initialized = false; /** * This gwtSetUp builds on the super class's, by setting the expectations * needed to get the places installed, then installing the places, and thus * draining those expectations. We do assert that the drainage is complete * here. */ @Override public void gwtSetUp() throws Exception { super.gwtSetUp(); if (!initialized) { initialized = true; // some of the place handlers assume there's an element with the GWT_ROOT // id... which is true in the app, but not in tests. Make one: if (Elements.getElementById(AppContext.GWT_ROOT) == null) { DivElement gwt_root = Elements.createDivElement(); gwt_root.setId(AppContext.GWT_ROOT); Elements.getBody().appendChild(gwt_root); } } // expectations for setupPlaces()... MockFrontendApi frontend = context.getFrontendApi(); JsoArray<ProjectInfo> projects = JsoArray.create(); projects.add( ProjectInfoImpl.make().setId(PROJECT_ID).setName("projectname").setSummary("summary")); JsoStringMap<String> templates = JsoStringMap.create(); // no templates // and do the setupPlaces, which will also drain those expectations. Unlike // EasyMock, we don't have any record/replay modality to mess with... so the // user's test expectations can be "recorded" even after this. TestHelper.setupPlaces(context); context.assertIsDrained(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/Counter.java
javatests/com/google/collide/client/testing/Counter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; /** * A local-scope object that can be "final" (for access by inner class methods) * but count test calls. * */ public class Counter { private int value; public Counter() { value = 0; } public Counter(int initialValue) { value = initialValue; } public int getValue() { return value; } public void decrement() { value--; } public void decrement(int decrBy) { value -= decrBy; } public void increment() { value++; } public void increment(int incrBy) { value += incrBy; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/MockAppContext.java
javatests/com/google/collide/client/testing/MockAppContext.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.collide.client.AppContext; import com.google.collide.client.Resources; import com.google.collide.client.editor.EditorContext; /** * A variant of {@link AppContext} which provides mock stubs for server communication, to enable * standalone unit testing. */ public class MockAppContext extends AppContext implements EditorContext<Resources> { private MockFrontendApi mockFrontendApi = new MockFrontendApi(); public MockAppContext() { } /** * Checks that all the mock APIs are drained. Throws an exception if not. */ public void assertIsDrained() { mockFrontendApi.assertIsDrained(); } /** * Returns the frontend API, cast as a mock */ @Override public MockFrontendApi getFrontendApi() { return mockFrontendApi; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/StubIncrementalScheduler.java
javatests/com/google/collide/client/testing/StubIncrementalScheduler.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.collide.client.util.IncrementalScheduler; /** * Stub incremental scheduler that can substituted for testing purposes. * Executes all operations synchronously and does not adjust the work amount * dynamically. */ public class StubIncrementalScheduler implements IncrementalScheduler { private final int workGuess; public StubIncrementalScheduler(int targetExecutionMs, int workGuess) { this.workGuess = workGuess; } @Override public void schedule(Task worker) { if (worker == null) { return; } while (true) { if (!worker.run(workGuess)) { break; } } } @Override public void cancel() { // no-op } @Override public boolean isPaused() { // TODO: Auto-generated method stub return false; } @Override public void pause() { // no-op } @Override public void resume() { // no-op } @Override public boolean isBusy() { return false; } @Override public void teardown() { // no-op } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/CommunicationGwtTestCase.java
javatests/com/google/collide/client/testing/CommunicationGwtTestCase.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; /** * Test case superclass for tests driving mock communication APIs. * */ public abstract class CommunicationGwtTestCase extends BootstrappedGwtTestCase { /** milliseconds after test method completion to wait before finishTest(). */ public static final int DEFAULT_TIMEOUT = 500; protected MockAppContext context; @Override public void gwtSetUp() throws Exception { super.gwtSetUp(); context = new MockAppContext(); } @Override public void gwtTearDown() throws Exception { super.gwtTearDown(); try { context.assertIsDrained(); } catch (Exception t) { // teardown can't fail the test, but at least we can warn people... System.err.println("Unmet expectations remain in MockAppContext at teardown"); throw t; } context = null; } protected void waitForMocksToDrain() { waitForMocksToDrain(DEFAULT_TIMEOUT); } protected void waitForMocksToDrain(int timeout) { delayTestFinish(timeout); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { // and wait for a second event loop cycle, to be sure we're last: Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { context.assertIsDrained(); finishTest(); } }); } }); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/MockDocOpsSavedNotifier.java
javatests/com/google/collide/client/testing/MockDocOpsSavedNotifier.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.collide.client.collaboration.DocOpsSavedNotifier; /** * Mock class for {@link DocOpsSavedNotifier}. * * <p>This will callback the client synchronously. */ public class MockDocOpsSavedNotifier extends DocOpsSavedNotifier { public MockDocOpsSavedNotifier() { super(null, null); } @Override public boolean notifyForWorkspace(Callback callback) { callback.onAllDocOpsSaved(); return false; } @Override public boolean notifyForFiles(Callback callback, String... fileEditSessionKeys) { callback.onAllDocOpsSaved(); return false; } @Override public boolean notifyForDocuments(Callback callback, int... documentIds) { callback.onAllDocOpsSaved(); return false; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/ExpectationTest.java
javatests/com/google/collide/client/testing/ExpectationTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.collide.client.testing.CollideDtoClientTestingImpls.ComplexDtoImpl; import com.google.collide.client.testing.CollideDtoClientTestingImpls.MockNestedDtoResponseImpl; import com.google.collide.client.testing.CollideDtoClientTestingImpls.NestedDtoResponseImpl; import com.google.collide.client.testing.CollideDtoClientTestingImpls.SimpleDtoImpl; import com.google.collide.client.testing.dto.ComplexDto; import com.google.collide.client.testing.dto.SimpleDto; import com.google.collide.dto.client.DtoClientImpls.CreateProjectImpl; import com.google.collide.dto.client.DtoClientImpls.CreateWorkspaceImpl; import com.google.collide.json.client.JsoArray; import com.google.collide.json.client.JsoStringMap; import com.google.gwt.junit.client.GWTTestCase; /** * */ public class ExpectationTest extends GWTTestCase { private static final String NAME = "SomeName"; private static final String OTHER = "Other"; /** * Some syntactic sugar for asserting a happy {@link FrontendExpectation#checkMatch}. * * @param checkResult */ private void assertCheckOkay(String checkResult) { assertEquals("", checkResult); } /** * Checks that a given {@link FrontendExpectation#checkMatch} result contains the * expected failure as a substring. */ private void assertCheckFails(String substring, String checkResult) { assertTrue("expected \"" + substring + "\" does not occur in \"" + checkResult + "\"", checkResult.contains(substring)); } @Override public String getModuleName() { return "com.google.collide.client.Collide"; } public void testCheckMatchSimple() { // simple cases: same object, same type different fields, different types assertCheckOkay(FrontendExpectation.checkMatch( CreateProjectImpl.make().setName(NAME), CreateProjectImpl.make().setName(NAME))); assertCheckFails("field name does not match", FrontendExpectation.checkMatch( CreateProjectImpl.make().setName(NAME), CreateProjectImpl.make().setName(OTHER))); assertCheckFails("field _type does not match", FrontendExpectation.checkMatch( CreateProjectImpl.make().setName(NAME), CreateWorkspaceImpl.make().setName(NAME))); } public void testCheckMatchPartial() { // partial pattern matching: ignore the extra project id assertCheckOkay(FrontendExpectation.checkMatch(CreateWorkspaceImpl.make().setName(NAME), CreateWorkspaceImpl.make().setName(NAME).setProjectId(OTHER))); // but not the reverse: assertCheckFails("field projectId does not match", FrontendExpectation.checkMatch(CreateWorkspaceImpl.make().setName(NAME).setProjectId(OTHER), CreateWorkspaceImpl.make().setName(NAME))); } public void testCheckMatchCompound() { // validating deep recursion // Different parents, same children. JsoArray<ComplexDto> parents = JsoArray.create(); ComplexDto parent = ComplexDtoImpl.make().setId(NAME); parents.add(parent); JsoStringMap<SimpleDto> childMap = JsoStringMap.create(); childMap.put("child1", SimpleDtoImpl.make().setName("c1-name").setValue("c1-value")); childMap.put("child2", SimpleDtoImpl.make().setName("c2-name").setValue("c2-value")); parent = ComplexDtoImpl.make().setId(OTHER).setMap(childMap); parents.add(parent); NestedDtoResponseImpl two = MockNestedDtoResponseImpl.make().setArray(parents); // Different parents, different children. parents = JsoArray.create(); childMap = JsoStringMap.create(); parent = ComplexDtoImpl.make().setId(NAME).setMap(childMap); parents.add(parent); childMap = JsoStringMap.create(); childMap.put("child3", SimpleDtoImpl.make().setName("c3-name").setValue("c3-value")); childMap.put("child4", SimpleDtoImpl.make().setName("c4-name").setValue("c4-value")); parent = ComplexDtoImpl.make().setId(OTHER).setMap(childMap); parents.add(parent); NestedDtoResponseImpl twoDifferent = MockNestedDtoResponseImpl.make().setArray(parents); // One parent, no children. parents = JsoArray.create(); childMap = JsoStringMap.create(); parent = ComplexDtoImpl.make().setId(OTHER).setMap(childMap); parents.add(parent); NestedDtoResponseImpl oneOfZero = MockNestedDtoResponseImpl.make().setArray(parents); // One parent, two children. parents = JsoArray.create(); childMap = JsoStringMap.create(); childMap.put("child1", SimpleDtoImpl.make().setName("c1-name").setValue("c1-value")); childMap.put("child2", SimpleDtoImpl.make().setName("c2-name").setValue("c2-value")); parent = ComplexDtoImpl.make().setId(NAME).setMap(childMap); parents.add(parent); NestedDtoResponseImpl oneOfSome = MockNestedDtoResponseImpl.make().setArray(parents); assertCheckOkay(FrontendExpectation.checkMatch(two, two)); assertCheckFails("", FrontendExpectation.checkMatch(oneOfZero, oneOfSome)); assertCheckFails("field child1 is not an object, but undefined, " + "field child2 is not an object, but undefined", FrontendExpectation.checkMatch(oneOfSome, oneOfZero)); assertCheckFails("field child1 is not an object, but undefined, " + "field child2 is not an object, but undefined", FrontendExpectation.checkMatch(two, twoDifferent)); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/MockFrontendApi.java
javatests/com/google/collide/client/testing/MockFrontendApi.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing; import com.google.collide.client.communication.FrontendApi; import com.google.collide.dto.RecoverFromMissedDocOps; import com.google.collide.dto.RecoverFromMissedDocOpsResponse; import com.google.collide.dto.Search; import com.google.collide.dto.SearchResponse; import com.google.collide.dto.ServerError; import com.google.collide.dtogen.shared.ClientToServerDto; import com.google.collide.dtogen.shared.ServerToClientDto; import java.util.LinkedList; import java.util.Queue; /** * A testing mock of our FrontendApi, sporting each API with an expectation * queue instead of actual client/server interaction. * */ public class MockFrontendApi extends FrontendApi { public class MockApi<REQ extends ClientToServerDto, RESP extends ServerToClientDto> extends ApiImpl<REQ, RESP> { protected MockApi() { super("mock"); } Queue<FrontendExpectation<REQ, RESP>> expectations = new LinkedList<FrontendExpectation<REQ, RESP>>(); /** * Throws a {@code RuntimeException} if there are unmet expectations. */ public void assertIsDrained() { if (!expectations.isEmpty()) { throw new Expectation.LeftoverExpectations(expectations.size(), expectations.peek()); } } public void expectAndFailSynchronouslyWithCommunicationError(REQ expect) { expectations.add(new FrontendExpectation.CommunicationFailure<REQ, RESP>(expect)); } public void expectAndFail(REQ expect, ServerError error) { expectations.add(new FrontendExpectation.Fail<REQ, RESP>(expect, error)); } public void expectAndReturn(REQ expect, RESP response) { expectations.add(new FrontendExpectation.Response<REQ, RESP>(expect, response)); } public void expectAndReturnAsync(REQ expect, RESP response) { expectations.add(new FrontendExpectation.AsyncResponse<REQ, RESP>(expect, response)); } public void expectAndThrow(REQ expect, Throwable thrown) { expectations.add(new FrontendExpectation.Throw<REQ, RESP>(expect, thrown)); } /** * Mostly for debugging the test infrastructure, this says how many unmet * expectations are in queue. * * @return integer count */ public int getExpectationCount() { return expectations.size(); } @Override public void send(REQ msg) { FrontendExpectation<REQ, RESP> expects = expectations.remove(); expects.checkExpectation(msg); } @Override public void send(REQ msg, ApiCallback<RESP> callback) { FrontendExpectation<REQ, RESP> expects = expectations.remove(); expects.checkExpectation(msg); expects.doCallback(callback); } } public MockFrontendApi() { super(null, null); } /** * Checks that all the APIs are drained */ public void assertIsDrained() { // TODO: implement? } @Override protected <REQ extends ClientToServerDto, RESP extends ServerToClientDto> MockApi<REQ, RESP> makeApi( String url) { return new MockApi<REQ, RESP>(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/dto/ComplexDto.java
javatests/com/google/collide/client/testing/dto/ComplexDto.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing.dto; import com.google.collide.json.shared.JsonStringMap; /** * DTO used for testing. Contains a map of DTOs. */ public interface ComplexDto { String getId(); JsonStringMap<SimpleDto> getMap(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/dto/NestedDtoResponse.java
javatests/com/google/collide/client/testing/dto/NestedDtoResponse.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing.dto; import com.google.collide.dtogen.shared.RoutingType; import com.google.collide.dtogen.shared.ServerToClientDto; import com.google.collide.json.shared.JsonArray; /** * DTO used for testing. Represents a server to client response containing a * list of DTOs, which themselves contain a map of DTOs. * */ @RoutingType(type = 12346) public interface NestedDtoResponse extends ServerToClientDto { JsonArray<ComplexDto> getArray(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testing/dto/SimpleDto.java
javatests/com/google/collide/client/testing/dto/SimpleDto.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testing.dto; /** * A simple DTO. */ public interface SimpleDto { String getName(); String getValue(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/search/TreeWalkFileNameSearchImplTest.java
javatests/com/google/collide/client/search/TreeWalkFileNameSearchImplTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.search; import com.google.collide.client.util.PathUtil; import collide.client.filetree.FileTreeModel; import collide.client.filetree.FileTreeNode; import com.google.collide.client.workspace.MockOutgoingController; import com.google.collide.dto.DirInfo; import com.google.collide.json.shared.JsonArray; import com.google.common.collect.ImmutableList; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.regexp.shared.RegExp; /** * Tests to ensure the search file indexer returns correct results */ public class TreeWalkFileNameSearchImplTest extends GWTTestCase { @Override public String getModuleName() { return SearchTestUtils.BUILD_MODULE_NAME; } private RegExp regex(String query) { return RegExp.compile(query, "i"); } public void testNoMatches() { FileNameSearch indexer = TreeWalkFileNameSearchImpl.create(); // Setup the file tree model with the simple tree (a list of hello files) FileTreeModel model = getFileTree(buildSimpleTree()); indexer.setFileTreeModel(model); // Verify no matches JsonArray<PathUtil> results = indexer.getMatches(regex("nothello"), 5); assertEquals(0, results.size()); } public void testMaxResults() { FileNameSearch indexer = TreeWalkFileNameSearchImpl.create(); // Setup the file tree model with the simple tree (a list of hello files) FileTreeModel model = getFileTree(buildSimpleTree()); indexer.setFileTreeModel(model); // Verify no matches JsonArray<PathUtil> results = indexer.getMatches(regex("hello"), 2); assertEquals(2, results.size()); results = indexer.getMatches(regex("hello"), 3); assertEquals(3, results.size()); results = indexer.getMatches(regex("hello"), FileNameSearch.RETURN_ALL_RESULTS); assertEquals(4, results.size()); } public void testCorrectMatchesFound() { FileNameSearch indexer = TreeWalkFileNameSearchImpl.create(); // Setup the file tree model with the simple tree (a list of hello files) FileTreeModel model = getFileTree(buildComplexTree()); indexer.setFileTreeModel(model); // Verify correct matches JsonArray<PathUtil> results = indexer.getMatches(regex("world"), 2); assertEquals(2, results.size()); assertContainsPaths(ImmutableList.of("/src/world.js", "/src/world.html"), results); results = indexer.getMatches(regex("data"), 4); assertEquals(1, results.size()); assertEquals("data.txt", results.get(0).getBaseName()); } public void testSameFileNames() { FileNameSearch indexer = TreeWalkFileNameSearchImpl.create(); // Setup the file tree model with the simple tree (a list of hello files) FileTreeModel model = getFileTree(buildComplexTree()); indexer.setFileTreeModel(model); // Verify that two results are returned from two different directories JsonArray<PathUtil> results = indexer.getMatches(regex("hello"), 2); assertEquals(2, results.size()); // Returns the proper two files assertContainsPaths(ImmutableList.of("/hello.js", "/src/hello.html"), results); } public void testFindFilesRelativeToPath() { FileNameSearch indexer = TreeWalkFileNameSearchImpl.create(); // Setup the file tree model with the simple tree (a list of hello files) FileTreeModel model = getFileTree(buildComplexTree()); indexer.setFileTreeModel(model); // Verify that two results are returned from two different directories JsonArray<PathUtil> results = indexer.getMatchesRelativeToPath(new PathUtil("/src"), regex("hello"), 2); assertEquals(1, results.size()); // Returns the proper two files assertContainsPaths(ImmutableList.of("/src/hello.html"), results); } public void testNoCrashWithInvalidModel() { FileNameSearch indexer = TreeWalkFileNameSearchImpl.create(); // Check null filetree indexer.setFileTreeModel(null); JsonArray<PathUtil> results = indexer.getMatches(regex("haha"), 4); assertEquals(0, results.size()); // Crap file tree so we can test no crashing FileTreeModel model = new FileTreeModel(new MockOutgoingController()); indexer.setFileTreeModel(model); results = indexer.getMatches(regex("haha"), 4); assertEquals(0, results.size()); } /** * Verifies that all values in the {@code actual} array are present in the * {@code expected}. Also checks that arrays are the same length */ private void assertContainsPaths(ImmutableList<String> expected, JsonArray<PathUtil> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { if (!expected.contains(actual.get(i).getPathString())) { fail("Actual contains " + actual.get(i).getPathString() + " which is not present in expected"); } } } /** * Creates a file tree model given a directory structure */ private FileTreeModel getFileTree(DirInfo dir) { FileTreeNode root = FileTreeNode.transform(dir); FileTreeModel model = new FileTreeModel(new MockOutgoingController()); model.replaceNode(PathUtil.WORKSPACE_ROOT, root, "1"); return model; } private final native DirInfo buildSimpleTree() /*-{ return { // Root node is magic nodeType : @com.google.collide.dto.TreeNodeInfo::DIR_TYPE, id : "1", originId : "1", name : "root", files : [ { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "5", originId : "5", name : "hello.js", rootId : "2", path : "/hello.js", size : "1234" }, { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "6", originId : "6", name : "hello2.js", rootId : "2", path : "/hello2.js", size : "1234" }, { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "7", originId : "7", name : "hello3.js", rootId : "2", path : "/hello3.js", size : "1234" }, { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "8", originId : "8", name : "hello4.js", rootId : "2", path : "/hello4.js", size : "1234" } ], isComplete : true, subDirectories : [] }; }-*/; public final native DirInfo buildComplexTree() /*-{ return { // Root node is magic nodeType : @com.google.collide.dto.TreeNodeInfo::DIR_TYPE, id : "1", originId : "1", name : "root", files : [ { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "5", originId : "5", name : "hello.js", rootId : "2", path : "/hello.js", size : "1234" } ], isComplete : true, subDirectories : [ { nodeType : @com.google.collide.dto.TreeNodeInfo::DIR_TYPE, id : "2", originId : "2", name : "src", path : "/src", files : [ { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "7", originId : "7", name : "world.js", rootId : "2", path : "/src/world.js", size : "1234" }, { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "3", originId : "3", name : "hello.html", rootId : "2", path : "/src/hello.html", size : "1234" }, { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "8", originId : "8", name : "world.html", rootId : "2", path : "/src/world.html", size : "1234" } ], isComplete : true, subDirectories : [] }, { nodeType : @com.google.collide.dto.TreeNodeInfo::DIR_TYPE, id : "4", originId : "4", name : "res", path : "/res", files : [ { nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE, id : "6", originId : "5", name : "data.txt", rootId : "4", path : "/res/data.txt", size : "1234" } ], isComplete : true, subDirectories : [] } ] }; }-*/; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/search/SearchTestUtils.java
javatests/com/google/collide/client/search/SearchTestUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.search; /** * Shared utility code for search tests. */ public class SearchTestUtils { /** * This is the GWT Module used for these tests. */ public static final String BUILD_MODULE_NAME = "com.google.collide.client.TestCode"; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/search/SearchTest.java
javatests/com/google/collide/client/search/SearchTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.search; import com.google.collide.client.testing.PlaceGwtTestCase; /** * Tests for the search. */ public class SearchTest extends PlaceGwtTestCase { @Override public String getModuleName() { return SearchTestUtils.BUILD_MODULE_NAME; } @Override public void gwtTearDown() throws Exception { super.gwtTearDown(); } public void testGotoSimpleSearch() { // Temporarily breaking local text searching in order to fix dependency // inversion. // TODO: Make this work again and restore test case. /* *SearchImpl searchReq = SearchImpl.make(); searchReq.setWorkspaceId(WS_ID); * searchReq.setQuery("Foo"); searchReq.setPage(1); SearchResponseImpl * searchResp = MockSearchResponseImpl.make(); searchResp.setPage(1); * searchResp.setPageCount(10); searchResp.setResultCount(195); * JsoArray<SearchResult> results = JsoArray.create(); * searchResp.setResults(results); for (int i = 0; i < 20; i++) { * SearchResultImpl item = SearchResultImpl.make(); JsonArray<Snippet> * snippets = JsoArray.create(); final SnippetImpl snippet = * SnippetImpl.make(); switch (i % 3) { case 0: break; // no snippet at all * case 1: snippet.setSnippetText("this is a one-line snippet text"); * snippet.setLineNumber(21); snippets.add(snippet); break; case 2: * snippet.setSnippetText("this is a two-line snippet"); * snippet.setLineNumber(1); snippets.add(snippet); SnippetImpl snippet2 = * SnippetImpl.make(); * snippet2.setSnippetText("text, separated by a single newline."); * snippet2.setLineNumber(17); snippets.add(snippet2); } * item.setSnippets(snippets); item.setTitle("/a/path/file" + i); if (i % 2 * == 0) { item.setUrl("http://somewhere.else.com/item" + i + ".html"); } * results.add(item); } * * * context.getMockFrontendApi().getSearchMockApi().expectAndReturn(searchReq, * searchResp); * * RootPlace.PLACE.dispatchHistory(HistoryUtils.parseHistoryString( * "/h/ws=(wsId=" + WS_ID + ",navEx=true)/code/search=(q=Foo,p=1)")); * * // and check the resulting display state, after a pause to let any dust * settle: this.delayTestFinish(500); Scheduler.get().scheduleDeferred(new * ScheduledCommand() { * * @Override public void execute() { SearchContainer.Css css = * context.getResources().searchContainerCss(); NodeList nodelist = * Browser.getDocument().getElementsByClassName(css.container()); * assertEquals(1, nodelist.getLength()); Element elem = (Element) * nodelist.item(0); // TODO: this is returning "undefined," not a * boolean, which I // think is an elemental bug. // * assertFalse(elem.isHidden()); assertEquals(2, * elem.getChildren().getLength()); assertTrue(((Element) * elem.getLastChild()).getClassName().equals(css.pager())); * * // glance at the results: elem = elem.getChildren().item(0); * HTMLCollection children = elem.getChildren(); assertEquals(20, * elem.getChildNodes().getLength()); * assertFalse(elem.getFirstChildElement() * .getClassName().equals(css.second())); assertTrue(((Element) * elem.getLastChild()).getClassName().equals(css.second())); // Tests case * 0 assertEquals(1, * elem.getFirstChildElement().getChildNodes().getLength()); AnchorElement * anchor = (AnchorElement) * elem.getFirstChildElement().getFirstChildElement(); * assertEquals("http://somewhere.else.com/item0.html", anchor.getHref()); * assertEquals("/a/path/file0", anchor.getTextContent()); // Tests case 1 * assertEquals(2, elem.getChildren().item(1).getChildNodes().getLength()); * anchor = (AnchorElement) * elem.getChildren().item(1).getFirstChildElement(); // Href is untestable. * assertEquals("/a/path/file1", anchor.getTextContent()); * assertEquals("21: this is a one-line snippet text", * elem.getChildren().item(1).getChildNodes().item(1).getTextContent()); // * Tests case 2 assertEquals(3, * elem.getChildren().item(2).getChildNodes().getLength()); anchor = * (AnchorElement) elem.getChildren().item(2).getFirstChildElement(); * assertEquals("http://somewhere.else.com/item2.html", anchor.getHref()); * assertEquals("/a/path/file2", anchor.getTextContent()); * assertEquals("1: this is a two-line snippet", * elem.getChildren().item(2).getChildNodes().item(1).getTextContent()); * assertEquals("17: text, separated by a single newline.", * elem.getChildren().item(2).getChildNodes().item(2).getTextContent()); * * // page 1, no previous: nodelist = * Browser.getDocument().getElementsByClassName(css.previous()); * assertEquals(0, nodelist.getLength()); * * elem = (Element) * Browser.getDocument().getElementsByClassName(css.pager()).item(0); * children = elem.getChildren(); // we seem to get empty elements (Text?) * between the spans, which // explains the even-only numbering until we get * to the end. * assertTrue(children.item(0).getClassName().equals(css.thispage())); * assertEquals("1", children.item(0).getTextContent()); * assertTrue(children.item(2).getClassName().equals(css.otherpage())); * assertEquals("2", children.item(2).getTextContent()); * assertTrue(children.item(4).getClassName().equals(css.otherpage())); * assertEquals("3", children.item(4).getTextContent()); * assertTrue(children.item(6).getClassName().equals(css.otherpage())); * assertEquals("4", children.item(6).getTextContent()); * assertTrue(children.item(8).getClassName().equals(css.otherpage())); * assertEquals("5", children.item(8).getTextContent()); * assertTrue(children.item(10).getClassName().equals(css.otherpage())); * assertEquals("6", children.item(10).getTextContent()); * assertTrue(children.item(11).getClassName().equals(css.thispage())); * assertEquals("...", children.item(11).getTextContent()); * assertTrue(children.item(12).getClassName().equals(css.next())); * assertEquals(13, children.getLength()); * * finishTest(); } }); */ } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/search/awesomebox/ManagedSelectionListTest.java
javatests/com/google/collide/client/search/awesomebox/ManagedSelectionListTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.search.awesomebox; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import junit.framework.TestCase; import elemental.dom.Element; /** * Tests the managed selection list used by AwesomeBox sections. * */ public class ManagedSelectionListTest extends TestCase { private class StubSelectableElement implements ManagedSelectionList.SelectableElement { private boolean isSelected = false; @Override public Element getElement() { // we don't actually have to return a real element for testing return null; } @Override public boolean onSelected() { isSelected = true; return true; } @Override public void onSelectionCleared() { isSelected = false; } public boolean getIsSelected() { return isSelected; } } private JsonArray<StubSelectableElement> createStubs(int size) { JsonArray<StubSelectableElement> elements = JsonCollections.createArray(); for (int i = 0; i < size; i++) { elements.add(new StubSelectableElement()); } return elements; } ManagedSelectionList<StubSelectableElement> elements = new ManagedSelectionList<StubSelectableElement>(); public void testNoSelectionWhenEmpty() { assertFalse(elements.hasSelection()); assertEquals(0, elements.size()); elements.add(new StubSelectableElement()); assertFalse(elements.hasSelection()); elements.asJsonArray().clear(); assertFalse(elements.hasSelection()); } public void testSelectionNextAndPrev() { JsonArray<StubSelectableElement> stubs = createStubs(5); elements.asJsonArray().addAll(stubs); assertFalse(elements.hasSelection()); elements.moveSelection(true); assertTrue(elements.hasSelection()); assertSame(stubs.get(0), elements.getSelectedElement()); assertTrue(stubs.get(0).getIsSelected()); elements.moveSelection(true); elements.moveSelection(true); elements.moveSelection(true); assertTrue(elements.hasSelection()); assertFalse(stubs.get(0).getIsSelected()); assertTrue(stubs.get(3).getIsSelected()); assertSame(stubs.get(3), elements.getSelectedElement()); elements.moveSelection(false); elements.moveSelection(false); elements.moveSelection(false); assertTrue(elements.hasSelection()); assertSame(stubs.get(0), elements.getSelectedElement()); assertTrue(stubs.get(0).getIsSelected()); assertFalse(stubs.get(3).getIsSelected()); } public void testSelectFirstAndLastItem() { JsonArray<StubSelectableElement> stubs = createStubs(5); elements.asJsonArray().addAll(stubs); elements.selectFirst(); assertSame(stubs.get(0), elements.getSelectedElement()); assertTrue(stubs.get(0).getIsSelected()); elements.selectLast(); assertSame(stubs.get(4), elements.getSelectedElement()); assertTrue(stubs.get(4).getIsSelected()); } public void testClearSelection() { JsonArray<StubSelectableElement> stubs = createStubs(5); elements.asJsonArray().addAll(stubs); elements.selectLast(); assertTrue(elements.hasSelection()); elements.clearSelection(); assertFalse(elements.hasSelection()); } public void testSelectIndex() { JsonArray<StubSelectableElement> stubs = createStubs(5); elements.asJsonArray().addAll(stubs); elements.selectIndex(3); assertTrue(elements.hasSelection()); assertSame(stubs.get(3), elements.getSelectedElement()); try { elements.selectIndex(10); fail("Didn't throw exception when index was out of bounds"); } catch (IndexOutOfBoundsException ex) { // pass test } try { elements.selectIndex(-1); fail("Didn't throw exception when index was out of bounds"); } catch (IndexOutOfBoundsException ex) { // pass test } } public void testNoMoveSelectionAtBoundaries() { JsonArray<StubSelectableElement> stubs = createStubs(5); elements.asJsonArray().addAll(stubs); elements.selectLast(); assertFalse(elements.selectNext()); elements.selectFirst(); assertFalse(elements.selectPrevious()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/search/awesomebox/MappedShortcutManagerTest.java
javatests/com/google/collide/client/search/awesomebox/MappedShortcutManagerTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.search.awesomebox; import com.google.collide.client.search.awesomebox.shared.MappedShortcutManager; import com.google.collide.client.search.awesomebox.shared.ShortcutManager; import com.google.collide.client.search.awesomebox.shared.ShortcutManager.ShortcutPressedCallback; import com.google.collide.client.util.input.ModifierKeys; import junit.framework.TestCase; import org.easymock.EasyMock; import elemental.events.KeyboardEvent; import elemental.events.KeyboardEvent.KeyCode; /** * Tests the context shortcut manager to ensure it calls back correctly. */ public class MappedShortcutManagerTest extends TestCase { ShortcutManager shortcutManager; private KeyboardEvent expectKeyboard(int modifiers, int keyCode, int charCode) { KeyboardEvent keyEvent = EasyMock.createMock(KeyboardEvent.class); EasyMock.expect(keyEvent.getKeyCode()).andReturn(keyCode).anyTimes(); EasyMock.expect(keyEvent.getCharCode()).andReturn(charCode).anyTimes(); EasyMock.expect(keyEvent.isAltKey()).andReturn( (modifiers & ModifierKeys.ALT) == ModifierKeys.ALT).anyTimes(); EasyMock.expect(keyEvent.isCtrlKey()).andReturn( (modifiers & ModifierKeys.ACTION) == ModifierKeys.ACTION).anyTimes(); EasyMock.expect(keyEvent.isMetaKey()).andReturn( (modifiers & ModifierKeys.ACTION) == ModifierKeys.ACTION).anyTimes(); EasyMock.expect(keyEvent.isShiftKey()).andReturn( (modifiers & ModifierKeys.SHIFT) == ModifierKeys.SHIFT).anyTimes(); EasyMock.replay(keyEvent); return keyEvent; } @Override public void setUp() { shortcutManager = new MappedShortcutManager(); } public void testShortcutCallbackCalled() { KeyboardEvent firstKey = expectKeyboard(ModifierKeys.ALT, KeyCode.A, 'a'); KeyboardEvent secondKey = expectKeyboard(ModifierKeys.ALT | ModifierKeys.SHIFT, KeyCode.B, 'B'); KeyboardEvent thirdKey = expectKeyboard(ModifierKeys.ALT | ModifierKeys.SHIFT | ModifierKeys.ACTION, KeyCode.B, 'B'); KeyboardEvent fourthKey = expectKeyboard(0, KeyCode.A, 'a'); ShortcutPressedCallback callback = EasyMock.createMock(ShortcutPressedCallback.class); callback.onShortcutPressed(firstKey); callback.onShortcutPressed(secondKey); callback.onShortcutPressed(thirdKey); callback.onShortcutPressed(fourthKey); EasyMock.replay(callback); shortcutManager.addShortcut(ModifierKeys.ALT, KeyCode.A, callback); shortcutManager.addShortcut(ModifierKeys.ALT | ModifierKeys.SHIFT, KeyCode.B, callback); shortcutManager.addShortcut( ModifierKeys.ALT | ModifierKeys.SHIFT | ModifierKeys.ACTION, KeyCode.B, callback); shortcutManager.addShortcut(0, KeyCode.A, callback); shortcutManager.onKeyDown(firstKey); shortcutManager.onKeyDown(secondKey); shortcutManager.onKeyDown(thirdKey); shortcutManager.onKeyDown(fourthKey); shortcutManager.onKeyDown(expectKeyboard(0, KeyCode.E, 'e')); EasyMock.verify(callback); } public void testClearShortcuts() { KeyboardEvent firstKey = expectKeyboard(ModifierKeys.ALT, KeyCode.A, 'a'); ShortcutPressedCallback callback = EasyMock.createMock(ShortcutPressedCallback.class); callback.onShortcutPressed(firstKey); EasyMock.replay(callback); shortcutManager.addShortcut(ModifierKeys.ALT, KeyCode.A, callback); shortcutManager.onKeyDown(firstKey); shortcutManager.clearShortcuts(); shortcutManager.onKeyDown(firstKey); EasyMock.verify(callback); } public void testExistingShortcutAddedCausesLastOneToRun() { KeyboardEvent firstKey = expectKeyboard(ModifierKeys.ALT, KeyCode.A, 'a'); ShortcutPressedCallback callback = EasyMock.createMock(ShortcutPressedCallback.class); EasyMock.replay(callback); ShortcutPressedCallback secondCallback = EasyMock.createMock(ShortcutPressedCallback.class); secondCallback.onShortcutPressed(firstKey); EasyMock.replay(secondCallback); shortcutManager.addShortcut(ModifierKeys.ALT, KeyCode.A, callback); shortcutManager.addShortcut(ModifierKeys.ALT, KeyCode.A, secondCallback); shortcutManager.onKeyDown(firstKey); EasyMock.verify(callback); EasyMock.verify(secondCallback); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/search/awesomebox/StubAwesomeBoxSection.java
javatests/com/google/collide/client/search/awesomebox/StubAwesomeBoxSection.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.search.awesomebox; import elemental.events.MouseEvent; import elemental.html.DivElement; /** * Stub AwesomeBoxSection used for testing. * */ public class StubAwesomeBoxSection implements AwesomeBox.AwesomeBoxSection { private boolean acceptsSelection = false; private boolean hasSelection = false; private int iterationCount = 0; public StubAwesomeBoxSection() { } public StubAwesomeBoxSection(boolean acceptsSelection) { this.acceptsSelection = acceptsSelection; } public boolean getHasSelection() { return hasSelection; } public int getAndResetWasIterated() { int count = iterationCount; iterationCount = 0; return count; } public void wasIterated() { iterationCount++; } @Override public DivElement getElement() { return null; } @Override public void onClearSelection() { } @Override public String onCompleteSelection() { return null; } @Override public void onHiding(AwesomeBox section) { } @Override public boolean onMoveSelection(boolean moveDown) { hasSelection = acceptsSelection; // if we can accept selection, we did. return acceptsSelection; } @Override public boolean onQueryChanged(String query) { return false; } @Override public ActionResult onSectionClicked(MouseEvent mouseEvent) { return null; } @Override public ActionResult onActionRequested() { return ActionResult.DO_NOTHING; } @Override public void onContextChanged(AwesomeBoxContext context) { } @Override public boolean onShowing(AwesomeBox section) { return false; } @Override public void onAddedToContext(AwesomeBoxContext context) { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/search/awesomebox/AwesomeBoxModelAndContextTest.java
javatests/com/google/collide/client/search/awesomebox/AwesomeBoxModelAndContextTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.search.awesomebox; import com.google.collide.client.search.awesomebox.AwesomeBox.AwesomeBoxSection; import com.google.collide.client.search.awesomebox.AwesomeBox.SectionIterationCallback; import com.google.collide.client.search.awesomebox.AwesomeBoxModel.ContextChangeListener; import junit.framework.TestCase; /** * Test the context and model of the AwesomeBox. */ public class AwesomeBoxModelAndContextTest extends TestCase { private AwesomeBoxModel model; private AwesomeBoxContext testContext; private class StubContextChangeListener implements ContextChangeListener { private int calledCount = 0; @Override public void onContextChanged(boolean contextAlreadyActive) { if (!contextAlreadyActive) { calledCount++; } } public int getCalledCount() { return calledCount; } } @Override public void setUp() { model = new AwesomeBoxModel(); testContext = new AwesomeBoxContext(new AwesomeBoxContext.Builder()); } @Override public void tearDown() { AwesomeBoxContext.DEFAULT.clearSections(); } public void testDefaultContextEmpty() { assertEquals(0, AwesomeBoxContext.DEFAULT.size()); } public void testSectionsCanBeAdded() { AwesomeBoxContext.DEFAULT.addSection(new StubAwesomeBoxSection()); AwesomeBoxContext.DEFAULT.addSection(new StubAwesomeBoxSection()); AwesomeBoxContext.DEFAULT.addSection(new StubAwesomeBoxSection()); assertEquals(3, AwesomeBoxContext.DEFAULT.size()); } public void testChangeContextsReturnsRightSections() { StubAwesomeBoxSection defaultSection = new StubAwesomeBoxSection(); StubAwesomeBoxSection testSection1 = new StubAwesomeBoxSection(); StubAwesomeBoxSection testSection2 = new StubAwesomeBoxSection(); AwesomeBoxContext.DEFAULT.addSection(defaultSection); testContext.addSection(testSection1); testContext.addSection(testSection2); assertSame(defaultSection, model.getContext().getSections().get(0)); model.changeContext(testContext); assertSame(testSection1, model.getContext().getSections().get(0)); assertSame(testSection2, model.getContext().getSections().get(1)); } public void testTrySetSelection() { StubAwesomeBoxSection section1 = new StubAwesomeBoxSection(true); StubAwesomeBoxSection section2 = new StubAwesomeBoxSection(false); AwesomeBoxContext.DEFAULT.addSection(section1); AwesomeBoxContext.DEFAULT.addSection(section2); assertTrue(model.trySetSelection(section1, true)); assertFalse(model.trySetSelection(section2, true)); } public void testGetSetSelection() { StubAwesomeBoxSection section1 = new StubAwesomeBoxSection(); StubAwesomeBoxSection section2 = new StubAwesomeBoxSection(false); AwesomeBoxContext.DEFAULT.addSection(section1); AwesomeBoxContext.DEFAULT.addSection(section2); model.setSelection(section1); assertSame(section1, model.getSelection(AwesomeBoxModel.SelectMode.DEFAULT)); } public void testSelectFirstItem() { StubAwesomeBoxSection section1 = new StubAwesomeBoxSection(false); StubAwesomeBoxSection section2 = new StubAwesomeBoxSection(false); StubAwesomeBoxSection section3 = new StubAwesomeBoxSection(true); AwesomeBoxContext.DEFAULT.addSection(section1); AwesomeBoxContext.DEFAULT.addSection(section2); AwesomeBoxContext.DEFAULT.addSection(section3); model.selectFirstItem(); assertSame(section3, model.getSelection(AwesomeBoxModel.SelectMode.DEFAULT)); assertFalse(section1.getHasSelection()); assertFalse(section2.getHasSelection()); assertTrue(section3.getHasSelection()); } public void testIteration() { final StubAwesomeBoxSection section1 = new StubAwesomeBoxSection(false); final StubAwesomeBoxSection section2 = new StubAwesomeBoxSection(false); final StubAwesomeBoxSection section3 = new StubAwesomeBoxSection(true); AwesomeBoxContext.DEFAULT.addSection(section1); AwesomeBoxContext.DEFAULT.addSection(section2); AwesomeBoxContext.DEFAULT.addSection(section3); // backward not quiting iteration model.iterateFrom(section3, false, new SectionIterationCallback() { @Override public boolean onIteration(AwesomeBoxSection section) { StubAwesomeBoxSection stub = (StubAwesomeBoxSection) section; stub.wasIterated(); return true; } }); assertEquals(1, section1.getAndResetWasIterated()); assertEquals(1, section2.getAndResetWasIterated()); assertEquals(0, section3.getAndResetWasIterated()); // forward quiting the iteration model.iterateFrom(section1, true, new SectionIterationCallback() { @Override public boolean onIteration(AwesomeBoxSection section) { StubAwesomeBoxSection stub = (StubAwesomeBoxSection) section; stub.wasIterated(); return false; } }); assertEquals(0, section1.getAndResetWasIterated()); assertEquals(1, section2.getAndResetWasIterated()); assertEquals(0, section3.getAndResetWasIterated()); // forward not-quiting the iteration model.iterateFrom(section1, true, new SectionIterationCallback() { @Override public boolean onIteration(AwesomeBoxSection section) { StubAwesomeBoxSection stub = (StubAwesomeBoxSection) section; stub.wasIterated(); return true; } }); assertEquals(0, section1.getAndResetWasIterated()); assertEquals(1, section2.getAndResetWasIterated()); assertEquals(1, section3.getAndResetWasIterated()); } public void testContextListenerCallback() { StubContextChangeListener listener = new StubContextChangeListener(); model.getContextChangeListener().add(listener); model.changeContext(testContext); model.changeContext(AwesomeBoxContext.DEFAULT); assertEquals(2, listener.getCalledCount()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testutil/CodeMirrorTestCase.java
javatests/com/google/collide/client/testutil/CodeMirrorTestCase.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testutil; import com.google.collide.client.Resources; import com.google.collide.codemirror2.CodeMirror2; import com.google.gwt.core.client.GWT; import elemental.dom.Element; import elemental.js.JsBrowser; import elemental.js.dom.JsDocument; /** * GWT test case that cleans up DOM body before and after test. * */ public abstract class CodeMirrorTestCase extends SynchronousTestCase { private static final String INJECTED_CODE_MIRROR_JS = "injectedCodeMirrorJs"; private static native boolean codeMirrorIsLoaded() /*-{ if ($wnd.CodeMirror) { return true; } return false }-*/; @Override public void gwtSetUp() throws Exception { super.gwtSetUp(); if (!codeMirrorIsLoaded()) { Resources resources = GWT.create(Resources.class); String js = CodeMirror2.getJs(resources); JsDocument jsDocument = JsBrowser.getDocument(); Element scriptElem = jsDocument.createElement("script"); scriptElem.setId(INJECTED_CODE_MIRROR_JS); scriptElem.setAttribute("language", "javascript"); scriptElem.setTextContent(js); jsDocument.getBody().appendChild(scriptElem); } } @Override public void gwtTearDown() throws Exception { JsBrowser.getDocument().getElementById(INJECTED_CODE_MIRROR_JS).removeFromParent(); super.gwtTearDown(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testutil/SynchronousTestCase.java
javatests/com/google/collide/client/testutil/SynchronousTestCase.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testutil; import com.google.gwt.junit.client.GWTTestCase; /** * Test case that disables scheduling during test execution. * * <p>Actually this test case make test execution more safe, by isolating * disallowing distinct cases to put deferred tasks to one queue. * * <p>Use this test case for all tests that do not rely on or test deferred or * scheduled execution (the most common case). * * <p>After case execution scheduling functionality is restored to make other * test cases and JUnit framework work properly. * * <p>If you extend this class and override {@link #gwtSetUp()} and / or * {@link #gwtTearDown()} - make sure you invoke super methods (before / * after other statements correspondingly). * */ public abstract class SynchronousTestCase extends GWTTestCase { @Override protected void gwtSetUp() throws Exception { super.gwtSetUp(); TestSchedulerImpl.setNoOp(true); } @Override protected void gwtTearDown() throws Exception { super.gwtTearDown(); TestSchedulerImpl.setNoOp(false); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/testutil/TestSchedulerImpl.java
javatests/com/google/collide/client/testutil/TestSchedulerImpl.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.testutil; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.impl.SchedulerImpl; /** * Scheduler implementation that allows to disable scheduling at runtime. * */ public class TestSchedulerImpl extends SchedulerImpl { /** * Implementation that ignores scheduled tasks. */ public static class NoOpScheduler extends Scheduler { @Override public void scheduleDeferred(ScheduledCommand scheduledCommand) {} @Override public void scheduleEntry(RepeatingCommand repeatingCommand) {} @Override public void scheduleEntry(ScheduledCommand scheduledCommand) {} @Override public void scheduleFinally(RepeatingCommand repeatingCommand) {} @Override public void scheduleFinally(ScheduledCommand scheduledCommand) {} @Override public void scheduleFixedDelay(RepeatingCommand repeatingCommand, int i) {} @Override public void scheduleFixedPeriod(RepeatingCommand repeatingCommand, int i) {} @Override public void scheduleIncremental(RepeatingCommand repeatingCommand) {} } /** * Implementation that throws exception on its methods invocation. */ public static class AngryScheduler extends Scheduler { @Override public void scheduleDeferred(ScheduledCommand scheduledCommand) { throw new IllegalStateException("No scheduling allowed"); } @Override public void scheduleEntry(RepeatingCommand repeatingCommand) { throw new IllegalStateException("No scheduling allowed"); } @Override public void scheduleEntry(ScheduledCommand scheduledCommand) { throw new IllegalStateException("No scheduling allowed"); } @Override public void scheduleFinally(RepeatingCommand repeatingCommand) { throw new IllegalStateException("No scheduling allowed"); } @Override public void scheduleFinally(ScheduledCommand scheduledCommand) { throw new IllegalStateException("No scheduling allowed"); } @Override public void scheduleFixedDelay(RepeatingCommand repeatingCommand, int i) { throw new IllegalStateException("No scheduling allowed"); } @Override public void scheduleFixedPeriod(RepeatingCommand repeatingCommand, int i) { throw new IllegalStateException("No scheduling allowed"); } @Override public void scheduleIncremental(RepeatingCommand repeatingCommand) { throw new IllegalStateException("No scheduling allowed"); } } public static final Scheduler NO_OP_SCHEDULER_IMPL = new NoOpScheduler(); private static Scheduler scheduler; @Override public void scheduleDeferred(ScheduledCommand cmd) { if (scheduler != null) { scheduler.scheduleDeferred(cmd); } else { super.scheduleDeferred(cmd); } } @Override public void scheduleEntry(RepeatingCommand cmd) { if (scheduler != null) { scheduler.scheduleEntry(cmd); } else { super.scheduleEntry(cmd); } } @Override public void scheduleEntry(ScheduledCommand cmd) { if (scheduler != null) { scheduler.scheduleEntry(cmd); } else { super.scheduleEntry(cmd); } } @Override public void scheduleFinally(RepeatingCommand cmd) { if (scheduler != null) { scheduler.scheduleFinally(cmd); } else { super.scheduleFinally(cmd); } } @Override public void scheduleFinally(ScheduledCommand cmd) { if (scheduler != null) { scheduler.scheduleFinally(cmd); } else { super.scheduleFinally(cmd); } } @Override public void scheduleFixedDelay(RepeatingCommand cmd, int delayMs) { if (scheduler != null) { scheduler.scheduleFixedDelay(cmd, delayMs); } else { super.scheduleFixedDelay(cmd, delayMs); } } @Override public void scheduleFixedPeriod(RepeatingCommand cmd, int delayMs) { if (scheduler != null) { scheduler.scheduleFixedPeriod(cmd, delayMs); } super.scheduleFixedPeriod(cmd, delayMs); } @Override public void scheduleIncremental(RepeatingCommand cmd) { if (scheduler != null) { scheduler.scheduleIncremental(cmd); } else { super.scheduleIncremental(cmd); } } public static void setNoOp(boolean noOp) { if (noOp) { if (scheduler != null) { throw new IllegalStateException("Can enter noOp mode only from standard mode"); } scheduler = NO_OP_SCHEDULER_IMPL; } else { if (scheduler != NO_OP_SCHEDULER_IMPL) { throw new IllegalStateException("Can enter standard mode only from noOp mode"); } scheduler = null; } } public static void runWithSpecificScheduler(Runnable runnable, Scheduler taskScheduler) { if (scheduler != NO_OP_SCHEDULER_IMPL) { throw new IllegalStateException("Can run runWithSpecificScheduler only from noOp mode"); } try { scheduler = taskScheduler; runnable.run(); if (scheduler != taskScheduler) { throw new IllegalStateException("Scheduler has been changed during execution"); } } finally { scheduler = NO_OP_SCHEDULER_IMPL; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/status/StatusManagerTest.java
javatests/com/google/collide/client/status/StatusManagerTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.status; import com.google.collide.client.status.StatusMessage.MessageType; import com.google.collide.json.client.JsoArray; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.junit.client.GWTTestCase; /** * These test cases exercise the event pumping of the {@link StatusManager} to * the {@link StatusHandler}. */ public class StatusManagerTest extends GWTTestCase { /** * A simple mock handler that lets us record events. Each message event is * appended to the statusMesssages array and the number of clear() calls is * tracked. */ private class MockStatusHandler implements StatusHandler { private int clearCount = 0; private JsoArray<StatusMessage> statusMessages = JsoArray.create(); @Override public void clear() { clearCount++; } @Override public void onStatusMessage(StatusMessage msg) { statusMessages.add(msg); } } private StatusMessage c1; private StatusMessage c2; private StatusMessage e1; private StatusMessage e2; private StatusMessage f1; private StatusMessage f2; private MockStatusHandler handler; private StatusMessage l1; private StatusMessage l2; private StatusManager statusManager; @Override public String getModuleName() { return "com.google.collide.client.TestCode"; } @Override protected void gwtSetUp() throws Exception { super.gwtSetUp(); statusManager = new StatusManager(); handler = new MockStatusHandler(); statusManager.setHandler(handler); l1 = new StatusMessage(statusManager, MessageType.LOADING, "l1"); l2 = new StatusMessage(statusManager, MessageType.LOADING, "l2"); c1 = new StatusMessage(statusManager, MessageType.CONFIRMATION, "c1"); c2 = new StatusMessage(statusManager, MessageType.CONFIRMATION, "c2"); e1 = new StatusMessage(statusManager, MessageType.ERROR, "e1"); e2 = new StatusMessage(statusManager, MessageType.ERROR, "e2"); f1 = new StatusMessage(statusManager, MessageType.FATAL, "f1"); f2 = new StatusMessage(statusManager, MessageType.FATAL, "f2"); } /** * Verify that canceling non-active messages triggers no events. */ public void testCancelNonActive() { e1.fire(); l1.fire(); c2.fire(); l2.fire(); l1.cancel(); c1.fire(); c1.cancel(); c2.cancel(); l2.cancel(); assertEquals(1, handler.statusMessages.size()); assertEquals(e1, handler.statusMessages.peek()); assertEquals(0, handler.clearCount); } /** * Verify that an event cannot be fired after being canceled. */ public void testCancelThenFire() { e1.cancel(); e1.fire(); assertEquals(0, handler.statusMessages.size()); } /** * Verify that delayed fire works. */ public void testDelayFire() { l1.fire(); e1.fireDelayed(100); c1.fire(); assertEquals(2, handler.statusMessages.size()); assertEquals(c1, handler.statusMessages.peek()); delayTestFinish(300); Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { @Override public boolean execute() { assertEquals(3, handler.statusMessages.size()); assertEquals(e1, handler.statusMessages.peek()); finishTest(); return false; } }, 200); } /** * Verify that expiry works. */ public void testExpire() { l1.expire(100); l2.fire(); l1.fire(); assertEquals(2, handler.statusMessages.size()); assertEquals(l1, handler.statusMessages.peek()); assertEquals(0, handler.clearCount); delayTestFinish(300); Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { @Override public boolean execute() { assertEquals(3, handler.statusMessages.size()); assertEquals(l2, handler.statusMessages.peek()); finishTest(); return false; } }, 200); } public void testFatalHandoff() { MockStatusHandler handoff = new MockStatusHandler(); f1.fire(); e1.fire(); statusManager.setHandler(handoff); f2.fire(); assertEquals(1, handler.statusMessages.size()); assertEquals(f1, handler.statusMessages.peek()); assertEquals(1, handler.clearCount); assertEquals(1, handoff.statusMessages.size()); assertEquals(f1, handoff.statusMessages.peek()); } public void testFatalIsFinal() { l1.fire(); c1.fire(); f1.fire(); assertEquals(3, handler.statusMessages.size()); assertEquals(f1, handler.statusMessages.peek()); e1.fire(); f1.cancel(); f2.fire(); assertEquals(3, handler.statusMessages.size()); assertEquals(f1, handler.statusMessages.peek()); f1.fire(); assertEquals(3, handler.statusMessages.size()); assertEquals(f1, handler.statusMessages.peek()); } /** * Verify that handing off to a new handler clears the current one and fires * the active message to the new one. */ public void testHandlerHandoff() { MockStatusHandler handoff = new MockStatusHandler(); c1.fire(); l1.fire(); e2.fire(); statusManager.setHandler(handoff); assertEquals(1, handler.clearCount); assertEquals(1, handoff.statusMessages.size()); assertEquals(e2, handoff.statusMessages.peek()); e2.cancel(); assertEquals(2, handoff.statusMessages.size()); assertEquals(c1, handoff.statusMessages.peek()); } /** * Verify our gwtSetup is sane. */ public void testInit() { assertEquals(0, handler.statusMessages.size()); assertEquals(0, handler.clearCount); } /** * Verify that firing a non-active event multiple times is a no-op. */ public void testMultipleFireNoop() { e1.fire(); e2.fire(); assertEquals(2, handler.statusMessages.size()); assertEquals(e2, handler.statusMessages.peek()); e1.fire(); assertEquals(2, handler.statusMessages.size()); assertEquals(e2, handler.statusMessages.peek()); assertEquals(0, handler.clearCount); } /** * Verify that firing an active event multiple times issues updates. */ public void testMultipleFireUpdate() { e1.fire(); e2.fire(); assertEquals(2, handler.statusMessages.size()); assertEquals(e2, handler.statusMessages.peek()); e2.fire(); assertEquals(3, handler.statusMessages.size()); assertEquals(e2, handler.statusMessages.get(2)); assertEquals(e2, handler.statusMessages.get(1)); assertEquals(0, handler.clearCount); } /** * Verify that messages of equivalent priority tie-break by most recent. */ public void testRecentPriority() { e1.fire(); c1.fire(); e2.fire(); assertEquals(2, handler.statusMessages.size()); assertEquals(e2, handler.statusMessages.peek()); } /** * Verify that cancellation works. */ public void testSimpleCancel() { l1.fire(); l1.cancel(); assertEquals(1, handler.statusMessages.size()); assertEquals(l1, handler.statusMessages.peek()); assertEquals(1, handler.clearCount); } /** * Verify that a simple message works. */ public void testSimpleMessage() { l1.fire(); assertEquals(1, handler.statusMessages.size()); assertEquals(l1, handler.statusMessages.peek()); assertEquals(0, handler.clearCount); } /** * Verify that our priority logic is sane. */ public void testSimplePriority() { e1.fire(); c1.fire(); l1.fire(); assertEquals(1, handler.statusMessages.size()); assertEquals(e1, handler.statusMessages.peek()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/document/linedimensions/LineDimensionsCalculatorTests.java
javatests/com/google/collide/client/document/linedimensions/LineDimensionsCalculatorTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.document.linedimensions; import com.google.collide.client.document.linedimensions.LineDimensionsCalculator.RoundingStrategy; import com.google.collide.client.editor.search.SearchTestsUtil; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import junit.framework.TestCase; /** * Tests for {@link LineDimensionsCalculator}. */ public class LineDimensionsCalculatorTests extends TestCase { /** * An object which provides measurement information to a * {@link LineDimensionsCalculator}. */ public static class TestMeasurementProvider implements MeasurementProvider { private final int characterWidth; public TestMeasurementProvider(int characterWidth) { this.characterWidth = characterWidth; } @Override public double getCharacterWidth() { return characterWidth; } @Override public double measureStringWidth(String text) { int length = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); int utype = Character.getType(c); if (utype == Character.COMBINING_SPACING_MARK || utype == Character.NON_SPACING_MARK || utype == Character.ENCLOSING_MARK) { // These characters are 0, width (we do this so its clear) length += 0; } else if (c == '\t') { length += TAB_SIZE; } else if (c == '\r') { length += 0; } else if (c < 255) { length += 1; } else { /* * if its not a combining mark, and its not standard Latin, make it * just like a tab. This is just for testing purposes, and isn't * usually the case. */ length += TAB_SIZE; } } return length * getCharacterWidth(); } } /** Tab size in columns. */ private static final int TAB_SIZE = 2; /** Width of a character in pixels. */ private static final int CHARACTER_SIZE = 8; private LineDimensionsCalculator calculator; private MeasurementProvider measurementProvider; private Document basicDocument; private Document indentAndCarriageReturnDocument; private Document fullUnicodeDocument; @Override public void setUp() { measurementProvider = new TestMeasurementProvider(CHARACTER_SIZE); calculator = LineDimensionsCalculator.createWithCustomProvider(measurementProvider); LineDimensionsUtils.setTabSpaceEquivalence(TAB_SIZE); basicDocument = Document.createFromString(Joiner.on('\n').join(BASIC_NO_SPECIAL_DOCUMENT)); indentAndCarriageReturnDocument = Document.createFromString(Joiner.on('\n').join(TAB_AND_CARRIAGE_RETURN_DOCUMENT)); fullUnicodeDocument = Document.createFromString(Joiner.on('\n').join(FULL_UNICODE_DOCUMENT)); } public void testSettingDocumentDoesNothingToDocument() { calculator.handleDocumentChange(basicDocument); LineInfo lineInfo = basicDocument.getFirstLineInfo(); do { assertTag(null, lineInfo.line()); } while (lineInfo.moveToNext()); } public void testLinesAreLazilyTagged() { calculator.handleDocumentChange(basicDocument); LineInfo lineTwo = SearchTestsUtil.gotoLineInfo(basicDocument, 2); LineInfo lineThree = SearchTestsUtil.gotoLineInfo(basicDocument, 3); calculator.convertColumnToX(lineTwo.line(), 3); calculator.convertColumnToX(lineThree.line(), 3); LineInfo lineInfo = basicDocument.getFirstLineInfo(); do { if (lineInfo.number() == lineTwo.number() || lineInfo.number() == lineThree.number()) { assertTag(false, lineInfo.line()); } else { assertTag(null, lineInfo.line()); } } while (lineInfo.moveToNext()); } public void testCalculatedCorrectlyForSimpleCase() { calculator.handleDocumentChange(basicDocument); LineInfo lineInfo = SearchTestsUtil.gotoLineInfo(basicDocument, 2); double x = assertReversibleAndReturnX(lineInfo.line(), 3); assertEquals(naiveColumnToX(3), x); x = assertReversibleAndReturnX(lineInfo.line(), 0); assertEquals(0.0, x); x = assertReversibleAndReturnX(lineInfo.line(), lineInfo.line().length() - 1); assertEquals(naiveColumnToX(lineInfo.line().length() - 1), x); } public void testIndentationAndCarriageReturnDoesNotAddOffsetCache() { calculator.handleDocumentChange(indentAndCarriageReturnDocument); LineInfo lineInfo = indentAndCarriageReturnDocument.getFirstLineInfo(); do { calculator.convertColumnToX(lineInfo.line(), 3); assertTag(false, lineInfo.line()); } while (lineInfo.moveToNext()); } public void testIndentationHandled() { calculator.handleDocumentChange(indentAndCarriageReturnDocument); LineInfo lineInfo = indentAndCarriageReturnDocument.getFirstLineInfo(); double x = assertReversibleAndReturnX(lineInfo.line(), 0); assertEquals(0.0, x); x = assertReversibleAndReturnX(lineInfo.line(), 1); assertWideChars(1, 1, x); x = assertReversibleAndReturnX(lineInfo.line(), 2); assertWideChars(2, 2, x); x = assertReversibleAndReturnX(lineInfo.line(), 3); assertWideChars(3, 3, x); x = assertReversibleAndReturnX(lineInfo.line(), 4); assertWideChars(4, 3, x); x = assertReversibleAndReturnX(lineInfo.line(), 4); assertWideChars(4, 3, x); int lastColumn = lineInfo.line().length() - 1; x = assertReversibleAndReturnX(lineInfo.line(), lastColumn); assertWideChars(lastColumn, 3, x); } public void testCarriageReturnHandled() { calculator.handleDocumentChange(indentAndCarriageReturnDocument); LineInfo lineInfo = SearchTestsUtil.gotoLineInfo(indentAndCarriageReturnDocument, 1); double x = assertReversibleAndReturnX(lineInfo.line(), 0); assertEquals(0.0, x); x = assertReversibleAndReturnX(lineInfo.line(), 5); assertEquals(naiveColumnToX(5), x); x = assertReversibleAndReturnX(lineInfo.line(), 15); assertEquals(naiveColumnToX(15), x); // Test offset due to carriage return is correct int length = lineInfo.line().length(); x = assertReversibleAndReturnX(lineInfo.line(), length - 3); assertWideCharsAndZeroWidthChars(length - 3, 0, 0, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineInfo.line(), length - 2, 1); assertWideCharsAndZeroWidthChars(length - 2, 0, 0, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineInfo.line(), length - 1, 0); assertWideCharsAndZeroWidthChars(length - 1, 0, 1, x); } public void testBothTabAndCarriageReturn() { calculator.handleDocumentChange(indentAndCarriageReturnDocument); LineInfo lineTwo = SearchTestsUtil.gotoLineInfo(indentAndCarriageReturnDocument, 2); double x = assertReversibleAndReturnX(lineTwo.line(), 1); assertWideChars(1, 1, x); x = assertReversibleAndReturnX(lineTwo.line(), 2); assertWideChars(2, 1, x); x = assertReversibleAndReturnX(lineTwo.line(), 10); assertWideChars(10, 1, x); // Test offset due to carriage return is correct int length = lineTwo.line().length(); x = assertReversibleAndReturnX(lineTwo.line(), length - 3); assertWideCharsAndZeroWidthChars(length - 3, 1, 0, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineTwo.line(), length - 2, 1); assertWideCharsAndZeroWidthChars(length - 2, 1, 0, x); x = assertReversibleAndReturnX(lineTwo.line(), length - 1); assertWideCharsAndZeroWidthChars(length - 1, 1, 1, x); } public void testLineWithAllTabsAndCarriageReturn() { calculator.handleDocumentChange(indentAndCarriageReturnDocument); LineInfo lineThree = SearchTestsUtil.gotoLineInfo(indentAndCarriageReturnDocument, 3); double x = assertReversibleAndReturnX(lineThree.line(), 1); assertWideChars(1, 1, x); x = assertReversibleAndReturnX(lineThree.line(), 2); assertWideChars(2, 2, x); x = assertReversibleAndReturnX(lineThree.line(), 3); assertWideChars(3, 3, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineThree.line(), 4, 1); assertWideChars(4, 4, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineThree.line(), 5, 0); assertWideCharsAndZeroWidthChars(5, 4, 1, x); } public void testLineWithAllTabsAndCarriageReturnWithTabSizeOfThree() { LineDimensionsUtils.setTabSpaceEquivalence(3); testLineWithAllTabsAndCarriageReturn(); testBothTabAndCarriageReturn(); } public void testAssertAllLinesWithSpecialCharsHaveATag() { LineInfo lineInfo = fullUnicodeDocument.getFirstLineInfo(); do { calculator.convertColumnToX(lineInfo.line(), 3); assertTag(true, lineInfo.line()); } while (lineInfo.moveToNext()); } public void testAssertLineOneOfUnicodeDocIsRight() { calculator.handleDocumentChange(fullUnicodeDocument); LineInfo lineOne = fullUnicodeDocument.getFirstLineInfo(); double x = assertReversibleAndReturnX(lineOne.line(), 1); assertWideChars(1, 1, x); x = assertReversibleAndReturnX(lineOne.line(), 7); assertWideChars(7, 1, x); x = assertReversibleAndReturnX(lineOne.line(), 8); assertWideChars(8, 2, x); // Test Carriage Return int length = lineOne.line().length(); x = assertReversibleAndReturnX(lineOne.line(), length - 4); assertWideCharsAndZeroWidthChars(length - 4, 2, 0, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineOne.line(), length - 3, 2); assertWideCharsAndZeroWidthChars(length - 3, 2, 0, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineOne.line(), length - 2, 1); assertWideCharsAndZeroWidthChars(length - 2, 2, 1, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineOne.line(), length - 1, 0); assertWideCharsAndZeroWidthChars(length - 1, 2, 2, x); } public void testAssertLineTwoOfUnicodeDocIsRight() { calculator.handleDocumentChange(fullUnicodeDocument); LineInfo lineTwo = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 1); for (int i = 0; i < lineTwo.line().length(); i++) { double x = assertReversibleAndReturnX(lineTwo.line(), i); assertWideChars(i, i, x); } } public void testAssertLineThreeOfUNicodeDocIsRight() { calculator.handleDocumentChange(fullUnicodeDocument); LineInfo lineThree = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 2); double x = assertReversibleAndReturnX(lineThree.line(), 0); assertEquals(0.0, x); for (int i = 1, j = 2; i < lineThree.line().length() - 2; i += 2, j += 2) { x = assertReversibleAndReturnX(lineThree.line(), i); assertWideChars(i, i - 1, x); x = assertReversibleAndReturnX(lineThree.line(), j); assertWideChars(j, j - 1, x); } // not dealing with \n btw int lastCharIndex = lineThree.line().length() - 1; x = assertReversibleAndReturnX(lineThree.line(), lastCharIndex); /* * so this looks funny so I'll comment it but its just convenient. it's * saying that given lastCharIndex column, it has 2 less widechars then its * column index. This makes sense because if every column before it was a * wide char then we'd have myIndex - 1 wide chars. */ assertWideChars(lastCharIndex, lastCharIndex - 2, x); } public void testAssertLineFourOfUnicodeDocIsRight() { calculator.handleDocumentChange(fullUnicodeDocument); LineInfo lineFour = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 3); double x = assertReversibleAndReturnX(lineFour.line(), 0); assertEquals(0.0, x); // The first character is an a + a ` combining mark x = assertReversibleAndReturnXAccountingForZeroWidth(lineFour.line(), 1, 1); assertWideCharsAndZeroWidthChars(1, 0, 0, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineFour.line(), 2, 0); assertWideCharsAndZeroWidthChars(2, 0, 1, x); // Test remaining characters x = assertReversibleAndReturnX(lineFour.line(), 3); assertWideCharsAndZeroWidthChars(3, 0, 1, x); x = assertReversibleAndReturnX(lineFour.line(), 4); assertWideCharsAndZeroWidthChars(4, 0, 1, x); } public void testAssertLineFiveOfUnicodeDocIsRight() { calculator.handleDocumentChange(fullUnicodeDocument); /* * This line looks like LLccLLccLL * NOTE: These characters all appear double wide since the test measurer * just blatently makes any character > 255 double wide. In realty arabic * characters aren't like that and present other challenges related to size. */ LineInfo lineFive = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 4); double x = assertReversibleAndReturnX(lineFive.line(), 0); assertEquals(0.0, x); x = assertReversibleAndReturnX(lineFive.line(), 1); assertWideCharsAndZeroWidthChars(1, 1, 0, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineFive.line(), 2, 2); assertWideCharsAndZeroWidthChars(2, 2, 0, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineFive.line(), 3, 1); assertWideCharsAndZeroWidthChars(3, 2, 1, x); x = assertReversibleAndReturnX(lineFive.line(), 4); assertWideCharsAndZeroWidthChars(4, 2, 2, x); x = assertReversibleAndReturnX(lineFive.line(), 5); assertWideCharsAndZeroWidthChars(5, 3, 2, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineFive.line(), 6, 2); assertWideCharsAndZeroWidthChars(6, 4, 2, x); x = assertReversibleAndReturnXAccountingForZeroWidth(lineFive.line(), 7, 1); assertWideCharsAndZeroWidthChars(7, 4, 3, x); x = assertReversibleAndReturnX(lineFive.line(), 8); assertWideCharsAndZeroWidthChars(8, 4, 4, x); x = assertReversibleAndReturnX(lineFive.line(), 9); assertWideCharsAndZeroWidthChars(9, 5, 4, x); x = assertReversibleAndReturnX(lineFive.line(), 10); assertWideCharsAndZeroWidthChars(10, 6, 4, x); } public void testAssertLineSixWithMultipleCombiningMarksWorks() { calculator.handleDocumentChange(fullUnicodeDocument); // This string is a````=à LineInfo lineSix = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 5); double x = assertReversibleAndReturnX(lineSix.line(), 0); assertEquals(0.0, x); // a` x = assertReversibleAndReturnXAccountingForZeroWidth(lineSix.line(), 1, 4); assertWideCharsAndZeroWidthChars(1, 0, 0, x); // a`` x = assertReversibleAndReturnXAccountingForZeroWidth(lineSix.line(), 2, 3); assertWideCharsAndZeroWidthChars(2, 0, 1, x); // a``` x = assertReversibleAndReturnXAccountingForZeroWidth(lineSix.line(), 3, 2); assertWideCharsAndZeroWidthChars(3, 0, 2, x); // a```, if you do this I hate you x = assertReversibleAndReturnXAccountingForZeroWidth(lineSix.line(), 4, 1); assertWideCharsAndZeroWidthChars(4, 0, 3, x); // a````= x = assertReversibleAndReturnX(lineSix.line(), 5); assertWideCharsAndZeroWidthChars(5, 0, 4, x); // a````=à x = assertReversibleAndReturnX(lineSix.line(), 6); assertWideCharsAndZeroWidthChars(6, 0, 4, x); } public void testTextMutationsMarkCacheDirtyWithoutCombiningMarks() { calculator.handleDocumentChange(fullUnicodeDocument); // The second line is all katakana characters so no combining marks LineInfo lineTwo = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 1); // we want to build the cache so 'll just ask for a column at the end's x calculator.convertColumnToX(lineTwo.line(), lineTwo.line().length() - 1); // Lets perform a delete and ensure all is still working :) fullUnicodeDocument.deleteText(lineTwo.line(), 5, 1); double x = assertReversibleAndReturnX(lineTwo.line(), 4); assertWideChars(4, 4, x); x = assertReversibleAndReturnX(lineTwo.line(), 5); assertWideChars(5, 5, x); x = assertReversibleAndReturnX(lineTwo.line(), 6); assertWideChars(6, 6, x); // Lets perform a non-special insertion. fullUnicodeDocument.insertText(lineTwo.line(), 5, "alex"); x = assertReversibleAndReturnX(lineTwo.line(), 4); assertWideChars(4, 4, x); x = assertReversibleAndReturnX(lineTwo.line(), 5); assertWideChars(5, 5, x); x = assertReversibleAndReturnX(lineTwo.line(), 6); assertWideChars(6, 5, x); x = assertReversibleAndReturnX(lineTwo.line(), 7); assertWideChars(7, 5, x); } public void testMutationsMakesNewLine() { calculator.handleDocumentChange(fullUnicodeDocument); // The second line is all katakana characters so no combining marks LineInfo lineInfo = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 1); // we want to build the cache so 'll just ask for a column at the end's x calculator.convertColumnToX(lineInfo.line(), lineInfo.line().length() - 1); // Lets perform a non-special insertion. fullUnicodeDocument.insertText(lineInfo.line(), 5, "al\nex"); double x = assertReversibleAndReturnX(lineInfo.line(), 4); assertWideChars(4, 4, x); x = assertReversibleAndReturnX(lineInfo.line(), 5); assertWideChars(5, 5, x); x = assertReversibleAndReturnX(lineInfo.line(), 6); assertWideChars(6, 5, x); x = assertReversibleAndReturnX(lineInfo.line(), 7); assertWideChars(7, 5, x); // Check the new line that was created works right lineInfo.moveToNext(); x = assertReversibleAndReturnX(lineInfo.line(), 1); assertWideChars(1, 0, x); x = assertReversibleAndReturnX(lineInfo.line(), 2); assertWideChars(2, 0, x); x = assertReversibleAndReturnX(lineInfo.line(), 3); assertWideChars(3, 1, x); x = assertReversibleAndReturnX(lineInfo.line(), 4); assertWideChars(4, 2, x); } public void testCorrectWhenMutationsAroundZeroWidthCharacters() { calculator.handleDocumentChange(fullUnicodeDocument); // We use the accented a from line three for these tests LineInfo lineFour = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 3); // we want to build the cache so I'll just ask for a column at the end's x calculator.convertColumnToX(lineFour.line(), lineFour.line().length() - 1); // delete the grave accent combining mark. cache should remove the entry // from a as well. fullUnicodeDocument.deleteText(lineFour.line(), 1, 1); double x = assertReversibleAndReturnX(lineFour.line(), 1); assertWideChars(1, 0, x); // We do some inserting of zero-width grave accents so we can test the // multi-combining mark case (the closest I can get to Arabic craziness). fullUnicodeDocument.insertText(lineFour.line(), 1, "\u0300\u0300\u0300"); // rebuild cache again calculator.convertColumnToX(lineFour.line(), lineFour.line().length() - 1); // delete the last mark fullUnicodeDocument.deleteText(lineFour.line(), 3, 1); // Assert all is well, and we measure correctly x = assertReversibleAndReturnXAccountingForZeroWidth(lineFour.line(), 2, 1); assertWideCharsAndZeroWidthChars(2, 0, 1, x); } public void testConvertingXToColumn() { calculator.handleDocumentChange(fullUnicodeDocument); // All characters in this line are double-wide. LineInfo lineTwo = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 1); // we loop through skipping the \n for (int i = 0; i < lineTwo.line().length() - 1; i++) { assertXToColumn(lineTwo.line(), i, CHARACTER_SIZE * 2 * i, CHARACTER_SIZE * 2 * (i + 1)); } LineInfo lineThree = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 3); assertXToColumn(lineThree.line(), 0, 0, CHARACTER_SIZE); // a // =, we bypass the ` automagically since it can't be clicked on assertXToColumn(lineThree.line(), 2, CHARACTER_SIZE, CHARACTER_SIZE * 2); // à assertXToColumn(lineThree.line(), 3, CHARACTER_SIZE * 2, CHARACTER_SIZE * 3); LineInfo lineFive = SearchTestsUtil.gotoLineInfo(fullUnicodeDocument, 5); assertXToColumn(lineFive.line(), 0, 0, CHARACTER_SIZE); // a // =, skip ```` assertXToColumn(lineFive.line(), 5, CHARACTER_SIZE, CHARACTER_SIZE * 2); } /** * Asserts that a range of x's maps to its corresponding column correctly. */ private void assertXToColumn(Line line, int column, double leftEdgeX, double rightEdgeX) { double characterWidth = rightEdgeX - leftEdgeX; for (double x = leftEdgeX; x < rightEdgeX; x++) { for (RoundingStrategy roundingStrategy : RoundingStrategy.values()) { int expectedColumn = roundingStrategy.apply(column + (x - leftEdgeX) / characterWidth); int resultColumn = calculator.convertXToColumn(line, x, roundingStrategy); assertEquals(expectedColumn, resultColumn); } } } /** * Converts a column to it's x position. Columns are 0-based. */ private double naiveColumnToX(int column) { return measurementProvider.getCharacterWidth() * column; } /** * Converts a column to its x coordinate then converts the x coordinate back * to a column ensuring it matches. * * @return the x coordinate of the column so it can be tested further. */ private double assertReversibleAndReturnX(Line line, int column) { return assertReversibleAndReturnXAccountingForZeroWidth(line, column, 0); } /** * Converts a column to its x coordinate then converts the x coordinate back * to a column ensuring it matches. This method accounts for any zero width * characters so that the assertion when converting x back to column will be * correct. * * @param contiguousZeroWidthChars number of contiguous zero width characters * to the right of the current column (inclusive). * * @return the x coordinate of the column so it can be tested further. */ private double assertReversibleAndReturnXAccountingForZeroWidth( Line line, int column, int contiguousZeroWidthChars) { double x = calculator.convertColumnToX(line, column); assertEquals(column + contiguousZeroWidthChars, calculator.convertXToColumn(line, x, RoundingStrategy.FLOOR)); return x; } /** * @see #assertWideCharsAndZeroWidthChars(int, int, int, double) */ private void assertWideChars(int column, int wideChars, double x) { assertWideCharsAndZeroWidthChars(column, wideChars, 0, x); } /** * @param wideChars Number of tabs * @param zeroWidthCharsToLeft Number of zero-width characters to the left of * the column (exclusive). */ private void assertWideCharsAndZeroWidthChars( int column, int wideChars, int zeroWidthCharsToLeft, double x) { assertEquals(naiveColumnToX(LineDimensionsUtils.getTabWidth() * wideChars) + naiveColumnToX(column - wideChars - zeroWidthCharsToLeft), x); } private static void assertTag(Boolean expected, Line line) { Boolean tag = line.getTag(LineDimensionsUtils.NEEDS_OFFSET_LINE_TAG); assertEquals("Line " + line.getText(), expected, tag); } public static final ImmutableList<String> BASIC_NO_SPECIAL_DOCUMENT = ImmutableList.of("Listen my children, and you shall hear", "Of the midnight ride of Paul Reveare", "On the eighteenth of April in seventy-five", "Hardly a man was now alive", "Who remembers that fateful day and year."); public static final ImmutableList<String> TAB_AND_CARRIAGE_RETURN_DOCUMENT = ImmutableList.of("\t\t\tSome people see a problem and think,", "'I know I'll use regular expressions!'.\r", "\tNow they have two problems\r", // Whoever types in this line is a real sob.... "\t\t\t\t\r", "This line intentionally left blank so previous line gets a \\n w/o me typing it :)"); public static final ImmutableList<String> FULL_UNICODE_DOCUMENT = ImmutableList.of("\tsimple\tline\r\r", // middle tab forces offset cache. "烏烏龍茶烏茶龍龍茶烏龍茶", "8\t♜\t♞\t♝\t♛\t♚\t♝\t♞\t♜8", // first a is a ` combining mark, second is a single char "à=à", // ahhh!!!!! Goes LLccLLccLL "لضَّالِّين", // this is an a + ` x 4 "à̀̀̀=à"); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/document/linedimensions/LineDimensionsUtilsTests.java
javatests/com/google/collide/client/document/linedimensions/LineDimensionsUtilsTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.document.linedimensions; import com.google.collide.client.document.linedimensions.LineDimensionsCalculatorTests.TestMeasurementProvider; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import junit.framework.TestCase; /** * Tests for {@link LineDimensionsUtils}. */ public class LineDimensionsUtilsTests extends TestCase { public void testInsertionSpaceBeforeTab() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 0, " "); assertTrue(LineDimensionsUtils.needsOffset(line)); } public void testInsertionTabBeforeTab() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 0, "\t"); assertFalse(LineDimensionsUtils.needsOffset(line)); } public void testInsertionSpaceAfter() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 1, " "); assertFalse(LineDimensionsUtils.needsOffset(line)); } public void testInsertionTabAfterTab() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 1, "\t"); assertFalse(LineDimensionsUtils.needsOffset(line)); } public void testInsertionSpaceAtTheEndOfLine() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 4, " "); assertFalse(LineDimensionsUtils.needsOffset(line)); } public void testInsertionTabTheEndOfLine() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 4, "\t"); assertTrue(LineDimensionsUtils.needsOffset(line)); } public void testInsertionSimpleMultiline() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 1, "qwe\n\t"); assertFalse(LineDimensionsUtils.needsOffset(line)); assertFalse(LineDimensionsUtils.needsOffset(line.getNextLine())); } public void testInsertionSpecialMultiline() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 1, "一二三\n\t"); assertTrue(LineDimensionsUtils.needsOffset(line)); assertFalse(LineDimensionsUtils.needsOffset(line.getNextLine())); } public void testInsertionSimpleMultilineAtTheBeginningOfLine() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 0, "qwe\n\t"); assertFalse(LineDimensionsUtils.needsOffset(line)); assertFalse(LineDimensionsUtils.needsOffset(line.getNextLine())); } public void testInsertionSpecialMultilineAtTheBeginningOfLine() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 0, "一二三\n\t"); assertTrue(LineDimensionsUtils.needsOffset(line)); assertFalse(LineDimensionsUtils.needsOffset(line.getNextLine())); } public void testInsertionSpecialMultilineAtTheEndOfLine() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 4, "一二三\n\tText"); assertTrue(LineDimensionsUtils.needsOffset(line)); assertFalse(LineDimensionsUtils.needsOffset(line.getNextLine())); } public void testInsertionThatMakesNextLineSpecial() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 1, "一二三\n \t"); assertTrue(LineDimensionsUtils.needsOffset(line)); assertTrue(LineDimensionsUtils.needsOffset(line.getNextLine())); } public void testInsertionOfLineBreakAtTheEndOfLastLine() { Document doc = Document.createFromString("\t123"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 4, "\n"); assertFalse(LineDimensionsUtils.needsOffset(line)); assertFalse(LineDimensionsUtils.needsOffset(line.getNextLine())); } public void testInsertionOfLineBreakAtTheEndOfLine() { Document doc = Document.createFromString("\t123\n456"); LineDimensionsCalculator.createWithCustomProvider(new TestMeasurementProvider(0)) .handleDocumentChange(doc); Line line = doc.getFirstLine(); assertFalse(LineDimensionsUtils.needsOffset(line)); doc.insertText(line, 0, 4, "\n"); assertFalse(LineDimensionsUtils.needsOffset(line)); assertFalse(LineDimensionsUtils.needsOffset(line.getNextLine())); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/ui/popup/CenterPanelTest.java
javatests/com/google/collide/client/ui/popup/CenterPanelTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.ui.popup; import collide.client.util.Elements; import com.google.collide.client.ui.popup.CenterPanel.Resources; import com.google.collide.client.ui.popup.CenterPanel.View; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.user.client.Timer; import elemental.dom.Element; /** * Tests for {@link CenterPanel}. * */ public class CenterPanelTest extends GWTTestCase { /** * The timeout allowed for deferred commands. */ private static final int DEFERRED_COMMAND_TIMEOUT = 2000; @Override public String getModuleName() { return PopupTestUtils.BUILD_MODULE_NAME; } private Element content; private CenterPanel panel; private Resources resources; private String styleGlass; private String styleGlassVisible; private String styleContent; private String styleContentVisible; private View view; public void testCreate() { // The content should be added to the content container. assertEquals(view.contentContainer, content.getParentElement()); // The popup is not showing or attached. assertFalse(panel.isShowing()); assertNull(view.popup.getParentElement()); } public void testHide() { // Show the popup. panel.show(); delayTestFinish(DEFERRED_COMMAND_TIMEOUT); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { assertTrue(panel.isShowing()); // Hide the panel. Styles are removed in this event loop, but the popup // isn't detached until the animation ends. panel.hide(); assertHiding(); } }); } public void testHideThenShow() { // Show the popup. panel.show(); delayTestFinish(DEFERRED_COMMAND_TIMEOUT); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { assertTrue(panel.isShowing()); panel.hide(); panel.show(); assertShowing(); } }); } public void testHideTwice() { // Show the popup. panel.show(); delayTestFinish(DEFERRED_COMMAND_TIMEOUT); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { assertTrue(panel.isShowing()); // Hide the panel. Styles are removed in this event loop, but the popup // isn't detached until the animation ends. panel.hide(); panel.hide(); // No-op. assertHiding(); } }); } public void testShow() { // Initial state is detached and not visible. assertFalse(panel.isShowing()); assertTrue(view.glass.getClassName().contains(styleGlass)); assertFalse(view.glass.getClassName().contains(styleGlassVisible)); assertTrue(view.contentContainer.getClassName().contains(styleContent)); assertFalse(view.contentContainer.getClassName().contains(styleContentVisible)); assertNull(view.popup.getParentElement()); // Show the popup. The popup is attached in this event loop, but styles are // not yet added. panel.show(); assertShowing(); } /** * Tests that the panel can be shown and hidden in the same event loop. */ public void testShowThenHide() { panel.show(); panel.hide(); assertHiding(); } public void testShowTwice() { panel.show(); panel.show(); // No-op. assertShowing(); } @Override protected void gwtSetUp() throws Exception { super.gwtSetUp(); resources = GWT.create(CenterPanel.Resources.class); content = Elements.createDivElement(); content.setInnerHTML("hello world"); panel = CenterPanel.create(resources, content); view = panel.getView(); styleGlass = view.css.glass(); styleGlassVisible = view.css.glassVisible(); styleContent = view.css.content(); styleContentVisible = view.css.contentVisible(); } @Override protected void gwtTearDown() throws Exception { super.gwtTearDown(); // Remove the popup from the DOM. panel.hide(); } /** * Asserts that the panel is transitioning to a hiding state, and eventually * is removed from the DOM. This method should be called after * {@link CenterPanel#hide()} is called. */ private void assertHiding() { // Styles are removed in this event loop, but the popup isn't detached until // the animation ends. assertFalse(panel.isShowing()); assertTrue(view.glass.getClassName().contains(styleGlass)); assertFalse(view.glass.getClassName().contains(styleGlassVisible)); assertTrue(view.contentContainer.getClassName().contains(styleContent)); assertFalse(view.contentContainer.getClassName().contains(styleContentVisible)); assertNotNull(view.popup.getParentElement()); // The panel is removed from the DOM after the animation completes. int animDuration = view.getAnimationDuration(); delayTestFinish(animDuration * 2); // Reset the timeout if already async. new Timer() { @Override public void run() { assertFalse(panel.isShowing()); assertTrue(view.glass.getClassName().contains(styleGlass)); assertFalse(view.glass.getClassName().contains(styleGlassVisible)); assertTrue(view.contentContainer.getClassName().contains(styleContent)); assertFalse(view.contentContainer.getClassName().contains(styleContentVisible)); assertNull(view.popup.getParentElement()); finishTest(); } }.schedule(animDuration + 1); } /** * Asserts that the panel is transitioning to a showing state, and eventually * becomes visible. This method should be called after * {@link CenterPanel#show()} is called. */ private void assertShowing() { // The popup is attached in this event loop, but styles are not yet added. assertTrue(panel.isShowing()); assertTrue(view.glass.getClassName().contains(styleGlass)); assertFalse(view.glass.getClassName().contains(styleGlassVisible)); assertTrue(view.contentContainer.getClassName().contains(styleContent)); assertFalse(view.contentContainer.getClassName().contains(styleContentVisible)); assertNotNull(view.popup.getParentElement()); // The visible styles are added after a deferred command to ensure that the // browser respects the CSS transitions. delayTestFinish(DEFERRED_COMMAND_TIMEOUT); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { assertTrue(panel.isShowing()); assertTrue(view.glass.getClassName().contains(styleGlass)); assertTrue(view.glass.getClassName().contains(styleGlassVisible)); assertTrue(view.contentContainer.getClassName().contains(styleContent)); assertTrue(view.contentContainer.getClassName().contains(styleContentVisible)); assertNotNull(view.popup.getParentElement()); finishTest(); } }); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/ui/popup/PopupTestUtils.java
javatests/com/google/collide/client/ui/popup/PopupTestUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.ui.popup; /** * Utility code for executing popup tests. */ public class PopupTestUtils { /** * This is the GWT Module used for these tests. */ public static final String BUILD_MODULE_NAME = "com.google.collide.client.ui.popup.TestCode"; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/ui/tree/SelectionModelTest.java
javatests/com/google/collide/client/ui/tree/SelectionModelTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.ui.tree; import org.waveprotocol.wave.client.common.util.SignalEvent; import collide.client.filetree.FileTreeNode; import collide.client.filetree.FileTreeNodeDataAdapter; import collide.client.filetree.FileTreeNodeRenderer; import collide.client.treeview.NodeDataAdapter; import collide.client.treeview.NodeRenderer; import collide.client.treeview.SelectionModel; import collide.client.treeview.Tree; import com.google.collide.json.client.JsoArray; import com.google.gwt.core.client.GWT; import com.google.gwt.junit.client.GWTTestCase; /** * Tests the {@link SelectionModel}. */ public class SelectionModelTest extends GWTTestCase { interface TestResources extends Tree.Resources, FileTreeNodeRenderer.Resources { } private static void checkNodeArray( JsoArray<FileTreeNode> expected, JsoArray<FileTreeNode> actual) { assertEquals("Array sizes don't line up!", expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertEquals("expected: " + expected.get(i).getName() + " != " + actual.get(i).getName(), expected.get(i), actual.get(i)); } } private Tree<FileTreeNode> mockTree; private SelectionModel<FileTreeNode> mockSelectionModel; private TestResources resources; @Override public String getModuleName() { return TreeTestUtils.BUILD_MODULE_NAME; } @Override public void gwtTearDown() throws Exception { super.gwtTearDown(); } /** * Tests select responses to ctrl clicks across tiers in the tree. */ public void testCtrlSelectAcrossTiers() { FileTreeNode root = mockTree.getModel().getRoot(); // Render the tree. mockTree.renderTree(-1); SignalEvent ctrlSignalEvent = new MockSignalEvent(true, false); // Select a bunch of nodes at the same tier. FileTreeNode AD1 = getNodeByPath(0); assertNotNull("Node did not get rendered!", AD1.getRenderedTreeNode()); assertFalse(AD1.getRenderedTreeNode().isSelected(resources.treeCss())); JsoArray<FileTreeNode> expectedSelects = JsoArray.create(); // Select the first top level dir. mockSelectionModel.selectNode(AD1, ctrlSignalEvent); expectedSelects.add(AD1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AD1.getRenderedTreeNode().isSelected(resources.treeCss())); // Select the second top level dir FileTreeNode BD1 = getNodeByPath(1); mockSelectionModel.selectNode(BD1, ctrlSignalEvent); expectedSelects.add(BD1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(BD1.getRenderedTreeNode().isSelected(resources.treeCss())); // Select deeper. We should not allow cross depth selecting and should // replace it with just the new select. FileTreeNode AF2 = getNodeByPath(0, 0); assertNotNull("Node did not get rendered!", AF2.getRenderedTreeNode()); assertFalse(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Change the select. mockSelectionModel.selectNode(AF2, ctrlSignalEvent); expectedSelects.clear(); expectedSelects.add(AF2); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(AD1.getRenderedTreeNode().isSelected(resources.treeCss())); // Select another peer node. FileTreeNode CF2 = getNodeByPath(0, 2); assertNotNull("Node did not get rendered!", CF2.getRenderedTreeNode()); assertFalse(CF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Change the select. mockSelectionModel.selectNode(CF2, ctrlSignalEvent); expectedSelects.add(CF2); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertTrue(CF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Select another peer node. FileTreeNode BF2 = getNodeByPath(0, 1); assertNotNull("Node did not get rendered!", BF2.getRenderedTreeNode()); assertFalse(BF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Change the select. mockSelectionModel.selectNode(BF2, ctrlSignalEvent); // We need to enforce sort order. AF2, BF2, CF2. expectedSelects.splice(1, 0, BF2); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertTrue(BF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertTrue(CF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Ensure that if we ctrl click back higher in the stack that we clear the // selected list. FileTreeNode AF1 = getNodeByPath(3); assertNotNull("Node did not get rendered!", AF1.getRenderedTreeNode()); assertFalse(AF1.getRenderedTreeNode().isSelected(resources.treeCss())); // Change the select. mockSelectionModel.selectNode(AF1, ctrlSignalEvent); expectedSelects.clear(); expectedSelects.add(AF1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AF1.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(BF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(CF2.getRenderedTreeNode().isSelected(resources.treeCss())); } /** * Tests select responses to ctrl clicks that should result in select toggling */ public void testCtrlSelectToggle() { FileTreeNode root = mockTree.getModel().getRoot(); // Render the tree. mockTree.renderTree(-1); SignalEvent ctrlSignalEvent = new MockSignalEvent(true, false); // Select a bunch of nodes at the same tier. FileTreeNode AD1 = getNodeByPath(0); assertNotNull("Node did not get rendered!", AD1.getRenderedTreeNode()); assertFalse(AD1.getRenderedTreeNode().isSelected(resources.treeCss())); JsoArray<FileTreeNode> expectedSelects = JsoArray.create(); // Select the first top level dir. mockSelectionModel.selectNode(AD1, ctrlSignalEvent); expectedSelects.add(AD1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AD1.getRenderedTreeNode().isSelected(resources.treeCss())); // Select the second top level dir FileTreeNode BD1 = getNodeByPath(1); mockSelectionModel.selectNode(BD1, ctrlSignalEvent); expectedSelects.add(BD1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(BD1.getRenderedTreeNode().isSelected(resources.treeCss())); // Select the first file. FileTreeNode AF1 = getNodeByPath(3); assertNotNull("Node did not get rendered!", AF1.getRenderedTreeNode()); assertFalse(AF1.getRenderedTreeNode().isSelected(resources.treeCss())); // Change the select. mockSelectionModel.selectNode(AF1, ctrlSignalEvent); expectedSelects.add(AF1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AF1.getRenderedTreeNode().isSelected(resources.treeCss())); // Now toggle the second dir. mockSelectionModel.selectNode(BD1, ctrlSignalEvent); expectedSelects.remove(BD1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertFalse(BD1.getRenderedTreeNode().isSelected(resources.treeCss())); } /** * Tests select responses to shift clicks that should do range selects. */ public void testShiftSelect() { FileTreeNode root = mockTree.getModel().getRoot(); // Render the tree. mockTree.renderTree(-1); SignalEvent shiftSignalEvent = new MockSignalEvent(false, true); FileTreeNode AD1 = getNodeByPath(0); assertNotNull("Node did not get rendered!", AD1.getRenderedTreeNode()); assertFalse(AD1.getRenderedTreeNode().isSelected(resources.treeCss())); JsoArray<FileTreeNode> expectedSelects = JsoArray.create(); // Select the first top level dir. mockSelectionModel.selectNode(AD1, shiftSignalEvent); expectedSelects.add(AD1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AD1.getRenderedTreeNode().isSelected(resources.treeCss())); // Shift select the last top level file. FileTreeNode BF1 = getNodeByPath(4); mockSelectionModel.selectNode(BF1, shiftSignalEvent); expectedSelects.add(getNodeByPath(1)); expectedSelects.add(getNodeByPath(2)); expectedSelects.add(getNodeByPath(3)); expectedSelects.add(getNodeByPath(4)); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(BF1.getRenderedTreeNode().isSelected(resources.treeCss())); assertTrue(getNodeByPath(2).getRenderedTreeNode().isSelected(resources.treeCss())); assertTrue(getNodeByPath(3).getRenderedTreeNode().isSelected(resources.treeCss())); // Select the last file. It should zero the shift selection. mockSelectionModel.selectNode(BF1, shiftSignalEvent); expectedSelects.clear(); expectedSelects.add(BF1); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(BF1.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(getNodeByPath(0).getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(getNodeByPath(1).getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(getNodeByPath(2).getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(getNodeByPath(3).getRenderedTreeNode().isSelected(resources.treeCss())); // Select deeper. We should not allow cross depth selecting and // should replace it with just the new select. FileTreeNode AF2 = getNodeByPath(0, 0); assertNotNull("Node did not get rendered!", AF2.getRenderedTreeNode()); assertFalse(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Change the select. mockSelectionModel.selectNode(AF2, shiftSignalEvent); expectedSelects.clear(); expectedSelects.add(AF2); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(BF1.getRenderedTreeNode().isSelected(resources.treeCss())); // Select the adjacent peer node. FileTreeNode BF2 = getNodeByPath(0, 1); assertNotNull("Node did not get rendered!", BF2.getRenderedTreeNode()); assertFalse(BF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Change the select. mockSelectionModel.selectNode(BF2, shiftSignalEvent); expectedSelects.add(BF2); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertTrue(BF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Select the last peer node. FileTreeNode DF2 = getNodeByPath(0, 3); assertNotNull("Node did not get rendered!", DF2.getRenderedTreeNode()); assertFalse(DF2.getRenderedTreeNode().isSelected(resources.treeCss())); // Change the select. mockSelectionModel.selectNode(DF2, shiftSignalEvent); expectedSelects.add(getNodeByPath(0, 2)); expectedSelects.add(getNodeByPath(0, 3)); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(DF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertTrue(getNodeByPath(0, 2).getRenderedTreeNode().isSelected(resources.treeCss())); // Ensure that if we shift click the last one we clear the selected list. mockSelectionModel.selectNode(DF2, shiftSignalEvent); expectedSelects.clear(); expectedSelects.add(DF2); checkNodeArray(expectedSelects, mockSelectionModel.getSelectedNodes()); assertTrue(DF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(AF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(BF2.getRenderedTreeNode().isSelected(resources.treeCss())); assertFalse(getNodeByPath(0, 2).getRenderedTreeNode().isSelected(resources.treeCss())); } @Override protected void gwtSetUp() throws Exception { super.gwtSetUp(); resources = GWT.create(TestResources.class); NodeDataAdapter<FileTreeNode> dataAdapter = new FileTreeNodeDataAdapter(); NodeRenderer<FileTreeNode> dataRenderer = FileTreeNodeRenderer.create(resources); Tree.Model<FileTreeNode> model = new Tree.Model<FileTreeNode>(dataAdapter, dataRenderer, resources); mockTree = new Tree<FileTreeNode>(new Tree.View<FileTreeNode>(resources), model); mockTree.getModel() .setRoot( FileTreeNode.transform(TreeTestUtils .createMockTree(TreeTestUtils.CLIENT_NODE_INFO_FACTORY))); mockSelectionModel = mockTree.getSelectionModel(); } private FileTreeNode getNodeByPath(int... indices) { FileTreeNode cursor = mockTree.getModel().getRoot(); for (int i = 0; i < indices.length; i++) { cursor = cursor.getUnifiedChildren().get(indices[i]); } return cursor; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/ui/tree/TreeTestUtils.java
javatests/com/google/collide/client/ui/tree/TreeTestUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.ui.tree; import com.google.collide.dto.DirInfo; import com.google.collide.dto.FileInfo; import com.google.collide.dto.TreeNodeInfo; import com.google.collide.dto.client.DtoClientImpls.DirInfoImpl; import com.google.collide.dto.client.DtoClientImpls.FileInfoImpl; import com.google.collide.json.client.JsoArray; import java.util.ArrayList; /** * Shared utility code for tree tests. * */ public class TreeTestUtils { public interface NodeInfoFactory { DirInfo makeDirInfo(); FileInfo makeFileInfo(); } public static final NodeInfoFactory CLIENT_NODE_INFO_FACTORY = new NodeInfoFactory() { @Override public DirInfo makeDirInfo() { return DirInfoImpl.make(); } @Override public FileInfo makeFileInfo() { return FileInfoImpl.make(); } }; public static final NodeInfoFactory SERVER_NODE_INFO_FACTORY = new NodeInfoFactory() { @Override public DirInfo makeDirInfo() { return com.google.collide.dto.server.DtoServerImpls.DirInfoImpl.make(); } @Override public FileInfo makeFileInfo() { return com.google.collide.dto.server.DtoServerImpls.FileInfoImpl.make(); } }; /** * This is the GWT Module used for these tests. */ public static final String BUILD_MODULE_NAME = "com.google.collide.client.TestCode"; /** * Constructs the mock file tree used in each of the tests. */ public static DirInfo createMockTree(NodeInfoFactory nodeInfoFactory) { // Root has 3 directories and 2 files. DirInfo root = makeEmptyDir(nodeInfoFactory, "Root"); // This has only files. This subtree is 1 level deep. DirInfo AD1 = makeEmptyDir(nodeInfoFactory, "AD1"); AD1.getFiles().add(makeFile(nodeInfoFactory, "AF2")); AD1.getFiles().add(makeFile(nodeInfoFactory, "BF2")); AD1.getFiles().add(makeFile(nodeInfoFactory, "CF2")); AD1.getFiles().add(makeFile(nodeInfoFactory, "DF2")); // This has mixed files and empty directories. this subtree is 1 level deep. DirInfo BD1 = makeEmptyDir(nodeInfoFactory, "BD1"); BD1.getSubDirectories().add(makeEmptyDir(nodeInfoFactory, "AD2")); BD1.getSubDirectories().add(makeEmptyDir(nodeInfoFactory, "BD2")); BD1.getFiles().add(makeFile(nodeInfoFactory, "EF2")); BD1.getFiles().add(makeFile(nodeInfoFactory, "FF2")); BD1.getFiles().add(makeFile(nodeInfoFactory, "GF2")); // This has mixed files and directories. The directories then have subfiles. // 2 levels deep. DirInfo CD1 = makeEmptyDir(nodeInfoFactory, "CD1"); CD1.getSubDirectories().add(makeEmptyDir(nodeInfoFactory, "CD2")); CD1.getSubDirectories().add(makeEmptyDir(nodeInfoFactory, "DD2")); CD1.getFiles().add(makeFile(nodeInfoFactory, "HF2")); CD1.getFiles().add(makeFile(nodeInfoFactory, "IF2")); CD1.getFiles().add(makeFile(nodeInfoFactory, "JF2")); // We must go deeper. DirInfo CD2 = CD1.getSubDirectories().get(0); CD2.getSubDirectories().add(makeEmptyDir(nodeInfoFactory, "AD3")); CD2.getSubDirectories().add(makeEmptyDir(nodeInfoFactory, "BD3")); CD2.getFiles().add(makeFile(nodeInfoFactory, "AF3")); CD2.getFiles().add(makeFile(nodeInfoFactory, "BF3")); CD2.getFiles().add(makeFile(nodeInfoFactory, "CF3")); DirInfo DD2 = CD1.getSubDirectories().get(1); DD2.getSubDirectories().add(makeEmptyDir(nodeInfoFactory, "CD3")); DD2.getSubDirectories().add(makeEmptyDir(nodeInfoFactory, "DD3")); DD2.getFiles().add(makeFile(nodeInfoFactory, "DF3")); DD2.getFiles().add(makeFile(nodeInfoFactory, "EF3")); DD2.getFiles().add(makeFile(nodeInfoFactory, "FF3")); // Add them to the root and return it. root.getSubDirectories().add(AD1); root.getSubDirectories().add(BD1); root.getSubDirectories().add(CD1); root.getFiles().add(makeFile(nodeInfoFactory, "AF1")); root.getFiles().add(makeFile(nodeInfoFactory, "BF1")); return root; } private static DirInfo makeEmptyDir(NodeInfoFactory nodeInfoFactory, String name) { DirInfo dirInterface = nodeInfoFactory.makeDirInfo(); if (dirInterface instanceof DirInfoImpl) { DirInfoImpl dir = (DirInfoImpl) dirInterface; dir.setNodeType(TreeNodeInfo.DIR_TYPE); dir.setName(name); dir.setFiles(JsoArray.<FileInfo>create()); dir.setSubDirectories(JsoArray.<DirInfo>create()); dir.setIsComplete(true); } else { com.google.collide.dto.server.DtoServerImpls.DirInfoImpl dir = (com.google.collide.dto.server.DtoServerImpls.DirInfoImpl) dirInterface; dir.setNodeType(TreeNodeInfo.DIR_TYPE); dir.setName(name); dir.setFiles( new ArrayList<com.google.collide.dto.server.DtoServerImpls.FileInfoImpl> ()); dir.setSubDirectories( new ArrayList<com.google.collide.dto.server.DtoServerImpls.DirInfoImpl> ()); dir.setIsComplete(true); } return dirInterface; } private static FileInfo makeFile(NodeInfoFactory nodeInfoFactory, String name) { FileInfo fileInterface = nodeInfoFactory.makeFileInfo(); if (fileInterface instanceof FileInfoImpl) { FileInfoImpl file = (FileInfoImpl) fileInterface; file.setNodeType(TreeNodeInfo.FILE_TYPE); file.setName(name); file.setSize("0"); } else { com.google.collide.dto.server.DtoServerImpls.FileInfoImpl file = (com.google.collide.dto.server.DtoServerImpls.FileInfoImpl) fileInterface; file.setNodeType(TreeNodeInfo.FILE_TYPE); file.setName(name); file.setSize("0"); } return fileInterface; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/ui/tree/MockSignalEvent.java
javatests/com/google/collide/client/ui/tree/MockSignalEvent.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.client.ui.tree; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.Event; import org.waveprotocol.wave.client.common.util.SignalEvent; /** * Simple stub for testing selection model responses to CTRL and SHIFT clicks. * */ class MockSignalEvent implements SignalEvent { private final boolean ctrl; private final boolean shift; MockSignalEvent(boolean ctrl, boolean shift) { this.ctrl = ctrl; this.shift = shift; } @Override public Event asEvent() { return null; } @Override public boolean getAltKey() { return false; } @Override public boolean getCommandKey() { return ctrl; } @Override public boolean getCtrlKey() { return ctrl; } @Override public int getKeyCode() { return 0; } @Override public KeySignalType getKeySignalType() { return null; } @Override public boolean getMetaKey() { return false; } @Override public int getMouseButton() { return 0; } @Override public MoveUnit getMoveUnit() { return null; } @Override public boolean getShiftKey() { return shift; } @Override public Element getTarget() { return null; } @Override public String getType() { return null; } @Override public boolean isClickEvent() { return false; } @Override public boolean isClipboardEvent() { return false; } @Override public boolean isCombo(int letter, KeyModifier modifier) { return false; } @Override public boolean isCompositionEvent() { return false; } @Override public boolean isCopyEvent() { return false; } @Override public boolean isCutEvent() { return false; } @Override public boolean isFocusEvent() { return false; } @Override public boolean isImeKeyEvent() { return false; } @Override public boolean isKeyEvent() { return false; } @Override public boolean isMouseButtonEvent() { return false; } @Override public boolean isMouseButtonlessEvent() { return false; } @Override public boolean isMouseEvent() { return false; } @Override public boolean isMutationEvent() { return false; } @Override public boolean isOnly(int letter) { return false; } @Override public boolean isPasteEvent() { return false; } @Override public boolean isRedoCombo() { return false; } @Override public boolean isUndoCombo() { return false; } @Override public void preventDefault() { } @Override public void stopPropagation() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/RegexpUtilTests.java
javatests/com/google/collide/shared/util/RegexpUtilTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import com.google.gwt.regexp.shared.RegExp; import junit.framework.TestCase; /** * */ public class RegexpUtilTests extends TestCase { /* Tests for createWildcardRegex */ public void testWildcardRegex() { RegExp re = RegExpUtils.createRegExpForWildcardPattern("t?st", "g"); assertEquals("t\\Sst", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("t*t", "g"); assertEquals("t\\S+t", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("t*?*", "g"); assertEquals("t\\S+\\S\\S+", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("t*{?}*", "g"); assertEquals("t\\S+\\{\\S\\}\\S+", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("*", "g"); assertEquals("\\S+", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("?", "g"); assertEquals("\\S", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("\\alex", "g"); assertEquals("\\\\alex", re.getSource()); // lets test all the escape characters (minus ? and *, i.e. .+()[]{}\) re = RegExpUtils.createRegExpForWildcardPattern(".+$^|()[]{}\\", "g"); assertEquals("\\.\\+\\$\\^\\|\\(\\)\\[\\]\\{\\}\\\\", re.getSource()); } public void testEscapedWildcardRegex() { RegExp re = RegExpUtils.createRegExpForWildcardPattern("\\*", "g"); assertEquals("\\*", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("\\?", "g"); assertEquals("\\?", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("\\?\\?\\*\\*\\?", "g"); assertEquals("\\?\\?\\*\\*\\?", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("j\\?uni? t*est\\*", "g"); assertEquals("j\\?uni\\S t\\S+est\\*", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("...\\?", "g"); assertEquals("\\.\\.\\.\\?", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("\\\\*", "g"); assertEquals("\\\\\\S+", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("\\\\?", "g"); assertEquals("\\\\\\S", re.getSource()); re = RegExpUtils.createRegExpForWildcardPattern("\\\\\\*", "g"); assertEquals("\\\\\\*", re.getSource()); } public void testGetNumberMatchesIsCorrect() { RegExp re = RegExp.compile("a","g"); assertEquals(2, RegExpUtils.getNumberOfMatches(re, "aall")); re = RegExp.compile("\\S+", "g"); assertEquals(1, RegExpUtils.getNumberOfMatches(re,"hahahahahaha")); re = RegExp.compile("ha","g"); assertEquals(6, RegExpUtils.getNumberOfMatches(re,"hahahahahaha")); re = RegExp.compile("haha"); assertEquals(1, RegExpUtils.getNumberOfMatches(re, "hahahahaha")); assertEquals(0, RegExpUtils.getNumberOfMatches(re, "asdffdsa")); assertEquals(0, RegExpUtils.getNumberOfMatches(null, "hasdf")); } /** * This test is kind of a shotgun that just tests a bunch of regex to see if * they come out right */ public void testRegexEscape() { assertEquals("a\\.\\.x\\{\\}lu\\[s\\]co", RegExpUtils.escape("a..x{}lu[s]co")); assertEquals("alex", RegExpUtils.escape("alex")); assertEquals("\\*af\\?\\|as\\(df\\|\\)", RegExpUtils.escape("*af?|as(df|)")); assertEquals("\\*af\\?\\|as\\(df\\|\\)", RegExpUtils.escape("*af?|as(df|)")); assertEquals("j\\$oh\\^n", RegExpUtils.escape("j$oh^n")); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/SortedListTests.java
javatests/com/google/collide/shared/util/SortedListTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import junit.framework.TestCase; /** * Tests for the {@link SortedList} class. * */ public class SortedListTests extends TestCase { private static final SortedList.Comparator<String> STRING_SORTING_FUNCTION = new SortedList.Comparator<String>() { @Override public int compare(String a, String b) { return a.compareTo(b); } }; private SortedList<String> sortedList; @Override protected void setUp() throws Exception { sortedList = new SortedList<String>( STRING_SORTING_FUNCTION); } public void testBinarySearchForEmptyArray() { assertEquals(0, sortedList.findInsertionIndex("")); assertEquals(0, sortedList.findInsertionIndex("a1")); assertEquals(-1, sortedList.findIndex("")); assertEquals(-1, sortedList.findIndex("a1")); } public void testBinarySearchForOneElementArray() { addElements("a2"); assertEquals(0, sortedList.findInsertionIndex("a1")); assertEquals(0, sortedList.findInsertionIndex("a2")); assertEquals(1, sortedList.findInsertionIndex("a3")); assertEquals(-1, sortedList.findIndex("a1")); assertEquals(0, sortedList.findIndex("a2")); assertEquals(-1, sortedList.findIndex("a3")); } public void testBinarySearchForEqualElementsArray() { addElements("a1", "a1", "a1", "a1"); assertEquals(0, sortedList.findInsertionIndex("a1")); assertNotSame(-1, sortedList.findIndex("a1")); } public void testBinarySearch() { addElements("a2", "a4", "a6", "a8"); assertEquals(0, sortedList.findInsertionIndex("a1")); assertEquals(1, sortedList.findInsertionIndex("a3")); assertEquals(2, sortedList.findInsertionIndex("a5")); assertEquals(3, sortedList.findInsertionIndex("a7")); assertEquals(4, sortedList.findInsertionIndex("a9")); assertEquals(-1, sortedList.findIndex("a1")); assertEquals(-1, sortedList.findIndex("a3")); assertEquals(-1, sortedList.findIndex("a5")); assertEquals(-1, sortedList.findIndex("a7")); assertEquals(-1, sortedList.findIndex("a9")); assertBinarySelfSearchResults(); } public void testBinarySearchAfterSort() { addElements("b43", "a5", "a4", "a9", "c7", "a8", "x", "z", "y"); assertEquals("a4,a5,a8,a9,b43,c7,x,y,z", joinAllElements()); assertBinarySelfSearchResults(); assertEquals(-1, sortedList.findIndex("a1")); assertEquals(-1, sortedList.findIndex("a7")); assertEquals(-1, sortedList.findIndex("y0")); } private void assertBinarySelfSearchResults() { for (int i = 0, n = sortedList.size(); i < n; ++i) { String s = sortedList.get(i); int index = sortedList.findIndex(s); assertNotSame(-1, index); assertEquals(s, sortedList.get(index)); int insertionIndex = sortedList.findInsertionIndex(s); assertTrue(insertionIndex >= 0); assertEquals(s, sortedList.get(insertionIndex)); } } private void addElements(String... array) { for (String s : array) { sortedList.add(s); } } private String joinAllElements() { String result = ""; for (int i = 0, n = sortedList.size(); i < n; ++i) { if (!result.isEmpty()) { result += ","; } result += sortedList.get(i); } return result; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/WorkspaceUtilsTests.java
javatests/com/google/collide/shared/util/WorkspaceUtilsTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import com.google.collide.dto.WorkspaceInfo; import com.google.collide.dto.server.DtoServerImpls.MockWorkspaceInfoImpl; import com.google.collide.dto.server.DtoServerImpls.WorkspaceInfoImpl; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.WorkspaceUtils.WorkspaceNode; import junit.framework.TestCase; import java.util.Comparator; /** * Tests for {@link WorkspaceUtils}. * */ public class WorkspaceUtilsTests extends TestCase { public void testGetWorkspaceHierarchy() { // Create a list of workspaces. JsonArray<WorkspaceInfo> workspaces = JsonCollections.createArray(); WorkspaceInfo a = makeWorkspace("a", null); WorkspaceInfo b = makeWorkspace("b", null); WorkspaceInfo aa = makeWorkspace("aa", a); WorkspaceInfo ab = makeWorkspace("ab", a); WorkspaceInfo ac = makeWorkspace("ac", a); WorkspaceInfo aaa = makeWorkspace("aaa", aa); WorkspaceInfo aab = makeWorkspace("aab", aa); WorkspaceInfo aac = makeWorkspace("aac", aa); workspaces.add(aa); workspaces.add(ab); workspaces.add(aab); workspaces.add(ac); workspaces.add(aac); workspaces.add(b); workspaces.add(aaa); workspaces.add(a); // Add an element with a parent that is not mapped. WorkspaceInfo zaa = makeWorkspace("zaa", makeWorkspace("unmapped", null)); workspaces.add(zaa); // Create an unsorted hierarchy. JsonArray<WorkspaceNode> roots = WorkspaceUtils.getWorkspaceHierarchy(workspaces, new Comparator<WorkspaceInfo>() { @Override public int compare(WorkspaceInfo o1, WorkspaceInfo o2) { return o1.getId().compareTo(o2.getId()); } }); assertEquals(3, roots.size()); assertEquals(a, roots.get(0).getWorkspace()); assertEquals(b, roots.get(1).getWorkspace()); assertEquals(zaa, roots.get(2).getWorkspace()); // b and daa are empty parents. assertEquals(0, roots.get(1).getChildCount()); assertEquals(0, roots.get(2).getChildCount()); // a contains unsorted children. assertChildrenUnordered(roots.get(0), aa, ab, ac); // aa contains unsorted children. assertChildrenUnordered(roots.get(0).getChild(0), aaa, aab, aac); } /** * Test {@link WorkspaceUtils#getWorkspaceHierarchy} with a map * of root workspaces. */ public void testGetWorkspaceHierarchyAllRoots() { JsonArray<WorkspaceInfo> workspaces = JsonCollections.createArray(); workspaces.add(makeWorkspace("b", null)); workspaces.add(makeWorkspace("a", null)); workspaces.add(makeWorkspace("c", null)); JsonArray<WorkspaceNode> roots = WorkspaceUtils.getWorkspaceHierarchy(workspaces); assertEquals(3, roots.size()); for (int i = 0; i < 3; i++) { assertEquals(0, roots.get(i).getChildCount()); } // Due to the nature of maps, the nodes are not in a specified order. } /** * Test {@link WorkspaceUtils#getWorkspaceHierarchy} if one of * the workspaces refers to a parent that is not mapped. */ public void testGetWorkspaceHierarchyNonExistentParent() { JsonArray<WorkspaceInfo> workspaces = JsonCollections.createArray(); WorkspaceInfo unmapped = makeWorkspace("unmapped", null); workspaces.add(makeWorkspace("b", unmapped)); workspaces.add(makeWorkspace("a", null)); workspaces.add(makeWorkspace("c", null)); JsonArray<WorkspaceNode> roots = WorkspaceUtils.getWorkspaceHierarchy(workspaces); assertEquals(3, roots.size()); for (int i = 0; i < 3; i++) { assertEquals(0, roots.get(i).getChildCount()); } // Due to the nature of maps, the nodes are not in a specified order. } public void testGetWorkspaceHierarchySorted() { // Create a list of workspaces. JsonArray<WorkspaceInfo> workspaces = JsonCollections.createArray(); WorkspaceInfo a = makeWorkspace("a", null); WorkspaceInfo b = makeWorkspace("b", null); WorkspaceInfo aa = makeWorkspace("aa", a); WorkspaceInfo ab = makeWorkspace("ab", a); WorkspaceInfo ac = makeWorkspace("ac", a); WorkspaceInfo aaa = makeWorkspace("aaa", aa); WorkspaceInfo aab = makeWorkspace("aab", aa); WorkspaceInfo aac = makeWorkspace("aac", aa); workspaces.add(aa); workspaces.add(ab); workspaces.add(aab); workspaces.add(ac); workspaces.add(aac); workspaces.add(b); workspaces.add(aaa); workspaces.add(a); // Add an element with a parent that is not mapped. WorkspaceInfo zaa = makeWorkspace("zaa", makeWorkspace("unmapped", null)); workspaces.add(zaa); // Create a sorted hierarchy. JsonArray<WorkspaceNode> roots = WorkspaceUtils.getWorkspaceHierarchy(workspaces, new Comparator<WorkspaceInfo>() { @Override public int compare(WorkspaceInfo o1, WorkspaceInfo o2) { return o1.getId().compareTo(o2.getId()); } }); assertEquals(3, roots.size()); assertEquals(a, roots.get(0).getWorkspace()); assertEquals(b, roots.get(1).getWorkspace()); assertEquals(zaa, roots.get(2).getWorkspace()); // b and daa are empty parents. assertEquals(0, roots.get(1).getChildCount()); assertEquals(0, roots.get(2).getChildCount()); // a contains sorted children. assertChildren(roots.get(0), aa, ab, ac); // aa contains sorted children. assertChildren(roots.get(0).getChild(0), aaa, aab, aac); } /** * Test that * {@link WorkspaceUtils#getWorkspaceHierarchy} * sorts the root nodes. */ public void testGetWorkspaceHierarchySortedRoots() { // Create a list of workspaces. JsonArray<WorkspaceInfo> workspaces = JsonCollections.createArray(); WorkspaceInfo a = makeWorkspace("a", null); WorkspaceInfo b = makeWorkspace("b", null); WorkspaceInfo c = makeWorkspace("c", null); workspaces.add(b); workspaces.add(a); workspaces.add(c); // Create a sorted hierarchy. JsonArray<WorkspaceNode> roots = WorkspaceUtils.getWorkspaceHierarchy(workspaces, new Comparator<WorkspaceInfo>() { @Override public int compare(WorkspaceInfo o1, WorkspaceInfo o2) { return o1.getId().compareTo(o2.getId()); } }); assertEquals(3, roots.size()); assertEquals(a, roots.get(0).getWorkspace()); assertEquals(b, roots.get(1).getWorkspace()); assertEquals(c, roots.get(2).getWorkspace()); } public void testWorkspaceNodeAddChild() { WorkspaceNode parentNode = makeWorkspaceNode("parent", null); assertEquals(0, parentNode.getChildCount()); WorkspaceInfo child0 = makeWorkspace("child0", parentNode.getWorkspace()); WorkspaceNode childNode0 = new WorkspaceNode(child0); parentNode.addChild(childNode0); assertEquals(1, parentNode.getChildCount()); assertEquals(childNode0, parentNode.getChild(0)); WorkspaceInfo child1 = makeWorkspace("child1", parentNode.getWorkspace()); WorkspaceNode childNode1 = new WorkspaceNode(child1); parentNode.addChild(childNode1); assertEquals(2, parentNode.getChildCount()); assertEquals(childNode0, parentNode.getChild(0)); assertEquals(childNode1, parentNode.getChild(1)); } public void testWorkspaceNodeSortChildren() { // Create a hierarchy. WorkspaceNode a = makeWorkspaceNode("a", null); WorkspaceNode ab = makeWorkspaceNode("ab", a); WorkspaceNode aa = makeWorkspaceNode("aa", a); WorkspaceNode ac = makeWorkspaceNode("ac", a); WorkspaceNode aaa = makeWorkspaceNode("aaa", aa); WorkspaceNode aac = makeWorkspaceNode("aac", aa); WorkspaceNode aab = makeWorkspaceNode("aab", aa); // Sort non-recursively. a.sortChildren(new Comparator<WorkspaceNode>() { @Override public int compare(WorkspaceNode o1, WorkspaceNode o2) { return o1.getWorkspace().getId().compareTo(o2.getWorkspace().getId()); } }); // Assert the children sorted. assertEquals(aa, a.getChild(0)); assertEquals(ab, a.getChild(1)); assertEquals(ac, a.getChild(2)); // Assert the grandchildren are NOT sorted. assertEquals(aaa, aa.getChild(0)); assertEquals(aac, aa.getChild(1)); assertEquals(aab, aa.getChild(2)); } public void testWorkspaceNodeSortChildrenRecursive() { // Create a hierarchy. WorkspaceNode a = makeWorkspaceNode("a", null); WorkspaceNode ab = makeWorkspaceNode("ab", a); WorkspaceNode aa = makeWorkspaceNode("aa", a); WorkspaceNode ac = makeWorkspaceNode("ac", a); WorkspaceNode aaa = makeWorkspaceNode("aaa", aa); WorkspaceNode aac = makeWorkspaceNode("aac", aa); WorkspaceNode aab = makeWorkspaceNode("aab", aa); // Sort non-recursively. a.sortChildren(new Comparator<WorkspaceNode>() { @Override public int compare(WorkspaceNode o1, WorkspaceNode o2) { return o1.getWorkspace().getId().compareTo(o2.getWorkspace().getId()); } }, true); // Assert the children sorted. assertEquals(aa, a.getChild(0)); assertEquals(ab, a.getChild(1)); assertEquals(ac, a.getChild(2)); // Assert the grandchildren are also sorted. assertEquals(aaa, aa.getChild(0)); assertEquals(aab, aa.getChild(1)); assertEquals(aac, aa.getChild(2)); } /** * Assert that a {@link WorkspaceNode} contains exactly the expected children * workspaces, in order. * * @param node the node to check * @param expected the expected values, in order */ private void assertChildren(WorkspaceNode node, WorkspaceInfo... expected) { // Check the size. int size = expected.length; assertEquals("Size mismatch", size, node.getChildCount()); // Check the values. for (int i = 0; i < size; i++) { assertEquals(expected[i], node.getChild(i).getWorkspace()); } } /** * Assert that a {@link WorkspaceNode} contains exactly the expected children * workspaces, in any order. Does not handle duplicate expected values. * * @param node the node to check * @param expected the expected values, in order */ private void assertChildrenUnordered(WorkspaceNode node, WorkspaceInfo... expected) { // Check the size. int size = expected.length; assertEquals("Size mismatch", size, node.getChildCount()); // Check the values. for (int i = 0; i < size; i++) { WorkspaceInfo toFind = expected[i]; boolean found = false; for (int j = 0; j < size; j++) { if (node.getChild(i).getWorkspace() == toFind) { found = true; break; } } if (!found) { fail("Node does not contain expected value " + expected); } } } private WorkspaceInfo makeWorkspace(String id, WorkspaceInfo parent) { WorkspaceInfoImpl ws = MockWorkspaceInfoImpl.make(); ws.setId(id); if (parent != null) { ws.setParentId(parent.getId()); } return ws; } private WorkspaceNode makeWorkspaceNode(String id, WorkspaceNode parent) { WorkspaceInfo parentWs = (parent == null) ? null : parent.getWorkspace(); WorkspaceInfo ws = makeWorkspace(id, parentWs); WorkspaceNode node = new WorkspaceNode(ws); if (parent != null) { parent.addChild(node); } return node; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/StringUtilsTest.java
javatests/com/google/collide/shared/util/StringUtilsTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import junit.framework.TestCase; /** * Test cases for {@link StringUtils}. */ public class StringUtilsTest extends TestCase { public void testStartsWith() { // Case (mis)match. assertTrue(StringUtils.startsWith("bar", "Barbeque", true)); assertTrue(StringUtils.startsWith("bar", "barbeque", true)); assertFalse(StringUtils.startsWith("bar", "Barbeque", false)); assertTrue(StringUtils.startsWith("bar", "barbeque", false)); // Prefix mismatch. assertFalse(StringUtils.startsWith("bad", "barbeque", true)); assertFalse(StringUtils.startsWith("bad", "barbeque", false)); // Empty prefix. assertTrue(StringUtils.startsWith("", "barbeque", true)); assertTrue(StringUtils.startsWith("", "barbeque", false)); // Empty content. assertFalse(StringUtils.startsWith("bar", "", true)); assertFalse(StringUtils.startsWith("bar", "", false)); // Short content. assertFalse(StringUtils.startsWith("bar", "b", true)); assertFalse(StringUtils.startsWith("bar", "b", false)); // Empty prefix, empty content. assertTrue(StringUtils.startsWith("", "", true)); assertTrue(StringUtils.startsWith("", "", false)); } public void testSplit() { assertEquals("a|b|c", StringUtils.split("abc", "").join("|")); assertEquals("a|b|c", StringUtils.split("a b c", " ").join("|")); assertEquals("a|b|c", StringUtils.split("a, b, c", ", ").join("|")); assertEquals("a, b, c", StringUtils.split("a, b, c", " ,").join("|")); assertEquals("|a||b|", StringUtils.split(".a..b.", ".").join("|")); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/MockTimer.java
javatests/com/google/collide/shared/util/MockTimer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import com.google.collide.json.shared.JsonArray; /** * A timer implementation that allows for the client to trigger the callback. */ public class MockTimer implements Timer { public static class Factory implements Timer.Factory { private final JsonArray<MockTimer> timers = JsonCollections.createArray(); @Override public Timer createTimer(Runnable runnable) { MockTimer timer = new MockTimer(runnable); timers.add(timer); return timer; } public void tickTime(int timeMs) { for (int i = 0; i < timers.size(); i++) { timers.get(i).tickTime(timeMs); } } public void tickToFireAllTimers() { tickTime(Integer.MAX_VALUE); } } private static final int NOT_SCHEDULED = -1; private final Runnable runnable; private int remainingDelayMs = NOT_SCHEDULED; public MockTimer(Runnable runnable) { this.runnable = runnable; } @Override public void schedule(int delayMs) { remainingDelayMs = delayMs; } private void tickTime(int timeMs) { if (remainingDelayMs >= 0) { remainingDelayMs -= timeMs; if (remainingDelayMs <= 0) { runnable.run(); remainingDelayMs = NOT_SCHEDULED; } } } @Override public void cancel() { remainingDelayMs = NOT_SCHEDULED; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/PathUtilsTest.java
javatests/com/google/collide/shared/util/PathUtilsTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import com.google.collide.shared.util.PathUtils.PathVisitor; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; /** * Tests for {@link PathUtils}. * */ public class PathUtilsTest extends TestCase { /** * A mock path visitor that remembers the path that was walked. */ private static class MockPathVisitor implements PathVisitor { private final List<String> visitedPaths = new ArrayList<String>(); private final List<String> visitedNames = new ArrayList<String>(); public void assertVisitedPaths(String... expected) { List<String> expectedList = Lists.newArrayList(expected); assertEquals(expectedList, visitedPaths); } public void assertVisitedNames(String... expected) { List<String> expectedList = Lists.newArrayList(expected); assertEquals(expectedList, visitedNames); } @Override public void visit(String path, String name) { visitedPaths.add(path); visitedNames.add(name); } } public void testWalk_rootOnly() { MockPathVisitor visitor = walkPath("/", "/"); visitor.assertVisitedPaths("/"); visitor.assertVisitedNames(""); } public void testWalk_rootToSubDirectory() { MockPathVisitor visitor = walkPath("/a/b/c", "/"); visitor.assertVisitedPaths("/", "/a", "/a/b", "/a/b/c"); visitor.assertVisitedNames("", "a", "b", "c"); } public void testWalk_directoryOnly() { MockPathVisitor visitor = walkPath("/a/b", "/a/b"); visitor.assertVisitedPaths("/a/b"); visitor.assertVisitedNames("b"); } public void testWalk_directoryToSubDirectory() { MockPathVisitor visitor = walkPath("/a/b/c/d", "/a/b"); visitor.assertVisitedPaths("/a/b", "/a/b/c", "/a/b/c/d"); visitor.assertVisitedNames("b", "c", "d"); } public void testWalk_pathEndsWithSlash() { MockPathVisitor visitor = walkPath("/a/b/", "/"); visitor.assertVisitedPaths("/", "/a", "/a/b"); visitor.assertVisitedNames("", "a", "b"); } public void testWalk_rootEndsWithSlash() { MockPathVisitor visitor = walkPath("/a/b/c", "/a/"); visitor.assertVisitedPaths("/a", "/a/b", "/a/b/c"); visitor.assertVisitedNames("a", "b", "c"); } public void testWalk_rootIsNotParent() { try { walkPath("/a/b/", "/notaparent"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected. } } /** * Walks the path from rootPath to path and returns the {@link MockPathVisitor} that visited each * path along the way. */ private MockPathVisitor walkPath(String path, String rootPath) { MockPathVisitor visitor = new MockPathVisitor(); PathUtils.walk(path, rootPath, visitor); return visitor; } public void testNormalizePath() { assertEquals("/", PathUtils.normalizePath("/")); assertEquals("/child", PathUtils.normalizePath("/child")); assertEquals("/trailing/slash", PathUtils.normalizePath("/trailing/slash/")); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/ListenerManagerTests.java
javatests/com/google/collide/shared/util/ListenerManagerTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import com.google.collide.shared.util.ListenerRegistrar.Remover; import junit.framework.TestCase; /** * Basic tests for listener manager. */ public class ListenerManagerTests extends TestCase { public class TestCallback { public int count; public void dispatch() { count += 1; } } public class Dispatcher implements ListenerManager.Dispatcher<TestCallback> { @Override public void dispatch(TestCallback listener) { listener.dispatch(); } } private ListenerManager<TestCallback> listenerManager; @Override public void setUp() { listenerManager = ListenerManager.create(); } public void testCallbackCalled() { TestCallback callback = new TestCallback(); listenerManager.add(callback); // duplicate add should be prevented listenerManager.add(callback); listenerManager.dispatch(new Dispatcher()); assertEquals(1, callback.count); listenerManager.remove(callback); listenerManager.dispatch(new Dispatcher()); // shouldn't be called agains ince it was removed assertEquals(1, callback.count); } public void testMultipleCallbacksCalled() { TestCallback callback1 = new TestCallback(); TestCallback callback2 = new TestCallback(); listenerManager.add(callback1); listenerManager.add(callback2); listenerManager.dispatch(new Dispatcher()); assertEquals(1, callback1.count); assertEquals(1, callback2.count); } public void testAddsQueuedDuringDispatch() { final TestCallback toAdd = new TestCallback(); TestCallback callback = new TestCallback() { @Override public void dispatch() { super.dispatch(); listenerManager.add(toAdd); } }; listenerManager.add(callback); listenerManager.dispatch(new Dispatcher()); assertEquals(0, toAdd.count); assertEquals(1, callback.count); listenerManager.dispatch(new Dispatcher()); assertEquals(1, toAdd.count); assertEquals(2, callback.count); } public void testRemovesQueuedDuringDispatch() { final TestCallback toRemove = new TestCallback(); TestCallback callback = new TestCallback() { @Override public void dispatch() { super.dispatch(); listenerManager.remove(toRemove); } }; listenerManager.add(callback); listenerManager.add(toRemove); listenerManager.dispatch(new Dispatcher()); assertEquals(1, toRemove.count); assertEquals(1, callback.count); listenerManager.dispatch(new Dispatcher()); assertEquals(1, toRemove.count); assertEquals(2, callback.count); } public void testRemover() { final TestCallback callback = new TestCallback(); Remover remover = listenerManager.add(callback); listenerManager.dispatch(new Dispatcher()); remover.remove(); listenerManager.dispatch(new Dispatcher()); assertEquals(1, callback.count); } public void testRemoverManager() { final ListenerRegistrar.RemoverManager manager = new ListenerRegistrar.RemoverManager(); final TestCallback callback1 = new TestCallback(); final TestCallback callback2 = new TestCallback(); final TestCallback callback3 = new TestCallback(); manager.track(listenerManager.add(callback1)); manager.track(listenerManager.add(callback2)); manager.track(listenerManager.add(callback3)); manager.remove(); listenerManager.dispatch(new Dispatcher()); assertEquals(0, callback1.count); assertEquals(0, callback2.count); assertEquals(0, callback3.count); } public void testRemoverManagerDoesNotFailWhenNoRemovers() { final ListenerRegistrar.RemoverManager manager = new ListenerRegistrar.RemoverManager(); manager.remove(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/TextUtilsTest.java
javatests/com/google/collide/shared/util/TextUtilsTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import junit.framework.TestCase; /** * Unit Tests for TextUtility functions. */ public class TextUtilsTest extends TestCase { public void testFindNextCharacterInclusive() { String text = "à\n"; assertEquals(0, TextUtils.findNextCharacterInclusive(text, 0)); assertEquals(2, TextUtils.findNextCharacterInclusive(text, 1)); assertEquals(2, TextUtils.findNextCharacterInclusive(text, 2)); assertEquals(1, TextUtils.findNextCharacterInclusive(text.substring(0, 1), 1)); } public void testBasicTextFindCharacter() { String text = "alex"; assertEquals(1, TextUtils.findNonMarkNorOtherCharacter(text, 0)); assertEquals(2, TextUtils.findNonMarkNorOtherCharacter(text, 1)); assertEquals(3, TextUtils.findNonMarkNorOtherCharacter(text, 2)); assertEquals(5, TextUtils.findNonMarkNorOtherCharacter(text, 3)); assertEquals(3, TextUtils.findPreviousNonMarkNorOtherCharacter(text, 4)); assertEquals(2, TextUtils.findPreviousNonMarkNorOtherCharacter(text, 3)); assertEquals(1, TextUtils.findPreviousNonMarkNorOtherCharacter(text, 2)); assertEquals(0, TextUtils.findPreviousNonMarkNorOtherCharacter(text, 1)); assertEquals(-1, TextUtils.findPreviousNonMarkNorOtherCharacter(text, 0)); } public void testCombiningMarkFindCharacter() { // Note: First a is a a + ` combining mark String text = "\tà=à\r\n"; assertEquals(1, TextUtils.findNonMarkNorOtherCharacter(text, 0)); // skip over combining mark assertEquals(3, TextUtils.findNonMarkNorOtherCharacter(text, 1)); // skip over \r assertEquals(6, TextUtils.findNonMarkNorOtherCharacter(text, 4)); assertEquals(8, TextUtils.findNonMarkNorOtherCharacter(text, 6)); // skip over \r assertEquals(4, TextUtils.findPreviousNonMarkNorOtherCharacter(text, 6)); // go from = to before a assertEquals(1, TextUtils.findPreviousNonMarkNorOtherCharacter(text, 3)); } public void testControlCharactersFindCharacter() { String text = "\t\t\t\r\n"; assertEquals(1, TextUtils.findNonMarkNorOtherCharacter(text, 0)); assertEquals(2, TextUtils.findNonMarkNorOtherCharacter(text, 1)); // skip over \r assertEquals(4, TextUtils.findNonMarkNorOtherCharacter(text, 2)); assertEquals(6, TextUtils.findNonMarkNorOtherCharacter(text, 4)); } public void testBasicTextFindNextWord() { String text = "alex lusco was here"; assertEquals(5, TextUtils.findNextWord(text, 0, true)); assertEquals(11, TextUtils.findNextWord(text, 5, true)); assertEquals(15, TextUtils.findNextWord(text, 11, true)); assertEquals(19, TextUtils.findNextWord(text, 15, true)); assertEquals(20, TextUtils.findNextWord(text, 19, true)); assertEquals(4, TextUtils.findNextWord(text, 0, false)); assertEquals(10, TextUtils.findNextWord(text, 4, false)); assertEquals(14, TextUtils.findNextWord(text, 10, false)); assertEquals(19, TextUtils.findNextWord(text, 14, false)); assertEquals(20, TextUtils.findNextWord(text, 19, false)); } public void testBasicTextFindPreviousWord() { String text = "alex lusco was here"; assertEquals(14, TextUtils.findPreviousWord(text, 19, true)); assertEquals(10, TextUtils.findPreviousWord(text, 14, true)); assertEquals(4, TextUtils.findPreviousWord(text, 10, true)); assertEquals(0, TextUtils.findPreviousWord(text, 4, true)); assertEquals(-1, TextUtils.findPreviousWord(text, 0, true)); assertEquals(15, TextUtils.findPreviousWord(text, 19, false)); assertEquals(11, TextUtils.findPreviousWord(text, 15, false)); assertEquals(5, TextUtils.findPreviousWord(text, 11, false)); assertEquals(0, TextUtils.findPreviousWord(text, 5, false)); assertEquals(-1, TextUtils.findPreviousWord(text, 0, false)); } public void testStopAtNewLineWhenFindNextWord() { String text = "alex\nalex\n"; assertEquals(5, TextUtils.findNextWord(text, 0, true)); assertEquals(4, TextUtils.findNextWord(text, 0, false)); assertEquals(10, TextUtils.findNextWord(text, 5, true)); assertEquals(9, TextUtils.findNextWord(text, 4, false)); } public void testIdentifierFindWord() { String text = "$(test.alex, 3)"; assertEquals(1, TextUtils.findNextWord(text, 0, true)); assertEquals(2, TextUtils.findNextWord(text, 1, true)); assertEquals(6, TextUtils.findNextWord(text, 2, true)); assertEquals(7, TextUtils.findNextWord(text, 6, true)); assertEquals(11, TextUtils.findNextWord(text, 7, true)); assertEquals(13, TextUtils.findNextWord(text, 11, true)); assertEquals(14, TextUtils.findNextWord(text, 13, true)); assertEquals(16, TextUtils.findNextWord(text, 14, true)); assertEquals(11, TextUtils.findNextWord(text, 7, false)); assertEquals(12, TextUtils.findNextWord(text, 11, false)); assertEquals(13, TextUtils.findPreviousWord(text, 14, false)); assertEquals(11, TextUtils.findPreviousWord(text, 13, false)); assertEquals(7, TextUtils.findPreviousWord(text, 11, false)); assertEquals(6, TextUtils.findPreviousWord(text, 7, false)); assertEquals(2, TextUtils.findPreviousWord(text, 6, false)); assertEquals(1, TextUtils.findPreviousWord(text, 2, false)); assertEquals(0, TextUtils.findPreviousWord(text, 1, false)); assertEquals(11, TextUtils.findPreviousWord(text, 13, true)); assertEquals(7, TextUtils.findPreviousWord(text, 11, true)); } public void testCombiningMarkFindWord() { String text = "\tà=à\r"; assertEquals(1, TextUtils.findNextWord(text, 0, true)); assertEquals(3, TextUtils.findNextWord(text, 1, true)); assertEquals(4, TextUtils.findNextWord(text, 3, true)); assertEquals(6, TextUtils.findNextWord(text, 4, true)); assertEquals(5, TextUtils.findPreviousWord(text, 6, true)); assertEquals(4, TextUtils.findPreviousWord(text, 5, true)); assertEquals(0, TextUtils.findPreviousWord(text, 3, true)); assertEquals(1, TextUtils.findPreviousWord(text, 3, false)); } public void testCountWhitespaceAtBegginingOfLine() { assertEquals(4, TextUtils.countWhitespacesAtTheBeginningOfLine("\t\t A")); assertEquals(4, TextUtils.countWhitespacesAtTheBeginningOfLine("\t\t ")); assertEquals(4, TextUtils.countWhitespacesAtTheBeginningOfLine("\t\t \n")); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/SortedPositionMapTests.java
javatests/com/google/collide/shared/util/SortedPositionMapTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import com.google.collide.json.shared.JsonArray; import junit.framework.TestCase; /** * Tests for the {@link SortedPositionMap} class. */ public class SortedPositionMapTests extends TestCase { private final SortedPositionMap<Object> map = new SortedPositionMap<Object>(); private final Object atL2C10 = new Object(); private final Object atL5C10 = new Object(); private final Object atL5C15 = new Object(); private final Object atL9C0 = new Object(); public void testRemoveRangeAll() { map.removeRange(0, 0, 100, 0); assertEquals(0, map.size()); } public void testRemoveRangeInclusiveExclusive() { map.removeRange(2, 10, 5, 15); assertEquals(2, map.size()); assertEquals(null, map.get(2, 10)); assertEquals(null, map.get(5, 10)); assertEquals(atL5C15, map.get(5, 15)); } public void testReplace() { assertEquals(atL9C0, map.get(9, 0)); Object newObject = new Object(); map.put(9, 0, newObject); assertEquals(newObject, map.get(9, 0)); JsonArray<Object> values = map.values(); assertEquals(4, values.size()); assertEquals(atL2C10, values.get(0)); assertEquals(atL5C10, values.get(1)); assertEquals(atL5C15, values.get(2)); assertEquals(newObject, values.get(3)); } public void testValues() { JsonArray<Object> values = map.values(); assertEquals(4, values.size()); assertEquals(atL2C10, values.get(0)); assertEquals(atL5C10, values.get(1)); assertEquals(atL5C15, values.get(2)); assertEquals(atL9C0, values.get(3)); } @Override protected void setUp() throws Exception { map.put(2, 10, atL2C10); map.put(5, 10, atL5C10); map.put(5, 15, atL5C15); map.put(9, 0, atL9C0); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/util/RoleUtilsTests.java
javatests/com/google/collide/shared/util/RoleUtilsTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.util; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.collide.dto.ProjectInfo; import com.google.collide.dto.Role; import com.google.collide.dto.WorkspaceInfo; import com.google.collide.shared.util.RoleUtils.Authenticator; import com.google.collide.shared.util.RoleUtils.ProjectAuthenticator; import com.google.collide.shared.util.RoleUtils.WorkspaceAuthenticator; import org.junit.Before; import org.junit.Test; /** * Tests for {@link RoleUtils}. */ public class RoleUtilsTests { ProjectInfo mockProject; WorkspaceInfo mockWorkspace; @Before public void createMocks() { mockProject = createMock(ProjectInfo.class); mockWorkspace = createMock(WorkspaceInfo.class); } @Test public void testIsWorkspaceReadOnly() { assertTrue(RoleUtils.isWorkspaceReadOnly(Role.READER, false)); assertTrue(RoleUtils.isWorkspaceReadOnly(Role.READER, true)); assertFalse(RoleUtils.isWorkspaceReadOnly(Role.CONTRIBUTOR, false)); assertTrue(RoleUtils.isWorkspaceReadOnly(Role.CONTRIBUTOR, true)); assertFalse(RoleUtils.isWorkspaceReadOnly(Role.OWNER, false)); assertTrue(RoleUtils.isWorkspaceReadOnly(Role.OWNER, true)); } @Test public void testWorkspaceOwnerAuthenticator() { runWorkspaceAuthenticatorTests(RoleUtils.WORKSPACE_OWNER_AUTHENTICATOR, true, false, false); } @Test public void testWorkspaceContributorAuthenticator() { runWorkspaceAuthenticatorTests(RoleUtils.WORKSPACE_CONTRIBUTOR_AUTHENTICATOR, true, true, false); } @Test public void testWorkspaceReaderAuthenticator() { runWorkspaceAuthenticatorTests(RoleUtils.WORKSPACE_READER_AUTHENTICATOR, true, true, true); } @Test public void testProjectOwnerAuthenticator() { runProjectAuthenticatorTests(RoleUtils.PROJECT_OWNER_AUTHENTICATOR, true, false, false); } @Test public void testProjectContributorAuthenticator() { runProjectAuthenticatorTests(RoleUtils.PROJECT_CONTRIBUTOR_AUTHENTICATOR, true, true, false); } @Test public void testProjectReaderAuthenticator() { runProjectAuthenticatorTests(RoleUtils.PROJECT_READER_AUTHENTICATOR, true, true, true); } private void runProjectAuthenticatorTests(ProjectAuthenticator authenticator, boolean owner, boolean contributor, boolean reader) { // Test isAuthorized(Role) runAuthenticatorTests(authenticator, owner, contributor, reader); // Test isAuthorized(ProjectInfo) expect(mockProject.getCurrentUserRole()).andReturn(Role.OWNER); replay(mockProject, mockWorkspace); assertEquals(owner, authenticator.isAuthorized(mockProject)); verifyAndReset(mockProject, mockWorkspace); expect(mockProject.getCurrentUserRole()).andReturn(Role.CONTRIBUTOR); replay(mockProject, mockWorkspace); assertEquals(contributor, authenticator.isAuthorized(mockProject)); verifyAndReset(mockProject, mockWorkspace); expect(mockProject.getCurrentUserRole()).andReturn(Role.READER); replay(mockProject, mockWorkspace); assertEquals(reader, authenticator.isAuthorized(mockProject)); verifyAndReset(mockProject, mockWorkspace); expect(mockProject.getCurrentUserRole()).andReturn(null); replay(mockProject, mockWorkspace); assertFalse(authenticator.isAuthorized(mockProject)); verifyAndReset(mockProject, mockWorkspace); } private void runWorkspaceAuthenticatorTests(WorkspaceAuthenticator authenticator, boolean owner, boolean contributor, boolean reader) { // Test isAuthorized(Role) runAuthenticatorTests(authenticator, owner, contributor, reader); // Test isAuthorized(WorkspaceInfo) expect(mockWorkspace.getCurrentUserRole()).andReturn(Role.OWNER); replay(mockProject, mockWorkspace); assertEquals(owner, authenticator.isAuthorized(mockWorkspace)); verifyAndReset(mockProject, mockWorkspace); expect(mockWorkspace.getCurrentUserRole()).andReturn(Role.CONTRIBUTOR); replay(mockProject, mockWorkspace); assertEquals(contributor, authenticator.isAuthorized(mockWorkspace)); verifyAndReset(mockProject, mockWorkspace); expect(mockWorkspace.getCurrentUserRole()).andReturn(Role.READER); replay(mockProject, mockWorkspace); assertEquals(reader, authenticator.isAuthorized(mockWorkspace)); verifyAndReset(mockProject, mockWorkspace); expect(mockWorkspace.getCurrentUserRole()).andReturn(null); replay(mockProject, mockWorkspace); assertFalse(authenticator.isAuthorized(mockWorkspace)); verifyAndReset(mockProject, mockWorkspace); } private void runAuthenticatorTests(Authenticator authenticator, boolean owner, boolean contributor, boolean reader) { assertEquals(owner, authenticator.isAuthorized(Role.OWNER)); assertEquals(contributor, authenticator.isAuthorized(Role.CONTRIBUTOR)); assertEquals(reader, authenticator.isAuthorized(Role.READER)); assertFalse(authenticator.isAuthorized((Role) null)); } private void verifyAndReset(Object... objects) { verify(objects); reset(objects); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/document/DocumentTestUtils.java
javatests/com/google/collide/shared/document/DocumentTestUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.document; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document.LineListener; import com.google.collide.shared.util.StringUtils; import junit.framework.Assert; /** * Test utility methods for document mutation. */ public final class DocumentTestUtils { public static void deleteAndAssertEquals(Line line, int column, int deleteCount, String expectedText) { Document doc = line.getDocument(); String deletedText = doc.getText(line, column, deleteCount); final int numberOfNewlinesInDeletedRange = StringUtils.countNumberOfOccurrences(deletedText, "\n"); class MyLineListener implements LineListener { boolean called = false; @Override public void onLineAdded(Document document, int lineNumber, JsonArray<Line> addedLines) { Assert.fail(); } @Override public void onLineRemoved(Document document, int lineNumber, JsonArray<Line> removedLines) { Assert.assertEquals(numberOfNewlinesInDeletedRange, removedLines.size()); called = true; } } MyLineListener lineListener = new MyLineListener(); doc.getLineListenerRegistrar().add(lineListener); try { doc.deleteText(line, column, deleteCount); } finally { doc.getLineListenerRegistrar().remove(lineListener); } if (numberOfNewlinesInDeletedRange != 0) { Assert.assertTrue(lineListener.called); } Assert.assertEquals(expectedText, line.getText()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/document/LineUtilsTests.java
javatests/com/google/collide/shared/document/LineUtilsTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.document; import com.google.collide.shared.document.util.PositionUtils; import com.google.common.base.Joiner; import junit.framework.TestCase; /** * Tests for the {@link LineUtils} class. * */ public class LineUtilsTests extends TestCase { /** Tests are dependent on these values, do not change. */ private static final String[] LINES = {"Hello world\n", "Foo bar\n", "Something else\n"}; private Document doc; private Line line; public void testGetPositionBackwards() { Position pos; line = doc.getLastLine(); pos = PositionUtils.getPosition(line, -1, 5, -1); assertPosition(line, 4, pos); pos = PositionUtils.getPosition(line, -1, 5, -3); assertPosition(line, 2, pos); pos = PositionUtils.getPosition(line, -1, 0, -1); assertPosition(line.getPreviousLine(), line.getPreviousLine().getText().length() - 1, pos); pos = PositionUtils.getPosition(line, -1, 5, -6); assertPosition(line.getPreviousLine(), line.getPreviousLine().getText().length() - 1, pos); pos = PositionUtils.getPosition(line, -1, 5, -5 - line.getPreviousLine().getText().length()); assertPosition(line.getPreviousLine(), 0, pos); pos = PositionUtils.getPosition(line, -1, 5, -6 - line.getPreviousLine().getText().length()); assertPosition(line.getPreviousLine().getPreviousLine(), line.getPreviousLine() .getPreviousLine().getText().length() - 1, pos); pos = PositionUtils.getPosition(line, -1, 5, -6 - line.getPreviousLine().getText().length() - line.getPreviousLine().getPreviousLine().getText().length()); assertPosition(line.getPreviousLine().getPreviousLine().getPreviousLine(), line .getPreviousLine().getPreviousLine().getPreviousLine().getText().length() - 1, pos); } public void testGetPositionForward() { Position pos; pos = PositionUtils.getPosition(line, -1, 0, 1); assertPosition(line, 1, pos); pos = PositionUtils.getPosition(line, -1, 0, 5); assertPosition(line, 5, pos); pos = PositionUtils.getPosition(line, -1, 3, 5); assertPosition(line, 8, pos); pos = PositionUtils.getPosition(line, -1, 11, 1); assertPosition(line.getNextLine(), 0, pos); pos = PositionUtils.getPosition(line, -1, 0, line.getText().length()); assertPosition(line.getNextLine(), 0, pos); pos = PositionUtils.getPosition(line, -1, 0, line.getText().length() + 5); assertPosition(line.getNextLine(), 5, pos); pos = PositionUtils.getPosition(line, -1, 3, line.getText().length()); assertPosition(line.getNextLine(), 3, pos); pos = PositionUtils.getPosition(line, -1, 0, line.getText().length() + line.getNextLine().getText().length()); assertPosition(line.getNextLine().getNextLine(), 0, pos); pos = PositionUtils.getPosition(line, -1, 3, line.getText().length() + line.getNextLine().getText().length() + 5); assertPosition(line.getNextLine().getNextLine(), 8, pos); pos = PositionUtils.getPosition(line, -1, 0, line.getText().length() + line.getNextLine().getText().length() + 5); assertPosition(line.getNextLine().getNextLine(), 5, pos); } public void testGetPositionOutOfBoundsBeginning() { try { PositionUtils.getPosition(line, -1, 0, -1); fail(); } catch (PositionOutOfBoundsException e) { } } public void testGetPositionForwardAtDocumentEnd() { line = doc.getLastLine(); Position pos = PositionUtils.getPosition(line, -1, line.getText().length() - 1, 1); assertPosition(doc.getLastLine(), doc.getLastLine().getText().length(), pos); } public void testGetPositionOutOfBoundsEnd() { line = doc.getLastLine(); try { PositionUtils.getPosition(line, -1, line.getText().length() - 1, 2); fail(); } catch (PositionOutOfBoundsException e) { } } @Override protected void setUp() throws Exception { doc = Document.createFromString(Joiner.on("").join(LINES)); line = doc.getFirstLine(); } private void assertPosition(Line expectedLine, int expectedColumn, Position actualPosition) { assertEquals(expectedLine, actualPosition.getLine()); assertEquals(expectedColumn, actualPosition.getColumn()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/document/TextChangeTests.java
javatests/com/google/collide/shared/document/TextChangeTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.document; import junit.framework.TestCase; /** * Tests for {@link TextChange}. */ public class TextChangeTests extends TestCase { private Document emptyDoc; private final String filledDocContents = "Hello\nWorld\nWoot"; private Document filledDoc; public void testEndForDeletion() { TextChange deletion = TextChange.createDeletion(filledDoc.getFirstLine(), 0, 3, "Something"); assertEquals(filledDoc.getFirstLine(), deletion.getEndLine()); assertEquals(0, deletion.getEndLineNumber()); assertEquals(3, deletion.getEndColumn()); } public void testEndForInsertion() { TextChange insertion; insertion = TextChange.createInsertion(filledDoc.getFirstLine(), 0, 2, filledDoc.getFirstLine() .getNextLine(), 1, "llo\n"); assertEquals(filledDoc.getFirstLine(), insertion.getEndLine()); assertEquals(0, insertion.getEndLineNumber()); assertEquals(5, insertion.getEndColumn()); insertion = TextChange.createInsertion(filledDoc.getFirstLine(), 0, 2, filledDoc.getFirstLine() .getNextLine(), 1, "llo\nWor"); assertEquals(filledDoc.getFirstLine().getNextLine(), insertion.getEndLine()); assertEquals(1, insertion.getEndLineNumber()); assertEquals(2, insertion.getEndColumn()); insertion = TextChange.createInsertion(filledDoc.getFirstLine(), 0, 1, filledDoc.getFirstLine(), 0, "el"); assertEquals(filledDoc.getFirstLine(), insertion.getEndLine()); assertEquals(0, insertion.getEndLineNumber()); assertEquals(2, insertion.getEndColumn()); } @Override protected void setUp() throws Exception { emptyDoc = Document.createFromString(""); filledDoc = Document.createFromString(filledDocContents); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/document/PositionUtilsTests.java
javatests/com/google/collide/shared/document/PositionUtilsTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.document; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.util.PositionUtils; import com.google.common.base.Joiner; import junit.framework.TestCase; import org.junit.Assert; /** * Tests for {@link PositionUtils}. */ public class PositionUtilsTests extends TestCase { /** Tests are dependent on these values, do not change. */ private static final String[] LINES = {"Hello world\n", "Foo bar\n", "Something else\n"}; private Document doc; private Line line; private Position startOfLine1; private Position endOfLine1; private Position startOfLine2; private Position endOfLine2; private Position startOfLine3; private Position endOfLine3; public void testPositionEquality() { assertEquals(startOfLine1, new Position(new LineInfo(line, 0), 0)); assertNotSame(startOfLine1, startOfLine2); } public void testIntersection() { // Equal ranges assertIntersectionEquals(startOfLine1, endOfLine1, startOfLine1, endOfLine1, startOfLine1, endOfLine1); // Ranges start at same place assertIntersectionEquals(startOfLine1, endOfLine1, startOfLine1, endOfLine1, startOfLine1, endOfLine2); assertIntersectionEquals(startOfLine1, endOfLine1, startOfLine1, endOfLine2, startOfLine1, endOfLine1); // One range inside another assertIntersectionEquals(startOfLine2, endOfLine2, startOfLine1, endOfLine3, startOfLine2, endOfLine2); // Ranges end at same place assertIntersectionEquals(startOfLine2, endOfLine2, startOfLine1, endOfLine2, startOfLine2, endOfLine2); // Typical intersection assertIntersectionEquals(startOfLine2, endOfLine2, startOfLine1, endOfLine2, startOfLine2, endOfLine3); // No intersection assertIntersectionEquals(null, null, startOfLine1, endOfLine1, startOfLine2, endOfLine2); } public void testDifference() { // No difference assertDifferenceEquals(startOfLine1, endOfLine1, startOfLine1, endOfLine1); // Ranges start at same place assertDifferenceEquals(startOfLine1, endOfLine1, startOfLine1, endOfLine2, startOfLine2, endOfLine2); assertDifferenceEquals(startOfLine1, endOfLine2, startOfLine1, endOfLine1, startOfLine2, endOfLine2); // One range inside another assertDifferenceEquals(startOfLine1, endOfLine3, startOfLine2, endOfLine2, startOfLine1, endOfLine1, startOfLine3, endOfLine3); // Ranges end at same place assertDifferenceEquals(startOfLine1, endOfLine2, startOfLine2, endOfLine2, startOfLine1, endOfLine1); // Typical intersection assertDifferenceEquals(startOfLine1, endOfLine2, startOfLine2, endOfLine3, startOfLine1, endOfLine1, startOfLine3, endOfLine3); // No intersection assertDifferenceEquals(startOfLine1, endOfLine1, startOfLine2, endOfLine2, startOfLine1, endOfLine1, startOfLine2, endOfLine2); } @Override protected void setUp() throws Exception { doc = Document.createFromString(Joiner.on("").join(LINES)); line = doc.getFirstLine(); Line curLine = line; startOfLine1 = new Position(new LineInfo(curLine, 0), 0); endOfLine1 = new Position(new LineInfo(curLine, 0), LINES[0].length() - 1); curLine = curLine.getNextLine(); startOfLine2 = new Position(new LineInfo(curLine, 1), 0); endOfLine2 = new Position(new LineInfo(curLine, 1), LINES[1].length() - 1); curLine = curLine.getNextLine(); startOfLine3 = new Position(new LineInfo(curLine, 2), 0); endOfLine3 = new Position(new LineInfo(curLine, 2), LINES[2].length() - 1); } private void assertIntersectionEquals(Position expectedStart, Position expectedEnd, Position aStart, Position aEnd, Position bStart, Position bEnd) { Position[] intersection = PositionUtils.getIntersection(new Position[] {aStart, aEnd}, new Position[] {bStart, bEnd}); if (expectedStart == null) { assertEquals(null, intersection); } else { Assert.assertArrayEquals((new Position[] {expectedStart, expectedEnd}), intersection); } } private void assertDifferenceEquals(Position aStart, Position aEnd, Position bStart, Position bEnd, Position... expected) { JsonArray<Position[]> difference = PositionUtils.getDifference(new Position[] {aStart, aEnd}, new Position[] {bStart, bEnd}); assertEquals(expected.length / 2, difference.size()); int expectedPos = 0; for (int diffPos = 0; diffPos < difference.size(); diffPos++) { Assert.assertArrayEquals(new Position[] {expected[expectedPos++], expected[expectedPos++]}, difference.get(diffPos)); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/document/DocumentTests.java
javatests/com/google/collide/shared/document/DocumentTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.document; import static com.google.collide.shared.document.AnchorTestUtils.assertAnchorPosition; import static com.google.collide.shared.document.DocumentTestUtils.deleteAndAssertEquals; import static com.google.collide.shared.document.anchor.AnchorManager.IGNORE_COLUMN; import static com.google.collide.shared.document.anchor.AnchorManager.IGNORE_LINE_NUMBER; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document.LineCountListener; import com.google.collide.shared.document.Document.LineListener; import com.google.collide.shared.document.Document.TextListener; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy; import com.google.collide.shared.document.anchor.Anchor.RemoveListener; import com.google.collide.shared.document.anchor.Anchor.ShiftListener; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.document.util.LineUtils; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.util.List; import java.util.Random; /** * Tests mutations on the document. * * Notes: * <ul> * <li>lineAnchor* members are anchors that only care about the line number * <li>columnAnchor* members are anchors that only care about the column (not a * line number) * <li>anchor* members are anchors that care about both the line number and * column * </ul> * */ public class DocumentTests extends TestCase { private static final AnchorType DOCUMENT_TEST_ANCHOR_TYPE = AnchorType.create(DocumentTests.class, "test"); /** Tests are dependent on these values, do not change. */ private static final String[] LINES = {"Hello world\n", "Foo bar\n", "Something else\n"}; /** Tests are dependent on these values, do not change. */ private static final String[] LINES_TO_INSERT = {"Insert number one\n", "Number two\n", "three\n"}; private Anchor columnAnchorOnLine0H; private Anchor anchorOnLine0Space; private Anchor columnAnchorOnLine0W; private Anchor anchorOnLine0D; private Anchor columnAnchorOnLine0Newline; private Anchor anchorOnLine1F; private Anchor columnAnchorOnLine1SecondO; private Anchor anchorOnLine1Space; private Anchor columnAnchorOnLine1R; private Anchor anchorOnLine1Newline; private Anchor columnAnchorOnLine2S; private Anchor columnAnchorOnLine2Space; private Anchor anchorOnLine2LastE; private Anchor columnAnchorOnLine2Newline; private Anchor lineAnchorOnLine0; private Anchor lineAnchorOnLine1; private Anchor lineAnchorOnLine2; private Document doc; private LineFinder lf; private AnchorManager anchorManager; /** Starts at first line of the document */ private Line line; private final Random random = new Random(); public void testCreateFromString() { Document doc = Document.createFromString(Joiner.on("").join(LINES)); Line line = doc.getFirstLine(); for (String expectedLineText : LINES) { assertEquals(expectedLineText, line.getText()); line = line.getNextLine(); } } public void testDeleteEntireDocumentContents() { Line originalFirstLine = line; int docLength = 0; while (line != null) { docLength += line.getText().length(); line = line.getNextLine(); } // Shift a few anchors columnAnchorOnLine0H.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); anchorOnLine1Space.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); columnAnchorOnLine2Newline.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); doc.deleteText(doc.getFirstLine(), 0, docLength); assertEquals(originalFirstLine, doc.getFirstLine()); assertEquals(originalFirstLine, doc.getLastLine()); assertEquals("", originalFirstLine.getText()); // The three shifted anchors above, and the line anchor on line 0 assertEquals(4, doc.getAnchorManager().getAnchors(originalFirstLine).size()); assertAnchorPosition(columnAnchorOnLine0H, 0, true, 0); assertAnchorPosition(anchorOnLine1Space, 0, false, 0); assertAnchorPosition(columnAnchorOnLine2Newline, 0, true, 0); assertFalse(anchorOnLine0D.isAttached()); assertFalse(anchorOnLine1Newline.isAttached()); assertFalse(anchorOnLine2LastE.isAttached()); } public void testDeleteText() { // Delete single letter in front, middle, end deleteAndAssertEquals(line, 0, 1, "ello world\n"); assertFalse(columnAnchorOnLine0H.isAttached()); assertEquals(4, anchorOnLine0Space.getColumn()); assertEquals(5, columnAnchorOnLine0W.getColumn()); assertEquals(10, columnAnchorOnLine0Newline.getColumn()); deleteAndAssertEquals(line, 4, 1, "elloworld\n"); assertFalse(anchorOnLine0Space.isAttached()); assertEquals(4, columnAnchorOnLine0W.getColumn()); assertEquals(9, columnAnchorOnLine0Newline.getColumn()); deleteAndAssertEquals(line, 8, 1, "elloworl\n"); assertFalse(anchorOnLine0D.isAttached()); assertEquals(4, columnAnchorOnLine0W.getColumn()); assertEquals(8, columnAnchorOnLine0Newline.getColumn()); assertEquals(0, lineAnchorOnLine0.getLineInfo().number()); assertEquals(AnchorManager.IGNORE_COLUMN, lineAnchorOnLine0.getColumn()); // Delete multiple letters from the front, middle, end line = line.getNextLine(); deleteAndAssertEquals(line, 0, 2, "o bar\n"); assertFalse(anchorOnLine1F.isAttached()); assertEquals(0, columnAnchorOnLine1SecondO.getColumn()); deleteAndAssertEquals(line, 1, 2, "oar\n"); assertFalse(anchorOnLine1Space.isAttached()); assertEquals(0, columnAnchorOnLine1SecondO.getColumn()); assertEquals(2, columnAnchorOnLine1R.getColumn()); assertEquals(3, anchorOnLine1Newline.getColumn()); deleteAndAssertEquals(line, 1, 2, "o\n"); assertFalse(columnAnchorOnLine1R.isAttached()); assertEquals(0, columnAnchorOnLine1SecondO.getColumn()); assertEquals(1, anchorOnLine1Newline.getColumn()); assertEquals(1, lineAnchorOnLine1.getLineInfo().number()); assertEquals(AnchorManager.IGNORE_COLUMN, lineAnchorOnLine1.getColumn()); // Delete entire contents of line, minus the newline line = line.getNextLine(); deleteAndAssertEquals(line, 0, LINES[2].length() - 1, "\n"); assertFalse(columnAnchorOnLine2S.isAttached()); assertFalse(columnAnchorOnLine2Space.isAttached()); assertFalse(anchorOnLine2LastE.isAttached()); assertEquals(0, columnAnchorOnLine2Newline.getColumn()); assertEquals(2, lineAnchorOnLine2.getLineInfo().number()); assertEquals(AnchorManager.IGNORE_COLUMN, lineAnchorOnLine2.getColumn()); } public void testDeleteMultilineText() { deleteAndAssertEquals(columnAnchorOnLine0Newline.getLine(), columnAnchorOnLine0Newline.getColumn(), 1, "Hello worldFoo bar\n"); } public void testViewportBottomShiftingOnSmallDocument() { Document doc = Document.createFromString("abc\n"); Anchor bottomAnchor = doc.getAnchorManager().createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, doc.getLastLine(), 1, IGNORE_COLUMN); deleteAndAssertEquals(doc.getFirstLine(), 3, 1, "abc"); assertAnchorPosition(bottomAnchor, 0, false, IGNORE_COLUMN); } public void testCursorAtEndOfOnlyLine() { Document doc = Document.createFromString("abc"); // Column is the non-existent character after 'c' Anchor cursorAnchor = doc.getAnchorManager().createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, doc.getFirstLine(), 0, 3); cursorAnchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); deleteAndAssertEquals(doc.getFirstLine(), 0, 3, ""); assertAnchorPosition(cursorAnchor, 0, false, 0); } public void testInsertText() { // Insert at front insertTextAndAssertEquals(line, 0, "This is ", "This is Hello world\n"); assertEquals(8, columnAnchorOnLine0H.getColumn()); assertEquals(13, anchorOnLine0Space.getColumn()); assertEquals(19, columnAnchorOnLine0Newline.getColumn()); // Insert in middle insertTextAndAssertEquals(line, 7, " a test of", "This is a test of Hello world\n"); assertEquals(18, columnAnchorOnLine0H.getColumn()); assertEquals(23, anchorOnLine0Space.getColumn()); assertEquals(29, columnAnchorOnLine0Newline.getColumn()); // Insert at end insertTextAndAssertEquals( line, line.getText().length() - 1, "!!", "This is a test of Hello world!!\n"); assertEquals(18, columnAnchorOnLine0H.getColumn()); assertEquals(23, anchorOnLine0Space.getColumn()); assertEquals(31, columnAnchorOnLine0Newline.getColumn()); } public void testInsertTextMultilineAtEnd() { String insertText = "\n" + getStringOfLinesToInsert(); // The last line is "", so get the line before it for "Something else" line = doc.getLastLine().getPreviousLine(); String lastLineText = line.getText(); /* * Insert before the last line's newline (insertText starts with a newline, * so in the end, its text should be unchanged) */ doc.insertText(line, line.getText().length() - 1, insertText); /* * The last line's text should be unchanged */ assertEquals(lastLineText, line.getText()); line = line.getNextLine(); for (int i = 0; i < LINES_TO_INSERT.length; i++) { assertEquals(LINES_TO_INSERT[i], line.getText()); line = line.getNextLine(); } // Empty newline since insertText started with newline assertEquals("\n", line.getText()); assertAnchorPosition(columnAnchorOnLine0H, 0, true, 0); assertAnchorPosition(anchorOnLine0Space, 0, false, 5); assertAnchorPosition(columnAnchorOnLine0W, 0, true, 6); assertAnchorPosition(anchorOnLine0D, 0, false, 10); assertAnchorPosition(columnAnchorOnLine0Newline, 0, true, 11); assertAnchorPosition(anchorOnLine1F, 1, false, 0); assertAnchorPosition(columnAnchorOnLine1SecondO, 1, true, 2); assertAnchorPosition(anchorOnLine1Space, 1, false, 3); assertAnchorPosition(columnAnchorOnLine1R, 1, true, 6); assertAnchorPosition(anchorOnLine1Newline, 1, false, 7); assertAnchorPosition(columnAnchorOnLine2S, 2, true, 0); assertAnchorPosition(columnAnchorOnLine2Space, 2, true, 9); assertAnchorPosition(anchorOnLine2LastE, 2, false, 13); // The only anchor that moved assertAnchorPosition(columnAnchorOnLine2Newline, 6, true, 0); assertAnchorPosition(lineAnchorOnLine0, 0, false, IGNORE_COLUMN); assertAnchorPosition(lineAnchorOnLine1, 1, false, IGNORE_COLUMN); assertAnchorPosition(lineAnchorOnLine2, 2, false, IGNORE_COLUMN); } public void testInsertTextMultilineAtFrontWithTrailingNewline() { String s = getStringOfLinesToInsert(); doc.insertText(line, 0, s); line = doc.getFirstLine(); for (int i = 0; i < LINES_TO_INSERT.length; i++) { assertEquals(LINES_TO_INSERT[i], line.getText()); line = line.getNextLine(); } for (int i = 0; i < LINES.length; i++) { assertEquals(LINES[i], line.getText()); line = line.getNextLine(); } assertAnchorPosition(columnAnchorOnLine0H, 3, true, 0); assertAnchorPosition(anchorOnLine0Space, 3, false, 5); assertAnchorPosition(columnAnchorOnLine0W, 3, true, 6); assertAnchorPosition(anchorOnLine0D, 3, false, 10); assertAnchorPosition(columnAnchorOnLine0Newline, 3, true, 11); assertAnchorPosition(anchorOnLine1F, 4, false, 0); assertAnchorPosition(columnAnchorOnLine1SecondO, 4, true, 2); assertAnchorPosition(anchorOnLine1Space, 4, false, 3); assertAnchorPosition(columnAnchorOnLine1R, 4, true, 6); assertAnchorPosition(anchorOnLine1Newline, 4, false, 7); assertAnchorPosition(columnAnchorOnLine2S, 5, true, 0); assertAnchorPosition(columnAnchorOnLine2Space, 5, true, 9); assertAnchorPosition(anchorOnLine2LastE, 5, false, 13); assertAnchorPosition(columnAnchorOnLine2Newline, 5, true, 14); assertAnchorPosition(lineAnchorOnLine0, 0, false, IGNORE_COLUMN); assertAnchorPosition(lineAnchorOnLine1, 4, false, IGNORE_COLUMN); assertAnchorPosition(lineAnchorOnLine2, 5, false, IGNORE_COLUMN); } public void testInsertTextMultilineAtMiddleOfLineWithoutTrailingNewline() { String s = getStringOfLinesToInsert(); s += "No trailing newline here!"; doc.insertText(line, 5, s); line = doc.getFirstLine(); assertEquals(LINES[0].substring(0, 5) + LINES_TO_INSERT[0], line.getText()); line = line.getNextLine(); for (int i = 1; i < LINES_TO_INSERT.length; i++) { assertEquals(LINES_TO_INSERT[i], line.getText()); line = line.getNextLine(); } assertEquals("No trailing newline here!" + LINES[0].substring(5), line.getText()); line = line.getNextLine(); for (int i = 1; i < LINES.length; i++) { assertEquals(LINES[i], line.getText()); line = line.getNextLine(); } assertAnchorPosition(columnAnchorOnLine0H, 0, true, 0); assertAnchorPosition(anchorOnLine0Space, 3, false, 25); assertAnchorPosition(columnAnchorOnLine0W, 3, true, 26); assertAnchorPosition(anchorOnLine0D, 3, false, 30); assertAnchorPosition(columnAnchorOnLine0Newline, 3, true, 31); assertAnchorPosition(anchorOnLine1F, 4, false, 0); assertAnchorPosition(columnAnchorOnLine1SecondO, 4, true, 2); assertAnchorPosition(anchorOnLine1Space, 4, false, 3); assertAnchorPosition(columnAnchorOnLine1R, 4, true, 6); assertAnchorPosition(anchorOnLine1Newline, 4, false, 7); assertAnchorPosition(columnAnchorOnLine2S, 5, true, 0); assertAnchorPosition(columnAnchorOnLine2Space, 5, true, 9); assertAnchorPosition(anchorOnLine2LastE, 5, false, 13); assertAnchorPosition(columnAnchorOnLine2Newline, 5, true, 14); assertAnchorPosition(lineAnchorOnLine0, 0, false, IGNORE_COLUMN); assertAnchorPosition(lineAnchorOnLine1, 4, false, IGNORE_COLUMN); assertAnchorPosition(lineAnchorOnLine2, 5, false, IGNORE_COLUMN); } public void testRemoveRemovalStrategy() { columnAnchorOnLine0H.setRemovalStrategy(Anchor.RemovalStrategy.REMOVE); doc.deleteText(line, 0, 2); assertFalse(columnAnchorOnLine0H.isAttached()); anchorOnLine0Space.setRemovalStrategy(Anchor.RemovalStrategy.REMOVE); int spaceColumn = anchorOnLine0Space.getColumn(); doc.deleteText(line, spaceColumn, 2); assertFalse(anchorOnLine0Space.isAttached()); anchorOnLine0D.setRemovalStrategy(Anchor.RemovalStrategy.REMOVE); int dColumn = anchorOnLine0D.getColumn(); doc.deleteText(line, dColumn, 1); assertFalse(anchorOnLine0D.isAttached()); // Deleting the newline will join lines columnAnchorOnLine0Newline.setRemovalStrategy(Anchor.RemovalStrategy.REMOVE); int newlineColumn = columnAnchorOnLine0Newline.getColumn(); doc.deleteText(line, newlineColumn, 1); assertFalse(columnAnchorOnLine0Newline.isAttached()); } public void testShiftRemovalStrategy() { columnAnchorOnLine0H.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); doc.deleteText(line, 0, 2); assertTrue(columnAnchorOnLine0H.isAttached()); assertEquals(line, columnAnchorOnLine0H.getLine()); assertEquals(0, columnAnchorOnLine0H.getColumn()); anchorOnLine0Space.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); int spaceColumn = anchorOnLine0Space.getColumn(); doc.deleteText(line, spaceColumn, 2); assertTrue(anchorOnLine0Space.isAttached()); assertEquals(line, anchorOnLine0Space.getLine()); assertEquals(spaceColumn, anchorOnLine0Space.getColumn()); anchorOnLine0D.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); int dColumn = anchorOnLine0D.getColumn(); doc.deleteText(line, dColumn, 1); assertTrue(anchorOnLine0D.isAttached()); assertEquals(line, anchorOnLine0D.getLine()); assertEquals(dColumn, anchorOnLine0D.getColumn()); // Deleting the newline will join lines columnAnchorOnLine0Newline.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); lineAnchorOnLine1.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); int newlineColumn = columnAnchorOnLine0Newline.getColumn(); doc.deleteText(line, newlineColumn, 1); assertTrue(columnAnchorOnLine0Newline.isAttached()); assertEquals(line, columnAnchorOnLine0Newline.getLine()); assertEquals(AnchorManager.IGNORE_LINE_NUMBER, columnAnchorOnLine0Newline.getLineNumber()); assertEquals(newlineColumn, columnAnchorOnLine0Newline.getColumn()); assertTrue(lineAnchorOnLine1.isAttached()); assertEquals(line, lineAnchorOnLine1.getLine()); assertEquals(0, lineAnchorOnLine1.getLineNumber()); assertEquals(AnchorManager.IGNORE_COLUMN, lineAnchorOnLine1.getColumn()); columnAnchorOnLine2Newline.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); line = columnAnchorOnLine2Newline.getLine(); newlineColumn = columnAnchorOnLine2Newline.getColumn(); doc.deleteText(line, newlineColumn, 1); assertTrue(columnAnchorOnLine2Newline.isAttached()); assertEquals(line, columnAnchorOnLine2Newline.getLine()); assertEquals(LineUtils.getLastCursorColumn(line), columnAnchorOnLine2Newline.getColumn()); } public void testLineCountDuringTextChangeDispatch() { final int origLineCount = doc.getLineCount(); doc.getTextListenerRegistrar().add(new TextListener() { @Override public void onTextChange(Document document, JsonArray<TextChange> textChanges) { assertEquals(origLineCount + 1, doc.getLineCount()); } }); doc.insertText(doc.getFirstLine(), 0, "\n"); } @SuppressWarnings("unchecked") public void testListenerCallbackOrderingOnInsertLine() { /* * The callback ordering is considered API and cannot be changed unless all * clients are updated (once public, it cannot be changed at all.) This must * match the ordering mentioned in the Document class's javadoc. */ doc = Document.createFromString("one\ntwo\nthree"); List<Class<?>> listenerOrdering = setupForListenerCallbackOrdering(doc); doc.insertText(doc.getFirstLine(), 0, "\n"); assertEquals(Lists.newArrayList(ShiftListener.class, LineCountListener.class, LineListener.class, TextListener.class), listenerOrdering); } @SuppressWarnings("unchecked") public void testListenerCallbackOrderingOnRemoveLine() { doc = Document.createFromString("one\ntwo\nthree"); List<Class<?>> listenerOrdering; listenerOrdering = setupForListenerCallbackOrdering(doc); doc.deleteText(doc.getFirstLine(), 0, doc.getFirstLine().length()); assertEquals(Lists.newArrayList(ShiftListener.class, LineCountListener.class, LineListener.class, TextListener.class), listenerOrdering); doc = Document.createFromString("one\ntwo\nthree"); listenerOrdering = setupForListenerCallbackOrdering(doc); doc.deleteText(doc.getFirstLine().getNextLine(), 0, doc.getFirstLine().getNextLine().length()); assertEquals(Lists.newArrayList(ShiftListener.class, RemoveListener.class, LineCountListener.class, LineListener.class, TextListener.class), listenerOrdering); } public void testErrorWhenMutatingPastEndOfLine() { try { doc.insertText(line, line.length(), "Something"); fail("Error should have been thrown"); } catch (Exception e) { } /* * This is OK since the last line does not have a newline, this is the only * way to append a char to the last line */ doc.insertText(doc.getLastLine(), doc.getLastLine().length(), "Something"); try { doc.insertText(doc.getLastLine(), doc.getLastLine().length()+1, "Something"); fail("Error should have been thrown"); } catch (Exception e) { } } /** * For anchor listener testing, the anchor will be attached to the * "number of lines / 2". */ private static List<Class<?>> setupForListenerCallbackOrdering(Document doc) { final List<Class<?>> callbackOrdering = Lists.newArrayList(); Anchor shiftAnchor = doc.getAnchorManager().createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, doc.getLineFinder().findLine(doc.getLineCount() / 2).line(), doc.getLineCount() / 2, 0); shiftAnchor.setRemovalStrategy(RemovalStrategy.SHIFT); shiftAnchor.getShiftListenerRegistrar().add(new ShiftListener() { @Override public void onAnchorShifted(Anchor anchor) { callbackOrdering.add(ShiftListener.class); } }); Anchor removeAnchor = doc.getAnchorManager().createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, doc.getLineFinder().findLine(doc.getLineCount() / 2).line(), doc.getLineCount() / 2, 0); removeAnchor.getRemoveListenerRegistrar().add(new RemoveListener() { @Override public void onAnchorRemoved(Anchor anchor) { callbackOrdering.add(RemoveListener.class); } }); doc.getLineCountListenerRegistrar().add(new LineCountListener() { @Override public void onLineCountChanged(Document document, int lineCount) { callbackOrdering.add(LineCountListener.class); } }); doc.getLineListenerRegistrar().add(new LineListener() { @Override public void onLineRemoved(Document document, int lineNumber, JsonArray<Line> removedLines) { callbackOrdering.add(LineListener.class); } @Override public void onLineAdded(Document document, int lineNumber, JsonArray<Line> addedLines) { callbackOrdering.add(LineListener.class); } }); doc.getTextListenerRegistrar().add(new TextListener() { @Override public void onTextChange(Document document, JsonArray<TextChange> textChanges) { callbackOrdering.add(TextListener.class); } }); return callbackOrdering; } @Override protected void setUp() throws Exception { doc = Document.createFromString(Joiner.on("").join(LINES)); lf = doc.getLineFinder(); anchorManager = doc.getAnchorManager(); line = doc.getFirstLine(); Line curLine = line; LineInfo curLineInfo = new LineInfo(line, 0); columnAnchorOnLine0H = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, IGNORE_LINE_NUMBER, 0); anchorOnLine0Space = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, 0, 5); columnAnchorOnLine0W = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, IGNORE_LINE_NUMBER, 6); anchorOnLine0D = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, 0, curLine.getText() .length() - 2); columnAnchorOnLine0Newline = anchorManager.createAnchor( DOCUMENT_TEST_ANCHOR_TYPE, curLine, IGNORE_LINE_NUMBER, curLine.getText().length() - 1); lineAnchorOnLine0 = anchorManager.createAnchor( DOCUMENT_TEST_ANCHOR_TYPE, curLineInfo.line(), curLineInfo.number(), IGNORE_COLUMN); curLine = curLine.getNextLine(); curLineInfo.moveToNext(); anchorOnLine1F = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, 1, 0); columnAnchorOnLine1SecondO = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, IGNORE_LINE_NUMBER, 2); anchorOnLine1Space = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, 1, 3); columnAnchorOnLine1R = anchorManager.createAnchor( DOCUMENT_TEST_ANCHOR_TYPE, curLine, IGNORE_LINE_NUMBER, curLine.getText().length() - 2); anchorOnLine1Newline = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, 1, curLine.getText() .length() - 1); lineAnchorOnLine1 = anchorManager.createAnchor( DOCUMENT_TEST_ANCHOR_TYPE, curLineInfo.line(), curLineInfo.number(), IGNORE_COLUMN); curLine = curLine.getNextLine(); curLineInfo.moveToNext(); columnAnchorOnLine2S = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, IGNORE_LINE_NUMBER, 0); columnAnchorOnLine2Space = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, IGNORE_LINE_NUMBER, 9); anchorOnLine2LastE = anchorManager.createAnchor(DOCUMENT_TEST_ANCHOR_TYPE, curLine, 2, curLine.getText() .length() - 2); columnAnchorOnLine2Newline = anchorManager.createAnchor( DOCUMENT_TEST_ANCHOR_TYPE, curLine, IGNORE_LINE_NUMBER, curLine.getText().length() - 1); lineAnchorOnLine2 = anchorManager.createAnchor( DOCUMENT_TEST_ANCHOR_TYPE, curLineInfo.line(), curLineInfo.number(), IGNORE_COLUMN); } private String getStringOfLinesToInsert() { String s = ""; for (int i = 0; i < LINES_TO_INSERT.length; i++) { s += LINES_TO_INSERT[i]; } return s; } private void insertTextAndAssertEquals(Line line, int column, String text, String expectedText) { doc.insertText(line, column, text); assertEquals(expectedText, line.getText()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/document/AnchorTestUtils.java
javatests/com/google/collide/shared/document/AnchorTestUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.document; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; /** * Utility methods for testing anchors. */ public final class AnchorTestUtils { private AnchorTestUtils() { } static void assertAnchorPosition(Anchor anchor, int lineNumber, boolean ignoresLineNumber, int column) { assertTrue(anchor.isAttached()); assertEquals(anchor.getLine().getDocument().getLineFinder().findLine(lineNumber).line(), anchor.getLine()); assertEquals(ignoresLineNumber ? AnchorManager.IGNORE_LINE_NUMBER : lineNumber, anchor.getLineNumber()); assertEquals(column, anchor.getColumn()); if (anchor.hasLineNumber()) { assertTrue(anchor.getLine().getDocument().getAnchorManager().getLineAnchors() .findIndex(anchor) != -1); } } static void assertAnchorPositions(Object... anchorAndLineNumbersAndColumnsAlternating) { for (int i = 0; i < anchorAndLineNumbersAndColumnsAlternating.length; i++) { Anchor anchor = (Anchor) anchorAndLineNumbersAndColumnsAlternating[i]; int lineNumber = (Integer) anchorAndLineNumbersAndColumnsAlternating[++i]; int column = (Integer) anchorAndLineNumbersAndColumnsAlternating[++i]; assertEquals(lineNumber, anchor.getLineNumber()); assertEquals(column, anchor.getColumn()); } } static void assertAnchorLineNumbers(Object... anchorAndLineNumbersAlternating) { for (int i = 0; i < anchorAndLineNumbersAlternating.length; i++) { Anchor anchor = (Anchor) anchorAndLineNumbersAlternating[i]; int lineNumber = (Integer) anchorAndLineNumbersAlternating[++i]; assertEquals(lineNumber, anchor.getLineNumber()); } } static void assertAnchorColumns(Object... anchorAndColumnsAlternating) { for (int i = 0; i < anchorAndColumnsAlternating.length; i++) { Anchor anchor = (Anchor) anchorAndColumnsAlternating[i]; int column = (Integer) anchorAndColumnsAlternating[++i]; assertEquals(column, anchor.getColumn()); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/document/AnchorTests.java
javatests/com/google/collide/shared/document/AnchorTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.document; import static com.google.collide.shared.document.AnchorTestUtils.assertAnchorColumns; import static com.google.collide.shared.document.AnchorTestUtils.assertAnchorLineNumbers; import static com.google.collide.shared.document.AnchorTestUtils.assertAnchorPositions; import static com.google.collide.shared.document.anchor.AnchorManager.IGNORE_COLUMN; import static com.google.collide.shared.document.anchor.AnchorManager.IGNORE_LINE_NUMBER; import static com.google.collide.shared.document.anchor.InsertionPlacementStrategy.EARLIER; import static com.google.collide.shared.document.anchor.InsertionPlacementStrategy.LATER; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy; import com.google.collide.shared.document.anchor.AnchorList; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.document.anchor.InsertionPlacementStrategy; import com.google.common.base.Joiner; import junit.framework.TestCase; import java.util.ArrayList; /** */ public class AnchorTests extends TestCase { // 100 cols FTW private static final String[] LINES = {"About Google\n", "\n", "The Beginning\n", "\n", "Beginning in 1996, Stanford University graduate students Larry Page and " + "Sergey Brin built a\n", "search engine called 'BackRub' that used links to determine the importance of " + "individual\n", "web pages. By 1998 they had formalized their work, creating the company you know " + "today as Google."}; private Document doc; private AnchorManager anchorManager; private static final AnchorType ANCHOR_TYPE_1 = AnchorType.create(AnchorTests.class, "1"); private static final AnchorType ANCHOR_TYPE_2 = AnchorType.create(AnchorTests.class, "2"); private Anchor docStart; private Anchor docStartCol1; private Anchor firstEmptyLine; private Anchor theBeginning; private Anchor year1996a; private Anchor year1996b; private Anchor year1996c; private Anchor individual; private Anchor year1998; private Anchor docEnd; private ArrayList<Anchor> anchors; @Override protected void setUp() { doc = Document.createFromString(Joiner.on("").join(LINES)); anchorManager = doc.getAnchorManager(); Line line = doc.getFirstLine(); docStart = anchorManager.createAnchor(ANCHOR_TYPE_1, line, IGNORE_LINE_NUMBER, 0); docStartCol1 = anchorManager.createAnchor(ANCHOR_TYPE_1, line, 0, 1); line = line.getNextLine(); firstEmptyLine = anchorManager.createAnchor(ANCHOR_TYPE_1, line, IGNORE_LINE_NUMBER, 0); line = line.getNextLine(); theBeginning = anchorManager.createAnchor(ANCHOR_TYPE_2, line, IGNORE_LINE_NUMBER, 0); line = line.getNextLine().getNextLine(); year1996a = anchorManager.createAnchor(ANCHOR_TYPE_1, line, IGNORE_LINE_NUMBER, 13); year1996b = anchorManager.createAnchor(ANCHOR_TYPE_2, line, IGNORE_LINE_NUMBER, 13); year1996c = anchorManager.createAnchor(ANCHOR_TYPE_2, line, IGNORE_LINE_NUMBER, 13); line = line.getNextLine(); individual = anchorManager.createAnchor(ANCHOR_TYPE_1, line, IGNORE_LINE_NUMBER, 79); line = line.getNextLine(); year1998 = anchorManager.createAnchor(ANCHOR_TYPE_2, line, IGNORE_LINE_NUMBER, 19); docEnd = anchorManager.createAnchor(ANCHOR_TYPE_1, line, IGNORE_LINE_NUMBER, 99); anchors = new ArrayList<Anchor>(); anchors.add(docStart); anchors.add(docStartCol1); anchors.add(firstEmptyLine); anchors.add(theBeginning); anchors.add(year1996a); anchors.add(year1996b); anchors.add(year1996c); anchors.add(individual); anchors.add(year1998); anchors.add(docEnd); } /** * Currently the AnchorType.create will create a new instance of an anchor for * the same type. So, anchor types cannot rely on reference equality. If we * ever decide to change that, this test will let us know to update * expectations elsewhere. */ public void testAnchorTypeEquality() { AnchorType type1dup = AnchorType.create(AnchorTests.class, "1"); assertEquals(ANCHOR_TYPE_1, type1dup); assertEquals(ANCHOR_TYPE_1.toString(), type1dup.toString()); // Reminder to update AnchorType comparisons to identity rather than .equals assertNotSame(ANCHOR_TYPE_1, type1dup); } /** * Verify we can walk the anchors in order. */ public void testSimpleTraversal() { AnchorList anchorList = anchorManager.getAnchors(doc.getFirstLine()); assertEquals(2, anchorList.size()); Anchor anchor = anchorList.get(0); for (Anchor a : anchors) { assertSame(anchor, a); anchor = anchorManager.getNextAnchor(anchor); } } /** * Verify we can walk the anchors in reverse order */ public void testBackwardsTraversal() { AnchorList anchorList = anchorManager.getAnchors(doc.getLastLine()); assertEquals(2, anchorList.size()); Anchor anchor = docEnd; for (int i = anchors.size() - 1; i >= 0; i--) { assertSame(anchors.get(i), anchor); assertEquals(anchors.get(i).getType(), anchor.getType()); anchor = anchorManager.getPreviousAnchor(anchor); } } /** * Test {@link AnchorManager#getAnchorsByTypeOrNull(Line, AnchorType)}. */ public void testGetAnchorsByTypeOrNull() { Line line = doc.getFirstLine(); JsonArray<Anchor> anchors = AnchorManager.getAnchorsByTypeOrNull(line, ANCHOR_TYPE_1); assertEquals(2, anchors.size()); assertSame(docStart, anchors.get(0)); assertSame(docStartCol1, anchors.get(1)); anchors = AnchorManager.getAnchorsByTypeOrNull(line, ANCHOR_TYPE_2); assertEquals(0, anchors.size()); line = line.getNextLine(); anchors = AnchorManager.getAnchorsByTypeOrNull(line, ANCHOR_TYPE_1); assertEquals(1, anchors.size()); assertSame(firstEmptyLine, anchors.get(0)); anchors = AnchorManager.getAnchorsByTypeOrNull(line, ANCHOR_TYPE_2); assertEquals(0, anchors.size()); line = line.getNextLine(); anchors = AnchorManager.getAnchorsByTypeOrNull(line, ANCHOR_TYPE_1); assertEquals(0, anchors.size()); anchors = AnchorManager.getAnchorsByTypeOrNull(line, ANCHOR_TYPE_2); assertEquals(1, anchors.size()); assertSame(theBeginning, anchors.get(0)); line = line.getNextLine(); assertNotNull(line); anchors = AnchorManager.getAnchorsByTypeOrNull(line, ANCHOR_TYPE_1); assertNull(anchors); anchors = AnchorManager.getAnchorsByTypeOrNull(line, ANCHOR_TYPE_2); assertNull(anchors); } /** * Currently, we rely on being able to push anchors past the end of the line. */ public void testAnchorPastEnd() { Line line = doc.getFirstLine().getNextLine(); Anchor anchor = anchorManager.createAnchor(ANCHOR_TYPE_1, line, IGNORE_LINE_NUMBER, 1); assertSame(anchorManager.getPreviousAnchor(anchor), firstEmptyLine); line = line.getNextLine(); anchorManager.moveAnchor(anchor, line, IGNORE_LINE_NUMBER, 100); assertSame(anchorManager.getPreviousAnchor(anchor), theBeginning); } /** * Verify that the type filter is working as expected. */ public void testType1Traversal() { ArrayList<Anchor> type1Anchors = new ArrayList<Anchor>(); for (Anchor a : anchors) { if (a.getType().equals(ANCHOR_TYPE_1)) { type1Anchors.add(a); } } Anchor anchor = docStart; assertEquals(ANCHOR_TYPE_1, anchor.getType()); for (Anchor a : type1Anchors) { assertSame(a, anchor); assertEquals(ANCHOR_TYPE_1, anchor.getType()); anchor = anchorManager.getNextAnchor(anchor, ANCHOR_TYPE_1); } assertNull(anchor); } public void testInsertionPlacementStrategyForLineAnchors() { Anchor a1 = createAnchorForPlacementStrategy(doc.getFirstLine(), true, IGNORE_COLUMN, EARLIER); Anchor a2 = createAnchorForPlacementStrategy(doc.getFirstLine(), true, IGNORE_COLUMN, LATER); assertAnchorLineNumbers(a1, 0, a2, 0); doc.insertText(doc.getFirstLine(), 0, "Newline\n"); assertAnchorLineNumbers(a1, 0, a2, 1); doc.deleteText(doc.getFirstLine(), 0, doc.getFirstLine().getText().length()); assertAnchorLineNumbers(a1, 0, a2, 0); doc.insertText(doc.getFirstLine(), 0, "Many\nnew\nlines\n!\n"); assertAnchorLineNumbers(a1, 0, a2, 4); } public void testInsertionPlacementStrategyForColumnAnchors() { Anchor a1 = createAnchorForPlacementStrategy(doc.getFirstLine(), false, 0, EARLIER); Anchor a2 = createAnchorForPlacementStrategy(doc.getFirstLine(), false, 0, LATER); assertAnchorColumns(a1, 0, a2, 0); doc.insertText(doc.getFirstLine(), 0, "a"); assertAnchorColumns(a1, 0, a2, 1); doc.deleteText(doc.getFirstLine(), 0, doc.getFirstLine().getText().length()); assertAnchorColumns(a1, 0, a2, 0); doc.insertText(doc.getFirstLine(), 0, "more than a trivial insertion"); assertAnchorColumns(a1, 0, a2, "more than a trivial insertion".length()); doc.insertText(doc.getFirstLine(), 0, "\n"); assertEquals(doc.getFirstLine(), a1.getLine()); assertEquals(doc.getFirstLine().getNextLine(), a2.getLine()); assertAnchorColumns(a1, 0, a2, "more than a trivial insertion".length()); } public void testInsertionPlacementStrategyForLineNumberAndColumnAnchors() { Anchor a1 = createAnchorForPlacementStrategy(doc.getFirstLine(), true, 1, EARLIER); Anchor a2 = createAnchorForPlacementStrategy(doc.getFirstLine(), true, 1, LATER); assertAnchorPositions(a1, 0, 1, a2, 0, 1); doc.insertText(doc.getFirstLine(), 0, "a"); assertAnchorPositions(a1, 0, 2, a2, 0, 2); doc.insertText(doc.getFirstLine(), 2, "a"); assertAnchorPositions(a1, 0, 2, a2, 0, 3); doc.insertText(doc.getFirstLine(), 0, "\n"); assertAnchorPositions(a1, 1, 2, a2, 1, 3); Line secondLine = doc.getFirstLine().getNextLine(); doc.deleteText(secondLine, 0, secondLine.getText().length()); assertAnchorPositions(a1, 1, 0, a2, 1, 0); doc.insertText(secondLine, 0, "more than a trivial insertion"); assertAnchorPositions(a1, 1, 0, a2, 1, "more than a trivial insertion".length()); doc.insertText(secondLine, 0, "many\nnew\nlines\n!\n"); assertAnchorPositions(a1, 1, 0, a2, 5, "more than a trivial insertion".length()); } private Anchor createAnchorForPlacementStrategy(Line line, boolean storeLineNumber, int column, InsertionPlacementStrategy insertionPlacementStrategy) { Anchor a = doc.getAnchorManager().createAnchor(ANCHOR_TYPE_1, doc.getFirstLine(), storeLineNumber ? doc.getLineFinder().findLine(line).number() : IGNORE_LINE_NUMBER, column); a.setInsertionPlacementStrategy(insertionPlacementStrategy); a.setRemovalStrategy(RemovalStrategy.SHIFT); return a; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/DocOpTestUtils.java
javatests/com/google/collide/shared/ot/DocOpTestUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.ot; import static com.google.collide.dto.DocOpComponent.Type.DELETE; import static com.google.collide.dto.DocOpComponent.Type.INSERT; import static com.google.collide.dto.DocOpComponent.Type.RETAIN; import static com.google.collide.dto.DocOpComponent.Type.RETAIN_LINE; import com.google.collide.dto.DocOp; import com.google.collide.dto.DocOpComponent; import com.google.collide.dto.DocOpComponent.Delete; import com.google.collide.dto.DocOpComponent.Insert; import com.google.collide.dto.DocOpComponent.Retain; import com.google.collide.dto.DocOpComponent.RetainLine; import com.google.collide.dto.server.ServerDocOpFactory; import com.google.collide.dto.shared.DocOpFactory; import com.google.collide.shared.Pair; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.ot.Composer.ComposeException; import org.junit.Assert; /** * Utility methods for testing document operations. * */ public class DocOpTestUtils extends Assert { public static void assertDocOpEquals(DocOp a, DocOp b) { try { assertSize(a.getComponents().size(), b); for (int i = 0; i < a.getComponents().size(); i++) { assertDocOpComponentEquals(a.getComponents().get(i), b.getComponents().get(i)); } } catch (AssertionError e) { AssertionError newE = new AssertionError("DocOps not equal:\n" + DocOpUtils.toString(a, false) + "\n" + DocOpUtils.toString(b, false)); newE.initCause(e); throw newE; } } public static void assertDocOpComponentEquals(DocOpComponent a, DocOpComponent b) { assertEquals("DocOpComponents are not equal", a.getType(), b.getType()); switch (a.getType()) { case INSERT: assertEquals(((Insert) a).getText(), ((Insert) b).getText()); break; case DELETE: assertEquals(((Delete) a).getText(), ((Delete) b).getText()); break; case RETAIN: assertEquals(((Retain) a).getCount(), ((Retain) b).getCount()); assertEquals(((Retain) a).hasTrailingNewline(), ((Retain) b).hasTrailingNewline()); break; case RETAIN_LINE: assertEquals(((RetainLine) a).getLineCount(), ((RetainLine) b).getLineCount()); break; default: assert false : "Fix test"; } } public static void assertDelete(String expectedDeleteText, DocOp op, int index) { DocOpComponent component = op.getComponents().get(index); assertEquals(DELETE, component.getType()); assertEquals(expectedDeleteText, ((Delete) component).getText()); } public static void assertInsert(String expectedInsertText, DocOp op, int index) { DocOpComponent component = op.getComponents().get(index); assertEquals(INSERT, component.getType()); assertEquals(expectedInsertText, ((Insert) component).getText()); } public static void assertRetain(int expectedRetainCount, boolean expectedHasTrailingNewline, DocOp op, int index) { DocOpComponent component = op.getComponents().get(index); assertEquals(RETAIN, component.getType()); Retain retain = (Retain) component; assertEquals(expectedRetainCount, retain.getCount()); assertEquals(expectedHasTrailingNewline, retain.hasTrailingNewline()); } public static void assertRetainLine(int expectedRetainLineCount, DocOp op, int index) { DocOpComponent component = op.getComponents().get(index); assertEquals(RETAIN_LINE, component.getType()); RetainLine retainLine = (RetainLine) component; assertEquals(expectedRetainLineCount, retainLine.getLineCount()); } public static void assertSize(int expectedComponentsSize, DocOp op) { assertEquals("DocOp sizes aren't equal", expectedComponentsSize, op.getComponents().size()); } public static void assertCompose(DocOp expected, DocOp a, DocOp b) { try { assertDocOpEquals(expected, compose(a, b)); } catch (ComposeException e) { throw new AssertionError(e); } } public static void assertComposeFails(DocOp a, DocOp b) { try { compose(a, b); throw new AssertionError("Compose should have failed"); } catch (Composer.ComposeException e) { } } /** * @see #assertCompose(DocOp, DocOp, DocOp) */ public static DocOp compose(DocOp a, DocOp b) throws ComposeException { Pair<DocOp, DocOp> composedDocOps = composeWithBothStartingStates(ServerDocOpFactory.INSTANCE, a, b); assertDocOpEquals(composedDocOps.first, composedDocOps.second); return composedDocOps.first; } public static DocOp asDocOp(TextChange textChange) { return DocOpUtils.createFromTextChange(ServerDocOpFactory.INSTANCE, textChange); } public static Pair<DocOp, DocOp> composeWithBothStartingStates(DocOpFactory factory, DocOp a, DocOp b) throws ComposeException { ComposeException e1 = null; DocOp composedDocOp1 = null; try { composedDocOp1 = Composer.composeWithStartState(factory, a, b, false); } catch (ComposeException e) { e1 = e; } ComposeException e2 = null; DocOp composedDocOp2 = null; try { composedDocOp2 = Composer.composeWithStartState(factory, a, b, true); } catch (ComposeException e) { e2 = e; } if ((e1 == null) != (e2 == null)) { throw new IllegalArgumentException( "One way of composition had an exception, the other didn't", e1 != null ? e1 : e2); } else if (e1 != null /* which means e2 != null too */) { throw e1; } return Pair.of(composedDocOp1, composedDocOp2); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/PositionTransformerTests.java
javatests/com/google/collide/shared/ot/PositionTransformerTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.ot; import com.google.collide.dto.server.ServerDocOpFactory; import junit.framework.TestCase; /** * */ public class PositionTransformerTests extends TestCase { private TerseDocOpBuilder b; public void testDeleteDocOpScenarios() { { // Deletion before position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.d("h").b()); assertPositionTransformerEquals(0, 4, transformer); } { // Deletion ending at position PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.d("h").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion containing position PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.d("hello").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion after position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.r(5).d("hello").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion with newline before position on next line PositionTransformer transformer = new PositionTransformer(1, 1); transformer.transform(b.d("hello\n").b()); assertPositionTransformerEquals(0, 1, transformer); } { // Deletion with newline after position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.r(5).d("hello\n").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion with newline where position is on newline PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.d("h\n").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion with newline where position is on newline PositionTransformer transformer = new PositionTransformer(5, 1); transformer.transform(b.rl(3).d("\n").rl(5).b()); assertPositionTransformerEquals(4, 1, transformer); } } public void testInsertDocOpScenarios() { { // Insertion before position PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.i("hello").b()); assertPositionTransformerEquals(0, 6, transformer); } { // Insertion at position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.i("hello").b()); assertPositionTransformerEquals(0, 5, transformer); } { // Insertion after position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.r(5).i("hello").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Insertion with newline before position PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.i("hello\n").b()); assertPositionTransformerEquals(1, 1, transformer); } { // Insertion with newline before position PositionTransformer transformer = new PositionTransformer(4, 1); transformer.transform(b.i("hello\n").b()); assertPositionTransformerEquals(5, 1, transformer); } { // Insertion with newline at position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.i("hello\n").b()); assertPositionTransformerEquals(1, 0, transformer); } { // Insertion with newline after position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.r(5).i("hello\n").b()); assertPositionTransformerEquals(0, 0, transformer); } } public void testRetainDocOpScenarios() { { // Retain before position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.r(4).b()); assertPositionTransformerEquals(0, 5, transformer); } { // Retain surrounding position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.r(40).b()); assertPositionTransformerEquals(0, 5, transformer); } { /* * Retain after position (this is an odd test case, but just ensuring the * r(40) doesn't affect anything) */ PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.r(10).r(40).b()); assertPositionTransformerEquals(0, 5, transformer); } { // Retain with newline containing position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.eolR(40).b()); assertPositionTransformerEquals(0, 5, transformer); } } public void testRetainLineDocOpScenarios() { { // Retain line before position PositionTransformer transformer = new PositionTransformer(4, 5); transformer.transform(b.rl(2).b()); assertPositionTransformerEquals(4, 5, transformer); } { // Retain line surrounding position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.rl(40).b()); assertPositionTransformerEquals(0, 5, transformer); } { /* * Retain line after position (this is an odd test case, but just ensuring * the rl(40) doesn't affect anything) */ PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.eolR(10).rl(40).b()); assertPositionTransformerEquals(0, 5, transformer); } } @Override protected void setUp() throws Exception { b = new TerseDocOpBuilder(ServerDocOpFactory.INSTANCE, false); } private static void assertPositionTransformerEquals(int expectedLineNumber, int expectedColumn, PositionTransformer positionTransformer) { assertEquals(expectedLineNumber, positionTransformer.getLineNumber()); assertEquals(expectedColumn, positionTransformer.getColumn()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/DocOpCreator.java
javatests/com/google/collide/shared/ot/DocOpCreator.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.ot; import com.google.collide.dto.DocOp; import com.google.collide.dto.shared.DocOpFactory; import org.junit.Assert; /** * Utility class to create document operations with one non-retain component by * reducing the burden of manually retaining, insert/deleting, and retaining. * The document operations all assume the document has a trailing newline. * */ public class DocOpCreator { private final DocOpBuilder builder; public DocOpCreator(DocOpFactory factory) { this.builder = new DocOpBuilder(factory, false); } /** * Creates a document operation that deletes the characters denoted by the * given range. * * @param size The initial size of the document. * @param location The location the characters to delete. * @param characters The characters to delete. * @return The document operation. */ public DocOp delete(int size, int location, String characters) { assertTrailingNewline(size, location, characters); return builder.retain(location, false).delete(characters) .retain(size - location - characters.length(), true).build(); } /** * Creates a document operation that acts as the identity on a document. * * @param size The size of the document. * @return The document operation. */ public DocOp identity(int size) { return builder.retain(size, true).build(); } /** * Creates a document operation that inserts the given characters at the given * location. * * @param size The initial size of the document. * @param location The location at which to insert characters. * @param characters The characters to insert. * @return The document operation. */ public DocOp insert(int size, int location, String characters) { assertTrailingNewline(size, location, characters); return builder.retain(location, false).insert(characters).retain(size - location, true).build(); } protected void assertTrailingNewline(int size, int location, String characters) { Assert.assertTrue("Must have trailing newline", size - location - characters.length() >= 1); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/DocOpTests.java
javatests/com/google/collide/shared/ot/DocOpTests.java
package com.google.collide.shared.ot; import static com.google.collide.shared.ot.DocOpTestUtils.assertDelete; import static com.google.collide.shared.ot.DocOpTestUtils.assertInsert; import static com.google.collide.shared.ot.DocOpTestUtils.assertRetain; import static com.google.collide.shared.ot.DocOpTestUtils.assertRetainLine; import static com.google.collide.shared.ot.DocOpTestUtils.assertSize; import com.google.collide.dto.DocOp; import com.google.collide.dto.server.ServerDocOpFactory; import com.google.collide.dto.shared.DocOpFactory; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Document.TextListener; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.StringUtils; import junit.framework.TestCase; /** * Tests for general document operation methods. * */ public class DocOpTests extends TestCase { private static final String[] LINES = {"Hello world\n", "Foo bar\n", "Something else\n"}; private DocOpFactory factory; private Document doc; private DocOpBuilder builder; private TerseDocOpBuilder b; public void testDocOpCapturerRetainCompacting() { DocOpCapturer c = new DocOpCapturer(factory, true); c.retain(5, true); c.retain(4, false); assertSize(2, c.getDocOp()); c = new DocOpCapturer(factory, true); c.retain(5, false); c.retain(4, false); assertSize(1, c.getDocOp()); } public void testMultilineTextChangeConversions() { TextChange textChange; DocOp op; textChange = TextChange.createInsertion(doc.getFirstLine(), 0, 0, doc.getFirstLine() .getNextLine(), 1, "Hello world\n"); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(3, op); assertInsert("Hello world\n", op, 0); // TODO: need to doc how we require this line to be retained // instead of "retain line"ed assertRetain(doc.getFirstLine().getNextLine().getText().length(), true, op, 1); assertRetainLine(2, op, 2); textChange = TextChange.createInsertion(doc.getFirstLine().getNextLine(), 1, 1, doc.getFirstLine() .getNextLine().getNextLine(), 2, "oo\nSomething "); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(6, op); assertRetainLine(1, op, 0); assertRetain(1, false, op, 1); assertInsert("oo\n", op, 2); assertInsert("Something ", op, 3); assertRetain("else\n".length(), true, op, 4); assertRetainLine(1, op, 5); textChange = TextChange.createInsertion(doc.getFirstLine(), 0, 5, doc.getFirstLine().getNextLine() .getNextLine(), 2, " world\nFoo bar\n"); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(5, op); assertRetain(5, false, op, 0); assertInsert(" world\n", op, 1); assertInsert("Foo bar\n", op, 2); assertRetain("Something else\n".length(), true, op, 3); assertRetainLine(1, op, 4); textChange = TextChange.createDeletion(doc.getFirstLine(), 0, 3, "Imagine this was a line\n"); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(4, op); assertRetain(3, false, op, 0); assertDelete("Imagine this was a line\n", op, 1); assertRetain("lo world\n".length(), true, op, 2); assertRetainLine(3, op, 3); textChange = TextChange.createDeletion(doc.getFirstLine().getNextLine(), 1, 3, "A line\nand some "); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(6, op); assertRetainLine(1, op, 0); assertRetain(3, false, op, 1); assertDelete("A line\n", op, 2); assertDelete("and some ", op, 3); assertRetain(" bar\n".length(), true, op, 4); assertRetainLine(2, op, 5); } public void testRetainTrailingNewLineBehavior() { // Add the to-be-inserted "A" and the "r" that is to be retained doc.insertText(doc.getLastLine(), 0, "Ar"); TextChange textChange; DocOp op; textChange = TextChange.createInsertion(doc.getLastLine(), doc.getLastLineNumber(), 0, doc.getLastLine(), doc.getLastLineNumber(), "A"); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(3, op); assertRetainLine(3, op, 0); assertInsert("A", op, 1); assertRetain(1, false, op, 2); Line line = doc.getLastLine().getPreviousLine(); textChange = TextChange.createInsertion(line, doc.getLastLineNumber() - 1, 0, line, doc.getLastLineNumber() - 1, "S"); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(4, op); assertRetainLine(2, op, 0); assertInsert("S", op, 1); assertRetain(line.getText().length() - 1, true, op, 2); assertRetainLine(1, op, 3); } public void testSimpleTextChangeConversions() { Document doc = Document.createFromString("\nThis is\na test\n"); TextChange textChange = TextChange.createInsertion(doc.getFirstLine(), 0, 0, doc.getFirstLine(), 0, "\n"); DocOp op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(3, op); assertInsert("\n", op, 0); assertRetain(8, true, op, 1); // There's an empty line at the end assertRetainLine(2, op, 2); } public void testSingleLineTextChangeConversions() { TextChange textChange; DocOp op; textChange = TextChange.createInsertion(doc.getFirstLine(), 0, 1, doc.getFirstLine(), 0, "ello"); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(4, op); assertRetain(1, false, op, 0); assertInsert("ello", op, 1); assertRetain(7, true, op, 2); assertRetainLine(3, op, 3); textChange = TextChange.createDeletion(doc.getFirstLine(), 0, 2, "WOOT"); op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(4, op); assertRetain(2, false, op, 0); assertDelete("WOOT", op, 1); assertRetain(10, true, op, 2); assertRetainLine(3, op, 3); } /** * Tests the scenario where the document is: * * <pre> * \n * \n * aa * </pre> * * and we insert a newline at line 0, position 0 */ public void testBuggyScenario1() { doc = Document.createFromString("\n\na"); final DocOp[] opFromListener = new DocOp[1]; doc.getTextListenerRegistrar().add(new TextListener() { @Override public void onTextChange(Document document, JsonArray<TextChange> textChanges) { opFromListener[0] = DocOpUtils.createFromTextChange(factory, textChanges.get(0)); } }); TextChange textChange = doc.insertText(doc.getFirstLine(), 0, "\n"); assertEquals(TextChange.createInsertion(doc.getFirstLine(), 0, 0, doc.getFirstLine() .getNextLine(), 1, "\n"), textChange); DocOp opPostListener = DocOpUtils.createFromTextChange(factory, textChange); DocOpTestUtils.assertDocOpEquals(opPostListener, opFromListener[0]); } /** * Tests the scenario where the document is: * * <pre> * a\n * b\n * c\n * d\n * e * </pre> * * and we delete a\nb\nc\nd. */ public void testBuggyDueToNoRetainWithTrailingNewLine() { doc = Document.createFromString("a\nb\nc\nd\ne"); TextChange textChange = doc.deleteText(doc.getFirstLine(), 0, 0, 7); DocOp op = DocOpUtils.createFromTextChange(factory, textChange); assertSize(6, op); assertDelete("a\n", op, 0); assertDelete("b\n", op, 1); assertDelete("c\n", op, 2); assertDelete("d", op, 3); assertRetain(1, true, op, 4); assertRetainLine(1, op, 5); } /** * <pre> * ?????????? * dAsSafasD * ASasd * DaASdf * DASas * DASs * DdAS * fD * ASD * ASD * ASD * ASD * ASD * AS * DAS * DAS * D * ASD * ASD * ASD * AS? * ? (this maps to a RL(1), so not sure if it was empty or had text) * (this is an empty line) * </pre> */ public void testWhetherDeleteMultilineSelectionInThisCaseCreatesRetainLineToMatchEmptyLastLine() { doc = Document.createFromString( "??????????\ndAsSafasD\nASasd\nDaASdf\nDASas\nDASs\nDdAS\nfD\nASD\nASD\nASD\nASD\n" + "ASD\nAS\nDAS\nDAS\nD\nASD\nASD\nASD\nAS?\n?\n"); assertEquals(23, doc.getLineCount()); int textCount = LineUtils.getTextCount( doc.getFirstLine(), 10, doc.getLastLine().getPreviousLine().getPreviousLine(), 1); TextChange textChange = doc.deleteText(doc.getFirstLine(), 10, textCount); DocOp docOp = DocOpUtils.createFromTextChange(factory, textChange); docOp.toString(); } public void testMissingRetainLineAfterDelete() { { doc = Document.createFromString("\n"); TextChange textChange = doc.deleteText(doc.getFirstLine(), 0, 1); DocOp docOp = DocOpUtils.createFromTextChange(factory, textChange); DocOp expected = b.d("\n").rl(1).b(); DocOpTestUtils.assertDocOpEquals(expected, docOp); } { doc = Document.createFromString("alex\n"); TextChange textChange = doc.deleteText(doc.getFirstLine(), 4, 1); DocOp docOp = DocOpUtils.createFromTextChange(factory, textChange); DocOp expected = b.r(4).d("\n").rl(1).b(); DocOpTestUtils.assertDocOpEquals(expected, docOp); } { doc = Document.createFromString("alex"); TextChange textChange = doc.insertText(doc.getFirstLine(), 4, "\n"); DocOp docOp = DocOpUtils.createFromTextChange(factory, textChange); DocOp expected = b.r(4).i("\n").rl(1).b(); DocOpTestUtils.assertDocOpEquals(expected, docOp); } { doc = Document.createFromString("alex\ntest"); TextChange textChange = doc.deleteText(doc.getFirstLine(), 0, 9); DocOp docOp = DocOpUtils.createFromTextChange(factory, textChange); DocOp expected = b.d("alex\n").d("test").rl(1).b(); DocOpTestUtils.assertDocOpEquals(expected, docOp); } } public void testSimpleConversionWorks() { doc = Document.createFromString("aa\nhh\nii"); TextChange textChange = doc.insertText(doc.getFirstLine().getNextLine(), 0, "hh\nii\n"); DocOp docOpA = DocOpUtils.createFromTextChange(factory, textChange); DocOp expected = b.rl(1).i("hh\n").i("ii\n").eolR(3).rl(1).b(); DocOpTestUtils.assertDocOpEquals(expected, docOpA); textChange = doc.deleteText(doc.getFirstLine().getNextLine().getNextLine(), 2, 6); DocOp docOpB = DocOpUtils.createFromTextChange(factory, textChange); expected = b.rl(2).r(2).d("\n").d("hh\n").d("ii").b(); DocOpTestUtils.assertDocOpEquals(expected, docOpB); } @Override protected void setUp() throws Exception { factory = ServerDocOpFactory.INSTANCE; builder = new DocOpBuilder(factory, false); b = new TerseDocOpBuilder(factory, false); doc = Document.createEmpty(); doc.insertText(doc.getFirstLine(), 0, StringUtils.join(LINES, "")); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/TerseDocOpBuilder.java
javatests/com/google/collide/shared/ot/TerseDocOpBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.ot; import com.google.collide.dto.DocOp; import com.google.collide.dto.shared.DocOpFactory; /** * A document operation builder with a terse API aimed at improving productivity * when writing tests. */ public class TerseDocOpBuilder { private final DocOpBuilder docOpBuilder; /** * @param shouldCompact whether to compact similar document operation * components (e.g. R(5) followed by R(5) would be compacted to R(10)) */ public TerseDocOpBuilder(DocOpFactory factory, boolean shouldCompact) { docOpBuilder = new DocOpBuilder(factory, shouldCompact); } /** * @see DocOpBuilder#build() */ public DocOp b() { return docOpBuilder.build(); } /** * @see DocOpBuilder#delete(String) */ public TerseDocOpBuilder d(String text) { docOpBuilder.delete(text); return this; } /** * Adds a retain component for {@code count} characters where the last * character is a newline. * * Note: "eol" stands for end-of-line. * * @see DocOpBuilder#retain(int, boolean) * @see #r(int) */ public TerseDocOpBuilder eolR(int count) { docOpBuilder.retain(count, true); return this; } /** * @see DocOpBuilder#insert(String) */ public TerseDocOpBuilder i(String text) { docOpBuilder.insert(text); return this; } /** * Adds a retain component for {@code count} characters where the last * character is NOT a newline. * * @see DocOpBuilder#retain(int, boolean) * @see #eolR(int) */ public TerseDocOpBuilder r(int count) { docOpBuilder.retain(count, false); return this; } /** * @see DocOpBuilder#retainLine(int) */ public TerseDocOpBuilder rl(int lineCount) { docOpBuilder.retainLine(lineCount); return this; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/EmptyLastLineRetainLineTests.java
javatests/com/google/collide/shared/ot/EmptyLastLineRetainLineTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.ot; import static com.google.collide.shared.ot.DocOpTestUtils.*; import com.google.collide.dto.DocOp; import com.google.collide.dto.server.ServerDocOpFactory; import com.google.collide.shared.document.Document; import junit.framework.TestCase; /** * Tests various functionality related to OT ensuring that in cases where the * last Line of a Document is empty (has Line.getText() == ""), there is a * RetainLine that covers that empty Line. * * For legacy reasons, the composer and transformer currently support inputs * that don't follow this requirement. However, if the inputs follow the * requirement, their output must also follow the requirement. That is what will * be tested by the test methods in this class. * */ public class EmptyLastLineRetainLineTests extends TestCase { private final TerseDocOpBuilder builder = new TerseDocOpBuilder(ServerDocOpFactory.INSTANCE, false); private Document doc; public void testDocumentMutationsProduceEmptyLastLineRL() { // Empty mutations { // This is an strange edge case, but might as well cover it doc = Document.createFromString(""); DocOp actual = delete(0, 0, 0); DocOp expected = builder.rl(1).b(); assertDocOpEquals(expected, actual); } { // This is an strange edge case, but might as well cover it doc = Document.createFromString(""); DocOp actual = insert(0, 0, ""); DocOp expected = builder.rl(1).b(); assertDocOpEquals(expected, actual); } // Mutations without newlines { // Ensure no RL doc = Document.createFromString(""); DocOp actual = insert(0, 0, "a"); DocOp expected = builder.i("a").b(); assertDocOpEquals(expected, actual); } { doc = Document.createFromString("a"); DocOp actual = delete(0, 0, 1); DocOp expected = builder.d("a").rl(1).b(); assertDocOpEquals(expected, actual); } // One/two-line documents and mutations with newlines { doc = Document.createFromString(""); DocOp actual = insert(0, 0, "\n"); DocOp expected = builder.i("\n").rl(1).b(); assertDocOpEquals(expected, actual); } { doc = Document.createFromString("\n"); DocOp actual = delete(0, 0, 1); DocOp expected = builder.d("\n").rl(1).b(); assertDocOpEquals(expected, actual); } // Multiple line documents { doc = Document.createFromString("\n\n"); DocOp actual = insert(0, 0, "\n"); DocOp expected = builder.i("\n").eolR(1).rl(2).b(); assertDocOpEquals(expected, actual); } { doc = Document.createFromString("\n\n"); DocOp actual = insert(0, 0, "\n\n"); DocOp expected = builder.i("\n").i("\n").eolR(1).rl(2).b(); assertDocOpEquals(expected, actual); } { doc = Document.createFromString("\n\n"); DocOp actual = delete(0, 0, 1); DocOp expected = builder.d("\n").eolR(1).rl(1).b(); assertDocOpEquals(expected, actual); } { doc = Document.createFromString("\n\n"); DocOp actual = delete(0, 0, 2); DocOp expected = builder.d("\n").d("\n").rl(1).b(); assertDocOpEquals(expected, actual); } // Misc { doc = Document.createFromString("a\n"); DocOp actual = insert(0, 0, "a"); DocOp expected = builder.i("a").eolR(2).rl(1).b(); assertDocOpEquals(expected, actual); } } public void testComposer() { DocOp a, b; // Insert vs Delete a = builder.i("a").b(); b = builder.d("a").rl(1).b(); assertCompose(builder.rl(1).b(), a, b); a = builder.i("a\n").rl(1).b(); b = builder.d("a\n").rl(1).b(); assertCompose(builder.rl(1).b(), a, b); a = builder.i("a\n").rl(1).b(); b = builder.d("a").rl(2).b(); assertCompose(builder.i("\n").rl(1).b(), a, b); // Delete vs Insert a = builder.d("a").rl(1).b(); b = builder.i("a").b(); assertCompose(builder.d("a").i("a").b(), a, b); a = builder.d("\n").rl(1).b(); b = builder.i("a").b(); assertCompose(builder.d("\n").i("a").b(), a, b); a = builder.d("\n").rl(1).b(); b = builder.i("\n").rl(1).b(); assertCompose(builder.d("\n").i("\n").rl(1).b(), a, b); // Insert vs Insert a = builder.i("\n").rl(1).b(); b = builder.i("\n").rl(2).b(); assertCompose(builder.i("\n").i("\n").rl(1).b(), a, b); a = builder.i("a").b(); b = builder.r(1).i("\n").rl(1).b(); assertCompose(builder.i("a\n").rl(1).b(), a, b); a = builder.i("\n").rl(1).b(); b = builder.i("a").rl(2).b(); assertCompose(builder.i("a\n").rl(1).b(), a, b); // Insert vs (Retain or RetainLine) a = builder.i("\n").rl(1).b(); b = builder.eolR(1).rl(1).b(); assertCompose(a, a, b); a = builder.i("\n").i("\n").rl(1).b(); b = builder.eolR(1).eolR(1).rl(1).b(); assertCompose(a, a, b); a = builder.i("\n").rl(1).b(); b = builder.rl(2).b(); assertCompose(a, a, b); a = builder.i("abc\n").rl(1).b(); b = builder.eolR(4).rl(1).b(); assertCompose(a, a, b); // Delete vs (Retain or RetainLine) a = builder.d("a").rl(1).b(); b = builder.rl(1).b(); assertCompose(a, a, b); a = builder.d("\n").rl(1).b(); b = builder.rl(1).b(); assertCompose(a, a, b); a = builder.d("abc\n").rl(1).b(); b = builder.rl(1).b(); assertCompose(a, a, b); a = builder.d("\n").d("\n").rl(1).b(); b = builder.rl(1).b(); assertCompose(a, a, b); // Retain vs (RetainLine or Retain) a = builder.eolR(1).rl(1).b(); b = builder.rl(2).b(); assertCompose(builder.rl(2).b(), a, b); a = builder.eolR(1).rl(1).b(); assertCompose(builder.rl(2).b(), a, a); a = builder.eolR(1).rl(1).b(); b = builder.rl(2).b(); assertCompose(builder.rl(2).b(), a, b); // (Retain or RetainLine) vs Delete a = builder.eolR(2).rl(1).b(); b = builder.d("a").eolR(1).rl(1).b(); assertCompose(builder.d("a").eolR(1).rl(1).b(), a, b); a = builder.eolR(2).rl(1).b(); b = builder.d("a").rl(2).b(); assertCompose(builder.d("a").eolR(1).rl(1).b(), a, b); a = builder.rl(2).b(); b = builder.d("a").eolR(1).rl(1).b(); assertCompose(builder.d("a").eolR(1).rl(1).b(), a, b); a = builder.rl(2).b(); b = builder.d("a").rl(2).b(); assertCompose(builder.d("a").rl(2).b(), a, b); } private DocOp delete(int lineNumber, int column, int deleteCount) { return asDocOp(doc.deleteText(doc.getLineFinder().findLine(0).line(), column, deleteCount)); } private DocOp insert(int lineNumber, int column, String text) { return asDocOp(doc.insertText(doc.getLineFinder().findLine(0).line(), column, text)); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/DocOpApplierTests.java
javatests/com/google/collide/shared/ot/DocOpApplierTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.ot; import static com.google.collide.shared.ot.DocOpApplierTests.Operation.DELETE; import static com.google.collide.shared.ot.DocOpApplierTests.Operation.INSERT; import com.google.collide.dto.server.ServerDocOpFactory; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.DocumentMutator; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.TextChange; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.util.List; /** * Tests for {@link DocOpApplier}. * */ public class DocOpApplierTests extends TestCase { public enum Operation { DELETE, INSERT } private class MockDocumentMutator implements DocumentMutator { private int index; private List<Operation> operations = Lists.newArrayList(); private List<Position> positions = Lists.newArrayList(); private List<String> texts = Lists.newArrayList(); public MockDocumentMutator(Object... alternatingPositionOperationAndText) { for (int i = 0; i < alternatingPositionOperationAndText.length;) { int lineNumber = (Integer) alternatingPositionOperationAndText[i++]; int column = (Integer) alternatingPositionOperationAndText[i++]; positions.add(createPosition(lineNumber, column)); operations.add((Operation) alternatingPositionOperationAndText[i++]); texts.add((String) alternatingPositionOperationAndText[i++]); } } private Position createPosition(int lineNumber, int column) { return new Position(doc.getLineFinder().findLine(lineNumber), column); } @Override public TextChange deleteText(Line line, int column, int deleteCount) { throw new IllegalStateException( "DocOpApplier knows its line number and should not call the inefficient deleteText"); } @Override public TextChange deleteText(Line line, int lineNumber, int column, int deleteCount) { assertPosition(line, lineNumber, column); assertEquals(operations.get(index), DELETE); assertEquals(texts.get(index).length(), deleteCount); index++; return doc.deleteText(line, lineNumber, column, deleteCount); } @Override public TextChange insertText(Line line, int column, String text) { throw new IllegalStateException( "DocOpApplier knows its line number and should not call the inefficient insertText"); } @Override public TextChange insertText(Line line, int lineNumber, int column, String text) { assertPosition(line, lineNumber, column); assertEquals(operations.get(index), INSERT); assertEquals(texts.get(index), text); index++; return doc.insertText(line, lineNumber, column, text); } @Override public TextChange insertText(Line line, int lineNumber, int column, String text, boolean canReplaceSelection) { // This mutator impl does not care to replace the selection return insertText(line, lineNumber, column, text); } private void assertPosition(Line line, int lineNumber, int column) { assertEquals(positions.get(index).getLine(), line); assertEquals(positions.get(index).getLineNumber(), lineNumber); assertEquals(positions.get(index).getColumn(), column); } } private Document doc = Document.createFromString(""); private TerseDocOpBuilder b = new TerseDocOpBuilder(ServerDocOpFactory.INSTANCE, false); public void testVerySimpleInsertion() { DocOpApplier.apply(b.i("a").b(), doc, new MockDocumentMutator(0, 0, INSERT, "a")); } public void testMultilineSimpleInsertion() { DocOpApplier.apply(b.i("a\n").i("b\n").b(), doc, new MockDocumentMutator(0, 0, INSERT, "a\nb\n")); } public void testMultilineSimpleMutations() { DocOpApplier.apply(b.i("a\n").i("b\n").b(), doc, new MockDocumentMutator(0, 0, INSERT, "a\nb\n")); DocOpApplier.apply(b.d("a\n").d("b\n").i("c\n").i("d").b(), doc, new MockDocumentMutator(0, 0, DELETE, "a\nb\n", 0, 0, INSERT, "c\nd")); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/ComposerTests.java
javatests/com/google/collide/shared/ot/ComposerTests.java
package com.google.collide.shared.ot; import static com.google.collide.shared.ot.DocOpTestUtils.assertCompose; import static com.google.collide.shared.ot.DocOpTestUtils.assertComposeFails; import com.google.collide.dto.DocOp; import com.google.collide.dto.server.ServerDocOpFactory; import com.google.collide.shared.document.Document; import com.google.collide.shared.ot.Composer.ComposeException; import com.google.collide.shared.util.StringUtils; import junit.framework.TestCase; /** * Tests for the document operation composer. * */ public class ComposerTests extends TestCase { private static final String[] LINES = {"Hello world\n", "Foo bar\n", "Something else\n"}; private Document doc; private TerseDocOpBuilder builder; public void testOneLastRetainLineMatchesOtherLastComponentWithoutNewline() { { DocOp a = builder.rl(1).b(); DocOp b = builder.r(14).b(); assertCompose(b, a, b); } { DocOp a = builder.rl(1).b(); DocOp b = builder.d("test").b(); assertCompose(b, a, b); } { DocOp a = builder.r(14).b(); DocOp b = builder.rl(1).b(); assertCompose(a, a, b); } { DocOp a = builder.i("test").b(); DocOp b = builder.rl(1).b(); assertCompose(a, a, b); } } public void testNonRetainLineComposition() { // R(1) o I(i),R(1) assertCompose(builder.i("i").r(1).b(), builder.r(1).b(), builder.i("i").r(1).b()); // R(1) o R(1),I(i) assertCompose(builder.r(1).i("i").b(), builder.r(1).b(), builder.r(1).i("i").b()); // D(h) o I(i) assertCompose(builder.d("h").i("i").b(), builder.d("h").b(), builder.i("i").b()); // I(h) o R(1),I(i) assertCompose(builder.i("hi").b(), builder.i("h").b(), builder.r(1).i("i").b()); // R(1) o D(i) assertCompose(builder.d("i").b(), builder.r(1).b(), builder.d("i").b()); // D(h),R(1) o D(i) assertCompose(builder.d("hi").b(), builder.d("h").r(1).b(), builder.d("i").b()); // I(h),R(1) o R(1),D(i) assertCompose(builder.i("h").d("i").b(), builder.i("h").r(1).b(), builder.r(1).d("i").b()); } public void testRetainLineIndependent() { DocOp a = builder.i("a\n").rl(1).b(); DocOp b = builder.rl(2).i("b\n").b(); assertCompose(builder.i("a\n").rl(1).i("b\n").b(), a, b); a = builder.d("a\n").rl(1).b(); b = builder.i("b").eolR(1).b(); assertCompose(builder.d("a\n").i("b").eolR(1).b(), a, b); a = builder.d("a\n").rl(2).b(); b = builder.rl(1).i("b").eolR(1).b(); assertCompose(builder.d("a\n").rl(1).i("b").eolR(1).b(), a, b); } public void testRetainLineOverlapping() { DocOp a = builder.rl(1).i("a").eolR(1).rl(1).b(); DocOp b = builder.rl(1).r(1).i("b").eolR(1).rl(1).b(); assertCompose(builder.rl(1).i("ab").eolR(1).rl(1).b(), a, b); } public void testAdjacentLineModifications() { { DocOp a = builder.rl(1).i("b").eolR(1).b(); DocOp b = builder.i("b").eolR(1).rl(1).b(); assertCompose(builder.i("b").eolR(1).i("b").eolR(1).b(), a, b); } { DocOp a = builder.rl(15).r(3).i("b").eolR(1).rl(3).b(); DocOp b = builder.rl(14).r(1).i("b").eolR(1).rl(4).b(); assertCompose(builder.rl(14).r(1).i("b").eolR(1).r(3).i("b").eolR(1).rl(3).b(), a, b); } } public void testRetainLineCanStartMidline() { { /* * Retain line will retain an empty string (this composition was * discovered in the real world) */ DocOp a = builder.r(1).i("a").b(); DocOp b = builder.r(1).d("a").rl(1).b(); assertCompose(builder.r(1).rl(1).b(), a, b); } } public void testRetainLineAndInsertPlayNice() { { DocOp a = builder.rl(2).r(5).i("en").eolR(1).rl(1).b(); DocOp b = builder.rl(3).r(1).i("tu").b(); DocOp expected = builder.rl(2).r(5).i("en").eolR(1).r(1).i("tu").b(); assertCompose(expected, a, b); } { DocOp a = builder.rl(2).r(1).i("ip").eolR(1).rl(3).b(); DocOp b = builder.rl(5).r(1).i("is").b(); DocOp expected = builder.rl(2).r(1).i("ip").eolR(1).rl(2).r(1).i("is").b(); assertCompose(expected, a, b); } } public void testThatIncorrectCompositionFails() { { DocOp a = builder.i("test").b(); DocOp b = builder.rl(50).rl(1).b(); assertComposeFails(a, b); } { DocOp a = builder.i("test").b(); DocOp b = builder.rl(1).rl(1).b(); assertComposeFails(a, b); } } public void testADeletesAndBInserts() { { DocOp a = builder.d("hello").d("world").b(); DocOp b = builder.i("foo").i("bar").b(); DocOp expected = builder.d("helloworld").i("foobar").b(); assertCompose(expected, a, b); } } public void testPositionMigratorCompositionFailure() throws ComposeException { { // Simplified test case // This tickles the path through ProcessingBForAInsert DocOp a = builder.i("\n").b(); DocOp b = builder.rl(2).b(); DocOp expected = builder.i("\n").b(); assertCompose(expected, a, b); } { // Simplified test case // This tickles the path through ProcessingBForAInsert DocOp a = builder.i("\n").b(); DocOp b = builder.rl(1).b(); DocOp expected = builder.i("\n").b(); assertCompose(expected, a, b); } { // Simplified test case // This tickles the path through ProcessingBForAInsert DocOp a = builder.i("abc\n").i("def\n").b(); DocOp b = builder.d("a").eolR(3).rl(2).b(); DocOp expected = builder.i("bc\n").i("def\n").b(); assertCompose(expected, a, b); } { // Simplified test case // This tickles the path through ProcessingAForBRetainLine DocOp a = builder.i("abc\n").i("def\n").b(); DocOp b = builder.rl(3).b(); DocOp expected = builder.i("abc\n").i("def\n").b(); assertCompose(expected, a, b); } { // This should fail DocOp a = builder.i("\n").b(); DocOp b = builder.rl(3).b(); assertComposeFails(a, b); } { // This should fail DocOp a = builder.i("\n").i("\n").b(); DocOp b = builder.rl(4).b(); assertComposeFails(a, b); } { // Related test case DocOp a = builder.i("abc\n").r(5).b(); DocOp b = builder.rl(2).b(); DocOp expected = builder.i("abc\n").r(5).b(); assertCompose(expected, a, b); } { // Full test case DocOp a = builder.d("var f = function() {\n"). d(" alert(\"foo!\");\n"). d("}\n"). d("\n"). d("f();\n"). i("d3.svg.diagonal = function() {\n"). i(" var source = d3_svg_chordSource,\n"). i(" target = d3_svg_chordTarget,\n"). i(" projection = d3_svg_diagonalProjection;\n"). i("\n"). i(" function diagonal(d, i) {\n"). i(" var p0 = source.call(this, d, i),\n"). i(" p3 = target.call(this, d, i),\n"). i(" m = (p0.y + p3.y) / 2,\n"). i(" p = [p0, {x: p0.x, y: m}, {x: p3.x, y: m}, p3];\n"). i(" p = p.map(projection);\n"). i(" return \"M\" + p[0] + \"C\" + p[1] + \" \" + p[2] + \" \" + p[3];\n"). i(" }\n"). i("\n"). i(" diagonal.source = function(x) {\n"). i(" if (!arguments.length) return source;\n"). i(" source = d3.functor(x);\n"). i(" return diagonal;\n"). i(" };\n"). i("\n"). i(" diagonal.target = function(x) {\n"). i(" if (!arguments.length) return target;\n"). i(" target = d3.functor(x);\n"). i(" return diagonal;\n"). i(" };\n"). i("\n"). i(" diagonal.projection = function(x) {\n"). i(" if (!arguments.length) return projection;\n"). i(" projection = x;\n"). i(" return diagonal;\n"). i(" };\n"). i("\n"). i(" return diagonal;\n"). i("};\n").b(); DocOp b = builder.d("d3.svg.").eolR(24).rl(34).b(); DocOpTestUtils.compose(a, b); } } public void testUnicodeCompositionFailure() { { /* * Simplified test case so we don't deal with the long unicode escape * sequences */ DocOp a = builder .rl(1) .d("a").i("abcde").eolR(5) .d("abcde").i("abcde").eolR(5) .rl(1) .b(); DocOp b = builder .d("abcde\n") .d("abcdeabcd\n") .d("abcdeabcd\n") .b(); DocOp expected = builder .d("abcde\n") .d("aabcd\n") .d("abcdeabcd\n") .b(); assertCompose(expected, a, b); } { DocOp a = builder.rl(1).b(); DocOp b = builder.b(); DocOp expected = builder.b(); assertCompose(expected, a, b); } } public void testProcessingBForAFinishedMightBeTooLeniant() { { // This makes sense DocOp a = builder.i("a").b(); DocOp b = builder.rl(1).b(); assertCompose(a, a, b); } { // This doesn't DocOp a = builder.i("a").b(); DocOp b = builder.rl(2).b(); assertComposeFails(a, b); } { // This makes sense DocOp a = builder.i("\n").b(); DocOp b = builder.rl(2).b(); assertCompose(a, a, b); } { // This doesn't DocOp a = builder.i("\n").b(); DocOp b = builder.rl(3).b(); assertComposeFails(a, b); } { // This makes sense DocOp a = builder.r(1).b(); DocOp b = builder.rl(1).b(); assertCompose(a, a, b); } { // This doesn't DocOp a = builder.r(1).b(); DocOp b = builder.rl(2).b(); assertComposeFails(a, b); } { // This makes sense DocOp a = builder.eolR(1).b(); DocOp b = builder.rl(2).b(); // It will compact the r("\n") to rl(1) DocOp expected = builder.rl(1).b(); assertCompose(expected, a, b); } { // This doesn't DocOp a = builder.eolR(1).b(); DocOp b = builder.rl(3).b(); assertComposeFails(a, b); } } public void testRetainLastLineNotCancelledStillSucceeds() { { DocOp a = builder.i("a").d("b").b(); DocOp b = builder.rl(1).b(); DocOp expected = builder.i("a").d("b").b(); assertCompose(expected, a, b); } { DocOp a = builder.rl(1).i("hh\n").i("ii").d("hh\n").d("ii").b(); DocOp b = builder.rl(1).i("hh\n").i("ii\n").eolR(3).rl(1).b(); DocOp expected = builder.rl(1).i("hh\n").i("ii\n").i("hh\n").i("ii").d("hh\n").d("ii").b(); DocOpTestUtils.assertCompose(expected, a, b); } } @Override protected void setUp() throws Exception { builder = new TerseDocOpBuilder(ServerDocOpFactory.INSTANCE, false); doc = Document.createEmpty(); doc.insertText(doc.getFirstLine(), 0, StringUtils.join(LINES, "")); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/PositionMigratorTests.java
javatests/com/google/collide/shared/ot/PositionMigratorTests.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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.google.collide.shared.ot; import com.google.collide.dto.server.ServerDocOpFactory; import junit.framework.TestCase; public class PositionMigratorTests extends TestCase { private TerseDocOpBuilder b; public void testDeleteDocOpScenarios() { { // Deletion before position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.d("h").b()); assertPositionTransformerEquals(0, 4, transformer); } { // Deletion ending at position PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.d("h").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion containing position PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.d("hello").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion after position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.r(5).d("hello").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion with newline before position on next line PositionTransformer transformer = new PositionTransformer(1, 1); transformer.transform(b.d("hello\n").b()); assertPositionTransformerEquals(0, 1, transformer); } { // Deletion with newline after position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.r(5).d("hello\n").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion with newline where position is on newline PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.d("h\n").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Deletion with newline where position is on newline PositionTransformer transformer = new PositionTransformer(5, 1); transformer.transform(b.rl(3).d("\n").rl(5).b()); assertPositionTransformerEquals(4, 1, transformer); } } public void testInsertDocOpScenarios() { { // Insertion before position PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.i("hello").b()); assertPositionTransformerEquals(0, 6, transformer); } { // Insertion at position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.i("hello").b()); assertPositionTransformerEquals(0, 5, transformer); } { // Insertion after position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.r(5).i("hello").b()); assertPositionTransformerEquals(0, 0, transformer); } { // Insertion with newline before position PositionTransformer transformer = new PositionTransformer(0, 1); transformer.transform(b.i("hello\n").b()); assertPositionTransformerEquals(1, 1, transformer); } { // Insertion with newline before position PositionTransformer transformer = new PositionTransformer(4, 1); transformer.transform(b.i("hello\n").b()); assertPositionTransformerEquals(5, 1, transformer); } { // Insertion with newline at position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.i("hello\n").b()); assertPositionTransformerEquals(1, 0, transformer); } { // Insertion with newline after position PositionTransformer transformer = new PositionTransformer(0, 0); transformer.transform(b.r(5).i("hello\n").b()); assertPositionTransformerEquals(0, 0, transformer); } } public void testRetainDocOpScenarios() { { // Retain before position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.r(4).b()); assertPositionTransformerEquals(0, 5, transformer); } { // Retain surrounding position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.r(40).b()); assertPositionTransformerEquals(0, 5, transformer); } { /* * Retain after position (this is an odd test case, but just ensuring the * r(40) doesn't affect anything) */ PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.r(10).r(40).b()); assertPositionTransformerEquals(0, 5, transformer); } { // Retain with newline containing position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.eolR(40).b()); assertPositionTransformerEquals(0, 5, transformer); } } public void testRetainLineDocOpScenarios() { { // Retain line before position PositionTransformer transformer = new PositionTransformer(4, 5); transformer.transform(b.rl(2).b()); assertPositionTransformerEquals(4, 5, transformer); } { // Retain line surrounding position PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.rl(40).b()); assertPositionTransformerEquals(0, 5, transformer); } { /* * Retain line after position (this is an odd test case, but just ensuring * the rl(40) doesn't affect anything) */ PositionTransformer transformer = new PositionTransformer(0, 5); transformer.transform(b.eolR(10).rl(40).b()); assertPositionTransformerEquals(0, 5, transformer); } } @Override protected void setUp() throws Exception { b = new TerseDocOpBuilder(ServerDocOpFactory.INSTANCE, false); } private static void assertPositionTransformerEquals(int expectedLineNumber, int expectedColumn, PositionTransformer positionTransformer) { assertEquals(expectedLineNumber, positionTransformer.getLineNumber()); assertEquals(expectedColumn, positionTransformer.getColumn()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/ot/TransformerTests.java
javatests/com/google/collide/shared/ot/TransformerTests.java
package com.google.collide.shared.ot; import static com.google.collide.shared.ot.DocOpTestUtils.assertDocOpEquals; import com.google.collide.dto.DocOp; import com.google.collide.dto.server.ServerDocOpFactory; import junit.framework.TestCase; import org.waveprotocol.wave.model.operation.OperationPair; /** * Tests for the document operation transformer. */ public class TransformerTests extends TestCase { private final class ReversibleTestParameters extends TestParameters { ReversibleTestParameters(DocOp clientMutation, DocOp serverMutation, DocOp transformedClientMutation, DocOp transformedServerMutation) { super(clientMutation, serverMutation, transformedClientMutation, transformedServerMutation); } @Override void run() throws Exception { singleTest(clientMutation, serverMutation, transformedClientMutation, transformedServerMutation); singleTest(serverMutation, clientMutation, transformedServerMutation, transformedClientMutation); } } private class TestParameters { final DocOp clientMutation; final DocOp serverMutation; final DocOp transformedClientMutation; final DocOp transformedServerMutation; TestParameters(DocOp clientMutation, DocOp serverMutation, DocOp transformedClientMutation, DocOp transformedServerMutation) { this.clientMutation = clientMutation; this.serverMutation = serverMutation; this.transformedClientMutation = transformedClientMutation; this.transformedServerMutation = transformedServerMutation; } void run() throws Exception { singleTest(clientMutation, serverMutation, transformedClientMutation, transformedServerMutation); } } private static final String N = "\n"; private static final String FIVE_N = "12345\n"; private static final String TEN_N = "abcdefghij\n"; private static final String TWENTY_N = "12345678901234567890\n"; private static final String FIVE = "12345"; private static final String TEN = "abcdefghij"; private static final String TWENTY = "12345678901234567890"; private DocOpCreator docOpCreator; private ServerDocOpFactory factory; private TerseDocOpBuilder dob; /** * Performs tests for transforming text deletions against text deletions. */ public void testDeleteVsDelete() throws Exception { // A's deletion spatially before B's deletion new ReversibleTestParameters(docOpCreator.delete(20, 1, "abcde"), docOpCreator.delete(20, 7, "fg"), docOpCreator.delete(18, 1, "abcde"), docOpCreator.delete(15, 2, "fg")).run(); // A's deletion spatially adjacent to and before B's deletion new ReversibleTestParameters(docOpCreator.delete(20, 1, "abcde"), docOpCreator.delete(20, 6, "fg"), docOpCreator.delete(18, 1, "abcde"), docOpCreator.delete(15, 1, "fg")).run(); // A's deletion overlaps B's deletion new ReversibleTestParameters(docOpCreator.delete(20, 1, "abcde"), docOpCreator.delete(20, 3, "cdefghi"), docOpCreator.delete(13, 1, "ab"), docOpCreator.delete(15, 1, "fghi")).run(); // A's deletion a subset of B's deletion new ReversibleTestParameters(docOpCreator.delete(20, 1, "abcdefg"), docOpCreator.delete(20, 3, "cd"), docOpCreator.delete(18, 1, "abefg"), dob.rl(1).b()).run(); // A's deletion identical to B's deletion new ReversibleTestParameters(docOpCreator.delete(20, 1, "abcdefg"), docOpCreator.delete(20, 1, "abcdefg"), dob.rl(1).b(), dob.rl(1).b()).run(); } /** * Performs tests for transforming text insertions against text deletions. */ public void testInsertVsDelete() throws Exception { // A's insertion spatially before B's deletion new ReversibleTestParameters(docOpCreator.insert(20, 1, "abc"), docOpCreator.delete(20, 2, "de"), docOpCreator.insert(18, 1, "abc"), docOpCreator.delete( 23, 5, "de")).run(); // A's insertion spatially inside B's deletion new ReversibleTestParameters(docOpCreator.insert(20, 2, "abc"), docOpCreator.delete(20, 1, "ce"), docOpCreator.insert(18, 1, "abc"), new DocOpBuilder( factory, false).retain(1, false).delete("c").retain(3, false).delete("e") .retain(17, true).build()).run(); // A's insertion spatially at the start of B's deletion new ReversibleTestParameters(docOpCreator.insert(20, 1, "abc"), docOpCreator.delete(20, 1, "de"), docOpCreator.insert(18, 1, "abc"), docOpCreator.delete( 23, 4, "de")).run(); // A's insertion spatially at the end of B's deletion new ReversibleTestParameters(docOpCreator.insert(20, 3, "abc"), docOpCreator.delete(20, 1, "de"), docOpCreator.insert(18, 1, "abc"), docOpCreator.delete( 23, 1, "de")).run(); // A's insertion spatially after B's deletion new ReversibleTestParameters(docOpCreator.insert(20, 4, "abc"), docOpCreator.delete(20, 1, "de"), docOpCreator.insert(18, 2, "abc"), docOpCreator.delete( 23, 1, "de")).run(); } /** * Performs tests for transforming text insertions against text insertions. */ public void testInsertVsInsert() throws Exception { // A's insertion spatially before B's insertion new ReversibleTestParameters(docOpCreator.insert(20, 1, "a"), docOpCreator.insert(20, 2, "1"), docOpCreator.insert(21, 1, "a"), docOpCreator.insert(21, 3, "1")).run(); // client's insertion spatially at the same location as server's insertion new TestParameters(docOpCreator.insert(20, 2, "abc"), docOpCreator.insert(20, 2, "123"), docOpCreator.insert(23, 2, "abc"), docOpCreator.insert(23, 5, "123")).run(); } public void testMultiLineDeleteVsDelete() throws Exception { { // Deletion above another deletion DocOp c = dob.d(TEN_N).d(TEN_N).d(TEN).eolR(5).rl(10).b(); DocOp s = dob.rl(5).d(FIVE_N).d(FIVE_N).d(FIVE_N).rl(5).b(); DocOp cPrime = dob.d(TEN_N).d(TEN_N).d(TEN).eolR(5).rl(7).b(); DocOp sPrime = dob.rl(3).d(FIVE_N).d(FIVE_N).d(FIVE_N).rl(5).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Deletion above another deletion (lines adjacent) DocOp c = dob.d(TEN_N).d(TEN_N).d(TEN_N).rl(10).b(); DocOp s = dob.rl(3).d(FIVE_N).d(FIVE_N).d(FIVE_N).rl(7).b(); DocOp cPrime = dob.d(TEN_N).d(TEN_N).d(TEN_N).rl(7).b(); DocOp sPrime = dob.d(FIVE_N).d(FIVE_N).d(FIVE_N).rl(7).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // TODO: the delete brought a RL onto a previously modified // line, is this legal? // Deletion above another deletion (characters adjacent) DocOp c = dob.d(TEN_N).d(TEN_N).d(TEN).eolR(6).rl(10).b(); DocOp s = dob.rl(2).r(10).d(FIVE_N).d(FIVE_N).d(FIVE_N).rl(8).b(); DocOp cPrime = dob.d(TEN_N).d(TEN_N).d(TEN).rl(8).b(); DocOp sPrime = dob.d(FIVE_N).d(FIVE_N).d(FIVE_N).rl(8).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Overlapping deletions (line granularity) DocOp c = dob.d(TEN_N).d(TEN_N).d(TEN_N).rl(10).b(); DocOp s = dob.rl(2).d(TEN_N).d(FIVE_N).d(FIVE_N).rl(8).b(); DocOp cPrime = dob.d(TEN_N).d(TEN_N).rl(8).b(); DocOp sPrime = dob.d(FIVE_N).d(FIVE_N).rl(8).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Overlapping deletions (character granularity) DocOp c = dob.d(TEN_N).d(TEN_N).d(TEN).eolR(1).rl(10).b(); DocOp s = dob.rl(2).d(TEN_N).d(FIVE_N).d(FIVE_N).rl(8).b(); DocOp cPrime = dob.d(TEN_N).d(TEN_N).rl(8).b(); DocOp sPrime = dob.d(N).d(FIVE_N).d(FIVE_N).rl(8).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Subset deletions (character granularity) DocOp c = dob.d(TEN_N).d(TEN_N).b(); DocOp s = dob.rl(1).d(TEN).eolR(1).b(); DocOp cPrime = dob.d(TEN_N).d(N).b(); DocOp sPrime = dob.b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Identical deletions DocOp c = dob.d(TEN_N).d(TEN_N).b(); DocOp s = c; DocOp cPrime = dob.b(); DocOp sPrime = cPrime; new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } } public void testMultiLineInsertVsDelete() throws Exception { { // Insertion above deletion DocOp c = dob.rl(2).i(FIVE_N).rl(2).b(); DocOp s = dob.rl(3).d(TEN_N).b(); DocOp cPrime = dob.rl(2).i(FIVE_N).rl(1).b(); DocOp sPrime = dob.rl(4).d(TEN_N).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Insertion above deletion, but adjacent lines DocOp c = dob.rl(2).i(FIVE_N).rl(1).b(); DocOp s = dob.rl(2).d(TEN_N).b(); DocOp cPrime = dob.rl(2).i(FIVE_N).b(); DocOp sPrime = dob.rl(3).d(TEN_N).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Insertion above/adjacent deletion (the last character of insertion is // adjacent to first character of deletion) DocOp c = dob.rl(2).i(FIVE_N).i(FIVE).eolR(11).rl(1).b(); DocOp s = dob.rl(2).d(TEN_N).d(TEN_N).b(); DocOp cPrime = dob.rl(2).i(FIVE_N).i(FIVE).b(); DocOp sPrime = dob.rl(3).r(5).d(TEN_N).d(TEN_N).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Insertion above/adjacent deletion (the last character of insertion is // adjacent to first character of deletion) DocOp c = dob.rl(2).i(FIVE_N).i(FIVE).eolR(11).rl(1).b(); DocOp s = dob.rl(2).d(TEN_N).d(TEN_N).b(); DocOp cPrime = dob.rl(2).i(FIVE_N).i(FIVE).b(); DocOp sPrime = dob.rl(3).r(5).d(TEN_N).d(TEN_N).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Insertion inside deletion DocOp c = dob.rl(2).i(FIVE_N).i(FIVE_N).rl(2).b(); DocOp s = dob.d(TEN_N).d(TEN_N).d(TEN_N).d(TEN_N).b(); DocOp cPrime = dob.i(FIVE_N).i(FIVE_N).b(); DocOp sPrime = dob.d(TEN_N).d(TEN_N).rl(2).d(TEN_N).d(TEN_N).b(); new TestParameters(c, s, cPrime, sPrime).run(); } { // Insertion starts right after the last char deleted DocOp c = dob.rl(1).r(10).i(FIVE_N).i(FIVE).eolR(2).rl(3).b(); DocOp s = dob.d(TEN_N).d(TEN).eolR(2).rl(3).b(); DocOp cPrime = dob.i(FIVE_N).i(FIVE).eolR(2).rl(3).b(); DocOp sPrime = dob.d(TEN_N).d(TEN).eolR(6).rl(4).b(); new TestParameters(c, s, cPrime, sPrime).run(); } { // Insertion starts on the line after the last line deleted DocOp c = dob.rl(4).r(10).i(FIVE_N).i(FIVE).eolR(2).rl(3).b(); DocOp s = dob.d(TEN_N).d(TEN).eolR(2).rl(6).b(); DocOp cPrime = dob.rl(3).r(10).i(FIVE_N).i(FIVE).eolR(2).rl(3).b(); DocOp sPrime = dob.d(TEN_N).d(TEN).eolR(2).rl(7).b(); new TestParameters(c, s, cPrime, sPrime).run(); } { // Insertion is later in the document DocOp c = dob.rl(5).i(FIVE_N).i(FIVE_N).b(); DocOp s = dob.d(TEN_N).d(TEN_N).rl(3).b(); DocOp cPrime = dob.rl(3).i(FIVE_N).i(FIVE_N).b(); DocOp sPrime = dob.d(TEN_N).d(TEN_N).rl(5).b(); new TestParameters(c, s, cPrime, sPrime).run(); } } public void testMultiLineInsertVsInsert() throws Exception { { // Simple test of a insertion with newline DocOp c = dob.rl(3).b(); DocOp s = dob.rl(1).i(TEN_N).eolR(1).rl(1).b(); DocOp cPrime = dob.rl(4).b(); DocOp sPrime = dob.rl(1).i(TEN_N).eolR(1).rl(1).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion spatially above B's insertion (simpler to trap bug) DocOp c = dob.rl(5).i(FIVE_N).i(FIVE_N).i(TEN).eolR(1).rl(4).b(); DocOp s = dob.rl(8).i(TEN_N).i(TWENTY_N).rl(2).b(); DocOp cPrime = dob.rl(5).i(FIVE_N).i(FIVE_N).i(TEN).eolR(1).rl(6).b(); DocOp sPrime = dob.rl(10).i(TEN_N).i(TWENTY_N).rl(2).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion spatially above B's insertion DocOp c = dob.rl(5).r(3).i(FIVE_N).i(FIVE_N).i(TEN).eolR(5).rl(4).b(); DocOp s = dob.rl(8).i(TEN_N).i(TWENTY_N).rl(2).b(); DocOp cPrime = dob.rl(5).r(3).i(FIVE_N).i(FIVE_N).i(TEN).eolR(5).rl(6).b(); DocOp sPrime = dob.rl(10).i(TEN_N).i(TWENTY_N).rl(2).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's retain gets cut short by B's newline insertion DocOp c = dob.eolR(5).b(); DocOp s = dob.r(2).i(FIVE_N).eolR(3).b(); DocOp cPrime = dob.eolR(8).eolR(3).b(); DocOp sPrime = dob.r(2).i(FIVE_N).eolR(3).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion's last line touched is the same as B's insertion's first // line touched DocOp c = dob.rl(5).i(FIVE_N).i(FIVE_N).i(TEN).eolR(5).rl(5).b(); DocOp s = dob.rl(5).r(2).i(TEN_N).i(TWENTY_N).eolR(3).rl(5).b(); DocOp cPrime = dob.rl(5).i(FIVE_N).i(FIVE_N).i(TEN).eolR(13).eolR(21).eolR(3).rl(5).b(); DocOp sPrime = dob.rl(5).eolR(6).eolR(6).r(12).i(TEN_N).i(TWENTY_N).eolR(3).rl(5).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion's last character is adjacent to B's insertion's first // character (simplified) DocOp c = dob.i(FIVE_N).i(FIVE_N).b(); DocOp s = dob.i(TEN_N).i(TEN_N).b(); DocOp cPrime = dob.i(FIVE_N).i(FIVE_N).rl(2).b(); DocOp sPrime = dob.rl(2).i(TEN_N).i(TEN_N).b(); new TestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion's last character is adjacent to B's insertion's first // character DocOp c = dob.rl(5).i(FIVE_N).i(FIVE_N).i(TEN).eolR(1).rl(5).b(); DocOp s = dob.rl(5).i(TEN_N).i(TWENTY_N).rl(6).b(); DocOp cPrime = dob.rl(5).i(FIVE_N).i(FIVE_N).i(TEN).eolR(11).rl(7).b(); DocOp sPrime = dob.rl(7).r(10).i(TEN_N).i(TWENTY_N).rl(6).b(); new TestParameters(c, s, cPrime, sPrime).run(); } } public void testRetainLineMatchingOtherNonEmptyLastLine() throws Exception { { // Tests that a final retain line matches the other's non-empty last line DocOp c = dob.rl(25).r(58).i("a").eolR(35).rl(1).b(); DocOp s = dob.rl(26).r(58).i("b").b(); DocOp cPrime = c; DocOp sPrime = s; new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // Tests that a retain line for more lines than available throws exception DocOp c = dob.rl(25).r(58).i("a").eolR(35).rl(2).b(); DocOp s = dob.rl(26).r(58).i("b").b(); DocOp cPrime = c; DocOp sPrime = s; try { new ReversibleTestParameters(c, s, cPrime, sPrime).run(); fail(); } catch (Throwable t) { } } } public void testSingleLineInsertVsInsertInMultiLineDocument() throws Exception { { // Simple test of a insertion DocOp c = dob.rl(3).b(); DocOp s = dob.rl(1).i(TEN).eolR(1).rl(1).b(); DocOp cPrime = dob.rl(3).b(); DocOp sPrime = dob.rl(1).i(TEN).eolR(1).rl(1).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion spatially above B's insertion DocOp c = dob.r(5).i(FIVE).eolR(5).rl(2).b(); DocOp s = dob.rl(2).i(TEN).eolR(10).b(); DocOp cPrime = c; DocOp sPrime = s; new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion spatially directly above B's insertion DocOp c = dob.r(5).i(FIVE).eolR(5).rl(1).b(); DocOp s = dob.rl(1).i(TEN).eolR(10).b(); DocOp cPrime = c; DocOp sPrime = s; new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion spatially intertwined with B's insertion DocOp c = dob.r(5).i(FIVE).eolR(5).r(2).d(FIVE).r(4).b(); DocOp s = dob.rl(1).i(TEN).eolR(11).b(); DocOp cPrime = dob.r(5).i(FIVE).eolR(5).r(12).d(FIVE).r(4).b(); DocOp sPrime = dob.rl(1).i(TEN).eolR(6).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // A's insertion would be a subset of B's insertion if this were text // replacement DocOp c = dob.rl(2).r(5).i(FIVE).eolR(5).rl(2).b(); DocOp s = dob.rl(2).r(2).i(TWENTY).eolR(8).rl(2).b(); DocOp cPrime = dob.rl(2).r(25).i(FIVE).eolR(5).rl(2).b(); DocOp sPrime = dob.rl(2).r(2).i(TWENTY).eolR(13).rl(2).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } } public void testSubstituteRetainCountForRetainLineProcessor() throws Exception { { DocOp c = dob.rl(1).d("b").b(); DocOp s = dob.r(1).d("\n").r(1).b(); DocOp cPrime = dob.r(1).d("b").b(); DocOp sPrime = dob.r(1).d("\n").b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { DocOp c = dob.rl(1).i("a").r(1).b(); DocOp s = dob.d("aaaa").r(3).d("\n").r(1).b(); DocOp cPrime = dob.r(3).i("a").r(1).b(); DocOp sPrime = dob.d("aaaa").r(3).d("\n").r(2).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } } public void testEmptyLineVsRetainLine() throws Exception { { // rl will match empty and nothing will be transformed DocOp c = dob.b(); DocOp s = dob.rl(1).b(); DocOp cPrime = dob.b(); DocOp sPrime = dob.rl(1).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // rl will match the empty string after the retain here as well DocOp c = dob.d("\n").b(); DocOp s = dob.eolR(1).rl(1).b(); DocOp cPrime = dob.d("\n").b(); DocOp sPrime = dob.rl(1).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { // rl cannot suffix here since it can only span an entire line DocOp c = dob.r(2).d("\n").b(); DocOp s = dob.r(1).d("a").eolR(1).rl(1).b(); DocOp cPrime = dob.r(1).d("\n").b(); DocOp sPrime = dob.r(1).d("a").rl(1).b(); new ReversibleTestParameters(c, s, cPrime, sPrime).run(); } { DocOp c = dob.r(5).b(); DocOp s = dob.rl(1).b(); new ReversibleTestParameters(c, s, c, s).run(); } } /** * Real world: * A: RL(1) * A: I(a) * A: R(1)I(s) * A: R(2)I(d) * A: R(3)I(f) * A: R(4)I(A) * A: R(5)I(S) * A: R(6)I(D) * A: R(7)I(\n)RL(1) * B: R(6)I(f)R(1\n) * @throws Exception */ public void testThatTransformationDoesNotRemoveEmptyLineBeingRetainLine1() throws Exception { { DocOp s = dob.r(7).i("\n").rl(1).b(); DocOp c = dob.r(6).i("f").r(1).b(); DocOp sPrime = dob.r(8).i("\n").rl(1).b(); DocOp cPrime = dob.r(6).i("f").eolR(2).rl(1).b(); singleTest(c, s, cPrime, sPrime); } { DocOp s = dob.i("\n").rl(1).b(); DocOp c = dob.i("f").b(); DocOp cPrime = dob.i("f").eolR(1).rl(1).b(); DocOp sPrime = dob.r(1).i("\n").rl(1).b(); singleTest(c, s, cPrime, sPrime); } { DocOp s = dob.i("f").b(); DocOp c = dob.i("\n").rl(1).b(); DocOp sPrime = dob.eolR(1).i("f").b(); singleTest(c, s, c, sPrime); } { DocOp s = dob.i("\n").rl(1).b(); DocOp c = dob.i("f").r(1).b(); DocOp cPrime = dob.i("f").eolR(1).r(1).b(); DocOp sPrime = dob.r(1).i("\n").rl(1).b(); singleTest(c, s, cPrime, sPrime); } } public void testSimpleRetainLineOfEmptyLastLine() throws Exception { DocOp c = dob.i("alex\n").rl(2).b(); DocOp s = dob.i("b").eolR(1).rl(1).b(); DocOp sPrime = dob.eolR(5).i("b").eolR(1).rl(1).b(); singleTest(c, s, c, sPrime); } public void testDeleteOfEmptyLastLine() throws Exception { // alex\n // DocOp c = dob.r(4).d("\n").rl(1).b(); DocOp s = dob.i("a").eolR(5).rl(1).b(); DocOp cPrime = dob.r(5).d("\n").rl(1).b(); DocOp sPrime = dob.i("a").r(4).rl(1).b(); new ReversibleTestParameters(s, c, sPrime, cPrime).run(); } @Override protected void setUp() throws Exception { factory = ServerDocOpFactory.INSTANCE; docOpCreator = new DocOpCreator(factory); dob = new TerseDocOpBuilder(factory, true); } private void singleTest(DocOp clientMutation, DocOp serverMutation, DocOp transformedClientMutation, DocOp transformedServerMutation) throws Exception { com.google.collide.shared.ot.OperationPair pair = Transformer.transform(factory, clientMutation, serverMutation); OperationPair<DocOp> mutationPair = new OperationPair<DocOp>(pair.clientOp(), pair.serverOp()); assertDocOpEquals(transformedClientMutation, mutationPair.clientOp()); assertDocOpEquals(transformedServerMutation, mutationPair.serverOp()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false