def test_visibility(self):
        """Confirm that SNOPT's symbols are not exported in the installed
        libdrake.so.  See comments in //tools/workspace/snopt/... for details.
        """

        # The shared library to be tested.
        libdrake = os.path.join(
            install_test_helper.get_install_dir(),
            "lib/libdrake.so"
            )
        self.assertTrue(os.path.exists(libdrake))

        # Dump the symbol names to an output string.
        if sys.platform == "linux2":
            command = ["readelf", "--wide", "--symbols"]
            undefined_marker = " UND "
        else:
            command = ["nm", "-a"]
            undefined_marker = " U "
        output = subprocess.check_output(command + [libdrake]).decode("utf8")
        for line in output.splitlines():
            if undefined_marker in line:
                # Ignore undefined references (like snprintf).
                continue
            # Most of snopt's symbols are 'snfoo' or 'f_snfoo' or '_snfoo'.  If
            # we don't find any of those, it seems unlikely that we would find
            # any others like the s08foo ones, etc.
            self.assertNotIn(" sn", line)
            self.assertNotIn(" f_sn", line)
            self.assertNotIn(" _sn", line)
예제 #2
0
 def test_install(self):
     # Get install directory.
     install_dir = install_test_helper.get_install_dir()
     executable_folder = os.path.join(install_dir, "bin")
     install_test_helper.check_call(
         [os.path.join(executable_folder, "lcm-gen"), "--help"],
         )
예제 #3
0
    def test_install(self):
        # Fail (on purpose) if not given exactly one command line argument.
        self.assertEqual(len(sys.argv), 2)
        with open(sys.argv[1], 'r') as f:
            lines = f.readlines()

        # Install into bazel read-only temporary directory. The temporary
        # directory does not need to be removed as bazel tests are run in a
        # scratch space.
        install_test_helper.install()
        installation_folder = install_test_helper.get_install_dir()
        self.assertTrue(os.path.isdir(installation_folder))

        # Verify install directory content.
        content = set(os.listdir(installation_folder))
        self.assertSetEqual(set(['bin', 'include', 'lib', 'share']), content)

        # Our launched processes should be independent, not inherit their
        # runfiles from the install_test.py runner.
        cmd_env = dict(os.environ)
        for key in ["RUNFILES_MANIFEST_FILE", "RUNFILES_DIR", "TEST_SRCDIR"]:
            if key in cmd_env:
                del cmd_env[key]

        # Execute the install actions.
        for cmd in lines:
            cmd = cmd.strip()
            print("+ {}".format(cmd))
            install_test_helper.check_call(
                [os.path.join(os.getcwd(), cmd)],
                env=cmd_env)
    def test_visibility(self):
        """Confirm that SNOPT's symbols are not exported in the installed
        libdrake.so.  See comments in //tools/workspace/snopt/... for details.
        """

        # The shared library to be tested.
        libdrake = os.path.join(install_test_helper.get_install_dir(),
                                "lib/libdrake.so")
        self.assertTrue(os.path.exists(libdrake))

        # Dump the symbol names to an output string.
        if sys.platform == "linux2":
            command = ["readelf", "--wide", "--symbols"]
            undefined_marker = " UND "
        else:
            command = ["nm", "-a"]
            undefined_marker = " U "
        output = subprocess.check_output(command + [libdrake])
        for line in output.splitlines():
            if undefined_marker in line:
                # Ignore undefined references (like snprintf).
                continue
            # Most of snopt's symbols are 'snfoo' or 'f_snfoo' or '_snfoo'.  If
            # we don't find any of those, it seems unlikely that we would find
            # any others like the s08foo ones, etc.
            self.assertNotIn(" sn", line)
            self.assertNotIn(" f_sn", line)
            self.assertNotIn(" _sn", line)
    def test_install_and_run(self):
        install_dir = install_test_helper.get_install_dir()
        resource_subfolder = "share/drake/"
        installed_sentinel = os.path.join(install_dir, resource_subfolder,
                                          ".drake-find_resource-sentinel")
        # Verifies that the sentinel file exists in the installed directory.
        # If it has been removed, we need to update this test.
        self.assertTrue(os.path.isfile(installed_sentinel))
        # Create a resource in the temporary directory.
        tmp_dir = install_test_helper.create_temporary_dir()

        resource_folder = os.path.join(tmp_dir, resource_subfolder)
        test_folder = os.path.join(resource_folder, "common/test")
        os.makedirs(test_folder)
        # Create sentinel file.
        sentinel = os.path.join(resource_folder,
                                os.path.basename(installed_sentinel))
        os.symlink(installed_sentinel, sentinel)
        # Create resource file.
        resource = os.path.join(test_folder, "tmp_resource")
        resource_data = "tmp_resource"
        with open(resource, "w") as f:
            f.write(resource_data)

        # Cross-check the resource root environment variable name.
        env_name = "DRAKE_RESOURCE_ROOT"
        resource_tool = os.path.join(install_dir,
                                     "share/drake/common/resource_tool")
        output_name = install_test_helper.check_output([
            resource_tool,
            "--print_resource_root_environment_variable_name",
        ], ).strip()
        self.assertEqual(output_name, env_name)

        # Use the installed resource_tool to find a resource.
        tool_env = dict(os.environ)
        tool_env[env_name] = os.path.join(tmp_dir, "share")
        absolute_path = install_test_helper.check_output(
            [
                resource_tool,
                "--print_resource_path",
                "drake/common/test/tmp_resource",
            ],
            env=tool_env,
        ).strip()
        with open(absolute_path, 'r') as data:
            self.assertEqual(data.read(), resource_data)

        # Use --add_resource_search_path instead of environment variable
        # to find resources.
        absolute_path = install_test_helper.check_output([
            resource_tool,
            "--print_resource_path",
            "drake/common/test/tmp_resource",
            "--add_resource_search_path",
            os.path.join(tmp_dir, "share"),
        ], ).strip()
        with open(absolute_path, 'r') as data:
            self.assertEqual(data.read(), resource_data)
