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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
|
# SPDX-FileCopyrightText: All Contributors to the PyTango project
# SPDX-License-Identifier: LGPL-3.0-or-later
"""Test utilities"""
import enum
import numpy as np
try:
import numpy.typing as npt
# in numpy 1.20 npt does not have npt.NDArray, so we cannot parce hits
npt.NDArray
except (AttributeError, ImportError):
npt = None
from functools import wraps
# Local imports
from tango import (
DevState,
GreenMode,
AttrDataFormat,
ExtractAs,
DevFailed,
DevVarLongStringArray,
DevVarDoubleStringArray,
SerialModel,
)
from tango.server import Device
from tango.test_context import MultiDeviceTestContext, DeviceTestContext
from tango.utils import is_non_str_seq, FROM_TANGO_TO_NUMPY_TYPE
from tango import DeviceClass, LatestDeviceImpl, DevLong64, SCALAR, READ
# Conditional imports
try:
import pytest
except ImportError:
pytest = None
__all__ = [
"MultiDeviceTestContext",
"DeviceTestContext",
"SimpleDevice",
"ClassicAPISimpleDeviceImpl",
"ClassicAPISimpleDeviceClass",
"state",
"command_typed_values",
"attribute_typed_values",
"dev_encoded_values",
"server_green_mode",
"attr_data_format",
"convert_dtype_to_typing_hint",
"assert_close",
"general_decorator",
"general_asyncio_decorator",
"DEVICE_SERVER_ARGUMENTS",
]
if npt:
__all__ += [
"command_numpy_typed_values",
"attribute_numpy_typed_values",
"attribute_wrong_numpy_typed",
]
UTF8_STRING = (
r"""ฤัฃ๐ ีฎแปลฟฤฃศแฅ๐วฉฤพแธฟ๊ศฏ๐ฑ๐๐๐ดศถ๐๐ฯ๐๐๐ฃ1234567890!@#$%^&*()-_=+[{]};:'",<.>/?~๐แธ๐ข๐ฏูคแธิะว๐
ฦิธโฒ๐เงฆฮก๐คษ๐ขศะฆ๐ฑั ๐งฦณศค"""
r"""แบฃ๐ขังแฏฤ๐ฑแป
๐๐แน๐ฒ๐๐ฤผแนละพ๐๐แตฒ๊ฑ๐ฉแปซ๐ลต๐๐ลบ1234567890!@#$%^&*()-_=+[{]};:'",<.>/?~ะแธโฒค๐๐ค๐๊ ๊งศ๐๐ฅ๊ก๐๐ตวฌ๐ฟ๐ล๐๐ฏ๐ด๐๐๊ซลธ๐ก"""
r"""๐ถฦ๐ผแธแบฟแตฎโ๐แฅ๐ะบฮนแนีคโฑบ๐
๐ฒ๐ฃ๐ลง๐ขแนฝแบ๐
แงลพ1234567890!@#$%^&*()-_=+[{]};:'",<.>/?~ัฆ๐ฑฦแฮฃโฑิาคูก๐ะ๐๐ฦศ๐ธ๐แน๐ขแนฎแนบฦฒแ๊ซ๐๐ญ"""
r"""แรงแซ๐๐ฟ๐แธง๐๐ฃาษญแธฟ๐๐จ๐๐ขแน๐ผัรบ๐ณแบโคฌ๐ฒ๐1234567890!@#$%^&*()-_=+[{]};:'",<.>/?~๐ ฮ๐๐๐ด๐ฤขศแป๐ต๊ส๐ผโเงฆ๐ธ๐คี๊ขแนฐวโ
ค๐โฒฌ๐๐๐ข๐ค"""
)
# char \x00 cannot be sent in a DevString. All other 1-255 chars can
ints = tuple(range(1, 256))
bytes_devstring = bytes(ints)
str_devstring = bytes_devstring.decode("latin-1")
# Test devices
class SimpleDevice(Device):
def init_device(self):
self.set_state(DevState.ON)
class ClassicAPISimpleDeviceImpl(LatestDeviceImpl):
def __init__(self, cls, name):
LatestDeviceImpl.__init__(self, cls, name)
ClassicAPISimpleDeviceImpl.init_device(self)
def init_device(self):
self.get_device_properties(self.get_device_class())
self.attr_attr1_read = 100
def read_attr1(self, attr):
attr.set_value(self.attr_attr1_read)
class ClassicAPISimpleDeviceClass(DeviceClass):
attr_list = {"attr1": [[DevLong64, SCALAR, READ]]}
# Test enums
class GoodEnum(enum.IntEnum):
START = 0
MIDDLE = 1
END = 2
class BadEnumNonZero(enum.IntEnum):
START = 1
MIDDLE = 2
END = 3
class BadEnumSkipValues(enum.IntEnum):
START = 0
MIDDLE = 2
END = 4
class BadEnumDuplicates(enum.IntEnum):
START = 0
MIDDLE = 1
END = 1
# Helpers
# Note on Tango properties using the Tango File database:
# Tango file database cannot handle properties with '\n'. It doesn't
# handle '\' neither. And it cuts ASCII extended characters. That is
# why you will find that all property related tests are truncated to
# the first two values of the arrays below
GENERAL_TYPED_VALUES = {
int: (1, 2, -65535, 23),
float: (2.71, 3.14, -34.678e-10, 12.678e15),
str: ("hey hey", "my my", bytes_devstring, str_devstring),
bool: (False, True, True, False),
(int,): (
np.array([1, 2]),
(1, 2, 3),
[9, 8, 7],
[-65535, 2224],
[0, 0],
),
(float,): (
np.array([0.1, 0.2]),
(0.1, 0.2, 0.3),
[0.9, 0.8, 0.7],
[-6.3232e-3],
[0.0, 12.56e12],
),
(str,): (
np.array(["foo", "bar"]),
["ab", "cd", "ef"],
["gh", "ij", "kl"],
3 * [bytes_devstring],
3 * [str_devstring],
),
(bool,): (
np.array([True, False]),
[False, False, True],
[True, False, False],
[False],
[True],
),
}
COMMAND_TYPED_VALUES = {
DevVarLongStringArray: ([[1, 2, 3], ["foo", "bar", "hmm"]],),
DevVarDoubleStringArray: ([[1.1, 2.2, 3.3], ["foo", "bar", "hmm"]],),
}
IMAGE_TYPED_VALUES = {
((int,),): (
np.vstack((np.array([1, 2]), np.array([3, 4]))),
((1, 2, 3), (4, 5, 6)),
[[-65535, 2224], [-65535, 2224]],
),
((float,),): (
np.vstack((np.array([0.1, 0.2]), np.array([0.3, 0.4]))),
((0.1, 0.2, 0.3), (0.9, 0.8, 0.7)),
[[-6.3232e-3, 0.0], [0.0, 12.56e12]],
),
((str,),): (
np.vstack((np.array(["hi-hi", "ha-ha"]), np.array(["hu-hu", "yuhuu"]))),
[["ab", "cd", "ef"], ["gh", "ij", "kl"]],
[3 * [bytes_devstring], 3 * [bytes_devstring]],
[3 * [str_devstring], 3 * [str_devstring]],
),
((bool,),): (
np.vstack((np.array([True, False]), np.array([False, True]))),
[[False, False, True], [True, False, False]],
[[False]],
[[True]],
),
}
_numpy_hits_source = (
((np.bool_,), True, [True, False], [[True, False], [False, True]]),
((np.ubyte,), 1, [1, 2], [[1, 2], [3, 4]]),
(
(
np.short,
np.ushort,
np.int32,
np.uint32,
np.int64,
np.uint64,
),
1,
[1, 2],
[[1, 2], [3, 4]],
),
(
(
np.float64,
np.float32,
),
1.1,
[1.1, 2.2],
[[1.1, 2.2], [3.3, 4.4]],
),
)
if npt:
NUMPY_GENERAL_TYPING_HINTS = []
NUMPY_IMAGES_TYPING_HINTS = []
for dtypes, scalar, spectrum, image in _numpy_hits_source:
for dtype in dtypes:
NUMPY_GENERAL_TYPING_HINTS.extend(
[
[dtype, dtype, AttrDataFormat.SCALAR, scalar],
[dtype, npt.NDArray[dtype], AttrDataFormat.SPECTRUM, spectrum],
]
)
NUMPY_IMAGES_TYPING_HINTS.append(
[dtype, npt.NDArray[dtype], AttrDataFormat.IMAGE, image]
)
WRONG_NUMPY_TYPING_HINTS = ( # dformat, max_x, max_y, value, error, match
(None, None, None, None, RuntimeError, "AttrDataFormat has to be specified"),
(
AttrDataFormat.IMAGE,
3,
0,
[[1, 2], [3, 4]],
DevFailed,
"Maximum y dim. wrongly defined",
),
(
AttrDataFormat.SPECTRUM,
3,
0,
[[1, 2], [3, 4]],
TypeError,
"No registered converter",
),
)
EXTRACT_AS = [
(ExtractAs.Numpy, np.ndarray),
(ExtractAs.Tuple, tuple),
(ExtractAs.List, list),
(ExtractAs.Bytes, bytes),
(ExtractAs.ByteArray, bytearray),
(ExtractAs.String, str),
]
BASE_TYPES = [float, int, str, bool]
# we also test a large dataset to force memory allocation from heap,
# to insure immediate segfault if we try to access data after dereferencing
LARGE_DATA_SIZE = 1 * 1024**2 # 1 Mb seems to be enough
DEV_ENCODED_DATA = {
"str": UTF8_STRING,
"bytes": UTF8_STRING.encode(),
"bytearray": bytearray(UTF8_STRING.encode()),
}
# these sets to test Device Server input arguments
OS_SYSTEMS = ["linux", "win"]
# os_system, in string, out arguments list, raised exception
DEVICE_SERVER_ARGUMENTS = (
(
["linux", "win"],
"MyDs instance --nodb --port 1234",
["MyDs", "instance", "-nodb", "-ORBendPoint", "giop:tcp:0.0.0.0:1234"],
),
(
["linux", "win"],
"MyDs -port 1234 -host myhost instance",
["MyDs", "instance", "-ORBendPoint", "giop:tcp:myhost:1234"],
),
(
["linux", "win"],
"MyDs instance --ORBendPoint giop:tcp::1234",
["MyDs", "instance", "-ORBendPoint", "giop:tcp::1234"],
),
(
["linux", "win"],
"MyDs instance -nodb -port 1000 -dlist a/b/c;d/e/f",
[
"MyDs",
"instance",
"-ORBendPoint",
"giop:tcp:0.0.0.0:1000",
"-nodb",
"-dlist",
"a/b/c;d/e/f",
],
),
(
["linux", "win"],
"MyDs instance -file a/b/c",
["MyDs", "instance", "-file=a/b/c"],
),
([], "MyDs instance -nodb", []), # this test should always fail
([], "MyDs instance -dlist a/b/c;d/e/f", []), # this test should always fail
# the most complicated case: verbose
(["linux", "win"], "MyDs instance -vvvv", ["MyDs", "instance", "-v4"]),
(
["linux", "win"],
"MyDs instance --verbose --verbose --verbose --verbose",
["MyDs", "instance", "-v4"],
),
(["linux", "win"], "MyDs instance -v4", ["MyDs", "instance", "-v4"]),
(["linux", "win"], "MyDs instance -v 4", ["MyDs", "instance", "-v4"]),
# some options can be only in win, in linux should be error
(
["win"],
"MyDs instance -dbg -i -s -u",
["MyDs", "instance", "-dbg", "-i", "-s", "-u"],
),
# variable ORB options
(
["linux", "win"],
"MyDs instance -ORBtest1 test1 --ORBtest2 test2",
["MyDs", "instance", "-ORBtest1", "test1", "-ORBtest2", "test2"],
),
(
["linux", "win"],
"MyDs ORBinstance -ORBtest myORBparam",
["MyDs", "ORBinstance", "-ORBtest", "myORBparam"],
),
(
["linux", "win"],
"MyDs instance -nodb -ORBendPoint giop:tcp:localhost:1234 -ORBendPointPublish giop:tcp:myhost.local:2345",
[
"MyDs",
"instance",
"-nodb",
"-ORBendPoint",
"giop:tcp:localhost:1234",
"-ORBendPointPublish",
"giop:tcp:myhost.local:2345",
],
),
(
[],
"MyDs instance -ORBtest1 test1 --orbinvalid value",
[],
), # lowercase "orb" should fail
)
def convert_dtype_to_typing_hint(dtype):
check_x_dim, check_y_dim = False, False
if type(dtype) is tuple:
dtype = dtype[0]
check_x_dim = True
if type(dtype) is tuple:
dtype = dtype[0]
check_y_dim = True
tuple_hint = tuple[
tuple[dtype, dtype, dtype],
tuple[dtype, dtype, dtype],
]
list_hint = list[list[dtype]]
else:
tuple_hint = tuple[dtype, dtype, dtype]
list_hint = list[dtype]
elif dtype == DevVarLongStringArray:
tuple_hint = tuple[tuple[int], tuple[str]]
list_hint = list[list[int], list[str]]
elif dtype == DevVarDoubleStringArray:
tuple_hint = tuple[tuple[float], tuple[str]]
list_hint = list[list[float], list[str]]
else:
tuple_hint = dtype
list_hint = dtype
return tuple_hint, list_hint, check_x_dim, check_y_dim
def general_decorator(function=None):
if function:
@wraps(function)
def _wrapper(*args, **kwargs):
return function(*args, **kwargs)
return _wrapper
else:
return general_decorator
def general_asyncio_decorator(function=None):
if function:
@wraps(function)
async def _wrapper(*args, **kwargs):
return await function(*args, **kwargs)
return _wrapper
else:
return general_asyncio_decorator
def repr_type(x):
if isinstance(x, (list, tuple)):
return f"({repr_type(x[0])},)"
elif x == DevVarLongStringArray:
return "DevVarLongStringArray"
elif x == DevVarDoubleStringArray:
return "DevVarDoubleStringArray"
return f"{x.__name__}"
def repr_numpy_type(dtype, dformat):
if dformat == AttrDataFormat.SCALAR:
return f"{dtype.__name__}, SCALAR"
elif dformat == AttrDataFormat.SPECTRUM:
return f"np.NDarray[{dtype.__name__}], SPECTRUM"
else:
return f"np.n2array[{dtype.__name__}], IMAGE"
# helpers to test enums
def check_attr_type(read_attr, attr_data_format, desired_type):
if attr_data_format == AttrDataFormat.SCALAR:
assert isinstance(read_attr, desired_type)
elif attr_data_format == AttrDataFormat.SPECTRUM:
for state in read_attr:
assert isinstance(state, desired_type)
else:
for state in read_attr:
for stat in state:
assert isinstance(stat, desired_type)
def assert_value_label(read_attr, value, label):
assert read_attr.value == value
assert read_attr.name == label
def check_read_attr(read_attr, attr_data_format, value, label):
if attr_data_format == AttrDataFormat.SCALAR:
assert_value_label(read_attr, value, label)
elif attr_data_format == AttrDataFormat.SPECTRUM:
for val in read_attr:
assert_value_label(val, value, label)
else:
for val in read_attr:
for v in val:
assert_value_label(v, value, label)
def make_nd_value(value, attr_data_format):
if attr_data_format == AttrDataFormat.SCALAR:
return value
elif attr_data_format == AttrDataFormat.SPECTRUM:
return (value,)
else:
return ((value,),)
# Numpy helpers
if pytest:
def __assert_all_types(a, b):
if isinstance(a, str):
assert a == b
return
elif isinstance(a, dict):
for k, v in a.items():
assert k in b
assert_close(v, b[k])
return
elif isinstance(a, (np.bool_, bool)) or isinstance(b, (np.bool_, bool)):
assert a == b
return
elif isinstance(a, (np.bool_, bool)) or isinstance(b, (np.bool_, bool)):
assert a == b
return
try:
assert a == pytest.approx(b)
except (ValueError, TypeError):
np.testing.assert_allclose(a, b)
def assert_close(a, b):
if is_non_str_seq(a):
assert len(a) == len(b)
for _a, _b in zip(a, b):
assert_close(_a, _b)
else:
__assert_all_types(a, b)
def __convert_value(value):
if isinstance(value, bytes):
return value.decode("latin-1")
return value
def create_result(dtype, value):
if isinstance(dtype, (list, tuple)):
dtype = dtype[0]
return [create_result(dtype, v) for v in value]
elif dtype == DevVarLongStringArray:
return [create_result(dtype, v) for v, dtype in zip(value, [int, str])]
elif dtype == DevVarDoubleStringArray:
return [create_result(dtype, v) for v, dtype in zip(value, [float, str])]
return __convert_value(value)
def convert_to_type(value, attr_type, expected_type):
if expected_type in [tuple, list]:
return expected_type(value)
elif expected_type == np.ndarray:
return np.array(value, dtype=FROM_TANGO_TO_NUMPY_TYPE[attr_type])
elif expected_type in [bytes, bytearray, str]:
value = np.array(value, dtype=FROM_TANGO_TO_NUMPY_TYPE[attr_type]).tobytes()
if expected_type is bytearray:
return bytearray(value)
elif expected_type is str:
return "".join([chr(b) for b in value])
return value
else:
pytest.xfail("Unknown extract_as type")
@pytest.fixture(params=DevState.values.values())
def state(request):
return request.param
@pytest.fixture(
params=list(GENERAL_TYPED_VALUES.items()), ids=lambda x: repr_type(x[0])
)
def general_typed_values(request):
dtype, values = request.param
expected = lambda v: create_result(dtype, v)
return dtype, values, expected
@pytest.fixture(
params=list({**GENERAL_TYPED_VALUES, **COMMAND_TYPED_VALUES}.items()),
ids=lambda x: repr_type(x[0]),
)
def command_typed_values(request):
dtype, values = request.param
expected = lambda v: create_result(dtype, v)
return dtype, values, expected
@pytest.fixture(
params=list({**GENERAL_TYPED_VALUES, **IMAGE_TYPED_VALUES}.items()),
ids=lambda x: repr_type(x[0]),
)
def attribute_typed_values(request):
dtype, values = request.param
expected = lambda v: create_result(dtype, v)
return dtype, values, expected
if npt:
@pytest.fixture(
params=NUMPY_GENERAL_TYPING_HINTS, ids=lambda x: repr_numpy_type(x[0], x[2])
)
def command_numpy_typed_values(request):
dtype, type_hint, dformat, values = request.param
expected = lambda v: create_result(dtype, v)
return type_hint, dformat, values, expected
@pytest.fixture(
params=NUMPY_GENERAL_TYPING_HINTS + NUMPY_IMAGES_TYPING_HINTS,
ids=lambda x: repr_numpy_type(x[0], x[2]),
)
def attribute_numpy_typed_values(request):
dtype, type_hint, dformat, values = request.param
expected = lambda v: create_result(dtype, v)
return type_hint, dformat, values, expected
@pytest.fixture(
params=WRONG_NUMPY_TYPING_HINTS, ids=lambda x: f"{x[-2].__name__}: {x[-1]}"
)
def attribute_wrong_numpy_typed(request):
return request.param
else:
@pytest.fixture
def command_numpy_typed_values(request):
raise RuntimeError(
f"Numpy typing supported only for Numpy >= 1.20, "
f"while current version is {np.version.version}"
)
@pytest.fixture
def attribute_numpy_typed_values(request):
raise RuntimeError(
f"Numpy typing supported only for Numpy >= 1.20, "
f"while current version is {np.version.version}"
)
@pytest.fixture
def attribute_wrong_numpy_typed(request):
raise RuntimeError(
f"Numpy typing supported only for Numpy >= 1.20, "
f"while current version is {np.version.version}"
)
@pytest.fixture(
params=list(DEV_ENCODED_DATA.items()),
ids=list(DEV_ENCODED_DATA.keys()),
)
def dev_encoded_values(request):
return request.param
@pytest.fixture(
params=EXTRACT_AS, ids=[f"extract_as.{req_type}" for req_type, _ in EXTRACT_AS]
)
def extract_as(request):
requested_type, expected_type = request.param
return requested_type, expected_type
@pytest.fixture(params=BASE_TYPES)
def base_type(request):
return request.param
@pytest.fixture(params=GreenMode.values.values())
def green_mode(request):
return request.param
@pytest.fixture(params=[GreenMode.Synchronous, GreenMode.Asyncio, GreenMode.Gevent])
def server_green_mode(request):
return request.param
@pytest.fixture(
params=[AttrDataFormat.SCALAR, AttrDataFormat.SPECTRUM, AttrDataFormat.IMAGE]
)
def attr_data_format(request):
return request.param
@pytest.fixture(
params=[
SerialModel.BY_DEVICE,
SerialModel.BY_CLASS,
SerialModel.BY_PROCESS,
SerialModel.NO_SYNC,
]
)
def server_serial_model(request):
return request.param
|