1# Copyright (C) 2023 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts")
16load(":host_for_device.bzl", "java_host_for_device")
17load(":import.bzl", "java_import")
18
19Platform = provider(
20    "Platform of the leaf dependency in a linear dependency chain",
21    fields = {
22        "platform": "the target platform",
23        "host_platform": "the host platform",
24    },
25)
26
27def _host_for_device_tester_aspect_impl(target, ctx):
28    if ctx.rule.attr.exports and len(ctx.rule.attr.exports) > 0 and Platform in ctx.rule.attr.exports[0]:
29        return ctx.rule.attr.exports[0][Platform]
30    return Platform(
31        platform = ctx.fragments.platform.platform,
32        host_platform = ctx.fragments.platform.host_platform,
33    )
34
35host_for_device_tester_aspect = aspect(
36    implementation = _host_for_device_tester_aspect_impl,
37    attr_aspects = ["exports"],
38    fragments = ["platform"],
39    provides = [Platform],
40)
41
42def _host_for_device_dep_runs_in_exec_config_test_impl(ctx):
43    env = analysistest.begin(ctx)
44    target_under_test = analysistest.target_under_test(env)
45    actual_platform = target_under_test[Platform].platform
46    expected_platform = target_under_test[Platform].host_platform
47    asserts.equals(env, expected_platform, actual_platform)
48    asserts.true(env, JavaInfo in target_under_test, "Expected host_for_device to provide JavaInfo")
49    return analysistest.end(env)
50
51host_for_device_dep_runs_in_exec_config_test = analysistest.make(
52    _host_for_device_dep_runs_in_exec_config_test_impl,
53    extra_target_under_test_aspects = [host_for_device_tester_aspect],
54)
55
56def test_host_for_device(name):
57    java_host_for_device(
58        name = name + "_parent",
59        exports = [name + "_child"],
60        tags = ["manual"],
61    )
62    java_import(
63        name = name + "_child",
64        jars = ["blah.jar"],
65        tags = ["manual"],
66    )
67    host_for_device_dep_runs_in_exec_config_test(
68        name = name,
69        target_under_test = name + "_parent",
70    )
71    return name
72
73def host_for_device_test_suite(name):
74    native.test_suite(
75        name = name,
76        tests = [test_host_for_device("test_host_for_device")],
77    )
78