
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", "click-bin-path")
            os.makedirs(self.srcdir)
            self.dstdir = os.path.join(
                  self.tempdir, "home", "foo", "click-bin")
            os.makedirs(self.dstdir)
            # cli1
            self.cli_dir = os.path.join(
                  self.tempdir, "opt", "click.ubuntu.com", ".click",
                  "users", "foo", "com.example.hello-cli", "bin")
            os.makedirs(self.cli_dir)
            self.cli = os.path.join(self.cli_dir, "hello")
            with open(self.cli, "w") as f:
                  pass
            # cli2
            self.cli_dir2 = os.path.join(
                  self.tempdir, "opt", "click.ubuntu.com", ".click",
                  "users", "foo", "com.example.hello2-cli", "bin")
            os.makedirs(self.cli_dir2)
            self.cli2 = os.path.join(self.cli_dir2, "hello")
            with open(self.cli2, "w") as f:
                  pass

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

      def test_add_one(self):
            os.symlink(
                  self.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)
            self.assertEqual(
                  os.path.realpath(os.path.join(self.dstdir, "hello")),
                  self.cli)

      def test_add_same_name(self):
            self.test_add_one()
            os.symlink(self.cli2, os.path.join(self.srcdir, "com.example.hello2-cli_hello_1.0.cli"))
            ret = subprocess.call([self.hook_cmd,
                                   "--srcdir", self.srcdir,
                                   "--dstdir", self.dstdir])
            self.assertEqual(ret, 1)
            self.assertEqual(
                  os.path.realpath(os.path.join(self.dstdir, "hello")),
                  self.cli)

      def test_remove_one(self):
            self.test_add_one()
            os.remove(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)
            self.assertEqual(os.listdir(self.dstdir), [])



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