Kleaf: init_ddk: Add initial unit testing

* This changes adds testing for:
  * Directory creation correctly handled.
  * Correct symlink of tools/bazel.
  * Prebuilts setup for both relative to workspace or not.

* Little cleanup of the now obsolete create_directory class method.

Bug: 328770706
Change-Id: Ic4d5c43128f1b9a5919fc7ace1d8abd13fccb48d
Signed-off-by: Ulises Mendez Martinez <umendez@google.com>
diff --git a/init/init_ddk.py b/init/init_ddk.py
index ebc0040..dbd7e35 100644
--- a/init/init_ddk.py
+++ b/init/init_ddk.py
@@ -73,7 +73,7 @@
         tools_bazel = self.ddk_workspace / _TOOLS_BAZEL
         kleaf_tools_bazel = self.kleaf_repo / _TOOLS_BAZEL
         # Prepare the location and clean up if necessary.
-        self._create_directory(tools_bazel.parent)
+        tools_bazel.parent.mkdir(parents=True, exist_ok=True)
         tools_bazel.unlink(missing_ok=True)
         tools_bazel.symlink_to(kleaf_tools_bazel)
 
@@ -168,27 +168,21 @@
             """),
         )
 
-    @staticmethod
-    def _create_directory(path: pathlib.Path):
-        if not path.exists():
-            logging.info("Creating directory %s.", path)
-        path.mkdir(parents=True, exist_ok=True)
-
     def _handle_ddk_workspace(self):
         if not self.ddk_workspace:
             return
-        self._create_directory(self.ddk_workspace)
+        self.ddk_workspace.mkdir(parents=True, exist_ok=True)
 
     def _handle_kleaf_repo(self):
         if not self.kleaf_repo:
             return
-        self._create_directory(self.kleaf_repo)
+        self.kleaf_repo.mkdir(parents=True, exist_ok=True)
         # TODO: b/328770706 - According to the needs, syncing git repos logic should go here.
 
     def _handle_prebuilts(self):
         if not self.ddk_workspace or not self.prebuilts_dir:
             return
-        self._create_directory(self.ddk_workspace / self.prebuilts_dir)
+        self.prebuilts_dir.mkdir(parents=True, exist_ok=True)
         # TODO: b/328770706 - When build_id is given dowloand artifacts here.
 
     def _run(self):
diff --git a/init/init_ddk_test.py b/init/init_ddk_test.py
index c8d0264..cc9cc9e 100644
--- a/init/init_ddk_test.py
+++ b/init/init_ddk_test.py
@@ -14,6 +14,7 @@
 
 """Tests for init_ddk.py"""
 
+import argparse
 import logging
 import pathlib
 import tempfile
@@ -21,7 +22,7 @@
 
 from absl.testing import absltest
 from absl.testing import parameterized
-from init_ddk import (KleafProjectSetter, _FILE_MARKER_BEGIN, _FILE_MARKER_END)
+import init_ddk
 
 # pylint: disable=protected-access
 
@@ -36,47 +37,171 @@
 class KleafProjectSetterTest(parameterized.TestCase):
 
     @parameterized.named_parameters([
-        ("Empty", "", join(_FILE_MARKER_BEGIN, _HELLO_WORLD, _FILE_MARKER_END)),
+        (
+            "Empty",
+            "",
+            join(
+                init_ddk._FILE_MARKER_BEGIN,
+                _HELLO_WORLD,
+                init_ddk._FILE_MARKER_END,
+            ),
+        ),
         (
             "BeforeNoMarkers",
             "Existing test\n",
             join(
                 "Existing test",
-                _FILE_MARKER_BEGIN,
+                init_ddk._FILE_MARKER_BEGIN,
                 _HELLO_WORLD,
-                _FILE_MARKER_END,
+                init_ddk._FILE_MARKER_END,
             ),
         ),
         (
             "AfterMarkers",
-            join(_FILE_MARKER_BEGIN, _FILE_MARKER_END, "Existing test after."),
             join(
-                _FILE_MARKER_BEGIN,
+                init_ddk._FILE_MARKER_BEGIN,
+                init_ddk._FILE_MARKER_END,
+                "Existing test after.",
+            ),
+            join(
+                init_ddk._FILE_MARKER_BEGIN,
                 _HELLO_WORLD,
-                _FILE_MARKER_END,
+                init_ddk._FILE_MARKER_END,
                 "Existing test after.",
             ),
         ),
     ])
     def test_update_file_existing(self, current_content, wanted_content):
+        """Tests only text within markers are updated."""
         with tempfile.TemporaryDirectory() as tmp:
             tmp_file = pathlib.Path(tmp) / "some_file"
             with open(tmp_file, "w+", encoding="utf-8") as tf:
                 tf.write(current_content)
-            KleafProjectSetter._update_file(tmp_file, "\n" + _HELLO_WORLD)
+            init_ddk.KleafProjectSetter._update_file(
+                tmp_file, "\n" + _HELLO_WORLD
+            )
             with open(tmp_file, "r", encoding="utf-8") as got:
                 self.assertEqual(wanted_content, got.read())
 
     def test_update_file_no_existing(self):
+        """Tests files are created when they don't exist."""
         with tempfile.TemporaryDirectory() as tmp:
             tmp_file = pathlib.Path(tmp) / "some_file"