예제 #6
0
 def setUpClass(cls):
     # Install into bazel read-only temporary directory.  We expect this
     # method to be called exactly once, so we assert that the install
     # directory must not exist beforehand, but must exist afterward.
     cls._installation_folder = install_test_helper.get_install_dir()
     assert not os.path.exists(cls._installation_folder)
     install_test_helper.install()
     assert os.path.isdir(cls._installation_folder)
예제 #7
0
 def test_install(self):
     # Get install directory
     install_dir = install_test_helper.get_install_dir()
     # Make sure the simulation can run without error.
     simulation = os.path.join(
         install_dir,
         "share/drake/examples/kuka_iiwa_arm/kuka_simulation")
     self.assertTrue(os.path.exists(simulation), "Can't find " + simulation)
     install_test_helper.check_call([simulation, "--simulation_sec=0.01"])
    def test_find_package_drake(self):
        cmake_source_dir = install_test_helper.create_temporary_dir("src")

        cc_content_drake = """
            #include <drake/common/symbolic.h>
            int main() {
              drake::symbolic::Environment environment;
              return 0;
            }
        """

        cc_filename_drake = os.path.join(cmake_source_dir, "main_drake.cc")

        with open(cc_filename_drake, "w") as f:
            f.write(textwrap.dedent(cc_content_drake))

        cc_content_drake_common_text_logging_gflags = """
            #include <drake/common/text_logging_gflags.h>
            int main() {
              drake::logging::HandleSpdlogGflags();
              return 0;
            }
        """

        cc_filename_drake_common_text_logging_gflags = os.path.join(
            cmake_source_dir, "main_drake_common_text_logging_gflags.cc")

        with open(cc_filename_drake_common_text_logging_gflags, "w") as f:
            f.write(textwrap.dedent(
                cc_content_drake_common_text_logging_gflags))

        cmake_prefix_path = install_test_helper.get_install_dir()

        cmake_content = """
            cmake_minimum_required(VERSION 3.10)
            project(find_package_drake_install_test)
            set(CMAKE_PREFIX_PATH {cmake_prefix_path})
            find_package(drake CONFIG REQUIRED)
            add_executable(main_drake main_drake.cc)
            target_link_libraries(main_drake drake::drake)
            add_executable(main_drake_common_text_logging_gflags
              main_drake_common_text_logging_gflags.cc)
            target_link_libraries(main_drake_common_text_logging_gflags
              drake::drake-common-text-logging-gflags)
        """.format(cmake_prefix_path=cmake_prefix_path)

        cmake_filename = os.path.join(cmake_source_dir, "CMakeLists.txt")

        with open(cmake_filename, "w") as f:
            f.write(textwrap.dedent(cmake_content))

        cmake_binary_dir = install_test_helper.create_temporary_dir("build")

        subprocess.check_call(["cmake", cmake_source_dir],
                              cwd=cmake_binary_dir)
        subprocess.check_call("make", cwd=cmake_binary_dir)
