Morteza Ardini
Morteza Ardini

Reputation: 11

Bazel: how to get access to srcs of a filegroup?

I have some html files in "root/html_files/*.html" directory. I want to iterate on these html files and run some bazel rules on them, from "root/tests/" directory. So, I made a filegroup of those html files and tried to get access to them in "root/tests/" directory, but that is't working. I wonder if it is possible?

My BUILD file in "root/" directory:

    HTMLS_LIST = glob(["html_files/*.html",])
    filegroup(
        name = "html_files",
        srcs = HTMLS_LIST,
        visibility = [ "//visibility:public" ],)

My BUILD file in "root/tests/" directory:

    load("//tests:automation_test.bzl", "make_and_run_html_tests")
    make_and_run_html_tests(
        name = 'test_all_htmls',
        srcs = ['test/automation_test.py'],
        html_files = '//:html_files')

My bzl file in "root/tests/" directory:


def make_and_run_html_tests(name, html_files, srcs):
    tests = []
    for html_file in html_files: # I want to iterate on sources of html filegroup here
        folders = html_file.split("/")
        filename = folders[-1].split(".")[0]
        test_rule_name = 'test_' + filename + '_file'
        native.py_test(
            name = test_rule_name,
            srcs = srcs,
            main = srcs[0],
            data = [
                html_file,
                ],
            args = [html_file],
        )
        testname = ":" + test_rule_name
        tests.append(testname)

    native.test_suite(
        name = name,
        tests = tests,
    )

And my python unittest file in "root/tests/" directory:

import sys
import codecs
import unittest


class TestHtmlDocumetns(unittest.TestCase):

    def setUp(self):
        self.html_file_path = sys.argv[1]

    def test_html_file(self):
        fid = codecs.open(self.html_file_path, 'r')
        print(fid.read())
        self.assertTrue(fid)


if __name__ == '__main__':

    unittest.main(argv=[sys.argv[1]])

Upvotes: 1

Views: 12045

Answers (1)

Matt Mackay
Matt Mackay

Reputation: 1329

You can't access the references to the files inside another filegroup / rule from within a macro like that. You'd need to create a rule and access them via the ctx.files attr

However, you can iterate over them if you were to remove the filegroup, and pass the glob directly to the macro:

HTMLS_LIST = glob(["html_files/*.html"])

make_and_run_html_tests(
  name = 'test_all_htmls',
  srcs = ['test/automation_test.py'],
  html_files = HTMLS_LIST
)

The glob is resolved to an array before expanding the macro

Upvotes: 3

Related Questions