private void assertCompDir(Path compDir, Optional<String> failure) throws Exception {
    ProjectFilesystem filesystem = new ProjectFilesystem(tmp.getRoot().toPath());
    CxxPlatform platform = DefaultCxxPlatforms.build(new CxxBuckConfig(new FakeBuckConfig()));

    // Build up the paths to various files the archive step will use.
    ImmutableList<String> compiler =
        platform.getCc().getCommandPrefix(new SourcePathResolver(new BuildRuleResolver()));
    Path output = filesystem.resolve(Paths.get("output.o"));
    Path relativeInput = Paths.get("input.c");
    Path input = filesystem.resolve(relativeInput);
    filesystem.writeContentsToPath("int main() {}", relativeInput);

    ImmutableList.Builder<String> preprocessorCommand = ImmutableList.builder();
    preprocessorCommand.addAll(compiler);

    ImmutableList.Builder<String> compilerCommand = ImmutableList.builder();
    compilerCommand.addAll(compiler);
    compilerCommand.add("-g");

    DebugPathSanitizer sanitizer =
        new DebugPathSanitizer(200, File.separatorChar, compDir, ImmutableBiMap.<Path, Path>of());

    // Build an archive step.
    CxxPreprocessAndCompileStep step =
        new CxxPreprocessAndCompileStep(
            CxxPreprocessAndCompileStep.Operation.COMPILE_MUNGE_DEBUGINFO,
            output,
            relativeInput,
            CxxSource.Type.C,
            Optional.of(preprocessorCommand.build()),
            Optional.of(compilerCommand.build()),
            ImmutableMap.<Path, Path>of(),
            sanitizer);

    // Execute the archive step and verify it ran successfully.
    ExecutionContext executionContext =
        TestExecutionContext.newBuilder()
            .setProjectFilesystem(new ProjectFilesystem(tmp.getRoot().toPath()))
            .build();
    TestConsole console = (TestConsole) executionContext.getConsole();
    int exitCode = step.execute(executionContext);
    if (failure.isPresent()) {
      assertNotEquals("compile step succeeded", 0, exitCode);
      assertThat(
          console.getTextWrittenToStdErr(),
          console.getTextWrittenToStdErr(),
          Matchers.containsString(failure.get()));
    } else {
      assertEquals("compile step failed: " + console.getTextWrittenToStdErr(), 0, exitCode);
      // Verify that we find the expected compilation dir embedded in the file.
      String contents = new String(Files.readAllBytes(output));
      assertThat(contents, Matchers.containsString(sanitizer.getCompilationDirectory()));
    }

    // Cleanup.
    Files.delete(input);
    Files.deleteIfExists(output);
  }
Example #2
0
 private ExecutionContext createExecutionContext(int verbosityLevel) {
   TestConsole console = new TestConsole();
   Verbosity verbosity = VerbosityParser.getVerbosityForLevel(verbosityLevel);
   console.setVerbosity(verbosity);
   return TestExecutionContext.newBuilder()
       .setConsole(console)
       .setAndroidPlatformTarget(androidPlatformTargetOptional)
       .build();
 }
  /** Verify that owners are correctly detected: - one owner, multiple inputs, json output */
  @Test
  public void verifyInputsWithOneOwnerAreCorrectlyReportedInJson()
      throws CmdLineException, IOException {
    // All files will be directories now
    FakeProjectFilesystem filesystem =
        new FakeProjectFilesystem() {
          @Override
          public File getFileForRelativePath(String pathRelativeToProjectRoot) {
            return new ExistingFile(getProjectRoot(), pathRelativeToProjectRoot);
          }
        };

    // Create inputs
    String[] args =
        new String[] {
          "java/somefolder/badfolder/somefile.java",
          "java/somefolder/perfect.java",
          "com/test/subtest/random.java"
        };
    ImmutableSortedSet<Path> inputs = MorePaths.asPaths(ImmutableSortedSet.copyOf(args));

    // Build rule that owns all inputs
    BuildTarget target = new BuildTarget("//base/name", "name");
    BuildRule ownerRule = new StubBuildRule(target, inputs);

    // Create graph
    MutableDirectedGraph<BuildRule> mutableGraph = new MutableDirectedGraph<BuildRule>();
    mutableGraph.addNode(ownerRule);

    DependencyGraph graph = new DependencyGraph(mutableGraph);

    // Create options
    AuditOwnerOptions options = getOptions(args);

    // Create command under test
    AuditOwnerCommand command = createAuditOwnerCommand(filesystem);

    // Generate report and verify nonFileInputs are filled in as expected.
    AuditOwnerCommand.OwnersReport report = command.generateOwnersReport(graph, options);
    command.printOwnersOnlyJsonReport(report);

    String expectedJson =
        Joiner.on("")
            .join(
                "{",
                "\"com/test/subtest/random.java\":[\"//base/name:name\"],",
                "\"java/somefolder/badfolder/somefile.java\":[\"//base/name:name\"],",
                "\"java/somefolder/perfect.java\":[\"//base/name:name\"]",
                "}");

    assertEquals(expectedJson, console.getTextWrittenToStdOut());
    assertEquals("", console.getTextWrittenToStdErr());
  }
