File: fixture.py

package info (click to toggle)
pcs 0.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,148 kB
  • sloc: python: 238,810; xml: 20,833; ruby: 13,203; makefile: 1,595; sh: 484
file content (433 lines) | stat: -rw-r--r-- 12,655 bytes parent folder | download
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import json
from collections import Counter
from typing import (
    Any,
    Generic,
    Mapping,
    NamedTuple,
    Optional,
    TypeVar,
    overload,
)

from pcs.common import reports
from pcs.common.str_tools import format_list

ALL_RESOURCE_XML_TAGS = ["bundle", "clone", "group", "master", "primitive"]


# Previously, a report item fixture was a plain tuple. That was, however, not
# the best to work with when access to specific indexes was needed. To provide
# a 1-to-1 replacement with more friendly interface, a NamedTuple was chosen
# instead of a dataclass. Order of the attributes is the same as in the
# original tuple, so it may be not the best, but it works without any changes
# to related code.
class ReportItemFixture(NamedTuple):
    severity: reports.types.SeverityLevel
    code: reports.types.MessageCode
    payload: Mapping[str, Any]
    force_code: Optional[reports.types.ForceCode]
    context: Optional[Mapping[str, Any]]

    def to_warn(self):
        return warn(self.code, self.context, **self.payload)

    def adapt(self, **payload):
        updated_payload = self.payload.copy()
        updated_payload.update(**payload)
        return type(self)(
            self.severity,
            self.code,
            updated_payload,
            self.force_code,
            self.context,
        )


def debug(
    code: reports.types.MessageCode,
    context: Optional[Mapping[str, Any]] = None,
    **kwargs,
) -> ReportItemFixture:
    return ReportItemFixture(
        reports.ReportItemSeverity.DEBUG, code, kwargs, None, context
    )


def warn(
    code: reports.types.MessageCode,
    context: Optional[Mapping[str, Any]] = None,
    **kwargs,
) -> ReportItemFixture:
    return ReportItemFixture(
        reports.ReportItemSeverity.WARNING, code, kwargs, None, context
    )


def deprecation(
    code: reports.types.MessageCode,
    context: Optional[Mapping[str, Any]] = None,
    **kwargs,
) -> ReportItemFixture:
    return ReportItemFixture(
        reports.ReportItemSeverity.DEPRECATION, code, kwargs, None, context
    )


def error(
    code: reports.types.MessageCode,
    force_code: Optional[reports.types.ForceCode] = None,
    context: Optional[Mapping[str, Any]] = None,
    **kwargs,
) -> ReportItemFixture:
    return ReportItemFixture(
        reports.ReportItemSeverity.ERROR, code, kwargs, force_code, context
    )


def info(
    code: reports.types.MessageCode,
    context: Optional[Mapping[str, Any]] = None,
    **kwargs,
) -> ReportItemFixture:
    return ReportItemFixture(
        reports.ReportItemSeverity.INFO, code, kwargs, None, context
    )


T = TypeVar("T")


