Debian Codegraph @

test/com/google/debugging/sourcemap/SourceMapTestCase.java

raw symbols SCIP
1 /*
2 * Copyright 2011 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.debugging.sourcemap;
18
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.Maps;
21 import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping;
22 import com.google.javascript.jscomp.Compiler;
23 import com.google.javascript.jscomp.CompilerOptions;
24 import com.google.javascript.jscomp.Result;
25 import com.google.javascript.jscomp.SourceFile;
26 import com.google.javascript.jscomp.SourceMap;
27 import com.google.javascript.jscomp.SourceMap.DetailLevel;
28
29 import junit.framework.TestCase;
30
31 import java.io.IOException;
32 import java.util.LinkedHashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36
37 /**
38 * @author [email protected] (John Lenz)
39 */
40 public abstract class SourceMapTestCase extends TestCase {
41
42 private boolean validateColumns = true;
43
44 public SourceMapTestCase() {
45 }
46
47 void disableColumnValidation() {
48 validateColumns = false;
49 }
50
51
52 static final List<SourceFile> EXTERNS = ImmutableList.of(
53 SourceFile.fromCode("externs", ""));
54
55 protected DetailLevel detailLevel = SourceMap.DetailLevel.ALL;
56
57 protected static class RunResult {
58 String generatedSource;
59 SourceMap sourceMap;
60 public String sourceMapFileContent;
61 }
62
63 protected static class Token {
64 final String tokenName;
65 final String inputName;
66 final FilePosition position;
67 Token(String tokenName, String inputName, FilePosition position) {
68 this.tokenName = tokenName;
69 this.inputName = inputName;
70 this.position = position;
71 }
72 }
73
74 @Override
75 public void setUp() {
76 detailLevel = SourceMap.DetailLevel.ALL;
77 }
78
79 /**
80 * Creates a source map for the given JS code and asserts it is
81 * equal to the expected golden map.
82 */
83 protected void checkSourceMap(String js, String expectedMap)
84 throws IOException {
85 checkSourceMap("testcode", js, expectedMap);
86 }
87
88 protected String getSourceMap(RunResult result) throws IOException {
89 StringBuilder sb = new StringBuilder();
90 result.sourceMap.appendTo(sb, "testcode");
91 return sb.toString();
92 }
93
94 protected void checkSourceMap(String fileName, String js, String expectedMap)
95 throws IOException {
96 RunResult result = compile(js, fileName);
97 assertEquals(expectedMap, result.sourceMapFileContent);
98 assertEquals(result.sourceMapFileContent, getSourceMap(result));
99 }
100
101 /**
102 * Finds the all the __XX__ tokens in the given JavaScript
103 * string.
104 */
105 private Map<String, Token> findTokens(Map<String, String> inputs) {
106 Map<String, Token> tokens = Maps.newLinkedHashMap();
107
108 for (Entry<String, String> entry : inputs.entrySet()) {
109 findTokens(tokens, entry.getKey(), entry.getValue());
110 }
111
112 return tokens;
113 }
114
115 /**
116 * Finds the all the __XX__ tokens in the given JavaScript
117 * string.
118 */
119 private Map<String, Token> findTokens(String src) {
120 Map<String, Token> tokens = Maps.newLinkedHashMap();
121
122 findTokens(tokens, "", src);
123
124 return tokens;
125 }
126
127 /**
128 * Finds the all the __XX__ tokens in the given JavaScript
129 * string.
130 */
131 private Map<String, Token> findTokens(
132 Map<String, Token> tokens, String inputName, String js) {
133
134 int currentLine = 0;
135 int positionOffset = 0;
136
137 for (int i = 0; i < js.length(); ++i) {
138 char current = js.charAt(i);
139
140 if (current == '\n') {
141 positionOffset = i + 1;
142 currentLine++;
143 continue;
144 }
145
146 if (current == '_' && (i < js.length() - 5)) {
147 // Check for the _ token.
148 if (js.charAt(i + 1) != '_') {
149 continue;
150 }
151
152 // Loop until we have another _ token.
153 String tokenName = "";
154
155 int j = i + 2;
156 for (; j < js.length(); ++j) {
157 if (js.charAt(j) == '_') {
158 break;
159 }
160
161 tokenName += js.charAt(j);
162 }
163
164 if (tokenName.length() > 0) {
165 int currentPosition = i - positionOffset;
166 Token token = new Token(
167 tokenName, inputName,
168 new FilePosition(currentLine, currentPosition));
169 tokens.put(tokenName, token);
170 }
171
172 i = j;
173 }
174 }
175
176 return tokens;
177 }
178
179 abstract protected SourceMap.Format getSourceMapFormat();
180
181 abstract protected SourceMapConsumer getSourceMapConsumer();
182
183 protected void compileAndCheck(String js) {
184 String inputName = "testcode";
185 RunResult result = compile(js, inputName);
186 check(inputName, js, result.generatedSource, result.sourceMapFileContent);
187 }
188
189 protected void check(
190 String inputName, String input, String output,
191 String sourceMapFileContent) {
192 Map<String, String> inputMap = new LinkedHashMap<String, String>();
193 inputMap.put(inputName, input);
194 check(inputMap, output, sourceMapFileContent);
195 }
196
197 protected void check(
198 Map<String, String> originalInputs, String generatedSource,
199 String sourceMapFileContent) {
200 check(originalInputs, generatedSource, sourceMapFileContent, null);
201 }
202
203 protected void check(
204 Map<String, String> originalInputs, String generatedSource,
205 String sourceMapFileContent, SourceMapSupplier supplier) {
206 // Find all instances of the __XXX__ pattern in the original
207 // source code.
208 Map<String, Token> originalTokens = findTokens(originalInputs);
209
210 // Find all instances of the __XXX__ pattern in the generated
211 // source code.
212 Map<String, Token> resultTokens = findTokens(generatedSource);
213
214 // Ensure that the generated instances match via the source map
215 // to the original source code.
216
217 // Ensure the token counts match.
218 assertEquals(originalTokens.size(), resultTokens.size());
219
220 SourceMapping reader;
221 try {
222 reader = SourceMapConsumerFactory.parse(sourceMapFileContent, supplier);
223 } catch (SourceMapParseException e) {
224 throw new RuntimeException("unexpected exception", e);
225 }
226
227 // Map the tokens from the generated source back to the
228 // input source and ensure that the map is correct.
229 for (Token token : resultTokens.values()) {
230 OriginalMapping mapping = reader.getMappingForLine(
231 token.position.getLine() + 1,
232 token.position.getColumn() + 1);
233
234 assertNotNull(mapping);
235
236 // Find the associated token in the input source.
237 Token inputToken = originalTokens.get(token.tokenName);
238 assertNotNull(inputToken);
239 assertEquals(mapping.getOriginalFile(), inputToken.inputName);
240
241 // Ensure that the map correctly points to the token (we add 1
242 // to normalize versus the Rhino line number indexing scheme).
243 assertEquals(mapping.getLineNumber(),
244 inputToken.position.getLine() + 1);
245
246 int start = inputToken.position.getColumn() + 1;
247 if (inputToken.tokenName.startsWith("STR")) {
248 // include the preceding quote.
249 start--;
250 }
251
252 if (validateColumns) {
253 assertEquals(start, mapping.getColumnPosition());
254 }
255
256 // Ensure that if the token name does not being with an 'STR' (meaning a
257 // string) it has an original name.
258 if (!inputToken.tokenName.startsWith("STR")) {
259 assertTrue("missing name for " + inputToken.tokenName,
260 !mapping.getIdentifier().isEmpty());
261 }
262
263 // Ensure that if the mapping has a name, it matches the token.
264 if (!mapping.getIdentifier().isEmpty()) {
265 assertEquals(mapping.getIdentifier(),
266 "__" + inputToken.tokenName + "__");
267 }
268 }
269 }
270
271 protected RunResult compile(String js, String fileName) {
272 return compile(js, fileName, null, null);
273 }
274
275 protected CompilerOptions getCompilerOptions() {
276 CompilerOptions options = new CompilerOptions();
277 options.sourceMapOutputPath = "testcode_source_map.out";
278 options.sourceMapFormat = getSourceMapFormat();
279 options.sourceMapDetailLevel = detailLevel;
280 return options;
281 }
282
283 protected RunResult compile(
284 String js1, String fileName1, String js2, String fileName2) {
285 Compiler compiler = new Compiler();
286 CompilerOptions options = getCompilerOptions();
287
288 // Turn on IDE mode to get rid of optimizations.
289 options.ideMode = true;
290
291 List<SourceFile> inputs =
292 ImmutableList.of(SourceFile.fromCode(fileName1, js1));
293
294 if (js2 != null && fileName2 != null) {
295 inputs = ImmutableList.of(
296 SourceFile.fromCode(fileName1, js1),
297 SourceFile.fromCode(fileName2, js2));
298 }
299
300 Result result = compiler.compile(EXTERNS, inputs, options);
301
302 assertTrue("compilation failed", result.success);
303 String source = compiler.toSource();
304
305 StringBuilder sb = new StringBuilder();
306 try {
307 result.sourceMap.validate(true);
308 result.sourceMap.appendTo(sb, "testcode");
309 } catch (IOException e) {
310 throw new RuntimeException("unexpected exception", e);
311 }
312
313 RunResult rr = new RunResult();
314 rr.generatedSource = source;
315 rr.sourceMap = result.sourceMap;
316 rr.sourceMapFileContent = sb.toString();
317 return rr;
318 }
319
320 }