Example #4
0
  @Test
  public void testJsonOutputForMissingBuildTarget()
      throws BuildFileParseException, IOException, InterruptedException {
    // nonexistent target should not exist.
    SortedMap<String, TargetNode<?>> buildRules = buildTargetNodes(filesystem, "//:nonexistent");
    targetsCommand.printJsonForTargets(
        params, executor, buildRules, ImmutableMap.<String, ShowOptions>of());

    String output = console.getTextWrittenToStdOut();
    assertEquals("[\n]\n", output);
    assertEquals(
        "unable to find rule for target //:nonexistent\n", console.getTextWrittenToStdErr());
  }
Example #5
0
  @Test
  public void testJsonOutputWithDirectDependencies() throws IOException {
    // Run Buck targets command on a case where the deps and direct_dependencies differ
    ProcessResult result = workspace.runBuckCommand("targets", "--json", "//:B");

    // Parse the observed JSON.
    JsonNode observed =
        objectMapper.readTree(
            objectMapper
                .getJsonFactory()
                .createJsonParser(result.getStdout())
                .enable(Feature.ALLOW_COMMENTS));

    // Parse the expected JSON.
    String expectedJson = workspace.getFileContents("TargetsCommandTestBuckJson2.js");
    JsonNode expected =
        objectMapper.readTree(
            objectMapper
                .getJsonFactory()
                .createJsonParser(expectedJson)
                .enable(Feature.ALLOW_COMMENTS));

    assertThat(
        "Output from targets command should match expected JSON.", observed, is(equalTo(expected)));
    assertThat(
        "Nothing should be printed to stderr.", console.getTextWrittenToStdErr(), is(equalTo("")));
  }
Example #6
0
  /** Verify that owners are correctly detected: - one owner, multiple inputs, json output */
  @Test
  public void verifyInputsWithOneOwnerAreCorrectlyReportedInJson()
      throws CmdLineException, IOException, InterruptedException {
    FakeProjectFilesystem filesystem =
        new FakeProjectFilesystem() {
          @Override
          public File getFileForRelativePath(String pathRelativeToProjectRoot) {
            return new ExistingFile(getRootPath(), pathRelativeToProjectRoot);
          }
        };

    ImmutableSet<String> inputs =
        ImmutableSet.of(
            "java/somefolder/badfolder/somefile.java",
            "java/somefolder/perfect.java",
            "com/test/subtest/random.java");
    ImmutableSortedSet<Path> inputPaths = MorePaths.asPaths(inputs);

    BuildTarget target = BuildTargetFactory.newInstance("//base/name:name");
    TargetNode<?> targetNode = createTargetNode(target, inputPaths);

    AuditOwnerCommand command = new AuditOwnerCommand();
    CommandRunnerParams params = createAuditOwnerCommandRunnerParams(filesystem);
    AuditOwnerCommand.OwnersReport report =
        AuditOwnerCommand.generateOwnersReport(params, targetNode, inputs, false);
    command.printOwnersOnlyJsonReport(params, report);

    String expectedJson =
        Joiner.on("")
            .join(
                "{",
                "\"com/test/subtest/random.java\":[\"//base/name:name\"],",
                "\"java/somefolder/badfolder/somefile.java\":[\"//base/name:name\"],",
                "\"java/somefolder/perfect.java\":[\"//base/name:name\"]",
                "}");

    assertEquals(expectedJson, console.getTextWrittenToStdOut());
    assertEquals("", console.getTextWrittenToStdErr());
  }
Example #7
0
  @Test
  public void testJsonOutputForBuildTarget()
      throws IOException, BuildFileParseException, InterruptedException {
    // run `buck targets` on the build file and parse the observed JSON.
    SortedMap<String, TargetNode<?>> nodes = buildTargetNodes(filesystem, "//:test-library");

    targetsCommand.printJsonForTargets(
        params, executor, nodes, ImmutableMap.<String, ShowOptions>of());
    String observedOutput = console.getTextWrittenToStdOut();
    JsonNode observed =
        objectMapper.readTree(objectMapper.getJsonFactory().createJsonParser(observedOutput));

    // parse the expected JSON.
    String expectedJson = workspace.getFileContents("TargetsCommandTestBuckJson1.js");
    JsonNode expected =
        objectMapper.readTree(
            objectMapper
                .getJsonFactory()
                .createJsonParser(expectedJson)
                .enable(Feature.ALLOW_COMMENTS));

    assertEquals("Output from targets command should match expected JSON.", expected, observed);
    assertEquals("Nothing should be printed to stderr.", "", console.getTextWrittenToStdErr());
  }