예제 #9
0
 def testDrakeFindResourceOrThrowInInstall(self):
     # Override PYTHONPATH to only use the installed `pydrake` module.
     env_python_path = "PYTHONPATH"
     tool_env = dict(os.environ)
     tool_env[env_python_path] = os.path.abspath(
         os.path.join(install_test_helper.get_install_dir(), "lib",
                      "python2.7", "site-packages"))
     data_folder = os.path.join(install_test_helper.get_install_dir(),
                                "share", "drake")
     # Calling `pydrake.getDrakePath()` twice verifies that there
     # is no memory allocation issue in the C code.
     output_path = install_test_helper.check_output(
         [
             install_test_helper.get_python_executable(), "-c",
             "import pydrake; print(pydrake.getDrakePath());\
          import pydrake; print(pydrake.getDrakePath())"
         ],
         env=tool_env,
     ).strip()
     found_install_path = (data_folder in output_path)
     self.assertTrue(found_install_path)
예제 #10
0
 def testDrakeFindResourceOrThrowInInstall(self):
     # Override PYTHONPATH to only use the installed `pydrake` module.
     env_python_path = "PYTHONPATH"
     tool_env = dict(os.environ)
     tool_env[env_python_path] = os.path.abspath(
         os.path.join(install_test_helper.get_install_dir(),
                      "lib", "python2.7", "site-packages")
     )
     data_folder = os.path.join(install_test_helper.get_install_dir(),
                                "share", "drake")
     # Calling `pydrake.getDrakePath()` twice verifies that there
     # is no memory allocation issue in the C code.
     output_path = install_test_helper.check_output(
         [install_test_helper.get_python_executable(),
          "-c", "import pydrake; print(pydrake.getDrakePath());\
          import pydrake; print(pydrake.getDrakePath())"
          ],
         env=tool_env,
         ).strip()
     found_install_path = (data_folder in output_path)
     self.assertTrue(found_install_path)
예제 #11
0
 def test_install(self):
     # Get install directory.
     install_dir = install_test_helper.get_install_dir()
     # Override PYTHONPATH to only use the installed `pydrake` module.
     env_python_path = "PYTHONPATH"
     tool_env = dict(os.environ)
     tool_env[env_python_path] = \
         install_test_helper.get_python_site_packages_dir(install_dir)
     # Ensure we can import all user-visible modules.
     script = "import pydrake.all"
     install_test_helper.check_call(
         [install_test_helper.get_python_executable(), "-c", script],
         env=tool_env)
예제 #12
0
 def test_install(self):
     # Get install directory.
     install_dir = install_test_helper.get_install_dir()
     # Override PYTHONPATH to only use the installed `pydrake` module.
     env_python_path = "PYTHONPATH"
     tool_env = dict(os.environ)
     tool_env[env_python_path] = \
         install_test_helper.get_python_site_packages_dir(install_dir)
     # Ensure we can import all user-visible modules.
     script = "import pydrake.all"
     install_test_helper.check_call(
         [install_test_helper.get_python_executable(), "-c", script],
         env=tool_env
     )
