Exemple #1
0
def run_goal(targets: list[MockTarget],
             *,
             show_documented: bool = False) -> tuple[str, str]:
    with mock_console(create_options_bootstrapper()) as (console,
                                                         stdio_reader):
        run_rule_with_mocks(
            list_targets,
            rule_args=[
                Addresses(tgt.address for tgt in targets),
                create_goal_subsystem(
                    ListSubsystem,
                    sep="\\n",
                    output_file=None,
                    documented=show_documented,
                ),
                console,
            ],
            mock_gets=[
                MockGet(
                    output_type=UnexpandedTargets,
                    input_type=Addresses,
                    mock=lambda _: UnexpandedTargets(targets),
                )
            ],
        )
        return stdio_reader.get_stdout(), stdio_reader.get_stderr()
Exemple #2
0
def run_goal(
    targets: Sequence[Target],
    *,
    target_type: list[str] | None = None,
    address_regex: list[str] | None = None,
    tag_regex: list[str] | None = None,
    granularity: TargetGranularity | None = None,
) -> str:
    with mock_console(create_options_bootstrapper()) as (console,
                                                         stdio_reader):
        run_rule_with_mocks(
            filter_targets,
            rule_args=[
                Targets(targets),
                create_goal_subsystem(
                    FilterSubsystem,
                    sep="\\n",
                    output_file=None,
                    target_type=target_type or [],
                    address_regex=address_regex or [],
                    tag_regex=tag_regex or [],
                    granularity=granularity or TargetGranularity.all_targets,
                    # Deprecated.
                    type=[],
                    target=[],
                    regex=[],
                    ancestor=[],
                ),
                console,
                RegisteredTargetTypes.create({type(tgt)
                                              for tgt in targets}),
            ],
        )
        assert not stdio_reader.get_stderr()
        return stdio_reader.get_stdout()
Exemple #3
0
def run_goal(
    targets: List[MockTarget],
    *,
    show_documented: bool = False,
    show_provides: bool = False,
    provides_columns: Optional[str] = None,
) -> Tuple[str, str]:
    console = MockConsole(use_colors=False)
    run_rule_with_mocks(
        list_targets,
        rule_args=[
            Addresses(tgt.address for tgt in targets),
            create_goal_subsystem(
                ListSubsystem,
                sep="\\n",
                output_file=None,
                documented=show_documented,
                provides=show_provides,
                provides_columns=provides_columns or "address,artifact_id",
            ),
            console,
        ],
        mock_gets=[
            MockGet(
                product_type=UnexpandedTargets,
                subject_type=Addresses,
                mock=lambda _: UnexpandedTargets(targets),
            )
        ],
    )
    return cast(str,
                console.stdout.getvalue()), cast(str,
                                                 console.stderr.getvalue())
Exemple #4
0
def run_goal(
    targets: Sequence[Target],
    *,
    target_type: Optional[List[str]] = None,
    address_regex: Optional[List[str]] = None,
    tag_regex: Optional[List[str]] = None,
) -> str:
    console = MockConsole(use_colors=False)
    run_rule_with_mocks(
        filter_targets,
        rule_args=[
            Targets(targets),
            create_goal_subsystem(
                FilterSubsystem,
                sep="\\n",
                output_file=None,
                target_type=target_type or [],
                address_regex=address_regex or [],
                tag_regex=tag_regex or [],
                # Deprecated.
                type=[],
                target=[],
                regex=[],
                ancestor=[],
            ),
            console,
            RegisteredTargetTypes.create({type(tgt) for tgt in targets}),
        ],
    )
    assert not console.stderr.getvalue()
    return cast(str, console.stdout.getvalue())
