aboutsummaryrefslogtreecommitdiffstats
path: root/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/JunitRunner.java
blob: 21890bab569d76d548af898cef0610966ee50a85 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.testrunner;

import ai.vespa.cloud.Environment;
import ai.vespa.cloud.SystemInfo;
import ai.vespa.cloud.Zone;
import ai.vespa.hosted.cd.internal.TestRuntimeProvider;
import com.yahoo.component.AbstractComponent;
import com.yahoo.component.annotation.Inject;
import com.yahoo.jdisc.application.OsgiFramework;
import com.yahoo.vespa.defaults.Defaults;
import org.junit.jupiter.engine.JupiterTestEngine;
import org.junit.platform.engine.discovery.ClassSelector;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.core.LauncherConfig;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;

import java.time.Clock;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.SortedMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutionException;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;


/**
 * @author mortent
 * @author jonmv
 */
public class JunitRunner extends AbstractComponent implements TestRunner {

    private static final Logger logger = Logger.getLogger(JunitRunner.class.getName());

    private final Clock clock;
    private final SortedMap<Long, LogRecord> logRecords = new ConcurrentSkipListMap<>();
    private final TeeStream stdoutTee = TeeStream.ofSystemOut();
    private final TeeStream stderrTee = TeeStream.ofSystemErr();
    private final TestRuntimeProvider testRuntimeProvider;
    private final Function<Suite, List<Class<?>>> classLoader;
    private final BiConsumer<LauncherDiscoveryRequest, TestExecutionListener[]> testExecutor;
    private volatile CompletableFuture<TestReport> execution;

    @Inject
    public JunitRunner(OsgiFramework osgiFramework,
                       JunitTestRunnerConfig config,
                       TestRuntimeProvider testRuntimeProvider,
                       SystemInfo systemInfo) {
        this(Clock.systemUTC(),
             testRuntimeProvider,
             new TestBundleLoader(osgiFramework)::loadTestClasses,
             JunitRunner::executeTests);

        uglyHackSetCredentialsRootSystemProperty(config, systemInfo.zone());

    }

    JunitRunner(Clock clock,
                TestRuntimeProvider testRuntimeProvider,
                Function<Suite, List<Class<?>>> classLoader,
                BiConsumer<LauncherDiscoveryRequest, TestExecutionListener[]> testExecutor) {
        this.clock = clock;
        this.classLoader = classLoader;
        this.testExecutor = testExecutor;
        this.testRuntimeProvider = testRuntimeProvider;
    }

    private static void executeTests(LauncherDiscoveryRequest discoveryRequest, TestExecutionListener[] listeners) {
        var launcher = LauncherFactory.create(LauncherConfig.builder()
                                                            .addTestEngines(new JupiterTestEngine())
                                                            .build());
        ClassLoader context = Thread.currentThread().getContextClassLoader();
        try {
            // Pick the bundle class loader of the first user test class, from the test class selector.
            discoveryRequest.getSelectorsByType(ClassSelector.class).stream()
                            .map(selector -> selector.getJavaClass().getClassLoader())
                            .findAny().ifPresent(Thread.currentThread()::setContextClassLoader);

            launcher.execute(discoveryRequest, listeners);
        }
        finally {
            Thread.currentThread().setContextClassLoader(context);
        }
    }

    @Override
    public CompletableFuture<?> test(Suite suite, byte[] testConfig) {
        if (execution != null && ! execution.isDone()) {
            throw new IllegalStateException("Test execution already in progress");
        }
        try {
            logRecords.clear();
            execution = CompletableFuture.supplyAsync(() -> launchJunit(suite, testConfig));
        } catch (Throwable t) {
            execution = CompletableFuture.completedFuture(TestReport.createFailed(clock, suite, t));
        }
        return execution;
    }

    @Override
    public Collection<LogRecord> getLog(long after) {
        return logRecords.tailMap(after + 1).values();
    }

    private TestReport launchJunit(Suite suite, byte[] testConfig) {
        List<Class<?>> testClasses = classLoader.apply(suite);
        if (testClasses == null)
            return  null;

        testRuntimeProvider.initialize(testConfig);
        TestReportGeneratingListener testReportListener = new TestReportGeneratingListener(suite,
                                                                                           record -> logRecords.put(record.getSequenceNumber(), record),
                                                                                           stdoutTee,
                                                                                           stderrTee,
                                                                                           clock);
        LauncherDiscoveryRequest discoveryRequest = LauncherDiscoveryRequestBuilder.request()
                                                                                   .selectors(testClasses.stream()
                                                                                                         .map(DiscoverySelectors::selectClass)
                                                                                                         .toList())
                                                                                   .build();
        testExecutor.accept(discoveryRequest, new TestExecutionListener[] { testReportListener });

        return testReportListener.report();
    }

    @Override
    public void deconstruct() {
        super.deconstruct();
    }

    @Override
    public TestRunner.Status getStatus() {
        if (execution == null) return TestRunner.Status.NOT_STARTED;
        if ( ! execution.isDone()) return TestRunner.Status.RUNNING;
        try {
            return testRunnerStatus(execution.get());
        } catch (InterruptedException | ExecutionException e) {
            logger.log(Level.WARNING, "Error while getting test report", e);
            return TestRunner.Status.ERROR;
        }
    }

    static TestRunner.Status testRunnerStatus(TestReport report) {
        if (report == null) return Status.NO_TESTS;
        switch (report.root().status()) {
            case error:
            case failed:       return Status.FAILURE;
            case inconclusive: return Status.INCONCLUSIVE;
            case successful:
            case skipped:
            case aborted:     return report.root().tally().containsKey(TestReport.Status.successful) ? Status.SUCCESS
                                                                                                     : Status.NO_TESTS;
            default: throw new IllegalStateException("unknown status '" + report.root().status() + "'");
        }
    }

    @Override
    public TestReport getReport() {
        if (execution.isDone()) {
            try {
                return execution.get();
            } catch (Throwable t) {
                logger.log(Level.WARNING, "Error getting test report", t);
                // Likely this is something wrong with the provided test bundle. Create a test report
                // and present in the console to enable tenants to act on it.
                return TestReport.createFailed(clock, null, t);
            }
        } else {
            return null;
        }
    }

    // TODO(bjorncs|tokle) Propagate credentials root without system property. Ideally move knowledge about path to test-runtime implementations
    private static void uglyHackSetCredentialsRootSystemProperty(JunitTestRunnerConfig config, Zone zone) {
        Optional<String> credentialsRoot;
        if (config.useAthenzCredentials()) {
            credentialsRoot = Optional.of(Defaults.getDefaults().underVespaHome("var/vespa/sia"));
        } else if (zone.environment() != Environment.prod){
            // Only set credentials in non-prod zones where not available
            credentialsRoot = Optional.of(config.artifactsPath().toString());
        } else {
            credentialsRoot = Optional.empty();
        }
        credentialsRoot.ifPresent(root -> System.setProperty("vespa.test.credentials.root", root));
    }

}