예제 #13
0
 def test_install(self):
     # Get install directory.
     install_dir = install_test_helper.get_install_dir()
     executable_folder = os.path.join(install_dir, "bin")
     try:
         install_test_helper.check_output(
             [os.path.join(executable_folder, "drake-lcm-spy"), "--help"],
             stderr=subprocess.STDOUT)
         # If the process doesn't fail, we cannot test the string
         # returned in the exception output. Since this should not
         # happen, we fail here. If lcm is updated to return 0 when
         # "--help" is called, this test will fail and will need to be
         # updated.
         self.fail(
             "drake-lcm-spy execution passed instead of failing. Update test"  # noqa
         )
     except subprocess.CalledProcessError as e:
         self.assertIn("usage: lcm-spy [options]", e.output.decode("utf8"))
예제 #14
0
 def test_install(self):
     # Get install directory.
     install_dir = install_test_helper.get_install_dir()
     executable_folder = os.path.join(install_dir, "bin")
     try:
         install_test_helper.check_output(
             [os.path.join(executable_folder, "drake-lcm-spy"), "--help"],
             stderr=subprocess.STDOUT
             )
         # If the process doesn't fail, we cannot test the string
         # returned in the exception output. Since this should not
         # happen, we fail here. If lcm is updated to return 0 when
         # "--help" is called, this test will fail and will need to be
         # updated.
         self.fail(
             "drake-lcm-spy execution passed instead of failing. Update test"  # noqa
             )
     except subprocess.CalledProcessError as e:
         self.assertIn("usage: lcm-spy [options]", e.output)
    def test_help(self):
        """Ensures we can call `./bin/drake-visualizer --help` from install."""
        # Get install directory.
        install_dir = install_test_helper.get_install_dir()
        # N.B. Do not update PYTHONPATH, as the script should handle that
        # itself.
        bin_path = join(install_dir, "bin", "drake-visualizer")
        text = install_test_helper.check_output([bin_path, "--help"])

        # N.B. This should be kept in sync with
        # `drake_visualizer_bazel_test`.
        print(text)
        # Test for nominal help string.
        self.assertIn("usage: drake-visualizer ", text)
        self.assertNotIn("drake-visualizer: error: unrecognized arguments",
                         text)
        # Test for modifications in help text.
        self.assertIn("--use_builtin_scripts", text)
        self.assertIn("Options: all,", text)
예제 #16
0
    def test_install(self):
        # Fail (on purpose) if not given exactly one command line argument.
        self.assertEqual(len(sys.argv), 2)
        with open(sys.argv[1], 'r') as f:
            lines = f.readlines()

        # Install into bazel read-only temporary directory. The temporary
        # directory does not need to be removed as bazel tests are run in a
        # scratch space.
        install_test_helper.install()
        installation_folder = install_test_helper.get_install_dir()
        self.assertTrue(os.path.isdir(installation_folder))

        # Verify install directory content.
        content = set(os.listdir(installation_folder))
        self.assertSetEqual(set(['bin', 'include', 'lib', 'share']), content)

        # Execute the install actions.
        for cmd in lines:
            cmd = cmd.strip()
            print("+ {}".format(cmd))
            install_test_helper.check_call([os.path.join(os.getcwd(), cmd)])
 def test_get_install_dir(self):
     self.assertIn("TEST_TMPDIR", os.environ)
     self.assertIn('installation', install_test_helper.get_install_dir())
