# Copyright 2023 The Bazel Authors. 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. """# FileSubject""" load(":str_subject.bzl", "StrSubject") def _file_subject_new(file, meta): """Creates a FileSubject asserting against the given file. Method: FileSubject.new Args: file: ([`File`]) the file to assert against. meta: ([`ExpectMeta`]) Returns: [`FileSubject`] object. """ # buildifier: disable=uninitialized public = struct( # keep sorted start equals = lambda *a, **k: _file_subject_equals(self, *a, **k), path = lambda *a, **k: _file_subject_path(self, *a, **k), short_path_equals = lambda *a, **k: _file_subject_short_path_equals(self, *a, **k), # keep sorted end ) self = struct(file = file, meta = meta, public = public) return public def _file_subject_equals(self, expected): """Asserts that `expected` references the same file as `self`. This uses Bazel's notion of [`File`] equality, which usually includes the configuration, owning action, internal hash, etc of a `File`. The particulars of comparison depend on the actual Java type implementing the `File` object (some ignore owner, for example). NOTE: This does not compare file content. Starlark cannot read files. NOTE: Same files generated by different owners are likely considered not equal to each other. The alternative for this is to assert the `File.path` paths are equal using [`FileSubject.path()`] Method: FileSubject.equals """ if self.file == expected: return self.meta.add_failure( "expected: {}".format(expected), "actual: {}".format(self.file), ) def _file_subject_path(self): """Returns a `StrSubject` asserting on the files `path` value. Method: FileSubject.path Returns: [`StrSubject`] object. """ return StrSubject.new( self.file.path, meta = self.meta.derive("path()"), ) def _file_subject_short_path_equals(self, path): """Asserts the file's short path is equal to the given path. Method: FileSubject.short_path_equals Args: self: implicitly added. path: ([`str`]) the value the file's `short_path` must be equal to. """ path = self.meta.format_str(path) if path == self.file.short_path: return self.meta.add_failure( "expected: {}".format(path), "actual: {}".format(self.file.short_path), ) # We use this name so it shows up nice in docs. # buildifier: disable=name-conventions FileSubject = struct( new = _file_subject_new, equals = _file_subject_equals, path = _file_subject_path, short_path_equals = _file_subject_short_path_equals, )