aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/com/squareup/javapoet/FileReadingTest.java
blob: 94ba6e8def72505b35fda3a3bacbb3c48433c12a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
 * Copyright (C) 2015 Square, Inc.
 *
 * 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.squareup.javapoet;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Locale;
import java.util.concurrent.Callable;
import javax.lang.model.element.Modifier;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.google.common.io.ByteStreams;

import static com.google.common.truth.Truth.assertThat;

@RunWith(JUnit4.class)
public class FileReadingTest {
  
  // Used for storing compilation output.
  @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder();

  @Test public void javaFileObjectUri() {
    TypeSpec type = TypeSpec.classBuilder("Test").build();
    assertThat(JavaFile.builder("", type).build().toJavaFileObject().toUri())
        .isEqualTo(URI.create("Test.java"));
    assertThat(JavaFile.builder("foo", type).build().toJavaFileObject().toUri())
        .isEqualTo(URI.create("foo/Test.java"));
    assertThat(JavaFile.builder("com.example", type).build().toJavaFileObject().toUri())
        .isEqualTo(URI.create("com/example/Test.java"));
  }
  
  @Test public void javaFileObjectKind() {
    JavaFile javaFile = JavaFile.builder("", TypeSpec.classBuilder("Test").build()).build();
    assertThat(javaFile.toJavaFileObject().getKind()).isEqualTo(Kind.SOURCE);
  }
  
  @Test public void javaFileObjectCharacterContent() throws IOException {
    TypeSpec type = TypeSpec.classBuilder("Test")
        .addJavadoc("Testing, 1, 2, 3!")
        .addMethod(MethodSpec.methodBuilder("fooBar").build())
        .build();
    JavaFile javaFile = JavaFile.builder("foo", type).build();
    JavaFileObject javaFileObject = javaFile.toJavaFileObject();
    
    // We can never have encoding issues (everything is in process)
    assertThat(javaFileObject.getCharContent(true)).isEqualTo(javaFile.toString());
    assertThat(javaFileObject.getCharContent(false)).isEqualTo(javaFile.toString());
  }
  
  @Test public void javaFileObjectInputStream() throws IOException {
    JavaFile javaFile = JavaFile.builder("foo", TypeSpec.classBuilder("Test").build())
        .addFileComment("\u00A9 Copyright character gets you everytime")
        .build();
    byte[] bytes = ByteStreams.toByteArray(javaFile.toJavaFileObject().openInputStream());
    
    // Be explicit with the default charset to assert the implicit behavior in the code
    assertThat(bytes).isEqualTo(javaFile.toString().getBytes(Charset.defaultCharset()));
  }
  
  @Test public void compileJavaFile() throws Exception {
    final String value = "Hello World!";
    TypeSpec type = TypeSpec.classBuilder("Test")
        .addModifiers(Modifier.PUBLIC)
        .addSuperinterface(ParameterizedTypeName.get(Callable.class, String.class))
        .addMethod(MethodSpec.methodBuilder("call")
            .returns(String.class)
            .addModifiers(Modifier.PUBLIC)
            .addStatement("return $S", value)
            .build())
        .build();
    JavaFile javaFile = JavaFile.builder("foo", type).build();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, 
        Locale.getDefault(), StandardCharsets.UTF_8);
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
        Collections.singleton(temporaryFolder.newFolder()));
    CompilationTask task = compiler.getTask(null, 
        fileManager,
        diagnosticCollector,
        Collections.<String>emptySet(),
        Collections.<String>emptySet(),
        Collections.singleton(javaFile.toJavaFileObject()));
    
    assertThat(task.call()).isTrue();
    assertThat(diagnosticCollector.getDiagnostics()).isEmpty();

    ClassLoader loader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT);
    Callable<?> test = Class.forName("foo.Test", true, loader).asSubclass(Callable.class).newInstance();
    assertThat(Callable.class.getMethod("call").invoke(test)).isEqualTo(value);
  }

}