def main():
    install_dir = install_test_helper.get_install_dir()

    # In scratch, mock up a drake_bazel_installed workspace.
    scratch_dir = install_test_helper.create_temporary_dir("scratch")

    # The commit (version) here should be identical to the commit listed in
    # drake/tools/workspace/rules_python/repository.bzl.
    rules_python_commit = "0.10.2"
    rules_python_url = f"https://github.com/bazelbuild/rules_python/archive/{rules_python_commit}.tar.gz"  # noqa
    rules_python_sha256 = "a3a6e99f497be089f81ec082882e40246bfd435f52f4e82f37e89449b04573f6"  # noqa

    with open(join(scratch_dir, "WORKSPACE"), "w") as f:
        f.write(f"""
workspace(name = "scratch")

load(
    "@bazel_tools//tools/build_defs/repo:http.bzl",
    "http_archive",
)
http_archive(
    name = "rules_python",
    sha256 = "{rules_python_sha256}",
    strip_prefix = "rules_python-{rules_python_commit}",
    url = "{rules_python_url}",
)

new_local_repository(
    name = "drake_binary",
    path = "{install_dir}",
    build_file_content = "#",
)
load(
    "@drake_binary//:share/drake/repo.bzl",
    "drake_repository",
)
drake_repository(name = "drake")
""")

    with open(join(scratch_dir, "BUILD.bazel"), "w") as f:
        f.write(f"""
load("@rules_python//python:defs.bzl", "py_test")
load("@drake//:.os.bzl", OS_NAME = "NAME")

cc_test(
    name = "text_logging_test",
    srcs = ["text_logging_test.cc"],
    # TODO(jwnimmer-tri) On macOS, we need to pkg-config fmt for this to pass.
    # For the moment, we'll say that :drake_shared_library is Ubuntu-only.
    tags = ["manual"] if OS_NAME == "mac os x" else [],
    deps = ["@drake//:drake_shared_library"],
)

py_test(
    name = "find_resource_test",
    srcs = ["find_resource_test.py"],
    size = "small",
    deps = ["@drake//bindings/pydrake"],
)

py_test(
    name = "import_all_test",
    srcs = ["import_all_test.py"],
    size = "small",
    deps = ["@drake//bindings/pydrake"],
)

# A stub for unit testing; not required for end users.
filegroup(name = "dummy_filegroup")
""")

    with open(join(scratch_dir, "text_logging_test.cc"), "w") as f:
        f.write("""
#include <drake/common/text_logging.h>
int main(int argc, char** argv) {
  drake::log()->info("Hello {}", "world");
  return 0;
}
""")

    with open(join(scratch_dir, "find_resource_test.py"), "w") as f:
        f.write("""
from pydrake.common import FindResourceOrThrow, set_log_level
set_log_level("trace")
FindResourceOrThrow("drake/examples/pendulum/Pendulum.urdf")
""")

    with open(join(scratch_dir, "import_all_test.py"), "w") as f:
        f.write("""
import pydrake.all
""")

    # Check that a full `bazel test` passes.
    command = "test"
    if sys.platform.startswith("darwin"):
        # TODO(jwnimmer-tri) A `test //...` doesn't pass yet on macOS.
        command = "build"
    subprocess.check_call(
        cwd=scratch_dir,
        args=[
            "bazel",
            # Use "release engineering" options for hermeticity.
            # https://docs.bazel.build/versions/master/user-manual.html#bazel-releng
            "--bazelrc=/dev/null",
            # Encourage the server to exit after the test completes.
            "--max_idle_secs=1",
            # Run all of the tests from the BUILD.bazel generated above.
            command,
            "//...",
            "--jobs=1",
            # Enable verbosity.
            "--announce_rc",
            "--test_output=streamed",
            # Use "release engineering" options for hermeticity.
            "--nokeep_state_after_build",
            # Nerf the coverage reporter to avoid downloading the entire JDK afresh
            # from the internet every time we run this test.
            "--coverage_report_generator=//:dummy_filegroup",
        ])
 def test_get_install_dir(self):
     self.assertIn("TEST_TMPDIR", os.environ)
     self.assertIn('installation', install_test_helper.get_install_dir())