Exemple #5
0
def test_line_oriented_goal() -> None:
    class OutputtingGoalOptions(LineOriented, GoalSubsystem):
        name = "dummy"

    class OutputtingGoal(Goal):
        subsystem_cls = OutputtingGoalOptions

    @goal_rule
    def output_rule(console: Console,
                    options: OutputtingGoalOptions) -> OutputtingGoal:
        with options.output(console) as write_stdout:
            write_stdout("output...")
        with options.line_oriented(console) as print_stdout:
            print_stdout("line oriented")
        return OutputtingGoal(0)

    with mock_console(create_options_bootstrapper()) as (console,
                                                         stdio_reader):
        result: OutputtingGoal = run_rule_with_mocks(
            output_rule,
            rule_args=[
                console,
                create_goal_subsystem(OutputtingGoalOptions,
                                      sep="\\n",
                                      output_file=None),
            ],
        )
        assert result.exit_code == 0
        assert stdio_reader.get_stdout() == "output...line oriented\n"
def run_typecheck_rule(
    *,
    request_types: List[Type[TypecheckRequest]],
    targets: List[Target],
    include_sources: bool = True,
) -> Tuple[int, str]:
    console = MockConsole(use_colors=False)
    union_membership = UnionMembership({TypecheckRequest: request_types})
    result: Typecheck = run_rule_with_mocks(
        typecheck,
        rule_args=[console, Targets(targets), union_membership],
        mock_gets=[
            MockGet(
                output_type=TypecheckResults,
                input_type=TypecheckRequest,
                mock=lambda field_set_collection: field_set_collection.
                typecheck_results,
            ),
            MockGet(
                output_type=FieldSetsWithSources,
                input_type=FieldSetsWithSourcesRequest,
                mock=lambda field_sets: FieldSetsWithSources(
                    field_sets if include_sources else ()),
            ),
        ],
        union_membership=union_membership,
    )
    assert not console.stdout.getvalue()
    return result.exit_code, console.stderr.getvalue()
Exemple #7
0
def run_create_coverage_config_rule(coverage_config: Optional[str]) -> str:
    coverage = create_subsystem(
        CoverageSubsystem, config="some_file" if coverage_config else None)
    resolved_config: List[str] = []

    def mock_handle_config(request: CreateDigest) -> Digest:
        assert len(request) == 1
        assert request[0].path == ".coveragerc"
        assert request[0].is_executable is False
        resolved_config.append(request[0].content.decode())
        return Digest("jerry", 30)

    def mock_read_config(_: PathGlobs) -> DigestContents:
        # This shouldn't be called if no config file provided.
        assert coverage_config is not None
        return DigestContents([
            FileContent(path="/dev/null/prelude",
                        content=coverage_config.encode())
        ])

    mock_gets = [
        MockGet(product_type=DigestContents,
                subject_type=PathGlobs,
                mock=mock_read_config),
        MockGet(product_type=Digest,
                subject_type=CreateDigest,
                mock=mock_handle_config),
    ]

    result = run_rule_with_mocks(create_coverage_config,
                                 rule_args=[coverage],
                                 mock_gets=mock_gets)
    assert result.digest.fingerprint == "jerry"
    assert len(resolved_config) == 1
    return resolved_config[0]
Exemple #8
0
def run_typecheck_rule(
    *,
    request_types: List[Type[TypecheckRequest]],
    targets: List[Target],
    include_sources: bool = True,
) -> Tuple[int, str]:
    union_membership = UnionMembership({TypecheckRequest: request_types})
    with mock_console(create_options_bootstrapper()) as (console,
                                                         stdio_reader):
        result: Typecheck = run_rule_with_mocks(
            typecheck,
            rule_args=[console, Targets(targets), union_membership],
            mock_gets=[
                MockGet(
                    output_type=EnrichedTypecheckResults,
                    input_type=TypecheckRequest,
                    mock=lambda field_set_collection: field_set_collection.
                    typecheck_results,
                ),
                MockGet(
                    output_type=FieldSetsWithSources,
                    input_type=FieldSetsWithSourcesRequest,
                    mock=lambda field_sets: FieldSetsWithSources(
                        field_sets if include_sources else ()),
                ),
            ],
            union_membership=union_membership,
        )
        assert not stdio_reader.get_stdout()
        return result.exit_code, stdio_reader.get_stderr()
