aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authornickreid <nickreid@google.com>2023-10-09 12:23:30 -0700
committerCopybara-Service <copybara-worker@google.com>2023-10-09 12:24:04 -0700
commit296fe3d842cb253a03ee6c8157090749ef55af49 (patch)
treed2ae3b3661c583b6e66dedb3e0463f4ff6491573
parentb3b689f3fb5d2428a37574e3e8f34398765b02a6 (diff)
downloadbazelbuild-kotlin-rules-296fe3d842cb253a03ee6c8157090749ef55af49.tar.gz
Move some more testing utils under common/testing
PiperOrigin-RevId: 572008882
-rw-r--r--kotlin/common/testing/analysis.bzl79
-rw-r--r--kotlin/common/testing/testing_rules.bzl113
-rw-r--r--tests/analysis/assert_failure_test.bzl15
-rw-r--r--tests/analysis/for_test.bzl24
-rw-r--r--tests/analysis/util.bzl109
5 files changed, 205 insertions, 135 deletions
diff --git a/kotlin/common/testing/analysis.bzl b/kotlin/common/testing/analysis.bzl
new file mode 100644
index 0000000..7774ead
--- /dev/null
+++ b/kotlin/common/testing/analysis.bzl
@@ -0,0 +1,79 @@
+# Copyright 2022 Google LLC. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the License);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""kt_analysis"""
+
+load("//:visibility.bzl", "RULES_KOTLIN")
+
+def _get_action(actions, mnemonic):
+ """Get a specific action
+
+ Args:
+ actions: [List[Action]]
+ mnemonic: [string] Identify the action whose args to search
+
+ Returns:
+ [Optional[action]] The arg value, or None if it couldn't be found
+ """
+ menmonic_actions = [a for a in actions if a.mnemonic == mnemonic]
+ if len(menmonic_actions) == 0:
+ return None
+ elif len(menmonic_actions) > 1:
+ fail("Expected a single '%s' action" % mnemonic)
+
+ return menmonic_actions[0]
+
+def _get_arg(action, arg_name, style = "trim"):
+ """Get a named arg from a specific action
+
+ Args:
+ action: [Optional[Action]]
+ arg_name: [string]
+ style: ["trim"|"next"|"list"] The style of commandline arg
+
+ Returns:
+ [Optional[string]] The arg value, or None if it couldn't be found
+ """
+ if not action:
+ return None
+
+ args = action.argv
+ matches = [(i, a) for (i, a) in enumerate(args) if a.startswith(arg_name)]
+ if len(matches) == 0:
+ return None
+ elif len(matches) > 1:
+ fail("Expected a single '%s' arg" % arg_name)
+ (index, arg) = matches[0]
+
+ if style == "trim":
+ return arg[len(arg_name):]
+ elif style == "next":
+ return args[index + 1]
+ elif style == "list":
+ result = []
+ for i in range(index + 1, len(args)):
+ if args[i].startswith("--"):
+ break
+ result.append(args[i])
+ return result
+
+ else:
+ fail("Unrecognized arg style '%s" % style)
+
+kt_analysis = struct(
+ # go/keep-sorted start
+ get_action = _get_action,
+ get_arg = _get_arg,
+ # go/keep-sorted end
+)
diff --git a/kotlin/common/testing/testing_rules.bzl b/kotlin/common/testing/testing_rules.bzl
new file mode 100644
index 0000000..2e9c3df
--- /dev/null
+++ b/kotlin/common/testing/testing_rules.bzl
@@ -0,0 +1,113 @@
+# Copyright 2022 Google LLC. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the License);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""kt_testing_rules"""
+
+load("//:visibility.bzl", "RULES_KOTLIN")
+load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts")
+
+# Mark targets that's aren't expected to build, but are needed for analysis test assertions.
+_ONLY_FOR_ANALYSIS_TAGS = ["manual", "nobuilder", "notap"]
+
+def _wrap_for_analysis(inner_rule):
+ """Wrap an existing rule to make it easier to use in analysis tests.
+
+ Args:
+ inner_rule: [rule|macro]
+
+ Returns:
+ [macro] Calls inner_rule with appropate tags, returning the target name
+ """
+
+ def wrapper(name, tags = [], **kwargs):
+ inner_rule(
+ name = name,
+ tags = tags + _ONLY_FOR_ANALYSIS_TAGS,
+ **kwargs
+ )
+ return name
+
+ return wrapper
+
+_assert_failure_test = analysistest.make(
+ impl = lambda ctx: _assert_failure_test_impl(ctx),
+ expect_failure = True,
+ attrs = dict(
+ msg_contains = attr.string(mandatory = True),
+ ),
+)
+
+def _assert_failure_test_impl(ctx):
+ env = analysistest.begin(ctx)
+ asserts.expect_failure(env, ctx.attr.msg_contains)
+ return analysistest.end(env)
+
+def _create_file(name, content = ""):
+ """Declare a generated file with optional content.
+
+ Args:
+ name: [string] The relative file path
+ content: [string]
+
+ Returns:
+ [File] The label of the file
+ """
+
+ if content.startswith("\n"):
+ content = content[1:-1]
+
+ native.genrule(
+ name = "gen_" + name,
+ outs = [name],
+ cmd = """
+cat > $@ <<EOF
+%s
+EOF
+""" % content,
+ )
+
+ return name
+
+_create_dir = rule(
+ implementation = lambda ctx: _create_dir_impl(ctx),
+ attrs = dict(
+ subdir = attr.string(),
+ srcs = attr.label_list(allow_files = True),
+ ),
+)
+
+def _create_dir_impl(ctx):
+ dir = ctx.actions.declare_directory(ctx.attr.name)
+
+ command = "mkdir -p {0} " + ("&& cp {1} {0}" if ctx.files.srcs else "# {1}")
+ ctx.actions.run_shell(
+ command = command.format(
+ dir.path + "/" + ctx.attr.subdir,
+ " ".join([s.path for s in ctx.files.srcs]),
+ ),
+ inputs = ctx.files.srcs,
+ outputs = [dir],
+ )
+
+ return [DefaultInfo(files = depset([dir]))]
+
+kt_testing_rules = struct(
+ # go/keep-sorted start
+ ONLY_FOR_ANALYSIS_TAGS = _ONLY_FOR_ANALYSIS_TAGS,
+ assert_failure_test = _assert_failure_test,
+ create_dir = _wrap_for_analysis(_create_dir),
+ create_file = _create_file,
+ wrap_for_analysis = _wrap_for_analysis,
+ # go/keep-sorted end
+)
diff --git a/tests/analysis/assert_failure_test.bzl b/tests/analysis/assert_failure_test.bzl
index 2a742c3..8731e7b 100644
--- a/tests/analysis/assert_failure_test.bzl
+++ b/tests/analysis/assert_failure_test.bzl
@@ -14,18 +14,7 @@
"""An assertion for analysis failure."""
-load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts")
load("//:visibility.bzl", "RULES_KOTLIN")
+load("//kotlin/common/testing:testing_rules.bzl", "kt_testing_rules")
-def _assert_failure_test_impl(ctx):
- env = analysistest.begin(ctx)
- asserts.expect_failure(env, ctx.attr.msg_contains)
- return analysistest.end(env)
-
-assert_failure_test = analysistest.make(
- _assert_failure_test_impl,
- expect_failure = True,
- attrs = dict(
- msg_contains = attr.string(mandatory = True),
- ),
-)
+assert_failure_test = kt_testing_rules.assert_failure_test
diff --git a/tests/analysis/for_test.bzl b/tests/analysis/for_test.bzl
index 2a75726..67c8c63 100644
--- a/tests/analysis/for_test.bzl
+++ b/tests/analysis/for_test.bzl
@@ -14,27 +14,11 @@
"""Rules for test."""
-load("//kotlin:jvm_library.bzl", "kt_jvm_library")
-load("//tests/analysis:util.bzl", "ONLY_FOR_ANALYSIS_TEST_TAGS")
load("//:visibility.bzl", "RULES_KOTLIN")
-
-def _kt_jvm_library_for_test(name, **kwargs):
- kt_jvm_library(
- name = name,
- tags = ONLY_FOR_ANALYSIS_TEST_TAGS,
- **kwargs
- )
- return name
-
-def _java_library_for_test(name, **kwargs):
- native.java_library(
- name = name,
- tags = ONLY_FOR_ANALYSIS_TEST_TAGS,
- **kwargs
- )
- return name
+load("//kotlin:jvm_library.bzl", "kt_jvm_library")
+load("//kotlin/common/testing:testing_rules.bzl", "kt_testing_rules")
rules_for_test = struct(
- kt_jvm_library = _kt_jvm_library_for_test,
- java_library = _java_library_for_test,
+ kt_jvm_library = kt_testing_rules.wrap_for_analysis(kt_jvm_library),
+ java_library = kt_testing_rules.wrap_for_analysis(native.java_library),
)
diff --git a/tests/analysis/util.bzl b/tests/analysis/util.bzl
index 653843b..c8e5b21 100644
--- a/tests/analysis/util.bzl
+++ b/tests/analysis/util.bzl
@@ -15,111 +15,16 @@
"""Some utils"""
load("//:visibility.bzl", "RULES_KOTLIN")
+load("//kotlin/common/testing:analysis.bzl", "kt_analysis")
+load("//kotlin/common/testing:testing_rules.bzl", "kt_testing_rules")
# Mark targets that's aren't expected to build, but are needed for analysis test assertions.
-ONLY_FOR_ANALYSIS_TEST_TAGS = ["manual", "nobuilder", "only_for_analysis_test"]
+ONLY_FOR_ANALYSIS_TEST_TAGS = kt_testing_rules.ONLY_FOR_ANALYSIS_TAGS
-def create_file(name, content):
- if content.startswith("\n"):
- content = content[1:-1]
+create_file = kt_testing_rules.create_file
- native.genrule(
- name = "gen_" + name,
- outs = [name],
- cmd = """
-cat > $@ <<EOF
-%s
-EOF
-""" % content,
- )
+create_dir = kt_testing_rules.create_dir
- return name
+get_arg = kt_analysis.get_arg
-def _create_dir_impl(ctx):
- dir = ctx.actions.declare_directory(ctx.attr.name)
-
- command = "mkdir -p {0} " + ("&& cp {1} {0}" if ctx.files.srcs else "# {1}")
- ctx.actions.run_shell(
- command = command.format(
- dir.path + "/" + ctx.attr.subdir,
- " ".join([s.path for s in ctx.files.srcs]),
- ),
- inputs = ctx.files.srcs,
- outputs = [dir],
- )
-
- return [DefaultInfo(files = depset([dir]))]
-
-_create_dir = rule(
- implementation = _create_dir_impl,
- attrs = dict(
- subdir = attr.string(),
- srcs = attr.label_list(allow_files = True),
- ),
-)
-
-def create_dir(
- name,
- subdir = None,
- srcs = None):
- _create_dir(
- name = name,
- subdir = subdir,
- srcs = srcs,
- )
- return name
-
-def get_action(actions, mnemonic):
- """Get a specific action
-
- Args:
- actions: [List[Action]]
- mnemonic: [string] Identify the action whose args to search
-
- Returns:
- [Optional[action]] The arg value, or None if it couldn't be found
- """
- menmonic_actions = [a for a in actions if a.mnemonic == mnemonic]
- if len(menmonic_actions) == 0:
- return None
- elif len(menmonic_actions) > 1:
- fail("Expected a single '%s' action" % mnemonic)
-
- return menmonic_actions[0]
-
-def get_arg(action, arg_name, style = "trim"):
- """Get a named arg from a specific action
-
- Args:
- action: [Optional[Action]]
- arg_name: [string]
- style: [Optional[string]] The style of commandline arg
-
- Returns:
- [Optional[string]] The arg value, or None if it couldn't be found
- """
- if not action:
- return None
-
- args = action.argv
- matches = [(i, a) for (i, a) in enumerate(args) if a.startswith(arg_name)]
- if len(matches) == 0:
- return None
- elif len(matches) > 1:
- fail("Expected a single '%s' arg" % arg_name)
- (index, arg) = matches[0]
-
- if style == "trim":
- return arg[len(arg_name):]
- elif style == "next":
- return args[index + 1]
- elif style == "list":
- result = []
- for i in range(index + 1, len(args)):
- if args[i].startswith("--"):
- break
- result.append(args[i])
- return result
-
- else:
- fail("Unrecognized arg style '%s" % style)
+get_action = kt_analysis.get_action