summaryrefslogtreecommitdiff
path: root/src/main/org/apache/tools/ant/taskdefs/optional/junitlauncher/StandaloneLauncher.java
blob: 69a1556c894e486776c7cee1cd2f611e490c80bd (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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You 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 org.apache.tools.ant.taskdefs.optional.junitlauncher;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Properties;

import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static javax.xml.stream.XMLStreamConstants.START_DOCUMENT;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import static org.apache.tools.ant.taskdefs.optional.junitlauncher.Constants.LD_XML_ATTR_HALT_ON_FAILURE;
import static org.apache.tools.ant.taskdefs.optional.junitlauncher.Constants.LD_XML_ATTR_PRINT_SUMMARY;
import static org.apache.tools.ant.taskdefs.optional.junitlauncher.Constants.LD_XML_ELM_LAUNCH_DEF;
import static org.apache.tools.ant.taskdefs.optional.junitlauncher.Constants.LD_XML_ELM_LISTENER;
import static org.apache.tools.ant.taskdefs.optional.junitlauncher.Constants.LD_XML_ELM_TEST;
import static org.apache.tools.ant.taskdefs.optional.junitlauncher.Constants.LD_XML_ELM_TEST_CLASSES;

/**
 * Used for launching forked tests from the {@link JUnitLauncherTask}.
 * <p>
 * Although this class is public, this isn't meant for external use. The contract of what
 * program arguments {@link #main(String[]) the main method} accepts and how it interprets it,
 * is also an internal detail and can change across Ant releases.
 *
 * @since Ant 1.10.6
 */
public class StandaloneLauncher {

    /**
     * Entry point to launching the forked test.
     *
     * @param args The arguments passed to this program for launching the tests
     * @throws Exception If any exception occurs during the execution
     */
    public static void main(final String[] args) throws Exception {
        // The main responsibility of this entry point is to create a LaunchDefinition,
        // by parsing the passed arguments and then use the LauncherSupport to
        // LauncherSupport#launch the tests
        try {
            ForkedLaunch launchDefinition = null;
            final ForkedExecution forkedExecution = new ForkedExecution();
            for (int i = 0; i < args.length; ) {
                final String arg = args[i];
                int numArgsConsumed = 1;
                switch (arg) {
                    case Constants.ARG_PROPERTIES: {
                        final Path propsPath = Paths.get(args[i + 1]);
                        if (!Files.isRegularFile(propsPath)) {
                            throw new IllegalArgumentException(propsPath + " does not point to a properties file");
                        }
                        final Properties properties = new Properties();
                        try (final InputStream is = Files.newInputStream(propsPath)) {
                            properties.load(is);
                        }
                        forkedExecution.setProperties(properties);
                        numArgsConsumed = 2;
                        break;
                    }
                    case Constants.ARG_LAUNCH_DEFINITION: {
                        final Path launchDefXmlPath = Paths.get(args[i + 1]);
                        if (!Files.isRegularFile(launchDefXmlPath)) {
                            throw new IllegalArgumentException(launchDefXmlPath + " does not point to a launch definition file");
                        }
                        launchDefinition = parseLaunchDefinition(launchDefXmlPath);
                        numArgsConsumed = 2;
                        break;
                    }
                }
                i = i + numArgsConsumed;
            }

            launchDefinition.setTestExecutionContext(forkedExecution);
            final LauncherSupport launcherSupport = new LauncherSupport(launchDefinition);
            try {
                launcherSupport.launch();
            } catch (Throwable t) {
                if (launcherSupport.hasTestFailures()) {
                    System.exit(Constants.FORK_EXIT_CODE_TESTS_FAILED);
                }
                throw t;
            }
            if (launcherSupport.hasTestFailures()) {
                System.exit(Constants.FORK_EXIT_CODE_TESTS_FAILED);
                return;
            }
            System.exit(Constants.FORK_EXIT_CODE_SUCCESS);
            return;
        } catch (Throwable t) {
            t.printStackTrace();
            throw t;
        }
    }

    private static ForkedLaunch parseLaunchDefinition(final Path pathToLaunchDefXml) {
        if (pathToLaunchDefXml == null || !Files.isRegularFile(pathToLaunchDefXml)) {
            throw new IllegalArgumentException(pathToLaunchDefXml + " is not a file");
        }
        final ForkedLaunch forkedLaunch = new ForkedLaunch();
        try (final InputStream is = Files.newInputStream(pathToLaunchDefXml)) {
            final XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(is);
            reader.require(START_DOCUMENT, null, null);
            reader.nextTag();
            reader.require(START_ELEMENT, null, LD_XML_ELM_LAUNCH_DEF);
            final String haltOnfFailure = reader.getAttributeValue(null, LD_XML_ATTR_HALT_ON_FAILURE);
            if (haltOnfFailure != null) {
                forkedLaunch.setHaltOnFailure(Boolean.parseBoolean(haltOnfFailure));
            }
            final String printSummary = reader.getAttributeValue(null, LD_XML_ATTR_PRINT_SUMMARY);
            if (printSummary != null) {
                forkedLaunch.setPrintSummary(Boolean.parseBoolean(printSummary));
            }
            if (haltOnfFailure != null) {
                forkedLaunch.setHaltOnFailure(Boolean.parseBoolean(haltOnfFailure));
            }
            reader.nextTag();
            reader.require(START_ELEMENT, null, null);
            final String elementName = reader.getLocalName();
            switch (elementName) {
                case LD_XML_ELM_TEST: {
                    forkedLaunch.addTests(Collections.singletonList(SingleTestClass.fromForkedRepresentation(reader)));
                    break;
                }
                case LD_XML_ELM_TEST_CLASSES: {
                    forkedLaunch.addTests(TestClasses.fromForkedRepresentation(reader));
                    break;
                }
                case LD_XML_ELM_LISTENER: {
                    forkedLaunch.addListener(ListenerDefinition.fromForkedRepresentation(reader));
                    break;
                }
            }
            reader.nextTag();
            reader.require(END_ELEMENT, null, LD_XML_ELM_LAUNCH_DEF);
            reader.next();
            reader.require(END_DOCUMENT, null, null);
            return forkedLaunch;
        } catch (Exception e) {
            throw new BuildException("Failed to construct definition from forked representation", e);
        }
    }


    private static final class ForkedExecution implements TestExecutionContext {
        private Properties properties = new Properties();

        private ForkedExecution() {
        }

        private ForkedExecution setProperties(final Properties properties) {
            this.properties = properties;
            return this;
        }

        @Override
        public Properties getProperties() {
            return this.properties;
        }

        @Override
        public Optional<Project> getProject() {
            // forked execution won't have access to the Ant Project
            return Optional.empty();
        }
    }

    private static final class ForkedLaunch implements LaunchDefinition {

        private boolean printSummary;
        private boolean haltOnFailure;
        private TestExecutionContext testExecutionContext;
        private List<TestDefinition> tests = new ArrayList<>();
        private List<ListenerDefinition> listeners = new ArrayList<>();

        @Override
        public List<TestDefinition> getTests() {
            return this.tests;
        }

        ForkedLaunch addTests(final List<TestDefinition> tests) {
            this.tests.addAll(tests);
            return this;
        }

        @Override
        public List<ListenerDefinition> getListeners() {
            return this.listeners;
        }

        ForkedLaunch addListener(final ListenerDefinition listener) {
            this.listeners.add(listener);
            return this;
        }

        @Override
        public boolean isPrintSummary() {
            return this.printSummary;
        }

        private ForkedLaunch setPrintSummary(final boolean printSummary) {
            this.printSummary = printSummary;
            return this;
        }

        @Override
        public boolean isHaltOnFailure() {
            return this.haltOnFailure;
        }

        public ForkedLaunch setHaltOnFailure(final boolean haltOnFailure) {
            this.haltOnFailure = haltOnFailure;
            return this;
        }

        public ForkedLaunch setTestExecutionContext(final TestExecutionContext testExecutionContext) {
            this.testExecutionContext = testExecutionContext;
            return this;
        }

        @Override
        public ClassLoader getClassLoader() {
            return this.getClass().getClassLoader();
        }

        @Override
        public TestExecutionContext getTestExecutionContext() {
            return this.testExecutionContext;
        }
    }
}