예제 #20
0
def main():
    install_dir = install_test_helper.get_install_dir()

    # In scratch, mock up a drake_bazel_installed workspace.
    scratch_dir = install_test_helper.create_temporary_dir("scratch")

    # TODO(jamiesnape): Automatically keep this synchronized with the version
    # used by @drake (or the nearest stable version).
    rules_python_commit = "0.2.0"
    rules_python_url = f"https://github.com/bazelbuild/rules_python/archive/{rules_python_commit}.tar.gz"  # noqa
    rules_python_sha256 = "0d25ab1c7b18b3f48d1bff97bfa70c1625438b40c5f661946fb43eca4ba9d9dd"  # noqa

    with open(join(scratch_dir, "WORKSPACE"), "w") as f:
        f.write(f"""
workspace(name = "scratch")

load(
    "@bazel_tools//tools/build_defs/repo:http.bzl",
    "http_archive",
)
http_archive(
    name = "rules_python",
    sha256 = "{rules_python_sha256}",
    strip_prefix = "rules_python-{rules_python_commit}",
    url = "{rules_python_url}",
)
load(
    "@rules_python//python:repositories.bzl",
    "py_repositories",
)
py_repositories()

new_local_repository(
    name = "drake_binary",
    path = "{install_dir}",
    build_file_content = "#",
)
load(
    "@drake_binary//:share/drake/repo.bzl",
    "drake_repository",
)
drake_repository(name = "drake")
""")

    with open(join(scratch_dir, "BUILD.bazel"), "w") as f:
        f.write(f"""
load("@rules_python//python:defs.bzl", "py_test")

py_test(
    name = "find_resource_test",
    srcs = ["find_resource_test.py"],
    size = "small",
    deps = ["@drake//bindings/pydrake"],
)

py_test(
    name = "import_all_test",
    srcs = ["import_all_test.py"],
    size = "small",
    deps = ["@drake//bindings/pydrake"],
)

# A stub for unit testing; not required for end users.
filegroup(name = "dummy_filegroup")
""")

    with open(join(scratch_dir, "find_resource_test.py"), "w") as f:
        f.write(f"""
from pydrake.common import FindResourceOrThrow, set_log_level
set_log_level("trace")
FindResourceOrThrow("drake/examples/pendulum/Pendulum.urdf")
""")

    with open(join(scratch_dir, "import_all_test.py"), "w") as f:
        f.write(f"""
import pydrake.all
""")

    # Check that a full `bazel test` passes.
    command = "test"
    if sys.platform.startswith("darwin"):
        # TODO(jwnimmer-tri) A `test //...` doesn't pass yet on macOS.
        command = "build"
    subprocess.check_call(
        cwd=scratch_dir,
        args=[
            "bazel",
            # Use "release engineering" options for hermeticity.
            # https://docs.bazel.build/versions/master/user-manual.html#bazel-releng
            "--bazelrc=/dev/null",
            # Encourage the server to exit after the test completes.
            "--max_idle_secs=1",
            # Run all of the tests from the BUILD.bazel generated above.
            command,
            "//...",
            "--jobs=1",
            # Enable verbosity.
            "--announce_rc",
            # Use "release engineering" options for hermeticity.
            "--nokeep_state_after_build",
            # Nerf the coverage reporter to avoid downloading the entire JDK afresh
            # from the internet every time we run this test.
            "--coverage_report_generator=//:dummy_filegroup",
        ])
예제 #21
0
import os
import sys
import install_test_helper

# Install into bazel read-only temporary directory. The temporary
# directory does not need to be removed as bazel tests are run in a
# scratch space.
install_test_helper.install()
installation_folder = install_test_helper.get_install_dir()
assert os.path.isdir(installation_folder)
# Verify install directory content.
content = os.listdir(installation_folder)
assert set(['bin', 'include', 'lib', 'share']) == set(content)
# Will fail (on purpose) if not exactly one command line argument given.
assert len(sys.argv) == 2

with open(sys.argv[1], "r") as f:
    lines = f.readlines()