Exemple #9
0
 def test_run_rule_goal_rule_generator(self) -> None:
     res = run_rule_with_mocks(
         a_goal_rule_generator,
         rule_args=[Console()],
         mock_gets=[MockGet(output_type=A, input_type=str, mock=lambda _: A())],
     )
     assert res == Example(0)
Exemple #10
0
def run_typecheck_rule(
    *,
    request_types: Sequence[Type[CheckRequest]],
    targets: list[Target],
    only: list[str] | None = None,
) -> Tuple[int, str]:
    union_membership = UnionMembership({CheckRequest: request_types})
    check_subsystem = create_subsystem(CheckSubsystem, only=only or [])
    with mock_console(create_options_bootstrapper()) as (console, stdio_reader):
        rule_runner = RuleRunner()
        result: Check = run_rule_with_mocks(
            check,
            rule_args=[
                console,
                Workspace(rule_runner.scheduler, _enforce_effects=False),
                Targets(targets),
                DistDir(relpath=Path("dist")),
                union_membership,
                check_subsystem,
            ],
            mock_gets=[
                MockGet(
                    output_type=CheckResults,
                    input_type=CheckRequest,
                    mock=lambda field_set_collection: field_set_collection.check_results,
                ),
            ],
            union_membership=union_membership,
        )
        assert not stdio_reader.get_stdout()
        return result.exit_code, stdio_reader.get_stderr()
Exemple #11
0
 def test_run_rule_goal_rule_generator(self):
     res = run_rule_with_mocks(
         a_goal_rule_generator,
         rule_args=[Console()],
         mock_gets=[MockGet(product_type=A, subject_type=str, mock=lambda _: A())],
     )
     self.assertEqual(res, Example(0))
Exemple #12
0
def test_all_roots_with_root_at_buildroot() -> None:
    source_root_config = create_subsystem(
        SourceRootConfig,
        root_patterns=["/"],
        marker_filenames=[],
    )

    # This function mocks out reading real directories off the file system
    def provider_rule(_: PathGlobs) -> Snapshot:
        dirs = ("foo", )  # A python package at the buildroot.
        return Snapshot(Digest("abcdef", 10), (), dirs)

    output = run_rule_with_mocks(
        all_roots,
        rule_args=[source_root_config],
        mock_gets=[
            MockGet(product_type=Snapshot,
                    subject_type=PathGlobs,
                    mock=provider_rule),
            MockGet(
                product_type=OptionalSourceRoot,
                subject_type=SourceRootRequest,
                mock=lambda req: OptionalSourceRoot(SourceRoot(".")),
            ),
        ],
    )
    assert {SourceRoot(".")} == set(output)
Exemple #13
0
def run_lint_rule(
    rule_runner: RuleRunner,
    *,
    lint_request_types: List[Type[LintRequest]],
    targets: List[Target],
    per_file_caching: bool,
) -> Tuple[int, str]:
    with mock_console(rule_runner.options_bootstrapper) as (console,
                                                            stdio_reader):
        union_membership = UnionMembership({LintRequest: lint_request_types})
        result: Lint = run_rule_with_mocks(
            lint,
            rule_args=[
                console,
                Workspace(rule_runner.scheduler, _enforce_effects=False),
                Targets(targets),
                create_goal_subsystem(LintSubsystem,
                                      per_file_caching=per_file_caching,
                                      per_target_caching=False),
                union_membership,
                DistDir(relpath=Path("dist")),
            ],
            mock_gets=[
                MockGet(
                    output_type=LintResults,
                    input_type=LintRequest,
                    mock=lambda field_set_collection: field_set_collection.
                    lint_results,
                )
            ],
            union_membership=union_membership,
        )
        assert not stdio_reader.get_stdout()
        return result.exit_code, stdio_reader.get_stderr()
