
import os
import shutil
import subprocess
import tempfile
import unittest


class ClickBinPathTestCase(unittest.TestCase):

      def setUp(self):
            self.hook_cmd = os.path.abspath(os.path.join(
                  os.path.dirname(__file__), "..", 
                  "click-bin-path-hook"))
            self.tempdir = tempfile.mkdtemp()
            self.srcdir = os.path.join(
                  self.tempdir, "home", "foo", ".cache", "snappy-bin-path")
            os.makedirs(self.srcdir)
            self.dstdir = os.path.join(
                  self.tempdir, "home", "foo", "snappy-bin")
            os.makedirs(self.dstdir)
            self.appsdir = os.path.join(
                  self.tempdir, "apps")
            os.makedirs(self.appsdir)

      def _make_bin_path_app(self, binary):
            subdir, binary = os.path.split(binary)
            path = os.path.join(
                  self.appsdir,
                  ".click",
                  "users",
                  "foo",
                  "com.example.%s-cli" % binary,
                  "bin",
                  subdir)
            if not os.path.exists(path):
                  os.makedirs(path)
            cli = os.path.join(path, "hello")
            with open(cli, "w"):
                  pass
            return cli

      def tearDown(self):
            shutil.rmtree(self.tempdir)

      def test_invalid_symlink(self):
            cli = self._make_bin_path_app("hello")
            os.symlink(
                  cli,
                  os.path.join(
                        self.srcdir, "com.example.hello-cli_hello_1.0.cli"))
            ret = subprocess.call([self.hook_cmd,
                             "--srcdir", self.srcdir,
                             "--dstdir", self.dstdir])
            self.assertEqual(ret, 0)


if __name__ == "__main__":
      unittest.main()