# Execute the install actions.
for cmd in lines:
    cmd = cmd.strip()
    install_test_helper.check_call(os.path.join(os.getcwd(), cmd))
    def test_install_and_run(self):
        install_dir = install_test_helper.get_install_dir()
        resource_subfolder = "share/drake/"
        installed_sentinel = os.path.join(install_dir,
                                          resource_subfolder,
                                          ".drake-find_resource-sentinel")
        # Verifies that the sentinel file exists in the installed directory.
        # If it has been removed, we need to update this test.
        self.assertTrue(os.path.isfile(installed_sentinel))
        # Create a resource in the temporary directory.
        tmp_dir = install_test_helper.create_temporary_dir()

        resource_folder = os.path.join(tmp_dir, resource_subfolder)
        test_folder = os.path.join(resource_folder, "common/test")
        os.makedirs(test_folder)
        # Create sentinel file.
        sentinel = os.path.join(resource_folder,
                                os.path.basename(installed_sentinel))
        os.symlink(installed_sentinel, sentinel)
        # Create resource file.
        resource = os.path.join(test_folder, "tmp_resource")
        resource_data = "tmp_resource"
        with open(resource, "w") as f:
            f.write(resource_data)

        # Cross-check the resource root environment variable name.
        env_name = "DRAKE_RESOURCE_ROOT"
        resource_tool = os.path.join(
            install_dir, "share/drake/common/resource_tool")
        output_name = install_test_helper.check_output(
            [resource_tool,
             "--print_resource_root_environment_variable_name",
             ],
            ).strip()
        self.assertEqual(output_name, env_name)

        # Use the installed resource_tool to find a resource.
        tool_env = dict(os.environ)
        tool_env[env_name] = os.path.join(tmp_dir, "share")
        absolute_path = install_test_helper.check_output(
            [resource_tool,
             "--print_resource_path",
             "drake/common/test/tmp_resource",
             ],
            env=tool_env,
            ).strip()
        with open(absolute_path, 'r') as data:
            self.assertEqual(data.read(), resource_data)

        # Use the installed resource_tool to find a directory.
        # (This feature is deprecated and will eventually be removed.)
        absolute_path = install_test_helper.check_output(
            [resource_tool,
             "--print_resource_path",
             "drake/common/test",
             ],
            env=tool_env,
            ).strip()
        with open(absolute_path + '/tmp_resource', 'r') as data:
            self.assertEqual(data.read(), resource_data)

        # Use the installed resource_tool to find a resource, but with a bogus
        # DRAKE_RESOURCE_ROOT that should be ignored.
        tool_env[env_name] = os.path.join(tmp_dir, "share", "drake")
        full_text = install_test_helper.check_output(
            [resource_tool,
             "--print_resource_path",
             "drake/examples/pendulum/Pendulum.urdf",
             ],
            env=tool_env,
            stderr=subprocess.STDOUT,
            ).strip()
        warning = full_text.splitlines()[0]
        absolute_path = full_text.splitlines()[-1]
        self.assertIn("FindResource ignoring DRAKE_RESOURCE_ROOT", warning)
        self.assertTrue(os.path.exists(absolute_path),
                        absolute_path + " does not exist")

        # Use --add_resource_search_path instead of environment variable
        # to find resources.
        # (This feature is deprecated and will eventually be removed.)
        absolute_path = install_test_helper.check_output(
            [resource_tool,
             "--print_resource_path",
             "drake/common/test/tmp_resource",
             "--add_resource_search_path",
             os.path.join(tmp_dir, "share"),
             ],
            ).strip()
        with open(absolute_path, 'r') as data:
            self.assertEqual(data.read(), resource_data)