def run_goal(
    *, union_membership: Optional[UnionMembership] = None, details_target: Optional[str] = None
) -> str:
    console = MockConsole(use_colors=False)
    run_rule_with_mocks(
        list_target_types,
        rule_args=[
            RegisteredTargetTypes.create([FortranBinary, FortranLibrary, FortranTests]),
            union_membership or UnionMembership({}),
            create_goal_subsystem(
                TargetTypesSubsystem, sep="\\n", output_file=None, details=details_target
            ),
            console,
            PantsBin(name="./BNF"),
        ],
    )
    return cast(str, console.stdout.getvalue())
Exemple #15
0
def single_target_run(
    rule_runner: RuleRunner,
    address: Address,
    *,
    program_text: bytes,
) -> Run:
    workspace = Workspace(rule_runner.scheduler, _enforce_effects=False)

    class TestRunFieldSet(RunFieldSet):
        required_fields = ()

    class TestBinaryTarget(Target):
        alias = "binary"
        core_fields = ()

    target = TestBinaryTarget({}, address)
    field_set = TestRunFieldSet.create(target)

    with mock_console(rule_runner.options_bootstrapper) as (console, _):
        res = run_rule_with_mocks(
            run,
            rule_args=[
                create_goal_subsystem(RunSubsystem, args=[], cleanup=True),
                create_subsystem(GlobalOptions,
                                 pants_workdir=rule_runner.pants_workdir,
                                 process_cleanup=True),
                workspace,
                BuildRoot(),
                rule_runner.environment,
            ],
            mock_gets=[
                MockGet(
                    output_type=TargetRootsToFieldSets,
                    input_type=TargetRootsToFieldSetsRequest,
                    mock=lambda _: TargetRootsToFieldSets(
                        {target: [field_set]}),
                ),
                MockGet(
                    output_type=WrappedTarget,
                    input_type=WrappedTargetRequest,
                    mock=lambda _: WrappedTarget(target),
                ),
                MockGet(
                    output_type=RunRequest,
                    input_type=TestRunFieldSet,
                    mock=lambda _: create_mock_run_request(
                        rule_runner, program_text),
                ),
                MockEffect(
                    output_type=InteractiveProcessResult,
                    input_type=InteractiveProcess,
                    mock=rule_runner.run_interactive_process,
                ),
            ],
        )
        return cast(Run, res)
Exemple #16
0
def test_strip_address_origin() -> None:
    addr = Address.parse("//:demo")
    result = run_rule_with_mocks(
        strip_address_origins,
        rule_args=[
            AddressesWithOrigins(
                [AddressWithOrigin(addr, AddressLiteralSpec("", "demo"))])
        ],
    )
    assert list(result) == [addr]
Exemple #17
0
def git_worktree(
        gitdir: os.PathLike[str] | None = None,
        subdir: os.PathLike[str] | None = None,
        binary: os.PathLike[str] = PurePath("git"),
) -> GitWorktree | None:
    maybe_git_worktree: MaybeGitWorktree = run_rule_with_mocks(
        rule=get_git_worktree,
        rule_args=[
            GitWorktreeRequest(gitdir=gitdir, subdir=subdir),
            MaybeGitBinary(git_binary=GitBinary(path=str(binary))),
        ],
    )

    return maybe_git_worktree.git_worktree
