Skip to content

Commit

Permalink
refactor: use lambda to allow test to mock repository_ctx
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeagle committed Nov 8, 2021
1 parent b34d373 commit cac9678
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 18 deletions.
2 changes: 1 addition & 1 deletion .bazelversion
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
4.2.0
5.0.0-pre.20211011.2
# The first line of this file is used by Bazelisk and Bazel to be sure
# the right version of Bazel is used to build and test this repo.
# This also defines which version is used on CI.
Expand Down
17 changes: 2 additions & 15 deletions js/private/translate_package_lock.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,7 @@ def npm_repositories():
)])
return bzl_out

def _define_aliases(repository_ctx, lockfile, do_writes = True):
# Return value if do_writes = False
aliases = {}

def _define_aliases(repository_ctx, lockfile):
# The lockfile format refers to the context as the package with empty name.
# This gives us a way to know which deps the user declared in their package.json
# (the direct dependencies).
Expand All @@ -105,17 +102,7 @@ alias(name = "{package}", actual = "{actual}", visibility = ["//visibility:publi
package = direct_name.split("/")[-1],
actual = "@" + _repo_name(direct_name, direct_dep["version"]),
)
if do_writes:
repository_ctx.file(direct_name + "/BUILD.bazel", dep_build_content)
else:
# In a starlark unit test, there is no global mutable data structure
# that allows us to capture the writes using a mock repository_ctx
# so we need a different return type that lets us assert on what's written.
# We could do this for production use as well, but then we'd waste memory
# in large package-lock.json files holding references to values
# we no longer need.
aliases[direct_name + "/BUILD.bazel"] = dep_build_content
return None if do_writes else aliases
repository_ctx.file(direct_name + "/BUILD.bazel", dep_build_content)

def _translate_package_lock(repository_ctx):
lock_content = json.decode(repository_ctx.read(repository_ctx.attr.package_lock))
Expand Down
7 changes: 5 additions & 2 deletions js/test/translate_package_lock_tests.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,11 @@ def npm_repositories():

def _aliases_test_impl(ctx):
env = unittest.begin(ctx)
mock_repository_ctx = struct()
actual = translate_package_lock.testonly_define_aliases(mock_repository_ctx, _lockfile, False)
actual = {}
mock_repository_ctx = struct(
file = lambda path, content: actual.update({path: content}),
)
translate_package_lock.testonly_define_aliases(mock_repository_ctx, _lockfile)
asserts.equals(env, 1, len(actual.items()))

# Note: @gregmagolan/test-a should not appear here since it's only a transitive dependency
Expand Down

0 comments on commit cac9678

Please sign in to comment.