def main():
    install_dir = install_test_helper.get_install_dir()

    # In scratch, mock up a drake_bazel_installed workspace.
    scratch_dir = install_test_helper.create_temporary_dir("scratch")
    with open(join(scratch_dir, "WORKSPACE"), "w") as f:
        f.write(f"""
workspace(name = "scratch")
new_local_repository(
    name = "drake_binary",
    path = "{install_dir}",
    build_file_content = "#",
)
load(
    "@drake_binary//:share/drake/repo.bzl",
    "drake_repository",
)
drake_repository(name = "drake")
""")

    with open(join(scratch_dir, "BUILD.bazel"), "w") as f:
        f.write(f"""
py_test(
    name = "find_resource_test",
    srcs = ["find_resource_test.py"],
    size = "small",
    deps = ["@drake//bindings/pydrake"],
)

py_test(
    name = "import_all_test",
    srcs = ["import_all_test.py"],
    size = "small",
    deps = ["@drake//bindings/pydrake"],
)

# A stub for unit testing; not required for end users.
filegroup(name = "dummy_filegroup")
""")

    with open(join(scratch_dir, "find_resource_test.py"), "w") as f:
        f.write(f"""
from pydrake.common import FindResourceOrThrow, set_log_level
set_log_level("trace")
FindResourceOrThrow("drake/examples/pendulum/Pendulum.urdf")
""")

    with open(join(scratch_dir, "import_all_test.py"), "w") as f:
        f.write(f"""
import pydrake.all
""")

    # Check that a full `bazel test` passes.
    command = "test"
    if sys.platform.startswith("darwin"):
        # TODO(jwnimmer-tri) A `test //...` doesn't pass yet on macOS.
        command = "build"
    subprocess.check_call(
        cwd=scratch_dir,
        args=[
            "bazel",
            # Use "release engineering" options for hermeticity.
            # https://docs.bazel.build/versions/master/user-manual.html#bazel-releng
            "--bazelrc=/dev/null",
            # Encourage the server to exit after the test completes.
            "--max_idle_secs=1",
            # Run all of the tests from the BUILD.bazel generated above.
            command,
            "//...",
            "--jobs=1",
            # Enable verbosity.
            "--announce_rc",
            # Use "release engineering" options for hermeticity.
            "--nokeep_state_after_build",
            # Nerf the coverage reporter to avoid downloading the entire JDK afresh
            # from the internet every time we run this test.
            "--coverage_report_generator=//:dummy_filegroup",
        ])
    def test_install_and_run(self):
        install_dir = install_test_helper.get_install_dir()
        resource_subfolder = "share/drake/"
        installed_sentinel = os.path.join(install_dir,
                                          resource_subfolder,
                                          ".drake-find_resource-sentinel")
        # Verifies that the sentinel file exists in the installed directory.
        # If it has been removed, we need to update this test.
        self.assertTrue(os.path.isfile(installed_sentinel))
        # Create a resource in the temporary directory.
        tmp_dir = install_test_helper.create_temporary_dir()

        resource_folder = os.path.join(tmp_dir, resource_subfolder)
        test_folder = os.path.join(resource_folder, "common/test")
        os.makedirs(test_folder)
        # Create sentinel file.
        sentinel = os.path.join(resource_folder,
                                os.path.basename(installed_sentinel))
        os.symlink(installed_sentinel, sentinel)
        # Create resource file.
        resource = os.path.join(test_folder, "tmp_resource")
        resource_data = "tmp_resource"
        with open(resource, "w") as f:
            f.write(resource_data)

        # Cross-check the resource root environment variable name.
        env_name = "DRAKE_RESOURCE_ROOT"
        resource_tool = os.path.join(
            install_dir, "share/drake/common/resource_tool")
        output_name = install_test_helper.check_output(
            [resource_tool,
             "--print_resource_root_environment_variable_name",
             ],
            ).strip()
        self.assertEqual(output_name, env_name)

        # Use the installed resource_tool to find a resource.
        tool_env = dict(os.environ)
        tool_env[env_name] = os.path.join(tmp_dir, "share")
        absolute_path = install_test_helper.check_output(
            [resource_tool,
             "--print_resource_path",
             "drake/common/test/tmp_resource",
             ],
            env=tool_env,
            ).strip()
        with open(absolute_path, 'r') as data:
            self.assertEqual(data.read(), resource_data)

        # Use --add_resource_search_path instead of environment variable
        # to find resources.
        absolute_path = install_test_helper.check_output(
            [resource_tool,
             "--print_resource_path",
             "drake/common/test/tmp_resource",
             "--add_resource_search_path",
             os.path.join(tmp_dir, "share"),
             ],
            ).strip()
        with open(absolute_path, 'r') as data:
            self.assertEqual(data.read(), resource_data)
예제 #25
0
 def test_install(self):
     # Get install directory.
     install_dir = install_test_helper.get_install_dir()
     executable_folder = os.path.join(install_dir, "bin")
     install_test_helper.check_call(
         [os.path.join(executable_folder, "lcm-gen"), "--help"], )