Exemple #18
0
def run_lint_rule(
    rule_runner: RuleRunner,
    *,
    lint_request_types: Sequence[Type[LintTargetsRequest]],
    targets: list[Target],
    run_files_linter: bool = False,
    batch_size: int = 128,
    only: list[str] | None = None,
) -> Tuple[int, str]:
    union_membership = UnionMembership({
        LintTargetsRequest:
        lint_request_types,
        LintFilesRequest: [MockFilesRequest] if run_files_linter else [],
    })
    lint_subsystem = create_goal_subsystem(
        LintSubsystem,
        batch_size=batch_size,
        only=only or [],
    )
    specs_snapshot = SpecsSnapshot(
        rule_runner.make_snapshot_of_empty_files(["f.txt"]))
    with mock_console(rule_runner.options_bootstrapper) as (console,
                                                            stdio_reader):
        result: Lint = run_rule_with_mocks(
            lint,
            rule_args=[
                console,
                Workspace(rule_runner.scheduler, _enforce_effects=False),
                Targets(targets),
                specs_snapshot,
                lint_subsystem,
                union_membership,
                DistDir(relpath=Path("dist")),
            ],
            mock_gets=[
                MockGet(
                    output_type=LintResults,
                    input_type=LintTargetsRequest,
                    mock=lambda mock_request: mock_request.lint_results,
                ),
                MockGet(
                    output_type=LintResults,
                    input_type=LintFilesRequest,
                    mock=lambda mock_request: mock_request.lint_results,
                ),
            ],
            union_membership=union_membership,
        )
        assert not stdio_reader.get_stdout()
        return result.exit_code, stdio_reader.get_stderr()
Exemple #19
0
    def single_target_run(
        self,
        *,
        console: MockConsole,
        program_text: bytes,
        address_spec: str,
    ) -> Run:
        workspace = Workspace(self.scheduler)
        interactive_runner = InteractiveRunner(self.scheduler)

        class TestRunFieldSet(RunFieldSet):
            required_fields = ()

        class TestBinaryTarget(Target):
            alias = "binary"
            core_fields = ()

        address = Address.parse(address_spec)
        target = TestBinaryTarget({}, address=address)
        target_with_origin = TargetWithOrigin(
            target, AddressLiteralSpec(address.spec_path, address.target_name))
        field_set = TestRunFieldSet.create(target)

        res = run_rule_with_mocks(
            run,
            rule_args=[
                create_goal_subsystem(RunSubsystem, args=[]),
                create_subsystem(GlobalOptions,
                                 pants_workdir=self.pants_workdir),
                console,
                interactive_runner,
                workspace,
                BuildRoot(),
            ],
            mock_gets=[
                MockGet(
                    product_type=TargetsToValidFieldSets,
                    subject_type=TargetsToValidFieldSetsRequest,
                    mock=lambda _: TargetsToValidFieldSets(
                        {target_with_origin: [field_set]}),
                ),
                MockGet(
                    product_type=RunRequest,
                    subject_type=TestRunFieldSet,
                    mock=lambda _: self.create_mock_run_request(program_text),
                ),
            ],
        )
        return cast(Run, res)
Exemple #20
0
def run_fmt_rule(
    rule_runner: RuleRunner,
    *,
    language_target_collection_types: List[Type[LanguageFmtTargets]],
    targets: List[Target],
    result_digest: Digest,
    per_file_caching: bool,
    include_sources: bool = True,
) -> str:
    with mock_console(rule_runner.options_bootstrapper) as (console,
                                                            stdio_reader):
        union_membership = UnionMembership(
            {LanguageFmtTargets: language_target_collection_types})
        result: Fmt = run_rule_with_mocks(
            fmt,
            rule_args=[
                console,
                Targets(targets),
                create_goal_subsystem(FmtSubsystem,
                                      per_file_caching=per_file_caching,
                                      per_target_caching=False),
                Workspace(rule_runner.scheduler),
                union_membership,
            ],
            mock_gets=[
                MockGet(
                    output_type=LanguageFmtResults,
                    input_type=LanguageFmtTargets,
                    mock=lambda language_targets_collection:
                    language_targets_collection.language_fmt_results(
                        result_digest),
                ),
                MockGet(
                    output_type=TargetsWithSources,
                    input_type=TargetsWithSourcesRequest,
                    mock=lambda tgts: TargetsWithSources(
                        tgts if include_sources else ()),
                ),
                MockGet(
                    output_type=Digest,
                    input_type=MergeDigests,
                    mock=lambda _: result_digest,
                ),
            ],
            union_membership=union_membership,
        )
        assert result.exit_code == 0
        assert not stdio_reader.get_stdout()
        return stdio_reader.get_stderr()
