File: integration-tests-generic.py

package info (click to toggle)
debusine 0.14.2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 15,200 kB
  • sloc: python: 195,951; sh: 849; javascript: 335; makefile: 116
file content (241 lines) | stat: -rwxr-xr-x 8,643 bytes parent folder | download | duplicates (3)
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/env python3

# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.
"""
Debusine generic integration tests.

Does not test any sbuild related code.
"""

import os
import shutil
import textwrap
import unittest
from pathlib import Path

import lxml.html
import requests
import yaml

from utils.client import Client
from utils.common import Configuration
from utils.server import DebusineServer
from utils.worker import Worker


class IntegrationGenericTests(unittest.TestCase):
    """
    Integration generic tests (excludes sbuild specific tests).

    These tests assume:
    - debusine-server is running
    - debusine-client is correctly configured
    - "sudo -u debusine-server debusine-admin COMMAND" works

    Note that these tests (via Worker) delete /etc/debusine/worker contents,
    stop and start debusine-worker, create new tokens in the debusine-server
    """

    TASK_NAME = 'noop'

    def setUp(self) -> None:
        """Initialize test."""
        # If debusine-server or nginx was launched just before the
        # integration-tests.py is launched the debusine-server might not be
        # yet available. Let's wait for the debusine-server to be
        # reachable if it's not ready yet
        self.assertTrue(
            DebusineServer.wait_for_server_ready(),
            f"debusine-server should be available (in "
            f"{Configuration.get_base_url()}) before the integration tests "
            f"are run",
        )

        self._worker = Worker()

    def connect_worker(self) -> None:
        """
        Connect the worker to the debusine-server.

        Steps:
        - set up worker (it fetches a disabled token file)
        - enable the token
        - wait for the worker to be connected
        """
        self._worker.set_up()

        # Worker re-connect automatically
        self.assertTrue(
            DebusineServer.wait_for_worker_connected(Worker.read_token())
        )

    def test_secret_key_file_not_readable_fails(self) -> None:
        """Key file cannot be read: the server does not start."""
        key_file = "/var/lib/debusine/server/key"
        tmp_key_file = "/var/lib/debusine/server/key.tmp"

        shutil.move(key_file, tmp_key_file)
        self.addCleanup(DebusineServer.restart)
        self.addCleanup(shutil.move, tmp_key_file, key_file)

        # Cannot start because key file cannot be read
        self.assertEqual(DebusineServer.restart().returncode, 1)

    def test_worker_is_not_connected(self) -> None:
        """The worker is not connected: the token is not enabled yet."""
        self._worker.set_up(use_activation_token=False)

        self.assertTrue(
            DebusineServer.verify_worker(
                self._worker.read_token(),
                connected=False,
                enabled=False,
            )
        )

    def test_worker_connects(self) -> None:
        """The admin enables the worker and it gets connected."""
        self.connect_worker()

        self.assertTrue(
            DebusineServer.verify_worker(
                Worker.read_token(), connected=True, enabled=True
            )
        )

    def test_create_work_requests_invalid(self) -> None:
        """Create an invalid work request."""
        # Client submits an invalid work-request (status will be 'error')
        # It is not valid because task_data is not valid

        self.connect_worker()

        create_work_request_output = Client.execute_command(
            "work-request", "create", "--yaml", self.TASK_NAME, stdin="foo: bar"
        )

        # Work Request is registered
        self.assertEqual(create_work_request_output["result"], "failure")

        # Specific "title" and "detail" are tested in the unit tests
        self.assertIn("title", create_work_request_output["error"])
        self.assertIn("detail", create_work_request_output["error"])

    def test_create_work_request_valid(self) -> None:
        """Create a valid work request."""
        self.connect_worker()

        task_data = textwrap.dedent(
            '''\
                result:
                    true
                '''
        )
        self.assert_create_work_request(
            task_data=task_data,
            expected_status="completed",
            expected_result="success",
        )

    def test_debusine_admin_print_permission_error_message(self) -> None:
        """debusine-admin is invoked with wrong user: print error message."""
        # This test is to catch invalid permission
        # (in the logs files for example). Since the test for the secret_key
        # happens before we change the secret_key permissions so it fails
        # later.
        secret_key = "/var/lib/debusine/server/key"
        self.addCleanup(shutil.chown, secret_key, Path(secret_key).owner())
        temp_user = "postgres"
        shutil.chown(secret_key, temp_user)

        result = DebusineServer.execute_command("list_tokens", user=temp_user)

        self.assertEqual(
            "Permission error: Unable to configure handler 'debug.log'. "
            "Check that the user running debusine-admin has access to the"
            " file \"/var/log/debusine/server/debug.log\".\n",
            result.stderr,
        )
        self.assertEqual(result.returncode, 3)

    def assert_create_work_request(
        self, *, task_data: str, expected_status: str, expected_result: str
    ) -> None:
        """
        Submit via debusine client a work request to the server.

        Create work request, assert creation and wait for the work request
        to be completed. Assert expected_status and expected_result.
        """
        create_work_request_output = Client.execute_command(
            'create-work-request', self.TASK_NAME, stdin=task_data
        )

        # Work Request is registered
        self.assertEqual(create_work_request_output['result'], 'success')
        self.assertIn('registered', create_work_request_output['message'])

        work_request_id = create_work_request_output['work_request_id']

        # The client will check the status of the created request
        show_work_request_output = Client.execute_command(
            'show-work-request', work_request_id
        )

        # Task name is as submitted
        self.assertEqual(show_work_request_output['task_name'], self.TASK_NAME)

        # Task data is as submitted
        actual_task_data = show_work_request_output['task_data'].copy()
        self.assertIsInstance(actual_task_data.pop("task_configuration"), int)
        self.assertEqual(actual_task_data, yaml.safe_load(task_data))

        # The worker should get the new work request and start executing it
        Client.wait_for_work_request_completed(work_request_id, expected_result)

        # Assert expected_result and expected_status
        show_work_request_output = Client.execute_command(
            "show-work-request", work_request_id
        )

        self.assertEqual(show_work_request_output["status"], expected_status)
        self.assertEqual(show_work_request_output["result"], expected_result)

    def test_web_login(self) -> None:
        """
        Ensure the web interface is accessible after login.

        Catches unit-tests-escaping issues like
        https://salsa.debian.org/freexian-team/debusine/-/issues/563
        """
        s = requests.session()
        r = s.get(f"{Configuration.get_base_url()}/-/login")
        html = lxml.html.fromstring(r.content)
        csrftoken = html.xpath(
            """//input[@name="csrfmiddlewaretoken"]/@value"""
        )[0]
        with open(os.environ["AUTOPKGTEST_TMP"] + "/test-password.txt") as f:
            password = f.read()[:-1]
        r = s.post(
            f"{Configuration.get_base_url()}/-/login/",
            {
                "username": "test-user",
                "password": password,
                "csrfmiddlewaretoken": csrftoken,
            },
            # Referer required in https
            headers={"Referer": f"{Configuration.get_base_url()}/-/login"},
        )
        html = lxml.html.fromstring(r.content)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(
            html.xpath("""//ul[@id='navbar-right']/li/a/text()""")[0].strip(),
            "test-user",
        )