File: helpers.py

package info (click to toggle)
click 0.5.2-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,372 kB
  • sloc: python: 7,135; ansic: 857; makefile: 441; sh: 236; perl: 26; xml: 11
file content (138 lines) | stat: -rw-r--r-- 4,672 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# Copyright (C) 2014 Canonical Ltd.
# Author: Michael Vogt <michael.vogt@ubuntu.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Integration tests helper for the click CLI interface."""

import contextlib
import glob
import json
import os
import random
import shutil
import string
import subprocess
import tempfile
import unittest


def require_root():
    if os.getuid() != 0:
        raise unittest.SkipTest("This test needs to run as root")


def require_network():
    try:
        if subprocess.call(["ping", "-c1", "archive.ubuntu.com"]) != 0:
            raise unittest.SkipTest("Need network")
    except Exception:
        pass


def require_overlay():
    lsmod = subprocess.Popen(["/sbin/lsmod"],stdout=subprocess.PIPE)
    try:
        subprocess.check_call(['grep', 'overlay'], stdin=lsmod.stdout)
        lsmod.stdout.close()
    except subprocess.CalledProcessError:
        try:
            subprocess.check_call(["/sbin/modprobe", "overlay"])
        except subprocess.CalledProcessError:
            raise unittest.SkipTest("Requires overlay fs support")


@contextlib.contextmanager
def chdir(target):
    curdir = os.getcwd()
    os.chdir(target)
    try:
        yield
    finally:
        os.chdir(curdir)


def cmdline_for_user(username):
    """Helper to get the click commandline for the given username"""
    if username == "@all":
        user = "--all-users"
    else:
        user = "--user=%s" % username
    return user


class ClickTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        if "TEST_INTEGRATION" not in os.environ:
            raise unittest.SkipTest("Skipping integration tests")
        cls.click_binary = os.environ.get("CLICK_BINARY", "/usr/bin/click")

    def setUp(self):
        super(ClickTestCase, self).setUp()
        self.temp_dir = tempfile.mkdtemp()

    def tearDown(self):
        super(ClickTestCase, self).tearDown()
        # we force the cleanup before removing the tempdir so that stuff
        # in temp_dir is still available
        self.doCleanups()
        shutil.rmtree(self.temp_dir)

    def click_install(self, path_to_click, click_name, username,
                      allow_unauthenticated=True):
        cmd = [self.click_binary, "install", cmdline_for_user(username)]
        if allow_unauthenticated:
            cmd.append("--allow-unauthenticated")
        cmd.append(path_to_click)
        subprocess.check_call(cmd)
        self.addCleanup(self.click_unregister, click_name, username)

    def click_unregister(self, click_name, username):
        subprocess.check_call(
            [self.click_binary, "unregister", cmdline_for_user(username),
             click_name])

    def _create_manifest(self, target, name, version, framework, hooks={}):
        with open(target, "w") as f:
            json.dump({
                'name': name,
                'version': str(version),
                'maintainer': 'Foo Bar <foo@example.org>',
                'title': 'test title',
                'framework': framework,
                'hooks': hooks,
                }, f)

    def _make_click(self, name=None, version=1.0,
                    framework="ubuntu-sdk-13.10", hooks={}):
        if name is None:
            name = "com.example.%s" % "".join(
                random.choice(string.ascii_lowercase) for i in range(10))
        tmpdir = tempfile.mkdtemp()
        if os.geteuid() == 0:
            os.chmod(tmpdir, 0o755)
        self.addCleanup(lambda: shutil.rmtree(tmpdir))
        clickdir = os.path.join(tmpdir, name)
        os.makedirs(clickdir)
        self._create_manifest(os.path.join(clickdir, "manifest.json"),
                              name, version, framework, hooks)
        with open(os.path.join(clickdir, "README"), "w") as f:
            f.write("hello world!")
        with chdir(tmpdir), open(os.devnull, "w") as devnull:
            subprocess.call(
                [self.click_binary, "build", clickdir], stdout=devnull)
        generated_clicks = glob.glob(os.path.join(tmpdir, "*.click"))
        self.assertEqual(len(generated_clicks), 1)
        return generated_clicks[0]