-            KleafProjectSetter._update_file(tmp_file, "\n" + _HELLO_WORLD)
+            init_ddk.KleafProjectSetter._update_file(
+                tmp_file, "\n" + _HELLO_WORLD
+            )
             with open(tmp_file, "r", encoding="utf-8") as got:
                 self.assertEqual(
-                    join(_FILE_MARKER_BEGIN, _HELLO_WORLD, _FILE_MARKER_END),
+                    join(
+                        init_ddk._FILE_MARKER_BEGIN,
+                        _HELLO_WORLD,
+                        init_ddk._FILE_MARKER_END,
+                    ),
                     got.read(),
                 )
 
+    def test_relevant_directories_created(self):
+        """Tests corresponding directories are created if they don't exist."""
+        with tempfile.TemporaryDirectory() as temp_dir:
+            temp_dir = pathlib.Path(temp_dir)
+            ddk_workspace = temp_dir / "ddk_workspace"
+            kleaf_repo = temp_dir / "kleaf_repo"
+            prebuilts_dir = temp_dir / "prebuilts_dir"
+            try:
+                init_ddk.KleafProjectSetter(
+                    argparse.Namespace(
+                        build_id=None,
+                        build_target=None,
+                        ddk_workspace=ddk_workspace,
+                        kleaf_repo=kleaf_repo,
+                        local=None,
+                        prebuilts_dir=prebuilts_dir,
+                        url_fmt=None,
+                    )
+                ).run()
+            except:  # pylint: disable=bare-except
+                pass
+            finally:
+                self.assertTrue(ddk_workspace.exists())
+                self.assertTrue(kleaf_repo.exists())
+                self.assertTrue(prebuilts_dir.exists())
+
+    def test_tools_bazel_symlink(self):
+        """Tests a symlink to tools/bazel is correctly created."""
+        with tempfile.TemporaryDirectory() as temp_dir:
+            temp_dir = pathlib.Path(temp_dir)
+            ddk_workspace = temp_dir / "ddk_workspace"
+            try:
+                init_ddk.KleafProjectSetter(
+                    argparse.Namespace(
+                        build_id=None,
+                        build_target=None,
+                        ddk_workspace=ddk_workspace,
+                        kleaf_repo=temp_dir / "kleaf_repo",
+                        local=None,
+                        prebuilts_dir=None,
+                        url_fmt=None,
+                    )
+                ).run()
+            except:  # pylint: disable=bare-except
+                pass
+            finally:
+                tools_bazel_symlink = ddk_workspace / init_ddk._TOOLS_BAZEL
+                self.assertTrue(tools_bazel_symlink.is_symlink())
+
+    def _run_test_module_bazel_for_prebuilts(
+        self,
+        ddk_workspace: pathlib.Path,
+        prebuilts_dir: pathlib.Path,
+        expected: str,
+    ):
+        """Helper method for checking path in a prebuilt extension."""
+        download_configs = prebuilts_dir / "download_configs.json"
+        download_configs.parent.mkdir(parents=True)
+        download_configs.write_text("{}")
+        try:
+            init_ddk.KleafProjectSetter(
+                argparse.Namespace(
+                    build_id=None,
+                    build_target=None,
+                    ddk_workspace=ddk_workspace,
+                    kleaf_repo=None,
+                    local=None,
+                    prebuilts_dir=prebuilts_dir,
+                    url_fmt=None,
+                )
+            ).run()
+        except:  # pylint: disable=bare-except
+            pass
+        finally:
+            module_bazel = ddk_workspace / init_ddk._MODULE_BAZEL_FILE
+            self.assertTrue(module_bazel.exists())
+            content = module_bazel.read_text()
+            self.assertTrue(f'local_artifact_path = "{expected}",' in content)
+
+    def test_module_bazel_for_prebuilts(self):
+        """Tests prebuilts setup is correct for relative and non-relative to workspace dirs."""
+        with tempfile.TemporaryDirectory() as tmp:
+            ddk_workspace = pathlib.Path(tmp) / "ddk_workspace"
+
+            # Verify the right local_artifact_path is set for prebuilts
+            #  in a relative to workspace directory.
+            prebuilts_dir_rel = ddk_workspace / "prebuilts_dir"
+            self._run_test_module_bazel_for_prebuilts(
+                ddk_workspace=ddk_workspace,
+                prebuilts_dir=prebuilts_dir_rel,
+                expected="prebuilts_dir",
+            )
+
+            # Verify the right local_artifact_path is set for prebuilts
+            #  in a non-relative to workspace directory.
+            prebuilts_dir_abs = pathlib.Path(tmp) / "prebuilts_dir"
+            self._run_test_module_bazel_for_prebuilts(
+                ddk_workspace=ddk_workspace,
+                prebuilts_dir=prebuilts_dir_abs,
+                expected=str(prebuilts_dir_abs),
+            )
+
 
 # This could be run as: tools/bazel test //build/kernel:init_ddk_test --test_output=all
 if __name__ == "__main__":