1 /*
2  * Copyright (C) 2017 The Dagger 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 dagger.internal.codegen;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 import static dagger.internal.codegen.binding.SourceFiles.simpleVariableName;
21 
22 import com.google.testing.compile.CompilationRule;
23 import dagger.internal.codegen.binding.SourceFiles;
24 import java.util.List;
25 import javax.lang.model.element.TypeElement;
26 import org.junit.Rule;
27 import org.junit.Test;
28 import org.junit.runner.RunWith;
29 import org.junit.runners.JUnit4;
30 
31 /** Tests for {@link SourceFiles}. */
32 @RunWith(JUnit4.class)
33 public final class SourceFilesTest {
34   @Rule public CompilationRule compilation = new CompilationRule();
35 
typeElementFor(Class<?> clazz)36   private TypeElement typeElementFor(Class<?> clazz) {
37     return compilation.getElements().getTypeElement(clazz.getCanonicalName());
38   }
39 
40   private static final class Int {}
41 
42   @Test
testSimpleVariableName_typeCollisions()43   public void testSimpleVariableName_typeCollisions() {
44     // a handful of boxed types
45     assertThat(simpleVariableName(typeElementFor(Long.class))).isEqualTo("l");
46     assertThat(simpleVariableName(typeElementFor(Double.class))).isEqualTo("d");
47     // not a boxed type type, but a custom type might collide
48     assertThat(simpleVariableName(typeElementFor(Int.class))).isEqualTo("i");
49     // void is the weird pseudo-boxed type
50     assertThat(simpleVariableName(typeElementFor(Void.class))).isEqualTo("v");
51     // reflective types
52     assertThat(simpleVariableName(typeElementFor(Class.class))).isEqualTo("clazz");
53     assertThat(simpleVariableName(typeElementFor(Package.class))).isEqualTo("pkg");
54   }
55 
56   private static final class For {}
57 
58   private static final class Goto {}
59 
60   @Test
testSimpleVariableName_randomKeywords()61   public void testSimpleVariableName_randomKeywords() {
62     assertThat(simpleVariableName(typeElementFor(For.class))).isEqualTo("for_");
63     assertThat(simpleVariableName(typeElementFor(Goto.class))).isEqualTo("goto_");
64   }
65 
66   @Test
testSimpleVariableName()67   public void testSimpleVariableName() {
68     assertThat(simpleVariableName(typeElementFor(Object.class))).isEqualTo("object");
69     assertThat(simpleVariableName(typeElementFor(List.class))).isEqualTo("list");
70   }
71 }
72