Exemple #21
0
def run_prelude_parsing_rule(prelude_content: str) -> BuildFilePreludeSymbols:
    symbols = run_rule_with_mocks(
        evaluate_preludes,
        rule_args=[BuildFileOptions((), prelude_globs=("prelude",))],
        mock_gets=[
            MockGet(
                output_type=DigestContents,
                input_type=PathGlobs,
                mock=lambda _: DigestContents(
                    [FileContent(path="/dev/null/prelude", content=prelude_content.encode())]
                ),
            ),
        ],
    )
    return cast(BuildFilePreludeSymbols, symbols)
Exemple #22
0
def test_build_docker_image_rule(target_values, expected_features):
    address = Address("docker/test", target_name="image")
    image = DockerImage(
        address=address,
        unhydrated_values=target_values,
    )
    field_set = DockerFieldSet.create(image)

    def build_context_mock(
            request: DockerBuildContextRequest) -> DockerBuildContext:
        return DockerBuildContext(digest=EMPTY_DIGEST)

    result = run_rule_with_mocks(
        build_docker_image,
        rule_args=[field_set],
        mock_gets=[
            MockGet(
                output_type=DockerBinary,
                input_type=DockerBinaryRequest,
                mock=lambda _: DockerBinary("/dummy/docker"),
            ),
            MockGet(
                output_type=DockerBuildContext,
                input_type=DockerBuildContextRequest,
                mock=build_context_mock,
            ),
            MockGet(
                output_type=ProcessResult,
                input_type=Process,
                # Process() generation has its own tests in test_docker_binary_build_image
                mock=lambda _: ProcessResult(
                    stdout=b"stdout",
                    stdout_digest=EMPTY_FILE_DIGEST,
                    stderr=b"stderr",
                    stderr_digest=EMPTY_FILE_DIGEST,
                    output_digest=EMPTY_DIGEST,
                ),
            ),
        ],
    )

    assert result.digest == EMPTY_DIGEST
    assert len(result.artifacts) == 1
    assert result.artifacts[0].relpath is None

    version = expected_features.get("version", "latest")
    assert f"Built docker image: image:{version}" in result.artifacts[
        0].extra_log_lines
Exemple #23
0
def resolve_config(path: str | None, content: str | None) -> str:
    coverage_subsystem = create_subsystem(CoverageSubsystem,
                                          config=path,
                                          config_discovery=True)
    resolved_config: list[str] = []

    def mock_find_existing_config(request: ConfigFilesRequest) -> ConfigFiles:
        if request.specified:
            assert path is not None
            snapshot = RuleRunner().make_snapshot_of_empty_files([path])
        else:
            snapshot = EMPTY_SNAPSHOT
        return ConfigFiles(snapshot)

    def mock_read_existing_config(_: Digest) -> DigestContents:
        # This shouldn't be called if no config file provided.
        assert path is not None
        assert content is not None
        return DigestContents([FileContent(path, content.encode())])

    def mock_create_final_config(request: CreateDigest) -> Digest:
        assert len(request) == 1
        assert isinstance(request[0], FileContent)
        assert request[0].path == path if path is not None else ".coveragerc"
        assert request[0].is_executable is False
        resolved_config.append(request[0].content.decode())
        return EMPTY_DIGEST

    mock_gets = [
        MockGet(output_type=ConfigFiles,
                input_type=ConfigFilesRequest,
                mock=mock_find_existing_config),
        MockGet(output_type=DigestContents,
                input_type=Digest,
                mock=mock_read_existing_config),
        MockGet(output_type=Digest,
                input_type=CreateDigest,
                mock=mock_create_final_config),
    ]

    result = run_rule_with_mocks(create_or_update_coverage_config,
                                 rule_args=[coverage_subsystem],
                                 mock_gets=mock_gets)
    assert result.digest == EMPTY_DIGEST
    assert len(resolved_config) == 1
    return resolved_config[0]