class NameValueSequence(Generic[T]):
    def __init__(
        self,
        name_list: Optional[list[Optional[str]]] = None,
        value_list: Optional[list[T]] = None,
    ):
        self.__names: list[Optional[str]] = name_list or []
        self.__values: list[T] = value_list or []

        if len(self.__names) != len(self.__values):
            raise AssertionError("Values count doesn't match names count")

        name_counter = Counter(self.__names)
        duplicate_names = [
            n for n in name_counter if n is not None and name_counter[n] > 1
        ]
        if duplicate_names:
            raise AssertionError(
                f"Duplicate names are not allowed in {type(self).__name__}. "
                f"Found duplications:\n  {format_list(duplicate_names)}"
            )

    @property
    def names(self) -> list[Optional[str]]:
        return list(self.__names)

    @property
    def values(self) -> list[T]:
        return list(self.__values)

    def append(self, value: T, name: Optional[str] = None) -> None:
        """
        Append new value with the specified name at the end of sequence

        value -- new value
        name -- new value name
        """
        self.__check_name(name)
        self.__names.append(name)
        self.__values.append(value)

    def prepend(self, value: T, name: Optional[str] = None) -> None:
        """
        Insert new value with the specified name at the start of sequence

        value -- new value
        name -- new value name
        """
        self.__check_name(name)
        self.__names.insert(0, name)
        self.__values.insert(0, value)

    def insert(self, before: str, value: T, name: Optional[str] = None) -> None:
        """
        Insert new value before a specified value

        before -- name of a value before which the new one will be placed
        value -- the new value
        name -- name of the new value
        """
        self.__check_name(name)
        index = self.__get_index(before)
        self.__names.insert(index, name)
        self.__values.insert(index, value)

    def remove(self, *name_list: str) -> None:
        """
        Remove values with specified names

        name_list -- names of values to be removed
        """
        for name in name_list:
            index = self.__get_index(name)
            del self.__names[index]
            del self.__values[index]

    def replace(
        self, name: str, value: T, new_name: Optional[str] = None
    ) -> None:
        """
        Replace a value specified by its name

        name -- name of a value to be replaced
        value -- new value
        new_name -- new name of the value, use 'name' if not specified
        """
        if new_name is not None and new_name != name and name in self.__names:
            raise AssertionError(f"Name '{new_name}' already present in {self}")
        for i, current_name in enumerate(self.__names):
            if current_name == name:
                self.__values[i] = value
                if new_name:
                    self.__names[i] = new_name
                return
        raise IndexError(self.__index_error(name))

    def trim_before(self, name: str) -> None:
        """
        Remove a value with the specified name and all values after it

        name -- name of a value to trim at
        """
        index = self.__get_index(name)
        self.__names = self.__names[:index]
        self.__values = self.__values[:index]

    def copy(self) -> "NameValueSequence":
        return type(self)(self.names, self.values)

    def __get_index(self, name: str) -> int:
        try:
            return self.__names.index(name)
        except ValueError as e:
            raise IndexError(self.__index_error(name)) from e

    def __index_error(self, index: str) -> str:
        return f"'{index}' not present in {self}"

    def __check_name(self, name: Optional[str]) -> None:
        if name is not None and name in self.__names:
            raise AssertionError(f"Name '{name}' already present in {self}")

    @overload
    def __getitem__(self, spec: str) -> T:
        pass

    @overload
    def __getitem__(self, spec: slice) -> "NameValueSequence":
        pass

    def __getitem__(self, spec):
        if not isinstance(spec, slice):
            try:
                return self.__values[self.__names.index(spec)]
            except ValueError as e:
                raise IndexError(self.__index_error(spec)) from e

        assert spec.step is None, "Step is not supported in slicing"
        start = None if spec.start is None else self.__names.index(spec.start)
        stop = None if spec.stop is None else self.__names.index(spec.stop)
        return type(self)(self.__names[start:stop], self.__values[start:stop])

    def __setitem__(self, name: str, value: T) -> None:
        return (
            self.replace(name, value)
            if name in self.__names
            else self.append(value, name)
        )

    def __delitem__(self, name: str) -> None:
        index = self.__get_index(name)
        del self.__names[index]
        del self.__values[index]

    def __add__(self, other: "NameValueSequence") -> "NameValueSequence":
        my_name = type(self).__name__
        other_name = type(other).__name__
        assert isinstance(other, type(self)), (
            f"Can only concatenate {my_name} with {my_name}, not {other_name}"
        )

        return type(self)(
            self.names + other.names,
            self.values + other.values,
        )

    def __str__(self) -> str:
        return f"{type(self).__name__} {hex(id(self))}:\n" + "\n".join(
            [
                f" {index:3}. {item[0] if item[0] else '<unnamed>'}: {item[1]}"
                for index, item in enumerate(
                    zip(self.__names, self.__values, strict=False), 1
                )
            ]
        )


