use of java.util.HashMap in project elasticsearch by elastic.
the class StashTests method testReplaceStashedValuesEmbeddedStashKey.
public void testReplaceStashedValuesEmbeddedStashKey() throws IOException {
Stash stash = new Stash();
stash.stashValue("stashed", "bar");
Map<String, Object> expected = new HashMap<>();
expected.put("key", singletonMap("a", "foobar"));
Map<String, Object> map = new HashMap<>();
Map<String, Object> map2 = new HashMap<>();
map2.put("a", "foo${stashed}");
map.put("key", map2);
Map<String, Object> actual = stash.replaceStashedValues(map);
assertEquals(expected, actual);
}
use of java.util.HashMap in project buck by facebook.
the class AppleTest method getTestCommand.
public Pair<ImmutableList<Step>, ExternalTestRunnerTestSpec> getTestCommand(ExecutionContext context, TestRunningOptions options, SourcePathResolver pathResolver, TestRule.TestReportingCallback testReportingCallback) {
ImmutableList.Builder<Step> steps = ImmutableList.builder();
ExternalTestRunnerTestSpec.Builder externalSpec = ExternalTestRunnerTestSpec.builder().setTarget(getBuildTarget()).setLabels(getLabels()).setContacts(getContacts());
Path resolvedTestBundleDirectory = pathResolver.getAbsolutePath(Preconditions.checkNotNull(testBundle.getSourcePathToOutput()));
Path pathToTestOutput = getProjectFilesystem().resolve(getPathToTestOutputDirectory());
steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), pathToTestOutput));
Path resolvedTestLogsPath = getProjectFilesystem().resolve(testLogsPath);
steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), resolvedTestLogsPath));
Path resolvedTestOutputPath = getProjectFilesystem().resolve(testOutputPath);
Optional<Path> testHostAppPath = Optional.empty();
if (testHostApp.isPresent()) {
Path resolvedTestHostAppDirectory = pathResolver.getAbsolutePath(Preconditions.checkNotNull(testHostApp.get().getSourcePathToOutput()));
testHostAppPath = Optional.of(resolvedTestHostAppDirectory.resolve(testHostApp.get().getUnzippedOutputFilePathToBinary()));
}
if (!useXctest) {
if (!xctool.isPresent()) {
throw new HumanReadableException("Set xctool_path = /path/to/xctool or xctool_zip_target = //path/to:xctool-zip " + "in the [apple] section of .buckconfig to run this test");
}
ImmutableSet.Builder<Path> logicTestPathsBuilder = ImmutableSet.builder();
ImmutableMap.Builder<Path, Path> appTestPathsToHostAppsBuilder = ImmutableMap.builder();
if (testHostAppPath.isPresent()) {
appTestPathsToHostAppsBuilder.put(resolvedTestBundleDirectory, testHostAppPath.get());
} else {
logicTestPathsBuilder.add(resolvedTestBundleDirectory);
}
xctoolStdoutReader = Optional.of(new AppleTestXctoolStdoutReader(testReportingCallback));
Optional<String> destinationSpecifierArg;
if (!destinationSpecifier.get().isEmpty()) {
destinationSpecifierArg = Optional.of(Joiner.on(',').join(Iterables.transform(destinationSpecifier.get().entrySet(), input -> input.getKey() + "=" + input.getValue())));
} else {
destinationSpecifierArg = defaultDestinationSpecifier;
}
Optional<String> snapshotReferenceImagesPath = Optional.empty();
if (this.snapshotReferenceImagesPath.isPresent()) {
if (this.snapshotReferenceImagesPath.get().isLeft()) {
snapshotReferenceImagesPath = Optional.of(pathResolver.getAbsolutePath(this.snapshotReferenceImagesPath.get().getLeft()).toString());
} else if (this.snapshotReferenceImagesPath.get().isRight()) {
snapshotReferenceImagesPath = Optional.of(getProjectFilesystem().getPathForRelativePath(this.snapshotReferenceImagesPath.get().getRight()).toString());
}
}
XctoolRunTestsStep xctoolStep = new XctoolRunTestsStep(getProjectFilesystem(), pathResolver.getAbsolutePath(xctool.get()), options.getEnvironmentOverrides(), xctoolStutterTimeout, platformName, destinationSpecifierArg, logicTestPathsBuilder.build(), appTestPathsToHostAppsBuilder.build(), resolvedTestOutputPath, xctoolStdoutReader, xcodeDeveloperDirSupplier, options.getTestSelectorList(), context.isDebugEnabled(), Optional.of(testLogDirectoryEnvironmentVariable), Optional.of(resolvedTestLogsPath), Optional.of(testLogLevelEnvironmentVariable), Optional.of(testLogLevel), testRuleTimeoutMs, snapshotReferenceImagesPath);
steps.add(xctoolStep);
externalSpec.setType("xctool-" + (testHostApp.isPresent() ? "application" : "logic"));
externalSpec.setCommand(xctoolStep.getCommand());
externalSpec.setEnv(xctoolStep.getEnv(context));
} else {
xctestOutputReader = Optional.of(new AppleTestXctestOutputReader(testReportingCallback));
HashMap<String, String> environment = new HashMap<>();
environment.putAll(xctest.getEnvironment(pathResolver));
environment.putAll(options.getEnvironmentOverrides());
if (testHostAppPath.isPresent()) {
environment.put("XCInjectBundleInto", testHostAppPath.get().toString());
}
XctestRunTestsStep xctestStep = new XctestRunTestsStep(getProjectFilesystem(), ImmutableMap.copyOf(environment), xctest.getCommandPrefix(pathResolver), resolvedTestBundleDirectory, resolvedTestOutputPath, xctestOutputReader, xcodeDeveloperDirSupplier);
steps.add(xctestStep);
externalSpec.setType("xctest");
externalSpec.setCommand(xctestStep.getCommand());
externalSpec.setEnv(xctestStep.getEnv(context));
}
return new Pair<>(steps.build(), externalSpec.build());
}
use of java.util.HashMap in project buck by facebook.
the class TestRunning method runTests.
@SuppressWarnings("PMD.EmptyCatchBlock")
public static int runTests(final CommandRunnerParams params, Iterable<TestRule> tests, ExecutionContext executionContext, final TestRunningOptions options, ListeningExecutorService service, BuildEngine buildEngine, final StepRunner stepRunner, SourcePathResolver sourcePathResolver, SourcePathRuleFinder ruleFinder) throws IOException, ExecutionException, InterruptedException {
ImmutableSet<JavaLibrary> rulesUnderTestForCoverage;
// If needed, we first run instrumentation on the class files.
if (options.isCodeCoverageEnabled()) {
rulesUnderTestForCoverage = getRulesUnderTest(tests);
if (!rulesUnderTestForCoverage.isEmpty()) {
try {
// We'll use the filesystem of the first rule under test. This will fail if there are any
// tests from a different repo, but it'll help us bootstrap ourselves to being able to
// support multiple repos
// TODO(t8220837): Support tests in multiple repos
JavaLibrary library = rulesUnderTestForCoverage.iterator().next();
stepRunner.runStepForBuildTarget(executionContext, new MakeCleanDirectoryStep(library.getProjectFilesystem(), JacocoConstants.getJacocoOutputDir(library.getProjectFilesystem())), Optional.empty());
} catch (StepFailedException e) {
params.getBuckEventBus().post(ConsoleEvent.severe(Throwables.getRootCause(e).getLocalizedMessage()));
return 1;
}
}
} else {
rulesUnderTestForCoverage = ImmutableSet.of();
}
final ImmutableSet<String> testTargets = FluentIterable.from(tests).transform(BuildRule::getBuildTarget).transform(Object::toString).toSet();
final int totalNumberOfTests = Iterables.size(tests);
params.getBuckEventBus().post(TestRunEvent.started(options.isRunAllTests(), options.getTestSelectorList(), options.shouldExplainTestSelectorList(), testTargets));
// Start running all of the tests. The result of each java_test() rule is represented as a
// ListenableFuture.
List<ListenableFuture<TestResults>> results = Lists.newArrayList();
TestRuleKeyFileHelper testRuleKeyFileHelper = new TestRuleKeyFileHelper(buildEngine);
final AtomicInteger lastReportedTestSequenceNumber = new AtomicInteger();
final List<TestRun> separateTestRuns = Lists.newArrayList();
List<TestRun> parallelTestRuns = Lists.newArrayList();
for (final TestRule test : tests) {
// Determine whether the test needs to be executed.
final Callable<TestResults> resultsInterpreter = getCachingCallable(test.interpretTestResults(executionContext, /*isUsingTestSelectors*/
!options.getTestSelectorList().isEmpty()));
boolean isTestRunRequired;
isTestRunRequired = isTestRunRequiredForTest(test, buildEngine, executionContext, testRuleKeyFileHelper, options.getTestResultCacheMode(), resultsInterpreter, !options.getTestSelectorList().isEmpty(), !options.getEnvironmentOverrides().isEmpty());
final Map<String, UUID> testUUIDMap = new HashMap<>();
final AtomicReference<TestStatusMessageEvent.Started> currentTestStatusMessageEvent = new AtomicReference<>();
TestRule.TestReportingCallback testReportingCallback = new TestRule.TestReportingCallback() {
@Override
public void testsDidBegin() {
LOG.debug("Tests for rule %s began", test.getBuildTarget());
}
@Override
public void statusDidBegin(TestStatusMessage didBeginMessage) {
LOG.debug("Test status did begin: %s", didBeginMessage);
TestStatusMessageEvent.Started startedEvent = TestStatusMessageEvent.started(didBeginMessage);
TestStatusMessageEvent.Started previousEvent = currentTestStatusMessageEvent.getAndSet(startedEvent);
Preconditions.checkState(previousEvent == null, "Received begin status before end status (%s)", previousEvent);
params.getBuckEventBus().post(startedEvent);
String message = didBeginMessage.getMessage();
if (message.toLowerCase().contains("debugger")) {
executionContext.getStdErr().println(executionContext.getAnsi().asWarningText(message));
}
}
@Override
public void statusDidEnd(TestStatusMessage didEndMessage) {
LOG.debug("Test status did end: %s", didEndMessage);
TestStatusMessageEvent.Started previousEvent = currentTestStatusMessageEvent.getAndSet(null);
Preconditions.checkState(previousEvent != null, "Received end status before begin status (%s)", previousEvent);
params.getBuckEventBus().post(TestStatusMessageEvent.finished(previousEvent, didEndMessage));
}
@Override
public void testDidBegin(String testCaseName, String testName) {
LOG.debug("Test rule %s test case %s test name %s began", test.getBuildTarget(), testCaseName, testName);
UUID testUUID = UUID.randomUUID();
// UUID is immutable and thread-safe as of Java 7, so it's
// safe to stash in a map and use later:
//
// http://bugs.java.com/view_bug.do?bug_id=6611830
testUUIDMap.put(testCaseName + ":" + testName, testUUID);
params.getBuckEventBus().post(TestSummaryEvent.started(testUUID, testCaseName, testName));
}
@Override
public void testDidEnd(TestResultSummary testResultSummary) {
LOG.debug("Test rule %s test did end: %s", test.getBuildTarget(), testResultSummary);
UUID testUUID = testUUIDMap.get(testResultSummary.getTestCaseName() + ":" + testResultSummary.getTestName());
Preconditions.checkNotNull(testUUID);
params.getBuckEventBus().post(TestSummaryEvent.finished(testUUID, testResultSummary));
}
@Override
public void testsDidEnd(List<TestCaseSummary> testCaseSummaries) {
LOG.debug("Test rule %s tests did end: %s", test.getBuildTarget(), testCaseSummaries);
}
};
List<Step> steps;
if (isTestRunRequired) {
params.getBuckEventBus().post(IndividualTestEvent.started(testTargets));
ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();
Preconditions.checkState(buildEngine.isRuleBuilt(test.getBuildTarget()));
List<Step> testSteps = test.runTests(executionContext, options, sourcePathResolver, testReportingCallback);
if (!testSteps.isEmpty()) {
stepsBuilder.addAll(testSteps);
stepsBuilder.add(testRuleKeyFileHelper.createRuleKeyInDirStep(test));
}
steps = stepsBuilder.build();
} else {
steps = ImmutableList.of();
}
TestRun testRun = TestRun.of(test, steps, getStatusTransformingCallable(isTestRunRequired, resultsInterpreter), testReportingCallback);
// commands because the rule is cached, but its results must still be processed.
if (test.runTestSeparately()) {
LOG.debug("Running test %s in serial", test);
separateTestRuns.add(testRun);
} else {
LOG.debug("Running test %s in parallel", test);
parallelTestRuns.add(testRun);
}
}
for (TestRun testRun : parallelTestRuns) {
ListenableFuture<TestResults> testResults = runStepsAndYieldResult(stepRunner, executionContext, testRun.getSteps(), testRun.getTestResultsCallable(), testRun.getTest().getBuildTarget(), params.getBuckEventBus(), service);
results.add(transformTestResults(params, testResults, testRun.getTest(), testRun.getTestReportingCallback(), testTargets, lastReportedTestSequenceNumber, totalNumberOfTests));
}
ListenableFuture<List<TestResults>> parallelTestStepsFuture = Futures.allAsList(results);
final List<TestResults> completedResults = Lists.newArrayList();
final ListeningExecutorService directExecutorService = MoreExecutors.newDirectExecutorService();
ListenableFuture<Void> uberFuture = MoreFutures.addListenableCallback(parallelTestStepsFuture, new FutureCallback<List<TestResults>>() {
@Override
public void onSuccess(List<TestResults> parallelTestResults) {
LOG.debug("Parallel tests completed, running separate tests...");
completedResults.addAll(parallelTestResults);
List<ListenableFuture<TestResults>> separateResultsList = Lists.newArrayList();
for (TestRun testRun : separateTestRuns) {
separateResultsList.add(transformTestResults(params, runStepsAndYieldResult(stepRunner, executionContext, testRun.getSteps(), testRun.getTestResultsCallable(), testRun.getTest().getBuildTarget(), params.getBuckEventBus(), directExecutorService), testRun.getTest(), testRun.getTestReportingCallback(), testTargets, lastReportedTestSequenceNumber, totalNumberOfTests));
}
ListenableFuture<List<TestResults>> serialResults = Futures.allAsList(separateResultsList);
try {
completedResults.addAll(serialResults.get());
} catch (ExecutionException e) {
LOG.error(e, "Error fetching serial test results");
throw new HumanReadableException(e, "Error fetching serial test results");
} catch (InterruptedException e) {
LOG.error(e, "Interrupted fetching serial test results");
try {
serialResults.cancel(true);
} catch (CancellationException ignored) {
// Rethrow original InterruptedException instead.
}
Thread.currentThread().interrupt();
throw new HumanReadableException(e, "Test cancelled");
}
LOG.debug("Done running serial tests.");
}
@Override
public void onFailure(Throwable e) {
LOG.error(e, "Parallel tests failed, not running serial tests");
throw new HumanReadableException(e, "Parallel tests failed");
}
}, directExecutorService);
try {
// Block until all the tests have finished running.
uberFuture.get();
} catch (ExecutionException e) {
e.printStackTrace(params.getConsole().getStdErr());
return 1;
} catch (InterruptedException e) {
try {
uberFuture.cancel(true);
} catch (CancellationException ignored) {
// Rethrow original InterruptedException instead.
}
Thread.currentThread().interrupt();
throw e;
}
params.getBuckEventBus().post(TestRunEvent.finished(testTargets, completedResults));
// Write out the results as XML, if requested.
Optional<String> path = options.getPathToXmlTestOutput();
if (path.isPresent()) {
try (Writer writer = Files.newWriter(new File(path.get()), Charsets.UTF_8)) {
writeXmlOutput(completedResults, writer);
}
}
// Generate the code coverage report.
if (options.isCodeCoverageEnabled() && !rulesUnderTestForCoverage.isEmpty()) {
try {
JavaBuckConfig javaBuckConfig = params.getBuckConfig().getView(JavaBuckConfig.class);
DefaultJavaPackageFinder defaultJavaPackageFinder = javaBuckConfig.createDefaultJavaPackageFinder();
stepRunner.runStepForBuildTarget(executionContext, getReportCommand(rulesUnderTestForCoverage, defaultJavaPackageFinder, javaBuckConfig.getDefaultJavaOptions().getJavaRuntimeLauncher(), params.getCell().getFilesystem(), sourcePathResolver, ruleFinder, JacocoConstants.getJacocoOutputDir(params.getCell().getFilesystem()), options.getCoverageReportFormat(), options.getCoverageReportTitle(), javaBuckConfig.getDefaultJavacOptions().getSpoolMode() == JavacOptions.SpoolMode.INTERMEDIATE_TO_DISK, options.getCoverageIncludes(), options.getCoverageExcludes()), Optional.empty());
} catch (StepFailedException e) {
params.getBuckEventBus().post(ConsoleEvent.severe(Throwables.getRootCause(e).getLocalizedMessage()));
return 1;
}
}
boolean failures = Iterables.any(completedResults, results1 -> {
LOG.debug("Checking result %s for failure", results1);
return !results1.isSuccess();
});
return failures ? TEST_FAILURES_EXIT_CODE : 0;
}
use of java.util.HashMap in project buck by facebook.
the class CxxDescriptionEnhancer method createSandboxTreeBuildRule.
public static SymlinkTree createSandboxTreeBuildRule(BuildRuleResolver resolver, CxxConstructorArg args, CxxPlatform platform, BuildRuleParams params) throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
SourcePathResolver sourcePathResolver = new SourcePathResolver(ruleFinder);
ImmutableCollection<SourcePath> privateHeaders = parseHeaders(params.getBuildTarget(), resolver, ruleFinder, sourcePathResolver, Optional.of(platform), args).values();
ImmutableCollection<CxxSource> sources = parseCxxSources(params.getBuildTarget(), resolver, ruleFinder, sourcePathResolver, platform, args).values();
HashMap<Path, SourcePath> links = new HashMap<>();
for (SourcePath headerPath : privateHeaders) {
links.put(Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), headerPath)), headerPath);
}
if (args instanceof CxxLibraryDescription.Arg) {
ImmutableCollection<SourcePath> publicHeaders = CxxDescriptionEnhancer.parseExportedHeaders(params.getBuildTarget(), resolver, ruleFinder, sourcePathResolver, Optional.of(platform), (CxxLibraryDescription.Arg) args).values();
for (SourcePath headerPath : publicHeaders) {
links.put(Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), headerPath)), headerPath);
}
}
for (CxxSource source : sources) {
SourcePath sourcePath = source.getPath();
links.put(Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), sourcePath)), sourcePath);
}
return createSandboxSymlinkTree(params, platform, ImmutableMap.copyOf(links), ruleFinder);
}
use of java.util.HashMap in project deeplearning4j by deeplearning4j.
the class GloveWeightLookupTable method load.
/**
* Load a glove model from an input stream.
* The format is:
* word num1 num2....
* @param is the input stream to read from for the weights
* @param vocab the vocab for the lookuptable
* @return the loaded model
* @throws java.io.IOException if one occurs
*/
public static GloveWeightLookupTable load(InputStream is, VocabCache<? extends SequenceElement> vocab) throws IOException {
LineIterator iter = IOUtils.lineIterator(is, "UTF-8");
GloveWeightLookupTable glove = null;
Map<String, float[]> wordVectors = new HashMap<>();
while (iter.hasNext()) {
String line = iter.nextLine().trim();
if (line.isEmpty())
continue;
String[] split = line.split(" ");
String word = split[0];
if (glove == null)
glove = new GloveWeightLookupTable.Builder().cache(vocab).vectorLength(split.length - 1).build();
if (word.isEmpty())
continue;
float[] read = read(split, glove.layerSize());
if (read.length < 1)
continue;
wordVectors.put(word, read);
}
glove.setSyn0(weights(glove, wordVectors, vocab));
glove.resetWeights(false);
iter.close();
return glove;
}
Aggregations