Exemple #24
0
def single_target_run(
    rule_runner: RuleRunner,
    address: Address,
    console: MockConsole,
    *,
    program_text: bytes,
) -> Run:
    workspace = Workspace(rule_runner.scheduler)
    interactive_runner = InteractiveRunner(rule_runner.scheduler)

    class TestRunFieldSet(RunFieldSet):
        required_fields = ()

    class TestBinaryTarget(Target):
        alias = "binary"
        core_fields = ()

    target = TestBinaryTarget({}, address=address)
    field_set = TestRunFieldSet.create(target)

    res = run_rule_with_mocks(
        run,
        rule_args=[
            create_goal_subsystem(RunSubsystem, args=[]),
            create_subsystem(GlobalOptions,
                             pants_workdir=rule_runner.pants_workdir),
            console,
            interactive_runner,
            workspace,
            BuildRoot(),
        ],
        mock_gets=[
            MockGet(
                output_type=TargetRootsToFieldSets,
                input_type=TargetRootsToFieldSetsRequest,
                mock=lambda _: TargetRootsToFieldSets({target: [field_set]}),
            ),
            MockGet(
                output_type=RunRequest,
                input_type=TestRunFieldSet,
                mock=lambda _: create_mock_run_request(rule_runner,
                                                       program_text),
            ),
        ],
    )
    return cast(Run, res)
Exemple #25
0
 def _do_find_root(src_root_req: SourceRootRequest) -> OptionalSourceRoot:
     return cast(
         OptionalSourceRoot,
         run_rule_with_mocks(
             get_optional_source_root,
             rule_args=[src_root_req, source_root_config],
             mock_gets=[
                 MockGet(
                     product_type=OptionalSourceRoot,
                     subject_type=SourceRootRequest,
                     mock=_do_find_root,
                 ),
                 MockGet(product_type=Snapshot,
                         subject_type=PathGlobs,
                         mock=_mock_fs_check),
             ],
         ),
     )
Exemple #26
0
 def hydrate_field(
     *, raw_source_files: List[str], hydrated_source_files: Tuple[str, ...]
 ) -> FortranSourcesResult:
     sources_field = FortranTarget(
         {FortranSources.alias: raw_source_files}, address=Address("", target_name="lib")
     )[FortranSources]
     result: FortranSourcesResult = run_rule_with_mocks(
         hydrate_fortran_sources,
         rule_args=[FortranSourcesRequest(sources_field)],
         mock_gets=[
             MockGet(
                 output_type=Snapshot,
                 input_type=PathGlobs,
                 mock=lambda _: Snapshot(EMPTY_DIGEST, files=hydrated_source_files, dirs=()),
             )
         ],
     )
     return result
def run_create_coverage_config_rule(coverage_config: Optional[str]) -> str:
    coverage = create_subsystem(
        CoverageSubsystem, config="some_file" if coverage_config else None)
    resolved_config: List[str] = []

    def mock_find_existing_config(request: ConfigFilesRequest) -> ConfigFiles:
        snapshot = (EMPTY_SNAPSHOT if not request.specified else
                    RuleRunner().make_snapshot_of_empty_files([".coveragerc"]))
        return ConfigFiles(snapshot)

    def mock_read_existing_config(_: Digest) -> DigestContents:
        # This shouldn't be called if no config file provided.
        assert coverage_config is not None
        return DigestContents([
            FileContent(path="/dev/null/prelude",
                        content=coverage_config.encode())
        ])

    def mock_create_final_config(request: CreateDigest) -> Digest:
        assert len(request) == 1
        assert request[0].path == ".coveragerc"
        assert isinstance(request[0], FileContent)
        assert request[0].is_executable is False
        resolved_config.append(request[0].content.decode())
        return EMPTY_DIGEST

    mock_gets = [
        MockGet(output_type=ConfigFiles,
                input_type=ConfigFilesRequest,
                mock=mock_find_existing_config),
        MockGet(output_type=DigestContents,
                input_type=Digest,
                mock=mock_read_existing_config),
        MockGet(output_type=Digest,
                input_type=CreateDigest,
                mock=mock_create_final_config),
    ]

    result = run_rule_with_mocks(create_coverage_config,
                                 rule_args=[coverage],
                                 mock_gets=mock_gets)
    assert result.digest.fingerprint == EMPTY_DIGEST.fingerprint
    assert len(resolved_config) == 1
    return resolved_config[0]