class ReportSequenceBuilder:
    def __init__(self, store: Optional[NameValueSequence] = None):
        self._store = store or NameValueSequence()

    @property
    def fixtures(self) -> NameValueSequence:
        return self._store

    def info(
        self,
        code: reports.types.MessageCode,
        _name: Optional[str] = None,
        **kwargs,
    ) -> "ReportSequenceBuilder":
        self._store.append(info(code, **kwargs), _name)
        return self

    def warn(
        self,
        code: reports.types.MessageCode,
        _name: Optional[str] = None,
        **kwargs,
    ) -> "ReportSequenceBuilder":
        self._store.append(warn(code, **kwargs), _name)
        return self

    def deprecation(
        self,
        code: reports.types.MessageCode,
        _name: Optional[str] = None,
        **kwargs,
    ) -> "ReportSequenceBuilder":
        self._store.append(deprecation(code, **kwargs), _name)
        return self

    def error(
        self,
        code: reports.types.MessageCode,
        force_code: Optional[reports.types.ForceCode] = None,
        _name: Optional[str] = None,
        **kwargs,
    ) -> "ReportSequenceBuilder":
        self._store.append(error(code, force_code=force_code, **kwargs), _name)
        return self


def report_not_found(
    res_id, context_type="", expected_types=None, context_id=""
):
    return error(
        reports.codes.ID_NOT_FOUND,
        context_type=context_type,
        context_id=context_id,
        id=res_id,
        expected_types=(
            ALL_RESOURCE_XML_TAGS if expected_types is None else expected_types
        ),
    )


def report_not_resource_or_tag(element_id, context_type="cib", context_id=""):
    return report_not_found(
        element_id,
        context_type=context_type,
        expected_types=sorted(ALL_RESOURCE_XML_TAGS + ["tag"]),
        context_id=context_id,
    )


def report_invalid_id(_id, invalid_char, id_description="id"):
    return error(
        reports.codes.INVALID_ID_BAD_CHAR,
        id=_id,
        id_description=id_description,
        is_first_char=(_id.index(invalid_char) == 0),
        invalid_character=invalid_char,
    )


def report_id_already_exist(_id):
    return error(
        reports.codes.ID_ALREADY_EXISTS,
        id=_id,
    )


def report_resource_not_running(
    resource, severity=reports.ReportItemSeverity.INFO
):
    return ReportItemFixture(
        severity,
        reports.codes.RESOURCE_DOES_NOT_RUN,
        dict(resource_id=resource),
        None,
        None,
    )


def report_resource_running(
    resource, roles, severity=reports.ReportItemSeverity.INFO
):
    return ReportItemFixture(
        severity,
        reports.codes.RESOURCE_RUNNING_ON_NODES,
        dict(
            resource_id=resource,
            roles_with_nodes=roles,
        ),
        None,
        None,
    )


def report_unexpected_element(element_id, element_type, expected_types):
    return error(
        reports.codes.ID_BELONGS_TO_UNEXPECTED_TYPE,
        id=element_id,
        expected_types=expected_types,
        current_type=element_type,
    )


def report_not_for_bundles(element_id):
    return report_unexpected_element(
        element_id, "bundle", ["clone", "master", "group", "primitive"]
    )


def report_wait_for_idle_timed_out(reason):
    return error(reports.codes.WAIT_FOR_IDLE_TIMED_OUT, reason=reason.strip())


def check_sbd_comm_success_fixture(node, watchdog, device_list):
    return dict(
        label=node,
        output=json.dumps(
            {
                "sbd": {
                    "installed": True,
                },
                "watchdog": {
                    "exist": True,
                    "path": watchdog,
                    "is_supported": True,
                },
                "device_list": [
                    dict(path=dev, exist=True, block_device=True)
                    for dev in device_list
                ],
            }
        ),
        param_list=[
            ("watchdog", watchdog),
            ("device_list", json.dumps(device_list)),
        ],
    )