diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000000000000000000000000000000000..dd330dce1226048d59332702870b7601336fcde6 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,8 @@ +# To ignore the commits below when using git blame: +# git blame --ignore-revs-file .git-blame-ignore-revs src/ska_tango_base/commands.py +# or +# git config blame.ignoreRevsFile .git-blame-ignore-revs +# git blame src/ska_tango_base/commands.py + +# black entire repo +4402797422cf9e01687e34786b94cbf2674f05e1 diff --git a/.make/lint.mk b/.make/lint.mk new file mode 100644 index 0000000000000000000000000000000000000000..318a1cd587934aa71ed9e6a2a7ba5a3b105a666a --- /dev/null +++ b/.make/lint.mk @@ -0,0 +1,19 @@ + +_format-lint-install: # install requirements for code formatting and checking + python3 -m pip install -r requirements-lint.txt + +.PHONY: _format-lint-install + + +format: _format-lint-install # apply code formatting + black src/ tests/ + +lint: _format-lint-install + mkdir -p build/reports + - python3 -m flake8 --format=junit-xml --output-file=build/reports/linting.xml src/ tests/ + python3 -m flake8 --statistics --show-source src/ tests/ + +# Format code then lint it +format-lint: format lint + +.PHONY: format lint format-lint diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index ddbbd9ecc51865295421a6d8a49fdfd06e0633de..0000000000000000000000000000000000000000 --- a/.pylintrc +++ /dev/null @@ -1,489 +0,0 @@ -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code. -extension-pkg-whitelist= - -# Add files or directories to the blacklist. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the blacklist. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the -# number of processors available to use. -jobs=0 - -# Control the amount of potential inferred values when inferring a single -# object. This can help the performance when dealing with large functions or -# complex, nested conditions. -limit-inference-results=100 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -# load-plugins= - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# When enabled, pylint would attempt to guess common misconfiguration and emit -# user-friendly hints instead of false-positive error messages. -suggestion-mode=yes - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once). You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use "--disable=all --enable=classes -# --disable=W". -disable=C, - R, - W, - I - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable=unreachable, - duplicate-key, - unnecessary-semicolon, - global-variable-not-assigned, - unused-variable, - binary-op-exception, - bad-format-string, - anomalous-backslash-in-string, - bad-open-mode - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details. -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio). You can also give a reporter class, e.g. -# mypackage.mymodule.MyReporterClass. -output-format=parseable - -# Tells whether to display a full report or only the messages. -reports=yes - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - -# Complete name of functions that never returns. When checking for -# inconsistent-return-statements if a never returning function is called then -# it will be considered as an explicit return statement and no message will be -# printed. -never-returning-functions=sys.exit - - -[BASIC] - -# Naming style matching correct argument names. -argument-naming-style=snake_case - -# Regular expression matching correct argument names. Overrides argument- -# naming-style. -#argument-rgx= - -# Naming style matching correct attribute names. -attr-naming-style=snake_case - -# Regular expression matching correct attribute names. Overrides attr-naming- -# style. -#attr-rgx= - -# Bad variable names which should always be refused, separated by a comma. -bad-names=foo, - bar, - baz, - toto, - tutu, - tata - -# Naming style matching correct class attribute names. -class-attribute-naming-style=any - -# Regular expression matching correct class attribute names. Overrides class- -# attribute-naming-style. -#class-attribute-rgx= - -# Naming style matching correct class names. -class-naming-style=PascalCase - -# Regular expression matching correct class names. Overrides class-naming- -# style. -#class-rgx= - -# Naming style matching correct constant names. -const-naming-style=UPPER_CASE - -# Regular expression matching correct constant names. Overrides const-naming- -# style. -#const-rgx= - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Naming style matching correct function names. -function-naming-style=snake_case - -# Regular expression matching correct function names. Overrides function- -# naming-style. -#function-rgx= - -# Good variable names which should always be accepted, separated by a comma. -good-names=i, - j, - k, - ex, - Run, - _ - -# Include a hint for the correct naming format with invalid-name. -include-naming-hint=no - -# Naming style matching correct inline iteration names. -inlinevar-naming-style=any - -# Regular expression matching correct inline iteration names. Overrides -# inlinevar-naming-style. -#inlinevar-rgx= - -# Naming style matching correct method names. -method-naming-style=snake_case - -# Regular expression matching correct method names. Overrides method-naming- -# style. -#method-rgx= - -# Naming style matching correct module names. -module-naming-style=snake_case - -# Regular expression matching correct module names. Overrides module-naming- -# style. -#module-rgx= - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -# These decorators are taken in consideration only for invalid-name. -property-classes=abc.abstractproperty - -# Naming style matching correct variable names. -variable-naming-style=snake_case - -# Regular expression matching correct variable names. Overrides variable- -# naming-style. -#variable-rgx= - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=no - -# Minimum lines number of a similarity. -min-similarity-lines=4 - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -notes=FIXME, - XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members=target|logger - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# Tells whether to warn about missing members when the owner of the attribute -# is inferred to be None. -ignore-none=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules= - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format. -logging-modules=logging - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_, - _cb - -# A regular expression matching the name of dummy variables (i.e. expected to -# not be used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore. -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -expected-line-ending-format= - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )?<?https?://\S+>?$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module. -max-module-lines=1000 - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma, - dict-separator - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SPELLING] - -# Limits count of emitted suggestions for spelling mistakes. -max-spelling-suggestions=4 - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package.. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[DESIGN] - -# Maximum number of arguments for function / method. -max-args=5 - -# Maximum number of attributes for a class (see R0902). -max-attributes=7 - -# Maximum number of boolean expressions in an if statement. -max-bool-expr=5 - -# Maximum number of branch for function / method body. -max-branches=12 - -# Maximum number of locals for function / method body. -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body. -max-returns=6 - -# Maximum number of statements in function / method body. -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=2 - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__, - __new__, - setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict, - _fields, - _replace, - _source, - _make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=cls - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma. -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled). -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled). -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled). -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception". -overgeneral-exceptions=Exception diff --git a/Makefile b/Makefile index 3326f5ca49537fb6ba188ebe679bdb71648c3d75..cedc8f3996d8b4ad59712431daa434c52ef02c32 100644 --- a/Makefile +++ b/Makefile @@ -18,26 +18,21 @@ SHELL = /bin/bash DOCKER_REGISTRY_USER:=ska-telescope PROJECT = ska_tango_base IMAGE_FOR_DIAGRAMS = nexus.engageska-portugal.pt/ska-tango-images/pytango-builder:9.3.3.3 -# -# include makefile to pick up the standard Make targets, e.g., 'make build' -# build, 'make push' docker push procedure, etc. The other Make targets -# ('make lint', 'make test', etc.) are defined in this file. -# + + +# import some standard Make targets e.g. `make build` (for building +# docker images), ``make push` (docker push procedure), etc. include .make/Makefile.mk +# import make targets for code linting e.g. `make lint` +include .make/lint.mk + .DEFAULT_GOAL := help test: ## test ska_tango_base Python code mkdir -p build/reports python3 setup.py test | tee build/setup_py_test.stdout -lint: ## lint ska_tango_base Python code - python3 -m pip install -U pylint==2.4.4 - python3 -m pip install pylint2junit - mkdir -p build/reports - pylint --output-format=parseable src/ska_tango_base | tee build/code_analysis.stdout - pylint --output-format=pylint2junit.JunitReporter src/ska_tango_base > build/reports/linting.xml - test-in-docker: build ## Build the docker image and run tests inside it. @docker run --rm $(IMAGE):$(VERSION) make test @@ -63,4 +58,4 @@ docs-in-docker: ## Generate docs inside a container help: ## show this help. @grep -hE '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' -.PHONY: test lint test-in-docker lint-in-docker help +.PHONY: test test-in-docker lint-in-docker help diff --git a/requirements-lint.txt b/requirements-lint.txt new file mode 100644 index 0000000000000000000000000000000000000000..08b13b0f611d03e74efd5cfc29167c20f300444d --- /dev/null +++ b/requirements-lint.txt @@ -0,0 +1,4 @@ +black +flake8 +flake8_formatter_junit_xml +flake8-black \ No newline at end of file diff --git a/setup.cfg b/setup.cfg index e106b66ce498ac8a958ee201fe44e96f20358dbc..00c43d7e4aaaf7fd5723498bceaff04d6a7d4025 100644 --- a/setup.cfg +++ b/setup.cfg @@ -17,3 +17,11 @@ addopts = --verbose --junitxml=build/reports/unit-tests.xml console_output_style = progress junit_family = legacy + +[flake8] +# We have some very long Pogo PROTECTED REGION boundary comments that can't be broken. +# Black will still wrap at 88. +max-line-length = 120 + +# E203 and W503 conflict with black +ignore = E203,W503 diff --git a/src/ska_tango_base/alarm_handler_device.py b/src/ska_tango_base/alarm_handler_device.py index 22bb34ce37b6836a28a39e5c81dd743b02f2f5a0..120198827bf9c752c702d72fc599030d79a0bbfd 100644 --- a/src/ska_tango_base/alarm_handler_device.py +++ b/src/ska_tango_base/alarm_handler_device.py @@ -29,6 +29,7 @@ class SKAAlarmHandler(SKABaseDevice): """ A generic base device for Alarms for SKA. """ + # PROTECTED REGION ID(SKAAlarmHandler.class_variable) ENABLED START # # PROTECTED REGION END # // SKAAlarmHandler.class_variable @@ -37,11 +38,11 @@ class SKAAlarmHandler(SKABaseDevice): # ----------------- SubAlarmHandlers = device_property( - dtype=('str',), + dtype=("str",), ) AlarmConfigFile = device_property( - dtype='str', + dtype="str", ) # ---------- @@ -49,44 +50,44 @@ class SKAAlarmHandler(SKABaseDevice): # ---------- statsNrAlerts = attribute( - dtype='int', + dtype="int", doc="Number of active Alerts", ) """Device attribute.""" statsNrAlarms = attribute( - dtype='int', + dtype="int", doc="Number of active Alarms", ) """Device attribute.""" statsNrNewAlarms = attribute( - dtype='int', + dtype="int", doc="Number of New active alarms", ) """Device attribute.""" statsNrUnackAlarms = attribute( - dtype='double', + dtype="double", doc="Number of unacknowledged alarms", ) """Device attribute.""" statsNrRtnAlarms = attribute( - dtype='double', + dtype="double", doc="Number of returned alarms", ) """Device attribute.""" activeAlerts = attribute( - dtype=('str',), + dtype=("str",), max_dim_x=10000, doc="List of active alerts", ) """Device attribute.""" activeAlarms = attribute( - dtype=('str',), + dtype=("str",), max_dim_x=10000, doc="List of active alarms", ) @@ -103,23 +104,23 @@ class SKAAlarmHandler(SKABaseDevice): super().init_command_objects() self.register_command_object( "GetAlarmRule", - self.GetAlarmRuleCommand(self, self.op_state_model, self.logger) + self.GetAlarmRuleCommand(self, self.op_state_model, self.logger), ) self.register_command_object( "GetAlarmData", - self.GetAlarmDataCommand(self, self.op_state_model, self.logger) + self.GetAlarmDataCommand(self, self.op_state_model, self.logger), ) self.register_command_object( "GetAlarmAdditionalInfo", - self.GetAlarmAdditionalInfoCommand(self, self.op_state_model, self.logger) + self.GetAlarmAdditionalInfoCommand(self, self.op_state_model, self.logger), ) self.register_command_object( "GetAlarmStats", - self.GetAlarmStatsCommand(self, self.op_state_model, self.logger) + self.GetAlarmStatsCommand(self, self.op_state_model, self.logger), ) self.register_command_object( "GetAlertStats", - self.GetAlertStatsCommand(self, self.op_state_model, self.logger) + self.GetAlertStatsCommand(self, self.op_state_model, self.logger), ) def always_executed_hook(self): @@ -187,7 +188,7 @@ class SKAAlarmHandler(SKABaseDevice): Reads list of active alerts. :return: List of active alerts """ - return [''] + return [""] # PROTECTED REGION END # // SKAAlarmHandler.activeAlerts_read def read_activeAlarms(self): @@ -196,7 +197,7 @@ class SKAAlarmHandler(SKABaseDevice): Reads list of active alarms. :return: List of active alarms """ - return [''] + return [""] # PROTECTED REGION END # // SKAAlarmHandler.activeAlarms_read # -------- @@ -275,7 +276,12 @@ class SKAAlarmHandler(SKABaseDevice): """ return "" - @command(dtype_in='str', doc_in="Alarm name", dtype_out='str', doc_out="JSON string",) + @command( + dtype_in="str", + doc_in="Alarm name", + dtype_out="str", + doc_out="JSON string", + ) @DebugIt() def GetAlarmRule(self, argin): # PROTECTED REGION ID(SKAAlarmHandler.GetAlarmRule) ENABLED START # @@ -292,7 +298,12 @@ class SKAAlarmHandler(SKABaseDevice): return command(argin) # PROTECTED REGION END # // SKAAlarmHandler.GetAlarmRule - @command(dtype_in='str', doc_in="Alarm name", dtype_out='str', doc_out="JSON string",) + @command( + dtype_in="str", + doc_in="Alarm name", + dtype_out="str", + doc_out="JSON string", + ) @DebugIt() def GetAlarmData(self, argin): # PROTECTED REGION ID(SKAAlarmHandler.GetAlarmData) ENABLED START # @@ -310,7 +321,12 @@ class SKAAlarmHandler(SKABaseDevice): return command(argin) # PROTECTED REGION END # // SKAAlarmHandler.GetAlarmData - @command(dtype_in='str', doc_in="Alarm name", dtype_out='str', doc_out="JSON string", ) + @command( + dtype_in="str", + doc_in="Alarm name", + dtype_out="str", + doc_out="JSON string", + ) @DebugIt() def GetAlarmAdditionalInfo(self, argin): # PROTECTED REGION ID(SKAAlarmHandler.GetAlarmAdditionalInfo) ENABLED START # @@ -327,7 +343,10 @@ class SKAAlarmHandler(SKABaseDevice): return command(argin) # PROTECTED REGION END # // SKAAlarmHandler.GetAlarmAdditionalInfo - @command(dtype_out='str', doc_out="JSON string",) + @command( + dtype_out="str", + doc_out="JSON string", + ) @DebugIt() def GetAlarmStats(self): # PROTECTED REGION ID(SKAAlarmHandler.GetAlarmStats) ENABLED START # @@ -343,7 +362,10 @@ class SKAAlarmHandler(SKABaseDevice): return command() # PROTECTED REGION END # // SKAAlarmHandler.GetAlarmStats - @command(dtype_out='str', doc_out="JSON string",) + @command( + dtype_out="str", + doc_out="JSON string", + ) @DebugIt() def GetAlertStats(self): # PROTECTED REGION ID(SKAAlarmHandler.GetAlertStats) ENABLED START # @@ -359,6 +381,7 @@ class SKAAlarmHandler(SKABaseDevice): return command() # PROTECTED REGION END # // SKAAlarmHandler.GetAlertStats + # ---------- # Run server # ---------- @@ -376,5 +399,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // SKAAlarmHandler.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/base/__init__.py b/src/ska_tango_base/base/__init__.py index 6934169135c523f121f17479ad36a08cadecad4b..965a6367fa6fc2eef5d54c5bfa130dfd0f352b47 100644 --- a/src/ska_tango_base/base/__init__.py +++ b/src/ska_tango_base/base/__init__.py @@ -18,6 +18,7 @@ from .op_state_model import OpStateModel from .component_manager import BaseComponentManager from .reference_component_manager import ( - ReferenceBaseComponentManager, check_communicating + ReferenceBaseComponentManager, + check_communicating, ) from .base_device import SKABaseDevice diff --git a/src/ska_tango_base/base/admin_mode_model.py b/src/ska_tango_base/base/admin_mode_model.py index 9f4f1945b50665f4a17a0a8bd610cc7bcb476f37..95236b4123cc2d93b9ea37be8da5bef3f9ef44eb 100644 --- a/src/ska_tango_base/base/admin_mode_model.py +++ b/src/ska_tango_base/base/admin_mode_model.py @@ -121,7 +121,7 @@ class AdminModeModel: diagnosis.) The actions supported are: - + * **to_not_fitted** * **to_reserved** * **to_offline** diff --git a/src/ska_tango_base/base/base_device.py b/src/ska_tango_base/base/base_device.py index 809e1e9094a73f82ae3d24fcebde20c1a833a889..005d1d9cd2625ff5e913500be2d048afa7ae5cd6 100644 --- a/src/ska_tango_base/base/base_device.py +++ b/src/ska_tango_base/base/base_device.py @@ -34,19 +34,29 @@ from tango.server import run, Device, attribute, command, device_property import debugpy import ska_ser_logging from ska_tango_base import release -from ska_tango_base.base import ( - AdminModeModel, OpStateModel, BaseComponentManager -) +from ska_tango_base.base import AdminModeModel, OpStateModel, BaseComponentManager from ska_tango_base.commands import ( - BaseCommand, CompletionCommand, StateModelCommand, ResponseCommand, ResultCode + BaseCommand, + CompletionCommand, + StateModelCommand, + ResponseCommand, + ResultCode, ) from ska_tango_base.control_model import ( - AdminMode, ControlMode, SimulationMode, TestMode, HealthState, - LoggingLevel + AdminMode, + ControlMode, + SimulationMode, + TestMode, + HealthState, + LoggingLevel, ) from ska_tango_base.utils import get_groups_from_json -from ska_tango_base.faults import GroupDefinitionsError, LoggingTargetError, LoggingLevelError +from ska_tango_base.faults import ( + GroupDefinitionsError, + LoggingTargetError, + LoggingLevelError, +) LOG_FILE_SIZE = 1024 * 1024 # Log file size 1MB. _DEBUGGER_PORT = 5678 @@ -126,8 +136,9 @@ class TangoLoggingServiceHandler(logging.Handler): else: tango_level = "UNKNOWN" name = "!No Tango logger!" - return '<{} {} (Python {}, Tango {})>'.format( - self.__class__.__name__, name, python_level, tango_level) + return "<{} {} (Python {}, Tango {})>".format( + self.__class__.__name__, name, python_level, tango_level + ) class LoggingUtils: @@ -174,12 +185,15 @@ class LoggingUtils: if target_type not in default_target_names: raise LoggingTargetError( "Invalid target type: {} - options are {}".format( - target_type, list(default_target_names.keys()))) + target_type, list(default_target_names.keys()) + ) + ) if not target_name: target_name = default_target_names[target_type] if not target_name: raise LoggingTargetError( - "Target name required for type {}".format(target_type)) + "Target name required for type {}".format(target_type) + ) valid_target = "{}::{}".format(target_type, target_name) valid_targets.append(valid_target) @@ -232,7 +246,8 @@ class LoggingUtils: if not parsed.hostname: raise LoggingTargetError( "Invalid syslog URL - could not extract hostname from '{}'".format( - url) + url + ) ) try: port = int(parsed.port) @@ -243,11 +258,14 @@ class LoggingUtils: ) ) address = (parsed.hostname, port) - socktype = socket.SOCK_DGRAM if parsed.scheme == "udp" else socket.SOCK_STREAM + socktype = ( + socket.SOCK_DGRAM if parsed.scheme == "udp" else socket.SOCK_STREAM + ) else: raise LoggingTargetError( "Invalid syslog URL - expected file, udp or tcp protocol scheme in '{}'".format( - url) + url + ) ) return address, socktype @@ -270,28 +288,37 @@ class LoggingUtils: target_type, target_name = target.split("::", 1) else: raise LoggingTargetError( - "Invalid target requested - missing '::' separator: {}".format(target)) + "Invalid target requested - missing '::' separator: {}".format(target) + ) if target_type == "console": handler = logging.StreamHandler(sys.stdout) elif target_type == "file": log_file_name = target_name handler = logging.handlers.RotatingFileHandler( - log_file_name, 'a', LOG_FILE_SIZE, 2, None, False) + log_file_name, "a", LOG_FILE_SIZE, 2, None, False + ) elif target_type == "syslog": - address, socktype = LoggingUtils.get_syslog_address_and_socktype(target_name) + address, socktype = LoggingUtils.get_syslog_address_and_socktype( + target_name + ) handler = logging.handlers.SysLogHandler( address=address, facility=logging.handlers.SysLogHandler.LOG_SYSLOG, - socktype=socktype) + socktype=socktype, + ) elif target_type == "tango": if tango_logger: handler = TangoLoggingServiceHandler(tango_logger) else: raise LoggingTargetError( - "Missing tango_logger instance for 'tango' target type") + "Missing tango_logger instance for 'tango' target type" + ) else: raise LoggingTargetError( - "Invalid target type requested: '{}' in '{}'".format(target_type, target)) + "Invalid target type requested: '{}' in '{}'".format( + target_type, target + ) + ) formatter = ska_ser_logging.get_default_formatter(tags=True) handler.setFormatter(formatter) handler.name = target @@ -308,10 +335,12 @@ class LoggingUtils: logger.removeHandler(handler) for target in targets: if target in added_targets: - handler = LoggingUtils.create_logging_handler(target, logger.tango_logger) + handler = LoggingUtils.create_logging_handler( + target, logger.tango_logger + ) logger.addHandler(handler) - logger.info('Logging targets set to %s', targets) + logger.info("Logging targets set to %s", targets) # PROTECTED REGION END # // SKABaseDevice.additionnal_import @@ -375,32 +404,24 @@ class SKABaseDevice(Device): device._simulation_mode = SimulationMode.FALSE device._test_mode = TestMode.NONE - device._build_state = '{}, {}, {}'.format(release.name, - release.version, - release.description) + device._build_state = "{}, {}, {}".format( + release.name, release.version, release.description + ) device._version_id = release.version device._methods_patched_for_debugger = False try: # create Tango Groups dict, according to property self.logger.debug( - "Groups definitions: {}".format( - device.GroupDefinitions - ) - ) - device.groups = get_groups_from_json( - device.GroupDefinitions + "Groups definitions: {}".format(device.GroupDefinitions) ) + device.groups = get_groups_from_json(device.GroupDefinitions) self.logger.info( - "Groups loaded: {}".format( - sorted(device.groups.keys()) - ) + "Groups loaded: {}".format(sorted(device.groups.keys())) ) except GroupDefinitionsError: self.logger.debug( - "No Groups loaded for device: {}".format( - device.get_name() - ) + "No Groups loaded for device: {}".format(device.get_name()) ) message = "SKABaseDevice Init command completed OK" @@ -458,7 +479,7 @@ class SKABaseDevice(Device): self._logging_level = None self.write_loggingLevel(self.LoggingLevelDefault) self.write_loggingTargets(self.LoggingTargetsDefault) - self.logger.debug('Logger initialised') + self.logger.debug("Logger initialised") # monkey patch Tango Logging Service streams so they go to the Python # logger instead @@ -474,30 +495,28 @@ class SKABaseDevice(Device): # Device Properties # ----------------- - SkaLevel = device_property( - dtype='int16', default_value=4 - ) + SkaLevel = device_property(dtype="int16", default_value=4) """ Device property. - + Indication of importance of the device in the SKA hierarchy to support drill-down navigation: 1..6, with 1 highest. """ GroupDefinitions = device_property( - dtype=('str',), + dtype=("str",), ) """ Device property. - + Each string in the list is a JSON serialised dict defining the ``group_name``, ``devices`` and ``subgroups`` in the group. A Tango Group object is created for each item in the list, according to the hierarchy defined. This provides easy access to the managed devices in bulk, or individually. - + The general format of the list is as follows, with optional ``devices`` and ``subgroups`` keys:: - + [ {"group_name": "<name>", "devices": ["<dev name>", ...]}, {"group_name": "<name>", @@ -506,9 +525,9 @@ class SKABaseDevice(Device): {<nested group>}, ...]}, ... ] - + For example, a hierarchy of racks, servers and switches:: - + [ {"group_name": "servers", "devices": ["elt/server/1", "elt/server/2", "elt/server/3", "elt/server/4"]}, @@ -530,21 +549,21 @@ class SKABaseDevice(Device): """ LoggingLevelDefault = device_property( - dtype='uint16', default_value=LoggingLevel.INFO + dtype="uint16", default_value=LoggingLevel.INFO ) """ Device property. - + Default logging level at device startup. See :py:class:`~ska_tango_base.control_model.LoggingLevel` """ LoggingTargetsDefault = device_property( - dtype='DevVarStringArray', default_value=["tango::logger"] + dtype="DevVarStringArray", default_value=["tango::logger"] ) """ Device property. - + Default logging targets at device startup. See the project readme for details. """ @@ -554,13 +573,13 @@ class SKABaseDevice(Device): # ---------- buildState = attribute( - dtype='str', + dtype="str", doc="Build state of this device", ) """Device attribute.""" versionId = attribute( - dtype='str', + dtype="str", doc="Version Id of this device", ) """Device attribute.""" @@ -569,29 +588,29 @@ class SKABaseDevice(Device): dtype=LoggingLevel, access=AttrWriteType.READ_WRITE, doc="Current logging level for this device - " - "initialises to LoggingLevelDefault on startup", + "initialises to LoggingLevelDefault on startup", ) """ Device attribute. - + See :py:class:`~ska_tango_base.control_model.LoggingLevel` """ loggingTargets = attribute( - dtype=('str',), + dtype=("str",), access=AttrWriteType.READ_WRITE, max_dim_x=4, doc="Logging targets for this device, excluding ska_ser_logging defaults" - " - initialises to LoggingTargetsDefault on startup", + " - initialises to LoggingTargetsDefault on startup", ) """Device attribute.""" healthState = attribute( dtype=HealthState, doc="The health state reported for this device. " - "It interprets the current device" - " condition and condition of all managed devices to set this. " - "Most possibly an aggregate attribute.", + "It interprets the current device" + " condition and condition of all managed devices to set this. " + "Most possibly an aggregate attribute.", ) """Device attribute.""" @@ -601,8 +620,8 @@ class SKABaseDevice(Device): memorized=True, hw_memorized=True, doc="The admin mode reported for this device. It may interpret the current " - "device condition and condition of all managed devices to set this. " - "Most possibly an aggregate attribute.", + "device condition and condition of all managed devices to set this. " + "Most possibly an aggregate attribute.", ) """Device attribute.""" @@ -612,9 +631,9 @@ class SKABaseDevice(Device): memorized=True, hw_memorized=True, doc="The control mode of the device. REMOTE, LOCAL" - "\nTango Device accepts only from a ‘local’ client and ignores commands and " - "queries received from TM or any other ‘remote’ clients. The Local clients" - " has to release LOCAL control before REMOTE clients can take control again.", + "\nTango Device accepts only from a ‘local’ client and ignores commands and " + "queries received from TM or any other ‘remote’ clients. The Local clients" + " has to release LOCAL control before REMOTE clients can take control again.", ) """Device attribute.""" @@ -624,8 +643,8 @@ class SKABaseDevice(Device): memorized=True, hw_memorized=True, doc="Reports the simulation mode of the device. \nSome devices may implement " - "both modes, while others will have simulators that set simulationMode " - "to True while the real devices always set simulationMode to False.", + "both modes, while others will have simulators that set simulationMode " + "to True while the real devices always set simulationMode to False.", ) """Device attribute.""" @@ -635,8 +654,8 @@ class SKABaseDevice(Device): memorized=True, hw_memorized=True, doc="The test mode of the device. \n" - "Either no test mode or an " - "indication of the test mode.", + "Either no test mode or an " + "indication of the test mode.", ) """Device attribute.""" @@ -727,7 +746,7 @@ class SKABaseDevice(Device): ) self.admin_mode_model = AdminModeModel( logger=self.logger, - callback = self._update_admin_mode, + callback=self._update_admin_mode, ) def create_component_manager(self): @@ -777,7 +796,9 @@ class SKABaseDevice(Device): self.register_command_object( "GetVersionInfo", self.GetVersionInfoCommand(*device_args) ) - self.register_command_object("DebugDevice", self.DebugDeviceCommand(*device_args)) + self.register_command_object( + "DebugDevice", self.DebugDeviceCommand(*device_args) + ) def always_executed_hook(self): # PROTECTED REGION ID(SKABaseDevice.always_executed_hook) ENABLED START # @@ -842,15 +863,18 @@ class SKABaseDevice(Device): except ValueError: raise LoggingLevelError( "Invalid level - {} - must be one of {} ".format( - value, [v for v in LoggingLevel.__members__.values()])) + value, [v for v in LoggingLevel.__members__.values()] + ) + ) self._logging_level = lmc_logging_level self.logger.setLevel(_LMC_TO_PYTHON_LOGGING_LEVEL[lmc_logging_level]) self.logger.tango_logger.set_level( _LMC_TO_TANGO_LOGGING_LEVEL[lmc_logging_level] ) - self.logger.info('Logging level set to %s on Python and Tango loggers', - lmc_logging_level) + self.logger.info( + "Logging level set to %s on Python and Tango loggers", lmc_logging_level + ) # PROTECTED REGION END # // SKABaseDevice.loggingLevel_write def read_loggingTargets(self): @@ -877,8 +901,7 @@ class SKABaseDevice(Device): :param value: Logging targets for logger """ device_name = self.get_name() - valid_targets = LoggingUtils.sanitise_logging_targets(value, - device_name) + valid_targets = LoggingUtils.sanitise_logging_targets(value, device_name) LoggingUtils.update_logging_handlers(valid_targets, self.logger) # PROTECTED REGION END # // SKABaseDevice.loggingTargets_write @@ -1014,7 +1037,10 @@ class SKABaseDevice(Device): device = self.target return [f"{device.__class__.__name__}, {device.read_buildState()}"] - @command(dtype_out=('str',), doc_out="Version strings",) + @command( + dtype_out=("str",), + doc_out="Version strings", + ) @DebugIt() def GetVersionInfo(self): # PROTECTED REGION ID(SKABaseDevice.GetVersionInfo) ENABLED START # @@ -1080,7 +1106,7 @@ class SKABaseDevice(Device): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -1150,7 +1176,7 @@ class SKABaseDevice(Device): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -1220,7 +1246,7 @@ class SKABaseDevice(Device): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -1244,6 +1270,7 @@ class SKABaseDevice(Device): """ A class for the SKABaseDevice's On() command. """ + def __init__(self, target, op_state_model, logger=None): """ Constructor for OnCommand @@ -1262,7 +1289,6 @@ class SKABaseDevice(Device): """ super().__init__(target, op_state_model, "on", logger=logger) - def do(self): """ Stateless hook for On() command functionality. @@ -1369,7 +1395,9 @@ class SKABaseDevice(Device): for name, method in inspect.getmembers(device, inspect.ismethod): methods.append((device, name, method)) for command_object in device._command_objects.values(): - for name, method in inspect.getmembers(command_object, inspect.ismethod): + for name, method in inspect.getmembers( + command_object, inspect.ismethod + ): methods.append((command_object, name, method)) return methods @@ -1405,8 +1433,7 @@ class SKABaseDevice(Device): setattr(owner, name, patched_method) @command( - dtype_out="DevUShort", - doc_out="The TCP port the debugger is listening on." + dtype_out="DevUShort", doc_out="The TCP port the debugger is listening on." ) @DebugIt() def DebugDevice(self): @@ -1437,5 +1464,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // SKABaseDevice.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/base/component_manager.py b/src/ska_tango_base/base/component_manager.py index a7535685c6ed37c30ce0ba5a6c771f22c388ce45..049fcc1f310a600c75ecc8e154150641e83c27a1 100644 --- a/src/ska_tango_base/base/component_manager.py +++ b/src/ska_tango_base/base/component_manager.py @@ -12,7 +12,7 @@ The basic model is: * A software routine, possibly implemented within the Tango device itself - + * In a hierarchical system, a pool of lower-level Tango devices. * A Tango device will usually need to establish and maintain a @@ -53,7 +53,7 @@ class BaseComponentManager: """ Establish communication with the component, then start monitoring. This is the place to do things like: - + * Initiate a connection to the component (if your communication is connection-oriented) * Subscribe to component events (if using "pull" model) @@ -79,7 +79,7 @@ class BaseComponentManager: Whether communication with the component is established and active, allowing monitoring and control of the component. For example: - + * If communication is over a connection, are you connected? * If communication is via event subscription, are you subscribed, and is the event subsystem healthy? diff --git a/src/ska_tango_base/base/op_state_model.py b/src/ska_tango_base/base/op_state_model.py index 0e05cb2b084f15d7a2ae86223d71b25795812804..46a32f9a47c9fa74dbe7c9ba2a482037d00985d1 100644 --- a/src/ska_tango_base/base/op_state_model.py +++ b/src/ska_tango_base/base/op_state_model.py @@ -343,7 +343,7 @@ class OpStateModel: A diagram of the operational state model, as implemented, is shown below. - + .. uml:: op_state_model.uml :caption: Diagram of the operational state model diff --git a/src/ska_tango_base/base/reference_component_manager.py b/src/ska_tango_base/base/reference_component_manager.py index ac3b0369d00b2fdf84580bb628e6882e178a294c..cf2ae9e991e30f8494baeaffa69a579187fac678 100644 --- a/src/ska_tango_base/base/reference_component_manager.py +++ b/src/ska_tango_base/base/reference_component_manager.py @@ -19,6 +19,7 @@ def check_communicating(func): :return: the wrapped function """ + @functools.wraps(func) def _wrapper(component_manager, *args, **kwargs): """ @@ -37,6 +38,7 @@ def check_communicating(func): return _wrapper + class ReferenceBaseComponentManager(BaseComponentManager): """ A component manager for Tango devices, supporting: @@ -52,7 +54,7 @@ class ReferenceBaseComponentManager(BaseComponentManager): The current implementation is intended to * illustrate the model - + * enable testing of these base classes It should not generally be used in concrete devices; instead, write diff --git a/src/ska_tango_base/capability_device.py b/src/ska_tango_base/capability_device.py index 9a2e1a0c3ae064a39696f414ae7fc4a55ed430c7..0654b20ad9987c6dd364f0a23a0d2a1895470d3d 100644 --- a/src/ska_tango_base/capability_device.py +++ b/src/ska_tango_base/capability_device.py @@ -16,6 +16,7 @@ from tango.server import run, attribute, command, device_property # SKA specific imports from ska_tango_base import SKAObsDevice from ska_tango_base.commands import ResponseCommand, ResultCode + # PROTECTED REGION END # // SKACapability.additionnal_imports __all__ = ["SKACapability", "main"] @@ -32,9 +33,8 @@ class SKACapability(SKAObsDevice): """ super().init_command_objects() self.register_command_object( - "ConfigureInstances", self.ConfigureInstancesCommand( - self, self.op_state_model, self.logger - ) + "ConfigureInstances", + self.ConfigureInstancesCommand(self, self.op_state_model, self.logger), ) class InitCommand(SKAObsDevice.InitCommand): @@ -66,15 +66,15 @@ class SKACapability(SKAObsDevice): # ----------------- CapType = device_property( - dtype='str', + dtype="str", ) CapID = device_property( - dtype='str', + dtype="str", ) subID = device_property( - dtype='str', + dtype="str", ) # ---------- @@ -82,7 +82,7 @@ class SKACapability(SKAObsDevice): # ---------- activationTime = attribute( - dtype='double', + dtype="double", unit="s", standard_unit="s", display_unit="s", @@ -91,13 +91,13 @@ class SKACapability(SKAObsDevice): """Device attribute.""" configuredInstances = attribute( - dtype='uint16', + dtype="uint16", doc="Number of instances of this Capability Type currently in use on this subarray.", ) """Device attribute.""" usedComponents = attribute( - dtype=('str',), + dtype=("str",), max_dim_x=100, doc="A list of components with no. of instances in use on this Capability.", ) @@ -175,9 +175,9 @@ class SKACapability(SKAObsDevice): return (ResultCode.OK, message) @command( - dtype_in='uint16', + dtype_in="uint16", doc_in="The number of instances to configure for this Capability.", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -203,6 +203,7 @@ class SKACapability(SKAObsDevice): # Run server # ---------- + def main(args=None, **kwargs): # PROTECTED REGION ID(SKACapability.main) ENABLED START # """Main function of the SKACapability module.""" @@ -210,5 +211,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // SKACapability.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/commands.py b/src/ska_tango_base/commands.py index 3d4834c6c87ef6dd4284b665c2a65afc5c6a3eef..ac28b9ec3a99b5dd07560fd2e8646bf7d3314a72 100644 --- a/src/ska_tango_base/commands.py +++ b/src/ska_tango_base/commands.py @@ -19,7 +19,7 @@ The following command classes are provided: * **ResponseCommand**: for commands that return a ``(ResultCode, message)`` tuple. - + * **CompletionCommand**: for commands that need to let their state machine know when they have completed; that is, long-running commands with transitional states, such as ``AssignResources()`` and @@ -156,9 +156,7 @@ class BaseCommand: else: returned = self.do(argin=argin) - self.logger.info( - f"Exiting command {self.name}" - ) + self.logger.info(f"Exiting command {self.name}") return returned def do(self, argin=None): @@ -250,8 +248,7 @@ class StateModelCommand(BaseCommand): try: return self.state_model.is_action_allowed( - self._invoked_action, - raise_if_disallowed=raise_if_disallowed + self._invoked_action, raise_if_disallowed=raise_if_disallowed ) except StateModelError as state_model_error: raise CommandError( @@ -268,7 +265,7 @@ class ObservationCommand(StateModelCommand): op_state_model, *args, logger=None, - **kwargs + **kwargs, ): """ A base class for commands that drive the device's observing @@ -327,7 +324,7 @@ class ObservationCommand(StateModelCommand): return False return super().is_allowed(raise_if_disallowed=raise_if_disallowed) - + class ResponseCommand(BaseCommand): """ @@ -341,7 +338,7 @@ class ResponseCommand(BaseCommand): ResultCode.STARTED: logging.INFO, ResultCode.QUEUED: logging.INFO, ResultCode.FAILED: logging.ERROR, - ResultCode.UNKNOWN: logging.WARNING + ResultCode.UNKNOWN: logging.WARNING, } def _call_do(self, argin=None): @@ -366,7 +363,7 @@ class ResponseCommand(BaseCommand): self.logger.log( self.RESULT_LOG_LEVEL.get(return_code, logging.ERROR), f"Exiting command {self.name} with return_code " - f"{return_code!s}, message: '{message}'." + f"{return_code!s}, message: '{message}'.", ) return (return_code, message) @@ -377,9 +374,7 @@ class CompletionCommand(StateModelCommand): the state model at command completion. """ - def __init__( - self, target, state_model, action_slug, *args, logger=None, **kwargs - ): + def __init__(self, target, state_model, action_slug, *args, logger=None, **kwargs): """ Create a new CompletionCommand for a device. @@ -404,7 +399,9 @@ class CompletionCommand(StateModelCommand): logger interface :param kwargs: additional keyword arguments """ - super().__init__(target, state_model, action_slug, *args, logger=logger, **kwargs) + super().__init__( + target, state_model, action_slug, *args, logger=logger, **kwargs + ) self._completed_hook = f"{action_slug}_completed" def __call__(self, argin=None): diff --git a/src/ska_tango_base/control_model.py b/src/ska_tango_base/control_model.py index 032909062ff423f8e607b70e96562556457b221c..16b6c60eac7dfaed6ac400b7e994e4217b33d5ba 100644 --- a/src/ska_tango_base/control_model.py +++ b/src/ska_tango_base/control_model.py @@ -326,6 +326,7 @@ class PowerMode(enum.IntEnum): Enumerated type for the power mode of components that rely upon a power supply, such as hardware. """ + UNKNOWN = 0 OFF = 1 STANDBY = 2 diff --git a/src/ska_tango_base/csp/__init__.py b/src/ska_tango_base/csp/__init__.py index ae357772a6b8fa25736b7c00ddfa3359a89af02a..d2fbc2fba3d565184182be7c395583ad9a018b73 100644 --- a/src/ska_tango_base/csp/__init__.py +++ b/src/ska_tango_base/csp/__init__.py @@ -25,5 +25,5 @@ from .obs import ( from .subarray import ( CspSubarrayComponentManager, ReferenceCspSubarrayComponentManager, - CspSubElementSubarray + CspSubElementSubarray, ) diff --git a/src/ska_tango_base/csp/master_device.py b/src/ska_tango_base/csp/master_device.py index c066c7da285a54c45dcefb655902d3a14e426d11..10bdd82599c0a5193aa568d258c53240668f88b9 100644 --- a/src/ska_tango_base/csp/master_device.py +++ b/src/ska_tango_base/csp/master_device.py @@ -14,6 +14,7 @@ Master device for SKA CSP Subelement. # PROTECTED REGION ID(CspSubElementMaster.additionnal_import) ENABLED START # # Python standard library from collections import defaultdict + # Tango imports import tango from tango import DebugIt, AttrWriteType @@ -25,6 +26,7 @@ from ska_tango_base import SKAMaster from ska_tango_base.commands import ResultCode, ResponseCommand, StateModelCommand from ska_tango_base.control_model import AdminMode from ska_tango_base.faults import CommandError + # PROTECTED REGION END # // CspSubElementMaster.additionnal_import __all__ = ["CspSubElementMaster", "main"] @@ -53,20 +55,16 @@ class CspSubElementMaster(SKAMaster): # Device Properties # ----------------- - PowerDelayStandbyOn = device_property( - dtype='DevFloat', default_value=2.0 - ) + PowerDelayStandbyOn = device_property(dtype="DevFloat", default_value=2.0) - PowerDelayStandbyOff = device_property( - dtype='DevFloat', default_value=1.5 - ) + PowerDelayStandbyOff = device_property(dtype="DevFloat", default_value=1.5) # ---------- # Attributes # ---------- powerDelayStandbyOn = attribute( - dtype='DevFloat', + dtype="DevFloat", access=AttrWriteType.READ_WRITE, label="powerDelayStandbyOn", unit="sec.", @@ -75,7 +73,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" powerDelayStandbyOff = attribute( - dtype='DevFloat', + dtype="DevFloat", access=AttrWriteType.READ_WRITE, label="powerDelayStandbyOff", unit="sec", @@ -84,7 +82,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" onProgress = attribute( - dtype='DevUShort', + dtype="DevUShort", label="onProgress", max_value=100, min_value=0, @@ -93,7 +91,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" onMaximumDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", access=AttrWriteType.READ_WRITE, label="onMaximumDuration", unit="sec.", @@ -102,7 +100,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" onMeasuredDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", label="onMeasuredDuration", unit="sec", doc="The measured time (sec) taken to execute the command.", @@ -110,7 +108,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" standbyProgress = attribute( - dtype='DevUShort', + dtype="DevUShort", label="standbyProgress", max_value=100, min_value=0, @@ -119,7 +117,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" standbyMaximumDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", access=AttrWriteType.READ_WRITE, label="standbyMaximumDuration", unit="sec.", @@ -128,7 +126,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" standbyMeasuredDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", label="standbyMeasuredDuration", unit="sec", doc="The measured time (sec) taken to execute the Standby command.", @@ -136,7 +134,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" offProgress = attribute( - dtype='DevUShort', + dtype="DevUShort", label="offProgress", max_value=100, min_value=0, @@ -145,7 +143,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" offMaximumDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", access=AttrWriteType.READ_WRITE, label="offMaximumDuration", unit="sec.", @@ -154,7 +152,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" offMeasuredDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", label="offMeasuredDuration", unit="sec", doc="The measured time (sec) taken to execute the Off command.", @@ -162,7 +160,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" totalOutputDataRateToSdp = attribute( - dtype='DevFloat', + dtype="DevFloat", label="totalOutputDataRateToSdp", unit="GB/s", doc="Report the total link expected output data rate.", @@ -170,7 +168,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" loadFirmwareProgress = attribute( - dtype='DevUShort', + dtype="DevUShort", label="loadFirmwareProgress", max_value=100, min_value=0, @@ -179,7 +177,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" loadFirmwareMaximumDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", access=AttrWriteType.READ_WRITE, label="loadFirmwareMaximumDuration", unit="sec", @@ -188,7 +186,7 @@ class CspSubElementMaster(SKAMaster): """Device attribute.""" loadFirmwareMeasuredDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", label="loadFirmwareMeasuredDuration", unit="sec", doc="The command execution measured duration (in sec).", @@ -208,7 +206,7 @@ class CspSubElementMaster(SKAMaster): "LoadFirmware", self.LoadFirmwareCommand( self, self.op_state_model, self.admin_mode_model, self.logger - ) + ), ) device_args = (self, self.op_state_model, self.logger) self.register_command_object( @@ -301,73 +299,73 @@ class CspSubElementMaster(SKAMaster): def read_onProgress(self): # PROTECTED REGION ID(CspSubElementMaster.onProgress_read) ENABLED START # """Return the onProgress attribute.""" - return self._cmd_progress['on'] + return self._cmd_progress["on"] # PROTECTED REGION END # // CspSubElementMaster.onProgress_read def read_onMaximumDuration(self): # PROTECTED REGION ID(CspSubElementMaster.onMaximumDuration_read) ENABLED START # """Return the onMaximumDuration attribute.""" - return self._cmd_maximum_duration['on'] + return self._cmd_maximum_duration["on"] # PROTECTED REGION END # // CspSubElementMaster.onMaximumDuration_read def write_onMaximumDuration(self, value): # PROTECTED REGION ID(CspSubElementMaster.onMaximumDuration_write) ENABLED START # """Set the onMaximumDuration attribute.""" - self._cmd_maximum_duration['on'] = value + self._cmd_maximum_duration["on"] = value # PROTECTED REGION END # // CspSubElementMaster.onMaximumDuration_write def read_onMeasuredDuration(self): # PROTECTED REGION ID(CspSubElementMaster.onMeasuredDuration_read) ENABLED START # """Return the onMeasuredDuration attribute.""" - return self._cmd_measured_duration['on'] + return self._cmd_measured_duration["on"] # PROTECTED REGION END # // CspSubElementMaster.onMeasuredDuration_read def read_standbyProgress(self): # PROTECTED REGION ID(CspSubElementMaster.standbyProgress_read) ENABLED START # """Return the standbyProgress attribute.""" - return self._cmd_progress['standby'] + return self._cmd_progress["standby"] # PROTECTED REGION END # // CspSubElementMaster.standbyProgress_read def read_standbyMaximumDuration(self): # PROTECTED REGION ID(CspSubElementMaster.standbyMaximumDuration_read) ENABLED START # """Return the standbyMaximumDuration attribute.""" - return self._cmd_maximum_duration['standby'] + return self._cmd_maximum_duration["standby"] # PROTECTED REGION END # // CspSubElementMaster.standbyMaximumDuration_read def write_standbyMaximumDuration(self, value): # PROTECTED REGION ID(CspSubElementMaster.standbyMaximumDuration_write) ENABLED START # """Set the standbyMaximumDuration attribute.""" - self._cmd_maximum_duration['standby'] = value + self._cmd_maximum_duration["standby"] = value # PROTECTED REGION END # // CspSubElementMaster.standbyMaximumDuration_write def read_standbyMeasuredDuration(self): # PROTECTED REGION ID(CspSubElementMaster.standbyMeasuredDuration_read) ENABLED START # """Return the standbyMeasuredDuration attribute.""" - return self._cmd_measured_duration['standby'] + return self._cmd_measured_duration["standby"] # PROTECTED REGION END # // CspSubElementMaster.standbyMeasuredDuration_read def read_offProgress(self): # PROTECTED REGION ID(CspSubElementMaster.offProgress_read) ENABLED START # """Return the offProgress attribute.""" - return self._cmd_progress['off'] + return self._cmd_progress["off"] # PROTECTED REGION END # // CspSubElementMaster.offProgress_read def read_offMaximumDuration(self): # PROTECTED REGION ID(CspSubElementMaster.offMaximumDuration_read) ENABLED START # """Return the offMaximumDuration attribute.""" - return self._cmd_maximum_duration['off'] + return self._cmd_maximum_duration["off"] # PROTECTED REGION END # // CspSubElementMaster.offMaximumDuration_read def write_offMaximumDuration(self, value): # PROTECTED REGION ID(CspSubElementMaster.offMaximumDuration_write) ENABLED START # """Set the offMaximumDuration attribute.""" - self._cmd_maximum_duration['off'] = value + self._cmd_maximum_duration["off"] = value # PROTECTED REGION END # // CspSubElementMaster.offMaximumDuration_write def read_offMeasuredDuration(self): # PROTECTED REGION ID(CspSubElementMaster.offMeasuredDuration_read) ENABLED START # """Return the offMeasuredDuration attribute.""" - return self._cmd_measured_duration['off'] + return self._cmd_measured_duration["off"] # PROTECTED REGION END # // CspSubElementMaster.offMeasuredDuration_read def read_totalOutputDataRateToSdp(self): @@ -391,25 +389,25 @@ class CspSubElementMaster(SKAMaster): def read_loadFirmwareProgress(self): # PROTECTED REGION ID(CspSubElementMaster.loadFirmwareProgress_read) ENABLED START # """Return the loadFirmwareProgress attribute.""" - return self._cmd_progress['loadfirmware'] + return self._cmd_progress["loadfirmware"] # PROTECTED REGION END # // CspSubElementMaster.loadFirmwareProgress_read def read_loadFirmwareMaximumDuration(self): # PROTECTED REGION ID(CspSubElementMaster.loadFirmwareMaximumDuration_read) ENABLED START # """Return the loadFirmwareMaximumDuration attribute.""" - return self._cmd_maximum_duration['loadfirmware'] + return self._cmd_maximum_duration["loadfirmware"] # PROTECTED REGION END # // CspSubElementMaster.loadFirmwareMaximumDuration_read def write_loadFirmwareMaximumDuration(self, value): # PROTECTED REGION ID(CspSubElementMaster.loadFirmwareMaximumDuration_write) ENABLED START # """Set the loadFirmwareMaximumDuration attribute.""" - self._cmd_maximum_duration['loadfirmware'] = value + self._cmd_maximum_duration["loadfirmware"] = value # PROTECTED REGION END # // CspSubElementMaster.loadFirmwareMaximumDuration_write def read_loadFirmwareMeasuredDuration(self): # PROTECTED REGION ID(CspSubElementMaster.loadFirmwareMeasuredDuration_read) ENABLED START # """Return the loadFirmwareMeasuredDuration attribute.""" - return self._cmd_measured_duration['loadfirmware'] + return self._cmd_measured_duration["loadfirmware"] # PROTECTED REGION END # // CspSubElementMaster.loadFirmwareMeasuredDuration_read # -------- @@ -419,7 +417,10 @@ class CspSubElementMaster(SKAMaster): """ A class for the LoadFirmware command. """ - def __init__(self, target, op_state_model, admin_mode_model, *args, logger=None, **kwargs): + + def __init__( + self, target, op_state_model, admin_mode_model, *args, logger=None, **kwargs + ): """ Creates a new BaseCommand object for a device. @@ -440,7 +441,9 @@ class CspSubElementMaster(SKAMaster): logger interface """ self._admin_mode_model = admin_mode_model - super().__init__(target, op_state_model, None, *args, logger=logger, **kwargs) + super().__init__( + target, op_state_model, None, *args, logger=logger, **kwargs + ) def do(self, argin): """ @@ -470,8 +473,10 @@ class CspSubElementMaster(SKAMaster): :return: ``True`` if the command is allowed. :rtype: boolean """ - allowed = (self.state_model.op_state == tango.DevState.OFF and - self._admin_mode_model.admin_mode == AdminMode.MAINTENANCE) + allowed = ( + self.state_model.op_state == tango.DevState.OFF + and self._admin_mode_model.admin_mode == AdminMode.MAINTENANCE + ) if allowed: return True if raise_if_disallowed: @@ -487,7 +492,9 @@ class CspSubElementMaster(SKAMaster): """ def __init__(self, target, op_state_model, *args, logger=None, **kwargs): - super().__init__(target, op_state_model, None, *args, logger=logger, **kwargs) + super().__init__( + target, op_state_model, None, *args, logger=logger, **kwargs + ) def do(self, argin): """ @@ -530,7 +537,9 @@ class CspSubElementMaster(SKAMaster): """ def __init__(self, target, op_state_model, *args, logger=None, **kwargs): - super().__init__(target, op_state_model, None, *args, logger=logger, **kwargs) + super().__init__( + target, op_state_model, None, *args, logger=logger, **kwargs + ) def do(self, argin): """ @@ -573,7 +582,9 @@ class CspSubElementMaster(SKAMaster): """ def __init__(self, target, op_state_model, *args, logger=None, **kwargs): - super().__init__(target, op_state_model, None, *args, logger=logger, **kwargs) + super().__init__( + target, op_state_model, None, *args, logger=logger, **kwargs + ) def do(self, argin): """ @@ -622,11 +633,11 @@ class CspSubElementMaster(SKAMaster): return command.is_allowed(True) @command( - dtype_in='DevVarStringArray', + dtype_in="DevVarStringArray", doc_in="The file name or a pointer to the filename , " - "the list of components that use software or firmware package (file)," - "checksum or signing", - dtype_out='DevVarLongStringArray', + "the list of components that use software or firmware package (file)," + "checksum or signing", + dtype_out="DevVarLongStringArray", ) @DebugIt() def LoadFirmware(self, argin): @@ -665,9 +676,9 @@ class CspSubElementMaster(SKAMaster): return command.is_allowed(True) @command( - dtype_in='DevVarStringArray', + dtype_in="DevVarStringArray", doc_in="The list of FQDNs to power-up", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="ReturnType, `informational message`", ) @DebugIt() @@ -701,9 +712,9 @@ class CspSubElementMaster(SKAMaster): return command.is_allowed(True) @command( - dtype_in='DevVarStringArray', + dtype_in="DevVarStringArray", doc_in="List of FQDNs to power-off", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="ReturnType, `informational message`", ) @DebugIt() @@ -738,9 +749,9 @@ class CspSubElementMaster(SKAMaster): return command.is_allowed(True) @command( - dtype_in='DevVarStringArray', + dtype_in="DevVarStringArray", doc_in="List of devices to re-initialize", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="ReturnType, `informational message`", ) @DebugIt() @@ -769,6 +780,7 @@ class CspSubElementMaster(SKAMaster): return [[return_code], [message]] # PROTECTED REGION END # // CspSubElementMaster.ReInitDevices + # ---------- # Run server # ---------- @@ -788,5 +800,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // CspSubElementMaster.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/csp/obs/__init__.py b/src/ska_tango_base/csp/obs/__init__.py index fbb20c6ca506e010518c50e66aed085c8738855c..5f4d95d65164a6d5bf44cd56c335d8368f7e97a3 100644 --- a/src/ska_tango_base/csp/obs/__init__.py +++ b/src/ska_tango_base/csp/obs/__init__.py @@ -17,4 +17,3 @@ from .component_manager import CspObsComponentManager from .reference_component_manager import ReferenceCspObsComponentManager from .obs_device import CspSubElementObsDevice - diff --git a/src/ska_tango_base/csp/obs/component_manager.py b/src/ska_tango_base/csp/obs/component_manager.py index d22598acdeb82f9094dbdc41d08d813f910620b5..448d51f36c326fb5669e1e7417d6a4fa3da615cf 100644 --- a/src/ska_tango_base/csp/obs/component_manager.py +++ b/src/ska_tango_base/csp/obs/component_manager.py @@ -3,6 +3,7 @@ This module models component management for CSP subelement observation devices. """ from ska_tango_base.base import BaseComponentManager + class CspObsComponentManager(BaseComponentManager): """ A component manager for SKA CSP subelement observation Tango devices: diff --git a/src/ska_tango_base/csp/obs/obs_device.py b/src/ska_tango_base/csp/obs/obs_device.py index 060ecebe1c233b8cc1c6c69ecda4d8309c30ed5f..a4d9bf49cf7f4f0964d3f4b4ba2a629bb943a73f 100644 --- a/src/ska_tango_base/csp/obs/obs_device.py +++ b/src/ska_tango_base/csp/obs/obs_device.py @@ -42,6 +42,7 @@ class CspSubElementObsDevice(SKAObsDevice): - Identification number of the observing device. - Type:'DevUShort' """ + # PROTECTED REGION ID(CspSubElementObsDevice.class_variable) ENABLED START # # PROTECTED REGION END # // CspSubElementObsDevice.class_variable @@ -49,61 +50,59 @@ class CspSubElementObsDevice(SKAObsDevice): # Device Properties # ----------------- - DeviceID = device_property( - dtype='DevUShort', default_value=1 - ) + DeviceID = device_property(dtype="DevUShort", default_value=1) # ---------- # Attributes # ---------- scanID = attribute( - dtype='DevULong64', + dtype="DevULong64", label="scanID", doc="The scan identification number to be inserted in the output\nproducts.", ) """Device attribute.""" configurationID = attribute( - dtype='DevString', + dtype="DevString", label="configurationID", doc="The configuration ID specified into the JSON configuration.", ) """Device attribute.""" deviceID = attribute( - dtype='DevUShort', + dtype="DevUShort", label="deviceID", doc="The observing device ID.", ) """Device attribute.""" lastScanConfiguration = attribute( - dtype='DevString', + dtype="DevString", label="lastScanConfiguration", doc="The last valid scan configuration.", ) """Device attribute.""" sdpDestinationAddresses = attribute( - dtype='DevString', + dtype="DevString", label="sdpDestinationAddresses", doc="JSON formatted string\nReport the list of all the SDP addresses provided by SDP" - " to receive the output products.\nSpecifies the Mac, IP, Port for each resource:\nCBF:" - " visibility channels\nPSS ? Pss pipelines\nPST ? PSTBeam\nNot used by al CSP Sub-element" - " observing device (for ex. Mid CBF VCCs)", + " to receive the output products.\nSpecifies the Mac, IP, Port for each resource:\nCBF:" + " visibility channels\nPSS ? Pss pipelines\nPST ? PSTBeam\nNot used by al CSP Sub-element" + " observing device (for ex. Mid CBF VCCs)", ) """Device attribute.""" sdpLinkCapacity = attribute( - dtype='DevFloat', + dtype="DevFloat", label="sdpLinkCapacity", doc="The SDP link capavity in GB/s.", ) """Device attribute.""" sdpLinkActive = attribute( - dtype=('DevBoolean',), + dtype=("DevBoolean",), max_dim_x=100, label="sdpLinkActive", doc="Flag reporting if the SDP link is active.\nTrue: active\nFalse:down", @@ -111,7 +110,7 @@ class CspSubElementObsDevice(SKAObsDevice): """Device attribute.""" healthFailureMessage = attribute( - dtype='DevString', + dtype="DevString", label="healthFailureMessage", doc="Message providing info about device health failure.", ) @@ -155,7 +154,7 @@ class CspSubElementObsDevice(SKAObsDevice): self.op_state_model, self.obs_state_model, self.logger, - ) + ), ) class InitCommand(SKAObsDevice.InitCommand): @@ -177,15 +176,21 @@ class CspSubElementObsDevice(SKAObsDevice): device = self.target device._obs_state = ObsState.IDLE - device._sdp_addresses = {"outputHost": [], "outputMac": [], "outputPort": []} + device._sdp_addresses = { + "outputHost": [], + "outputMac": [], + "outputPort": [], + } # a sub-element obsdevice can have more than one link to the SDP # (for ex. Mid.CBF FSP) - device._sdp_links_active = [False, ] - device._sdp_links_capacity = 0. + device._sdp_links_active = [ + False, + ] + device._sdp_links_capacity = 0.0 # JSON string, deliberately left in Tango layer - device._last_scan_configuration = '' - device._health_failure_msg = '' + device._last_scan_configuration = "" + device._health_failure_msg = "" message = "CspSubElementObsDevice Init command completed OK" device.logger.info(message) @@ -205,6 +210,7 @@ class CspSubElementObsDevice(SKAObsDevice): """ # PROTECTED REGION ID(CspSubElementObsDevice.delete_device) ENABLED START # # PROTECTED REGION END # // CspSubElementObsDevice.delete_device + # ------------------ # Attributes methods # ------------------ @@ -212,13 +218,13 @@ class CspSubElementObsDevice(SKAObsDevice): def read_scanID(self): # PROTECTED REGION ID(CspSubElementObsDevice.scanID_read) ENABLED START # """Return the scanID attribute.""" - return self.component_manager.scan_id #pylint: disable=no-member + return self.component_manager.scan_id # PROTECTED REGION END # // CspSubElementObsDevice.scanID_read def read_configurationID(self): # PROTECTED REGION ID(CspSubElementObsDevice.configurationID_read) ENABLED START # """Return the configurationID attribute.""" - return self.component_manager.config_id #pylint: disable=no-member + return self.component_manager.config_id # PROTECTED REGION END # // CspSubElementObsDevice.configurationID_read def read_deviceID(self): @@ -325,7 +331,11 @@ class CspSubElementObsDevice(SKAObsDevice): msg = f"Validate configuration failed with unknown error: {other_errs}" return (None, ResultCode.FAILED, msg) - return (configuration_dict, ResultCode.OK, "ConfigureScan arguments validation successful") + return ( + configuration_dict, + ResultCode.OK, + "ConfigureScan arguments validation successful", + ) class ScanCommand(ObservationCommand, ResponseCommand): """ @@ -372,7 +382,7 @@ class CspSubElementObsDevice(SKAObsDevice): if result_code == ResultCode.OK: component_manager.scan(int(argin)) return (ResultCode.STARTED, "Scan command started") - return(result_code, msg) + return (result_code, msg) def validate_input(self, argin): """ @@ -554,11 +564,11 @@ class CspSubElementObsDevice(SKAObsDevice): return (ResultCode.OK, "Abort command completed OK") @command( - dtype_in='DevString', + dtype_in="DevString", doc_in="JSON formatted string with the scan configuration.", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status. " - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def ConfigureScan(self, argin): @@ -585,11 +595,11 @@ class CspSubElementObsDevice(SKAObsDevice): # PROTECTED REGION END # // CspSubElementObsDevice.ConfigureScan @command( - dtype_in='DevString', + dtype_in="DevString", doc_in="A string with the scan ID", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def Scan(self, argin): @@ -610,9 +620,9 @@ class CspSubElementObsDevice(SKAObsDevice): # PROTECTED REGION END # // CspSubElementObsDevice.Scan @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def EndScan(self): @@ -630,9 +640,9 @@ class CspSubElementObsDevice(SKAObsDevice): # PROTECTED REGION END # // CspSubElementObsDevice.EndScan @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def GoToIdle(self): @@ -644,7 +654,7 @@ class CspSubElementObsDevice(SKAObsDevice): The message is for information purpose only. :rtype: (ResultCode, str) """ - self._last_scan_configuration = '' + self._last_scan_configuration = "" command = self.get_command_object("GoToIdle") (return_code, message) = command() @@ -652,9 +662,9 @@ class CspSubElementObsDevice(SKAObsDevice): # PROTECTED REGION END # // CspSubElementObsDevice.GoToIdle @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def ObsReset(self): @@ -672,9 +682,9 @@ class CspSubElementObsDevice(SKAObsDevice): # PROTECTED REGION END # // CspSubElementObsDevice.ObsReset @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def Abort(self): @@ -692,6 +702,7 @@ class CspSubElementObsDevice(SKAObsDevice): return [[return_code], [message]] # PROTECTED REGION END # // CspSubElementObsDevice.Abort + # ---------- # Run server # ---------- @@ -704,5 +715,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // CspSubElementObsDevice.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/csp/obs/obs_state_model.py b/src/ska_tango_base/csp/obs/obs_state_model.py index 93fdcd19528a892446aa23fdccdb377135e25fcb..b9a8bb478655ff175cfdff0caa45a218c1839274 100644 --- a/src/ska_tango_base/csp/obs/obs_state_model.py +++ b/src/ska_tango_base/csp/obs/obs_state_model.py @@ -8,7 +8,7 @@ comprises: * a :py:class:`.CspSubElementObsStateModel` that maps the underlying state machine state to a value of the :py:class:`ska_tango_base.control_model.ObsState` enum. - + """ from transitions.extensions import LockedMachine as Machine @@ -270,7 +270,7 @@ class CspSubElementObsStateModel(ObsStateModel): * **CONFIGURING**: transitional state to report device configuration is in progress. - + TODO: Need to understand if this state is really required by the observing devices of any CSP sub-element. diff --git a/src/ska_tango_base/csp/obs/reference_component_manager.py b/src/ska_tango_base/csp/obs/reference_component_manager.py index 4210f632537a745f78f5ff6872b36abfa5997e40..220176d1cc354862c6f2e962948fd9f83621b743 100644 --- a/src/ska_tango_base/csp/obs/reference_component_manager.py +++ b/src/ska_tango_base/csp/obs/reference_component_manager.py @@ -3,8 +3,6 @@ This module models component management for CSP subelement observation devices. """ import functools -from tango import DevState - from ska_tango_base.csp.obs import CspObsComponentManager from ska_tango_base.base import check_communicating, ReferenceBaseComponentManager @@ -21,6 +19,7 @@ def check_on(func): :return: the wrapped function """ + @functools.wraps(func) def _wrapper(component, *args, **kwargs): """ @@ -42,7 +41,9 @@ def check_on(func): return _wrapper -class ReferenceCspObsComponentManager(CspObsComponentManager, ReferenceBaseComponentManager): +class ReferenceCspObsComponentManager( + CspObsComponentManager, ReferenceBaseComponentManager +): """ A component manager for SKA CSP subelement observation Tango devices: @@ -77,14 +78,14 @@ class ReferenceCspObsComponentManager(CspObsComponentManager, ReferenceBaseCompo _faulty=False, ): """ - Initialise a new instance - State Machine<State_Machine> + Initialise a new instance + State Machine<State_Machine> - :param _power_mode: initial power mode of this component - (for testing only) - :param _faulty: whether this component should initially - simulate a fault (for testing only) + :param _power_mode: initial power mode of this component + (for testing only) + :param _faulty: whether this component should initially + simulate a fault (for testing only) """ self._configured = False self._configured_callback = None diff --git a/src/ska_tango_base/csp/subarray/reference_component_manager.py b/src/ska_tango_base/csp/subarray/reference_component_manager.py index e2d9b4815eae005889793b12ebed331c76e9a77c..3f8c7eab0885fff8323e58e607326ca8760ae1e2 100644 --- a/src/ska_tango_base/csp/subarray/reference_component_manager.py +++ b/src/ska_tango_base/csp/subarray/reference_component_manager.py @@ -19,6 +19,7 @@ def check_on(func): :return: the wrapped function """ + @functools.wraps(func) def _wrapper(component, *args, **kwargs): """ @@ -131,8 +132,7 @@ class ReferenceCspSubarrayComponentManager( obs_state_model, capability_types, logger, - _component=_component - or self._Component(capability_types), + _component=_component or self._Component(capability_types), ) @property diff --git a/src/ska_tango_base/csp/subarray/subarray_device.py b/src/ska_tango_base/csp/subarray/subarray_device.py index d1a6810a342405e2b0ea0f392ad46f624162b221..94cbadc288d85b50b3e122d09ccf2e60b0cccc24 100644 --- a/src/ska_tango_base/csp/subarray/subarray_device.py +++ b/src/ska_tango_base/csp/subarray/subarray_device.py @@ -15,6 +15,7 @@ Subarray device for SKA CSP SubElement import json from json.decoder import JSONDecodeError from collections import defaultdict + # Tango imports from tango import DebugIt from tango.server import run @@ -23,8 +24,14 @@ from tango import AttrWriteType # SKA import from ska_tango_base import SKASubarray -from ska_tango_base.commands import CompletionCommand, ObservationCommand, ResponseCommand, ResultCode +from ska_tango_base.commands import ( + CompletionCommand, + ObservationCommand, + ResponseCommand, + ResultCode, +) from ska_tango_base.csp.subarray import CspSubarrayComponentManager + # Additional import # PROTECTED REGION END # // CspSubElementSubarray.additionnal_import @@ -35,6 +42,7 @@ class CspSubElementSubarray(SKASubarray): """ Subarray device for SKA CSP SubElement """ + # PROTECTED REGION ID(CspSubElementSubarray.class_variable) ENABLED START # # PROTECTED REGION END # // CspSubElementSubarray.class_variable @@ -47,29 +55,31 @@ class CspSubElementSubarray(SKASubarray): # ---------- scanID = attribute( - dtype='DevULong64', + dtype="DevULong64", label="scanID", doc="The scan identification number to be inserted in the output products.", ) """Device attribute.""" configurationID = attribute( - dtype='DevString', + dtype="DevString", label="configurationID", doc="The configuration ID specified into the JSON configuration.", ) """Device attribute.""" sdpDestinationAddresses = attribute( - dtype='DevString', + dtype="DevString", access=AttrWriteType.READ_WRITE, label="sdpDestinationAddresses", - doc="JSON formatted string.\nReport the list of all the SDP addresses provided by SDP to receive the output products.\nSpecifies the Mac, IP, Port for each resource:CBF visibility channels, Pss pipelines, PSTBeam", + doc="JSON formatted string.\nReport the list of all the SDP addresses provided " + "by SDP to receive the output products.\nSpecifies the Mac, IP, Port for each " + "resource:CBF visibility channels, Pss pipelines, PSTBeam", ) """Device attribute.""" outputDataRateToSdp = attribute( - dtype='DevFloat', + dtype="DevFloat", label="outputDataRateToSdp", unit="GB/s", doc="The output data rate (GB/s) on the link for each scan.", @@ -77,14 +87,14 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" lastScanConfiguration = attribute( - dtype='DevString', + dtype="DevString", label="lastScanConfiguration", doc="The last valid scan configuration.", ) """Device attribute.""" sdpLinkActive = attribute( - dtype=('DevBoolean',), + dtype=("DevBoolean",), max_dim_x=100, label="sdpLinkActive", doc="Flag reporting if the SDP links are active.", @@ -92,14 +102,16 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" listOfDevicesCompletedTasks = attribute( - dtype='DevString', + dtype="DevString", label="listOfDevicesCompletedTasks", - doc="JSON formatted string reporting for each task/command the list of devices\nthat completed successfully the task.\nEx.\n{``cmd1``: [``device1``, ``device2``], ``cmd2``: [``device2``, ``device3``]}", + doc="JSON formatted string reporting for each task/command the list of devices" + "\nthat completed successfully the task.\nEx.\n{``cmd1``: [``device1``, " + "``device2``], ``cmd2``: [``device2``, ``device3``]}", ) """Device attribute.""" configureScanMeasuredDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", label="configureScanMeasuredDuration", unit="sec", doc="The measured time (sec) taken to execute the command", @@ -107,14 +119,14 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" configureScanTimeoutExpiredFlag = attribute( - dtype='DevBoolean', + dtype="DevBoolean", label="configureScanTimeoutExpiredFlag", doc="Flag reporting ConfigureScan command timeout expiration.", ) """Device attribute.""" assignResourcesMaximumDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", access=AttrWriteType.READ_WRITE, label="assignResourcesMaximumDuration", unit="sec", @@ -123,7 +135,7 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" assignResourcesMeasuredDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", label="assignResourcesMeasuredDuration", unit="sec", doc="The measured command execution duration.", @@ -131,7 +143,7 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" assignResourcesProgress = attribute( - dtype='DevUShort', + dtype="DevUShort", label="assignResourcesProgress", max_value=100, min_value=0, @@ -140,14 +152,14 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" assignResourcesTimeoutExpiredFlag = attribute( - dtype='DevBoolean', + dtype="DevBoolean", label="assignResourcesTimeoutExpiredFlag", doc="Flag reporting AssignResources command timeout expiration.", ) """Device attribute.""" releaseResourcesMaximumDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", access=AttrWriteType.READ_WRITE, label="releaseResourcesMaximumDuration", unit="sec", @@ -156,7 +168,7 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" releaseResourcesMeasuredDuration = attribute( - dtype='DevFloat', + dtype="DevFloat", label="releaseResourcesMeasuredDuration", unit="sec", doc="The measured command execution duration.", @@ -164,7 +176,7 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" releaseResourcesProgress = attribute( - dtype='DevUShort', + dtype="DevUShort", label="releaseResourcesProgress", max_value=100, min_value=0, @@ -173,7 +185,7 @@ class CspSubElementSubarray(SKASubarray): """Device attribute.""" releaseResourcesTimeoutExpiredFlag = attribute( - dtype='DevBoolean', + dtype="DevBoolean", label="timeoutExpiredFlag", doc="Flag reporting command timeout expiration.", ) @@ -192,13 +204,16 @@ class CspSubElementSubarray(SKASubarray): """ super().init_command_objects() - device_args = (self.component_manager, self.op_state_model, self.obs_state_model, self.logger) - self.register_command_object( - "ConfigureScan", self.ConfigureScanCommand(*device_args) + device_args = ( + self.component_manager, + self.op_state_model, + self.obs_state_model, + self.logger, ) self.register_command_object( - "GoToIdle", self.GoToIdleCommand(*device_args) + "ConfigureScan", self.ConfigureScanCommand(*device_args) ) + self.register_command_object("GoToIdle", self.GoToIdleCommand(*device_args)) class InitCommand(SKASubarray.InitCommand): """ @@ -219,14 +234,20 @@ class CspSubElementSubarray(SKASubarray): device = self.target device._scan_id = 0 - device._sdp_addresses = {"outputHost": [], "outputMac": [], "outputPort": []} - device._sdp_links_active = [False, ] - device._sdp_output_data_rate = 0. + device._sdp_addresses = { + "outputHost": [], + "outputMac": [], + "outputPort": [], + } + device._sdp_links_active = [ + False, + ] + device._sdp_output_data_rate = 0.0 - device._config_id = '' + device._config_id = "" # JSON string, deliberately left in Tango layer - device._last_scan_configuration = '' + device._last_scan_configuration = "" # _list_of_devices_completed_task: for each task/command reports # the list of the devices that successfully completed the task. @@ -259,12 +280,12 @@ class CspSubElementSubarray(SKASubarray): # values: True/False device._timeout_expired = defaultdict(bool) # configure the flags to push event from the device server - device.set_change_event('configureScanTimeoutExpiredFlag', True, True) - device.set_archive_event('configureScanTimeoutExpiredFlag', True, True) - device.set_change_event('assignResourcesTimeoutExpiredFlag', True, True) - device.set_archive_event('assignResourcesTimeoutExpiredFlag', True, True) - device.set_change_event('releaseResourcesTimeoutExpiredFlag', True, True) - device.set_archive_event('releaseResourcesTimeoutExpiredFlag', True, True) + device.set_change_event("configureScanTimeoutExpiredFlag", True, True) + device.set_archive_event("configureScanTimeoutExpiredFlag", True, True) + device.set_change_event("assignResourcesTimeoutExpiredFlag", True, True) + device.set_archive_event("assignResourcesTimeoutExpiredFlag", True, True) + device.set_change_event("releaseResourcesTimeoutExpiredFlag", True, True) + device.set_archive_event("releaseResourcesTimeoutExpiredFlag", True, True) message = "CspSubElementSubarray Init command completed OK" device.logger.info(message) @@ -292,13 +313,13 @@ class CspSubElementSubarray(SKASubarray): def read_scanID(self): # PROTECTED REGION ID(CspSubElementSubarray.scanID_read) ENABLED START # """Return the scanID attribute.""" - return self.component_manager.scan_id #pylint: disable=no-member + return self.component_manager.scan_id # PROTECTED REGION END # // CspSubElementSubarray.scanID_read def read_configurationID(self): # PROTECTED REGION ID(CspSubElementSubarray.configurationID_read) ENABLED START # """Return the configurationID attribute.""" - return self.component_manager.config_id #pylint: disable=no-member + return self.component_manager.config_id # PROTECTED REGION END # // CspSubElementSubarray.configurationID_read def read_sdpDestinationAddresses(self): @@ -328,13 +349,13 @@ class CspSubElementSubarray(SKASubarray): def read_configureScanMeasuredDuration(self): # PROTECTED REGION ID(CspSubElementSubarray.configureScanMeasuredDuration_read) ENABLED START # """Return the configureScanMeasuredDuration attribute.""" - return self._cmd_measured_duration['configurescan'] + return self._cmd_measured_duration["configurescan"] # PROTECTED REGION END # // CspSubElementSubarray.configureScanMeasuredDuration_read def read_configureScanTimeoutExpiredFlag(self): # PROTECTED REGION ID(CspSubElementSubarray.configureScanTimeoutExpiredFlag_read) ENABLED START # """Return the configureScanTimeoutExpiredFlag attribute.""" - return self._timeout_expired['configurescan'] + return self._timeout_expired["configurescan"] # PROTECTED REGION END # // CspSubElementSubarray.configureScanTimeoutExpiredFlag_read def read_listOfDevicesCompletedTasks(self): @@ -347,61 +368,61 @@ class CspSubElementSubarray(SKASubarray): def read_assignResourcesMaximumDuration(self): # PROTECTED REGION ID(CspSubElementSubarray.assignResourcesMaximumDuration_read) ENABLED START # """Return the assignResourcesMaximumDuration attribute.""" - return self._cmd_maximum_duration['assignresources'] + return self._cmd_maximum_duration["assignresources"] # PROTECTED REGION END # // CspSubElementSubarray.assignResourcesMaximumDuration_read def write_assignResourcesMaximumDuration(self, value): # PROTECTED REGION ID(CspSubElementSubarray.assignResourcesMaximumDuration_write) ENABLED START # """Set the assignResourcesMaximumDuration attribute.""" - self._cmd_maximum_duration['assignresources'] = value + self._cmd_maximum_duration["assignresources"] = value # PROTECTED REGION END # // CspSubElementSubarray.assignResourcesMaximumDuration_write def read_assignResourcesMeasuredDuration(self): # PROTECTED REGION ID(CspSubElementSubarray.assignResourcesMeasuredDuration_read) ENABLED START # """Return the assignResourcesMeasuredDuration attribute.""" - return self._cmd_measured_duration['assignresources'] + return self._cmd_measured_duration["assignresources"] # PROTECTED REGION END # // CspSubElementSubarray.assignResourcesMeasuredDuration_read def read_assignResourcesProgress(self): # PROTECTED REGION ID(CspSubElementSubarray.assignResourcesProgress_read) ENABLED START # """Return the assignResourcesProgress attribute.""" - return self._cmd_progress['assignresources'] + return self._cmd_progress["assignresources"] # PROTECTED REGION END # // CspSubElementSubarray.assignResourcesProgress_read def read_assignResourcesTimeoutExpiredFlag(self): # PROTECTED REGION ID(CspSubElementSubarray.assignResourcesTimeoutExpiredFlag_read) ENABLED START # """Return the assignResourcesTimeoutExpiredFlag attribute.""" - return self._timeout_expired['assignresources'] + return self._timeout_expired["assignresources"] # PROTECTED REGION END # // CspSubElementSubarray.assignResourcesTimeoutExpiredFlag_read def read_releaseResourcesMaximumDuration(self): # PROTECTED REGION ID(CspSubElementSubarray.releaseResourcesMaximumDuration_read) ENABLED START # """Return the releaseResourcesMaximumDuration attribute.""" - return self._cmd_maximum_duration['releaseresources'] + return self._cmd_maximum_duration["releaseresources"] # PROTECTED REGION END # // CspSubElementSubarray.releaseResourcesMaximumDuration_read def write_releaseResourcesMaximumDuration(self, value): # PROTECTED REGION ID(CspSubElementSubarray.releaseResourcesMaximumDuration_write) ENABLED START # """Set the releaseResourcesMaximumDuration attribute.""" - self._cmd_maximum_duration['releaseresources'] = value + self._cmd_maximum_duration["releaseresources"] = value # PROTECTED REGION END # // CspSubElementSubarray.releaseResourcesMaximumDuration_write def read_releaseResourcesMeasuredDuration(self): # PROTECTED REGION ID(CspSubElementSubarray.releaseResourcesMeasuredDuration_read) ENABLED START # """Return the releaseResourcesMeasuredDuration attribute.""" - return self._cmd_measured_duration['releaseresources'] + return self._cmd_measured_duration["releaseresources"] # PROTECTED REGION END # // CspSubElementSubarray.releaseResourcesMeasuredDuration_read def read_releaseResourcesProgress(self): # PROTECTED REGION ID(CspSubElementSubarray.releaseResourcesProgress_read) ENABLED START # """Return the releaseResourcesProgress attribute.""" - return self._cmd_progress['releaseresources'] + return self._cmd_progress["releaseresources"] # PROTECTED REGION END # // CspSubElementSubarray.releaseResourcesProgress_read def read_releaseResourcesTimeoutExpiredFlag(self): # PROTECTED REGION ID(CspSubElementSubarray.releaseResourcesTimeoutExpiredFlag_read) ENABLED START # """Return the releaseResourcesTimeoutExpiredFlag attribute.""" - return self._timeout_expired['releaseresources'] + return self._timeout_expired["releaseresources"] # PROTECTED REGION END # // CspSubElementSubarray.releaseResourcesTimeoutExpiredFlag_read def read_sdpLinkActive(self): @@ -478,7 +499,11 @@ class CspSubElementSubarray(SKASubarray): self.logger.error(msg) return (None, ResultCode.FAILED, msg) - return (configuration_dict, ResultCode.OK, "ConfigureScan arguments validation successful") + return ( + configuration_dict, + ResultCode.OK, + "ConfigureScan arguments validation successful", + ) class GoToIdleCommand(ObservationCommand, ResponseCommand): """ @@ -522,11 +547,11 @@ class CspSubElementSubarray(SKASubarray): return (ResultCode.OK, "GoToIdle command completed OK") @command( - dtype_in='DevString', + dtype_in="DevString", doc_in="A Json-encoded string with the scan configuration.", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def ConfigureScan(self, argin): @@ -554,11 +579,11 @@ class CspSubElementSubarray(SKASubarray): # PROTECTED REGION END # // CspSubElementSubarray.Configure @command( - dtype_in='DevString', + dtype_in="DevString", doc_in="A Json-encoded string with the scan configuration.", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def Configure(self, argin): @@ -577,9 +602,9 @@ class CspSubElementSubarray(SKASubarray): # PROTECTED REGION END # // CspSubElementSubarray.Configure @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def GoToIdle(self): @@ -591,16 +616,16 @@ class CspSubElementSubarray(SKASubarray): A tuple containing a return code and a string message indicating status. The message is for information purpose only. """ - self._last_scan_configuration = '' + self._last_scan_configuration = "" command = self.get_command_object("GoToIdle") (return_code, message) = command() return [[return_code], [message]] @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="A tuple containing a return code and a string message indicating status." - "The message is for information purpose only.", + "The message is for information purpose only.", ) @DebugIt() def End(self): @@ -616,6 +641,7 @@ class CspSubElementSubarray(SKASubarray): return self.GoToIdle() # PROTECTED REGION END # // CspSubElementSubarray.End + # ---------- # Run server # ---------- @@ -628,5 +654,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // CspSubElementSubarray.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/faults.py b/src/ska_tango_base/faults.py index 516a561a1732965c059c2b169a13e7ea25104b34..7215ee63f543aee1218e0ebc7e7a13463df3546b 100644 --- a/src/ska_tango_base/faults.py +++ b/src/ska_tango_base/faults.py @@ -32,8 +32,10 @@ class CommandError(RuntimeError): class CapabilityValidationError(ValueError): """Error in validating capability input against capability types.""" + class ComponentError(Exception): """Component cannot perform as requested.""" + class ComponentFault(ComponentError): """Component is in FAULT state and cannot perform as requested.""" diff --git a/src/ska_tango_base/logger_device.py b/src/ska_tango_base/logger_device.py index 5c2bc5f26a657762c5931c19311ff267c785eda9..8930377fc5e07c5e40d5481f061a848dea08184f 100644 --- a/src/ska_tango_base/logger_device.py +++ b/src/ska_tango_base/logger_device.py @@ -19,6 +19,7 @@ from tango.server import run, command from ska_tango_base import SKABaseDevice from ska_tango_base.commands import ResponseCommand, ResultCode from ska_tango_base.control_model import LoggingLevel + # PROTECTED REGION END # // SKALogger.additionnal_import __all__ = ["SKALogger", "main"] @@ -28,6 +29,7 @@ class SKALogger(SKABaseDevice): """ A generic base device for Logging for SKA. """ + # PROTECTED REGION ID(SKALogger.class_variable) ENABLED START # # PROTECTED REGION END # // SKALogger.class_variable @@ -49,7 +51,7 @@ class SKALogger(SKABaseDevice): super().init_command_objects() self.register_command_object( "SetLoggingLevel", - self.SetLoggingLevelCommand(self, self.op_state_model, self.logger) + self.SetLoggingLevelCommand(self, self.op_state_model, self.logger), ) def always_executed_hook(self): @@ -107,23 +109,26 @@ class SKALogger(SKABaseDevice): for level, device in zip(logging_levels, logging_devices): try: new_level = LoggingLevel(level) - self.logger.info("Setting logging level %s for %s", new_level, device) + self.logger.info( + "Setting logging level %s for %s", new_level, device + ) dev_proxy = DeviceProxy(device) dev_proxy.loggingLevel = new_level except DevFailed: self.logger.exception( - "Failed to set logging level %s for %s", level, device) + "Failed to set logging level %s for %s", level, device + ) message = "SetLoggingLevel command completed OK" self.logger.info(message) return (ResultCode.OK, message) @command( - dtype_in='DevVarLongStringArray', + dtype_in="DevVarLongStringArray", doc_in="Logging level for selected devices:" - "(0=OFF, 1=FATAL, 2=ERROR, 3=WARNING, 4=INFO, 5=DEBUG)." - "Example: [[4, 5], ['my/dev/1', 'my/dev/2']].", - dtype_out='DevVarLongStringArray', + "(0=OFF, 1=FATAL, 2=ERROR, 3=WARNING, 4=INFO, 5=DEBUG)." + "Example: [[4, 5], ['my/dev/1', 'my/dev/2']].", + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -150,6 +155,7 @@ class SKALogger(SKABaseDevice): # PROTECTED REGION END # // SKALogger.SetLoggingLevel + # ---------- # Run server # ---------- @@ -164,5 +170,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // SKALogger.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/master_device.py b/src/ska_tango_base/master_device.py index 741d409c9d8668628e5effeae4e5a7230e557b4b..c6c85943d65e4006ce2d2417578a5636d25468dc 100644 --- a/src/ska_tango_base/master_device.py +++ b/src/ska_tango_base/master_device.py @@ -17,7 +17,11 @@ from tango.server import run, attribute, command, device_property # SKA specific imports from ska_tango_base import SKABaseDevice from ska_tango_base.commands import BaseCommand, ResultCode -from ska_tango_base.utils import validate_capability_types, validate_input_sizes, convert_dict_to_list +from ska_tango_base.utils import ( + validate_capability_types, + validate_input_sizes, + convert_dict_to_list, +) # PROTECTED REGION END # // SKAMaster.additionnal_imports @@ -37,9 +41,7 @@ class SKAMaster(SKABaseDevice): super().init_command_objects() self.register_command_object( "IsCapabilityAchievable", - self.IsCapabilityAchievableCommand( - self, self.op_state_model, self.logger - ) + self.IsCapabilityAchievableCommand(self, self.op_state_model, self.logger), ) class InitCommand(SKABaseDevice.InitCommand): @@ -69,9 +71,12 @@ class SKAMaster(SKABaseDevice): device._max_capabilities = {} if device.MaxCapabilities: for max_capability in device.MaxCapabilities: - capability_type, max_capability_instances = max_capability.split(":") + capability_type, max_capability_instances = max_capability.split( + ":" + ) device._max_capabilities[capability_type] = int( - max_capability_instances) + max_capability_instances + ) device._available_capabilities = device._max_capabilities.copy() message = "SKAMaster Init command completed OK" @@ -89,7 +94,7 @@ class SKAMaster(SKABaseDevice): # CORRELATOR=512, PSS-BEAMS=4, PST-BEAMS=6, VLBI-BEAMS=4 or for DSH it can be: # BAND-1=1, BAND-2=1, BAND3=0, BAND-4=0, BAND-5=0 (if only bands 1&2 is installed) MaxCapabilities = device_property( - dtype=('str',), + dtype=("str",), ) # ---------- @@ -97,42 +102,44 @@ class SKAMaster(SKABaseDevice): # ---------- elementLoggerAddress = attribute( - dtype='str', + dtype="str", doc="FQDN of Element Logger", ) """Device attribute.""" elementAlarmAddress = attribute( - dtype='str', + dtype="str", doc="FQDN of Element Alarm Handlers", ) """Device attribute.""" elementTelStateAddress = attribute( - dtype='str', + dtype="str", doc="FQDN of Element TelState device", ) """Device attribute.""" elementDatabaseAddress = attribute( - dtype='str', + dtype="str", doc="FQDN of Element Database device", ) """Device attribute.""" maxCapabilities = attribute( - dtype=('str',), + dtype=("str",), max_dim_x=20, - doc=("Maximum number of instances of each capability type," - " e.g. 'CORRELATOR:512', 'PSS-BEAMS:4'."), + doc=( + "Maximum number of instances of each capability type," + " e.g. 'CORRELATOR:512', 'PSS-BEAMS:4'." + ), ) """Device attribute.""" availableCapabilities = attribute( - dtype=('str',), + dtype=("str",), max_dim_x=20, doc="A list of available number of instances of each capability type, " - "e.g. 'CORRELATOR:512', 'PSS-BEAMS:4'.", + "e.g. 'CORRELATOR:512', 'PSS-BEAMS:4'.", ) """Device attribute.""" @@ -207,25 +214,27 @@ class SKAMaster(SKABaseDevice): :rtype: bool """ device = self.target - command_name = 'isCapabilityAchievable' + command_name = "isCapabilityAchievable" capabilities_instances, capability_types = argin validate_input_sizes(command_name, argin) - validate_capability_types(command_name, capability_types, - list(device._max_capabilities.keys())) + validate_capability_types( + command_name, capability_types, list(device._max_capabilities.keys()) + ) for capability_type, capability_instances in zip( capability_types, capabilities_instances ): - if not device._available_capabilities[ - capability_type - ] >= capability_instances: + if ( + not device._available_capabilities[capability_type] + >= capability_instances + ): return False return True @command( - dtype_in='DevVarLongStringArray', + dtype_in="DevVarLongStringArray", doc_in="[nrInstances][Capability types]", - dtype_out='bool', + dtype_out="bool", ) @DebugIt() def isCapabilityAchievable(self, argin): @@ -260,5 +269,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // SKAMaster.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/obs/obs_device.py b/src/ska_tango_base/obs/obs_device.py index 31d70fdb23f8ce5defcad3800798ab9c7d48efa0..d993a9dcbe175588e4cc3fe5f081bea8b948a498 100644 --- a/src/ska_tango_base/obs/obs_device.py +++ b/src/ska_tango_base/obs/obs_device.py @@ -13,8 +13,6 @@ instead of just SKABaseDevice. # Additional import # PROTECTED REGION ID(SKAObsDevice.additionnal_import) ENABLED START # -import warnings - # Tango imports from tango.server import run, attribute @@ -22,6 +20,7 @@ from tango.server import run, attribute from ska_tango_base import SKABaseDevice from ska_tango_base.commands import ResultCode from ska_tango_base.control_model import ObsMode, ObsState + # PROTECTED REGION END # // SKAObsDevice.additionnal_imports __all__ = ["SKAObsDevice", "main"] @@ -31,6 +30,7 @@ class SKAObsDevice(SKABaseDevice): """ A generic base device for Observations for SKA. """ + class InitCommand(SKABaseDevice.InitCommand): """ A class for the SKAObsDevice's init_device() "command". @@ -85,7 +85,7 @@ class SKAObsDevice(SKABaseDevice): """Device attribute.""" configurationProgress = attribute( - dtype='uint16', + dtype="uint16", unit="%", max_value=100, min_value=0, @@ -94,7 +94,7 @@ class SKAObsDevice(SKABaseDevice): """Device attribute.""" configurationDelayExpected = attribute( - dtype='uint16', + dtype="uint16", unit="seconds", doc="Configuration delay expected in seconds", ) @@ -167,6 +167,7 @@ class SKAObsDevice(SKABaseDevice): # Commands # -------- + # ---------- # Run server # ---------- @@ -184,5 +185,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // SKAObsDevice.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/subarray/__init__.py b/src/ska_tango_base/subarray/__init__.py index 42bdc884b54116a878f7ad769435722d4d835b32..8d8ffe64bc3e8c9f57a4e6ec1bde981651ec007c 100644 --- a/src/ska_tango_base/subarray/__init__.py +++ b/src/ska_tango_base/subarray/__init__.py @@ -14,7 +14,5 @@ __all__ = ( from .subarray_obs_state_model import SubarrayObsStateModel from .component_manager import SubarrayComponentManager -from .reference_component_manager import ( - ReferenceSubarrayComponentManager, check_on -) +from .reference_component_manager import ReferenceSubarrayComponentManager, check_on from .subarray_device import SKASubarray diff --git a/src/ska_tango_base/subarray/reference_component_manager.py b/src/ska_tango_base/subarray/reference_component_manager.py index bd22716e505eeb81540a19de3a0c8cced539306f..6ca16084809f7b6a41e520080605db4ffe30860a 100644 --- a/src/ska_tango_base/subarray/reference_component_manager.py +++ b/src/ska_tango_base/subarray/reference_component_manager.py @@ -3,8 +3,6 @@ This module models component management for SKA subarray devices. """ import functools -from tango import DevState - from ska_tango_base.subarray import SubarrayComponentManager from ska_tango_base.base import ( check_communicating, @@ -27,6 +25,7 @@ def check_on(func): :return: the wrapped function """ + @functools.wraps(func) def _wrapper(component, *args, **kwargs): """ @@ -164,6 +163,7 @@ class ReferenceSubarrayComponentManager( ``component_configured``, ``component_scanning``, ``component_not_scanning`` and ``component_obsfault`` methods. """ + def __init__( self, capability_types, @@ -427,7 +427,12 @@ class ReferenceSubarrayComponentManager( self._invoke_obsfault_callback() def __init__( - self, op_state_model, obs_state_model, capability_types, logger=None, _component=None + self, + op_state_model, + obs_state_model, + capability_types, + logger=None, + _component=None, ): """ Initialise a new ReferenceSubarrayComponentManager instance diff --git a/src/ska_tango_base/subarray/subarray_device.py b/src/ska_tango_base/subarray/subarray_device.py index 170c89587f935e3cc58a81feeaa4b212cd6a5733..61e5a1257fa2b3c064c23a4d33e764cd67bc2fd3 100644 --- a/src/ska_tango_base/subarray/subarray_device.py +++ b/src/ska_tango_base/subarray/subarray_device.py @@ -12,7 +12,6 @@ information like assigned resources, configured capabilities, etc. """ # PROTECTED REGION ID(SKASubarray.additionnal_import) ENABLED START # import json -import warnings from tango import DebugIt from tango.server import run, attribute, command @@ -20,7 +19,12 @@ from tango.server import device_property # SKA specific imports from ska_tango_base import SKAObsDevice -from ska_tango_base.commands import CompletionCommand, ObservationCommand, ResponseCommand, ResultCode +from ska_tango_base.commands import ( + CompletionCommand, + ObservationCommand, + ResponseCommand, + ResultCode, +) from ska_tango_base.subarray import SubarrayComponentManager, SubarrayObsStateModel # PROTECTED REGION END # // SKASubarray.additionnal_imports @@ -56,8 +60,9 @@ class SKASubarray(SKAObsDevice): self.logger.info(message) return (ResultCode.OK, message) - - class AssignResourcesCommand(ObservationCommand, ResponseCommand, CompletionCommand): + class AssignResourcesCommand( + ObservationCommand, ResponseCommand, CompletionCommand + ): """ A class for SKASubarray's AssignResources() command. """ @@ -81,7 +86,9 @@ class SKASubarray(SKAObsDevice): :type logger: a logger that implements the standard library logger interface """ - super().__init__(target, obs_state_model, "assign", op_state_model, logger=logger) + super().__init__( + target, obs_state_model, "assign", op_state_model, logger=logger + ) def do(self, argin): """ @@ -102,7 +109,9 @@ class SKASubarray(SKAObsDevice): self.logger.info(message) return (ResultCode.OK, message) - class ReleaseResourcesCommand(ObservationCommand, ResponseCommand, CompletionCommand): + class ReleaseResourcesCommand( + ObservationCommand, ResponseCommand, CompletionCommand + ): """ A class for SKASubarray's ReleaseResources() command. """ @@ -126,7 +135,9 @@ class SKASubarray(SKAObsDevice): :type logger: a logger that implements the standard library logger interface """ - super().__init__(target, obs_state_model, "release", op_state_model, logger=logger) + super().__init__( + target, obs_state_model, "release", op_state_model, logger=logger + ) def do(self, argin): """ @@ -147,10 +158,13 @@ class SKASubarray(SKAObsDevice): self.logger.info(message) return (ResultCode.OK, message) - class ReleaseAllResourcesCommand(ObservationCommand, ResponseCommand, CompletionCommand): + class ReleaseAllResourcesCommand( + ObservationCommand, ResponseCommand, CompletionCommand + ): """ A class for SKASubarray's ReleaseAllResources() command. """ + def __init__(self, target, op_state_model, obs_state_model, logger=None): """ Constructor for ReleaseResourcesCommand @@ -170,7 +184,9 @@ class SKASubarray(SKAObsDevice): :type logger: a logger that implements the standard library logger interface """ - super().__init__(target, obs_state_model, "release", op_state_model, logger=logger) + super().__init__( + target, obs_state_model, "release", op_state_model, logger=logger + ) def do(self): """ @@ -278,7 +294,7 @@ class SKASubarray(SKAObsDevice): component_manager = self.target component_manager.scan(argin) - message = f"Scan command started" + message = "Scan command started" self.logger.info(message) return (ResultCode.STARTED, message) @@ -509,8 +525,7 @@ class SKASubarray(SKAObsDevice): """ super()._init_state_model() self.obs_state_model = SubarrayObsStateModel( - logger=self.logger, - callback=self._update_obs_state + logger=self.logger, callback=self._update_obs_state ) def create_component_manager(self): @@ -537,26 +552,29 @@ class SKASubarray(SKAObsDevice): self.register_command_object( command_name, command_class( - self.component_manager, self.op_state_model, self.obs_state_model, self.logger - ) + self.component_manager, + self.op_state_model, + self.obs_state_model, + self.logger, + ), ) # ----------------- # Device Properties # ----------------- CapabilityTypes = device_property( - dtype=('str',), + dtype=("str",), ) SubID = device_property( - dtype='str', + dtype="str", ) # ---------- # Attributes # ---------- activationTime = attribute( - dtype='double', + dtype="double", unit="s", standard_unit="s", display_unit="s", @@ -565,19 +583,19 @@ class SKASubarray(SKAObsDevice): """Device attribute.""" assignedResources = attribute( - dtype=('str',), + dtype=("str",), max_dim_x=100, doc="The list of resources assigned to the subarray.", ) """Device attribute.""" configuredCapabilities = attribute( - dtype=('str',), + dtype=("str",), max_dim_x=10, doc="A list of capability types with no. of instances " - "in use on this subarray; " - "e.g.\nCorrelators:512, PssBeams:4, " - "PstBeams:4, VlbiBeams:0.", + "in use on this subarray; " + "e.g.\nCorrelators:512, PssBeams:4, " + "PstBeams:4, VlbiBeams:0.", ) """Device attribute.""" @@ -620,7 +638,7 @@ class SKASubarray(SKAObsDevice): :return: Resources assigned to the device. """ - return self.component_manager.assigned_resources #pylint: disable=no-member + return self.component_manager.assigned_resources # PROTECTED REGION END # // SKASubarray.assignedResources_read def read_configuredCapabilities(self): @@ -631,7 +649,7 @@ class SKASubarray(SKAObsDevice): :return: A list of capability types with no. of instances used in the Subarray """ - return self.component_manager.configured_capabilities #pylint: disable=no-member + return self.component_manager.configured_capabilities # PROTECTED REGION END # // SKASubarray.configuredCapabilities_read # -------- @@ -652,7 +670,7 @@ class SKASubarray(SKAObsDevice): @command( dtype_in="DevString", doc_in="JSON-encoded string with the resources to add to subarray", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -690,7 +708,7 @@ class SKASubarray(SKAObsDevice): @command( dtype_in="DevString", doc_in="JSON-encoded string with the resources to remove from the subarray", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -726,7 +744,7 @@ class SKASubarray(SKAObsDevice): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -760,7 +778,7 @@ class SKASubarray(SKAObsDevice): @command( dtype_in="DevString", doc_in="JSON-encoded string with the scan configuration", - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -832,7 +850,7 @@ class SKASubarray(SKAObsDevice): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -863,7 +881,7 @@ class SKASubarray(SKAObsDevice): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -895,7 +913,7 @@ class SKASubarray(SKAObsDevice): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -928,7 +946,7 @@ class SKASubarray(SKAObsDevice): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -960,7 +978,7 @@ class SKASubarray(SKAObsDevice): return command.is_allowed(raise_if_disallowed=True) @command( - dtype_out='DevVarLongStringArray', + dtype_out="DevVarLongStringArray", doc_out="(ReturnType, 'informational message')", ) @DebugIt() @@ -999,5 +1017,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // SKASubarray.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/subarray/subarray_obs_state_model.py b/src/ska_tango_base/subarray/subarray_obs_state_model.py index 1c00bb9c07b242e53c893c4c00daea86caabf2a4..76de3042a4451b0a0c424a1a4e4d4e490b8a276a 100644 --- a/src/ska_tango_base/subarray/subarray_obs_state_model.py +++ b/src/ska_tango_base/subarray/subarray_obs_state_model.py @@ -7,7 +7,7 @@ subarray Tango devices. It consists of: * an :py:class:`.SubarrayObsStateModel` that maps the underlying state machine state to a value of the :py:class:`ska_tango_base.control_model.ObsState` enum. - + """ from transitions.extensions import LockedMachine as Machine @@ -21,12 +21,12 @@ class _SubarrayObsStateMachine(Machine): """ State machine representing the observation state machine for subarrays. - + The machine implemented is essentially as agreed in ADR-8, but with some states broken down into sub-states to account for the interactions between commands and monitoring of the underlying component. - + For example, ADR-8 says that a configuring subarray moves from IDLE to CONFIGURING to READY. But in a device model where the state machine is responsive to both commands and changes to the monitored diff --git a/src/ska_tango_base/tel_state_device.py b/src/ska_tango_base/tel_state_device.py index 98cb65519382c83ffeb03d1983c93f65113be7af..ca3209e2ec049a9bb0d08e006d7fe58189026c16 100644 --- a/src/ska_tango_base/tel_state_device.py +++ b/src/ska_tango_base/tel_state_device.py @@ -15,6 +15,7 @@ from tango.server import run, device_property # SKA specific imports from ska_tango_base import SKABaseDevice + # PROTECTED REGION END # // SKATelState.additionnal_imports __all__ = ["SKATelState", "main"] @@ -24,6 +25,7 @@ class SKATelState(SKABaseDevice): """ A generic base device for Telescope State for SKA. """ + # PROTECTED REGION ID(SKATelState.class_variable) ENABLED START # # PROTECTED REGION END # // SKATelState.class_variable @@ -32,7 +34,7 @@ class SKATelState(SKABaseDevice): # ----------------- TelStateConfigFile = device_property( - dtype='str', + dtype="str", ) # ---------- @@ -60,6 +62,7 @@ class SKATelState(SKABaseDevice): # Commands # -------- + # ---------- # Run server # ---------- @@ -80,5 +83,5 @@ def main(args=None, **kwargs): # PROTECTED REGION END # // SKATelState.main -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/ska_tango_base/utils.py b/src/ska_tango_base/utils.py index 2ed8c12eda2da37980ba4422f63bb11c50e39643..712715a6cb0096a868ab6908b3c36f93c6e649ec 100644 --- a/src/ska_tango_base/utils.py +++ b/src/ska_tango_base/utils.py @@ -12,40 +12,49 @@ import warnings from datetime import datetime import tango -from tango import (DeviceProxy, DbDatum, DbDevInfo, AttrQuality, - AttrWriteType, Except, ErrSeverity) +from tango import ( + DeviceProxy, + DbDatum, + DbDevInfo, + AttrQuality, + AttrWriteType, + Except, + ErrSeverity, +) from tango import DevState from contextlib import contextmanager from ska_tango_base.faults import GroupDefinitionsError, SKABaseError -int_types = {tango._tango.CmdArgType.DevUShort, - tango._tango.CmdArgType.DevLong, - tango._tango.CmdArgType.DevInt, - tango._tango.CmdArgType.DevULong, - tango._tango.CmdArgType.DevULong64, - tango._tango.CmdArgType.DevLong64, - tango._tango.CmdArgType.DevShort} +int_types = { + tango._tango.CmdArgType.DevUShort, + tango._tango.CmdArgType.DevLong, + tango._tango.CmdArgType.DevInt, + tango._tango.CmdArgType.DevULong, + tango._tango.CmdArgType.DevULong64, + tango._tango.CmdArgType.DevLong64, + tango._tango.CmdArgType.DevShort, +} -float_types = {tango._tango.CmdArgType.DevDouble, - tango._tango.CmdArgType.DevFloat} +float_types = {tango._tango.CmdArgType.DevDouble, tango._tango.CmdArgType.DevFloat} # TBD - investigate just using (command argin data_type) -tango_type_conversion = {tango.CmdArgType.DevUShort.real: 'int', - tango.CmdArgType.DevLong.real: 'int', - tango.CmdArgType.DevInt.real: 'int', - tango.CmdArgType.DevULong.real: 'int', - tango.CmdArgType.DevULong64.real: 'int', - tango.CmdArgType.DevLong64.real: 'int', - tango.CmdArgType.DevShort.real: 'int', - tango.CmdArgType.DevDouble.real: 'float', - tango.CmdArgType.DevFloat.real: 'float', - tango.CmdArgType.DevString.real: 'str', - tango.CmdArgType.DevBoolean.real: 'bool', - tango.CmdArgType.DevEncoded.real: 'encoded', - tango.CmdArgType.DevState.real: 'state', - tango.CmdArgType.DevVoid.real: 'void', - tango.CmdArgType.DevEnum.real: 'enum', - } +tango_type_conversion = { + tango.CmdArgType.DevUShort.real: "int", + tango.CmdArgType.DevLong.real: "int", + tango.CmdArgType.DevInt.real: "int", + tango.CmdArgType.DevULong.real: "int", + tango.CmdArgType.DevULong64.real: "int", + tango.CmdArgType.DevLong64.real: "int", + tango.CmdArgType.DevShort.real: "int", + tango.CmdArgType.DevDouble.real: "float", + tango.CmdArgType.DevFloat.real: "float", + tango.CmdArgType.DevString.real: "str", + tango.CmdArgType.DevBoolean.real: "bool", + tango.CmdArgType.DevEncoded.real: "encoded", + tango.CmdArgType.DevState.real: "state", + tango.CmdArgType.DevVoid.real: "void", + tango.CmdArgType.DevEnum.real: "enum", +} # TBD - not all tango types are used # tango.CmdArgType.ConstDevString tango.CmdArgType.DevState # tango.CmdArgType.DevVarLong64Array tango.CmdArgType.conjugate @@ -80,7 +89,9 @@ def exception_manager(cls, callback=None): calframe = inspect.getouterframes(curframe, 2) # Form exception message - message = "{}: {}".format(type(tango.DevFailed).__name__, tango.DevFailed.message) + message = "{}: {}".format( + type(tango.DevFailed).__name__, tango.DevFailed.message + ) # Retrieve class class_name = str(cls.__class__.__name__) @@ -95,8 +106,12 @@ def exception_manager(cls, callback=None): if callback: callback() - tango.Except.re_throw_exception(tango.DevFailed, "SKA_CommandFailed", message, - class_name + "::" + calframe[2][3]) + tango.Except.re_throw_exception( + tango.DevFailed, + "SKA_CommandFailed", + message, + class_name + "::" + calframe[2][3], + ) except Exception as anything: # Find caller from the relative point of this executing handler curframe = inspect.currentframe() @@ -119,16 +134,17 @@ def exception_manager(cls, callback=None): if callback: callback() - tango.Except.throw_exception("SKA_CommandFailed", message, - class_name + "::" + calframe[2][3]) + tango.Except.throw_exception( + "SKA_CommandFailed", message, class_name + "::" + calframe[2][3] + ) def get_dev_info(domain_name, device_server_name, device_ref): dev_info = DbDevInfo() dev_info._class = device_server_name - dev_info.server = '%s/%s' % (device_server_name, domain_name) + dev_info.server = "%s/%s" % (device_server_name, domain_name) # add the device - dev_info.name = '%s/%s' % (domain_name, device_ref) + dev_info.name = "%s/%s" % (domain_name, device_ref) return dev_info @@ -146,7 +162,7 @@ def dp_set_property(device_name, property_name, property_value): def get_device_group_and_id(device_name): device_name = device_name - return device_name.split('/')[1:] + return device_name.split("/")[1:] def convert_api_value(param_dict): @@ -155,20 +171,22 @@ def convert_api_value(param_dict): :param param_dict: :return: """ - VALID_TYPES = ['int', 'bool', 'str', 'float'] - type_str = param_dict.get('type', 'str').lower() + VALID_TYPES = ["int", "bool", "str", "float"] + type_str = param_dict.get("type", "str").lower() if type_str not in VALID_TYPES: - raise Exception('Valid types must be from %s' % ', '.join(VALID_TYPES)) + raise Exception("Valid types must be from %s" % ", ".join(VALID_TYPES)) value_type = pydoc.locate(type_str) if value_type == bool: - if not param_dict.get('value').lower() in ['true', 'false']: - raise Exception('Parameter value %s is not of type %s' - % (param_dict.get('value'), value_type)) - value = param_dict.get('value').lower() == 'true' + if not param_dict.get("value").lower() in ["true", "false"]: + raise Exception( + "Parameter value %s is not of type %s" + % (param_dict.get("value"), value_type) + ) + value = param_dict.get("value").lower() == "true" else: - value = value_type(param_dict.get('value')) - return param_dict.get('name'), value + value = value_type(param_dict.get("value")) + return param_dict.get("name"), value def coerce_value(value): @@ -182,15 +200,20 @@ def coerce_value(value): def get_dp_attribute(device_proxy, attribute, with_value=False, with_context=False): attr_dict = { - 'name': attribute.name, - 'polling_frequency': attribute.events.per_event.period, - 'min_value': (attribute.min_value if attribute.min_value != 'Not specified' - else None), - 'max_value': (attribute.max_value if attribute.max_value != 'Not specified' - else None), - 'readonly': attribute.writable not in [AttrWriteType.READ_WRITE, - AttrWriteType.WRITE, - AttrWriteType.READ_WITH_WRITE] + "name": attribute.name, + "polling_frequency": attribute.events.per_event.period, + "min_value": ( + attribute.min_value if attribute.min_value != "Not specified" else None + ), + "max_value": ( + attribute.max_value if attribute.max_value != "Not specified" else None + ), + "readonly": attribute.writable + not in [ + AttrWriteType.READ_WRITE, + AttrWriteType.WRITE, + AttrWriteType.READ_WITH_WRITE, + ], } # TBD - use tango_type_conversion dict, or just str(attribute.data_format) @@ -213,17 +236,17 @@ def get_dp_attribute(device_proxy, attribute, with_value=False, with_context=Fal if with_context: device_type, device_id = get_tango_device_type_id(device_proxy.dev_name()) - attr_dict['component_type'] = device_type - attr_dict['component_id'] = device_id + attr_dict["component_type"] = device_type + attr_dict["component_id"] = device_id if with_value: try: attr_value = device_proxy.read_attribute(attribute.name) - attr_dict['value'] = coerce_value(attr_value.value) - attr_dict['is_alarm'] = attr_value.quality == AttrQuality.ATTR_ALARM + attr_dict["value"] = coerce_value(attr_value.value) + attr_dict["is_alarm"] = attr_value.quality == AttrQuality.ATTR_ALARM ts = datetime.fromtimestamp(attr_value.time.tv_sec) ts.replace(microsecond=attr_value.time.tv_usec) - attr_dict['timestamp'] = ts.isoformat() + attr_dict["timestamp"] = ts.isoformat() except Exception: # TBD - decide what to do - add log? pass @@ -239,31 +262,31 @@ def get_dp_command(device_name, command, with_context=False): def command_parameters(command_desc): try: - non_json = ['', 'none', 'Uninitialised'] + non_json = ["", "none", "Uninitialised"] if command_desc in non_json: return [] # ugghhh POGO replaces quotes with backticks :( - return ast.literal_eval(command_desc.replace('`', "'")) + return ast.literal_eval(command_desc.replace("`", "'")) except Exception: # TBD - decide what to do - add log? pass return [] command_dict = { - 'name': command.cmd_name, - 'parameters': command_parameters(command.in_type_desc) + "name": command.cmd_name, + "parameters": command_parameters(command.in_type_desc), } if with_context: device_type, device_id = get_tango_device_type_id(device_name) - command_dict['component_type'] = device_type - command_dict['component_id'] = device_id + command_dict["component_type"] = device_type + command_dict["component_id"] = device_id return command_dict def get_tango_device_type_id(tango_address): - return tango_address.split('/')[1:3] + return tango_address.split("/")[1:3] def get_groups_from_json(json_definitions): @@ -372,7 +395,7 @@ def get_groups_from_json(json_definitions): if json_definition: definition = json.loads(json_definition) _validate_group(definition) - group_name = definition['group_name'] + group_name = definition["group_name"] groups[group_name] = _build_group(definition) return groups @@ -389,24 +412,24 @@ def _validate_group(definition): """ error_message = "Missing 'group_name' key - {}".format(definition) - assert 'group_name' in definition, error_message + assert "group_name" in definition, error_message error_message = "Missing 'devices' or 'subgroups' key - {}".format(definition) - assert 'devices' in definition or 'subgroups' in definition, error_message + assert "devices" in definition or "subgroups" in definition, error_message - definition['group_name'] = definition['group_name'].strip() + definition["group_name"] = definition["group_name"].strip() - old_devices = definition.get('devices', []) + old_devices = definition.get("devices", []) new_devices = [] for old_device in old_devices: # sanity check on device name, expect 'domain/family/member' # TODO (AJ): Check with regex. Allow fully qualified names? device = old_device.strip() error_message = "Invalid device name format - {}".format(device) - assert device.count('/') == 2, error_message + assert device.count("/") == 2, error_message new_devices.append(device) - definition['devices'] = new_devices + definition["devices"] = new_devices - subgroups = definition.get('subgroups', []) + subgroups = definition.get("subgroups", []) for subgroup_definition in subgroups: _validate_group(subgroup_definition) # recurse @@ -417,9 +440,9 @@ def _build_group(definition): Used internally by `get_groups_from_json`. """ - group_name = definition['group_name'] - devices = definition.get('devices', []) - subgroups = definition.get('subgroups', []) + group_name = definition["group_name"] + devices = definition.get("devices", []) + subgroups = definition.get("subgroups", []) group = tango.Group(group_name) for device_name in devices: @@ -445,13 +468,15 @@ def validate_capability_types(command_name, requested_capabilities, valid_capabi types. :type valid_capabilities: list(str) """ - invalid_capabilities = list( - set(requested_capabilities) - set(valid_capabilities)) + invalid_capabilities = list(set(requested_capabilities) - set(valid_capabilities)) if invalid_capabilities: Except.throw_exception( - "Command failed!", "Invalid capability types requested {}".format( - invalid_capabilities), command_name, ErrSeverity.ERR) + "Command failed!", + "Invalid capability types requested {}".format(invalid_capabilities), + command_name, + ErrSeverity.ERR, + ) def validate_input_sizes(command_name, argin): @@ -466,19 +491,23 @@ def validate_input_sizes(command_name, argin): """ capabilities_instances, capability_types = argin if len(capabilities_instances) != len(capability_types): - Except.throw_exception("Command failed!", "Argin value lists size mismatch.", - command_name, ErrSeverity.ERR) + Except.throw_exception( + "Command failed!", + "Argin value lists size mismatch.", + command_name, + ErrSeverity.ERR, + ) def convert_dict_to_list(dictionary): the_list = [] - for key, value in (list(dictionary.items())): + for key, value in list(dictionary.items()): the_list.append("{}:{}".format(key, value)) return sorted(the_list) -def for_testing_only(func, _testing_check=lambda: 'pytest' in sys.modules): +def for_testing_only(func, _testing_check=lambda: "pytest" in sys.modules): """ A decorator that marks a function as available for testing purposes only. If the decorated function is called outside of testing, a warning is raised. @@ -490,6 +519,7 @@ def for_testing_only(func, _testing_check=lambda: 'pytest' in sys.modules): argument, allowing for it to be replaced in testing. (The `_testing_check` argument is inaccessible via the @-syntax, which is a nice bonus.) """ + @functools.wraps(func) def _wrapper(*args, **kwargs): """ @@ -498,5 +528,5 @@ def for_testing_only(func, _testing_check=lambda: 'pytest' in sys.modules): if not _testing_check(): warnings.warn(f"{func.__name__} should only be used for testing purposes.") return func(*args, **kwargs) - + return _wrapper diff --git a/tests/conftest.py b/tests/conftest.py index 461ee070c8455a27bb7fe0f051c85fe5b5ec94a6..5dfbbd92010752d8a1e874c2f80824cd58eb6f11 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,7 +1,6 @@ """ A module defining a list of fixtures that are shared across all ska_tango_base tests. """ -import importlib import logging from queue import Empty, Queue @@ -19,6 +18,7 @@ def device_properties(): """ return {} + @pytest.fixture(scope="class") def tango_context(device_test_config): """ @@ -34,11 +34,13 @@ def tango_context(device_test_config): yield tango_context tango_context.stop() + def pytest_itemcollected(item): """Make Tango-related tests run in forked mode""" if "tango_context" in item.fixturenames: item.add_marker("forked") + @pytest.fixture(scope="function") def initialize_device(tango_context): """Re-initializes the device. @@ -139,7 +141,8 @@ def tango_change_event_helper(tango_context): if event_data.err: error = event_data.errors[0] self._errors.append( - "Event callback error: [%s] %s" % (error.reason, error.desc)) + "Event callback error: [%s] %s" % (error.reason, error.desc) + ) else: self._values_queue.put(event_data.attr_value.value) diff --git a/tests/test_alarm_handler_device.py b/tests/test_alarm_handler_device.py index 53d14943dce3112528a51c35516ac4a6fbce40e5..8aaffda8837d08d9c889a64751b238575d0f244d 100644 --- a/tests/test_alarm_handler_device.py +++ b/tests/test_alarm_handler_device.py @@ -17,12 +17,15 @@ from ska_tango_base import SKAAlarmHandler from ska_tango_base.base import ReferenceBaseComponentManager from ska_tango_base.control_model import AdminMode + # PROTECTED REGION ID(SKAAlarmHandler.test_additional_imports) ENABLED START # # PROTECTED REGION END # // SKAAlarmHandler.test_additional_imports # Device test case # PROTECTED REGION ID(SKAAlarmHandler.test_SKAAlarmHandler_decorators) ENABLED START # -@pytest.mark.usefixtures("tango_context", "initialize_device") # PROTECTED REGION END # // SKAAlarmHandler.test_SKAAlarmHandler_decorators + + +@pytest.mark.usefixtures("tango_context", "initialize_device") class TestSKAAlarmHandler(object): """ Test class for tests of the SKAAlarmHander device class. @@ -96,8 +99,8 @@ class TestSKAAlarmHandler(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(SKAAlarmHandler.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -149,8 +152,9 @@ class TestSKAAlarmHandler(object): """Test for buildState""" # PROTECTED REGION ID(SKAAlarmHandler.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // SKAAlarmHandler.test_buildState @@ -159,7 +163,7 @@ class TestSKAAlarmHandler(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(SKAAlarmHandler.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // SKAAlarmHandler.test_versionId @@ -168,7 +172,7 @@ class TestSKAAlarmHandler(object): def test_activeAlerts(self, tango_context): """Test for activeAlerts""" # PROTECTED REGION ID(SKAAlarmHandler.test_activeAlerts) ENABLED START # - assert tango_context.device.activeAlerts == ('',) + assert tango_context.device.activeAlerts == ("",) # PROTECTED REGION END # // SKAAlarmHandler.test_activeAlerts # PROTECTED REGION ID(SKAAlarmHandler.test_activeAlarms_decorators) ENABLED START # @@ -176,5 +180,5 @@ class TestSKAAlarmHandler(object): def test_activeAlarms(self, tango_context): """Test for activeAlarms""" # PROTECTED REGION ID(SKAAlarmHandler.test_activeAlarms) ENABLED START # - assert tango_context.device.activeAlarms == ('',) + assert tango_context.device.activeAlarms == ("",) # PROTECTED REGION END # // SKAAlarmHandler.test_activeAlarms diff --git a/tests/test_base_component_manager.py b/tests/test_base_component_manager.py index 4fc2a2ae81a9f54748e6a12161abffc02890a645..99087a1058e19affe51ba2386fb887e8f4cce82e 100644 --- a/tests/test_base_component_manager.py +++ b/tests/test_base_component_manager.py @@ -52,7 +52,9 @@ class TestBaseComponentManager: :return: the component manager under test """ - return ReferenceBaseComponentManager(mock_op_state_model, logger=logger, _component=component) + return ReferenceBaseComponentManager( + mock_op_state_model, logger=logger, _component=component + ) def test_state_changes_with_start_and_stop( self, component_manager, mock_op_state_model, initial_power_mode, initial_fault @@ -90,7 +92,9 @@ class TestBaseComponentManager: "component_disconnected" ) - def test_simulate_communication_failure(self, component_manager, mock_op_state_model): + def test_simulate_communication_failure( + self, component_manager, mock_op_state_model + ): """ Test that we can simulate connection failure. diff --git a/tests/test_base_device.py b/tests/test_base_device.py index c98de2672f3e26ad81ab312659a5a3361eadb48c..cfe622ad23cdc566e3b2e641541e3f3280d6c4c6 100644 --- a/tests/test_base_device.py +++ b/tests/test_base_device.py @@ -34,18 +34,23 @@ from ska_tango_base.base.base_device import ( ) from ska_tango_base.commands import ResultCode from ska_tango_base.control_model import ( - AdminMode, ControlMode, HealthState, LoggingLevel, SimulationMode, TestMode + AdminMode, + ControlMode, + HealthState, + LoggingLevel, + SimulationMode, + TestMode, ) from ska_tango_base.faults import CommandError from .state.conftest import load_state_machine_spec + # PROTECTED REGION END # // SKABaseDevice.test_additional_imports # Device test case # PROTECTED REGION ID(SKABaseDevice.test_SKABaseDevice_decorators) ENABLED START # class TestTangoLoggingServiceHandler: - @pytest.fixture() def tls_handler(self): self.tango_logger = mock.MagicMock(spec=tango.Logger) @@ -54,19 +59,21 @@ class TestTangoLoggingServiceHandler: self.tango_logger.get_level.return_value = _Log4TangoLoggingLevel.DEBUG return TangoLoggingServiceHandler(self.tango_logger) - @pytest.fixture(params=[ - logging.DEBUG, - logging.INFO, - logging.WARN, - logging.ERROR, - logging.CRITICAL, - ]) + @pytest.fixture( + params=[ + logging.DEBUG, + logging.INFO, + logging.WARN, + logging.ERROR, + logging.CRITICAL, + ] + ) def python_log_level(self, request): return request.param def test_emit_message_at_correct_level(self, tls_handler, python_log_level): # arrange - record = logging.LogRecord('test', python_log_level, '', 1, 'message', (), None) + record = logging.LogRecord("test", python_log_level, "", 1, "message", (), None) # act tls_handler.emit(record) # assert @@ -76,8 +83,9 @@ class TestTangoLoggingServiceHandler: def test_emit_message_is_formatted(self, tls_handler): # arrange - record = logging.LogRecord('test', logging.INFO, '', 1, - 'message %s', ('param',), None) + record = logging.LogRecord( + "test", logging.INFO, "", 1, "message %s", ("param",), None + ) def format_stub(log_record): return "LOG: " + log_record.getMessage() @@ -93,7 +101,7 @@ class TestTangoLoggingServiceHandler: def test_emit_exception_error_handled(self, tls_handler): # arrange - record = logging.LogRecord('test', logging.INFO, '', 1, 'message', (), None) + record = logging.LogRecord("test", logging.INFO, "", 1, "message", (), None) def cause_exception(*args, **kwargs): raise RuntimeError("Testing") @@ -106,47 +114,56 @@ class TestTangoLoggingServiceHandler: assert tls_handler.handleError.call_args_list == [mock.call(record)] def test_repr_normal(self, tls_handler): - expected = '<TangoLoggingServiceHandler unit/test/dev (Python NOTSET, Tango DEBUG)>' + expected = ( + "<TangoLoggingServiceHandler unit/test/dev (Python NOTSET, Tango DEBUG)>" + ) assert repr(tls_handler) == expected def test_repr_tango_logger_none(self, tls_handler): tls_handler.tango_logger = None - expected = '<TangoLoggingServiceHandler !No Tango logger! (Python NOTSET, Tango UNKNOWN)>' + expected = "<TangoLoggingServiceHandler !No Tango logger! (Python NOTSET, Tango UNKNOWN)>" assert repr(tls_handler) == expected class TestLoggingUtils: - @pytest.fixture(params=[ - (None, []), - ([""], []), - ([" \n\t "], []), - (["console"], ["console::cout"]), - (["console::"], ["console::cout"]), - (["console::cout"], ["console::cout"]), - (["console::anything"], ["console::anything"]), - (["file"], ["file::my_dev_name.log"]), - (["file::"], ["file::my_dev_name.log"]), - (["file::/tmp/dummy"], ["file::/tmp/dummy"]), - (["syslog::some/path"], ["syslog::some/path"]), - (["syslog::file://some/path"], ["syslog::file://some/path"]), - (["syslog::protocol://somehost:1234"], ["syslog::protocol://somehost:1234"]), - (["tango"], ["tango::logger"]), - (["tango::"], ["tango::logger"]), - (["tango::logger"], ["tango::logger"]), - (["tango::anything"], ["tango::anything"]), - (["console", "file"], ["console::cout", "file::my_dev_name.log"]), - ]) + @pytest.fixture( + params=[ + (None, []), + ([""], []), + ([" \n\t "], []), + (["console"], ["console::cout"]), + (["console::"], ["console::cout"]), + (["console::cout"], ["console::cout"]), + (["console::anything"], ["console::anything"]), + (["file"], ["file::my_dev_name.log"]), + (["file::"], ["file::my_dev_name.log"]), + (["file::/tmp/dummy"], ["file::/tmp/dummy"]), + (["syslog::some/path"], ["syslog::some/path"]), + (["syslog::file://some/path"], ["syslog::file://some/path"]), + ( + ["syslog::protocol://somehost:1234"], + ["syslog::protocol://somehost:1234"], + ), + (["tango"], ["tango::logger"]), + (["tango::"], ["tango::logger"]), + (["tango::logger"], ["tango::logger"]), + (["tango::anything"], ["tango::anything"]), + (["console", "file"], ["console::cout", "file::my_dev_name.log"]), + ] + ) def good_logging_targets(self, request): targets_in, expected = request.param dev_name = "my/dev/name" return targets_in, dev_name, expected - @pytest.fixture(params=[ - ["invalid"], - ["invalid", "console"], - ["invalid::type"], - ["syslog"], - ]) + @pytest.fixture( + params=[ + ["invalid"], + ["invalid", "console"], + ["invalid::type"], + ["syslog"], + ] + ) def bad_logging_targets(self, request): targets_in = request.param dev_name = "my/dev/name" @@ -162,44 +179,51 @@ class TestLoggingUtils: with pytest.raises(LoggingTargetError): LoggingUtils.sanitise_logging_targets(targets_in, dev_name) - @pytest.fixture(params=[ - ("deprecated/path", ["deprecated/path", None]), - ("file:///abs/path", ["/abs/path", None]), - ("file://relative/path", ["relative/path", None]), - ("file://some/spaced%20path", ["some/spaced path", None]), - ("udp://somehost.domain:1234", - [("somehost.domain", 1234), socket.SOCK_DGRAM]), - ("udp://127.0.0.1:1234", [("127.0.0.1", 1234), socket.SOCK_DGRAM]), - ("tcp://somehost:1234", [("somehost", 1234), socket.SOCK_STREAM]), - ("tcp://127.0.0.1:1234", [("127.0.0.1", 1234), socket.SOCK_STREAM]), - ]) + @pytest.fixture( + params=[ + ("deprecated/path", ["deprecated/path", None]), + ("file:///abs/path", ["/abs/path", None]), + ("file://relative/path", ["relative/path", None]), + ("file://some/spaced%20path", ["some/spaced path", None]), + ( + "udp://somehost.domain:1234", + [("somehost.domain", 1234), socket.SOCK_DGRAM], + ), + ("udp://127.0.0.1:1234", [("127.0.0.1", 1234), socket.SOCK_DGRAM]), + ("tcp://somehost:1234", [("somehost", 1234), socket.SOCK_STREAM]), + ("tcp://127.0.0.1:1234", [("127.0.0.1", 1234), socket.SOCK_STREAM]), + ] + ) def good_syslog_url(self, request): url, (expected_address, expected_socktype) = request.param return url, (expected_address, expected_socktype) - @pytest.fixture(params=[ - None, - "", - "file://", - "udp://", - "udp://somehost", - "udp://somehost:", - "udp://somehost:not_integer_port", - "udp://:1234", - "tcp://", - "tcp://somehost", - "tcp://somehost:", - "tcp://somehost:not_integer_port", - "tcp://:1234", - "invalid://somehost:1234" - ]) + @pytest.fixture( + params=[ + None, + "", + "file://", + "udp://", + "udp://somehost", + "udp://somehost:", + "udp://somehost:not_integer_port", + "udp://:1234", + "tcp://", + "tcp://somehost", + "tcp://somehost:", + "tcp://somehost:not_integer_port", + "tcp://:1234", + "invalid://somehost:1234", + ] + ) def bad_syslog_url(self, request): return request.param def test_get_syslog_address_and_socktype_success(self, good_syslog_url): url, (expected_address, expected_socktype) = good_syslog_url actual_address, actual_socktype = LoggingUtils.get_syslog_address_and_socktype( - url) + url + ) assert actual_address == expected_address assert actual_socktype == expected_socktype @@ -207,17 +231,19 @@ class TestLoggingUtils: with pytest.raises(LoggingTargetError): LoggingUtils.get_syslog_address_and_socktype(bad_syslog_url) - @mock.patch('ska_tango_base.base.base_device.TangoLoggingServiceHandler') - @mock.patch('logging.handlers.SysLogHandler') - @mock.patch('logging.handlers.RotatingFileHandler') - @mock.patch('logging.StreamHandler') - @mock.patch('ska_ser_logging.get_default_formatter') - def test_create_logging_handler(self, - mock_get_formatter, - mock_stream_handler, - mock_file_handler, - mock_syslog_handler, - mock_tango_handler): + @mock.patch("ska_tango_base.base.base_device.TangoLoggingServiceHandler") + @mock.patch("logging.handlers.SysLogHandler") + @mock.patch("logging.handlers.RotatingFileHandler") + @mock.patch("logging.StreamHandler") + @mock.patch("ska_ser_logging.get_default_formatter") + def test_create_logging_handler( + self, + mock_get_formatter, + mock_stream_handler, + mock_file_handler, + mock_syslog_handler, + mock_tango_handler, + ): # Expect formatter be created using `get_default_formatter(tags=True)` # Use some mocks to check this. mock_formatter = mock.MagicMock() @@ -241,7 +267,7 @@ class TestLoggingUtils: mock_syslog_handler.assert_called_once_with( address=("somehost", 1234), facility=mock_syslog_handler.LOG_SYSLOG, - socktype=socket.SOCK_DGRAM + socktype=socket.SOCK_DGRAM, ) assert handler == mock_syslog_handler() handler.setFormatter.assert_called_once_with(mock_formatter) @@ -249,14 +275,14 @@ class TestLoggingUtils: mock_syslog_handler.reset_mock() handler = LoggingUtils.create_logging_handler("syslog::file:///tmp/path") mock_syslog_handler.assert_called_once_with( - address="/tmp/path", - facility=mock_syslog_handler.LOG_SYSLOG, - socktype=None + address="/tmp/path", facility=mock_syslog_handler.LOG_SYSLOG, socktype=None ) assert handler == mock_syslog_handler() handler.setFormatter.assert_called_once_with(mock_formatter) - handler = LoggingUtils.create_logging_handler("tango::logger", mock_tango_logger) + handler = LoggingUtils.create_logging_handler( + "tango::logger", mock_tango_logger + ) mock_tango_handler.assert_called_once_with(mock_tango_logger) assert handler == mock_tango_handler() handler.setFormatter.assert_called_once_with(mock_formatter) @@ -271,7 +297,7 @@ class TestLoggingUtils: LoggingUtils.create_logging_handler("tango::logger", tango_logger=None) def test_update_logging_handlers(self): - logger = logging.getLogger('testing') + logger = logging.getLogger("testing") logger.tango_logger = mock.MagicMock(spec=tango.Logger) def null_creator(target, tango_logger): @@ -301,15 +327,21 @@ class TestLoggingUtils: # test other valid target types new_targets = [ - "console::cout", "file::/tmp/dummy", "syslog::some/address", "tango::logger"] + "console::cout", + "file::/tmp/dummy", + "syslog::some/address", + "tango::logger", + ] mocked_creator.reset_mock() LoggingUtils.update_logging_handlers(new_targets, logger) assert len(logger.handlers) == 4 assert mocked_creator.call_count == 3 mocked_creator.assert_has_calls( - [mock.call("file::/tmp/dummy", logger.tango_logger), - mock.call("syslog::some/address", logger.tango_logger), - mock.call("tango::logger", logger.tango_logger)], + [ + mock.call("file::/tmp/dummy", logger.tango_logger), + mock.call("syslog::some/address", logger.tango_logger), + mock.call("tango::logger", logger.tango_logger), + ], any_order=True, ) @@ -355,7 +387,6 @@ class TestSKABaseDevice(object): "memorized": {"adminMode": str(AdminMode.ONLINE.value)}, } - @pytest.mark.skip("Not implemented") def test_properties(self, tango_context): # Test the properties @@ -393,8 +424,8 @@ class TestSKABaseDevice(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(SKABaseDevice.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -461,8 +492,9 @@ class TestSKABaseDevice(object): """Test for buildState""" # PROTECTED REGION ID(SKABaseDevice.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // SKABaseDevice.test_buildState @@ -471,7 +503,7 @@ class TestSKABaseDevice(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(SKABaseDevice.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // SKABaseDevice.test_versionId @@ -497,7 +529,7 @@ class TestSKABaseDevice(object): """Test for loggingTargets""" # PROTECTED REGION ID(SKABaseDevice.test_loggingTargets) ENABLED START # # tango logging target must be enabled by default - assert tango_context.device.loggingTargets == ("tango::logger", ) + assert tango_context.device.loggingTargets == ("tango::logger",) with mock.patch( "ska_tango_base.base.base_device.LoggingUtils.create_logging_handler" @@ -513,20 +545,29 @@ class TestSKABaseDevice(object): # test console target tango_context.device.loggingTargets = ["console::cout"] - assert tango_context.device.loggingTargets == ("console::cout", ) + assert tango_context.device.loggingTargets == ("console::cout",) mocked_creator.assert_called_once_with("console::cout", mock.ANY) # test adding file and syslog targets (already have console) mocked_creator.reset_mock() tango_context.device.loggingTargets = [ - "console::cout", "file::/tmp/dummy", "syslog::udp://localhost:514"] + "console::cout", + "file::/tmp/dummy", + "syslog::udp://localhost:514", + ] assert tango_context.device.loggingTargets == ( - "console::cout", "file::/tmp/dummy", "syslog::udp://localhost:514") + "console::cout", + "file::/tmp/dummy", + "syslog::udp://localhost:514", + ) assert mocked_creator.call_count == 2 mocked_creator.assert_has_calls( - [mock.call("file::/tmp/dummy", mock.ANY), - mock.call("syslog::udp://localhost:514", mock.ANY)], - any_order=True) + [ + mock.call("file::/tmp/dummy", mock.ANY), + mock.call("syslog::udp://localhost:514", mock.ANY), + ], + any_order=True, + ) # test adding tango logging again, now that mock is active # (it wasn't active when device was initialised) @@ -641,6 +682,7 @@ class TestSKABaseDevice_commands: """ This class contains tests of SKABaseDevice commands """ + @pytest.fixture def op_state_model(self, logger): """ @@ -659,6 +701,7 @@ class TestSKABaseDevice_commands: :returns: a factory that constructs a command object for a given class """ + def _command_factory(command): return command(mocker.Mock(), op_state_model) @@ -693,7 +736,7 @@ class TestSKABaseDevice_commands: (SKABaseDevice.OffCommand, "off"), (SKABaseDevice.StandbyCommand, "standby"), (SKABaseDevice.OnCommand, "on"), - ] + ], ) def test_Command( self, @@ -702,7 +745,7 @@ class TestSKABaseDevice_commands: command_factory, op_state_model, command_class, - slug + slug, ): """ Test that certain commands can only be invoked in certain diff --git a/tests/test_capability_device.py b/tests/test_capability_device.py index 945c8d20d23593379d3242a1ef6b5ede6a3daf53..480316c66c61c9cebfd821ece0fb188b3e8fab03 100644 --- a/tests/test_capability_device.py +++ b/tests/test_capability_device.py @@ -91,8 +91,9 @@ class TestSKACapability(object): """Test for buildState""" # PROTECTED REGION ID(SKACapability.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // SKACapability.test_buildState @@ -101,7 +102,7 @@ class TestSKACapability(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(SKACapability.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // SKACapability.test_versionId @@ -118,5 +119,5 @@ class TestSKACapability(object): def test_usedComponents(self, tango_context): """Test for usedComponents""" # PROTECTED REGION ID(SKACapability.test_usedComponents) ENABLED START # - assert tango_context.device.usedComponents == ('',) + assert tango_context.device.usedComponents == ("",) # PROTECTED REGION END # // SKACapability.test_usedComponents diff --git a/tests/test_csp_master.py b/tests/test_csp_master.py index 954a97786873db1c606bc6def82f49534063c4ee..38a8a1a98c75ed702e5651706588cc5091ecc333 100644 --- a/tests/test_csp_master.py +++ b/tests/test_csp_master.py @@ -20,8 +20,13 @@ from ska_tango_base import SKAMaster, CspSubElementMaster from ska_tango_base.base import ReferenceBaseComponentManager from ska_tango_base.commands import ResultCode from ska_tango_base.control_model import ( - AdminMode, ControlMode, HealthState, SimulationMode, TestMode + AdminMode, + ControlMode, + HealthState, + SimulationMode, + TestMode, ) + # PROTECTED REGION END # // CspSubElementMaster.test_additional_imports @@ -37,7 +42,7 @@ class TestCspSubElementMaster(object): Fixture that returns device_properties to be provided to the device under test. """ - return {'PowerDelayStandbyOn': '1.5', 'PowerDelayStandbyOff': '1.0'} + return {"PowerDelayStandbyOn": "1.5", "PowerDelayStandbyOff": "1.0"} @pytest.fixture(scope="class") def device_test_config(self, device_properties): @@ -87,8 +92,8 @@ class TestCspSubElementMaster(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(CspSubelementMaster.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -99,8 +104,9 @@ class TestCspSubElementMaster(object): """Test for buildState""" # PROTECTED REGION ID(CspSubelementMaster.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // CspSubelementMaster.test_buildState @@ -109,7 +115,7 @@ class TestCspSubElementMaster(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(CspSubelementMaster.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // CspSubelementMaster.test_versionId @@ -159,7 +165,7 @@ class TestCspSubElementMaster(object): """Test for powerDelayStandbyOn""" # PROTECTED REGION ID(CspSubelementMaster.test_testMode) ENABLED START # assert tango_context.device.powerDelayStandbyOn == pytest.approx( - float(device_properties['PowerDelayStandbyOn']) + float(device_properties["PowerDelayStandbyOn"]) ) tango_context.device.powerDelayStandbyOn = 3 assert tango_context.device.powerDelayStandbyOn == 3 @@ -171,7 +177,7 @@ class TestCspSubElementMaster(object): """Test for powerDelayStandbyOff""" # PROTECTED REGION ID(CspSubelementMaster.test_testMode) ENABLED START # assert tango_context.device.powerDelayStandbyOff == pytest.approx( - float(device_properties['PowerDelayStandbyOff']) + float(device_properties["PowerDelayStandbyOff"]) ) tango_context.device.powerDelayStandbyOff = 2 assert tango_context.device.powerDelayStandbyOff == 2 @@ -285,9 +291,9 @@ class TestCspSubElementMaster(object): # After initialization the device is in the right state (OFF/MAINTENANCE) to # execute the command. tango_context.device.adminMode = AdminMode.MAINTENANCE - assert tango_context.device.LoadFirmware(['file', 'test/dev/b', '918698a7fea3']) == [ - [ResultCode.OK], ["LoadFirmware command completed OK"] - ] + assert tango_context.device.LoadFirmware( + ["file", "test/dev/b", "918698a7fea3"] + ) == [[ResultCode.OK], ["LoadFirmware command completed OK"]] # PROTECTED REGION END # // CspSubelementMaster.test_LoadFirmware # PROTECTED REGION ID(CspSubelementMaster.test_LoadFirmware_when_in_wrong_state_decorators) ENABLED START # @@ -298,7 +304,7 @@ class TestCspSubElementMaster(object): # Set the device in ON/ONLINE state tango_context.device.On() with pytest.raises(DevFailed, match="LoadFirmwareCommand not allowed"): - tango_context.device.LoadFirmware(['file', 'test/dev/b', '918698a7fea3']) + tango_context.device.LoadFirmware(["file", "test/dev/b", "918698a7fea3"]) # PROTECTED REGION END # // CspSubelementMaster.test_LoadFirmware_when_in_wrong_state # PROTECTED REGION ID(CspSubelementMaster.test_PowerOnDevices_decorators) ENABLED START # @@ -308,8 +314,9 @@ class TestCspSubElementMaster(object): # PROTECTED REGION ID(CspSubelementMaster.test_PowerOnDevices) ENABLED START # # put it in ON state tango_context.device.On() - assert tango_context.device.PowerOnDevices(['test/dev/1', 'test/dev/2']) == [ - [ResultCode.OK], ["PowerOnDevices command completed OK"] + assert tango_context.device.PowerOnDevices(["test/dev/1", "test/dev/2"]) == [ + [ResultCode.OK], + ["PowerOnDevices command completed OK"], ] # PROTECTED REGION END # // CspSubelementMaster.test_PowerOnDevices @@ -319,7 +326,7 @@ class TestCspSubElementMaster(object): """Test for PowerOnDevices when the Master is in wrong state""" # PROTECTED REGION ID(CspSubelementMaster.test_PowerOnDevices_when_in_wrong_state) ENABLED START # with pytest.raises(DevFailed, match="PowerOnDevicesCommand not allowed"): - tango_context.device.PowerOnDevices(['test/dev/1', 'test/dev/2']) + tango_context.device.PowerOnDevices(["test/dev/1", "test/dev/2"]) # PROTECTED REGION END # // CspSubelementMaster.test_PowerOnDevices_when_in_wrong_state # PROTECTED REGION ID(CspSubelementMaster.test_PowerOffDevices_decorators) ENABLED START # @@ -329,8 +336,9 @@ class TestCspSubElementMaster(object): # PROTECTED REGION ID(CspSubelementMaster.test_PowerOffDevices) ENABLED START # # put it in ON state tango_context.device.On() - assert tango_context.device.PowerOffDevices(['test/dev/1', 'test/dev/2']) == [ - [ResultCode.OK], ["PowerOffDevices command completed OK"] + assert tango_context.device.PowerOffDevices(["test/dev/1", "test/dev/2"]) == [ + [ResultCode.OK], + ["PowerOffDevices command completed OK"], ] # PROTECTED REGION END # // CspSubelementMaster.test_PowerOffDevices @@ -340,7 +348,7 @@ class TestCspSubElementMaster(object): """Test for PowerOffDevices when the Master is in wrong state""" # PROTECTED REGION ID(CspSubelementMaster.test_PowerOffDevices_when_in_wrong_state) ENABLED START # with pytest.raises(DevFailed, match="PowerOffDevicesCommand not allowed"): - tango_context.device.PowerOffDevices(['test/dev/1', 'test/dev/2']) + tango_context.device.PowerOffDevices(["test/dev/1", "test/dev/2"]) # PROTECTED REGION END # // CspSubelementMaster.test_PowerOffDevices_when_in_wrong_state # PROTECTED REGION ID(CspSubelementMaster.test_ReInitDevices_decorators) ENABLED START # @@ -350,8 +358,9 @@ class TestCspSubElementMaster(object): # PROTECTED REGION ID(CspSubelementMaster.test_ReInitDevices) ENABLED START # # put it in ON state tango_context.device.On() - assert tango_context.device.ReInitDevices(['test/dev/1', 'test/dev/2']) == [ - [ResultCode.OK], ["ReInitDevices command completed OK"] + assert tango_context.device.ReInitDevices(["test/dev/1", "test/dev/2"]) == [ + [ResultCode.OK], + ["ReInitDevices command completed OK"], ] # PROTECTED REGION END # // CspSubelementMaster.test_ReInitDevices @@ -362,7 +371,7 @@ class TestCspSubElementMaster(object): # PROTECTED REGION ID(CspSubelementMaster.test_ReInitDevices_when_in_wrong_state) ENABLED START # # put it in ON state with pytest.raises(DevFailed, match="ReInitDevicesCommand not allowed"): - tango_context.device.ReInitDevices(['test/dev/1', 'test/dev/2']) + tango_context.device.ReInitDevices(["test/dev/1", "test/dev/2"]) # PROTECTED REGION END # // CspSubelementMaster.test_ReInitDevices_when_in_wrong_state diff --git a/tests/test_csp_obs_device.py b/tests/test_csp_obs_device.py index 5ef30ab4c475ca4cff8c31618a7d10d98d454aa5..8007dfa6911d0a6891129ce636d6571d2b8e6182 100644 --- a/tests/test_csp_obs_device.py +++ b/tests/test_csp_obs_device.py @@ -21,11 +21,18 @@ from tango.test_context import MultiDeviceTestContext from ska_tango_base import SKAObsDevice, CspSubElementObsDevice from ska_tango_base.commands import ResultCode from ska_tango_base.control_model import ( - ObsState, AdminMode, ControlMode, HealthState, SimulationMode, TestMode + ObsState, + AdminMode, + ControlMode, + HealthState, + SimulationMode, + TestMode, ) from ska_tango_base.csp import ( - CspSubElementObsStateModel, ReferenceCspObsComponentManager + CspSubElementObsStateModel, + ReferenceCspObsComponentManager, ) + # PROTECTED REGION END # // CspSubElementObsDevice.test_additional_imports @@ -33,6 +40,7 @@ from ska_tango_base.csp import ( # PROTECTED REGION ID(CspSubElementObsDevice.test_CspSubelementObsDevice_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementObsDevice.test_CspSubelementObsDevice_decorators + @pytest.fixture def csp_subelement_obsdevice_state_model(logger): """ @@ -52,7 +60,7 @@ class TestCspSubElementObsDevice(object): Fixture that returns device_properties to be provided to the device under test. """ - return {'DeviceID': '11'} + return {"DeviceID": "11"} @pytest.fixture(scope="class") def device_test_config(self, device_properties): @@ -73,7 +81,6 @@ class TestCspSubElementObsDevice(object): "memorized": {"adminMode": str(AdminMode.ONLINE.value)}, } - # PROTECTED REGION ID(CspSubelementObsDevice.test_State_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementObsDevice.test_State_decorators def test_State(self, tango_context): @@ -96,8 +103,8 @@ class TestCspSubElementObsDevice(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(CspSubelementObsDevice.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -109,8 +116,9 @@ class TestCspSubElementObsDevice(object): """Test for buildState""" # PROTECTED REGION ID(CspSubelementObsDevice.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // CspSubelementObsDevice.test_buildState @@ -119,7 +127,7 @@ class TestCspSubElementObsDevice(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(CspSubelementObsDevice.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // CspSubelementObsDevice.test_versionId @@ -179,7 +187,7 @@ class TestCspSubElementObsDevice(object): def test_deviceID(self, tango_context, device_properties): """Test for deviceID""" # PROTECTED REGION ID(CspSubelementObsDevice.test_scanID) ENABLED START # - assert tango_context.device.deviceID == int(device_properties['DeviceID']) + assert tango_context.device.deviceID == int(device_properties["DeviceID"]) # PROTECTED REGION END # // CspSubelementObsDevice.test_scanID # PROTECTED REGION ID(CspSubelementObsDevice.test_sdpDestinationAddresses_decorators) ENABLED START # @@ -187,14 +195,16 @@ class TestCspSubElementObsDevice(object): def test_sdpDestinationAddresses(self, tango_context): """Test for sdpDestinationAddresses""" # PROTECTED REGION ID(CspSubelementObsDevice.test_sdpDestinationAddresses) ENABLED START # - addresses_dict = {'outputHost': [], 'outputMac': [], 'outputPort': []} - assert tango_context.device.sdpDestinationAddresses == json.dumps(addresses_dict) + addresses_dict = {"outputHost": [], "outputMac": [], "outputPort": []} + assert tango_context.device.sdpDestinationAddresses == json.dumps( + addresses_dict + ) # PROTECTED REGION END # // CspSubelementObsDevice.test_sdpDestinationAddresses # PROTECTED REGION ID(CspSubelementObsDevice.test_sdpLinkActive_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementObsDevice.test_sdpLinkActive_decorators def test_sdpLinkActivity(self, tango_context): - """Test for sdpLinkActive """ + """Test for sdpLinkActive""" # PROTECTED REGION ID(CspSubelementObsDevice.test_sdpLinkActive) ENABLED START # actual = tango_context.device.sdpLinkActive n_links = len(actual) @@ -205,7 +215,7 @@ class TestCspSubElementObsDevice(object): # PROTECTED REGION ID(CspSubelementObsDevice.test_sdpLinkCapacity_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementObsDevice.test_sdpLinkCapacity_decorators def test_sdpLinkCapacity(self, tango_context): - """Test for sdpLinkCapacity """ + """Test for sdpLinkCapacity""" # PROTECTED REGION ID(CspSubelementObsDevice.test_sdpLinkCapacity) ENABLED START # assert tango_context.device.sdpLinkCapacity == 0 # PROTECTED REGION END # // CspSubelementObsDevice.test_sdpLinkCapacity @@ -213,9 +223,9 @@ class TestCspSubElementObsDevice(object): # PROTECTED REGION ID(CspSubelementObsDevice.test_healthFailureMessage_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementObsDevice.test_healthFailureMessage_decorators def test_healthFailureMessage(self, tango_context): - """Test for healthFailureMessage """ + """Test for healthFailureMessage""" # PROTECTED REGION ID(CspSubelementObsDevice.test_healthFailureMessage) ENABLED START # - assert tango_context.device.healthFailureMessage == '' + assert tango_context.device.healthFailureMessage == "" # PROTECTED REGION END # // CspSubelementObsDevice.test_healthFailureMessage # PROTECTED REGION ID(CspSubelementObsDevice.test_ConfigureScan_decorators) ENABLED START # @@ -230,7 +240,9 @@ class TestCspSubElementObsDevice(object): obs_state_callback = tango_change_event_helper.subscribe("obsState") scan_configuration = '{"id":"sbi-mvp01-20200325-00002"}' device_under_test.ConfigureScan(scan_configuration) - obs_state_callback.assert_calls([ObsState.IDLE, ObsState.CONFIGURING, ObsState.READY]) + obs_state_callback.assert_calls( + [ObsState.IDLE, ObsState.CONFIGURING, ObsState.READY] + ) assert device_under_test.obsState == ObsState.READY assert device_under_test.configurationID == "sbi-mvp01-20200325-00002" assert device_under_test.lastScanConfiguration == scan_configuration @@ -252,7 +264,7 @@ class TestCspSubElementObsDevice(object): # PROTECTED REGION END # // CspSubelementObsDevice.test_ConfigureScan_with_wrong_input_args_decorators def test_ConfigureScan_with_wrong_input_args(self, tango_context): """Test for ConfigureScan when input argument specifies a wrong json configuration - and the device is in IDLE state. + and the device is in IDLE state. """ # PROTECTED REGION ID(CspSubelementObsDevice.test_ConfigureScan_with_wrong_input_args_when_idle) ENABLED START # tango_context.device.On() @@ -268,7 +280,7 @@ class TestCspSubElementObsDevice(object): # PROTECTED REGION ID(CspSubelementObsDevice.test_ConfigureScan_with_json_syntax_error) ENABLED START # # PROTECTED REGION END # // CspSubelementObsDevice.test_ConfigureScan_with_json_syntax_error_decorators def test_ConfigureScan_with_json_syntax_error(self, tango_context): - """Test for ConfigureScan when syntax error in json configuration """ + """Test for ConfigureScan when syntax error in json configuration""" # PROTECTED REGION ID(CspSubelementObsDevice.test_ConfigureScan_with_json_syntax_error) ENABLED START # tango_context.device.On() assert tango_context.device.obsState == ObsState.IDLE @@ -287,11 +299,12 @@ class TestCspSubElementObsDevice(object): obs_state_callback = tango_change_event_helper.subscribe("obsState") tango_context.device.ConfigureScan('{"id":"sbi-mvp01-20200325-00002"}') obs_state_callback.assert_calls( - [ObsState.IDLE, ObsState.CONFIGURING, ObsState.READY]) + [ObsState.IDLE, ObsState.CONFIGURING, ObsState.READY] + ) tango_context.device.GoToIdle() obs_state_callback.assert_call(ObsState.IDLE) assert tango_context.device.scanID == 0 - assert tango_context.device.configurationID == '' + assert tango_context.device.configurationID == "" # PROTECTED REGION END # // CspSubelementObsDevice.test_GoToIdle # PROTECTED REGION ID(CspSubelementObsDevice.test_GoToIdle_when_in_wrong_state_decorators) ENABLED START # @@ -302,7 +315,7 @@ class TestCspSubElementObsDevice(object): # The device in in OFF/IDLE state, not valid to invoke GoToIdle. with pytest.raises(DevFailed, match="Command not permitted by state model."): tango_context.device.GoToIdle() - + # PROTECTED REGION END # // CspSubelementObsDevice.test_GoToIdle_when_in_wrong_state # PROTECTED REGION ID(CspSubelementObsDevice.test_Scan_decorators) ENABLED START # @@ -313,7 +326,7 @@ class TestCspSubElementObsDevice(object): tango_context.device.On() tango_context.device.ConfigureScan('{"id":"sbi-mvp01-20200325-00002"}') obs_state_callback = tango_change_event_helper.subscribe("obsState") - tango_context.device.Scan('1') + tango_context.device.Scan("1") obs_state_callback.assert_calls([ObsState.READY, ObsState.SCANNING]) assert tango_context.device.scanID == 1 # PROTECTED REGION END # // CspSubelementObsDevice.test_Scan @@ -326,18 +339,18 @@ class TestCspSubElementObsDevice(object): # Set the device in ON/IDLE state tango_context.device.On() with pytest.raises(DevFailed, match="Command not permitted by state model."): - tango_context.device.Scan('32') + tango_context.device.Scan("32") # PROTECTED REGION END # // CspSubelementObsDevice.test_Scan_when_in_wrong_state # PROTECTED REGION ID(CspSubelementObsDevice.test_Scan_with_wrong_argument_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementObsDevice.test_Scan_with_wrong_argument_decorators def test_Scan_with_wrong_argument(self, tango_context): - """Test for Scan when a wrong input argument is passed. """ + """Test for Scan when a wrong input argument is passed.""" # PROTECTED REGION ID(CspSubelementObsDevice.test_Scan_with_wrong_argument) ENABLED START # # Set the device in ON/IDLE state tango_context.device.On() tango_context.device.ConfigureScan('{"id":"sbi-mvp01-20200325-00002"}') - (result_code, _) = tango_context.device.Scan('abc') + (result_code, _) = tango_context.device.Scan("abc") assert result_code == ResultCode.FAILED assert tango_context.device.obsState == ObsState.READY # PROTECTED REGION END # // CspSubelementObsDevice.test_Scan_with_wrong_argument @@ -351,7 +364,7 @@ class TestCspSubElementObsDevice(object): tango_context.device.ConfigureScan('{"id":"sbi-mvp01-20200325-00002"}') obs_state_callback = tango_change_event_helper.subscribe("obsState") obs_state_callback.assert_call(ObsState.READY) - tango_context.device.Scan('1') + tango_context.device.Scan("1") obs_state_callback.assert_call(ObsState.SCANNING) tango_context.device.EndScan() obs_state_callback.assert_call(ObsState.READY) @@ -367,7 +380,7 @@ class TestCspSubElementObsDevice(object): tango_context.device.ConfigureScan('{"id":"sbi-mvp01-20200325-00002"}') with pytest.raises(DevFailed, match="Command not permitted by state model."): tango_context.device.EndScan() - + # PROTECTED REGION END # // CspSubelementObsDevice.test_EndScan_when_in_wrong_state # PROTECTED REGION ID(CspSubelementObsDevice.test_ObsReset_decorators) ENABLED START # @@ -406,7 +419,8 @@ class TestCspSubElementObsDevice(object): obs_state_callback = tango_change_event_helper.subscribe("obsState") tango_context.device.Abort() obs_state_callback.assert_calls( - [ObsState.READY, ObsState.ABORTING, ObsState.ABORTED]) + [ObsState.READY, ObsState.ABORTING, ObsState.ABORTED] + ) # PROTECTED REGION END # // CspSubelementObsDevice.test_Abort diff --git a/tests/test_csp_subarray.py b/tests/test_csp_subarray.py index ad33e26ea5628f4dc2cfe4fc3f7a7cfa5689e088..22cffd03e0fe3d5516d496f8612ddba8dd1270f2 100644 --- a/tests/test_csp_subarray.py +++ b/tests/test_csp_subarray.py @@ -19,11 +19,18 @@ from tango import DevState, DevFailed # PROTECTED REGION ID(CspSubelementSubarray.test_additional_imports) ENABLED START # from ska_tango_base.commands import ResultCode from ska_tango_base.control_model import ( - ObsState, AdminMode, ControlMode, HealthState, SimulationMode, TestMode + ObsState, + AdminMode, + ControlMode, + HealthState, + SimulationMode, + TestMode, ) from ska_tango_base.csp import ( - CspSubElementSubarray, ReferenceCspSubarrayComponentManager + CspSubElementSubarray, + ReferenceCspSubarrayComponentManager, ) + # PROTECTED REGION END # // CspSubElementSubarray.test_additional_imports @@ -31,6 +38,7 @@ from ska_tango_base.csp import ( # PROTECTED REGION ID(CspSubElementSubarray.test_CspSubelementSubarray_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_CspSubelementSubarray_decorators + class TestCspSubElementSubarray(object): """Test case for CSP SubElement Subarray class.""" @@ -58,7 +66,7 @@ class TestCspSubElementSubarray(object): self.op_state_model, self.obs_state_model, self.CapabilityTypes, - logger=self.logger + logger=self.logger, ), "properties": device_properties, "memorized": {"adminMode": str(AdminMode.ONLINE.value)}, @@ -93,8 +101,8 @@ class TestCspSubElementSubarray(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(CspSubelementSubarray.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -105,8 +113,9 @@ class TestCspSubElementSubarray(object): """Test for buildState""" # PROTECTED REGION ID(CspSubelementSubarray.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // CspSubelementSubarray.test_buildState @@ -115,7 +124,7 @@ class TestCspSubElementSubarray(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(CspSubelementSubarray.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // CspSubelementSubarray.test_versionId @@ -174,15 +183,17 @@ class TestCspSubElementSubarray(object): def test_sdpDestinationAddresses(self, tango_context): """Test for sdpDestinationAddresses""" # PROTECTED REGION ID(CspSubelementSubarray.test_sdpDestinationAddresses) ENABLED START # - addresses_dict = {'outputHost': [], 'outputMac': [], 'outputPort': []} + addresses_dict = {"outputHost": [], "outputMac": [], "outputPort": []} tango_context.device.sdpDestinationAddresses = json.dumps(addresses_dict) - assert tango_context.device.sdpDestinationAddresses == json.dumps(addresses_dict) + assert tango_context.device.sdpDestinationAddresses == json.dumps( + addresses_dict + ) # PROTECTED REGION END # // CspSubelementSubarray.test_sdpDestinationAddresses # PROTECTED REGION ID(CspSubelementSubarray.test_sdpLinkActive_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_sdpLinkActive_decorators def test_sdpLinkActivity(self, tango_context): - """Test for sdpLinkActive """ + """Test for sdpLinkActive""" # PROTECTED REGION ID(CspSubelementSubarray.test_sdpLinkActive) ENABLED START # actual = tango_context.device.sdpLinkActive n_links = len(actual) @@ -193,7 +204,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_outputDataRateToSdp_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_outputDataRateToSdp_decorators def test_outputDataRateToSdp(self, tango_context): - """Test for outputDataRateToSdp """ + """Test for outputDataRateToSdp""" # PROTECTED REGION ID(CspSubelementSubarray.test_outputDataRateToSdp) ENABLED START # assert tango_context.device.outputDataRateToSdp == 0 # PROTECTED REGION END # // CspSubelementSubarray.test_outputDataRateToSdp @@ -201,9 +212,11 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_listOfDevicesCompletedTasks_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_listOfDevicesCompletedTasks_decorators def test_listOfDevicesCompletedTasks(self, tango_context): - """Test for listOfDevicesCompletedTasks """ + """Test for listOfDevicesCompletedTasks""" # PROTECTED REGION ID(CspSubelementSubarray.test_listOfDevicesCompletedTasks) ENABLED START # - attr_value_as_dict = json.loads(tango_context.device.listOfDevicesCompletedTasks) + attr_value_as_dict = json.loads( + tango_context.device.listOfDevicesCompletedTasks + ) assert not bool(attr_value_as_dict) # PROTECTED REGION END # // CspSubelementSubarray.test_listOfDevicesCompletedTasks @@ -213,7 +226,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_assignResourcesMaximumDuration_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_assignResourcesMaximumDuration_decorators def test_assignResourcesMaximumDuration(self, tango_context): - """Test for assignResourcesMaximumDuration """ + """Test for assignResourcesMaximumDuration""" # PROTECTED REGION ID(CspSubelementSubarray.test_assignResourcesMaximumDuration) ENABLED START # tango_context.device.assignResourcesMaximumDuration = 5 assert tango_context.device.assignResourcesMaximumDuration == 5 @@ -222,7 +235,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_configureScanMeasuredDuration_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_configureScanMeasuredDuration_decorators def test_configureScanMeasuredDuration(self, tango_context): - """Test for configureScanMeasuredDuration """ + """Test for configureScanMeasuredDuration""" # PROTECTED REGION ID(CspSubelementSubarray.test_configureScanMeasuredDuration) ENABLED START # assert tango_context.device.configureScanMeasuredDuration == 0 # PROTECTED REGION END # // CspSubelementSubarray.test_configureScanMeasuredDuration @@ -230,7 +243,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_configurationProgress_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_configurationProgress_decorators def test_configurationProgress(self, tango_context): - """Test for configurationProgress """ + """Test for configurationProgress""" # PROTECTED REGION ID(CspSubelementSubarray.test_configurationProgress) ENABLED START # assert tango_context.device.configurationProgress == 0 # PROTECTED REGION END # // CspSubelementSubarray.test_configurationProgress @@ -238,7 +251,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_assignResourcesMeasuredDuration_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_assignResourcesMeasuredDuration_decorators def test_assignResourcesMeasuredDuration(self, tango_context): - """Test for assignResourcesMeasuredDuration """ + """Test for assignResourcesMeasuredDuration""" # PROTECTED REGION ID(CspSubelementSubarray.test_assignResourcesMeasuredDuration) ENABLED START # assert tango_context.device.assignResourcesMeasuredDuration == 0 # PROTECTED REGION END # // CspSubelementSubarray.test_assignResourcesMeasuredDuration @@ -246,7 +259,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_assignResourcesProgress_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_assignResourcesProgress_decorators def test_assignResourcesProgress(self, tango_context): - """Test for assignResourcesProgress """ + """Test for assignResourcesProgress""" # PROTECTED REGION ID(CspSubelementSubarray.test_assignResourcesProgress) ENABLED START # assert tango_context.device.assignResourcesProgress == 0 # PROTECTED REGION END # // CspSubelementSubarray.test_assignResourcesProgress @@ -254,7 +267,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_releaseResourcesMaximumDuration_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_releaseResourcesMaximumDuration_decorators def test_releaseResourcesMaximumDuration(self, tango_context): - """Test for releaseResourcesMaximumDuration """ + """Test for releaseResourcesMaximumDuration""" # PROTECTED REGION ID(CspSubelementSubarray.test_releaseResourcesMaximumDuration) ENABLED START # tango_context.device.releaseResourcesMaximumDuration = 5 assert tango_context.device.releaseResourcesMaximumDuration == 5 @@ -263,7 +276,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_releaseResourcesMeasuredDuration_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_releaseResourcesMeasuredDuration_decorators def test_releaseResourcesMeasuredDuration(self, tango_context): - """Test for releaseResourcesMeasuredDuration """ + """Test for releaseResourcesMeasuredDuration""" # PROTECTED REGION ID(CspSubelementSubarray.test_releaseResourcesMeasuredDuration) ENABLED START # assert tango_context.device.releaseResourcesMeasuredDuration == 0 # PROTECTED REGION END # // CspSubelementSubarray.test_releaseResourcesMeasuredDuration @@ -271,7 +284,7 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_releaseResourcesProgress_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_releaseResourcesProgress_decorators def test_releaseResourcesProgress(self, tango_context): - """Test for releaseResourcesProgress """ + """Test for releaseResourcesProgress""" # PROTECTED REGION ID(CspSubelementSubarray.test_releaseResourcesProgress) ENABLED START # assert tango_context.device.releaseResourcesProgress == 0 # PROTECTED REGION END # // CspSubelementSubarray.test_releaseResourcesProgress @@ -279,42 +292,46 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_timeoutExpiredFlag_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_timeoutExpiredFlag_decorators def test_configureScanTimeoutExpiredFlag(self, tango_context): - """Test for timeoutExpiredFlag """ + """Test for timeoutExpiredFlag""" # PROTECTED REGION ID(CspSubelementSubarray.test_timeoutExpiredFlag) ENABLED START # - assert tango_context.device.configureScanTimeoutExpiredFlag == False + assert not tango_context.device.configureScanTimeoutExpiredFlag # PROTECTED REGION END # // CspSubelementSubarray.test_timeoutExpiredFlag # PROTECTED REGION ID(CspSubelementSubarray.test_timeoutExpiredFlag_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_timeoutExpiredFlag_decorators def test_assignResourcesTimeoutExpiredFlag(self, tango_context): - """Test for timeoutExpiredFlag """ + """Test for timeoutExpiredFlag""" # PROTECTED REGION ID(CspSubelementSubarray.test_timeoutExpiredFlag) ENABLED START # - assert tango_context.device.assignResourcesTimeoutExpiredFlag == False + assert not tango_context.device.assignResourcesTimeoutExpiredFlag # PROTECTED REGION END # // CspSubelementSubarray.test_timeoutExpiredFlag # PROTECTED REGION ID(CspSubelementSubarray.test_timeoutExpiredFlag_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_timeoutExpiredFlag_decorators def test_releaseResourcesTimeoutExpiredFlag(self, tango_context): - """Test for timeoutExpiredFlag """ + """Test for timeoutExpiredFlag""" # PROTECTED REGION ID(CspSubelementSubarray.test_timeoutExpiredFlag) ENABLED START # - assert tango_context.device.releaseResourcesTimeoutExpiredFlag == False + assert not tango_context.device.releaseResourcesTimeoutExpiredFlag # PROTECTED REGION END # // CspSubelementSubarray.test_timeoutExpiredFlag # PROTECTED REGION ID(CspSubelementSubarray.test_ConfigureScan_decorators) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_ConfigureScan_decorators @pytest.mark.parametrize("command_alias", ["Configure", "ConfigureScan"]) - def test_ConfigureScan(self, tango_context, tango_change_event_helper, command_alias): + def test_ConfigureScan( + self, tango_context, tango_change_event_helper, command_alias + ): """Test for ConfigureScan""" # PROTECTED REGION ID(CspSubelementSubarray.test_ConfigureScan) ENABLED START # device_under_test = tango_context.device device_under_test.On() - device_under_test.AssignResources(json.dumps([1,2,3])) + device_under_test.AssignResources(json.dumps([1, 2, 3])) assert device_under_test.obsState == ObsState.IDLE obs_state_callback = tango_change_event_helper.subscribe("obsState") scan_configuration = '{"id":"sbi-mvp01-20200325-00002"}' device_under_test.command_inout(command_alias, scan_configuration) - obs_state_callback.assert_calls([ObsState.IDLE, ObsState.CONFIGURING, ObsState.READY]) + obs_state_callback.assert_calls( + [ObsState.IDLE, ObsState.CONFIGURING, ObsState.READY] + ) assert device_under_test.obsState == ObsState.READY assert tango_context.device.configurationID == "sbi-mvp01-20200325-00002" assert tango_context.device.lastScanConfiguration == scan_configuration @@ -334,11 +351,11 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION END # // CspSubelementSubarray.test_ConfigureScan_with_wrong_configId_key_decorators def test_ConfigureScan_with_wrong_configId_key(self, tango_context): """Test for ConfigureScan when json configuration specifies a wrong key for - configuration ID + configuration ID """ # PROTECTED REGION ID(CspSubelementSubarray.test_ConfigureScan_with_wrong_configId_key) ENABLED START # tango_context.device.On() - tango_context.device.AssignResources(json.dumps([1,2,3])) + tango_context.device.AssignResources(json.dumps([1, 2, 3])) # wrong configurationID key assert tango_context.device.obsState == ObsState.IDLE @@ -351,10 +368,10 @@ class TestCspSubElementSubarray(object): # PROTECTED REGION ID(CspSubelementSubarray.test_ConfigureScan_with_json_syntax_error) ENABLED START # # PROTECTED REGION END # // CspSubelementSubarray.test_ConfigureScan_with_json_syntax_error_decorators def test_ConfigureScan_with_json_syntax_error(self, tango_context): - """Test for ConfigureScan when syntax error in json configuration """ + """Test for ConfigureScan when syntax error in json configuration""" # PROTECTED REGION ID(CspSubelementSubarray.test_ConfigureScan_with_json_syntax_error) ENABLED START # tango_context.device.On() - tango_context.device.AssignResources(json.dumps([1,2,3])) + tango_context.device.AssignResources(json.dumps([1, 2, 3])) assert tango_context.device.obsState == ObsState.IDLE result_code, _ = tango_context.device.ConfigureScan('{"foo": 1,}') @@ -369,13 +386,14 @@ class TestCspSubElementSubarray(object): """Test for GoToIdle""" # PROTECTED REGION ID(CspSubelementSubarray.test_GoToIdle) ENABLED START # tango_context.device.On() - tango_context.device.AssignResources(json.dumps([1,2,3])) + tango_context.device.AssignResources(json.dumps([1, 2, 3])) obs_state_callback = tango_change_event_helper.subscribe("obsState") tango_context.device.ConfigureScan('{"id":"sbi-mvp01-20200325-00002"}') obs_state_callback.assert_calls( - [ObsState.IDLE, ObsState.CONFIGURING, ObsState.READY]) + [ObsState.IDLE, ObsState.CONFIGURING, ObsState.READY] + ) tango_context.device.command_inout(command_alias) obs_state_callback.assert_call(ObsState.IDLE) assert tango_context.device.scanID == 0 - assert tango_context.device.configurationID == '' + assert tango_context.device.configurationID == "" # PROTECTED REGION END # // CspSubelementSubarray.test_GoToIdle diff --git a/tests/test_csp_subarray_component_manager.py b/tests/test_csp_subarray_component_manager.py index 589d1ffd561d73d4c8afa09f9d2d4ec128f8be1c..3caa84f5664395e787021d8a7791c799b4f7db46 100644 --- a/tests/test_csp_subarray_component_manager.py +++ b/tests/test_csp_subarray_component_manager.py @@ -136,7 +136,9 @@ class TestCspSubelementSubarrayComponentManager: "component_disconnected" ) - def test_simulate_communication_failure(self, component_manager, mock_op_state_model): + def test_simulate_communication_failure( + self, component_manager, mock_op_state_model + ): """ Test that we can simulate connection failure. diff --git a/tests/test_logger_device.py b/tests/test_logger_device.py index ea85f8571d41a26a52367b87844516c02332d021..9d818b86a7daa5558c49d73a26208235e0d52b89 100644 --- a/tests/test_logger_device.py +++ b/tests/test_logger_device.py @@ -82,8 +82,8 @@ class TestSKALogger(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(SKALogger.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None diff --git a/tests/test_master_device.py b/tests/test_master_device.py index 49d8dbab79ebfadc194dcd69910c7e172f4c39d1..35e67215c6bbc51a4a9f894c18bd78701e10119c 100644 --- a/tests/test_master_device.py +++ b/tests/test_master_device.py @@ -15,7 +15,14 @@ from tango import DevState # PROTECTED REGION ID(SKAMaster.test_additional_imports) ENABLED START # from ska_tango_base import SKAMaster from ska_tango_base.base import ReferenceBaseComponentManager -from ska_tango_base.control_model import AdminMode, ControlMode, HealthState, SimulationMode, TestMode +from ska_tango_base.control_model import ( + AdminMode, + ControlMode, + HealthState, + SimulationMode, + TestMode, +) + # PROTECTED REGION END # // SKAMaster.test_additional_imports @@ -36,12 +43,12 @@ class TestSKAMaster(object): device under test. """ return { - 'SkaLevel': '4', - 'LoggingTargetsDefault': '', - 'GroupDefinitions': '', - 'NrSubarrays': '16', - 'CapabilityTypes': '', - 'MaxCapabilities': ['BAND1:1', 'BAND2:1'] + "SkaLevel": "4", + "LoggingTargetsDefault": "", + "GroupDefinitions": "", + "NrSubarrays": "16", + "CapabilityTypes": "", + "MaxCapabilities": ["BAND1:1", "BAND2:1"], } @pytest.fixture(scope="class") @@ -63,8 +70,6 @@ class TestSKAMaster(object): "memorized": {"adminMode": str(AdminMode.ONLINE.value)}, } - - @pytest.mark.skip("Not implemented") def test_properties(self, tango_context): # Test the properties @@ -94,8 +99,8 @@ class TestSKAMaster(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(SKAMaster.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -106,15 +111,16 @@ class TestSKAMaster(object): def test_isCapabilityAchievable_failure(self, tango_context): """Test for isCapabilityAchievable to test failure condition""" # PROTECTED REGION ID(SKAMaster.test_isCapabilityAchievable_failure) ENABLED START # - assert tango_context.device.isCapabilityAchievable([[2], ['BAND1']]) is False + assert tango_context.device.isCapabilityAchievable([[2], ["BAND1"]]) is False # PROTECTED REGION END # // SKAMaster.test_isCapabilityAchievable_failure # PROTECTED REGION ID(SKAMaster.test_isCapabilityAchievable_success_decorators) ENABLED START # # PROTECTED REGION END # // SKAMaster.test_isCapabilityAchievable_success_decorators + def test_isCapabilityAchievable_success(self, tango_context): """Test for isCapabilityAchievable to test success condition""" # PROTECTED REGION ID(SKAMaster.test_isCapabilityAchievable_success) ENABLED START # - assert tango_context.device.isCapabilityAchievable([[1], ['BAND1']]) is True + assert tango_context.device.isCapabilityAchievable([[1], ["BAND1"]]) is True # PROTECTED REGION END # // SKAMaster.test_isCapabilityAchievable_success # PROTECTED REGION ID(SKAMaster.test_elementLoggerAddress_decorators) ENABLED START # @@ -122,7 +128,7 @@ class TestSKAMaster(object): def test_elementLoggerAddress(self, tango_context): """Test for elementLoggerAddress""" # PROTECTED REGION ID(SKAMaster.test_elementLoggerAddress) ENABLED START # - assert tango_context.device.elementLoggerAddress == '' + assert tango_context.device.elementLoggerAddress == "" # PROTECTED REGION END # // SKAMaster.test_elementLoggerAddress # PROTECTED REGION ID(SKAMaster.test_elementAlarmAddress_decorators) ENABLED START # @@ -130,7 +136,7 @@ class TestSKAMaster(object): def test_elementAlarmAddress(self, tango_context): """Test for elementAlarmAddress""" # PROTECTED REGION ID(SKAMaster.test_elementAlarmAddress) ENABLED START # - assert tango_context.device.elementAlarmAddress == '' + assert tango_context.device.elementAlarmAddress == "" # PROTECTED REGION END # // SKAMaster.test_elementAlarmAddress # PROTECTED REGION ID(SKAMaster.test_elementTelStateAddress_decorators) ENABLED START # @@ -138,7 +144,7 @@ class TestSKAMaster(object): def test_elementTelStateAddress(self, tango_context): """Test for elementTelStateAddress""" # PROTECTED REGION ID(SKAMaster.test_elementTelStateAddress) ENABLED START # - assert tango_context.device.elementTelStateAddress == '' + assert tango_context.device.elementTelStateAddress == "" # PROTECTED REGION END # // SKAMaster.test_elementTelStateAddress # PROTECTED REGION ID(SKAMaster.test_elementDatabaseAddress_decorators) ENABLED START # @@ -146,7 +152,7 @@ class TestSKAMaster(object): def test_elementDatabaseAddress(self, tango_context): """Test for elementDatabaseAddress""" # PROTECTED REGION ID(SKAMaster.test_elementDatabaseAddress) ENABLED START # - assert tango_context.device.elementDatabaseAddress == '' + assert tango_context.device.elementDatabaseAddress == "" # PROTECTED REGION END # // SKAMaster.test_elementDatabaseAddress # PROTECTED REGION ID(SKAMaster.test_buildState_decorators) ENABLED START # @@ -155,11 +161,10 @@ class TestSKAMaster(object): """Test for buildState""" # PROTECTED REGION ID(SKAMaster.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') - assert ( - re.match(buildPattern, tango_context.device.buildState) - ) is not None + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) + assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // SKAMaster.test_buildState # PROTECTED REGION ID(SKAMaster.test_versionId_decorators) ENABLED START # @@ -167,10 +172,8 @@ class TestSKAMaster(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(SKAMaster.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') - assert ( - re.match(versionIdPattern, tango_context.device.versionId) - ) is not None + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") + assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // SKAMaster.test_versionId # PROTECTED REGION ID(SKAMaster.test_healthState_decorators) ENABLED START # @@ -218,7 +221,7 @@ class TestSKAMaster(object): def test_maxCapabilities(self, tango_context): """Test for maxCapabilities""" # PROTECTED REGION ID(SKAMaster.test_maxCapabilities) ENABLED START # - assert tango_context.device.maxCapabilities == ('BAND1:1', 'BAND2:1') + assert tango_context.device.maxCapabilities == ("BAND1:1", "BAND2:1") # PROTECTED REGION END # // SKAMaster.test_maxCapabilities # PROTECTED REGION ID(SKAMaster.test_availableCapabilities_decorators) ENABLED START # @@ -226,5 +229,5 @@ class TestSKAMaster(object): def test_availableCapabilities(self, tango_context): """Test for availableCapabilities""" # PROTECTED REGION ID(SKAMaster.test_availableCapabilities) ENABLED START # - assert tango_context.device.availableCapabilities == ('BAND1:1', 'BAND2:1') + assert tango_context.device.availableCapabilities == ("BAND1:1", "BAND2:1") # PROTECTED REGION END # // SKAMaster.test_availableCapabilities diff --git a/tests/test_obs_device.py b/tests/test_obs_device.py index 02eb54320f220a07934323072661467800ff9322..59388f949dd45f0f98ce6e432a72f2b37ff1d71c 100644 --- a/tests/test_obs_device.py +++ b/tests/test_obs_device.py @@ -19,8 +19,15 @@ from tango.test_context import MultiDeviceTestContext from ska_tango_base import SKABaseDevice, SKAObsDevice from ska_tango_base.base import ReferenceBaseComponentManager from ska_tango_base.control_model import ( - AdminMode, ControlMode, HealthState, ObsMode, ObsState, SimulationMode, TestMode + AdminMode, + ControlMode, + HealthState, + ObsMode, + ObsState, + SimulationMode, + TestMode, ) + # PROTECTED REGION END # // SKAObsDevice.test_additional_imports @@ -52,7 +59,6 @@ class TestSKAObsDevice(object): "memorized": {"adminMode": str(AdminMode.ONLINE.value)}, } - @pytest.mark.skip("Not implemented") def test_properties(self, tango_context): # Test the properties @@ -82,8 +88,8 @@ class TestSKAObsDevice(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(SKAObsDevice.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -132,8 +138,9 @@ class TestSKAObsDevice(object): """Test for buildState""" # PROTECTED REGION ID(SKAObsDevice.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // SKAObsDevice.test_buildState @@ -142,7 +149,7 @@ class TestSKAObsDevice(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(SKAObsDevice.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // SKAObsDevice.test_versionId diff --git a/tests/test_subarray_component_manager.py b/tests/test_subarray_component_manager.py index ee9e0c8a5e4d4adf22ff66b57d04031e7dd02faa..f41d47cf3a8104aea700a1e92058e4bb1d0d6661 100644 --- a/tests/test_subarray_component_manager.py +++ b/tests/test_subarray_component_manager.py @@ -206,7 +206,7 @@ class TestSubarrayComponentManager: mock_op_state_model, mock_obs_state_model, initial_power_mode, - initial_fault + initial_fault, ): """ Test that the state model is updated with state changes when the @@ -257,7 +257,9 @@ class TestSubarrayComponentManager: "component_disconnected" ) - def test_simulate_communication_failure(self, component_manager, mock_op_state_model): + def test_simulate_communication_failure( + self, component_manager, mock_op_state_model + ): """ Test that we can simulate connection failure. diff --git a/tests/test_subarray_device.py b/tests/test_subarray_device.py index 95a9c3c4589b1f71a384d1ed789630d6832a2582..34d5fdedc9c9c40606ab974695bec0378125afd7 100644 --- a/tests/test_subarray_device.py +++ b/tests/test_subarray_device.py @@ -29,8 +29,10 @@ from ska_tango_base.control_model import ( ) from ska_tango_base.faults import CommandError from ska_tango_base.subarray import ( - ReferenceSubarrayComponentManager, SubarrayObsStateModel + ReferenceSubarrayComponentManager, + SubarrayObsStateModel, ) + # PROTECTED REGION END # // SKASubarray.test_additional_imports @@ -47,10 +49,10 @@ class TestSKASubarray: """ return { "CapabilityTypes": ["BAND1", "BAND2"], - 'LoggingTargetsDefault': '', - 'GroupDefinitions': '', - 'SkaLevel': '4', - 'SubID': '1', + "LoggingTargetsDefault": "", + "GroupDefinitions": "", + "SkaLevel": "4", + "SubID": "1", } @pytest.fixture(scope="class") @@ -96,11 +98,10 @@ class TestSKASubarray: obs_state_callback.assert_call(ObsState.READY) assert tango_context.device.Abort() == [ - [ResultCode.OK], ["Abort command completed OK"] + [ResultCode.OK], + ["Abort command completed OK"], ] - obs_state_callback.assert_calls( - [ObsState.ABORTING, ObsState.ABORTED] - ) + obs_state_callback.assert_calls([ObsState.ABORTING, ObsState.ABORTED]) # PROTECTED REGION END # // SKASubarray.test_Abort # PROTECTED REGION ID(SKASubarray.test_Configure_decorators) ENABLED START # @@ -116,9 +117,7 @@ class TestSKASubarray: tango_context.device.Configure('{"BAND1": 2}') - obs_state_callback.assert_calls( - [ObsState.CONFIGURING, ObsState.READY] - ) + obs_state_callback.assert_calls([ObsState.CONFIGURING, ObsState.READY]) assert tango_context.device.obsState == ObsState.READY assert tango_context.device.configuredCapabilities == ("BAND1:2", "BAND2:0") # PROTECTED REGION END # // SKASubarray.test_Configure @@ -129,8 +128,8 @@ class TestSKASubarray: """Test for GetVersionInfo""" # PROTECTED REGION ID(SKASubarray.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -165,20 +164,16 @@ class TestSKASubarray: resources_to_assign = ["BAND1", "BAND2"] tango_context.device.AssignResources(json.dumps(resources_to_assign)) - obs_state_callback.assert_calls( - [ObsState.RESOURCING, ObsState.IDLE] - ) + obs_state_callback.assert_calls([ObsState.RESOURCING, ObsState.IDLE]) assert tango_context.device.ObsState == ObsState.IDLE assert list(tango_context.device.assignedResources) == resources_to_assign tango_context.device.ReleaseAllResources() - obs_state_callback.assert_calls( - [ObsState.RESOURCING, ObsState.EMPTY] - ) + obs_state_callback.assert_calls([ObsState.RESOURCING, ObsState.EMPTY]) assert tango_context.device.ObsState == ObsState.EMPTY with pytest.raises(DevFailed): - tango_context.device.AssignResources('Invalid JSON') + tango_context.device.AssignResources("Invalid JSON") # PROTECTED REGION END # // SKASubarray.test_AssignResources # PROTECTED REGION ID(SKASubarray.test_EndSB_decorators) ENABLED START # @@ -194,7 +189,8 @@ class TestSKASubarray: obs_state_callback.assert_call(ObsState.READY) assert tango_context.device.End() == [ - [ResultCode.OK], ["End command completed OK"] + [ResultCode.OK], + ["End command completed OK"], ] obs_state_callback.assert_call(ObsState.IDLE) @@ -214,7 +210,8 @@ class TestSKASubarray: obs_state_callback.assert_call(ObsState.SCANNING) assert tango_context.device.EndScan() == [ - [ResultCode.OK], ["EndScan command completed OK"] + [ResultCode.OK], + ["EndScan command completed OK"], ] obs_state_callback.assert_call(ObsState.READY) @@ -235,9 +232,7 @@ class TestSKASubarray: tango_context.device.ReleaseAllResources() - obs_state_callback.assert_calls( - [ObsState.RESOURCING, ObsState.EMPTY] - ) + obs_state_callback.assert_calls([ObsState.RESOURCING, ObsState.EMPTY]) assert tango_context.device.assignedResources is None # PROTECTED REGION END # // SKASubarray.test_ReleaseAllResources @@ -254,11 +249,9 @@ class TestSKASubarray: tango_context.device.ReleaseResources(json.dumps(["BAND1"])) - obs_state_callback.assert_calls( - [ObsState.RESOURCING, ObsState.IDLE] - ) + obs_state_callback.assert_calls([ObsState.RESOURCING, ObsState.IDLE]) assert tango_context.device.ObsState == ObsState.IDLE - assert tango_context.device.assignedResources == ('BAND2',) + assert tango_context.device.assignedResources == ("BAND2",) # PROTECTED REGION END # // SKASubarray.test_ReleaseResources # PROTECTED REGION ID(SKASubarray.test_Reset_decorators) ENABLED START # @@ -275,12 +268,11 @@ class TestSKASubarray: obs_state_callback.assert_call(ObsState.ABORTED) assert tango_context.device.ObsReset() == [ - [ResultCode.OK], ["ObsReset command completed OK"] + [ResultCode.OK], + ["ObsReset command completed OK"], ] - obs_state_callback.assert_calls( - [ObsState.RESETTING, ObsState.IDLE] - ) + obs_state_callback.assert_calls([ObsState.RESETTING, ObsState.IDLE]) assert tango_context.device.obsState == ObsState.IDLE # PROTECTED REGION END # // SKASubarray.test_Reset @@ -297,7 +289,8 @@ class TestSKASubarray: obs_state_callback.assert_call(ObsState.READY) assert tango_context.device.Scan('{"id": 123}') == [ - [ResultCode.STARTED], ["Scan command started"] + [ResultCode.STARTED], + ["Scan command started"], ] obs_state_callback.assert_call(ObsState.SCANNING) @@ -305,7 +298,7 @@ class TestSKASubarray: tango_context.device.EndScan() with pytest.raises(DevFailed): - tango_context.device.Scan('Invalid JSON') + tango_context.device.Scan("Invalid JSON") # PROTECTED REGION END # // SKASubarray.test_Scan # PROTECTED REGION ID(SKASubarray.test_activationTime_decorators) ENABLED START # @@ -349,8 +342,9 @@ class TestSKASubarray: """Test for buildState""" # PROTECTED REGION ID(SKASubarray.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // SKASubarray.test_buildState @@ -423,7 +417,7 @@ class TestSKASubarray: def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(SKASubarray.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // SKASubarray.test_versionId @@ -450,6 +444,7 @@ class TestSKASubarray_commands: """ This class contains tests of SKASubarray commands """ + @pytest.fixture def op_state_model(self, logger): """ @@ -476,13 +471,12 @@ class TestSKASubarray_commands: """ mock_capability_types = ["foo", "bah"] return ReferenceSubarrayComponentManager( - op_state_model, - subarray_state_model, - mock_capability_types, - logger=logger + op_state_model, subarray_state_model, mock_capability_types, logger=logger ) - def test_AssignCommand(self, component_manager, op_state_model, subarray_state_model): + def test_AssignCommand( + self, component_manager, op_state_model, subarray_state_model + ): """ Test for SKASubarray.AssignResourcesCommand """ diff --git a/tests/test_tel_state_device.py b/tests/test_tel_state_device.py index d682835c39a2680fc39fa10ee8b2b80961c2f408..c5c987a571d3badb631a7431fd14bf07bae2494c 100644 --- a/tests/test_tel_state_device.py +++ b/tests/test_tel_state_device.py @@ -15,7 +15,14 @@ from tango import DevState # PROTECTED REGION ID(SKATelState.test_additional_imports) ENABLED START # from ska_tango_base import SKATelState from ska_tango_base.base import ReferenceBaseComponentManager -from ska_tango_base.control_model import AdminMode, ControlMode, HealthState, SimulationMode, TestMode +from ska_tango_base.control_model import ( + AdminMode, + ControlMode, + HealthState, + SimulationMode, + TestMode, +) + # PROTECTED REGION END # // SKATelState.test_additional_imports @@ -42,7 +49,6 @@ class TestSKATelState(object): "memorized": {"adminMode": str(AdminMode.ONLINE.value)}, } - @pytest.mark.skip("Not implemented") def test_properties(self, tango_context): # Test the properties @@ -72,8 +78,8 @@ class TestSKATelState(object): """Test for GetVersionInfo""" # PROTECTED REGION ID(SKATelState.test_GetVersionInfo) ENABLED START # versionPattern = re.compile( - f'{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - 'A set of generic base devices for SKA Telescope.' + f"{tango_context.device.info().dev_class}, ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + "A set of generic base devices for SKA Telescope." ) versionInfo = tango_context.device.GetVersionInfo() assert (re.match(versionPattern, versionInfo[0])) is not None @@ -85,8 +91,9 @@ class TestSKATelState(object): """Test for buildState""" # PROTECTED REGION ID(SKATelState.test_buildState) ENABLED START # buildPattern = re.compile( - r'ska_tango_base, [0-9]+.[0-9]+.[0-9]+, ' - r'A set of generic base devices for SKA Telescope') + r"ska_tango_base, [0-9]+.[0-9]+.[0-9]+, " + r"A set of generic base devices for SKA Telescope" + ) assert (re.match(buildPattern, tango_context.device.buildState)) is not None # PROTECTED REGION END # // SKATelState.test_buildState @@ -95,7 +102,7 @@ class TestSKATelState(object): def test_versionId(self, tango_context): """Test for versionId""" # PROTECTED REGION ID(SKATelState.test_versionId) ENABLED START # - versionIdPattern = re.compile(r'[0-9]+.[0-9]+.[0-9]+') + versionIdPattern = re.compile(r"[0-9]+.[0-9]+.[0-9]+") assert (re.match(versionIdPattern, tango_context.device.versionId)) is not None # PROTECTED REGION END # // SKATelState.test_versionId diff --git a/tests/test_utils.py b/tests/test_utils.py index fecd8fd460c3add54f924c0f792ab455e2914792..80829884ad1cc0ec10ffed1c34b08ca3f3681ff8 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -7,121 +7,112 @@ from ska_tango_base.utils import ( get_groups_from_json, get_tango_device_type_id, GroupDefinitionsError, - for_testing_only + for_testing_only, ) TEST_GROUPS = { # Valid groups - 'basic_no_subgroups': { - 'group_name': 'g1', - 'devices': ['my/dev/1'], + "basic_no_subgroups": { + "group_name": "g1", + "devices": ["my/dev/1"], }, - 'basic_empty_subgroups': { - 'group_name': 'g2', - 'devices': ['my/dev/2'], - 'subgroups': [] + "basic_empty_subgroups": { + "group_name": "g2", + "devices": ["my/dev/2"], + "subgroups": [], }, - 'dual_level': { - 'group_name': 'g3', - 'subgroups': [ - {'group_name': 'g3-1', - 'devices': ['my/dev/3-1']} - ] + "dual_level": { + "group_name": "g3", + "subgroups": [{"group_name": "g3-1", "devices": ["my/dev/3-1"]}], }, - 'multi_level': { - 'group_name': 'data_centre_1', - 'devices': ['dc1/aircon/1', 'dc1/aircon/2'], - 'subgroups': [ - {'group_name': 'racks', - 'subgroups': [ - {'group_name': 'rackA', - 'devices': ['dc1/server/1', 'dc1/server/2', - 'dc1/switch/A', 'dc1/pdu/rackA']}, - {'group_name': 'rackB', - 'devices': ['dc1/server/3', 'dc1/server/4', - 'dc1/switch/B', 'dc1/pdu/rackB'], - 'subgroups': []}, - ]}, - ] + "multi_level": { + "group_name": "data_centre_1", + "devices": ["dc1/aircon/1", "dc1/aircon/2"], + "subgroups": [ + { + "group_name": "racks", + "subgroups": [ + { + "group_name": "rackA", + "devices": [ + "dc1/server/1", + "dc1/server/2", + "dc1/switch/A", + "dc1/pdu/rackA", + ], + }, + { + "group_name": "rackB", + "devices": [ + "dc1/server/3", + "dc1/server/4", + "dc1/switch/B", + "dc1/pdu/rackB", + ], + "subgroups": [], + }, + ], + }, + ], }, - # Invalid groups (bad keys) - 'bk1_bad_keys': { - }, - 'bk2_bad_keys': { - 'group_name': 'bk2', - 'bad_devices_key': ['my/dev/01', 'my/dev/02'] - }, - 'bk3_bad_keys': { - 'group_name': 'bk3', - 'bad_subgroups_key': [] + "bk1_bad_keys": {}, + "bk2_bad_keys": { + "group_name": "bk2", + "bad_devices_key": ["my/dev/01", "my/dev/02"], }, - 'bk4_bad_keys': { - 'bad_group_name_key': 'bk4', - 'devices': ['my/dev/41'] + "bk3_bad_keys": {"group_name": "bk3", "bad_subgroups_key": []}, + "bk4_bad_keys": {"bad_group_name_key": "bk4", "devices": ["my/dev/41"]}, + "bk5_bad_nested_keys": { + "group_name": "bk5", + "subgroups": [{"group_name": "bk5-1", "bad_devices_key": ["my/dev/3-1"]}], }, - 'bk5_bad_nested_keys': { - 'group_name': 'bk5', - 'subgroups': [ - {'group_name': 'bk5-1', - 'bad_devices_key': ['my/dev/3-1']} - ] + "bk6_bad_nested_keys": { + "group_name": "bk6", + "subgroups": [{"bad_group_name_key": "bk6-1", "devices": ["my/dev/3-1"]}], }, - 'bk6_bad_nested_keys': { - 'group_name': 'bk6', - 'subgroups': [ - {'bad_group_name_key': 'bk6-1', - 'devices': ['my/dev/3-1']} - ] - }, - # Invalid groups (bad values) - 'bv1_bad_device_names': { - 'group_name': 'bv1', - 'devices': ['my\\dev-11'] - }, - 'bv2_bad_device_names': { - 'group_name': 'bv2', - 'devices': ['1', '2', 'bad'] - }, - 'bv3_bad_device_names': { - 'group_name': 'bv3', - 'devices': [' '] - }, - 'bv4_bad_subgroups_value': { - 'group_name': 'bv4', - 'subgroups': [' '] - }, - 'bv5_bad_nested_device_names': { - 'group_name': 'bv5', - 'subgroups': [ - {'group_name': 'bv5-1', - 'devices': ['my\\dev-11']} - ] + "bv1_bad_device_names": {"group_name": "bv1", "devices": ["my\\dev-11"]}, + "bv2_bad_device_names": {"group_name": "bv2", "devices": ["1", "2", "bad"]}, + "bv3_bad_device_names": {"group_name": "bv3", "devices": [" "]}, + "bv4_bad_subgroups_value": {"group_name": "bv4", "subgroups": [" "]}, + "bv5_bad_nested_device_names": { + "group_name": "bv5", + "subgroups": [{"group_name": "bv5-1", "devices": ["my\\dev-11"]}], }, } VALID_GROUP_KEYS = [ - ('basic_no_subgroups', ), - ('basic_no_subgroups', 'basic_empty_subgroups', ), - ('basic_no_subgroups', 'basic_empty_subgroups', 'dual_level', ), - ('basic_no_subgroups', 'basic_empty_subgroups', 'dual_level', 'multi_level'), + ("basic_no_subgroups",), + ( + "basic_no_subgroups", + "basic_empty_subgroups", + ), + ( + "basic_no_subgroups", + "basic_empty_subgroups", + "dual_level", + ), + ("basic_no_subgroups", "basic_empty_subgroups", "dual_level", "multi_level"), ] BAD_GROUP_KEYS = [ - ('bk1_bad_keys', ), - ('bk2_bad_keys', ), - ('bk3_bad_keys', ), - ('bk4_bad_keys', ), - ('bk5_bad_nested_keys', ), - ('bk6_bad_nested_keys', ), - ('bv1_bad_device_names', ), - ('bv2_bad_device_names', ), - ('bv3_bad_device_names', ), - ('bv4_bad_subgroups_value', ), - ('bv5_bad_nested_device_names', ), + ("bk1_bad_keys",), + ("bk2_bad_keys",), + ("bk3_bad_keys",), + ("bk4_bad_keys",), + ("bk5_bad_nested_keys",), + ("bk6_bad_nested_keys",), + ("bv1_bad_device_names",), + ("bv2_bad_device_names",), + ("bv3_bad_device_names",), + ("bv4_bad_subgroups_value",), + ("bv5_bad_nested_device_names",), # Include a valid group, g2 with an invalid group - ('basic_no_subgroups', 'bk1_bad_keys', ), + ( + "basic_no_subgroups", + "bk1_bad_keys", + ), ] @@ -144,7 +135,7 @@ def _get_group_configs_from_keys(group_keys): def _group_id_name(keys): """Helper function to give tests nicer names.""" - return ','.join(keys) + return ",".join(keys) @pytest.fixture(scope="module", params=VALID_GROUP_KEYS, ids=_group_id_name) @@ -163,17 +154,17 @@ def test_get_groups_from_json_empty_list(): groups = get_groups_from_json([]) assert groups == {} # empty or whitespace strings should also be ignored - groups = get_groups_from_json(['']) + groups = get_groups_from_json([""]) assert groups == {} - groups = get_groups_from_json([' ', '', ' ']) + groups = get_groups_from_json([" ", "", " "]) assert groups == {} def _validate_group(definition, group): """Compare groups test definition dict to actual tango.Group.""" - expected_group_name = definition['group_name'] # key must exist - expected_devices = definition.get('devices', []) # key may exist - expected_subgroups = definition.get('subgroups', []) # key may exist + expected_group_name = definition["group_name"] # key must exist + expected_devices = definition.get("devices", []) # key may exist + expected_subgroups = definition.get("subgroups", []) # key may exist print("Checking group:", expected_group_name, group) assert group is not None @@ -183,7 +174,7 @@ def _validate_group(definition, group): for expected_subgroup in expected_subgroups: print("\tsubgroup def", expected_subgroup) - subgroup = group.get_group(expected_subgroup['group_name']) + subgroup = group.get_group(expected_subgroup["group_name"]) assert subgroup is not None # recurse the tree _validate_group(expected_subgroup, subgroup) @@ -196,7 +187,7 @@ def test_get_groups_from_json_valid(valid_group_configs): # Check result assert len(groups) == len(valid_group_configs) for group_config in valid_group_configs: - name = group_config['group_name'] + name = group_config["group_name"] group = groups[name] _validate_group(group_config, group) @@ -219,12 +210,11 @@ def test_get_tango_device_type_id(): ( False, pytest.warns( - UserWarning, - match='foo should only be used for testing purposes' - ) + UserWarning, match="foo should only be used for testing purposes" + ), ), (True, nullcontext()), - ] + ], ) def test_for_testing_only(in_test, context): """ @@ -232,6 +222,7 @@ def test_for_testing_only(in_test, context): if we are NOT testing. This is achieved by patching the test, which cannot be done using the @decorator syntax. """ + def foo(): """Dummy function for wrapping by decorator under test.""" return "foo" @@ -246,6 +237,7 @@ def test_for_testing_only_decorator(): """ Test the unpatched for_testing_only decorator using the usual @decorator syntax """ + @for_testing_only def bah(): """Dummy function for wrapping by decorator under test."""