Exemple #28
0
def run_lint_rule(
    rule_runner: RuleRunner,
    *,
    lint_request_types: List[Type[LintRequest]],
    targets: List[Target],
    per_file_caching: bool,
    include_sources: bool = True,
) -> Tuple[int, str]:
    with mock_console(rule_runner.options_bootstrapper) as (console,
                                                            stdio_reader):
        workspace = Workspace(rule_runner.scheduler)
        union_membership = UnionMembership({LintRequest: lint_request_types})
        result: Lint = run_rule_with_mocks(
            lint,
            rule_args=[
                console,
                workspace,
                Targets(targets),
                create_goal_subsystem(LintSubsystem,
                                      per_file_caching=per_file_caching,
                                      per_target_caching=False),
                union_membership,
            ],
            mock_gets=[
                MockGet(
                    output_type=EnrichedLintResults,
                    input_type=LintRequest,
                    mock=lambda field_set_collection: field_set_collection.
                    lint_results,
                ),
                MockGet(
                    output_type=FieldSetsWithSources,
                    input_type=FieldSetsWithSourcesRequest,
                    mock=lambda field_sets: FieldSetsWithSources(
                        field_sets if include_sources else ()),
                ),
                MockGet(output_type=Digest,
                        input_type=MergeDigests,
                        mock=lambda _: EMPTY_DIGEST),
            ],
            union_membership=union_membership,
        )
        assert not stdio_reader.get_stdout()
        return result.exit_code, stdio_reader.get_stderr()
Exemple #29
0
def test_parse_address_family_empty() -> None:
    """Test that parsing an empty BUILD file results in an empty AddressFamily."""
    af = run_rule_with_mocks(
        parse_address_family,
        rule_args=[
            Parser(build_root="", target_type_aliases=[], object_aliases=BuildFileAliases()),
            BuildFileOptions(("BUILD",)),
            BuildFilePreludeSymbols(FrozenDict()),
            AddressFamilyDir("/dev/null"),
        ],
        mock_gets=[
            MockGet(
                output_type=DigestContents,
                input_type=PathGlobs,
                mock=lambda _: DigestContents([FileContent(path="/dev/null/BUILD", content=b"")]),
            ),
        ],
    )
    assert len(af.name_to_target_adaptors) == 0
Exemple #30
0
 def run_lint_rule(
     self,
     *,
     lint_request_types: List[Type[LintRequest]],
     targets: List[Target],
     per_file_caching: bool,
     include_sources: bool = True,
 ) -> Tuple[int, str]:
     console = MockConsole(use_colors=False)
     workspace = Workspace(self.scheduler)
     union_membership = UnionMembership({LintRequest: lint_request_types})
     result: Lint = run_rule_with_mocks(
         lint,
         rule_args=[
             console,
             workspace,
             Targets(targets),
             create_goal_subsystem(LintSubsystem,
                                   per_file_caching=per_file_caching,
                                   per_target_caching=False),
             union_membership,
         ],
         mock_gets=[
             MockGet(
                 product_type=LintResults,
                 subject_type=LintRequest,
                 mock=lambda field_set_collection: field_set_collection.
                 lint_results,
             ),
             MockGet(
                 product_type=FieldSetsWithSources,
                 subject_type=FieldSetsWithSourcesRequest,
                 mock=lambda field_sets: FieldSetsWithSources(
                     field_sets if include_sources else ()),
             ),
             MockGet(product_type=Digest,
                     subject_type=MergeDigests,
                     mock=lambda _: EMPTY_DIGEST),
         ],
         union_membership=union_membership,
     )
     assert not console.stdout.getvalue()
     return result.exit_code, console.stderr.getvalue()