diff --git a/.flake8 b/.flake8
new file mode 100644
index 000000000..397b9cdd1
--- /dev/null
+++ b/.flake8
@@ -0,0 +1,5 @@
+# flake8 configuration.
+[flake8]
+exclude = .tox,.git,__pycache__
+ignore = D211,D400,E251,E731,W503
+max-line-length = 120
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a3e138ac3..b0284d7f1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -191,7 +191,7 @@ jobs:
# continue_on_error: true
- name: flake8
tox: flake8
- continue_on_error: true
+ # continue_on_error: true
- name: Docs
tox: docs
os:
diff --git a/doc/api/doxygen/build.py b/doc/api/doxygen/build.py
index ddcab224c..6ee2bf044 100644
--- a/doc/api/doxygen/build.py
+++ b/doc/api/doxygen/build.py
@@ -1,19 +1,21 @@
#!/usr/bin/env python3
-""" Doxygen API Builder
----------------------
-"""
+"""Doxygen API Builder."""
import os
import shutil
+
def is_exe(path):
- """ Returns if the program is executable
+ """Return if the program is executable.
+
:param path: The path to the file
:return: True if it is, False otherwise
"""
return os.path.exists(path) and os.access(path, os.X_OK)
+
def which(program):
- """ Check to see if an executable exists
+ """Check to see if an executable exists.
+
:param program: The program to check for
:return: The full path of the executable or None if not found
"""
@@ -28,9 +30,11 @@ def which(program):
return exe_file
return None
+
if which('doxygen') is not None:
print("Building Doxygen API Documentation")
- os.system("doxygen .doxygen") #nosec
+ os.system("doxygen .doxygen") # nosec
if os.path.exists('../../../build'):
shutil.move("html", "../../../build/doxygen")
-else: print("Doxygen not available...not building")
+else:
+ print("Doxygen not available...not building")
diff --git a/doc/api/epydoc/build.py b/doc/api/epydoc/build.py
index d9e350616..a81ff1901 100755
--- a/doc/api/epydoc/build.py
+++ b/doc/api/epydoc/build.py
@@ -1,6 +1,5 @@
#!/usr/bin/env python3
-""" Epydoc API Runner
-------------------
+"""Epydoc API Runner.
Using pkg_resources, we attempt to see if epydoc is installed,
if so, we use its cli program to compile the documents
@@ -14,7 +13,7 @@
try:
pkg_resources.require("epydoc")
- from epydoc.cli import cli # pylint: disable=import-error
+ from epydoc.cli import cli # pylint: disable=import-error
sys.argv = """epydoc.py pymodbus
--html --simple-term --quiet
--include-log
@@ -25,7 +24,7 @@
--exclude=tests
--output=html/
""".split()
- #bugs in trunk for --docformat=restructuredtext
+ # bugs in trunk for --docformat=restructuredtext
if not os.path.exists("./html"):
os.mkdir("./html")
@@ -35,6 +34,6 @@
if os.path.exists('../../../build'):
shutil.move("html", "../../../build/epydoc")
-except Exception: # pylint: disable=broad-except
+except Exception: # pylint: disable=broad-except
traceback.print_exc(file=sys.stdout)
- print( "Epydoc not available...not building")
+ print("Epydoc not available...not building")
diff --git a/doc/api/pydoc/build.py b/doc/api/pydoc/build.py
index 460a1d23b..f2fd4cc49 100644
--- a/doc/api/pydoc/build.py
+++ b/doc/api/pydoc/build.py
@@ -1,448 +1,464 @@
#!/usr/bin/env python3 # pylint: disable-all
-"""
-Pydoc sub-class for generating documentation for entire packages.
+"""Pydoc sub-class for generating documentation for entire packages.
Taken from: http://pyopengl.sourceforge.net/pydoc/OpenGLContext.pydoc.pydoc2.html
Author: Mike Fletcher
"""
import logging
-import pydoc, inspect, os, string, shutil
-import sys, imp, os, stat, re, types, inspect
-from repr import Repr
-from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
+import pydoc
+import inspect
+import os
+import string
+import shutil
+import sys
+from string import join, split, strip
_log = logging.getLogger(__name__)
+
def classify_class_attrs(cls):
- """Return list of attribute-descriptor tuples.
-
- For each name in dir(cls), the return list contains a 4-tuple
- with these elements:
-
- 0. The name (a string).
-
- 1. The kind of attribute this is, one of these strings:
- 'class method' created via classmethod()
- 'static method' created via staticmethod()
- 'property' created via property()
- 'method' any other flavor of method
- 'data' not a method
-
- 2. The class which defined this attribute (a class).
-
- 3. The object as obtained directly from the defining class's
- __dict__, not via getattr. This is especially important for
- data attributes: C.data is just a data object, but
- C.__dict__['data'] may be a data descriptor with additional
- info, like a __doc__ string.
-
- Note: This version is patched to work with Zope Interface-bearing objects
- """
-
- mro = inspect.getmro(cls)
- names = dir(cls)
- result = []
- for name in names:
- # Get the object associated with the name.
- # Getting an obj from the __dict__ sometimes reveals more than
- # using getattr. Static and class methods are dramatic examples.
- if name in cls.__dict__:
- obj = cls.__dict__[name]
- else:
- try:
- obj = getattr(cls, name)
- except AttributeError:
- continue
-
- # Figure out where it was defined.
- homecls = getattr(obj, "__objclass__", None)
- if homecls is None:
- # search the dicts.
- for base in mro:
- if name in base.__dict__:
- homecls = base
- break
-
- # Get the object again, in order to get it from the defining
- # __dict__ instead of via getattr (if possible).
- if homecls is not None and name in homecls.__dict__:
- obj = homecls.__dict__[name]
-
- # Also get the object via getattr.
- obj_via_getattr = getattr(cls, name)
-
- # Classify the object.
- if isinstance(obj, staticmethod):
- kind = "static method"
- elif isinstance(obj, classmethod):
- kind = "class method"
- elif isinstance(obj, property):
- kind = "property"
- elif (inspect.ismethod(obj_via_getattr) or
- inspect.ismethoddescriptor(obj_via_getattr)):
- kind = "method"
- else:
- kind = "data"
-
- result.append((name, kind, homecls, obj))
-
- return result
+ """Return list of attribute-descriptor tuples.
+
+ For each name in dir(cls), the return list contains a 4-tuple
+ with these elements:
+
+ 0. The name (a string).
+
+ 1. The kind of attribute this is, one of these strings:
+ 'class method' created via classmethod()
+ 'static method' created via staticmethod()
+ 'property' created via property()
+ 'method' any other flavor of method
+ 'data' not a method
+
+ 2. The class which defined this attribute (a class).
+
+ 3. The object as obtained directly from the defining class's
+ __dict__, not via getattr. This is especially important for
+ data attributes: C.data is just a data object, but
+ C.__dict__['data'] may be a data descriptor with additional
+ info, like a __doc__ string.
+
+ Note: This version is patched to work with Zope Interface-bearing objects
+ """
+ mro = inspect.getmro(cls)
+ names = dir(cls)
+ result = []
+ for name in names:
+ # Get the object associated with the name.
+ # Getting an obj from the __dict__ sometimes reveals more than
+ # using getattr. Static and class methods are dramatic examples.
+ if name in cls.__dict__:
+ obj = cls.__dict__[name]
+ else:
+ try:
+ obj = getattr(cls, name)
+ except AttributeError:
+ continue
+
+ # Figure out where it was defined.
+ homecls = getattr(obj, "__objclass__", None)
+ if homecls is None:
+ # search the dicts.
+ for base in mro:
+ if name in base.__dict__:
+ homecls = base
+ break
+
+ # Get the object again, in order to get it from the defining
+ # __dict__ instead of via getattr (if possible).
+ if homecls is not None and name in homecls.__dict__:
+ obj = homecls.__dict__[name]
+
+ # Also get the object via getattr.
+ obj_via_getattr = getattr(cls, name)
+
+ # Classify the object.
+ if isinstance(obj, staticmethod):
+ kind = "static method"
+ elif isinstance(obj, classmethod):
+ kind = "class method"
+ elif isinstance(obj, property):
+ kind = "property"
+ elif (inspect.ismethod(obj_via_getattr) or # noqa W504
+ inspect.ismethoddescriptor(obj_via_getattr)):
+ kind = "method"
+ else:
+ kind = "data"
+
+ result.append((name, kind, homecls, obj))
+
+ return result
+
+
inspect.classify_class_attrs = classify_class_attrs
class DefaultFormatter(pydoc.HTMLDoc):
- def docmodule(self, object, name=None, mod=None, packageContext = None, *ignored):
- """Produce HTML documentation for a module object."""
- my_name = object.__name__ # ignore the passed-in name
- parts = split(my_name, '.')
- links = []
- for i in range(len(parts)-1):
- links.append(
- '%s' %
- (join(parts[:i+1], '.'), parts[i]))
- linkedname = join(links + parts[-1:], '.')
- head = '%s' % linkedname
- try:
- path = inspect.getabsfile(object)
- url = path
- if sys.platform == 'win32':
- import nturl2path
- url = nturl2path.pathname2url(path)
- filelink = '%s' % (url, path)
- except TypeError:
- filelink = '(built-in)'
- info = []
- if hasattr(object, '__version__'):
- version = str(object.__version__)
- if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
- version = strip(version[11:-1])
- info.append('version %s' % self.escape(version))
- if hasattr(object, '__date__'):
- info.append(self.escape(str(object.__date__)))
- if info:
- head = head + ' (%s)' % join(info, ', ')
- result = self.heading(
- head, '#ffffff', '#7799ee', 'index
' + filelink)
-
- modules = inspect.getmembers(object, inspect.ismodule)
-
- classes, cdict = [], {}
- for key, value in inspect.getmembers(object, inspect.isclass):
- if (inspect.getmodule(value) or object) is object:
- classes.append((key, value))
- cdict[key] = cdict[value] = '#' + key
- for key, value in classes:
- for base in value.__bases__:
- key, modname = base.__name__, base.__module__
- module = sys.modules.get(modname)
- if modname != my_name and module and hasattr(module, key):
- if getattr(module, key) is base:
- if not cdict.has_key(key):
- cdict[key] = cdict[base] = modname + '.html#' + key
- funcs, fdict = [], {}
- for key, value in inspect.getmembers(object, inspect.isroutine):
- if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
- funcs.append((key, value))
- fdict[key] = '#-' + key
- if inspect.isfunction(value): fdict[value] = fdict[key]
- data = []
- for key, value in inspect.getmembers(object, pydoc.isdata):
- if key not in ['__builtins__', '__doc__']:
- data.append((key, value))
-
- doc = self.markup(pydoc.getdoc(object), self.preformat, fdict, cdict)
- doc = doc and '%s' % doc
- result = result + '
%s
\n' % doc - - packageContext.clean ( classes, object ) - packageContext.clean ( funcs, object ) - packageContext.clean ( data, object ) - - if hasattr(object, '__path__'): - modpkgs = [] - modnames = [] - for file in os.listdir(object.__path__[0]): - path = os.path.join(object.__path__[0], file) - modname = inspect.getmodulename(file) - if modname and modname not in modnames: - modpkgs.append((modname, my_name, 0, 0)) - modnames.append(modname) - elif pydoc.ispackage(path): - modpkgs.append((file, my_name, 1, 0)) - modpkgs.sort() - contents = self.multicolumn(modpkgs, self.modpkglink) -## result = result + self.bigsection( -## 'Package Contents', '#ffffff', '#aa55cc', contents) - result = result + self.moduleSection( object, packageContext) - elif modules: -#FIX contents = self.multicolumn( -#FIX modules, lambda (key, value), s=self: s.modulelink(value)) - result = result + self.bigsection( - 'Modules', '#fffff', '#aa55cc', contents) - - - if classes: -#FIX classlist = map(lambda (key, value): value, classes) - contents = [ - self.formattree(inspect.getclasstree(classlist, 1), my_name)] - for key, value in classes: - contents.append(self.document(value, key, my_name, fdict, cdict)) - result = result + self.bigsection( - 'Classes', '#ffffff', '#ee77aa', join(contents)) - if funcs: - contents = [] - for key, value in funcs: - contents.append(self.document(value, key, my_name, fdict, cdict)) - result = result + self.bigsection( - 'Functions', '#ffffff', '#eeaa77', join(contents)) - if data: - contents = [] - for key, value in data: - try: - contents.append(self.document(value, key)) - except Exception: #nosec - pass - result = result + self.bigsection( - 'Data', '#ffffff', '#55aa55', join(contents, '%s
\n' % doc + + packageContext.clean(classes, object) + packageContext.clean(funcs, object) + packageContext.clean(data, object) + + if hasattr(object, '__path__'): + modpkgs = [] + modnames = [] + for file in os.listdir(object.__path__[0]): + path = os.path.join(object.__path__[0], file) + modname = inspect.getmodulename(file) + if modname and modname not in modnames: + modpkgs.append((modname, my_name, 0, 0)) + modnames.append(modname) + elif pydoc.ispackage(path): + modpkgs.append((file, my_name, 1, 0)) + modpkgs.sort() + contents = self.multicolumn(modpkgs, self.modpkglink) + # # result = result + self.bigsection( + # # 'Package Contents', '#ffffff', '#aa55cc', contents) + result = result + self.moduleSection(object, packageContext) + elif modules: + # FIX contents = self.multicolumn( + # FIX modules, lambda (key, value), s=self: s.modulelink(value)) + result = result + self.bigsection( + 'Modules', '#fffff', '#aa55cc', contents) + + if classes: + # FIX classlist = map(lambda (key, value): value, classes) + contents = [ + self.formattree(inspect.getclasstree(classlist, 1), my_name)] # noqa F821 + for key, value in classes: + contents.append(self.document(value, key, my_name, fdict, cdict)) + result = result + self.bigsection( + 'Classes', '#ffffff', '#ee77aa', join(contents)) + if funcs: + contents = [] + for key, value in funcs: + contents.append(self.document(value, key, my_name, fdict, cdict)) + result = result + self.bigsection( + 'Functions', '#ffffff', '#eeaa77', join(contents)) + if data: + contents = [] + for key, value in data: + try: + contents.append(self.document(value, key)) + except Exception: # nosec + pass + result = result + self.bigsection( + 'Data', '#ffffff', '#55aa55', join(contents, '- """ + """Return a string in canonical short version format:. . . .""" if self.pre: return f'{self.major}.{self.minor}.{self.micro}.{self.pre}' return f'{self.major}.{self.minor}.{self.micro}' def __str__(self): - """ Returns a string representation of the object + """Return a string representation of the object. :returns: A string representation of this object """ diff --git a/setup.py b/setup.py index aa0954f54..34f4c669a 100644 --- a/setup.py +++ b/setup.py @@ -27,8 +27,8 @@ from pymodbus import __version__, __author__, __maintainer__ CONSOLE_SCRIPTS = [ - 'pymodbus.console=pymodbus.repl.client.main:main' - ] + 'pymodbus.console=pymodbus.repl.client.main:main' +] CONSOLE_SCRIPTS.append('pymodbus.server=pymodbus.repl.server.main:server') with open('requirements.txt') as reqs: install_requires = [ diff --git a/setup_commands.py b/setup_commands.py index e04a7be6c..526ede53d 100755 --- a/setup_commands.py +++ b/setup_commands.py @@ -1,3 +1,4 @@ +"""Setup commands.""" import os import shutil import sys @@ -8,25 +9,27 @@ class BuildApiDocsCommand(Command): - """ Helper command to build the available api documents + """Helper command to build the available api documents. + This scans all the subdirectories under api and runs the build.py script underneath trying to build the api documentation for the given format. """ + description = "build all the project's api documents" user_options = [] def initialize_options(self): - """ options setup """ + """Initialize options setup.""" if not os.path.exists('./build'): os.mkdir('./build') def finalize_options(self): - """ options teardown """ + """Finalize options teardown.""" pass def run(self): - """ command runner """ + """Run command.""" old_cwd = os.getcwd() directories = (d for d in os.listdir('./doc/api') if not d.startswith('.')) for entry in directories: @@ -36,10 +39,8 @@ def run(self): class DeepCleanCommand(Command): - """ - Helper command to return the directory to a completely - clean state. - """ + """Helper command to return the directory to a completely clean state.""" + description = "clean everything that we don't want" user_options = [] trash = ['build', 'dist', 'pymodbus.egg-info', @@ -47,19 +48,19 @@ class DeepCleanCommand(Command): ] def initialize_options(self): - """ options setup """ + """Initialize options setup.""" pass def finalize_options(self): pass def run(self): - """ command runner """ + """Run command.""" self._delete_pyc_files() self._delete_trash_dirs() def _delete_trash_dirs(self): - """ remove all directories created in building """ + """Remove all directories created in building.""" self._delete_pyc_files() for directory in self.trash: if os.path.exists(directory): @@ -67,7 +68,7 @@ def _delete_trash_dirs(self): @staticmethod def _delete_pyc_files(): - """ remove all python cache files """ + """Remove all python cache files.""" for root, dirs, files in os.walk('.'): for file in files: if file.endswith('.pyc'): @@ -75,15 +76,13 @@ def _delete_pyc_files(): class LintCommand(Command): - """ - Helper command to perform a lint scan of the - sourcecode and return the results. - """ + """Helper command to perform a lint scan of the sourcecode and return the results.""" + description = "perform a lint scan of the code" user_options = [] def initialize_options(self): - """ options setup """ + """Initialize options setup.""" if not os.path.exists('./build'): os.mkdir('./build') @@ -91,7 +90,7 @@ def finalize_options(self): pass def run(self): - """ command runner """ + """Run command.""" scanners = [s for s in dir(self) if s.find('__try') >= 0] for scanner in scanners: if getattr(self, scanner)(): @@ -108,35 +107,35 @@ def _try_pyflakes(self): def _try_pychecker(self): try: - import pychecker + import pychecker # noqa F401 sys.argv = """pychecker pymodbus/*.py""".split() - main() + main() # noqa F821 return True except Exception: return False def _try_pylint(self): try: - import pylint + import pylint # noqa F401 sys.argv = """pylint pymodbus/*.py""".split() - main() + main() # noqa F821 return True except Exception: return False class Python3Command(Command): - """ Helper command to scan for potential python 3 - errors. + """Helper command to scan for potential python 3 errors. ./setup.py scan_2to3 > build/diffs_2to3 build/report_2to3 """ + description = "perform 2to3 scan of the code" user_options = [] directories = ['pymodbus', 'test', 'examples'] def initialize_options(self): - """ options setup """ + """Initialize options setup.""" if not os.path.exists('./build'): os.mkdir('./build') @@ -144,7 +143,7 @@ def finalize_options(self): pass def run(self): - """ command runner """ + """Run command""" self._run_python3() def _run_python3(self): @@ -158,15 +157,14 @@ def _run_python3(self): class Pep8Command(Command): - """ - Helper command to scan for potential pep8 violations - """ + """Helper command to scan for potential pep8 violations.""" + description = "perform pep8 scan of the code" user_options = [] directories = ['pymodbus'] def initialize_options(self): - """ options setup """ + """Initialize options setup""" if not os.path.exists('./build'): os.mkdir('./build') @@ -174,7 +172,7 @@ def finalize_options(self): pass def run(self): - """ command runner """ + """Run command.""" self._run_pep8() def _run_pep8(self): diff --git a/test/__init__.py b/test/__init__.py index e69de29bb..a8e0472a0 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -0,0 +1 @@ +"""Dummy.""" diff --git a/test/asyncio_test_helper.py b/test/asyncio_test_helper.py index 64d1a8b5f..10c7ac37d 100644 --- a/test/asyncio_test_helper.py +++ b/test/asyncio_test_helper.py @@ -3,8 +3,8 @@ import functools -def _yielded_return(return_value, *args): # pylint: disable=unused-argument - """Generator factory function with return value.""" +def _yielded_return(return_value, *args): # pylint: disable=unused-argument + """Return Generator factory function with return value.""" async def _(): """Actual generator producing value.""" @@ -16,7 +16,7 @@ async def _(): def return_as_coroutine(return_value=None): - """Creates a function that behaves like an asyncio coroutine and returns the given value. + """Create a function that behaves like an asyncio coroutine and returns the given value. Typically used as a side effect of a mocked coroutine like this: @@ -37,8 +37,7 @@ def test_it(mock_sleep): def run_coroutine(coro): - """Runs a coroutine as top-level task by iterating through all yielded steps.""" - + """Run a coroutine as top-level task by iterating through all yielded steps.""" result = None try: # step through all parts of coro without scheduling anything else: @@ -47,5 +46,5 @@ def run_coroutine(coro): except StopIteration as exc: # coro reached end pass on its return value: return exc.value - except: # pylint: disable=try-except-raise + except: # noqa E722 pylint: disable=try-except-raise raise diff --git a/test/modbus_mocks.py b/test/modbus_mocks.py index ddd789a5a..2d09db44b 100644 --- a/test/modbus_mocks.py +++ b/test/modbus_mocks.py @@ -1,10 +1,12 @@ """Modbus mocks.""" from pymodbus.interfaces import IModbusSlaveContext -#---------------------------------------------------------------------------# -# Mocks -#---------------------------------------------------------------------------# -class mock: # pylint: disable=too-few-public-methods,invalid-name +# ---------------------------------------------------------------------------# +# Mocks +# ---------------------------------------------------------------------------# + + +class mock: # pylint: disable=too-few-public-methods,invalid-name """Mock.""" @@ -12,6 +14,7 @@ class MockContext(IModbusSlaveContext): """Mock context.""" def __init__(self, valid=False, default=True): + """Initialize.""" self.valid = valid self.default = default @@ -26,14 +29,18 @@ def getValues(self, fx, address, count=0): def setValues(self, fx, address, values): """Set values.""" + class FakeList: - """ todo, replace with magic mock """ + """Todo, replace with magic mock.""" def __init__(self, size): + """Initialize.""" self.size = size def __len__(self): + """Get length.""" return self.size - def __iter__(self): # pylint: disable=non-iterator-returned + def __iter__(self): # pylint: disable=non-iterator-returned + """Iterate.""" return [] diff --git a/test/test_all_messages.py b/test/test_all_messages.py index 7982199b4..5bed0c855 100644 --- a/test/test_all_messages.py +++ b/test/test_all_messages.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test all messages.""" +"""Test all messages.""" import unittest from pymodbus.constants import Defaults from pymodbus.bit_read_message import ( @@ -29,20 +29,20 @@ WriteSingleRegisterRequest, ) -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class ModbusAllMessagesTests(unittest.TestCase): """All messages tests.""" - #-----------------------------------------------------------------------# - # Setup/TearDown - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Setup/TearDown + # -----------------------------------------------------------------------# def setUp(self): - """ Initializes the test environment and builds request/result - encoding pairs - """ + """Initialize the test environment and builds request/result encoding pairs.""" arguments = { 'read_address': 1, 'read_count': 1, 'write_address': 1, 'write_registers': 1 @@ -71,30 +71,30 @@ def setUp(self): ] def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_initializing_slave_address_request(self): - """ Test that every request can initialize the unit id """ + """Test that every request can initialize the unit id""" unit_id = 0x12 for factory in self.requests: request = factory(unit_id) self.assertEqual(request.unit_id, unit_id) def test_initializing_slave_address_response(self): - """ Test that every response can initialize the unit id """ + """Test that every response can initialize the unit id""" unit_id = 0x12 for factory in self.responses: response = factory(unit_id) self.assertEqual(response.unit_id, unit_id) def test_forwarding_kwargs_to_pdu(self): - """ Test that the kwargs are forwarded to the pdu correctly """ - request = ReadCoilsRequest(1,5, unit=0x12, transaction=0x12, protocol=0x12) + """Test that the kwargs are forwarded to the pdu correctly""" + request = ReadCoilsRequest(1, 5, unit=0x12, transaction=0x12, protocol=0x12) self.assertEqual(request.unit_id, 0x12) self.assertEqual(request.transaction_id, 0x12) self.assertEqual(request.protocol_id, 0x12) - request = ReadCoilsRequest(1,5) + request = ReadCoilsRequest(1, 5) self.assertEqual(request.unit_id, Defaults.UnitId) self.assertEqual(request.transaction_id, Defaults.TransactionId) self.assertEqual(request.protocol_id, Defaults.ProtocolId) diff --git a/test/test_bit_read_messages.py b/test/test_bit_read_messages.py index 1e2530c26..e2bd5dea8 100644 --- a/test/test_bit_read_messages.py +++ b/test/test_bit_read_messages.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" Bit Message Test Fixture --------------------------------- +"""Bit Message Test Fixture. + This fixture tests the functionality of all the bit based request/response messages: @@ -17,110 +17,110 @@ from .modbus_mocks import MockContext res = [True] * 21 res.extend([False] * 3) -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class ModbusBitMessageTests(unittest.TestCase): - """ Modbus bit read message tests. """ + """Modbus bit read message tests.""" - #-----------------------------------------------------------------------# - # Setup/TearDown - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Setup/TearDown + # -----------------------------------------------------------------------# def setUp(self): - """ Initializes the test environment and builds request/result - encoding pairs - """ + """Initialize the test environment and builds request/result encoding pairs.""" def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_read_bit_base_class_methods(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" handle = ReadBitsRequestBase(1, 1) - msg = "ReadBitRequest(1,1)" + msg = "ReadBitRequest(1,1)" self.assertEqual(msg, str(handle)) - handle = ReadBitsResponseBase([1,1]) - msg = "ReadBitsResponseBase(2)" + handle = ReadBitsResponseBase([1, 1]) + msg = "ReadBitsResponseBase(2)" self.assertEqual(msg, str(handle)) def test_bit_read_base_request_encoding(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" for i in range(20): handle = ReadBitsRequestBase(i, i) - result = struct.pack('>HH',i, i) + result = struct.pack('>HH', i, i) self.assertEqual(handle.encode(), result) handle.decode(result) - self.assertEqual((handle.address, handle.count), (i,i)) + self.assertEqual((handle.address, handle.count), (i, i)) def test_bit_read_base_response_encoding(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" for i in range(20): - data = [True] * i + data = [True] * i handle = ReadBitsResponseBase(data) result = handle.encode() handle.decode(result) self.assertEqual(handle.bits[:i], data) def test_bit_read_base_response_helper_methods(self): - """ Test the extra methods on a ReadBitsResponseBase """ - data = [False] * 8 + """Test the extra methods on a ReadBitsResponseBase""" + data = [False] * 8 handle = ReadBitsResponseBase(data) - for i in (1,3,5): + for i in (1, 3, 5): handle.setBit(i, True) - for i in (1,3,5): + for i in (1, 3, 5): handle.resetBit(i) for i in range(8): self.assertEqual(handle.getBit(i), False) def test_bit_read_base_requests(self): - """ Test bit read request encoding """ + """Test bit read request encoding""" messages = { - ReadBitsRequestBase(12, 14) : b'\x00\x0c\x00\x0e', - ReadBitsResponseBase([1,0,1,1,0]) : b'\x01\x0d' + ReadBitsRequestBase(12, 14): b'\x00\x0c\x00\x0e', + ReadBitsResponseBase([1, 0, 1, 1, 0]): b'\x01\x0d' } for request, expected in iter(messages.items()): self.assertEqual(request.encode(), expected) def test_bit_read_message_execute_value_errors(self): - """ Test bit read request encoding """ + """Test bit read request encoding""" context = MockContext() requests = [ - ReadCoilsRequest(1,0x800), - ReadDiscreteInputsRequest(1,0x800), + ReadCoilsRequest(1, 0x800), + ReadDiscreteInputsRequest(1, 0x800), ] for request in requests: result = request.execute(context) self.assertEqual(ModbusExceptions.IllegalValue, - result.exception_code) + result.exception_code) def test_bit_read_message_execute_address_errors(self): - """ Test bit read request encoding """ + """Test bit read request encoding""" context = MockContext() requests = [ - ReadCoilsRequest(1,5), - ReadDiscreteInputsRequest(1,5), + ReadCoilsRequest(1, 5), + ReadDiscreteInputsRequest(1, 5), ] for request in requests: result = request.execute(context) self.assertEqual(ModbusExceptions.IllegalAddress, result.exception_code) def test_bit_read_message_execute_success(self): - """ Test bit read request encoding """ + """Test bit read request encoding""" context = MockContext() - context.validate = lambda a,b,c: True + context.validate = lambda a, b, c: True requests = [ - ReadCoilsRequest(1,5), - ReadDiscreteInputsRequest(1,5), + ReadCoilsRequest(1, 5), + ReadDiscreteInputsRequest(1, 5), ] for request in requests: result = request.execute(context) self.assertEqual(result.bits, [True] * 5) def test_bit_read_message_get_response_pdu(self): - """ Test bit read message get response pdu.""" + """Test bit read message get response pdu.""" requests = { - ReadCoilsRequest(1,5): 3, + ReadCoilsRequest(1, 5): 3, ReadCoilsRequest(1, 8): 3, ReadCoilsRequest(0, 16): 4, ReadDiscreteInputsRequest(1, 21): 5, @@ -132,8 +132,8 @@ def test_bit_read_message_get_response_pdu(self): self.assertEqual(pdu_len, expected) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_bit_write_messages.py b/test/test_bit_write_messages.py index 8f392316e..dac479863 100644 --- a/test/test_bit_write_messages.py +++ b/test/test_bit_write_messages.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" Bit Message Test Fixture --------------------------------- +"""Bit Message Test Fixture. + This fixture tests the functionality of all the bit based request/response messages: @@ -18,37 +18,37 @@ from .modbus_mocks import MockContext, FakeList -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class ModbusBitMessageTests(unittest.TestCase): - """ Modbus bit write message tests. """ + """Modbus bit write message tests.""" - #-----------------------------------------------------------------------# - # Setup/TearDown - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Setup/TearDown + # -----------------------------------------------------------------------# def setUp(self): - """ Initializes the test environment and builds request/result - encoding pairs - """ + """Initialize the test environment and builds request/result encoding pairs.""" def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_bit_write_base_requests(self): - """ Test bit write base. """ + """Test bit write base.""" messages = { - WriteSingleCoilRequest(1, 0xabcd) : b'\x00\x01\xff\x00', - WriteSingleCoilResponse(1, 0xabcd) : b'\x00\x01\xff\x00', - WriteMultipleCoilsRequest(1, [True]*5) : b'\x00\x01\x00\x05\x01\x1f', - WriteMultipleCoilsResponse(1, 5) : b'\x00\x01\x00\x05', + WriteSingleCoilRequest(1, 0xabcd): b'\x00\x01\xff\x00', + WriteSingleCoilResponse(1, 0xabcd): b'\x00\x01\xff\x00', + WriteMultipleCoilsRequest(1, [True] * 5): b'\x00\x01\x00\x05\x01\x1f', + WriteMultipleCoilsResponse(1, 5): b'\x00\x01\x00\x05', } for request, expected in iter(messages.items()): self.assertEqual(request.encode(), expected) def test_bit_write_message_get_response_pdu(self): - """ Test bit write message. """ + """Test bit write message.""" requests = { WriteSingleCoilRequest(1, 0xabcd): 5 } @@ -57,30 +57,29 @@ def test_bit_write_message_get_response_pdu(self): self.assertEqual(pdu_len, expected) def test_write_multiple_coils_request(self): - """ Test write multiple coils. """ - request = WriteMultipleCoilsRequest(1, [True]*5) + """Test write multiple coils.""" + request = WriteMultipleCoilsRequest(1, [True] * 5) request.decode(b'\x00\x01\x00\x05\x01\x1f') self.assertEqual(request.byte_count, 1) self.assertEqual(request.address, 1) - self.assertEqual(request.values, [True]*5) + self.assertEqual(request.values, [True] * 5) self.assertEqual(request.get_response_pdu_size(), 5) - def test_invalid_write_multiple_coils_request(self): - """ Test write invalid multiple coils. """ + """Test write invalid multiple coils.""" request = WriteMultipleCoilsRequest(1, None) self.assertEqual(request.values, []) def test_write_single_coil_request_encode(self): - """ Test write single coil. """ + """Test write single coil.""" request = WriteSingleCoilRequest(1, False) self.assertEqual(request.encode(), b'\x00\x01\x00\x00') def test_write_single_coil_execute(self): - """ Test write single coil. """ + """Test write single coil.""" context = MockContext(False, default=True) request = WriteSingleCoilRequest(2, True) - result = request.execute(context) + result = request.execute(context) self.assertEqual(result.exception_code, ModbusExceptions.IllegalAddress) context.valid = True @@ -93,51 +92,52 @@ def test_write_single_coil_execute(self): self.assertEqual(result.encode(), b'\x00\x02\x00\x00') def test_write_multiple_coils_execute(self): - """ Test write multiple coils. """ + """Test write multiple coils.""" context = MockContext(False) # too many values request = WriteMultipleCoilsRequest(2, FakeList(0x123456)) - result = request.execute(context) + result = request.execute(context) self.assertEqual(result.exception_code, ModbusExceptions.IllegalValue) # bad byte count - request = WriteMultipleCoilsRequest(2, [0x00]*4) + request = WriteMultipleCoilsRequest(2, [0x00] * 4) request.byte_count = 0x00 - result = request.execute(context) + result = request.execute(context) self.assertEqual(result.exception_code, ModbusExceptions.IllegalValue) # does not validate context.valid = False - request = WriteMultipleCoilsRequest(2, [0x00]*4) - result = request.execute(context) + request = WriteMultipleCoilsRequest(2, [0x00] * 4) + result = request.execute(context) self.assertEqual(result.exception_code, ModbusExceptions.IllegalAddress) # validated request context.valid = True - result = request.execute(context) + result = request.execute(context) self.assertEqual(result.encode(), b'\x00\x02\x00\x04') def test_write_multiple_coils_response(self): - """ Test write multiple coils. """ + """Test write multiple coils.""" response = WriteMultipleCoilsResponse() response.decode(b'\x00\x80\x00\x08') self.assertEqual(response.address, 0x80) self.assertEqual(response.count, 0x08) def test_serializing_to_string(self): - """ Test serializing to string. """ + """Test serializing to string.""" requests = [ WriteSingleCoilRequest(1, 0xabcd), WriteSingleCoilResponse(1, 0xabcd), - WriteMultipleCoilsRequest(1, [True]*5), + WriteMultipleCoilsRequest(1, [True] * 5), WriteMultipleCoilsResponse(1, 5), ] for request in requests: result = str(request) - self.assertTrue(result is not None and len(result)) #NOSONAR + self.assertTrue(result is not None and len(result)) # NOSONAR + -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_client_async.py b/test/test_client_async.py index 2f617aeef..09bd056c1 100644 --- a/test/test_client_async.py +++ b/test/test_client_async.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test client async. """ +"""Test client async.""" import contextlib import sys import ssl @@ -35,13 +35,13 @@ def mock_asyncio_gather(coro): - """ Mock asyncio gather. """ + """Mock asyncio gather.""" return coro @contextlib.contextmanager def maybe_manage(condition, manager): - """ Maybe manage. """ + """Maybe manage.""" if condition: with manager as value: yield value @@ -50,15 +50,15 @@ def maybe_manage(condition, manager): class TestAsynchronousClient: - """ Unittest for the pymodbus.client.asynchronous module. """ + """Unittest for the pymodbus.client.asynchronous module.""" # -----------------------------------------------------------------------# # Test TCP Client client # -----------------------------------------------------------------------# - def test_tcp_twisted_client(self): # pylint: disable=no-self-use - """ Test the TCP Twisted client. """ + def test_tcp_twisted_client(self): # pylint: disable=no-self-use + """Test the TCP Twisted client.""" with patch("twisted.internet.reactor"): - def test_callback(client): # pylint: disable=unused-argument + def test_callback(client): # pylint: disable=unused-argument pass AsyncModbusTCPClient(schedulers.REACTOR, @@ -68,52 +68,50 @@ def test_callback(client): # pylint: disable=unused-argument @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.IOStream") - def test_tcp_tornado_client(self, mock_iostream, mock_ioloop): # pylint: disable=no-self-use,unused-argument - """ Test the TCP tornado client client initialize """ - protocol, future = AsyncModbusTCPClient( # NOSOANR pylint: disable=unpacking-non-sequence + def test_tcp_tornado_client(self, mock_iostream, mock_ioloop): # pylint: disable=no-self-use,unused-argument + """Test the TCP tornado client client initialize""" + protocol, future = AsyncModbusTCPClient( # NOSOANR pylint: disable=unpacking-non-sequence schedulers.IO_LOOP, framer=ModbusSocketFramer(ClientDecoder())) client = future.result() - assert isinstance(client, AsyncTornadoModbusTcpClient) #nosec - assert not list(client.transaction) #nosec - assert isinstance(client.framer, ModbusSocketFramer) #nosec - assert client.port == 502 #nosec - assert client._connected #nosec pylint: disable=protected-access - assert client.stream.connect.call_count == 1 #nosec - assert client.stream.read_until_close.call_count == 1 #nosec + assert isinstance(client, AsyncTornadoModbusTcpClient) # nosec + assert not list(client.transaction) # nosec + assert isinstance(client.framer, ModbusSocketFramer) # nosec + assert client.port == 502 # nosec + assert client._connected # nosec pylint: disable=protected-access + assert client.stream.connect.call_count == 1 # nosec + assert client.stream.read_until_close.call_count == 1 # nosec def handle_failure(failure): - assert isinstance(failure.exception(), ConnectionException) #nosec + assert isinstance(failure.exception(), ConnectionException) # nosec - response = client._build_response(0x00) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access response.add_done_callback(handle_failure) - assert client._connected #nosec pylint: disable=protected-access + assert client._connected # nosec pylint: disable=protected-access client.close() protocol.stop() - assert not client._connected #nosec pylint: disable=protected-access - + assert not client._connected # nosec pylint: disable=protected-access @patch("asyncio.get_event_loop") @patch("asyncio.gather") - def test_tcp_asyncio_client(self, mock_gather, mock_loop): # pylint: disable=no-self-use,unused-argument - """ Test the TCP Twisted client. """ + def test_tcp_asyncio_client(self, mock_gather, mock_loop): # pylint: disable=no-self-use,unused-argument + """Test the TCP Twisted client.""" pytest.skip("TBD") # -----------------------------------------------------------------------# # Test TLS Client client # -----------------------------------------------------------------------# - - def test_tls_asyncio_client(self): # pylint: disable=no-self-use - """ Test the TLS AsyncIO client. """ - _, client = AsyncModbusTLSClient(schedulers.ASYNC_IO) #NOSONAR pylint: disable=unpacking-non-sequence - assert isinstance(client, ReconnectingAsyncioModbusTlsClient) #nosec - assert isinstance(client.framer, ModbusTlsFramer) #nosec - assert isinstance(client.sslctx, ssl.SSLContext) #nosec - assert client.port == 802 #nosec + def test_tls_asyncio_client(self): # pylint: disable=no-self-use + """Test the TLS AsyncIO client.""" + _, client = AsyncModbusTLSClient(schedulers.ASYNC_IO) # NOSONAR pylint: disable=unpacking-non-sequence + assert isinstance(client, ReconnectingAsyncioModbusTlsClient) # nosec + assert isinstance(client.framer, ModbusTlsFramer) # nosec + assert isinstance(client.sslctx, ssl.SSLContext) # nosec + assert client.port == 802 # nosec client.stop() - assert client.host is None #nosec + assert client.host is None # nosec # -----------------------------------------------------------------------# # Test UDP client @@ -121,37 +119,37 @@ def test_tls_asyncio_client(self): # pylint: disable=no-self-use @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.IOStream") - def test_udp_tornado_client(self, mock_iostream, mock_ioloop): # pylint: disable=no-self-use,unused-argument - """ Test the udp tornado client client initialize """ - protocol, future = AsyncModbusUDPClient( #NOSONAR pylint: disable=unpacking-non-sequence + def test_udp_tornado_client(self, mock_iostream, mock_ioloop): # pylint: disable=no-self-use,unused-argument + """Test the udp tornado client client initialize""" + protocol, future = AsyncModbusUDPClient( # NOSONAR pylint: disable=unpacking-non-sequence schedulers.IO_LOOP, framer=ModbusSocketFramer(ClientDecoder())) client = future.result() - assert isinstance(client, AsyncTornadoModbusUdoClient) #nosec - assert not list(client.transaction) #nosec - assert isinstance(client.framer, ModbusSocketFramer) #nosec - assert client.port == 502 #nosec - assert client._connected #nosec pylint: disable=protected-access + assert isinstance(client, AsyncTornadoModbusUdoClient) # nosec + assert not list(client.transaction) # nosec + assert isinstance(client.framer, ModbusSocketFramer) # nosec + assert client.port == 502 # nosec + assert client._connected # nosec pylint: disable=protected-access def handle_failure(failure): - assert isinstance(failure.exception(), ConnectionException) #nosec + assert isinstance(failure.exception(), ConnectionException) # nosec - response = client._build_response(0x00) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access response.add_done_callback(handle_failure) - assert client._connected #nosec pylint: disable=protected-access + assert client._connected # nosec pylint: disable=protected-access client.close() protocol.stop() - assert not client._connected #nosec pylint: disable=protected-access + assert not client._connected # nosec pylint: disable=protected-access - def test_udp_twisted_client(self): # pylint: disable=no-self-use - """ Test the udp twisted client client initialize """ + def test_udp_twisted_client(self): # pylint: disable=no-self-use + """Test the udp twisted client client initialize""" with pytest.raises(NotImplementedError): AsyncModbusUDPClient(schedulers.REACTOR, framer=ModbusSocketFramer(ClientDecoder())) @patch("asyncio.get_event_loop") @patch("asyncio.gather", side_effect=mock_asyncio_gather) - def test_udp_asyncio_client(self, mock_gather, mock_event_loop): # pylint: disable=no-self-use,unused-argument + def test_udp_asyncio_client(self, mock_gather, mock_event_loop): # pylint: disable=no-self-use,unused-argument """Test the udp asyncio client""" pytest.skip("TBD") @@ -167,62 +165,64 @@ def test_udp_asyncio_client(self, mock_gather, mock_event_loop): # pylint: disab ("socket", ModbusSocketFramer), ("binary", ModbusBinaryFramer), ("ascii", ModbusAsciiFramer)]) - def test_serial_twisted_client(self, method, framer): # pylint: disable=no-self-use - """ Test the serial twisted client client initialize """ + def test_serial_twisted_client(self, method, framer): # pylint: disable=no-self-use + """Test the serial twisted client client initialize""" with patch("serial.Serial"): - from twisted.internet.serialport import SerialPort # pylint: disable=import-outside-toplevel + from twisted.internet.serialport import SerialPort # pylint: disable=import-outside-toplevel with maybe_manage(sys.platform == 'win32', patch.object( - SerialPort, "_finishPortSetup")): + SerialPort, "_finishPortSetup")): with patch('twisted.internet.reactor'): - protocol, client = AsyncModbusSerialClient(schedulers.REACTOR, #NOSONAR pylint: disable=unpacking-non-sequence - method=method, - port=pytest.SERIAL_PORT, - proto_cls=ModbusSerClientProtocol) + protocol, client = AsyncModbusSerialClient( # NOSONAR pylint: disable=unpacking-non-sequence + schedulers.REACTOR, + method=method, + port=pytest.SERIAL_PORT, + proto_cls=ModbusSerClientProtocol + ) - assert isinstance(client, SerialPort) #nosec - assert isinstance(client.protocol, ModbusSerClientProtocol) #nosec - assert not list(client.protocol.transaction) #nosec - assert isinstance(client.protocol.framer, framer) #nosec - assert client.protocol._connected #nosec pylint: disable=protected-access + assert isinstance(client, SerialPort) # nosec + assert isinstance(client.protocol, ModbusSerClientProtocol) # nosec + assert not list(client.protocol.transaction) # nosec + assert isinstance(client.protocol.framer, framer) # nosec + assert client.protocol._connected # nosec pylint: disable=protected-access def handle_failure(failure): - assert (isinstance(failure.exception(), ConnectionException)) #nosec + assert (isinstance(failure.exception(), ConnectionException)) # nosec - response = client.protocol._buildResponse(0x00) # pylint: disable=protected-access + response = client.protocol._buildResponse(0x00) # pylint: disable=protected-access response.addCallback(handle_failure) - assert client.protocol._connected #nosec pylint: disable=protected-access + assert client.protocol._connected # nosec pylint: disable=protected-access client.protocol.close() protocol.stop() - assert not client.protocol._connected #nosec pylint: disable=protected-access + assert not client.protocol._connected # nosec pylint: disable=protected-access @pytest.mark.parametrize("method, framer", [("rtu", ModbusRtuFramer), ("socket", ModbusSocketFramer), ("binary", ModbusBinaryFramer), ("ascii", ModbusAsciiFramer)]) - def test_serial_tornado_client(self, method, framer): # pylint: disable=no-self-use - """ Test the serial tornado client client initialize """ - with maybe_manage(sys.platform in set(('darwin', 'win32')),patch.object(Serial, "open")): - protocol, future = AsyncModbusSerialClient( #NOSONAR pylint: disable=unpacking-non-sequence + def test_serial_tornado_client(self, method, framer): # pylint: disable=no-self-use + """Test the serial tornado client client initialize""" + with maybe_manage(sys.platform in set(('darwin', 'win32')), patch.object(Serial, "open")): + protocol, future = AsyncModbusSerialClient( # NOSONAR pylint: disable=unpacking-non-sequence schedulers.IO_LOOP, method=method, port=pytest.SERIAL_PORT) client = future.result() - assert isinstance(client, AsyncTornadoModbusSerialClient) #nosec - assert not list(client.transaction) #nosec - assert isinstance(client.framer, framer) #nosec - assert client.port == pytest.SERIAL_PORT #nosec - assert client._connected #nosec pylint: disable=protected-access + assert isinstance(client, AsyncTornadoModbusSerialClient) # nosec + assert not list(client.transaction) # nosec + assert isinstance(client.framer, framer) # nosec + assert client.port == pytest.SERIAL_PORT # nosec + assert client._connected # nosec pylint: disable=protected-access def handle_failure(failure): - assert isinstance(failure.exception(), ConnectionException) #nosec + assert isinstance(failure.exception(), ConnectionException) # nosec - response = client._build_response(0x00) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access response.add_done_callback(handle_failure) - assert client._connected #nosec pylint: disable=protected-access + assert client._connected # nosec pylint: disable=protected-access client.close() protocol.stop() - assert not client._connected #nosec pylint: disable=protected-access + assert not client._connected # nosec pylint: disable=protected-access @patch("asyncio.get_event_loop") @patch("asyncio.gather", side_effect=mock_asyncio_gather) @@ -230,22 +230,21 @@ def handle_failure(failure): ("socket", ModbusSocketFramer), ("binary", ModbusBinaryFramer), ("ascii", ModbusAsciiFramer)]) - def test_serial_asyncio_client(self, mock_gather, mock_event_loop, method, framer): # pylint: disable=no-self-use,unused-argument - """ Test that AsyncModbusSerialClient instantiates - AsyncioModbusSerialClient for asyncio scheduler. - """ + def test_serial_asyncio_client(self, mock_gather, # pylint: disable=no-self-use,unused-argument + mock_event_loop, method, framer): # pylint: disable=unused-argument + """Test that AsyncModbusSerialClient instantiates AsyncioModbusSerialClient for asyncio scheduler.""" loop = asyncio.get_event_loop() loop.is_running.side_effect = lambda: False - loop, client = AsyncModbusSerialClient( #NOSONAR pylint: disable=unpacking-non-sequence + loop, client = AsyncModbusSerialClient( # NOSONAR pylint: disable=unpacking-non-sequence schedulers.ASYNC_IO, method=method, port=pytest.SERIAL_PORT, loop=loop, baudrate=19200, parity='E', stopbits=2, bytesize=7) - assert isinstance(client, AsyncioModbusSerialClient) #nosec - assert isinstance(client.framer, framer) #nosec - assert client.port == pytest.SERIAL_PORT #nosec - assert client.baudrate == 19200 #nosec - assert client.parity == 'E' #nosec - assert client.stopbits == 2 #nosec - assert client.bytesize == 7 #nosec + assert isinstance(client, AsyncioModbusSerialClient) # nosec + assert isinstance(client.framer, framer) # nosec + assert client.port == pytest.SERIAL_PORT # nosec + assert client.baudrate == 19200 # nosec + assert client.parity == 'E' # nosec + assert client.stopbits == 2 # nosec + assert client.bytesize == 7 # nosec client.stop() loop.stop() diff --git a/test/test_client_async_asyncio.py b/test/test_client_async_asyncio.py index b9b24cba4..5a0143304 100644 --- a/test/test_client_async_asyncio.py +++ b/test/test_client_async_asyncio.py @@ -1,4 +1,4 @@ -""" Test client asyncio. """ +"""Test client asyncio.""" import sys from unittest import mock from test.asyncio_test_helper import return_as_coroutine, run_coroutine @@ -22,35 +22,36 @@ class TestAsyncioClient: - """ Test asyncio client. """ - def test_base_modbus_async_client_protocol(self): # pylint: disable=no-self-use - """ Test base modbus async client protocol. """ + """Test asyncio client.""" + + def test_base_modbus_async_client_protocol(self): # pylint: disable=no-self-use + """Test base modbus async client protocol.""" protocol = BaseModbusAsyncClientProtocol() - assert protocol.factory is None #nosec - assert protocol.transport is None #nosec - assert not protocol._connected #nosec pylint: disable=protected-access + assert protocol.factory is None # nosec + assert protocol.transport is None # nosec + assert not protocol._connected # nosec pylint: disable=protected-access - def test_protocol_connection_state_propagation_to_factory(self): # pylint: disable=no-self-use - """ Test protocol connection state progration to factory. """ + def test_protocol_connection_state_propagation_to_factory(self): # pylint: disable=no-self-use + """Test protocol connection state progration to factory.""" protocol = ModbusClientProtocol() - assert protocol.factory is None #nosec - assert protocol.transport is None #nosec - assert not protocol._connected #nosec pylint: disable=protected-access + assert protocol.factory is None # nosec + assert protocol.transport is None # nosec + assert not protocol._connected # nosec pylint: disable=protected-access protocol.factory = mock.MagicMock() protocol.connection_made(mock.sentinel.TRANSPORT) - assert protocol.transport is mock.sentinel.TRANSPORT #nosec - protocol.factory.protocol_made_connection.assert_called_once_with( # pylint: disable=no-member + assert protocol.transport is mock.sentinel.TRANSPORT # nosec + protocol.factory.protocol_made_connection.assert_called_once_with( # pylint: disable=no-member protocol) - assert not protocol.factory.protocol_lost_connection.call_count #nosec pylint: disable=no-member + assert not protocol.factory.protocol_lost_connection.call_count # nosec pylint: disable=no-member protocol.factory.reset_mock() protocol.connection_lost(mock.sentinel.REASON) - assert protocol.transport is None #nosec - assert not protocol.factory.protocol_made_connection.call_count #nosec pylint: disable=no-member - protocol.factory.protocol_lost_connection.assert_called_once_with( # pylint: disable=no-member + assert protocol.transport is None # nosec + assert not protocol.factory.protocol_made_connection.call_count # nosec pylint: disable=no-member + protocol.factory.protocol_lost_connection.assert_called_once_with( # pylint: disable=no-member protocol) protocol.raise_future = mock.MagicMock() request = mock.MagicMock() @@ -61,84 +62,85 @@ def test_protocol_connection_state_propagation_to_factory(self): # pylint: disab else: call_args = protocol.raise_future.call_args[0] protocol.raise_future.assert_called_once() - assert call_args[0] == request #nosec - assert isinstance(call_args[1], ConnectionException) #nosec + assert call_args[0] == request # nosec + assert isinstance(call_args[1], ConnectionException) # nosec - def test_factory_initialization_state(self): # pylint: disable=no-self-use - """ Test factory initialization state. """ + def test_factory_initialization_state(self): # pylint: disable=no-self-use + """Test factory initialization state.""" mock_protocol_class = mock.MagicMock() mock_loop = mock.MagicMock() client = ReconnectingAsyncioModbusTcpClient( protocol_class=mock_protocol_class, loop=mock_loop) - assert not client.connected #nosec - assert client.delay_ms < client.DELAY_MAX_MS #nosec + assert not client.connected # nosec + assert client.delay_ms < client.DELAY_MAX_MS # nosec - assert client.loop is mock_loop #nosec - assert client.protocol_class is mock_protocol_class #nosec + assert client.loop is mock_loop # nosec + assert client.protocol_class is mock_protocol_class # nosec @pytest.mark.asyncio - async def test_initialization_tcp_in_loop(self): # pylint: disable=no-self-use - """ Test initialization tcp in loop. """ - _, client = AsyncModbusTCPClient(schedulers.ASYNC_IO, #NOSONAR pylint: disable=unpacking-non-sequence + async def test_initialization_tcp_in_loop(self): # pylint: disable=no-self-use + """Test initialization tcp in loop.""" + _, client = AsyncModbusTCPClient(schedulers.ASYNC_IO, # NOSONAR pylint: disable=unpacking-non-sequence port=5020) client = await client - assert not client.connected #nosec - assert client.port == 5020 #nosec - assert client.delay_ms < client.DELAY_MAX_MS #nosec + assert not client.connected # nosec + assert client.port == 5020 # nosec + assert client.delay_ms < client.DELAY_MAX_MS # nosec @pytest.mark.asyncio - async def test_initialization_udp_in_loop(self): # pylint: disable=no-self-use - """ Test initialization udp in loop. """ - _, client = AsyncModbusUDPClient(schedulers.ASYNC_IO, port=5020) # pylint: disable=unpacking-non-sequence + async def test_initialization_udp_in_loop(self): # pylint: disable=no-self-use + """Test initialization udp in loop.""" + _, client = AsyncModbusUDPClient(schedulers.ASYNC_IO, port=5020) # pylint: disable=unpacking-non-sequence client = await client - assert client.connected #nosec - assert client.port == 5020 #nosec - assert client.delay_ms < client.DELAY_MAX_MS #nosec + assert client.connected # nosec + assert client.port == 5020 # nosec + assert client.delay_ms < client.DELAY_MAX_MS # nosec @pytest.mark.asyncio - async def test_initialization_tls_in_loop(self): # pylint: disable=no-self-use - """ Test initialization tls in loop. """ - _, client = AsyncModbusTLSClient(schedulers.ASYNC_IO, port=5020) #NOSONAR pylint: disable=unpacking-non-sequence + async def test_initialization_tls_in_loop(self): # pylint: disable=no-self-use + """Test initialization tls in loop.""" + _, client = AsyncModbusTLSClient( # NOSONAR pylint: disable=unpacking-non-sequence + schedulers.ASYNC_IO, port=5020) client = await client - assert not client.connected #nosec - assert client.port == 5020 #nosec - assert client.delay_ms < client.DELAY_MAX_MS #nosec + assert not client.connected # nosec + assert client.port == 5020 # nosec + assert client.delay_ms < client.DELAY_MAX_MS # nosec @pytest.mark.asyncio - def test_initialization_serial_in_loop(self): # pylint: disable=no-self-use - """ Test initialization serial in loop. """ - _, client = AsyncModbusSerialClient( #NOSONAR pylint: disable=unpacking-non-sequence - schedulers.ASYNC_IO, port='/tmp/ptyp0', baudrate=9600, method='rtu') #NOSONAR #nosec + def test_initialization_serial_in_loop(self): # pylint: disable=no-self-use + """Test initialization serial in loop.""" + _, client = AsyncModbusSerialClient( # NOSONAR pylint: disable=unpacking-non-sequence + schedulers.ASYNC_IO, port='/tmp/ptyp0', baudrate=9600, method='rtu') # NOSONAR #nosec - assert client.port == '/tmp/ptyp0' # nosec NOSONAR - assert client.baudrate == 9600 #nosec + assert client.port == '/tmp/ptyp0' # nosec NOSONAR + assert client.baudrate == 9600 # nosec - def test_factory_reset_wait_before_reconnect(self): # pylint: disable=no-self-use - """ Test factory reset wait before reconnect. """ + def test_factory_reset_wait_before_reconnect(self): # pylint: disable=no-self-use + """Test factory reset wait before reconnect.""" mock_protocol_class = mock.MagicMock() mock_loop = mock.MagicMock() client = ReconnectingAsyncioModbusTcpClient( protocol_class=mock_protocol_class, loop=mock_loop) initial_delay = client.delay_ms - assert initial_delay > 0 #nosec + assert initial_delay > 0 # nosec client.delay_ms *= 2 - assert client.delay_ms > initial_delay #nosec + assert client.delay_ms > initial_delay # nosec client.reset_delay() - assert client.delay_ms == initial_delay #nosec + assert client.delay_ms == initial_delay # nosec - def test_factory_stop(self): # pylint: disable=no-self-use - """ Test factory stop. """ + def test_factory_stop(self): # pylint: disable=no-self-use + """Test factory stop.""" mock_protocol_class = mock.MagicMock() mock_loop = mock.MagicMock() client = ReconnectingAsyncioModbusTcpClient( protocol_class=mock_protocol_class, loop=mock_loop) - assert not client.connected #nosec + assert not client.connected # nosec client.stop() - assert not client.connected #nosec + assert not client.connected # nosec # fake connected client: client.protocol = mock.MagicMock() @@ -147,31 +149,31 @@ def test_factory_stop(self): # pylint: disable=no-self-use client.stop() client.protocol.transport.close.assert_called_once_with() - def test_factory_protocol_made_connection(self): # pylint: disable=no-self-use - """ Test factory protocol made connection. """ + def test_factory_protocol_made_connection(self): # pylint: disable=no-self-use + """Test factory protocol made connection.""" mock_protocol_class = mock.MagicMock() mock_loop = mock.MagicMock() client = ReconnectingAsyncioModbusTcpClient( protocol_class=mock_protocol_class, loop=mock_loop) - assert not client.connected #nosec - assert client.protocol is None #nosec + assert not client.connected # nosec + assert client.protocol is None # nosec client.protocol_made_connection(mock.sentinel.PROTOCOL) - assert client.connected #nosec - assert client.protocol is mock.sentinel.PROTOCOL #nosec + assert client.connected # nosec + assert client.protocol is mock.sentinel.PROTOCOL # nosec client.protocol_made_connection(mock.sentinel.PROTOCOL_UNEXPECTED) - assert client.connected #nosec - assert client.protocol is mock.sentinel.PROTOCOL #nosec + assert client.connected # nosec + assert client.protocol is mock.sentinel.PROTOCOL # nosec @mock.patch('pymodbus.client.asynchronous.async_io.asyncio.ensure_future') - def test_factory_protocol_lost_connection(self, mock_async): # pylint: disable=no-self-use - """ Test factory protocol lost connection. """ + def test_factory_protocol_lost_connection(self, mock_async): # pylint: disable=no-self-use + """Test factory protocol lost connection.""" mock_protocol_class = mock.MagicMock() mock_loop = mock.MagicMock() client = ReconnectingAsyncioModbusTcpClient( protocol_class=mock_protocol_class, loop=mock_loop) - assert not client.connected #nosec - assert client.protocol is None #nosec + assert not client.connected # nosec + assert client.protocol is None # nosec # fake client is connected and *then* looses connection: client.connected = True @@ -180,7 +182,7 @@ def test_factory_protocol_lost_connection(self, mock_async): # pylint: disable=n client.protocol = mock.sentinel.PROTOCOL client.protocol_lost_connection(mock.sentinel.PROTOCOL_UNEXPECTED) mock_async.reset_mock() - assert not client.connected #nosec + assert not client.connected # nosec client.connected = True with mock.patch( @@ -192,19 +194,19 @@ def test_factory_protocol_lost_connection(self, mock_async): # pylint: disable=n if sys.version_info == (3, 7): mock_async.assert_called_once_with( mock.sentinel.RECONNECT_GENERATOR, loop=mock_loop) - assert not client.connected #nosec - assert client.protocol is None #nosec + assert not client.connected # nosec + assert client.protocol is None # nosec @pytest.mark.asyncio - async def test_factory_start_success(self): # pylint: disable=no-self-use - """ Test factory start success. """ + async def test_factory_start_success(self): # pylint: disable=no-self-use + """Test factory start success.""" mock_protocol_class = mock.MagicMock() client = ReconnectingAsyncioModbusTcpClient(protocol_class=mock_protocol_class) await client.start(mock.sentinel.HOST, mock.sentinel.PORT) @mock.patch('pymodbus.client.asynchronous.async_io.asyncio.ensure_future') - def test_factory_start_failing_and_retried(self, mock_async): # pylint: disable=no-self-use - """ Test factory start failing and retried. """ + def test_factory_start_failing_and_retried(self, mock_async): # pylint: disable=no-self-use + """Test factory start failing and retried.""" mock_protocol_class = mock.MagicMock() mock_loop = mock.MagicMock() mock_loop.create_connection = mock.MagicMock(side_effect=Exception('Did not work.')) @@ -224,8 +226,8 @@ def test_factory_start_failing_and_retried(self, mock_async): # pylint: disable= # @pytest.mark.asyncio @mock.patch('pymodbus.client.asynchronous.async_io.asyncio.sleep') - def test_factory_reconnect(self, mock_sleep): # pylint: disable=no-self-use - """ Test factory reconnect. """ + def test_factory_reconnect(self, mock_sleep): # pylint: disable=no-self-use + """Test factory reconnect.""" mock_protocol_class = mock.MagicMock() mock_sleep.side_effect = return_as_coroutine() mock_loop = mock.MagicMock() @@ -233,43 +235,43 @@ def test_factory_reconnect(self, mock_sleep): # pylint: disable=no-self-use protocol_class=mock_protocol_class, loop=mock_loop) client.delay_ms = 5000 - run_coroutine(client._reconnect()) # pylint: disable=protected-access + run_coroutine(client._reconnect()) # pylint: disable=protected-access mock_sleep.assert_called_once_with(5) - assert mock_loop.create_connection.call_count == 1 #nosec + assert mock_loop.create_connection.call_count == 1 # nosec @pytest.mark.parametrize("protocol", protocols) - def test_client_protocol_connection_made(self, protocol): # pylint: disable=no-self-use - """ Test the client protocol close. """ + def test_client_protocol_connection_made(self, protocol): # pylint: disable=no-self-use + """Test the client protocol close.""" protocol = protocol(ModbusSocketFramer(ClientDecoder())) transport = mock.MagicMock() factory = mock.MagicMock() if isinstance(protocol, ModbusUdpClientProtocol): protocol.factory = factory protocol.connection_made(transport) - assert protocol.transport == transport #nosec - assert protocol.connected #nosec + assert protocol.transport == transport # nosec + assert protocol.connected # nosec if isinstance(protocol, ModbusUdpClientProtocol): - assert protocol.factory.protocol_made_connection.call_count == 1 #nosec + assert protocol.factory.protocol_made_connection.call_count == 1 # nosec @pytest.mark.parametrize("protocol", protocols) - def test_client_protocol_close(self, protocol): # pylint: disable=no-self-use - """ Test the client protocol close. """ + def test_client_protocol_close(self, protocol): # pylint: disable=no-self-use + """Test the client protocol close.""" protocol = protocol(ModbusSocketFramer(ClientDecoder())) transport = mock.MagicMock() factory = mock.MagicMock() if isinstance(protocol, ModbusUdpClientProtocol): protocol.factory = factory protocol.connection_made(transport) - assert protocol.transport == transport #nosec - assert protocol.connected #nosec + assert protocol.transport == transport # nosec + assert protocol.connected # nosec protocol.close() transport.close.assert_called_once_with() - assert not protocol.connected #nosec + assert not protocol.connected # nosec @pytest.mark.skip("To fix") @pytest.mark.parametrize("protocol", protocols) - def test_client_protocol_connection_lost(self, protocol): # pylint: disable=no-self-use - """ Test the client protocol connection lost""" + def test_client_protocol_connection_lost(self, protocol): # pylint: disable=no-self-use + """Test the client protocol connection lost""" framer = ModbusSocketFramer(None) protocol = protocol(framer=framer, timeout=0) protocol.execute = mock.MagicMock() @@ -288,34 +290,34 @@ def test_client_protocol_connection_lost(self, protocol): # pylint: disable=no-s # d = await d protocol.connection_lost("REASON") excp = response.exception() - assert isinstance(excp, ConnectionException) #nosec + assert isinstance(excp, ConnectionException) # nosec if isinstance(protocol, ModbusUdpClientProtocol): - assert protocol.factory.protocol_lost_connection.call_count == 1 #nosec + assert protocol.factory.protocol_lost_connection.call_count == 1 # nosec @pytest.mark.parametrize("protocol", protocols) - async def test_client_protocol_data_received(self, protocol): # pylint: disable=no-self-use - """ Test the client protocol data received """ + async def test_client_protocol_data_received(self, protocol): # pylint: disable=no-self-use + """Test the client protocol data received""" protocol = protocol(ModbusSocketFramer(ClientDecoder())) transport = mock.MagicMock() protocol.connection_made(transport) - assert protocol.transport == transport #nosec - assert protocol.connected #nosec + assert protocol.transport == transport # nosec + assert protocol.connected # nosec data = b'\x00\x00\x12\x34\x00\x06\xff\x01\x01\x02\x00\x04' # setup existing request - response = protocol._buildResponse(0x00) # pylint: disable=protected-access + response = protocol._buildResponse(0x00) # pylint: disable=protected-access if isinstance(protocol, ModbusUdpClientProtocol): protocol.datagram_received(data, None) else: protocol.data_received(data) result = response.result() - assert isinstance(result, ReadCoilsResponse) #nosec + assert isinstance(result, ReadCoilsResponse) # nosec # @pytest.mark.skip("To fix") @pytest.mark.asyncio @pytest.mark.parametrize("protocol", protocols) - async def test_client_protocol_execute(self, protocol): # pylint: disable=no-self-use - """ Test the client protocol execute method """ + async def test_client_protocol_execute(self, protocol): # pylint: disable=no-self-use + """Test the client protocol execute method""" framer = ModbusSocketFramer(None) protocol = protocol(framer=framer) protocol.create_future = mock.MagicMock() @@ -330,11 +332,11 @@ async def test_client_protocol_execute(self, protocol): # pylint: disable=no-sel response = await protocol.execute(request) tid = request.transaction_id f_trans = protocol.transaction.getTransaction(tid) - assert response == f_trans #nosec + assert response == f_trans # nosec @pytest.mark.parametrize("protocol", protocols) - async def test_client_protocol_handle_response(self, protocol): # pylint: disable=no-self-use - """ Test the client protocol handles responses """ + async def test_client_protocol_handle_response(self, protocol): # pylint: disable=no-self-use + """Test the client protocol handles responses""" protocol = protocol() transport = mock.MagicMock() protocol.connection_made(transport=transport) @@ -344,26 +346,26 @@ async def test_client_protocol_handle_response(self, protocol): # pylint: disabl # import asyncio # protocol.create_future.return_value = asyncio.Future() # handle skipped cases - protocol._handleResponse(None) # pylint: disable=protected-access - protocol._handleResponse(reply) # pylint: disable=protected-access + protocol._handleResponse(None) # pylint: disable=protected-access + protocol._handleResponse(reply) # pylint: disable=protected-access # handle existing cases - response = protocol._buildResponse(0x00) # pylint: disable=protected-access - protocol._handleResponse(reply) # pylint: disable=protected-access + response = protocol._buildResponse(0x00) # pylint: disable=protected-access + protocol._handleResponse(reply) # pylint: disable=protected-access result = response.result() - assert result == reply #nosec + assert result == reply # nosec @pytest.mark.parametrize("protocol", protocols) - async def test_client_protocol_build_response(self, protocol): # pylint: disable=no-self-use - """ Test the udp client protocol builds responses """ + async def test_client_protocol_build_response(self, protocol): # pylint: disable=no-self-use + """Test the udp client protocol builds responses""" protocol = protocol() - assert not len(list(protocol.transaction)) #nosec pylint: disable=use-implicit-booleaness-not-len + assert not len(list(protocol.transaction)) # nosec pylint: disable=use-implicit-booleaness-not-len - response = protocol._buildResponse(0x00) #nosec pylint: disable=protected-access + response = protocol._buildResponse(0x00) # nosec pylint: disable=protected-access excp = response.exception() - assert isinstance(excp, ConnectionException) #nosec - assert not len(list(protocol.transaction)) #nosec pylint: disable=use-implicit-booleaness-not-len + assert isinstance(excp, ConnectionException) # nosec + assert not len(list(protocol.transaction)) # nosec pylint: disable=use-implicit-booleaness-not-len - protocol._connected = True # pylint: disable=protected-access - protocol._buildResponse(0x00) # pylint: disable=protected-access - assert len(list(protocol.transaction)) == 1 #nosec + protocol._connected = True # pylint: disable=protected-access + protocol._buildResponse(0x00) # pylint: disable=protected-access + assert len(list(protocol.transaction)) == 1 # nosec diff --git a/test/test_client_async_tornado.py b/test/test_client_async_tornado.py index 457153229..360b3975b 100644 --- a/test/test_client_async_tornado.py +++ b/test/test_client_async_tornado.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test client tornado. """ +"""Test client tornado.""" import unittest from unittest.mock import patch, Mock import pytest @@ -23,55 +23,55 @@ class AsynchronousClientTest(unittest.TestCase): - """ Unittest for the pymodbus.client.asynchronous module. """ + """Unittest for the pymodbus.client.asynchronous module.""" # -----------------------------------------------------------------------# # Test Client client # -----------------------------------------------------------------------# def test_base_client_init(self): - """ Test the client client initialize """ + """Test the client client initialize""" client = BaseTornadoClient() self.assertTrue(client.port == 502) self.assertTrue(client.host == "127.0.0.1") self.assertEqual(0, len(list(client.transaction))) - self.assertFalse(client._connected) # pylint: disable=protected-access + self.assertFalse(client._connected) # pylint: disable=protected-access self.assertTrue(client.io_loop is None) self.assertTrue(isinstance(client.framer, ModbusSocketFramer)) framer = object() client = BaseTornadoClient(framer=framer, ioloop=schedulers.IO_LOOP) self.assertEqual(0, len(list(client.transaction))) - self.assertFalse(client._connected) # pylint: disable=protected-access + self.assertFalse(client._connected) # pylint: disable=protected-access self.assertTrue(client.io_loop == schedulers.IO_LOOP) self.assertTrue(framer is client.framer) @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.IOStream") - def test_base_client_on_receive(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the BaseTornado client data received """ + def test_base_client_on_receive(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument + """Test the BaseTornado client data received""" client = AsyncModbusTCPClient(port=5020) client.connect() out = [] data = b'\x00\x00\x12\x34\x00\x06\xff\x01\x01\x02\x00\x04' # setup existing request - response = client._build_response(0x00) # pylint: disable=protected-access - response.add_done_callback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda + response = client._build_response(0x00) # pylint: disable=protected-access + response.add_done_callback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda client.on_receive(data) self.assertTrue(isinstance(response.result(), ReadCoilsResponse)) data = b'' out = [] - response = client._build_response(0x01) # pylint: disable=protected-access + response = client._build_response(0x01) # pylint: disable=protected-access client.on_receive(data) - response.add_done_callback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda + response.add_done_callback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda self.assertFalse(out) @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.IOStream") - def test_base_client_execute(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the BaseTornado client execute method """ + def test_base_client_execute(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument + """Test the BaseTornado client execute method""" client = AsyncModbusTCPClient(port=5020) client.connect() client.stream = Mock() @@ -84,8 +84,8 @@ def test_base_client_execute(self, mock_iostream, mock_ioloop): # pylint: disabl @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.IOStream") - def test_base_client_handle_response(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the BaseTornado client handles responses """ + def test_base_client_handle_response(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument + """Test the BaseTornado client handles responses""" client = AsyncModbusTCPClient(port=5020) client.connect() out = [] @@ -93,19 +93,19 @@ def test_base_client_handle_response(self, mock_iostream, mock_ioloop): # pylint reply.transaction_id = 0x00 # handle skipped cases - client._handle_response(None) # pylint: disable=protected-access - client._handle_response(reply) # pylint: disable=protected-access + client._handle_response(None) # pylint: disable=protected-access + client._handle_response(reply) # pylint: disable=protected-access # handle existing cases - response = client._build_response(0x00) # pylint: disable=protected-access - response.add_done_callback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda - client._handle_response(reply) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access + response.add_done_callback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda + client._handle_response(reply) # pylint: disable=protected-access self.assertEqual(response.result(), reply) @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.IOStream") - def test_base_client_build_response(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the BaseTornado client client builds responses """ + def test_base_client_build_response(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument + """Test the BaseTornado client client builds responses""" client = BaseTornadoClient() self.assertEqual(0, len(list(client.transaction))) @@ -113,19 +113,19 @@ def handle_failure(failure): exc = failure.exception() self.assertTrue(isinstance(exc, ConnectionException)) - response = client._build_response(0x00) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access response.add_done_callback(handle_failure) self.assertEqual(0, len(list(client.transaction))) - client._connected = True # pylint: disable=protected-access - client._build_response(0x00) # pylint: disable=protected-access + client._connected = True # pylint: disable=protected-access + client._build_response(0x00) # pylint: disable=protected-access self.assertEqual(1, len(list(client.transaction))) # -----------------------------------------------------------------------# # Test TCP Client client # -----------------------------------------------------------------------# def test_tcp_client_init(self): - """ Test the tornado tcp client client initialize """ + """Test the tornado tcp client client initialize""" client = AsyncModbusTCPClient() self.assertEqual(0, len(list(client.transaction))) self.assertTrue(isinstance(client.framer, ModbusSocketFramer)) @@ -136,36 +136,36 @@ def test_tcp_client_init(self): @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.IOStream") - def test_tcp_client_connect(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the tornado tcp client client connect """ + def test_tcp_client_connect(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument + """Test the tornado tcp client client connect""" client = AsyncModbusTCPClient(port=5020) self.assertTrue(client.port, 5020) - self.assertFalse(client._connected) # pylint: disable=protected-access + self.assertFalse(client._connected) # pylint: disable=protected-access client.connect() - self.assertTrue(client._connected) # pylint: disable=protected-access + self.assertTrue(client._connected) # pylint: disable=protected-access @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.IOStream") - def test_tcp_client_disconnect(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the tornado tcp client client disconnect """ + def test_tcp_client_disconnect(self, mock_iostream, mock_ioloop): # pylint: disable=unused-argument + """Test the tornado tcp client client disconnect""" client = AsyncModbusTCPClient(port=5020) client.connect() def handle_failure(failure): self.assertTrue(isinstance(failure.exception(), ConnectionException)) - response = client._build_response(0x00) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access response.add_done_callback(handle_failure) - self.assertTrue(client._connected) # pylint: disable=protected-access + self.assertTrue(client._connected) # pylint: disable=protected-access client.close() - self.assertFalse(client._connected) # pylint: disable=protected-access + self.assertFalse(client._connected) # pylint: disable=protected-access # -----------------------------------------------------------------------# # Test Serial Client client # -----------------------------------------------------------------------# def test_serial_client_init(self): - """ Test the tornado serial client client initialize """ + """Test the tornado serial client client initialize""" client = AsyncModbusSerialClient(ioloop=schedulers.IO_LOOP, framer=ModbusRtuFramer( ClientDecoder()), @@ -180,43 +180,44 @@ def test_serial_client_init(self): @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.SerialIOStream") @patch("pymodbus.client.asynchronous.tornado.Serial") - def test_serial_client_connect(self, mock_serial, mock_seriostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the tornado serial client client connect """ + def test_serial_client_connect(self, mock_serial, mock_seriostream, mock_ioloop): # pylint: disable=unused-argument + """Test the tornado serial client client connect""" client = AsyncModbusSerialClient(ioloop=schedulers.IO_LOOP, framer=ModbusRtuFramer( ClientDecoder()), port=pytest.SERIAL_PORT) self.assertTrue(client.port, pytest.SERIAL_PORT) - self.assertFalse(client._connected) # pylint: disable=protected-access + self.assertFalse(client._connected) # pylint: disable=protected-access client.connect() - self.assertTrue(client._connected) # pylint: disable=protected-access + self.assertTrue(client._connected) # pylint: disable=protected-access client.close() @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.SerialIOStream") @patch("pymodbus.client.asynchronous.tornado.Serial") - def test_serial_client_disconnect(self, mock_serial, mock_seriostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the tornado serial client client disconnect """ + def test_serial_client_disconnect(self, mock_serial, # pylint: disable=unused-argument + mock_seriostream, mock_ioloop): # pylint: disable=unused-argument + """Test the tornado serial client client disconnect""" client = AsyncModbusSerialClient(ioloop=schedulers.IO_LOOP, framer=ModbusRtuFramer( ClientDecoder()), port=pytest.SERIAL_PORT) client.connect() - self.assertTrue(client._connected) # pylint: disable=protected-access + self.assertTrue(client._connected) # pylint: disable=protected-access def handle_failure(failure): self.assertTrue(isinstance(failure.exception(), ConnectionException)) - response = client._build_response(0x00) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access response.add_done_callback(handle_failure) client.close() - self.assertFalse(client._connected) # pylint: disable=protected-access + self.assertFalse(client._connected) # pylint: disable=protected-access @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.SerialIOStream") @patch("pymodbus.client.asynchronous.tornado.Serial") - def test_serial_client_execute(self, mock_serial, mock_seriostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the tornado serial client client execute method """ + def test_serial_client_execute(self, mock_serial, mock_seriostream, mock_ioloop): # pylint: disable=unused-argument + """Test the tornado serial client client execute method""" client = AsyncModbusSerialClient(ioloop=schedulers.IO_LOOP, framer=ModbusRtuFramer( ClientDecoder()), @@ -235,8 +236,9 @@ def test_serial_client_execute(self, mock_serial, mock_seriostream, mock_ioloop) @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.SerialIOStream") @patch("pymodbus.client.asynchronous.tornado.Serial") - def test_serial_client_handle_response(self, mock_serial, mock_seriostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the tornado serial client client handles responses """ + def test_serial_client_handle_response(self, mock_serial, # pylint: disable=unused-argument + mock_seriostream, mock_ioloop): # pylint: disable=unused-argument + """Test the tornado serial client client handles responses""" client = AsyncModbusSerialClient(ioloop=schedulers.IO_LOOP, framer=ModbusRtuFramer( ClientDecoder()), @@ -247,20 +249,23 @@ def test_serial_client_handle_response(self, mock_serial, mock_seriostream, mock reply.transaction_id = 0x00 # handle skipped cases - client._handle_response(None) # pylint: disable=protected-access - client._handle_response(reply) # pylint: disable=protected-access + client._handle_response(None) # pylint: disable=protected-access + client._handle_response(reply) # pylint: disable=protected-access # handle existing cases - response = client._build_response(0x00) # pylint: disable=protected-access - response.add_done_callback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda - client._handle_response(reply) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access + response.add_done_callback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda + client._handle_response(reply) # pylint: disable=protected-access self.assertEqual(response.result(), reply) @patch("pymodbus.client.asynchronous.tornado.IOLoop") @patch("pymodbus.client.asynchronous.tornado.SerialIOStream") @patch("pymodbus.client.asynchronous.tornado.Serial") - def test_serial_client_build_response(self, mock_serial, mock_seriostream, mock_ioloop): # pylint: disable=unused-argument - """ Test the tornado serial client client builds responses """ + def test_serial_client_build_response(self, + mock_serial, # pylint: disable=unused-argument + mock_seriostream, # pylint: disable=unused-argument + mock_ioloop): # pylint: disable=unused-argument + """Test the tornado serial client client builds responses""" client = AsyncModbusSerialClient(ioloop=schedulers.IO_LOOP, framer=ModbusRtuFramer( ClientDecoder()), @@ -270,12 +275,12 @@ def test_serial_client_build_response(self, mock_serial, mock_seriostream, mock_ def handle_failure(failure): exc = failure.exception() self.assertTrue(isinstance(exc, ConnectionException)) - response = client._build_response(0x00) # pylint: disable=protected-access + response = client._build_response(0x00) # pylint: disable=protected-access response.add_done_callback(handle_failure) self.assertEqual(0, len(list(client.transaction))) - client._connected = True # pylint: disable=protected-access - client._build_response(0x00) # pylint: disable=protected-access + client._connected = True # pylint: disable=protected-access + client._build_response(0x00) # pylint: disable=protected-access self.assertEqual(1, len(list(client.transaction))) # -----------------------------------------------------------------------# @@ -283,7 +288,7 @@ def handle_failure(failure): # -----------------------------------------------------------------------# def test_udp_client_init(self): - """ Test the udp client client initialize """ + """Test the udp client client initialize""" client = AsyncModbusUDPClient() self.assertEqual(0, len(list(client.transaction))) self.assertTrue(isinstance(client.framer, ModbusSocketFramer)) @@ -297,7 +302,7 @@ def test_udp_client_init(self): # -----------------------------------------------------------------------# def test_modbus_client_factory(self): - """ Test the base class for all the clients """ + """Test the base class for all the clients""" factory = ModbusClientFactory() self.assertTrue(factory is not None) diff --git a/test/test_client_async_twisted.py b/test/test_client_async_twisted.py index 29024edc9..2af906a16 100644 --- a/test/test_client_async_twisted.py +++ b/test/test_client_async_twisted.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test client async twisted. """ +"""Test client async twisted.""" import unittest from unittest.mock import Mock @@ -15,68 +15,70 @@ from pymodbus.transaction import ModbusSocketFramer, ModbusRtuFramer from pymodbus.bit_read_message import ReadCoilsRequest, ReadCoilsResponse -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + class AsynchronousClientTest(unittest.TestCase): - """ Unittest for the pymodbus.client.asynchronous module. """ + """Unittest for the pymodbus.client.asynchronous module.""" - #-----------------------------------------------------------------------# - # Test Client Protocol - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Test Client Protocol + # -----------------------------------------------------------------------# def test_client_protocol_init(self): - """ Test the client protocol initialize """ + """Test the client protocol initialize""" protocol = ModbusClientProtocol() self.assertEqual(0, len(list(protocol.transaction))) - self.assertFalse(protocol._connected) # pylint: disable=protected-access + self.assertFalse(protocol._connected) # pylint: disable=protected-access self.assertTrue(isinstance(protocol.framer, ModbusSocketFramer)) framer = object() protocol = ModbusClientProtocol(framer=framer) self.assertEqual(0, len(list(protocol.transaction))) - self.assertFalse(protocol._connected) # pylint: disable=protected-access + self.assertFalse(protocol._connected) # pylint: disable=protected-access self.assertTrue(framer is protocol.framer) def test_client_protocol_connect(self): - """ Test the client protocol connect """ + """Test the client protocol connect""" decoder = object() framer = ModbusSocketFramer(decoder) protocol = ModbusClientProtocol(framer=framer) - self.assertFalse(protocol._connected) # pylint: disable=protected-access + self.assertFalse(protocol._connected) # pylint: disable=protected-access protocol.connectionMade() - self.assertTrue(protocol._connected) # pylint: disable=protected-access + self.assertTrue(protocol._connected) # pylint: disable=protected-access def test_client_protocol_disconnect(self): - """ Test the client protocol disconnect """ + """Test the client protocol disconnect""" protocol = ModbusClientProtocol() protocol.connectionMade() + def handle_failure(failure): self.assertTrue(isinstance(failure.value, ConnectionException)) - response = protocol._buildResponse(0x00) # pylint: disable=protected-access + response = protocol._buildResponse(0x00) # pylint: disable=protected-access response.addErrback(handle_failure) - self.assertTrue(protocol._connected) # pylint: disable=protected-access + self.assertTrue(protocol._connected) # pylint: disable=protected-access protocol.connectionLost('because') - self.assertFalse(protocol._connected) # pylint: disable=protected-access + self.assertFalse(protocol._connected) # pylint: disable=protected-access def test_client_protocol_data_received(self): - """ Test the client protocol data received """ + """Test the client protocol data received""" protocol = ModbusClientProtocol(ModbusSocketFramer(ClientDecoder())) protocol.connectionMade() out = [] data = b'\x00\x00\x12\x34\x00\x06\xff\x01\x01\x02\x00\x04' # setup existing request - response = protocol._buildResponse(0x00) # pylint: disable=protected-access - response.addCallback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda + response = protocol._buildResponse(0x00) # pylint: disable=protected-access + response.addCallback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda protocol.dataReceived(data) self.assertTrue(isinstance(out[0], ReadCoilsResponse)) def test_client_protocol_execute(self): - """ Test the client protocol execute method """ + """Test the client protocol execute method""" framer = ModbusSocketFramer(None) protocol = ModbusClientProtocol(framer=framer) protocol.connectionMade() @@ -89,7 +91,7 @@ def test_client_protocol_execute(self): self.assertEqual(response, protocol.transaction.getTransaction(tid)) def test_client_protocol_handle_response(self): - """ Test the client protocol handles responses """ + """Test the client protocol handles responses""" protocol = ModbusClientProtocol() protocol.connectionMade() out = [] @@ -97,35 +99,35 @@ def test_client_protocol_handle_response(self): reply.transaction_id = 0x00 # handle skipped cases - protocol._handleResponse(None) # pylint: disable=protected-access - protocol._handleResponse(reply) # pylint: disable=protected-access + protocol._handleResponse(None) # pylint: disable=protected-access + protocol._handleResponse(reply) # pylint: disable=protected-access # handle existing cases - response = protocol._buildResponse(0x00) # pylint: disable=protected-access - response.addCallback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda - protocol._handleResponse(reply) # pylint: disable=protected-access + response = protocol._buildResponse(0x00) # pylint: disable=protected-access + response.addCallback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda + protocol._handleResponse(reply) # pylint: disable=protected-access self.assertEqual(out[0], reply) def test_client_protocol_build_response(self): - """ Test the udp client protocol builds responses """ + """Test the udp client protocol builds responses""" protocol = ModbusClientProtocol() self.assertEqual(0, len(list(protocol.transaction))) def handle_failure(failure): self.assertTrue(isinstance(failure.value, ConnectionException)) - response = protocol._buildResponse(0x00) # pylint: disable=protected-access + response = protocol._buildResponse(0x00) # pylint: disable=protected-access response.addErrback(handle_failure) self.assertEqual(0, len(list(protocol.transaction))) - protocol._connected = True # pylint: disable=protected-access - protocol._buildResponse(0x00) # pylint: disable=protected-access + protocol._connected = True # pylint: disable=protected-access + protocol._buildResponse(0x00) # pylint: disable=protected-access self.assertEqual(1, len(list(protocol.transaction))) - #-----------------------------------------------------------------------# - # Test TCP Client Protocol - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Test TCP Client Protocol + # -----------------------------------------------------------------------# def test_tcp_client_protocol_init(self): - """ Test the udp client protocol initialize """ + """Test the udp client protocol initialize""" protocol = ModbusTcpClientProtocol() self.assertEqual(0, len(list(protocol.transaction))) self.assertTrue(isinstance(protocol.framer, ModbusSocketFramer)) @@ -134,11 +136,11 @@ def test_tcp_client_protocol_init(self): protocol = ModbusClientProtocol(framer=framer) self.assertTrue(framer is protocol.framer) - #-----------------------------------------------------------------------# - # Test Serial Client Protocol - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Test Serial Client Protocol + # -----------------------------------------------------------------------# def test_serial_client_protocol_init(self): - """ Test the udp client protocol initialize """ + """Test the udp client protocol initialize""" protocol = ModbusSerClientProtocol() self.assertEqual(0, len(list(protocol.transaction))) self.assertTrue(isinstance(protocol.framer, ModbusRtuFramer)) @@ -147,12 +149,12 @@ def test_serial_client_protocol_init(self): protocol = ModbusClientProtocol(framer=framer) self.assertTrue(framer is protocol.framer) - #-----------------------------------------------------------------------# - # Test Udp Client Protocol - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Test Udp Client Protocol + # -----------------------------------------------------------------------# def test_udp_client_protocol_init(self): - """ Test the udp client protocol initialize """ + """Test the udp client protocol initialize""" protocol = ModbusUdpClientProtocol() self.assertEqual(0, len(list(protocol.transaction))) self.assertTrue(isinstance(protocol.framer, ModbusSocketFramer)) @@ -162,21 +164,21 @@ def test_udp_client_protocol_init(self): self.assertTrue(framer is protocol.framer) def test_udp_client_protocol_data_received(self): - """ Test the udp client protocol data received """ + """Test the udp client protocol data received""" protocol = ModbusUdpClientProtocol() out = [] data = b'\x00\x00\x12\x34\x00\x06\xff\x01\x01\x02\x00\x04' server = ('127.0.0.1', 12345) # setup existing request - response = protocol._buildResponse(0x00) # pylint: disable=protected-access - response.addCallback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda + response = protocol._buildResponse(0x00) # pylint: disable=protected-access + response.addCallback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda protocol.datagramReceived(data, server) self.assertTrue(isinstance(out[0], ReadCoilsResponse)) def test_udp_client_protocol_execute(self): - """ Test the udp client protocol execute method """ + """Test the udp client protocol execute method""" protocol = ModbusUdpClientProtocol() protocol.transport = Mock() protocol.transport.write = Mock() @@ -187,41 +189,42 @@ def test_udp_client_protocol_execute(self): self.assertEqual(response, protocol.transaction.getTransaction(tid)) def test_udp_client_protocol_handle_response(self): - """ Test the udp client protocol handles responses """ + """Test the udp client protocol handles responses""" protocol = ModbusUdpClientProtocol() out = [] reply = ReadCoilsRequest(1, 1) reply.transaction_id = 0x00 # handle skipped cases - protocol._handleResponse(None) # pylint: disable=protected-access - protocol._handleResponse(reply) # pylint: disable=protected-access + protocol._handleResponse(None) # pylint: disable=protected-access + protocol._handleResponse(reply) # pylint: disable=protected-access # handle existing cases - response = protocol._buildResponse(0x00) # pylint: disable=protected-access - response.addCallback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda - protocol._handleResponse(reply) # pylint: disable=protected-access + response = protocol._buildResponse(0x00) # pylint: disable=protected-access + response.addCallback(lambda v: out.append(v)) # pylint: disable=unnecessary-lambda + protocol._handleResponse(reply) # pylint: disable=protected-access self.assertEqual(out[0], reply) def test_udp_client_protocol_build_response(self): - """ Test the udp client protocol builds responses """ + """Test the udp client protocol builds responses""" protocol = ModbusUdpClientProtocol() self.assertEqual(0, len(list(protocol.transaction))) - protocol._buildResponse(0x00) # pylint: disable=protected-access + protocol._buildResponse(0x00) # pylint: disable=protected-access self.assertEqual(1, len(list(protocol.transaction))) - #-----------------------------------------------------------------------# - # Test Client Factories - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Test Client Factories + # -----------------------------------------------------------------------# def test_modbus_client_factory(self): - """ Test the base class for all the clients """ + """Test the base class for all the clients""" factory = ModbusClientFactory() self.assertTrue(factory is not None) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_client_common.py b/test/test_client_common.py index d6544ccee..83be96b71 100644 --- a/test/test_client_common.py +++ b/test/test_client_common.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test client common. """ +"""Test client common.""" import unittest from pymodbus.client.common import ModbusClientMixin from pymodbus.bit_read_message import ( @@ -21,62 +21,64 @@ WriteSingleRegisterRequest, ) -#---------------------------------------------------------------------------# -# Mocks -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Mocks +# ---------------------------------------------------------------------------# + + class MockClient(ModbusClientMixin): - """ Mock client. """ + """Mock client.""" - def execute(self, request): # pylint: disable=no-self-use - """ Mock execute. """ + def execute(self, request): # pylint: disable=no-self-use + """Mock execute.""" return request -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class ModbusCommonClientTests(unittest.TestCase): - """ Modbus common client tests. """ + """Modbus common client tests.""" - #-----------------------------------------------------------------------# - # Setup/TearDown - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Setup/TearDown + # -----------------------------------------------------------------------# def setUp(self): - """ Initializes the test environment and builds request/result - encoding pairs - """ + """Initialize the test environment and builds request/result encoding pairs.""" self.client = MockClient() def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.client - #-----------------------------------------------------------------------# - # Tests - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Tests + # -----------------------------------------------------------------------# def test_modbus_client_mixin_methods(self): - """ This tests that the mixing returns the correct request object """ + """This tests that the mixing returns the correct request object""" arguments = { 'read_address': 1, 'read_count': 1, 'write_address': 1, 'write_registers': 1 } self.assertTrue( - isinstance(self.client.read_coils(1,1), ReadCoilsRequest)) + isinstance(self.client.read_coils(1, 1), ReadCoilsRequest)) self.assertTrue( - isinstance(self.client.read_discrete_inputs(1,1), ReadDiscreteInputsRequest)) + isinstance(self.client.read_discrete_inputs(1, 1), ReadDiscreteInputsRequest)) self.assertTrue( - isinstance(self.client.write_coil(1,True), WriteSingleCoilRequest)) + isinstance(self.client.write_coil(1, True), WriteSingleCoilRequest)) self.assertTrue( - isinstance(self.client.write_coils(1,[True]), WriteMultipleCoilsRequest)) + isinstance(self.client.write_coils(1, [True]), WriteMultipleCoilsRequest)) self.assertTrue( - isinstance(self.client.write_register(1,0x00), WriteSingleRegisterRequest)) + isinstance(self.client.write_register(1, 0x00), WriteSingleRegisterRequest)) self.assertTrue( - isinstance(self.client.write_registers(1,[0x00]), WriteMultipleRegistersRequest)) + isinstance(self.client.write_registers(1, [0x00]), WriteMultipleRegistersRequest)) self.assertTrue( - isinstance(self.client.read_holding_registers(1,1), ReadHoldingRegistersRequest)) + isinstance(self.client.read_holding_registers(1, 1), ReadHoldingRegistersRequest)) self.assertTrue( - isinstance(self.client.read_input_registers(1,1), ReadInputRegistersRequest)) + isinstance(self.client.read_input_registers(1, 1), ReadInputRegistersRequest)) self.assertTrue( isinstance(self.client.readwrite_registers(**arguments), - ReadWriteMultipleRegistersRequest)) + ReadWriteMultipleRegistersRequest)) self.assertTrue( - isinstance(self.client.mask_write_register(1,0,0), MaskWriteRegisterRequest)) + isinstance(self.client.mask_write_register(1, 0, 0), MaskWriteRegisterRequest)) diff --git a/test/test_client_sync.py b/test/test_client_sync.py index c9eb8e20a..0a3cb39f1 100755 --- a/test/test_client_sync.py +++ b/test/test_client_sync.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test client sync. """ +"""Test client sync.""" import socket import ssl import sys @@ -25,44 +25,45 @@ # ---------------------------------------------------------------------------# # Mock Classes # ---------------------------------------------------------------------------# -class mockSocket: #NOSONAR pylint: disable=invalid-name - """ Mock socket. """ +class mockSocket: # NOSONAR pylint: disable=invalid-name + """Mock socket.""" + timeout = 2 - def close(self): # pylint: disable=no-self-use - """ Close. """ + def close(self): # pylint: disable=no-self-use + """Close.""" return True - def recv(self, size): # pylint: disable=no-self-use - """ Receive. """ + def recv(self, size): # pylint: disable=no-self-use + """Receive.""" return b'\x00' * size - def read(self, size): # pylint: disable=no-self-use - """ Read. """ + def read(self, size): # pylint: disable=no-self-use + """Read.""" return b'\x00' * size - def send(self, msg): # pylint: disable=no-self-use - """ Send. """ + def send(self, msg): # pylint: disable=no-self-use + """Send.""" return len(msg) - def write(self, msg): # pylint: disable=no-self-use - """ Write. """ + def write(self, msg): # pylint: disable=no-self-use + """Write.""" return len(msg) - def recvfrom(self, size): # pylint: disable=no-self-use - """ Receive from. """ + def recvfrom(self, size): # pylint: disable=no-self-use + """Receive from.""" return [b'\x00' * size] - def sendto(self, msg, *args): #NOSONAR pylint: disable=no-self-use,unused-argument - """ Send to. """ + def sendto(self, msg, *args): # NOSONAR pylint: disable=no-self-use,unused-argument + """Send to.""" return len(msg) - def setblocking(self, flag): #NOSONAR pylint: disable=no-self-use,unused-argument - """ Set blocking. """ + def setblocking(self, flag): # NOSONAR pylint: disable=no-self-use,unused-argument + """Set blocking.""" return None - def in_waiting(self): # pylint: disable=no-self-use - """ in waiting. """ + def in_waiting(self): # pylint: disable=no-self-use + """Do in waiting.""" return None @@ -75,28 +76,27 @@ def in_waiting(self): # pylint: disable=no-self-use ) - # ---------------------------------------------------------------------------# # Fixture # ---------------------------------------------------------------------------# -class SynchronousClientTest(unittest.TestCase): # pylint: disable=too-many-public-methods - """ Unittest for the pymodbus.client.sync module. """ +class SynchronousClientTest(unittest.TestCase): # pylint: disable=too-many-public-methods + """Unittest for the pymodbus.client.sync module.""" # -----------------------------------------------------------------------# # Test Base Client # -----------------------------------------------------------------------# def test_base_modbus_client(self): - """ Test the base class for all the clients """ - + """Test the base class for all the clients""" client = BaseModbusClient(None) client.transaction = None - self.assertRaises(NotImplementedException, lambda: client.connect()) # pylint: disable=unnecessary-lambda + self.assertRaises(NotImplementedException, lambda: client.connect()) # pylint: disable=unnecessary-lambda self.assertRaises(NotImplementedException, lambda: client.send(None)) self.assertRaises(NotImplementedException, lambda: client.recv(None)) - self.assertRaises(NotImplementedException, lambda: client.__enter__()) # pylint: disable=unnecessary-lambda - self.assertRaises(NotImplementedException, lambda: client.execute()) # pylint: disable=unnecessary-lambda - self.assertRaises(NotImplementedException, lambda: client.is_socket_open()) # pylint: disable=unnecessary-lambda + self.assertRaises(NotImplementedException, lambda: client.__enter__()) # pylint: disable=unnecessary-lambda + self.assertRaises(NotImplementedException, lambda: client.execute()) # pylint: disable=unnecessary-lambda + self.assertRaises(NotImplementedException, lambda: client.is_socket_open() # pylint: disable=unnecessary-lambda + ) # pylint: disable=unnecessary-lambda self.assertEqual("Null Transport", str(client)) client.close() client.__exit__(0, 0, 0) @@ -112,7 +112,7 @@ def test_base_modbus_client(self): self.assertEqual(False, client.debug_enabled()) writable = StringIO() client.trace(writable) - client._dump(b'\x00\x01\x02') # pylint: disable=protected-access + client._dump(b'\x00\x01\x02') # pylint: disable=protected-access self.assertEqual(hexlify_packets(b'\x00\x01\x02'), writable.getvalue()) # a successful execute @@ -123,27 +123,26 @@ def test_base_modbus_client(self): # a unsuccessful connect client.connect = lambda: False - self.assertRaises(ConnectionException, lambda: client.__enter__()) # pylint: disable=unnecessary-lambda - self.assertRaises(ConnectionException, lambda: client.execute()) # pylint: disable=unnecessary-lambda + self.assertRaises(ConnectionException, lambda: client.__enter__()) # pylint: disable=unnecessary-lambda + self.assertRaises(ConnectionException, lambda: client.execute()) # pylint: disable=unnecessary-lambda # -----------------------------------------------------------------------# # Test UDP Client # -----------------------------------------------------------------------# def test_sync_udp_client_instantiation(self): - """ Test sync udp clientt. """ + """Test sync udp clientt.""" client = ModbusUdpClient() self.assertNotEqual(client, None) def tes_basic_sync_udp_client(self): - """ Test the basic methods for the udp sync client""" - + """Test the basic methods for the udp sync client""" # receive/send client = ModbusUdpClient() client.socket = mockSocket() - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access - self.assertEqual(1, client._send(b'\x00')) # pylint: disable=protected-access - self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(1, client._send(b'\x00')) # pylint: disable=protected-access + self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access # connect/disconnect self.assertTrue(client.connect()) @@ -157,20 +156,21 @@ def tes_basic_sync_udp_client(self): @inet_pton_skipif def test_udp_client_address_family(self): - """ Test the Udp client get address family method""" + """Test the Udp client get address family method""" client = ModbusUdpClient() self.assertEqual(socket.AF_INET, - client._get_address_family('127.0.0.1')) # pylint: disable=protected-access - self.assertEqual(socket.AF_INET6, client._get_address_family('::1')) # pylint: disable=protected-access + client._get_address_family('127.0.0.1')) # pylint: disable=protected-access + self.assertEqual(socket.AF_INET6, client._get_address_family('::1')) # pylint: disable=protected-access @inet_pton_skipif def test_udp_client_connect(self): - """ Test the Udp client connection method""" + """Test the Udp client connection method""" with patch.object(socket, 'socket') as mock_method: - class DummySocket: # pylint: disable=too-few-public-methods - """ Dummy socket. """ + class DummySocket: # pylint: disable=too-few-public-methods + """Dummy socket.""" + def settimeout(self, *a, **kwa): - """ Set timeout. """ + """Set timeout.""" mock_method.return_value = DummySocket() client = ModbusUdpClient() @@ -183,30 +183,30 @@ def settimeout(self, *a, **kwa): @inet_pton_skipif def test_udp_client_is_socket_open(self): - """ Test the udp client is_socket_open method""" + """Test the udp client is_socket_open method""" client = ModbusUdpClient() self.assertTrue(client.is_socket_open()) def test_udp_client_send(self): - """ Test the udp client send method""" + """Test the udp client send method""" client = ModbusUdpClient() - self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access client.socket = mockSocket() - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access - self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access def test_udp_client_recv(self): - """ Test the udp client receive method""" + """Test the udp client receive method""" client = ModbusUdpClient() - self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access client.socket = mockSocket() - self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access - self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access + self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access def test_udp_client_repr(self): - """ Test udp client representation. """ + """Test udp client representation.""" client = ModbusUdpClient() rep = f"<{client.__class__.__name__} at {hex(id(client))} socket={client.socket}, "\ f"ipaddr={client.host}, port={client.port}, timeout={client.timeout}>" @@ -217,21 +217,20 @@ def test_udp_client_repr(self): # -----------------------------------------------------------------------# def test_sync_tcp_client_instantiation(self): - """ Test sync tcp client. """ + """Test sync tcp client.""" client = ModbusTcpClient() self.assertNotEqual(client, None) @patch('pymodbus.client.sync.select') def test_basic_sync_tcp_client(self, mock_select): - """ Test the basic methods for the tcp sync client""" - + """Test the basic methods for the tcp sync client""" # receive/send mock_select.select.return_value = [True] client = ModbusTcpClient() client.socket = mockSocket() - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access - self.assertEqual(1, client._send(b'\x00')) # pylint: disable=protected-access - self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(1, client._send(b'\x00')) # pylint: disable=protected-access + self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access # connect/disconnect self.assertTrue(client.connect()) @@ -244,7 +243,7 @@ def test_basic_sync_tcp_client(self, mock_select): self.assertEqual("ModbusTcpClient(127.0.0.1:502)", str(client)) def test_tcp_client_connect(self): - """ Test the tcp client connection method""" + """Test the tcp client connection method""" with patch.object(socket, 'create_connection') as mock_method: _socket = MagicMock() mock_method.return_value = _socket @@ -258,66 +257,66 @@ def test_tcp_client_connect(self): self.assertFalse(client.connect()) def test_tcp_client_is_socket_open(self): - """ Test the tcp client is_socket_open method""" + """Test the tcp client is_socket_open method""" client = ModbusTcpClient() self.assertFalse(client.is_socket_open()) def test_tcp_client_send(self): - """ Test the tcp client send method""" + """Test the tcp client send method""" client = ModbusTcpClient() - self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access client.socket = mockSocket() - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access - self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access @patch('pymodbus.client.sync.time') @patch('pymodbus.client.sync.select') def test_tcp_client_recv(self, mock_select, mock_time): - """ Test the tcp client receive method""" - + """Test the tcp client receive method""" mock_select.select.return_value = [True] mock_time.time.side_effect = count() client = ModbusTcpClient() - self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access client.socket = mockSocket() - self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access - self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access + self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access mock_socket = MagicMock() mock_socket.recv.side_effect = iter([b'\x00', b'\x01', b'\x02']) client.socket = mock_socket client.timeout = 3 - self.assertEqual(b'\x00\x01\x02', client._recv(3)) # pylint: disable=protected-access + self.assertEqual(b'\x00\x01\x02', client._recv(3)) # pylint: disable=protected-access mock_socket.recv.side_effect = iter([b'\x00', b'\x01', b'\x02']) - self.assertEqual(b'\x00\x01', client._recv(2)) # pylint: disable=protected-access + self.assertEqual(b'\x00\x01', client._recv(2)) # pylint: disable=protected-access mock_select.select.return_value = [False] - self.assertEqual(b'', client._recv(2)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(2)) # pylint: disable=protected-access client.socket = mockSocket() mock_select.select.return_value = [True] - self.assertIn(b'\x00', client._recv(None)) # pylint: disable=protected-access + self.assertIn(b'\x00', client._recv(None)) # pylint: disable=protected-access mock_socket = MagicMock() mock_socket.recv.return_value = b'' client.socket = mock_socket - self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access mock_socket.recv.side_effect = iter([b'\x00', b'\x01', b'\x02', b'']) client.socket = mock_socket - self.assertEqual(b'\x00\x01\x02', client._recv(1024)) # pylint: disable=protected-access + self.assertEqual(b'\x00\x01\x02', client._recv(1024)) # pylint: disable=protected-access def test_tcp_client_repr(self): - """ Test tcp client. """ + """Test tcp client.""" client = ModbusTcpClient() rep = f"<{client.__class__.__name__} at {hex(id(client))} socket={client.socket}, "\ f"ipaddr={client.host}, port={client.port}, timeout={client.timeout}>" self.assertEqual(repr(client), rep) def test_tcp_client_register(self): - """ Test tcp client. """ - class CustomRequest: # pylint: disable=too-few-public-methods - """ Dummy custom request. """ + """Test tcp client.""" + class CustomRequest: # pylint: disable=too-few-public-methods + """Dummy custom request.""" + function_code = 79 client = ModbusTcpClient() client.framer = Mock() @@ -329,7 +328,7 @@ class CustomRequest: # pylint: disable=too-few-public-methods # -----------------------------------------------------------------------# def test_tls_sslctx_provider(self): - """ test that sslctx_provider() produce SSLContext correctly """ + """Test that sslctx_provider() produce SSLContext correctly""" with patch.object(ssl.SSLContext, 'load_cert_chain') as mock_method: sslctx1 = sslctx_provider(certfile="cert.pem") self.assertIsNotNone(sslctx1) @@ -351,7 +350,7 @@ def test_tls_sslctx_provider(self): self.assertEqual(sslctx_new, sslctx_old) def test_sync_tls_client_instantiation(self): - """ Test sync tls client. """ + """Test sync tls client.""" # default SSLContext client = ModbusTlsClient() self.assertNotEqual(client, None) @@ -359,14 +358,13 @@ def test_sync_tls_client_instantiation(self): self.assertTrue(client.sslctx) def test_basic_sync_tls_client(self): - """ Test the basic methods for the tls sync client""" - + """Test the basic methods for the tls sync client""" # receive/send client = ModbusTlsClient() client.socket = mockSocket() - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access - self.assertEqual(1, client._send(b'\x00')) # pylint: disable=protected-access - self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(1, client._send(b'\x00')) # pylint: disable=protected-access + self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access # connect/disconnect self.assertTrue(client.connect()) @@ -379,7 +377,7 @@ def test_basic_sync_tls_client(self): self.assertEqual("ModbusTlsClient(localhost:802)", str(client)) def test_tls_client_connect(self): - """ Test the tls client connection method""" + """Test the tls client connection method""" with patch.object(ssl.SSLSocket, 'connect') as mock_method: client = ModbusTlsClient() self.assertTrue(client.connect()) @@ -390,39 +388,39 @@ def test_tls_client_connect(self): self.assertFalse(client.connect()) def test_tls_client_send(self): - """ Test the tls client send method""" + """Test the tls client send method""" client = ModbusTlsClient() - self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access client.socket = mockSocket() - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access - self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access @patch('pymodbus.client.sync.time') def test_tls_client_recv(self, mock_time): - """ Test the tls client receive method""" + """Test the tls client receive method""" client = ModbusTlsClient() - self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access mock_time.time.side_effect = count() client.socket = mockSocket() - self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access - self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access + self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access client.timeout = 2 - self.assertIn(b'\x00', client._recv(None)) # pylint: disable=protected-access + self.assertIn(b'\x00', client._recv(None)) # pylint: disable=protected-access mock_socket = MagicMock() mock_socket.recv.side_effect = iter([b'\x00', b'\x01', b'\x02']) client.socket = mock_socket client.timeout = 3 - self.assertEqual(b'\x00\x01\x02', client._recv(3)) # pylint: disable=protected-access + self.assertEqual(b'\x00\x01\x02', client._recv(3)) # pylint: disable=protected-access mock_socket.recv.side_effect = iter([b'\x00', b'\x01', b'\x02']) - self.assertEqual(b'\x00\x01', client._recv(2)) # pylint: disable=protected-access + self.assertEqual(b'\x00\x01', client._recv(2)) # pylint: disable=protected-access def test_tls_client_repr(self): - """ Test tls client. """ + """Test tls client.""" client = ModbusTlsClient() rep = f"<{client.__class__.__name__} at {hex(id(client))} socket={client.socket}, "\ f"ipaddr={client.host}, port={client.port}, sslctx={client.sslctx}, "\ @@ -430,9 +428,10 @@ def test_tls_client_repr(self): self.assertEqual(repr(client), rep) def test_tls_client_register(self): - """ Test tls client. """ - class CustomeRequest: # pylint: disable=too-few-public-methods - """ Dummy custom request. """ + """Test tls client.""" + class CustomeRequest: # pylint: disable=too-few-public-methods + """Dummy custom request.""" + function_code = 79 client = ModbusTlsClient() client.framer = Mock() @@ -444,7 +443,7 @@ class CustomeRequest: # pylint: disable=too-few-public-methods # -----------------------------------------------------------------------# def test_sync_serial_client_instantiation(self): - """ Test sync serial client. """ + """Test sync serial client.""" client = ModbusSerialClient() self.assertNotEqual(client, None) self.assertTrue(isinstance(ModbusSerialClient(method='ascii').framer, @@ -459,7 +458,7 @@ def test_sync_serial_client_instantiation(self): lambda: ModbusSerialClient(method='something')) def test_sync_serial_rtu_client_timeouts(self): - """ Test sync serial rtu. """ + """Test sync serial rtu.""" client = ModbusSerialClient(method="rtu", baudrate=9600) self.assertEqual(client.silent_interval, round((3.5 * 11 / 9600), 6)) client = ModbusSerialClient(method="rtu", baudrate=38400) @@ -467,20 +466,19 @@ def test_sync_serial_rtu_client_timeouts(self): @patch("serial.Serial") def test_basic_sync_serial_client(self, mock_serial): - """ Test the basic methods for the serial sync client""" - + """Test the basic methods for the serial sync client.""" # receive/send mock_serial.in_waiting = 0 - mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda + mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda mock_serial.read = lambda size: b'\x00' * size client = ModbusSerialClient() client.socket = mock_serial client.state = 0 - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access client.state = 0 - self.assertEqual(1, client._send(b'\x00')) # pylint: disable=protected-access - self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access + self.assertEqual(1, client._send(b'\x00')) # pylint: disable=protected-access + self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access # connect/disconnect self.assertTrue(client.connect()) @@ -499,7 +497,7 @@ def test_basic_sync_serial_client(self, mock_serial): self.assertEqual('ModbusSerialClient(ascii baud[19200])', str(client)) def test_serial_client_connect(self): - """ Test the serial client connection method""" + """Test the serial client connection method""" with patch.object(serial, 'Serial') as mock_method: mock_method.return_value = MagicMock() client = ModbusSerialClient() @@ -512,7 +510,7 @@ def test_serial_client_connect(self): @patch("serial.Serial") def test_serial_client_is_socket_open(self, mock_serial): - """ Test the serial client is_socket_open method""" + """Test the serial client is_socket_open method""" client = ModbusSerialClient() self.assertFalse(client.is_socket_open()) client.socket = mock_serial @@ -520,51 +518,51 @@ def test_serial_client_is_socket_open(self, mock_serial): @patch("serial.Serial") def test_serial_client_send(self, mock_serial): - """ Test the serial client send method""" + """Test the serial client send method""" mock_serial.in_waiting = None - mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda + mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda client = ModbusSerialClient() - self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access # client.connect() client.socket = mock_serial client.state = 0 - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access client.state = 0 - self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access + self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access @patch("serial.Serial") def test_serial_client_cleanup_buffer_before_send(self, mock_serial): - """ Test the serial client send method""" + """Test the serial client send method""" mock_serial.in_waiting = 4 mock_serial.read = lambda x: b'1' * x - mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda + mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda client = ModbusSerialClient() - self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._send(None)) # pylint: disable=protected-access # client.connect() client.socket = mock_serial client.state = 0 - self.assertEqual(0, client._send(None)) # pylint: disable=protected-access + self.assertEqual(0, client._send(None)) # pylint: disable=protected-access client.state = 0 - self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access + self.assertEqual(4, client._send('1234')) # pylint: disable=protected-access def test_serial_client_recv(self): - """ Test the serial client receive method""" + """Test the serial client receive method""" client = ModbusSerialClient() - self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access client.socket = mockSocket() - self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access - self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access + self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access client.socket = MagicMock() client.socket.read.return_value = b'' - self.assertEqual(b'', client._recv(None)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(None)) # pylint: disable=protected-access client.socket.timeout = 0 - self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access client.timeout = None - self.assertEqual(b'', client._recv(None)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(None)) # pylint: disable=protected-access def test_serial_client_repr(self): - """ Test serial client. """ + """Test serial client.""" client = ModbusSerialClient() rep = f"<{client.__class__.__name__} at {hex(id(client))} socket={client.socket}, "\ f"method={client.method}, timeout={client.timeout}>" diff --git a/test/test_client_sync_diag.py b/test/test_client_sync_diag.py index c24cc52e9..ba61aba1e 100755 --- a/test/test_client_sync_diag.py +++ b/test/test_client_sync_diag.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test client sync diag. """ +"""Test client sync diag.""" import unittest from itertools import count from unittest.mock import patch, MagicMock @@ -14,7 +14,8 @@ # Fixture # ---------------------------------------------------------------------------# class SynchronousDiagnosticClientTest(unittest.TestCase): - """ Unittest for the pymodbus.client.sync_diag module. + """Unittest for the pymodbus.client.sync_diag module. + It is a copy of parts of the test for the TCP class in the pymodbus.client.sync module, as it should operate identically and only log some additional lines. @@ -25,13 +26,12 @@ class SynchronousDiagnosticClientTest(unittest.TestCase): # -----------------------------------------------------------------------# def test_sync_tcp_diag_client_instantiation(self): - """ Test sync tcp diag client. """ + """Test sync tcp diag client.""" client = get_client() self.assertNotEqual(client, None) def test_basic_sync_tcp_diag_client(self): - """ Test the basic methods for the tcp sync diag client""" - + """Test the basic methods for the tcp sync diag client""" # connect/disconnect client = ModbusTcpDiagClient() client.socket = mockSocket() @@ -39,7 +39,7 @@ def test_basic_sync_tcp_diag_client(self): client.close() def test_tcp_diag_client_connect(self): - """ Test the tcp sync diag client connection method""" + """Test the tcp sync diag client connection method""" with patch.object(socket, 'create_connection') as mock_method: mock_method.return_value = object() client = ModbusTcpDiagClient() @@ -54,49 +54,48 @@ def test_tcp_diag_client_connect(self): @patch('pymodbus.client.sync_diag.time') @patch('pymodbus.client.sync.select') def test_tcp_diag_client_recv(self, mock_select, mock_diag_time, mock_time): - """ Test the tcp sync diag client receive method""" - + """Test the tcp sync diag client receive method""" mock_select.select.return_value = [True] mock_time.time.side_effect = count() mock_diag_time.time.side_effect = count() client = ModbusTcpDiagClient() - self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access client.socket = mockSocket() # Test logging of non-delayed responses - self.assertIn(b'\x00', client._recv(None)) # pylint: disable=protected-access - self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access + self.assertIn(b'\x00', client._recv(None)) # pylint: disable=protected-access + self.assertEqual(b'\x00', client._recv(1)) # pylint: disable=protected-access # Fool diagnostic logger into thinking we're running late, # test logging of delayed responses mock_diag_time.time.side_effect = count(step=3) - self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access - self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access + self.assertEqual(b'\x00' * 4, client._recv(4)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(0)) # pylint: disable=protected-access mock_socket = MagicMock() mock_socket.recv.side_effect = iter([b'\x00', b'\x01', b'\x02']) client.timeout = 3 client.socket = mock_socket - self.assertEqual(b'\x00\x01\x02', client._recv(3)) # pylint: disable=protected-access + self.assertEqual(b'\x00\x01\x02', client._recv(3)) # pylint: disable=protected-access mock_socket.recv.side_effect = iter([b'\x00', b'\x01', b'\x02']) - self.assertEqual(b'\x00\x01', client._recv(2)) # pylint: disable=protected-access + self.assertEqual(b'\x00\x01', client._recv(2)) # pylint: disable=protected-access mock_select.select.return_value = [False] - self.assertEqual(b'', client._recv(2)) # pylint: disable=protected-access + self.assertEqual(b'', client._recv(2)) # pylint: disable=protected-access client.socket = mockSocket() mock_select.select.return_value = [True] - self.assertIn(b'\x00', client._recv(None)) # pylint: disable=protected-access + self.assertIn(b'\x00', client._recv(None)) # pylint: disable=protected-access mock_socket = MagicMock() client.socket = mock_socket mock_socket.recv.return_value = b'' - self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access + self.assertRaises(ConnectionException, lambda: client._recv(1024)) # pylint: disable=protected-access mock_socket.recv.side_effect = iter([b'\x00', b'\x01', b'\x02', b'']) client.socket = mock_socket - self.assertEqual(b'\x00\x01\x02', client._recv(1024)) # pylint: disable=protected-access + self.assertEqual(b'\x00\x01\x02', client._recv(1024)) # pylint: disable=protected-access def test_tcp_diag_client_repr(self): - """ Test tcp diag client. """ + """Test tcp diag client.""" client = ModbusTcpDiagClient() rep = f"<{client.__class__.__name__} at {hex(id(client))} "\ f"socket={client.socket}, ipaddr={client.host}, "\ diff --git a/test/test_datastore.py b/test/test_datastore.py index 307655015..a0e8a63d6 100644 --- a/test/test_datastore.py +++ b/test/test_datastore.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test datastore. """ +"""Test datastore.""" import unittest import random from mock import MagicMock @@ -19,48 +19,48 @@ class ModbusDataStoreTest(unittest.TestCase): - """ Unittest for the pymodbus.datastore module. """ + """Unittest for the pymodbus.datastore module.""" def setUp(self): - pass + """Do setup.""" def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_modbus_data_block(self): - """ Test a base data block store """ + """Test a base data block store""" block = BaseModbusDataBlock() block.default(10, True) self.assertNotEqual(str(block), None) self.assertEqual(block.default_value, True) - self.assertEqual(block.values, [True]*10) + self.assertEqual(block.values, [True] * 10) block.default_value = False block.reset() - self.assertEqual(block.values, [False]*10) + self.assertEqual(block.values, [False] * 10) def test_modbus_data_block_iterate(self): - """ Test a base data block store """ + """Test a base data block store""" block = BaseModbusDataBlock() block.default(10, False) - for _,value in block: + for _, value in block: self.assertEqual(value, False) - block.values = {0 : False, 2 : False, 3 : False } - for _,value in block: + block.values = {0: False, 2: False, 3: False} + for _, value in block: self.assertEqual(value, False) def test_modbus_data_block_other(self): - """ Test a base data block store """ + """Test a base data block store""" block = BaseModbusDataBlock() - self.assertRaises(NotImplementedException, lambda: block.validate(1,1)) - self.assertRaises(NotImplementedException, lambda: block.getValues(1,1)) - self.assertRaises(NotImplementedException, lambda: block.setValues(1,1)) + self.assertRaises(NotImplementedException, lambda: block.validate(1, 1)) + self.assertRaises(NotImplementedException, lambda: block.getValues(1, 1)) + self.assertRaises(NotImplementedException, lambda: block.setValues(1, 1)) def test_modbus_sequential_data_block(self): - """ Test a sequential data block store """ - block = ModbusSequentialDataBlock(0x00, [False]*10) + """Test a sequential data block store""" + block = ModbusSequentialDataBlock(0x00, [False] * 10) self.assertFalse(block.validate(-1, 0)) self.assertFalse(block.validate(0, 20)) self.assertFalse(block.validate(10, 1)) @@ -69,19 +69,19 @@ def test_modbus_sequential_data_block(self): block.setValues(0x00, True) self.assertEqual(block.getValues(0x00, 1), [True]) - block.setValues(0x00, [True]*10) - self.assertEqual(block.getValues(0x00, 10), [True]*10) + block.setValues(0x00, [True] * 10) + self.assertEqual(block.getValues(0x00, 10), [True] * 10) def test_modbus_sequential_data_block_factory(self): - """ Test the sequential data block store factory """ + """Test the sequential data block store factory""" block = ModbusSequentialDataBlock.create() - self.assertEqual(block.getValues(0x00, 65536), [False]*65536) + self.assertEqual(block.getValues(0x00, 65536), [False] * 65536) block = ModbusSequentialDataBlock(0x00, 0x01) self.assertEqual(block.values, [0x01]) def test_modbus_sparse_data_block(self): - """ Test a sparse data block store """ - values = dict(enumerate([True]*10)) + """Test a sparse data block store""" + values = dict(enumerate([True] * 10)) block = ModbusSparseDataBlock(values) self.assertFalse(block.validate(-1, 0)) self.assertFalse(block.validate(0, 20)) @@ -94,22 +94,22 @@ def test_modbus_sparse_data_block(self): block.setValues(0x00, True) self.assertEqual(block.getValues(0x00, 1), [True]) - block.setValues(0x00, [True]*10) - self.assertEqual(block.getValues(0x00, 10), [True]*10) + block.setValues(0x00, [True] * 10) + self.assertEqual(block.getValues(0x00, 10), [True] * 10) - block.setValues(0x00, dict(enumerate([False]*10))) - self.assertEqual(block.getValues(0x00, 10), [False]*10) + block.setValues(0x00, dict(enumerate([False] * 10))) + self.assertEqual(block.getValues(0x00, 10), [False] * 10) block = ModbusSparseDataBlock({3: [10, 11, 12], 10: 1, 15: [0] * 4}) self.assertEqual(block.values, {3: 10, 4: 11, 5: 12, 10: 1, - 15:0 , 16:0, 17:0, 18:0 }) + 15: 0, 16: 0, 17: 0, 18: 0}) self.assertEqual(block.default_value, {3: 10, 4: 11, 5: 12, 10: 1, - 15:0 , 16:0, 17:0, 18:0 }) + 15: 0, 16: 0, 17: 0, 18: 0}) self.assertEqual(block.mutable, True) block.setValues(3, [20, 21, 22, 23], use_as_default=True) self.assertEqual(block.getValues(3, 4), [20, 21, 22, 23]) - self.assertEqual(block.default_value, {3: 20, 4: 21, 5: 22, 6:23, 10: 1, - 15:0 , 16:0, 17:0, 18:0 }) + self.assertEqual(block.default_value, {3: 20, 4: 21, 5: 22, 6: 23, 10: 1, + 15: 0, 16: 0, 17: 0, 18: 0}) # check when values is a dict, address is ignored block.setValues(0, {5: 32, 7: 43}) self.assertEqual(block.getValues(5, 3), [32, 23, 43]) @@ -129,48 +129,46 @@ def test_modbus_sparse_data_block(self): block = ModbusSparseDataBlock({3: [10, 11, 12], 10: 1, 15: [0] * 4}) block.setValues(0, {3: [20, 21, 22], 10: 11, 15: [10] * 4}) self.assertEqual(block.values, {3: 20, 4: 21, 5: 22, 10: 11, - 15: 10 ,16:10, 17:10, 18:10 }) + 15: 10, 16: 10, 17: 10, 18: 10}) block.reset() self.assertEqual(block.values, {3: 10, 4: 11, 5: 12, 10: 1, 15: 0, 16: 0, 17: 0, 18: 0}) - def test_modbus_sparse_data_block_factory(self): - """ Test the sparse data block store factory """ - block = ModbusSparseDataBlock.create([0x00]*65536) - self.assertEqual(block.getValues(0x00, 65536), [False]*65536) + """Test the sparse data block store factory""" + block = ModbusSparseDataBlock.create([0x00] * 65536) + self.assertEqual(block.getValues(0x00, 65536), [False] * 65536) def test_modbus_sparse_data_block_other(self): - """ Test modbus sparce data block. """ - block = ModbusSparseDataBlock([True]*10) - self.assertEqual(block.getValues(0x00, 10), [True]*10) + """Test modbus sparce data block.""" + block = ModbusSparseDataBlock([True] * 10) + self.assertEqual(block.getValues(0x00, 10), [True] * 10) self.assertRaises(ParameterException, - lambda: ModbusSparseDataBlock(True)) - + lambda: ModbusSparseDataBlock(True)) def test_modbus_slave_context(self): - """ Test a modbus slave context """ + """Test a modbus slave context""" store = { - 'di' : ModbusSequentialDataBlock(0, [False]*10), - 'co' : ModbusSequentialDataBlock(0, [False]*10), - 'ir' : ModbusSequentialDataBlock(0, [False]*10), - 'hr' : ModbusSequentialDataBlock(0, [False]*10), + 'di': ModbusSequentialDataBlock(0, [False] * 10), + 'co': ModbusSequentialDataBlock(0, [False] * 10), + 'ir': ModbusSequentialDataBlock(0, [False] * 10), + 'hr': ModbusSequentialDataBlock(0, [False] * 10), } context = ModbusSlaveContext(**store) self.assertNotEqual(str(context), None) - for i in (1,2,3,4): - context.setValues(i, 0, [True]*10) - self.assertTrue(context.validate(i, 0,10)) - self.assertEqual(context.getValues(i, 0,10), [True]*10) + for i in (1, 2, 3, 4): + context.setValues(i, 0, [True] * 10) + self.assertTrue(context.validate(i, 0, 10)) + self.assertEqual(context.getValues(i, 0, 10), [True] * 10) context.reset() - for i in (1,2,3,4): - self.assertTrue(context.validate(i, 0,10)) - self.assertEqual(context.getValues(i, 0,10), [False]*10) + for i in (1, 2, 3, 4): + self.assertTrue(context.validate(i, 0, 10)) + self.assertEqual(context.getValues(i, 0, 10), [False] * 10) def test_modbus_server_context(self): - """ Test a modbus server context """ + """Test a modbus server context""" def _set(ctx): ctx[0xffff] = None context = ModbusServerContext(single=False) @@ -179,29 +177,30 @@ def _set(ctx): class RedisDataStoreTest(unittest.TestCase): - """ Unittest for the pymodbus.datastore.database.redis module. """ + """Unittest for the pymodbus.datastore.database.redis module.""" def setUp(self): + """Do setup.""" self.slave = RedisSlaveContext() def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_str(self): - """ Test string. """ + """Test string.""" # slave = RedisSlaveContext() self.assertEqual(str(self.slave), f"Redis Slave Context {self.slave.client}") def test_reset(self): - """ Test reset. """ + """Test reset.""" self.assertTrue(isinstance(self.slave.client, redis.Redis)) self.slave.client = MagicMock() self.slave.reset() self.slave.client.flushall.assert_called_once_with() def test_val_callbacks_success(self): - """ Test value callbacks success. """ - self.slave._build_mapping() # pylint: disable=protected-access + """Test value callbacks success.""" + self.slave._build_mapping() # pylint: disable=protected-access mock_count = 3 mock_offset = 0 self.slave.client.mset = MagicMock() @@ -209,12 +208,12 @@ def test_val_callbacks_success(self): for key in ('d', 'c', 'h', 'i'): self.assertTrue( - self.slave._val_callbacks[key](mock_offset, mock_count) # pylint: disable=protected-access + self.slave._val_callbacks[key](mock_offset, mock_count) # pylint: disable=protected-access ) def test_val_callbacks_failure(self): - """ Test value callbacks failure. """ - self.slave._build_mapping() # pylint: disable=protected-access + """Test value callbacks failure.""" + self.slave._build_mapping() # pylint: disable=protected-access mock_count = 3 mock_offset = 0 self.slave.client.mset = MagicMock() @@ -222,82 +221,85 @@ def test_val_callbacks_failure(self): for key in ('d', 'c', 'h', 'i'): self.assertFalse( - self.slave._val_callbacks[key](mock_offset, mock_count) # pylint: disable=protected-access + self.slave._val_callbacks[key](mock_offset, mock_count) # pylint: disable=protected-access ) def test_get_callbacks(self): - """ Test get callbacks. """ - self.slave._build_mapping() # pylint: disable=protected-access + """Test get callbacks.""" + self.slave._build_mapping() # pylint: disable=protected-access mock_count = 3 mock_offset = 0 self.slave.client.mget = MagicMock(return_value='11') for key in ('d', 'c'): - resp = self.slave._get_callbacks[key](mock_offset, mock_count) # pylint: disable=protected-access + resp = self.slave._get_callbacks[key](mock_offset, mock_count) # pylint: disable=protected-access self.assertEqual(resp, [True, False, False]) for key in ('h', 'i'): - resp = self.slave._get_callbacks[key](mock_offset, mock_count) # pylint: disable=protected-access + resp = self.slave._get_callbacks[key](mock_offset, mock_count) # pylint: disable=protected-access self.assertEqual(resp, ['1', '1']) def test_set_callbacks(self): - """ Test set callbacks. """ - self.slave._build_mapping() # pylint: disable=protected-access + """Test set callbacks.""" + self.slave._build_mapping() # pylint: disable=protected-access mock_values = [3] mock_offset = 0 self.slave.client.mset = MagicMock() self.slave.client.mget = MagicMock() for key in ('c', 'd'): - self.slave._set_callbacks[key](mock_offset, [3]) # pylint: disable=protected-access + self.slave._set_callbacks[key](mock_offset, [3]) # pylint: disable=protected-access k = f"pymodbus:{key}:{mock_offset}" self.slave.client.mset.assert_called_with( {k: '\x01'} ) for key in ('h', 'i'): - self.slave._set_callbacks[key](mock_offset, [3]) # pylint: disable=protected-access + self.slave._set_callbacks[key](mock_offset, [3]) # pylint: disable=protected-access k = f"pymodbus:{key}:{mock_offset}" self.slave.client.mset.assert_called_with( {k: mock_values[0]} ) def test_validate(self): - """ Test validate. """ + """Test validate.""" self.slave.client.mget = MagicMock(return_value=[123]) self.assertTrue(self.slave.validate(0x01, 3000)) def test_set_value(self): - """ Test set value. """ + """Test set value.""" self.slave.client.mset = MagicMock() self.slave.client.mget = MagicMock() self.assertEqual(self.slave.setValues(0x01, 1000, [12]), None) def test_get_value(self): - """ Test get value. """ + """Test get value.""" self.slave.client.mget = MagicMock(return_value=["123"]) self.assertEqual(self.slave.getValues(0x01, 23), []) -class MockSqlResult: # pylint: disable=too-few-public-methods - """ Mock SQL Result. """ +class MockSqlResult: # pylint: disable=too-few-public-methods + """Mock SQL Result.""" + def __init__(self, rowcount=0, value=0): + """Initialize.""" self.rowcount = rowcount self.value = value class SqlDataStoreTest(unittest.TestCase): - """ Unittest for the pymodbus.datastore.database.SqlSlaveContext module. """ + """Unittest for the pymodbus.datastore.database.SqlSlaveContext module.""" def setUp(self): + """Do setup.""" self.slave = SqlSlaveContext() - self.slave._metadata.drop_all = MagicMock() # pylint: disable=protected-access - self.slave._db_create = MagicMock() # pylint: disable=protected-access - self.slave._table.select = MagicMock() # pylint: disable=protected-access - self.slave._connection = MagicMock() # pylint: disable=protected-access + self.slave._metadata.drop_all = MagicMock() # pylint: disable=protected-access + self.slave._db_create = MagicMock() # pylint: disable=protected-access + self.slave._table.select = MagicMock() # pylint: disable=protected-access + self.slave._connection = MagicMock() # pylint: disable=protected-access - self.mock_addr = random.randint(0, 65000) #NOSONAR # nosec - self.mock_values = random.sample(range(1, 100), 5) #NOSONAR # nosec + self.mock_addr = random.randint(0, 65000) # NOSONAR # nosec + self.mock_values = random.sample(range(1, 100), 5) # NOSONAR # nosec self.mock_function = 0x01 self.mock_type = 'h' self.mock_offset = 0 @@ -308,38 +310,40 @@ def setUp(self): self.function_map.update([(i, 'c') for i in (1, 5, 15)]) def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_str(self): - """ Test string. """ + """Test string.""" self.assertEqual(str(self.slave), "Modbus Slave Context") def test_reset(self): - """ Test reset. """ + """Test reset.""" self.slave.reset() - self.slave._metadata.drop_all.assert_called_once_with() # pylint: disable=protected-access - self.slave._db_create.assert_called_once_with( # pylint: disable=protected-access + self.slave._metadata.drop_all.assert_called_once_with() # pylint: disable=protected-access + self.slave._db_create.assert_called_once_with( # pylint: disable=protected-access self.slave.table, self.slave.database ) def test_validate_success(self): - """ Test validate success. """ - self.slave._connection.execute.return_value.fetchall.return_value = self.mock_values # pylint: disable=protected-access + """Test validate success.""" + self.slave._connection.execute.return_value.fetchall.return_value = \ + self.mock_values # pylint: disable=protected-access self.assertTrue(self.slave.validate( self.mock_function, self.mock_addr, len(self.mock_values)) ) def test_validate_failure(self): - """ Test validate failure. """ + """Test validate failure.""" wrong_count = 9 - self.slave._connection.execute.return_value.fetchall.return_value = self.mock_values # pylint: disable=protected-access + self.slave._connection.execute.return_value.fetchall.return_value = \ + self.mock_values # pylint: disable=protected-access self.assertFalse(self.slave.validate( self.mock_function, self.mock_addr, wrong_count) ) def test_build_set(self): - """ Test build set. """ + """Test build set.""" mock_set = [ { 'index': 0, @@ -352,72 +356,72 @@ def test_build_set(self): 'value': 12 } ] - self.assertListEqual(self.slave._build_set('h', 0, [11, 12]), mock_set) # pylint: disable=protected-access + self.assertListEqual(self.slave._build_set('h', 0, [11, 12]), mock_set) # pylint: disable=protected-access def test_check_success(self): - """ Test check success. """ + """Test check success.""" mock_success_results = [1, 2, 3] - self.slave._get = MagicMock(return_value=mock_success_results) # pylint: disable=protected-access - self.assertFalse(self.slave._check('h', 0, 1)) # pylint: disable=protected-access + self.slave._get = MagicMock(return_value=mock_success_results) # pylint: disable=protected-access + self.assertFalse(self.slave._check('h', 0, 1)) # pylint: disable=protected-access def test_check_failure(self): - """ Test check failure. """ + """Test check failure.""" mock_success_results = [] - self.slave._get = MagicMock(return_value=mock_success_results) # pylint: disable=protected-access - self.assertTrue(self.slave._check('h', 0, 1)) # pylint: disable=protected-access + self.slave._get = MagicMock(return_value=mock_success_results) # pylint: disable=protected-access + self.assertTrue(self.slave._check('h', 0, 1)) # pylint: disable=protected-access def test_get_values(self): - """ Test get values. """ - self.slave._get = MagicMock() # pylint: disable=protected-access + """Test get values.""" + self.slave._get = MagicMock() # pylint: disable=protected-access for key, value in self.function_map.items(): self.slave.getValues(key, self.mock_addr, self.mock_count) - self.slave._get.assert_called_with( # pylint: disable=protected-access + self.slave._get.assert_called_with( # pylint: disable=protected-access value, self.mock_addr + 1, self.mock_count ) def test_set_values(self): - """ Test set values. """ - self.slave._set = MagicMock() # pylint: disable=protected-access + """Test set values.""" + self.slave._set = MagicMock() # pylint: disable=protected-access for key, value in self.function_map.items(): self.slave.setValues(key, self.mock_addr, self.mock_values, update=False) - self.slave._set.assert_called_with( # pylint: disable=protected-access + self.slave._set.assert_called_with( # pylint: disable=protected-access value, self.mock_addr + 1, self.mock_values ) def test_set(self): - """ Test set. """ - self.slave._check = MagicMock(return_value=True) # pylint: disable=protected-access - self.slave._connection.execute = MagicMock( # pylint: disable=protected-access + """Test set.""" + self.slave._check = MagicMock(return_value=True) # pylint: disable=protected-access + self.slave._connection.execute = MagicMock( # pylint: disable=protected-access return_value=MockSqlResult(rowcount=len(self.mock_values)) ) - self.assertTrue(self.slave._set( # pylint: disable=protected-access + self.assertTrue(self.slave._set( # pylint: disable=protected-access self.mock_type, self.mock_offset, self.mock_values) ) - self.slave._check = MagicMock(return_value=False) # pylint: disable=protected-access + self.slave._check = MagicMock(return_value=False) # pylint: disable=protected-access self.assertFalse( - self.slave._set(self.mock_type, self.mock_offset, self.mock_values) # pylint: disable=protected-access + self.slave._set(self.mock_type, self.mock_offset, self.mock_values) # pylint: disable=protected-access ) def test_update_success(self): - """ Test update success. """ - self.slave._connection.execute = MagicMock( # pylint: disable=protected-access + """Test update success.""" + self.slave._connection.execute = MagicMock( # pylint: disable=protected-access return_value=MockSqlResult(rowcount=len(self.mock_values)) ) self.assertTrue( - self.slave._update(self.mock_type, self.mock_offset, self.mock_values) # pylint: disable=protected-access + self.slave._update(self.mock_type, self.mock_offset, self.mock_values) # pylint: disable=protected-access ) def test_update_failure(self): - """ Test update failure. """ - self.slave._connection.execute = MagicMock( # pylint: disable=protected-access + """Test update failure.""" + self.slave._connection.execute = MagicMock( # pylint: disable=protected-access return_value=MockSqlResult(rowcount=100) ) self.assertFalse( - self.slave._update(self.mock_type, self.mock_offset, self.mock_values) # pylint: disable=protected-access + self.slave._update(self.mock_type, self.mock_offset, self.mock_values) # pylint: disable=protected-access ) diff --git a/test/test_device.py b/test/test_device.py index 1b43c8188..86055ac0e 100644 --- a/test/test_device.py +++ b/test/test_device.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test device. """ +"""Test device.""" import unittest from pymodbus.device import ( ModbusPlusStatistics, @@ -11,22 +11,25 @@ from pymodbus.events import ModbusEvent, RemoteReceiveEvent from pymodbus.constants import DeviceInformation -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# -class SimpleDataStoreTest(unittest.TestCase): # pylint: disable=too-many-public-methods - """ Unittest for the pymodbus.device module. """ +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# - #-----------------------------------------------------------------------# - # Setup/TearDown - #-----------------------------------------------------------------------# + +class SimpleDataStoreTest(unittest.TestCase): # pylint: disable=too-many-public-methods + """Unittest for the pymodbus.device module.""" + + # -----------------------------------------------------------------------# + # Setup/TearDown + # -----------------------------------------------------------------------# def setUp(self): + """Do setup.""" self.info = { 0x00: 'Bashwork', # VendorName 0x01: 'PTM', # ProductCode 0x02: '1.0', # MajorMinorRevision - 0x03: 'http://internets.com', #NOSONAR VendorUrl + 0x03: 'http://internets.com', # NOSONAR VendorUrl 0x04: 'pymodbus', # ProductName 0x05: 'bashwork', # ModelName 0x06: 'unittest', # UserApplicationName @@ -37,30 +40,30 @@ def setUp(self): 0x82: 'custom2', # device specific 0xFF: 'customlast', # device specific last } - self.ident = ModbusDeviceIdentification(self.info) + self.ident = ModbusDeviceIdentification(self.info) self.control = ModbusControlBlock() - self.access = ModbusAccessControl() + self.access = ModbusAccessControl() self.control.reset() def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.ident del self.control del self.access def test_update_identity(self): - """ Test device identification reading """ + """Test device identification reading""" self.control.Identity.update(self.ident) self.assertEqual(self.control.Identity.VendorName, 'Bashwork') self.assertEqual(self.control.Identity.ProductCode, 'PTM') self.assertEqual(self.control.Identity.MajorMinorRevision, '1.0') - self.assertEqual(self.control.Identity.VendorUrl, 'http://internets.com') #NOSONAR + self.assertEqual(self.control.Identity.VendorUrl, 'http://internets.com') # NOSONAR self.assertEqual(self.control.Identity.ProductName, 'pymodbus') self.assertEqual(self.control.Identity.ModelName, 'bashwork') self.assertEqual(self.control.Identity.UserApplicationName, 'unittest') def test_device_identification_factory(self): - """ Test device identification reading """ + """Test device identification reading""" self.control.Identity.update(self.ident) result = DeviceInformationFactory.get(self.control, DeviceInformation.Specific, 0x00) self.assertEqual(result[0x00], 'Bashwork') @@ -74,13 +77,13 @@ def test_device_identification_factory(self): self.assertEqual(result[0x00], 'Bashwork') self.assertEqual(result[0x01], 'PTM') self.assertEqual(result[0x02], '1.0') - self.assertEqual(result[0x03], 'http://internets.com') #NOSONAR + self.assertEqual(result[0x03], 'http://internets.com') # NOSONAR self.assertEqual(result[0x04], 'pymodbus') self.assertEqual(result[0x05], 'bashwork') self.assertEqual(result[0x06], 'unittest') def test_device_identification_factory_lookup(self): - """ Test device identification factory lookup. """ + """Test device identification factory lookup.""" result = DeviceInformationFactory.get(self.control, DeviceInformation.Basic, 0x00) self.assertEqual(sorted(result.keys()), [0x00, 0x01, 0x02]) result = DeviceInformationFactory.get(self.control, DeviceInformation.Basic, 0x02) @@ -93,7 +96,7 @@ def test_device_identification_factory_lookup(self): self.assertEqual(sorted(result.keys()), [0x05, 0x06]) result = DeviceInformationFactory.get(self.control, DeviceInformation.Extended, 0x00) self.assertEqual(sorted(result.keys()), - [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x80, 0x82, 0xFF]) + [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x80, 0x82, 0xFF]) result = DeviceInformationFactory.get(self.control, DeviceInformation.Extended, 0x02) self.assertEqual(sorted(result.keys()), [0x02, 0x03, 0x04, 0x05, 0x06, 0x80, 0x82, 0xFF]) result = DeviceInformationFactory.get(self.control, DeviceInformation.Extended, 0x06) @@ -104,19 +107,19 @@ def test_device_identification_factory_lookup(self): self.assertEqual(sorted(result.keys()), [0x82, 0xFF]) result = DeviceInformationFactory.get(self.control, DeviceInformation.Extended, 0x81) self.assertEqual(sorted(result.keys()), - [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x80, 0x82, 0xFF]) + [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x80, 0x82, 0xFF]) def test_basic_commands(self): - """ Test device identification reading """ - self.assertEqual(str(self.ident), "DeviceIdentity") + """Test device identification reading""" + self.assertEqual(str(self.ident), "DeviceIdentity") self.assertEqual(str(self.control), "ModbusControl") def test_modbus_device_identification_get(self): - """ Test device identification reading """ + """Test device identification reading""" self.assertEqual(self.ident[0x00], 'Bashwork') self.assertEqual(self.ident[0x01], 'PTM') self.assertEqual(self.ident[0x02], '1.0') - self.assertEqual(self.ident[0x03], 'http://internets.com') #NOSONAR + self.assertEqual(self.ident[0x03], 'http://internets.com') # NOSONAR self.assertEqual(self.ident[0x04], 'pymodbus') self.assertEqual(self.ident[0x05], 'bashwork') self.assertEqual(self.ident[0x06], 'unittest') @@ -126,13 +129,13 @@ def test_modbus_device_identification_get(self): self.assertEqual(self.ident[0x54], '') def test_modbus_device_identification_summary(self): - """ Test device identification summary creation """ - summary = sorted(self.ident.summary().values()) - expected = sorted(list(self.info.values())[:0x07]) # remove private + """Test device identification summary creation""" + summary = sorted(self.ident.summary().values()) + expected = sorted(list(self.info.values())[:0x07]) # remove private self.assertEqual(summary, expected) def test_modbus_device_identification_set(self): - """ Test a device identification writing """ + """Test a device identification writing""" self.ident[0x07] = 'y' self.ident[0x08] = 'y' self.ident[0x10] = 'public' @@ -144,7 +147,7 @@ def test_modbus_device_identification_set(self): self.assertEqual('testing', self.ident[0x54]) def test_modbus_control_block_ascii_modes(self): - """ Test a server control block ascii mode """ + """Test a server control block ascii mode""" self.assertEqual(id(self.control), id(ModbusControlBlock())) self.control.Mode = 'RTU' self.assertEqual('RTU', self.control.Mode) @@ -152,21 +155,21 @@ def test_modbus_control_block_ascii_modes(self): self.assertNotEqual('FAKE', self.control.Mode) def test_modbus_control_block_counters(self): - """ Tests the MCB counters methods """ + """Tests the MCB counters methods""" self.assertEqual(0x0, self.control.Counter.BusMessage) for _ in range(10): self.control.Counter.BusMessage += 1 self.control.Counter.SlaveMessage += 1 self.assertEqual(10, self.control.Counter.BusMessage) self.control.Counter.BusMessage = 0x00 - self.assertEqual(0, self.control.Counter.BusMessage) + self.assertEqual(0, self.control.Counter.BusMessage) self.assertEqual(10, self.control.Counter.SlaveMessage) self.control.Counter.reset() self.assertEqual(0, self.control.Counter.SlaveMessage) def test_modbus_control_block_update(self): - """ Tests the MCB counters update methods """ - values = {'SlaveMessage':5, 'BusMessage':5} + """Tests the MCB counters update methods""" + values = {'SlaveMessage': 5, 'BusMessage': 5} self.control.Counter.BusMessage += 1 self.control.Counter.SlaveMessage += 1 self.control.Counter.update(values) @@ -174,19 +177,19 @@ def test_modbus_control_block_update(self): self.assertEqual(6, self.control.Counter.BusMessage) def test_modbus_control_block_iterator(self): - """ Tests the MCB counters iterator """ + """Tests the MCB counters iterator""" self.control.Counter.reset() - for _,count in self.control: + for _, count in self.control: self.assertEqual(0, count) def test_modbus_counters_handler_iterator(self): - """ Tests the MCB counters iterator """ + """Tests the MCB counters iterator""" self.control.Counter.reset() - for _,count in self.control.Counter: + for _, count in self.control.Counter: self.assertEqual(0, count) def test_modbus_control_block_counter_summary(self): - """ Tests retrieving the current counter summary """ + """Tests retrieving the current counter summary""" self.assertEqual(0x00, self.control.Counter.summary()) for _ in range(10): self.control.Counter.BusMessage += 1 @@ -198,15 +201,14 @@ def test_modbus_control_block_counter_summary(self): self.assertEqual(0x00, self.control.Counter.summary()) def test_modbus_control_block_listen(self): - """ Tests the MCB listen flag methods """ - + """Test the MCB listen flag methods""" self.control.ListenOnly = False self.assertEqual(self.control.ListenOnly, False) self.control.ListenOnly = not self.control.ListenOnly self.assertEqual(self.control.ListenOnly, True) def test_modbus_control_block_delimiter(self): - """ Tests the MCB delimiter setting methods """ + """Tests the MCB delimiter setting methods""" self.control.Delimiter = b'\r' self.assertEqual(self.control.Delimiter, b'\r') self.control.Delimiter = '=' @@ -215,26 +217,26 @@ def test_modbus_control_block_delimiter(self): self.assertEqual(self.control.Delimiter, b'=') def test_modbus_control_block_diagnostic(self): - """ Tests the MCB delimiter setting methods """ + """Tests the MCB delimiter setting methods""" self.assertEqual([False] * 16, self.control.getDiagnosticRegister()) - for i in (1,3,4,6): - self.control.setDiagnostic({i:True}) + for i in (1, 3, 4, 6): + self.control.setDiagnostic({i: True}) self.assertEqual(True, self.control.getDiagnostic(1)) self.assertEqual(False, self.control.getDiagnostic(2)) actual = [False, True, False, True, True, False, True] + [False] * 9 self.assertEqual(actual, self.control.getDiagnosticRegister()) for i in range(16): - self.control.setDiagnostic({i:False}) + self.control.setDiagnostic({i: False}) def test_modbus_control_block_invalid_diagnostic(self): - """ Tests querying invalid MCB counters methods """ + """Tests querying invalid MCB counters methods""" self.assertEqual(None, self.control.getDiagnostic(-1)) self.assertEqual(None, self.control.getDiagnostic(17)) self.assertEqual(None, self.control.getDiagnostic(None)) - self.assertEqual(None, self.control.getDiagnostic([1,2,3])) + self.assertEqual(None, self.control.getDiagnostic([1, 2, 3])) def test_add_remove__single_clients(self): - """ Test adding and removing a host """ + """Test adding and removing a host""" self.assertFalse(self.access.check("192.168.1.1")) # NOSONAR self.access.add("192.168.1.1") # NOSONAR self.assertTrue(self.access.check("192.168.1.1")) # NOSONAR @@ -243,7 +245,7 @@ def test_add_remove__single_clients(self): self.assertFalse(self.access.check("192.168.1.1")) # NOSONAR def test_add_remove_multiple_clients(self): - """ Test adding and removing a host """ + """Test adding and removing a host""" clients = ["192.168.1.1", "192.168.1.2", "192.168.1.3"] # NOSONAR self.access.add(clients) for host in clients: @@ -251,7 +253,7 @@ def test_add_remove_multiple_clients(self): self.access.remove(clients) def test_network_access_list_iterator(self): - """ Test adding and removing a host """ + """Test adding and removing a host""" clients = ["127.0.0.1", "192.168.1.1", "192.168.1.2", "192.168.1.3"] # NOSONAR self.access.add(clients) for host in self.access: @@ -260,7 +262,7 @@ def test_network_access_list_iterator(self): self.assertTrue(host in self.access) def test_clearing_control_events(self): - """ Test adding and clearing modbus events """ + """Test adding and clearing modbus events""" self.assertEqual(self.control.Events, []) event = ModbusEvent() self.control.addEvent(event) @@ -271,7 +273,7 @@ def test_clearing_control_events(self): self.assertEqual(self.control.Counter.Event, 1) def test_retrieving_control_events(self): - """ Test adding and removing a host """ + """Test adding and removing a host""" self.assertEqual(self.control.Events, []) event = RemoteReceiveEvent() self.control.addEvent(event) @@ -280,7 +282,7 @@ def test_retrieving_control_events(self): self.assertEqual(packet, b'\x40') def test_modbus_plus_statistics(self): - """ Test device identification reading """ + """Test device identification reading""" default = [0x0000] * 55 statistics = ModbusPlusStatistics() self.assertEqual(default, statistics.encode()) @@ -288,24 +290,23 @@ def test_modbus_plus_statistics(self): self.assertEqual(default, statistics.encode()) self.assertEqual(default, self.control.Plus.encode()) - - def test_modbus_plus_statistics_helpers(self): - """ Test modbus plus statistics helper methods """ + """Test modbus plus statistics helper methods""" statistics = ModbusPlusStatistics() summary = [ - [0],[0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0],[0], - [0,0,0,0,0,0,0,0],[0],[0],[0],[0],[0,0],[0],[0],[0],[0], - [0],[0],[0],[0,0],[0],[0],[0],[0],[0,0,0,0,0,0,0,0],[0], - [0,0,0,0,0,0,0,0],[0,0],[0],[0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0],[0],[0],[0,0],[0],[0],[0],[0],[0,0], - [0],[0],[0],[0],[0],[0,0],[0],[0,0,0,0,0,0,0,0]] - stats_summary = [x for x in statistics.summary()] # pylint: disable=unnecessary-comprehension + [0], [0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0], [0], + [0, 0, 0, 0, 0, 0, 0, 0], [0], [0], [0], [0], [0, 0], [0], [0], [0], [0], + [0], [0], [0], [0, 0], [0], [0], [0], [0], [0, 0, 0, 0, 0, 0, 0, 0], [0], + [0, 0, 0, 0, 0, 0, 0, 0], [0, 0], [0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], [0], [0], [0, 0], [0], [0], [0], [0], [0, 0], + [0], [0], [0], [0], [0], [0, 0], [0], [0, 0, 0, 0, 0, 0, 0, 0]] + stats_summary = [x for x in statistics.summary()] # pylint: disable=unnecessary-comprehension self.assertEqual(sorted(summary), sorted(stats_summary)) self.assertEqual(0x00, sum(sum(value[1]) for value in statistics)) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_diag_messages.py b/test/test_diag_messages.py index 11b18d68e..1924bed65 100644 --- a/test/test_diag_messages.py +++ b/test/test_diag_messages.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test diag messages. """ +"""Test diag messages.""" import unittest from pymodbus.exceptions import NotImplementedException @@ -45,10 +45,12 @@ from pymodbus.diag_message import DiagnosticStatusSimpleRequest from pymodbus.diag_message import DiagnosticStatusSimpleResponse + class SimpleDataStoreTest(unittest.TestCase): - """ Unittest for the pymodbus.diag_message module. """ + """Unittest for the pymodbus.diag_message module.""" def setUp(self): + """Do setup.""" self.requests = [ (RestartCommunicationsOptionRequest, b'\x00\x01\x00\x00', b'\x00\x01\xff\x00'), @@ -87,82 +89,82 @@ def setUp(self): ] self.responses = [ - #(DiagnosticStatusResponse, b'\x00\x00\x00\x00'), - #(DiagnosticStatusSimpleResponse, b'\x00\x00\x00\x00'), - (ReturnQueryDataResponse, b'\x00\x00\x00\x00'), - (RestartCommunicationsOptionResponse, b'\x00\x01\x00\x00'), - (ReturnDiagnosticRegisterResponse, b'\x00\x02\x00\x00'), - (ChangeAsciiInputDelimiterResponse, b'\x00\x03\x00\x00'), - (ForceListenOnlyModeResponse, b'\x00\x04'), - (ReturnQueryDataResponse, b'\x00\x00\x00\x00'), - (ClearCountersResponse, b'\x00\x0a\x00\x00'), - (ReturnBusMessageCountResponse, b'\x00\x0b\x00\x00'), - (ReturnBusCommunicationErrorCountResponse, b'\x00\x0c\x00\x00'), - (ReturnBusExceptionErrorCountResponse, b'\x00\x0d\x00\x00'), - (ReturnSlaveMessageCountResponse, b'\x00\x0e\x00\x00'), - (ReturnSlaveNoReponseCountResponse, b'\x00\x0f\x00\x00'), - (ReturnSlaveNAKCountResponse, b'\x00\x10\x00\x00'), - (ReturnSlaveBusyCountResponse, b'\x00\x11\x00\x00'), - (ReturnSlaveBusCharacterOverrunCountResponse, b'\x00\x12\x00\x00'), - (ReturnIopOverrunCountResponse, b'\x00\x13\x00\x00'), - (ClearOverrunCountResponse, b'\x00\x14\x00\x00'), - (GetClearModbusPlusResponse, b'\x00\x15\x00\x04' + b'\x00\x00' * 55), + # (DiagnosticStatusResponse, b'\x00\x00\x00\x00'), + # (DiagnosticStatusSimpleResponse, b'\x00\x00\x00\x00'), + (ReturnQueryDataResponse, b'\x00\x00\x00\x00'), + (RestartCommunicationsOptionResponse, b'\x00\x01\x00\x00'), + (ReturnDiagnosticRegisterResponse, b'\x00\x02\x00\x00'), + (ChangeAsciiInputDelimiterResponse, b'\x00\x03\x00\x00'), + (ForceListenOnlyModeResponse, b'\x00\x04'), + (ReturnQueryDataResponse, b'\x00\x00\x00\x00'), + (ClearCountersResponse, b'\x00\x0a\x00\x00'), + (ReturnBusMessageCountResponse, b'\x00\x0b\x00\x00'), + (ReturnBusCommunicationErrorCountResponse, b'\x00\x0c\x00\x00'), + (ReturnBusExceptionErrorCountResponse, b'\x00\x0d\x00\x00'), + (ReturnSlaveMessageCountResponse, b'\x00\x0e\x00\x00'), + (ReturnSlaveNoReponseCountResponse, b'\x00\x0f\x00\x00'), + (ReturnSlaveNAKCountResponse, b'\x00\x10\x00\x00'), + (ReturnSlaveBusyCountResponse, b'\x00\x11\x00\x00'), + (ReturnSlaveBusCharacterOverrunCountResponse, b'\x00\x12\x00\x00'), + (ReturnIopOverrunCountResponse, b'\x00\x13\x00\x00'), + (ClearOverrunCountResponse, b'\x00\x14\x00\x00'), + (GetClearModbusPlusResponse, b'\x00\x15\x00\x04' + b'\x00\x00' * 55), ] def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.requests del self.responses def test_diagnostic_requests_decode(self): - """ Testing diagnostic request messages encoding """ - for msg,enc,_ in self.requests: + """Testing diagnostic request messages encoding""" + for msg, enc, _ in self.requests: handle = DiagnosticStatusRequest() handle.decode(enc) self.assertEqual(handle.sub_function_code, msg.sub_function_code) def test_diagnostic_simple_requests(self): - """ Testing diagnostic request messages encoding """ + """Testing diagnostic request messages encoding""" request = DiagnosticStatusSimpleRequest(b'\x12\x34') request.sub_function_code = 0x1234 - self.assertRaises(NotImplementedException, lambda: request.execute()) # pylint: disable=unnecessary-lambda + self.assertRaises(NotImplementedException, lambda: request.execute()) # pylint: disable=unnecessary-lambda self.assertEqual(request.encode(), b'\x12\x34\x12\x34') DiagnosticStatusSimpleResponse(None) def test_diagnostic_response_decode(self): - """ Testing diagnostic request messages encoding """ - for msg,enc,_ in self.requests: + """Testing diagnostic request messages encoding""" + for msg, enc, _ in self.requests: handle = DiagnosticStatusResponse() handle.decode(enc) self.assertEqual(handle.sub_function_code, msg.sub_function_code) def test_diagnostic_requests_encode(self): - """ Testing diagnostic request messages encoding """ - for msg,enc,_ in self.requests: + """Testing diagnostic request messages encoding""" + for msg, enc, _ in self.requests: self.assertEqual(msg().encode(), enc) def test_diagnostic_execute(self): - """ Testing diagnostic message execution """ + """Testing diagnostic message execution""" for message, encoded, executed in self.requests: encoded = message().execute().encode() self.assertEqual(encoded, executed) def test_return_query_data_request(self): - """ Testing diagnostic message execution """ - message = ReturnQueryDataRequest([0x0000]*2) + """Testing diagnostic message execution""" + message = ReturnQueryDataRequest([0x0000] * 2) self.assertEqual(message.encode(), b'\x00\x00\x00\x00\x00\x00') message = ReturnQueryDataRequest(0x0000) self.assertEqual(message.encode(), b'\x00\x00\x00\x00') def test_return_query_data_response(self): - """ Testing diagnostic message execution """ - message = ReturnQueryDataResponse([0x0000]*2) + """Testing diagnostic message execution""" + message = ReturnQueryDataResponse([0x0000] * 2) self.assertEqual(message.encode(), b'\x00\x00\x00\x00\x00\x00') message = ReturnQueryDataResponse(0x0000) self.assertEqual(message.encode(), b'\x00\x00\x00\x00') def test_restart_cmmunications_option(self): - """ Testing diagnostic message execution """ + """Testing diagnostic message execution""" request = RestartCommunicationsOptionRequest(True) self.assertEqual(request.encode(), b'\x00\x01\xff\x00') request = RestartCommunicationsOptionRequest(False) @@ -174,7 +176,7 @@ def test_restart_cmmunications_option(self): self.assertEqual(response.encode(), b'\x00\x01\x00\x00') def test_get_clear_modbus_plus_request_execute(self): - """ Testing diagnostic message execution """ + """Testing diagnostic message execution""" request = GetClearModbusPlusRequest(data=ModbusPlusOperation.ClearStatistics) response = request.execute() self.assertEqual(response.message, ModbusPlusOperation.ClearStatistics) @@ -182,10 +184,11 @@ def test_get_clear_modbus_plus_request_execute(self): request = GetClearModbusPlusRequest(data=ModbusPlusOperation.GetStatistics) response = request.execute() resp = [ModbusPlusOperation.GetStatistics] - self.assertEqual(response.message, resp+[0x00] * 55) + self.assertEqual(response.message, resp + [0x00] * 55) + -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_events.py b/test/test_events.py index 1120ee8c8..f3ed1f5e9 100644 --- a/test/test_events.py +++ b/test/test_events.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test events. """ +"""Test events.""" import unittest from pymodbus.events import ( CommunicationRestartEvent, @@ -11,23 +11,24 @@ from pymodbus.exceptions import NotImplementedException from pymodbus.exceptions import ParameterException + class ModbusEventsTest(unittest.TestCase): - """ Unittest for the pymodbus.device module. """ + """Unittest for the pymodbus.device module.""" def setUp(self): - """ Sets up the test environment """ + """Set up the test environment""" def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_modbus_event_base_class(self): - """ Test modbus event base class. """ + """Test modbus event base class.""" event = ModbusEvent() self.assertRaises(NotImplementedException, event.encode) self.assertRaises(NotImplementedException, lambda: event.decode(None)) def test_remote_receive_event(self): - """ Test remove receive event. """ + """Test remove receive event.""" event = RemoteReceiveEvent() event.decode(b'\x70') self.assertTrue(event.overrun) @@ -35,7 +36,7 @@ def test_remote_receive_event(self): self.assertTrue(event.broadcast) def test_remote_sent_event(self): - """ Test remote sent event. """ + """Test remote sent event.""" event = RemoteSendEvent() result = event.encode() self.assertEqual(result, b'\x40') @@ -48,21 +49,21 @@ def test_remote_sent_event(self): self.assertTrue(event.listen) def test_remote_sent_event_encode(self): - """ Test remote sent event encode. """ + """Test remote sent event encode.""" arguments = { - 'read' : True, - 'slave_abort' : True, - 'slave_busy' : True, - 'slave_nak' : True, - 'write_timeout' : True, - 'listen' : True, + 'read': True, + 'slave_abort': True, + 'slave_busy': True, + 'slave_nak': True, + 'write_timeout': True, + 'listen': True, } event = RemoteSendEvent(**arguments) result = event.encode() self.assertEqual(result, b'\x7f') def test_entered_listen_mode_event(self): - """ Test entered listen mode event. """ + """Test entered listen mode event.""" event = EnteredListenModeEvent() result = event.encode() self.assertEqual(result, b'\x04') @@ -71,7 +72,7 @@ def test_entered_listen_mode_event(self): self.assertRaises(ParameterException, lambda: event.decode(b'\x00')) def test_communication_restart_event(self): - """ Test communication restart event. """ + """Test communication restart event.""" event = CommunicationRestartEvent() result = event.encode() self.assertEqual(result, b'\x00') @@ -79,8 +80,9 @@ def test_communication_restart_event(self): self.assertEqual(event.value, 0x00) self.assertRaises(ParameterException, lambda: event.decode(b'\x04')) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_exceptions.py b/test/test_exceptions.py index 2403d5d07..bb314a673 100644 --- a/test/test_exceptions.py +++ b/test/test_exceptions.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test exceptions. """ +"""Test exceptions.""" import unittest from pymodbus.exceptions import ( @@ -10,24 +10,25 @@ ModbusIOException, ) + class SimpleExceptionsTest(unittest.TestCase): - """ Unittest for the pymodbus.exceptions module. """ + """Unittest for the pymodbus.exceptions module.""" def setUp(self): - """ Initializes the test environment """ + """Initialize the test environment""" self.exceptions = [ - ModbusException("bad base"), - ModbusIOException("bad register"), - ParameterException("bad parameter"), - NotImplementedException("bad function"), - ConnectionException("bad connection"), + ModbusException("bad base"), + ModbusIOException("bad register"), + ParameterException("bad parameter"), + NotImplementedException("bad function"), + ConnectionException("bad connection"), ] def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_exceptions(self): - """ Test all module exceptions """ + """Test all module exceptions""" for exc in self.exceptions: try: raise exc @@ -36,8 +37,9 @@ def test_exceptions(self): return self.fail("Excepted a ModbusExceptions") -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_factory.py b/test/test_factory.py index b9dec1041..377d4ad85 100644 --- a/test/test_factory.py +++ b/test/test_factory.py @@ -1,95 +1,97 @@ #!/usr/bin/env python3 -""" Test factory. """ +"""Test factory.""" import unittest from pymodbus.factory import ServerDecoder, ClientDecoder from pymodbus.exceptions import ModbusException from pymodbus.pdu import ModbusResponse, ModbusRequest + def _raise_exception(_): - """ Raise exception. """ + """Raise exception.""" raise ModbusException('something') + class SimpleFactoryTest(unittest.TestCase): - """ Unittest for the pymod.exceptions module. """ + """Unittest for the pymod.exceptions module.""" def setUp(self): - """ Initializes the test environment """ - self.client = ClientDecoder() - self.server = ServerDecoder() + """Initialize the test environment""" + self.client = ClientDecoder() + self.server = ServerDecoder() self.request = ( - (0x01, b'\x01\x00\x01\x00\x01'), # read coils - (0x02, b'\x02\x00\x01\x00\x01'), # read discrete inputs - (0x03, b'\x03\x00\x01\x00\x01'), # read holding registers - (0x04, b'\x04\x00\x01\x00\x01'), # read input registers - (0x05, b'\x05\x00\x01\x00\x01'), # write single coil - (0x06, b'\x06\x00\x01\x00\x01'), # write single register - (0x07, b'\x07'), # read exception status - (0x08, b'\x08\x00\x00\x00\x00'), # read diagnostic - (0x0b, b'\x0b'), # get comm event counters - (0x0c, b'\x0c'), # get comm event log - (0x0f, b'\x0f\x00\x01\x00\x08\x01\x00\xff'), # write multiple coils - (0x10, b'\x10\x00\x01\x00\x02\x04\0xff\xff'), # write multiple registers - (0x11, b'\x11'), # report slave id - (0x14, b'\x14\x0e\x06\x00\x04\x00\x01\x00\x02' \ - b'\x06\x00\x03\x00\x09\x00\x02'), # read file record - (0x15, b'\x15\x0d\x06\x00\x04\x00\x07\x00\x03' \ - b'\x06\xaf\x04\xbe\x10\x0d'), # write file record - (0x16, b'\x16\x00\x01\x00\xff\xff\x00'), # mask write register - (0x17, b'\x17\x00\x01\x00\x01\x00\x01\x00\x01\x02\x12\x34'), # r/w multiple regs - (0x18, b'\x18\x00\x01'), # read fifo queue - (0x2b, b'\x2b\x0e\x01\x00'), # read device identification + (0x01, b'\x01\x00\x01\x00\x01'), # read coils + (0x02, b'\x02\x00\x01\x00\x01'), # read discrete inputs + (0x03, b'\x03\x00\x01\x00\x01'), # read holding registers + (0x04, b'\x04\x00\x01\x00\x01'), # read input registers + (0x05, b'\x05\x00\x01\x00\x01'), # write single coil + (0x06, b'\x06\x00\x01\x00\x01'), # write single register + (0x07, b'\x07'), # read exception status + (0x08, b'\x08\x00\x00\x00\x00'), # read diagnostic + (0x0b, b'\x0b'), # get comm event counters + (0x0c, b'\x0c'), # get comm event log + (0x0f, b'\x0f\x00\x01\x00\x08\x01\x00\xff'), # write multiple coils + (0x10, b'\x10\x00\x01\x00\x02\x04\0xff\xff'), # write multiple registers + (0x11, b'\x11'), # report slave id + (0x14, b'\x14\x0e\x06\x00\x04\x00\x01\x00\x02' \ + b'\x06\x00\x03\x00\x09\x00\x02'), # read file record + (0x15, b'\x15\x0d\x06\x00\x04\x00\x07\x00\x03' \ + b'\x06\xaf\x04\xbe\x10\x0d'), # write file record + (0x16, b'\x16\x00\x01\x00\xff\xff\x00'), # mask write register + (0x17, b'\x17\x00\x01\x00\x01\x00\x01\x00\x01\x02\x12\x34'), # r/w multiple regs + (0x18, b'\x18\x00\x01'), # read fifo queue + (0x2b, b'\x2b\x0e\x01\x00'), # read device identification ) self.response = ( - (0x01, b'\x01\x01\x01'), # read coils - (0x02, b'\x02\x01\x01'), # read discrete inputs - (0x03, b'\x03\x02\x01\x01'), # read holding registers - (0x04, b'\x04\x02\x01\x01'), # read input registers - (0x05, b'\x05\x00\x01\x00\x01'), # write single coil - (0x06, b'\x06\x00\x01\x00\x01'), # write single register - (0x07, b'\x07\x00'), # read exception status - (0x08, b'\x08\x00\x00\x00\x00'), # read diagnostic - (0x0b, b'\x0b\x00\x00\x00\x00'), # get comm event counters - (0x0c, b'\x0c\x08\x00\x00\x01\x08\x01\x21\x20\x00'), # get comm event log - (0x0f, b'\x0f\x00\x01\x00\x08'), # write multiple coils - (0x10, b'\x10\x00\x01\x00\x02'), # write multiple registers - (0x11, b'\x11\x03\x05\x01\x54'), # report slave id (device specific) - (0x14, b'\x14\x0c\x05\x06\x0d\xfe\x00\x20\x05' \ - b'\x06\x33\xcd\x00\x40'), # read file record - (0x15, b'\x15\x0d\x06\x00\x04\x00\x07\x00\x03' \ - b'\x06\xaf\x04\xbe\x10\x0d'), # write file record - (0x16, b'\x16\x00\x01\x00\xff\xff\x00'), # mask write register - (0x17, b'\x17\x02\x12\x34'), # read/write multiple registers - (0x18, b'\x18\x00\x01\x00\x01\x00\x00'), # read fifo queue - (0x2b, b'\x2b\x0e\x01\x01\x00\x00\x01\x00\x01\x77'), # read device identification + (0x01, b'\x01\x01\x01'), # read coils + (0x02, b'\x02\x01\x01'), # read discrete inputs + (0x03, b'\x03\x02\x01\x01'), # read holding registers + (0x04, b'\x04\x02\x01\x01'), # read input registers + (0x05, b'\x05\x00\x01\x00\x01'), # write single coil + (0x06, b'\x06\x00\x01\x00\x01'), # write single register + (0x07, b'\x07\x00'), # read exception status + (0x08, b'\x08\x00\x00\x00\x00'), # read diagnostic + (0x0b, b'\x0b\x00\x00\x00\x00'), # get comm event counters + (0x0c, b'\x0c\x08\x00\x00\x01\x08\x01\x21\x20\x00'), # get comm event log + (0x0f, b'\x0f\x00\x01\x00\x08'), # write multiple coils + (0x10, b'\x10\x00\x01\x00\x02'), # write multiple registers + (0x11, b'\x11\x03\x05\x01\x54'), # report slave id (device specific) + (0x14, b'\x14\x0c\x05\x06\x0d\xfe\x00\x20\x05' \ + b'\x06\x33\xcd\x00\x40'), # read file record + (0x15, b'\x15\x0d\x06\x00\x04\x00\x07\x00\x03' \ + b'\x06\xaf\x04\xbe\x10\x0d'), # write file record + (0x16, b'\x16\x00\x01\x00\xff\xff\x00'), # mask write register + (0x17, b'\x17\x02\x12\x34'), # read/write multiple registers + (0x18, b'\x18\x00\x01\x00\x01\x00\x00'), # read fifo queue + (0x2b, b'\x2b\x0e\x01\x01\x00\x00\x01\x00\x01\x77'), # read device identification ) self.exception = ( - (0x81, b'\x81\x01\xd0\x50'), # illegal function exception - (0x82, b'\x82\x02\x90\xa1'), # illegal data address exception - (0x83, b'\x83\x03\x50\xf1'), # illegal data value exception - (0x84, b'\x84\x04\x13\x03'), # skave device failure exception - (0x85, b'\x85\x05\xd3\x53'), # acknowledge exception - (0x86, b'\x86\x06\x93\xa2'), # slave device busy exception - (0x87, b'\x87\x08\x53\xf2'), # memory parity exception - (0x88, b'\x88\x0a\x16\x06'), # gateway path unavailable exception - (0x89, b'\x89\x0b\xd6\x56'), # gateway target failed exception + (0x81, b'\x81\x01\xd0\x50'), # illegal function exception + (0x82, b'\x82\x02\x90\xa1'), # illegal data address exception + (0x83, b'\x83\x03\x50\xf1'), # illegal data value exception + (0x84, b'\x84\x04\x13\x03'), # skave device failure exception + (0x85, b'\x85\x05\xd3\x53'), # acknowledge exception + (0x86, b'\x86\x06\x93\xa2'), # slave device busy exception + (0x87, b'\x87\x08\x53\xf2'), # memory parity exception + (0x88, b'\x88\x0a\x16\x06'), # gateway path unavailable exception + (0x89, b'\x89\x0b\xd6\x56'), # gateway target failed exception ) self.bad = ( - (0x80, b'\x80\x00\x00\x00'), # Unknown Function - (0x81, b'\x81\x00\x00\x00'), # error message + (0x80, b'\x80\x00\x00\x00'), # Unknown Function + (0x81, b'\x81\x00\x00\x00'), # error message ) def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.bad del self.request del self.response def test_exception_lookup(self): - """ Test that we can look up exception messages """ + """Test that we can look up exception messages""" for func, _ in self.exception: response = self.client.lookupPduClass(func) self.assertNotEqual(response, None) @@ -99,55 +101,56 @@ def test_exception_lookup(self): self.assertNotEqual(response, None) def test_response_lookup(self): - """ Test a working response factory lookup """ + """Test a working response factory lookup""" for func, _ in self.response: response = self.client.lookupPduClass(func) self.assertNotEqual(response, None) def test_request_ookup(self): - """ Test a working request factory lookup """ + """Test a working request factory lookup""" for func, _ in self.request: request = self.client.lookupPduClass(func) self.assertNotEqual(request, None) def test_response_working(self): - """ Test a working response factory decoders """ + """Test a working response factory decoders""" for func, msg in self.response: try: self.client.decode(msg) except ModbusException: - self.fail("Failed to Decode Response Message", func) # pylint: disable=too-many-function-args + self.fail("Failed to Decode Response Message", func) # pylint: disable=too-many-function-args def test_response_errors(self): - """ Test a response factory decoder exceptions """ - self.assertRaises(ModbusException, self.client._helper, self.bad[0][1]) # pylint: disable=protected-access + """Test a response factory decoder exceptions""" + self.assertRaises(ModbusException, self.client._helper, self.bad[0][1]) # pylint: disable=protected-access self.assertEqual(self.client.decode(self.bad[1][1]).function_code, self.bad[1][0], - "Failed to decode error PDU") + "Failed to decode error PDU") def test_requests_working(self): - """ Test a working request factory decoders """ + """Test a working request factory decoders""" for func, msg in self.request: try: self.server.decode(msg) except ModbusException: - self.fail("Failed to Decode Request Message", func) # pylint: disable=too-many-function-args + self.fail("Failed to Decode Request Message", func) # pylint: disable=too-many-function-args def test_client_factory_fails(self): - """ Tests that a client factory will fail to decode a bad message """ - self.client._helper = _raise_exception # pylint: disable=protected-access + """Tests that a client factory will fail to decode a bad message""" + self.client._helper = _raise_exception # pylint: disable=protected-access actual = self.client.decode(None) self.assertEqual(actual, None) def test_server_factory_fails(self): - """ Tests that a server factory will fail to decode a bad message """ - self.server._helper = _raise_exception # pylint: disable=protected-access + """Tests that a server factory will fail to decode a bad message""" + self.server._helper = _raise_exception # pylint: disable=protected-access actual = self.server.decode(None) self.assertEqual(actual, None) def test_server_register_custom_request(self): - """ Test server register custom request. """ + """Test server register custom request.""" class CustomRequest(ModbusRequest): - """ Custom request. """ + """Custom request.""" + function_code = 0xff self.server.register(CustomRequest) self.assertTrue(self.client.lookupPduClass(CustomRequest.function_code)) @@ -156,30 +159,33 @@ class CustomRequest(ModbusRequest): self.assertTrue(self.server.lookupPduClass(CustomRequest.function_code)) def test_client_register_custom_response(self): - """ Test client register custom response. """ + """Test client register custom response.""" class CustomResponse(ModbusResponse): - """ Custom response. """ + """Custom response.""" + function_code = 0xff self.client.register(CustomResponse) self.assertTrue(self.client.lookupPduClass(CustomResponse.function_code)) CustomResponse.sub_function_code = 0xff self.client.register(CustomResponse) self.assertTrue(self.client.lookupPduClass(CustomResponse.function_code)) -#---------------------------------------------------------------------------# -# I don't actually know what is supposed to be returned here, I assume that -# since the high bit is set, it will simply echo the resulting message -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# I don't actually know what is supposed to be returned here, I assume that +# since the high bit is set, it will simply echo the resulting message +# ---------------------------------------------------------------------------# + def test_request_errors(self): - """ Test a request factory decoder exceptions """ + """Test a request factory decoder exceptions""" for func, msg in self.bad: result = self.server.decode(msg) self.assertEqual(result.ErrorCode, 1, - "Failed to decode invalid requests") + "Failed to decode invalid requests") self.assertEqual(result.execute(None).function_code, func, - "Failed to create correct response message") + "Failed to create correct response message") + -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_file_message.py b/test/test_file_message.py index 295cbd29e..a0646b106 100644 --- a/test/test_file_message.py +++ b/test/test_file_message.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -""" Bit Message Test Fixture --------------------------------- +"""Bit Message Test Fixture. This fixture tests the functionality of all the bit based request/response messages: @@ -22,97 +21,98 @@ from .modbus_mocks import MockContext -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class ModbusBitMessageTests(unittest.TestCase): - """ Modbus bit message tests. """ - #-----------------------------------------------------------------------# - # Setup/TearDown - #-----------------------------------------------------------------------# + """Modbus bit message tests.""" + + # -----------------------------------------------------------------------# + # Setup/TearDown + # -----------------------------------------------------------------------# def setUp(self): - """ Initializes the test environment and builds request/result - encoding pairs - """ + """Initialize the test environment and builds request/result encoding pairs.""" def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" - #-----------------------------------------------------------------------# - # Read Fifo Queue - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Read Fifo Queue + # -----------------------------------------------------------------------# def test_read_fifo_queue_request_encode(self): - """ Test basic bit message encoding/decoding """ - handle = ReadFifoQueueRequest(0x1234) - result = handle.encode() + """Test basic bit message encoding/decoding""" + handle = ReadFifoQueueRequest(0x1234) + result = handle.encode() self.assertEqual(result, b'\x12\x34') def test_read_fifo_queue_request_decode(self): - """ Test basic bit message encoding/decoding """ - handle = ReadFifoQueueRequest(0x0000) + """Test basic bit message encoding/decoding""" + handle = ReadFifoQueueRequest(0x0000) handle.decode(b'\x12\x34') self.assertEqual(handle.address, 0x1234) def test_read_fifo_queue_request(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" context = MockContext() - handle = ReadFifoQueueRequest(0x1234) - result = handle.execute(context) + handle = ReadFifoQueueRequest(0x1234) + result = handle.execute(context) self.assertTrue(isinstance(result, ReadFifoQueueResponse)) handle.address = -1 - result = handle.execute(context) + result = handle.execute(context) self.assertEqual(ModbusExceptions.IllegalValue, - result.exception_code) + result.exception_code) - handle.values = [0x00]*33 - result = handle.execute(context) + handle.values = [0x00] * 33 + result = handle.execute(context) self.assertEqual(ModbusExceptions.IllegalValue, - result.exception_code) + result.exception_code) def test_read_fifo_queue_request_error(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" context = MockContext() - handle = ReadFifoQueueRequest(0x1234) - handle.values = [0x00]*32 + handle = ReadFifoQueueRequest(0x1234) + handle.values = [0x00] * 32 result = handle.execute(context) self.assertEqual(result.function_code, 0x98) def test_read_fifo_queue_response_encode(self): - """ Test that the read fifo queue response can encode """ + """Test that the read fifo queue response can encode""" message = b'\x00\n\x00\x08\x00\x01\x00\x02\x00\x03\x00\x04' - handle = ReadFifoQueueResponse([1,2,3,4]) - result = handle.encode() + handle = ReadFifoQueueResponse([1, 2, 3, 4]) + result = handle.encode() self.assertEqual(result, message) def test_read_fifo_queue_response_decode(self): - """ Test that the read fifo queue response can decode """ + """Test that the read fifo queue response can decode""" message = b'\x00\n\x00\x08\x00\x01\x00\x02\x00\x03\x00\x04' - handle = ReadFifoQueueResponse([1,2,3,4]) + handle = ReadFifoQueueResponse([1, 2, 3, 4]) handle.decode(message) - self.assertEqual(handle.values, [1,2,3,4]) + self.assertEqual(handle.values, [1, 2, 3, 4]) def test_rtu_frame_size(self): - """ Test that the read fifo queue response can decode """ + """Test that the read fifo queue response can decode""" message = b'\x00\n\x00\x08\x00\x01\x00\x02\x00\x03\x00\x04' - result = ReadFifoQueueResponse.calculateRtuFrameSize(message) + result = ReadFifoQueueResponse.calculateRtuFrameSize(message) self.assertEqual(result, 14) - #-----------------------------------------------------------------------# - # File Record - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # File Record + # -----------------------------------------------------------------------# def test_file_record_length(self): - """ Test file record length generation """ + """Test file record length generation""" record = FileRecord(file_number=0x01, record_number=0x02, - record_data=b'\x00\x01\x02\x04') + record_data=b'\x00\x01\x02\x04') self.assertEqual(record.record_length, 0x02) self.assertEqual(record.response_length, 0x05) def test_file_record_compare(self): - """ Test file record comparison operations """ + """Test file record comparison operations""" record1 = FileRecord(file_number=0x01, record_number=0x02, record_data=b'\x00\x01\x02\x04') record2 = FileRecord(file_number=0x01, record_number=0x02, record_data=b'\x00\x0a\x0e\x04') record3 = FileRecord(file_number=0x02, record_number=0x03, record_data=b'\x00\x01\x02\x04') @@ -127,130 +127,130 @@ def test_file_record_compare(self): self.assertEqual(str(record2), "FileRecord(file=1, record=2, length=2)") self.assertEqual(str(record3), "FileRecord(file=2, record=3, length=2)") - #-----------------------------------------------------------------------# - # Read File Record Request - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Read File Record Request + # -----------------------------------------------------------------------# def test_read_file_record_request_encode(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" records = [FileRecord(file_number=0x01, record_number=0x02)] - handle = ReadFileRecordRequest(records) - result = handle.encode() + handle = ReadFileRecordRequest(records) + result = handle.encode() self.assertEqual(result, b'\x07\x06\x00\x01\x00\x02\x00\x00') def test_read_file_record_request_decode(self): - """ Test basic bit message encoding/decoding """ - record = FileRecord(file_number=0x04, record_number=0x01, record_length=0x02) + """Test basic bit message encoding/decoding""" + record = FileRecord(file_number=0x04, record_number=0x01, record_length=0x02) request = b'\x0e\x06\x00\x04\x00\x01\x00\x02\x06\x00\x03\x00\x09\x00\x02' - handle = ReadFileRecordRequest() + handle = ReadFileRecordRequest() handle.decode(request) self.assertEqual(handle.records[0], record) def test_read_file_record_request_rtu_frame_size(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" request = b'\x00\x00\x0e\x06\x00\x04\x00\x01\x00\x02\x06\x00\x03\x00\x09\x00\x02' - handle = ReadFileRecordRequest() - size = handle.calculateRtuFrameSize(request) + handle = ReadFileRecordRequest() + size = handle.calculateRtuFrameSize(request) self.assertEqual(size, 0x0e + 5) def test_read_file_record_request_execute(self): - """ Test basic bit message encoding/decoding """ - handle = ReadFileRecordRequest() - result = handle.execute(None) + """Test basic bit message encoding/decoding""" + handle = ReadFileRecordRequest() + result = handle.execute(None) self.assertTrue(isinstance(result, ReadFileRecordResponse)) - #-----------------------------------------------------------------------# - # Read File Record Response - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Read File Record Response + # -----------------------------------------------------------------------# def test_read_file_record_response_encode(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" records = [FileRecord(record_data=b'\x00\x01\x02\x03')] - handle = ReadFileRecordResponse(records) - result = handle.encode() + handle = ReadFileRecordResponse(records) + result = handle.encode() self.assertEqual(result, b'\x06\x06\x02\x00\x01\x02\x03') def test_read_file_record_response_decode(self): - """ Test basic bit message encoding/decoding """ - record = FileRecord(file_number=0x00, record_number=0x00, - record_data=b'\x0d\xfe\x00\x20') + """Test basic bit message encoding/decoding""" + record = FileRecord(file_number=0x00, record_number=0x00, + record_data=b'\x0d\xfe\x00\x20') request = b'\x0c\x05\x06\x0d\xfe\x00\x20\x05\x05\x06\x33\xcd\x00\x40' - handle = ReadFileRecordResponse() + handle = ReadFileRecordResponse() handle.decode(request) self.assertEqual(handle.records[0], record) def test_read_file_record_response_rtu_frame_size(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" request = b'\x00\x00\x0c\x05\x06\x0d\xfe\x00\x20\x05\x05\x06\x33\xcd\x00\x40' - handle = ReadFileRecordResponse() - size = handle.calculateRtuFrameSize(request) + handle = ReadFileRecordResponse() + size = handle.calculateRtuFrameSize(request) self.assertEqual(size, 0x0c + 5) - #-----------------------------------------------------------------------# - # Write File Record Request - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Write File Record Request + # -----------------------------------------------------------------------# def test_write_file_record_request_encode(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" records = [FileRecord(file_number=0x01, record_number=0x02, - record_data=b'\x00\x01\x02\x03')] - handle = WriteFileRecordRequest(records) - result = handle.encode() + record_data=b'\x00\x01\x02\x03')] + handle = WriteFileRecordRequest(records) + result = handle.encode() self.assertEqual(result, b'\x0b\x06\x00\x01\x00\x02\x00\x02\x00\x01\x02\x03') def test_write_file_record_request_decode(self): - """ Test basic bit message encoding/decoding """ - record = FileRecord(file_number=0x04, record_number=0x07, - record_data=b'\x06\xaf\x04\xbe\x10\x0d') + """Test basic bit message encoding/decoding""" + record = FileRecord(file_number=0x04, record_number=0x07, + record_data=b'\x06\xaf\x04\xbe\x10\x0d') request = b'\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d' - handle = WriteFileRecordRequest() + handle = WriteFileRecordRequest() handle.decode(request) self.assertEqual(handle.records[0], record) def test_write_file_record_request_rtu_frame_size(self): - """ Test write file record request rtu frame size calculation """ + """Test write file record request rtu frame size calculation""" request = b'\x00\x00\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d' - handle = WriteFileRecordRequest() - size = handle.calculateRtuFrameSize(request) + handle = WriteFileRecordRequest() + size = handle.calculateRtuFrameSize(request) self.assertEqual(size, 0x0d + 5) def test_write_file_record_request_execute(self): - """ Test basic bit message encoding/decoding """ - handle = WriteFileRecordRequest() - result = handle.execute(None) + """Test basic bit message encoding/decoding""" + handle = WriteFileRecordRequest() + result = handle.execute(None) self.assertTrue(isinstance(result, WriteFileRecordResponse)) - #-----------------------------------------------------------------------# - # Write File Record Response - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Write File Record Response + # -----------------------------------------------------------------------# def test_write_file_record_response_encode(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" records = [FileRecord(file_number=0x01, record_number=0x02, - record_data=b'\x00\x01\x02\x03')] - handle = WriteFileRecordResponse(records) - result = handle.encode() + record_data=b'\x00\x01\x02\x03')] + handle = WriteFileRecordResponse(records) + result = handle.encode() self.assertEqual(result, b'\x0b\x06\x00\x01\x00\x02\x00\x02\x00\x01\x02\x03') def test_write_file_record_response_decode(self): - """ Test basic bit message encoding/decoding """ - record = FileRecord(file_number=0x04, record_number=0x07, - record_data=b'\x06\xaf\x04\xbe\x10\x0d') + """Test basic bit message encoding/decoding""" + record = FileRecord(file_number=0x04, record_number=0x07, + record_data=b'\x06\xaf\x04\xbe\x10\x0d') request = b'\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d' - handle = WriteFileRecordResponse() + handle = WriteFileRecordResponse() handle.decode(request) self.assertEqual(handle.records[0], record) def test_write_file_record_response_rtu_frame_size(self): - """ Test write file record response rtu frame size calculation """ + """Test write file record response rtu frame size calculation""" request = b'\x00\x00\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d' - handle = WriteFileRecordResponse() - size = handle.calculateRtuFrameSize(request) + handle = WriteFileRecordResponse() + size = handle.calculateRtuFrameSize(request) self.assertEqual(size, 0x0d + 5) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_fixes.py b/test/test_fixes.py index f7c12f32f..cd403f31d 100644 --- a/test/test_fixes.py +++ b/test/test_fixes.py @@ -1,26 +1,28 @@ #!/usr/bin/env python3 -""" Test fixes. """ +"""Test fixes.""" import logging import unittest + class ModbusFixesTest(unittest.TestCase): - """ Unittest for the pymodbus._version code. """ + """Unittest for the pymodbus._version code.""" def test_true_false_defined(self): - """ Test that True and False are defined on all versions""" + """Test that True and False are defined on all versions""" try: - True,False + True, False except NameError: self.assertEqual(True, 1) self.assertEqual(False, 1) def test_null_logger_attached(self): - """ Test that the null logger is attached""" + """Test that the null logger is attached""" logger = logging.getLogger('pymodbus') self.assertEqual(len(logger.handlers), 1) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_framers.py b/test/test_framers.py index 32eb21c03..2b17ebf02 100644 --- a/test/test_framers.py +++ b/test/test_framers.py @@ -1,4 +1,4 @@ -""" Test framers. """ +"""Test framers.""" from unittest.mock import Mock, patch import pytest @@ -13,58 +13,58 @@ @pytest.fixture def rtu_framer(): - """ RTU framer. """ + """RTU framer.""" return ModbusRtuFramer(ClientDecoder()) @pytest.fixture def ascii_framer(): - """ Ascii framer. """ + """Ascii framer.""" return ModbusAsciiFramer(ClientDecoder()) @pytest.fixture def binary_framer(): - """ Binary framer. """ + """Binary framer.""" return ModbusBinaryFramer(ClientDecoder()) -@pytest.mark.parametrize("framer", [ModbusRtuFramer, - ModbusAsciiFramer, - ModbusBinaryFramer, - ]) +@pytest.mark.parametrize("framer", [ModbusRtuFramer, + ModbusAsciiFramer, + ModbusBinaryFramer, + ]) def test_framer_initialization(framer): - """ Test framer initialization. """ + """Test framer initialization.""" decoder = ClientDecoder() framer = framer(decoder) - assert framer.client is None #nosec - assert framer._buffer == b'' #nosec pylint: disable=protected-access - assert framer.decoder == decoder #nosec + assert framer.client is None # nosec + assert framer._buffer == b'' # nosec pylint: disable=protected-access + assert framer.decoder == decoder # nosec if isinstance(framer, ModbusAsciiFramer): - assert framer._header == {'lrc': '0000', 'len': 0, 'uid': 0x00} #nosec pylint: disable=protected-access - assert framer._hsize == 0x02 #nosec pylint: disable=protected-access - assert framer._start == b':' #nosec pylint: disable=protected-access - assert framer._end == b"\r\n" #nosec pylint: disable=protected-access + assert framer._header == {'lrc': '0000', 'len': 0, 'uid': 0x00} # nosec pylint: disable=protected-access + assert framer._hsize == 0x02 # nosec pylint: disable=protected-access + assert framer._start == b':' # nosec pylint: disable=protected-access + assert framer._end == b"\r\n" # nosec pylint: disable=protected-access elif isinstance(framer, ModbusRtuFramer): - assert framer._header == {'uid': 0x00, 'len': 0, 'crc': b'\x00\x00'} #nosec pylint: disable=protected-access - assert framer._hsize == 0x01 #nosec pylint: disable=protected-access - assert framer._end == b'\x0d\x0a' #nosec pylint: disable=protected-access - assert framer._min_frame_size == 4 #nosec pylint: disable=protected-access + assert framer._header == {'uid': 0x00, 'len': 0, 'crc': b'\x00\x00'} # nosec pylint: disable=protected-access + assert framer._hsize == 0x01 # nosec pylint: disable=protected-access + assert framer._end == b'\x0d\x0a' # nosec pylint: disable=protected-access + assert framer._min_frame_size == 4 # nosec pylint: disable=protected-access else: - assert framer._header == {'crc': 0x0000, 'len': 0, 'uid': 0x00} #nosec pylint: disable=protected-access - assert framer._hsize == 0x01 #nosec pylint: disable=protected-access - assert framer._start == b'\x7b' #nosec pylint: disable=protected-access - assert framer._end == b'\x7d' #nosec pylint: disable=protected-access - assert framer._repeat == [b'}'[0], b'{'[0]] #nosec pylint: disable=protected-access + assert framer._header == {'crc': 0x0000, 'len': 0, 'uid': 0x00} # nosec pylint: disable=protected-access + assert framer._hsize == 0x01 # nosec pylint: disable=protected-access + assert framer._start == b'\x7b' # nosec pylint: disable=protected-access + assert framer._end == b'\x7d' # nosec pylint: disable=protected-access + assert framer._repeat == [b'}'[0], b'{'[0]] # nosec pylint: disable=protected-access @pytest.mark.parametrize("data", [(b'', {}), (b'abcd', {'fcode': 98, 'unit': 97})]) -def test_decode_data(rtu_framer, data): # pylint: disable=redefined-outer-name - """ Test decode data. """ +def test_decode_data(rtu_framer, data): # pylint: disable=redefined-outer-name + """Test decode data.""" data, expected = data decoded = rtu_framer.decode_data(data) - assert decoded == expected #nosec + assert decoded == expected # nosec @pytest.mark.parametrize("data", [ @@ -73,11 +73,11 @@ def test_decode_data(rtu_framer, data): # pylint: disable=redefined-outer-name (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAD', True), # valid frame (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAC', False), # invalid frame CRC ]) -def test_check_frame(rtu_framer, data): # pylint: disable=redefined-outer-name - """ Test check frame. """ +def test_check_frame(rtu_framer, data): # pylint: disable=redefined-outer-name + """Test check frame.""" data, expected = data - rtu_framer._buffer = data # pylint: disable=protected-access - assert expected == rtu_framer.checkFrame() #nosec + rtu_framer._buffer = data # pylint: disable=protected-access + assert expected == rtu_framer.checkFrame() # nosec @pytest.mark.parametrize("data", [ @@ -86,24 +86,24 @@ def test_check_frame(rtu_framer, data): # pylint: disable=redefined-outer-name (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAD\x12\x03', # real case, frame size is 11 {'uid': 0x00, 'len': 11, 'crc': b'\x00\x00'}, b'\x12\x03'), ]) -def test_rtu_advance_framer(rtu_framer, data): # pylint: disable=redefined-outer-name - """ Test rtu advance framer. """ +def test_rtu_advance_framer(rtu_framer, data): # pylint: disable=redefined-outer-name + """Test rtu advance framer.""" before_buf, before_header, after_buf = data - rtu_framer._buffer = before_buf # pylint: disable=protected-access - rtu_framer._header = before_header # pylint: disable=protected-access + rtu_framer._buffer = before_buf # pylint: disable=protected-access + rtu_framer._header = before_header # pylint: disable=protected-access rtu_framer.advanceFrame() - assert rtu_framer._header == {'uid': 0x00, 'len': 0, 'crc': b'\x00\x00'} #nosec pylint: disable=protected-access - assert rtu_framer._buffer == after_buf #nosec pylint: disable=protected-access + assert rtu_framer._header == {'uid': 0x00, 'len': 0, 'crc': b'\x00\x00'} # nosec pylint: disable=protected-access + assert rtu_framer._buffer == after_buf # nosec pylint: disable=protected-access @pytest.mark.parametrize("data", [b'', b'abcd']) -def test_rtu_reset_framer(rtu_framer, data): # pylint: disable=redefined-outer-name - """ Test rtu reset framer. """ - rtu_framer._buffer = data # pylint: disable=protected-access +def test_rtu_reset_framer(rtu_framer, data): # pylint: disable=redefined-outer-name + """Test rtu reset framer.""" + rtu_framer._buffer = data # pylint: disable=protected-access rtu_framer.resetFrame() - assert rtu_framer._header == {'uid': 0x00, 'len': 0, 'crc': b'\x00\x00'} #nosec pylint: disable=protected-access - assert rtu_framer._buffer == b'' #nosec pylint: disable=protected-access + assert rtu_framer._header == {'uid': 0x00, 'len': 0, 'crc': b'\x00\x00'} # nosec pylint: disable=protected-access + assert rtu_framer._buffer == b'' # nosec pylint: disable=protected-access @pytest.mark.parametrize("data", [ @@ -115,12 +115,12 @@ def test_rtu_reset_framer(rtu_framer, data): # pylint: disable=redefined-outer-n (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAD', True), (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAD\xAB\xCD', True), ]) -def test_is_frame_ready(rtu_framer, data): # pylint: disable=redefined-outer-name - """ Test is frame ready. """ +def test_is_frame_ready(rtu_framer, data): # pylint: disable=redefined-outer-name + """Test is frame ready.""" data, expected = data - rtu_framer._buffer = data # pylint: disable=protected-access + rtu_framer._buffer = data # pylint: disable=protected-access # rtu_framer.advanceFrame() - assert rtu_framer.isFrameReady() == expected #nosec + assert rtu_framer.isFrameReady() == expected # nosec @pytest.mark.parametrize("data", [ @@ -130,8 +130,8 @@ def test_is_frame_ready(rtu_framer, data): # pylint: disable=redefined-outer-nam b'\x11\x03\x06', b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x43', ]) -def test_rtu_populate_header_fail(rtu_framer, data): # pylint: disable=redefined-outer-name - """ Test rtu populate header fail. """ +def test_rtu_populate_header_fail(rtu_framer, data): # pylint: disable=redefined-outer-name + """Test rtu populate header fail.""" with pytest.raises(IndexError): rtu_framer.populateHeader(data) @@ -141,33 +141,33 @@ def test_rtu_populate_header_fail(rtu_framer, data): # pylint: disable=redefined (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAD\x11\x03', { 'crc': b'\x49\xAD', 'uid': 17, 'len': 11}) ]) -def test_rtu_populate_header(rtu_framer, data): # pylint: disable=redefined-outer-name - """ Test rtu populate header. """ +def test_rtu_populate_header(rtu_framer, data): # pylint: disable=redefined-outer-name + """Test rtu populate header.""" buffer, expected = data rtu_framer.populateHeader(buffer) - assert rtu_framer._header == expected #nosec pylint: disable=protected-access + assert rtu_framer._header == expected # nosec pylint: disable=protected-access -def test_add_to_frame(rtu_framer): # pylint: disable=redefined-outer-name - """ Test add to frame. """ - assert rtu_framer._buffer == b'' #nosec pylint: disable=protected-access +def test_add_to_frame(rtu_framer): # pylint: disable=redefined-outer-name + """Test add to frame.""" + assert rtu_framer._buffer == b'' # nosec pylint: disable=protected-access rtu_framer.addToFrame(b'abcd') - assert rtu_framer._buffer == b'abcd' #nosec pylint: disable=protected-access + assert rtu_framer._buffer == b'abcd' # nosec pylint: disable=protected-access -def test_get_frame(rtu_framer): # pylint: disable=redefined-outer-name - """ Test get frame. """ +def test_get_frame(rtu_framer): # pylint: disable=redefined-outer-name + """Test get frame.""" rtu_framer.addToFrame(b'\x02\x01\x01\x00Q\xcc') rtu_framer.populateHeader(b'\x02\x01\x01\x00Q\xcc') - assert rtu_framer.getFrame() == b'\x01\x01\x00' #nosec + assert rtu_framer.getFrame() == b'\x01\x01\x00' # nosec -def test_populate_result(rtu_framer): # pylint: disable=redefined-outer-name - """ Test populate result. """ - rtu_framer._header['uid'] = 255 # pylint: disable=protected-access +def test_populate_result(rtu_framer): # pylint: disable=redefined-outer-name + """Test populate result.""" + rtu_framer._header['uid'] = 255 # pylint: disable=protected-access result = Mock() rtu_framer.populateResult(result) - assert result.unit_id == 255 #nosec + assert result.unit_id == 255 # nosec @pytest.mark.parametrize("data", [ @@ -181,27 +181,27 @@ def test_populate_result(rtu_framer): # pylint: disable=redefined-outer-name (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAD', 17, False, True), # good frame (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAD', 16, True, False), # incorrect unit id (b'\x11\x03\x06\xAE\x41\x56\x52\x43\x40\x49\xAD\x11\x03', 17, False, True), - # good frame + part of next frame + # good frame + part of next frame ]) -def test_rtu_incoming_packet(rtu_framer, data): # pylint: disable=redefined-outer-name - """ Test rtu process incoming packet. """ +def test_rtu_incoming_packet(rtu_framer, data): # pylint: disable=redefined-outer-name + """Test rtu process incoming packet.""" buffer, units, reset_called, process_called = data with patch.object(rtu_framer, '_process') as mock_process, \ patch.object(rtu_framer, 'resetFrame') as mock_reset: rtu_framer.processIncomingPacket(buffer, Mock(), units) - assert mock_process.call_count == (1 if process_called else 0) #nosec - assert mock_reset.call_count == (1 if reset_called else 0) #nosec + assert mock_process.call_count == (1 if process_called else 0) # nosec + assert mock_reset.call_count == (1 if reset_called else 0) # nosec -def test_build_packet(rtu_framer): # pylint: disable=redefined-outer-name - """ Test build packet. """ +def test_build_packet(rtu_framer): # pylint: disable=redefined-outer-name + """Test build packet.""" message = ReadCoilsRequest(1, 10) - assert rtu_framer.buildPacket(message) == b'\x00\x01\x00\x01\x00\n\xec\x1c' #nosec + assert rtu_framer.buildPacket(message) == b'\x00\x01\x00\x01\x00\n\xec\x1c' # nosec -def test_send_packet(rtu_framer): # pylint: disable=redefined-outer-name - """ Test send packet. """ +def test_send_packet(rtu_framer): # pylint: disable=redefined-outer-name + """Test send packet.""" message = b'\x00\x01\x00\x01\x00\n\xec\x1c' client = Mock() client.state = ModbusTransactionState.TRANSACTION_COMPLETE @@ -211,51 +211,51 @@ def test_send_packet(rtu_framer): # pylint: disable=redefined-outer-name client.idle_time.return_value = 1 client.send.return_value = len(message) rtu_framer.client = client - assert rtu_framer.sendPacket(message) == len(message) #nosec + assert rtu_framer.sendPacket(message) == len(message) # nosec client.state = ModbusTransactionState.PROCESSING_REPLY - assert rtu_framer.sendPacket(message) == len(message) #nosec + assert rtu_framer.sendPacket(message) == len(message) # nosec -def test_recv_packet(rtu_framer): # pylint: disable=redefined-outer-name - """ Test receive packet. """ +def test_recv_packet(rtu_framer): # pylint: disable=redefined-outer-name + """Test receive packet.""" message = b'\x00\x01\x00\x01\x00\n\xec\x1c' client = Mock() client.recv.return_value = message rtu_framer.client = client - assert rtu_framer.recvPacket(len(message)) == message #nosec + assert rtu_framer.recvPacket(len(message)) == message # nosec -def test_process(rtu_framer): # pylint: disable=redefined-outer-name - """ Test process. """ +def test_process(rtu_framer): # pylint: disable=redefined-outer-name + """Test process.""" def callback(res): return res - rtu_framer._buffer = b'\x00\x01\x00\x01\x00\n\xec\x1c' # pylint: disable=protected-access + rtu_framer._buffer = b'\x00\x01\x00\x01\x00\n\xec\x1c' # pylint: disable=protected-access with pytest.raises(ModbusIOException): - rtu_framer._process(callback) # pylint: disable=protected-access + rtu_framer._process(callback) # pylint: disable=protected-access -def test_get_raw_frame(rtu_framer): # pylint: disable=redefined-outer-name - """ Test get raw frame. """ - rtu_framer._buffer = b'\x00\x01\x00\x01\x00\n\xec\x1c' # pylint: disable=protected-access - assert rtu_framer.getRawFrame() == rtu_framer._buffer #nosec pylint: disable=protected-access +def test_get_raw_frame(rtu_framer): # pylint: disable=redefined-outer-name + """Test get raw frame.""" + rtu_framer._buffer = b'\x00\x01\x00\x01\x00\n\xec\x1c' # pylint: disable=protected-access + assert rtu_framer.getRawFrame() == rtu_framer._buffer # nosec pylint: disable=protected-access -def test_validate_unit_id(rtu_framer): # pylint: disable=redefined-outer-name - """ Test validate unit. """ - rtu_framer.populateHeader( b'\x00\x01\x00\x01\x00\n\xec\x1c') - assert rtu_framer._validate_unit_id([0], False) #nosec pylint: disable=protected-access - assert rtu_framer._validate_unit_id([1], True) #nosec pylint: disable=protected-access +def test_validate_unit_id(rtu_framer): # pylint: disable=redefined-outer-name + """Test validate unit.""" + rtu_framer.populateHeader(b'\x00\x01\x00\x01\x00\n\xec\x1c') + assert rtu_framer._validate_unit_id([0], False) # nosec pylint: disable=protected-access + assert rtu_framer._validate_unit_id([1], True) # nosec pylint: disable=protected-access @pytest.mark.parametrize('data', [b':010100010001FC\r\n', b'']) -def test_decode_ascii_data(ascii_framer, data): # pylint: disable=redefined-outer-name - """ Test decode ascii. """ +def test_decode_ascii_data(ascii_framer, data): # pylint: disable=redefined-outer-name + """Test decode ascii.""" data = ascii_framer.decode_data(data) - assert isinstance(data, dict) #nosec + assert isinstance(data, dict) # nosec if data: - assert data.get("unit") == 1 #nosec - assert data.get("fcode") == 1 #nosec + assert data.get("unit") == 1 # nosec + assert data.get("fcode") == 1 # nosec else: - assert not data #nosec + assert not data # nosec diff --git a/test/test_interfaces.py b/test/test_interfaces.py index 0e5bd8691..f20d9c140 100644 --- a/test/test_interfaces.py +++ b/test/test_interfaces.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test interfaces. """ +"""Test interfaces.""" import unittest from pymodbus.interfaces import ( @@ -11,26 +11,28 @@ ) from pymodbus.exceptions import NotImplementedException -class _SingleInstance(Singleton): # pylint: disable=too-few-public-methods - """ Single instance. """ + +class _SingleInstance(Singleton): # pylint: disable=too-few-public-methods + """Single instance.""" + class ModbusInterfaceTestsTest(unittest.TestCase): - """ Unittest for the pymodbus.interfaces module. """ + """Unittest for the pymodbus.interfaces module.""" def setUp(self): - """ Initializes the test environment """ + """Initialize the test environment""" def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_singleton_interface(self): - """ Test that the singleton interface works """ - first = _SingleInstance() + """Test that the singleton interface works""" + first = _SingleInstance() second = _SingleInstance() self.assertEqual(first, second) def test_modbus_decoder_interface(self): - """ Test that the base class isn't implemented """ + """Test that the base class isn't implemented""" x_base = None instance = IModbusDecoder() self.assertRaises(NotImplementedException, lambda: instance.decode(x_base)) @@ -40,7 +42,7 @@ def test_modbus_decoder_interface(self): lambda: instance.register(x_base)) def test_modbus_framer_interface(self): - """ Test that the base class isn't implemented """ + """Test that the base class isn't implemented""" x_base = None instance = IModbusFramer() self.assertRaises(NotImplementedException, instance.checkFrame) @@ -48,30 +50,31 @@ def test_modbus_framer_interface(self): self.assertRaises(NotImplementedException, instance.isFrameReady) self.assertRaises(NotImplementedException, instance.getFrame) self.assertRaises(NotImplementedException, lambda: - instance.addToFrame(x_base)) + instance.addToFrame(x_base)) self.assertRaises(NotImplementedException, lambda: - instance.populateResult(x_base)) + instance.populateResult(x_base)) self.assertRaises(NotImplementedException, lambda: - instance.processIncomingPacket(x_base,x_base)) + instance.processIncomingPacket(x_base, x_base)) self.assertRaises(NotImplementedException, lambda: - instance.buildPacket(x_base)) + instance.buildPacket(x_base)) def test_modbus_slave_context_interface(self): - """ Test that the base class isn't implemented """ + """Test that the base class isn't implemented""" x_base = None instance = IModbusSlaveContext() self.assertRaises(NotImplementedException, instance.reset) - self.assertRaises(NotImplementedException, lambda: instance.validate(x_base,x_base,x_base)) - self.assertRaises(NotImplementedException, lambda: instance.getValues(x_base,x_base,x_base)) - self.assertRaises(NotImplementedException, lambda: instance.setValues(x_base,x_base,x_base)) + self.assertRaises(NotImplementedException, lambda: instance.validate(x_base, x_base, x_base)) + self.assertRaises(NotImplementedException, lambda: instance.getValues(x_base, x_base, x_base)) + self.assertRaises(NotImplementedException, lambda: instance.setValues(x_base, x_base, x_base)) def test_modbus_payload_builder_interface(self): - """ Test that the base class isn't implemented """ + """Test that the base class isn't implemented""" instance = IPayloadBuilder() - self.assertRaises(NotImplementedException, lambda: instance.build()) # pylint: disable=unnecessary-lambda + self.assertRaises(NotImplementedException, lambda: instance.build()) # pylint: disable=unnecessary-lambda + -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_mei_messages.py b/test/test_mei_messages.py index 7fc5b660b..cdf537cb5 100644 --- a/test/test_mei_messages.py +++ b/test/test_mei_messages.py @@ -1,5 +1,4 @@ -""" MEI Message Test Fixture --------------------------------- +"""MEI Message Test Fixture. This fixture tests the functionality of all the mei based request/response messages: @@ -12,42 +11,44 @@ from pymodbus.constants import DeviceInformation from pymodbus.device import ModbusControlBlock -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class ModbusMeiMessageTest(unittest.TestCase): - """ Unittest for the pymodbus.mei_message module. """ + """Unittest for the pymodbus.mei_message module.""" - #-----------------------------------------------------------------------# - # Read Device Information - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Read Device Information + # -----------------------------------------------------------------------# def test_read_device_information_request_encode(self): - """ Test basic bit message encoding/decoding """ - params = {'read_code':DeviceInformation.Basic, 'object_id':0x00 } - handle = ReadDeviceInformationRequest(**params) - result = handle.encode() + """Test basic bit message encoding/decoding""" + params = {'read_code': DeviceInformation.Basic, 'object_id': 0x00} + handle = ReadDeviceInformationRequest(**params) + result = handle.encode() self.assertEqual(result, b'\x0e\x01\x00') self.assertEqual("ReadDeviceInformationRequest(1,0)", str(handle)) def test_read_device_information_request_decode(self): - """ Test basic bit message encoding/decoding """ - handle = ReadDeviceInformationRequest() + """Test basic bit message encoding/decoding""" + handle = ReadDeviceInformationRequest() handle.decode(b'\x0e\x01\x00') self.assertEqual(handle.read_code, DeviceInformation.Basic) self.assertEqual(handle.object_id, 0x00) def test_read_device_information_request(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" context = None control = ModbusControlBlock() - control.Identity.VendorName = "Company" + control.Identity.VendorName = "Company" control.Identity.ProductCode = "Product" control.Identity.MajorMinorRevision = "v2.1.12" control.Identity.update({0x81: ['Test', 'Repeated']}) - handle = ReadDeviceInformationRequest() - result = handle.execute(context) + handle = ReadDeviceInformationRequest() + result = handle.execute(context) self.assertTrue(isinstance(result, ReadDeviceInformationResponse)) self.assertEqual(result.information[0x00], "Company") self.assertEqual(result.information[0x01], "Product") @@ -61,8 +62,8 @@ def test_read_device_information_request(self): self.assertEqual(result.information[0x81], ['Test', 'Repeated']) def test_read_device_information_request_error(self): - """ Test basic bit message encoding/decoding """ - handle = ReadDeviceInformationRequest() + """Test basic bit message encoding/decoding""" + handle = ReadDeviceInformationRequest() handle.read_code = -1 self.assertEqual(handle.execute(None).function_code, 0xab) handle.read_code = 0x05 @@ -73,17 +74,17 @@ def test_read_device_information_request_error(self): self.assertEqual(handle.execute(None).function_code, 0xab) def test_read_device_information_encode(self): - """ Test that the read fifo queue response can encode """ - message = b'\x0e\x01\x83\x00\x00\x03' + """Test that the read fifo queue response can encode""" + message = b'\x0e\x01\x83\x00\x00\x03' message += b'\x00\x07Company\x01\x07Product\x02\x07v2.1.12' - dataset = { + dataset = { 0x00: 'Company', 0x01: 'Product', 0x02: 'v2.1.12', } - handle = ReadDeviceInformationResponse( + handle = ReadDeviceInformationResponse( read_code=DeviceInformation.Basic, information=dataset) - result = handle.encode() + result = handle.encode() self.assertEqual(result, message) self.assertEqual("ReadDeviceInformationResponse(1)", str(handle)) @@ -102,33 +103,33 @@ def test_read_device_information_encode(self): self.assertEqual(result, message) def test_read_device_information_encode_long(self): - """ Test that the read fifo queue response can encode """ + """Test that the read fifo queue response can encode""" longstring = "Lorem ipsum dolor sit amet, consectetur adipiscing " \ "elit. Vivamus rhoncus massa turpis, sit amet ultrices" \ " orci semper ut. Aliquam tristique sapien in lacus " \ "pharetra, in convallis nunc consectetur. Nunc velit " \ "elit, vehicula tempus tempus sed. " - message = b'\x0e\x01\x83\xFF\x80\x03' + message = b'\x0e\x01\x83\xFF\x80\x03' message += b'\x00\x07Company\x01\x07Product\x02\x07v2.1.12' - dataset = { + dataset = { 0x00: 'Company', 0x01: 'Product', 0x02: 'v2.1.12', 0x80: longstring } - handle = ReadDeviceInformationResponse( + handle = ReadDeviceInformationResponse( read_code=DeviceInformation.Basic, information=dataset) - result = handle.encode() + result = handle.encode() self.assertEqual(result, message) self.assertEqual("ReadDeviceInformationResponse(1)", str(handle)) def test_read_device_information_decode(self): - """ Test that the read device information response can decode """ - message = b'\x0e\x01\x01\x00\x00\x05' + """Test that the read device information response can decode""" + message = b'\x0e\x01\x01\x00\x00\x05' message += b'\x00\x07Company\x01\x07Product\x02\x07v2.1.12' message += b'\x81\x04Test\x81\x08Repeated\x81\x07Another' - handle = ReadDeviceInformationResponse(read_code=0x00, information=[]) + handle = ReadDeviceInformationResponse(read_code=0x00, information=[]) handle.decode(message) self.assertEqual(handle.read_code, DeviceInformation.Basic) self.assertEqual(handle.conformity, 0x01) @@ -138,17 +139,17 @@ def test_read_device_information_decode(self): self.assertEqual(handle.information[0x81], [b'Test', b'Repeated', b'Another']) def test_rtu_frame_size(self): - """ Test that the read device information response can decode """ + """Test that the read device information response can decode""" message = b'\x04\x2B\x0E\x01\x81\x00\x01\x01\x00\x06\x66\x6F\x6F\x62\x61\x72\xD7\x3B' - result = ReadDeviceInformationResponse.calculateRtuFrameSize(message) + result = ReadDeviceInformationResponse.calculateRtuFrameSize(message) self.assertEqual(result, 18) message = b'\x00\x2B\x0E\x02\x00\x4D\x47' result = ReadDeviceInformationRequest.calculateRtuFrameSize(message) self.assertEqual(result, 7) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_other_messages.py b/test/test_other_messages.py index de8e33d29..09ce4cebc 100644 --- a/test/test_other_messages.py +++ b/test/test_other_messages.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test other messages. """ +"""Test other messages.""" import unittest import mock @@ -7,9 +7,10 @@ class ModbusOtherMessageTest(unittest.TestCase): - """ Unittest for the pymodbus.other_message module. """ + """Unittest for the pymodbus.other_message module.""" def setUp(self): + """Do setup.""" self.requests = [ pymodbus_message.ReadExceptionStatusRequest, pymodbus_message.GetCommEventCounterRequest, @@ -20,24 +21,24 @@ def setUp(self): self.responses = [ lambda: pymodbus_message.ReadExceptionStatusResponse(0x12), lambda: pymodbus_message.GetCommEventCounterResponse(0x12), - pymodbus_message.GetCommEventLogResponse, + pymodbus_message.GetCommEventLogResponse, lambda: pymodbus_message.ReportSlaveIdResponse(0x12), ] def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment.""" del self.requests del self.responses def test_other_messages_to_string(self): - """ Test other messages to string. """ + """Test other messages to string.""" for message in self.requests: self.assertNotEqual(str(message()), None) for message in self.responses: self.assertNotEqual(str(message()), None) def test_read_exception_status(self): - """ Test read exception status. """ + """Test read exception status.""" request = pymodbus_message.ReadExceptionStatusRequest() request.decode(b'\x12') self.assertEqual(request.encode(), b'') @@ -49,7 +50,7 @@ def test_read_exception_status(self): self.assertEqual(response.status, 0x12) def test_get_comm_event_counter(self): - """ Test get comm event counter. """ + """Test get comm event counter.""" request = pymodbus_message.GetCommEventCounterRequest() request.decode(b'\x12') self.assertEqual(request.encode(), b'') @@ -65,7 +66,7 @@ def test_get_comm_event_counter(self): self.assertEqual(response.encode(), b'\xFF\xFF\x00\x12') def test_get_comm_event_log(self): - """ Test get comm event log. """ + """Test get comm event log.""" request = pymodbus_message.GetCommEventLogRequest() request.decode(b'\x12') self.assertEqual(request.encode(), b'') @@ -83,17 +84,17 @@ def test_get_comm_event_log(self): self.assertEqual(response.encode(), b'\x06\xff\xff\x00\x12\x00\x12') def test_get_comm_event_log_with_events(self): - """ Test get comm event log with events. """ - response = pymodbus_message.GetCommEventLogResponse(events=[0x12,0x34,0x56]) + """Test get comm event log with events.""" + response = pymodbus_message.GetCommEventLogResponse(events=[0x12, 0x34, 0x56]) self.assertEqual(response.encode(), b'\x09\x00\x00\x00\x00\x00\x00\x12\x34\x56') response.decode(b'\x09\x00\x00\x00\x12\x00\x12\x12\x34\x56') self.assertEqual(response.status, True) self.assertEqual(response.message_count, 0x12) self.assertEqual(response.event_count, 0x12) - self.assertEqual(response.events, [0x12,0x34,0x56]) + self.assertEqual(response.events, [0x12, 0x34, 0x56]) def test_report_slave_id_request(self): - """ Test report slave id request. """ + """Test report slave id request.""" with mock.patch("pymodbus.other_message.DeviceInformationFactory") as dif: # First test regular identity strings identity = { @@ -133,7 +134,7 @@ def test_report_slave_id_request(self): self.assertEqual(response.identifier, expected_identity) def test_report_slave_id(self): - """ Test report slave id. """ + """Test report slave id.""" with mock.patch("pymodbus.other_message.DeviceInformationFactory") as dif: dif.get.return_value = {} request = pymodbus_message.ReportSlaveIdRequest() @@ -151,8 +152,9 @@ def test_report_slave_id(self): response.status = False self.assertEqual(response.encode(), b'\x03\x12\x00\x00') -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_payload.py b/test/test_payload.py index 9e02bc1d2..7b3d23b77 100644 --- a/test/test_payload.py +++ b/test/test_payload.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" Payload Utilities Test Fixture --------------------------------- +"""Payload Utilities Test Fixture. + This fixture tests the functionality of the payload utilities. @@ -12,45 +12,45 @@ from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadBuilder, BinaryPayloadDecoder -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class ModbusPayloadUtilityTests(unittest.TestCase): - """ Modbus payload utility tests. """ + """Modbus payload utility tests.""" # ----------------------------------------------------------------------- # # Setup/TearDown # ----------------------------------------------------------------------- # def setUp(self): - """ Initializes the test environment and builds request/result - encoding pairs - """ + """Initialize the test environment and builds request/result encoding pairs.""" self.little_endian_payload = \ - b'\x01\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00\x00' \ - b'\x00\x00\x00\xff\xfe\xff\xfd\xff\xff\xff\xfc\xff' \ - b'\xff\xff\xff\xff\xff\xff\x00\x00\xa0\x3f\x00\x00' \ - b'\x00\x00\x00\x00\x19\x40\x01\x00\x74\x65\x73\x74' \ - b'\x11' + b'\x01\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00\x00' \ + b'\x00\x00\x00\xff\xfe\xff\xfd\xff\xff\xff\xfc\xff' \ + b'\xff\xff\xff\xff\xff\xff\x00\x00\xa0\x3f\x00\x00' \ + b'\x00\x00\x00\x00\x19\x40\x01\x00\x74\x65\x73\x74' \ + b'\x11' self.big_endian_payload = \ - b'\x01\x00\x02\x00\x00\x00\x03\x00\x00\x00\x00\x00' \ - b'\x00\x00\x04\xff\xff\xfe\xff\xff\xff\xfd\xff\xff' \ - b'\xff\xff\xff\xff\xff\xfc\x3f\xa0\x00\x00\x40\x19' \ - b'\x00\x00\x00\x00\x00\x00\x00\x01\x74\x65\x73\x74' \ - b'\x11' + b'\x01\x00\x02\x00\x00\x00\x03\x00\x00\x00\x00\x00' \ + b'\x00\x00\x04\xff\xff\xfe\xff\xff\xff\xfd\xff\xff' \ + b'\xff\xff\xff\xff\xff\xfc\x3f\xa0\x00\x00\x40\x19' \ + b'\x00\x00\x00\x00\x00\x00\x00\x01\x74\x65\x73\x74' \ + b'\x11' self.bitstring = [True, False, False, False, True, False, False, False] def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" # ----------------------------------------------------------------------- # # Payload Builder Tests # ----------------------------------------------------------------------- # def test_little_endian_payload_builder(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" builder = BinaryPayloadBuilder(byteorder=Endian.Little, wordorder=Endian.Little) builder.add_8bit_uint(1) @@ -69,7 +69,7 @@ def test_little_endian_payload_builder(self): self.assertEqual(self.little_endian_payload, builder.to_string()) def test_big_endian_payload_builder(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" builder = BinaryPayloadBuilder(byteorder=Endian.Big) builder.add_8bit_uint(1) builder.add_16bit_uint(2) @@ -87,7 +87,7 @@ def test_big_endian_payload_builder(self): self.assertEqual(self.big_endian_payload, builder.to_string()) def test_payload_builder_reset(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" builder = BinaryPayloadBuilder() builder.add_8bit_uint(0x12) builder.add_8bit_uint(0x34) @@ -100,7 +100,7 @@ def test_payload_builder_reset(self): self.assertEqual([], builder.build()) def test_payload_builder_with_raw_payload(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" _coils1 = [False, False, True, True, False, True, False, False, False, False, False, True, False, False, True, False, False, True, True, True, True, False, False, False, False, True, False, @@ -130,44 +130,44 @@ def test_payload_builder_with_raw_payload(self): # ----------------------------------------------------------------------- # def test_little_endian_payload_decoder(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" decoder = BinaryPayloadDecoder(self.little_endian_payload, byteorder=Endian.Little, wordorder=Endian.Little) - self.assertEqual(1, decoder.decode_8bit_uint()) - self.assertEqual(2, decoder.decode_16bit_uint()) - self.assertEqual(3, decoder.decode_32bit_uint()) - self.assertEqual(4, decoder.decode_64bit_uint()) - self.assertEqual(-1, decoder.decode_8bit_int()) - self.assertEqual(-2, decoder.decode_16bit_int()) - self.assertEqual(-3, decoder.decode_32bit_int()) - self.assertEqual(-4, decoder.decode_64bit_int()) - self.assertEqual(1.25, decoder.decode_32bit_float()) - self.assertEqual(6.25, decoder.decode_64bit_float()) - self.assertEqual(None, decoder.skip_bytes(2)) + self.assertEqual(1, decoder.decode_8bit_uint()) + self.assertEqual(2, decoder.decode_16bit_uint()) + self.assertEqual(3, decoder.decode_32bit_uint()) + self.assertEqual(4, decoder.decode_64bit_uint()) + self.assertEqual(-1, decoder.decode_8bit_int()) + self.assertEqual(-2, decoder.decode_16bit_int()) + self.assertEqual(-3, decoder.decode_32bit_int()) + self.assertEqual(-4, decoder.decode_64bit_int()) + self.assertEqual(1.25, decoder.decode_32bit_float()) + self.assertEqual(6.25, decoder.decode_64bit_float()) + self.assertEqual(None, decoder.skip_bytes(2)) self.assertEqual('test', decoder.decode_string(4).decode()) self.assertEqual(self.bitstring, decoder.decode_bits()) def test_big_endian_payload_decoder(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" decoder = BinaryPayloadDecoder(self.big_endian_payload, byteorder=Endian.Big) - self.assertEqual(1, decoder.decode_8bit_uint()) - self.assertEqual(2, decoder.decode_16bit_uint()) - self.assertEqual(3, decoder.decode_32bit_uint()) - self.assertEqual(4, decoder.decode_64bit_uint()) - self.assertEqual(-1, decoder.decode_8bit_int()) - self.assertEqual(-2, decoder.decode_16bit_int()) - self.assertEqual(-3, decoder.decode_32bit_int()) - self.assertEqual(-4, decoder.decode_64bit_int()) - self.assertEqual(1.25, decoder.decode_32bit_float()) - self.assertEqual(6.25, decoder.decode_64bit_float()) - self.assertEqual(None, decoder.skip_bytes(2)) + self.assertEqual(1, decoder.decode_8bit_uint()) + self.assertEqual(2, decoder.decode_16bit_uint()) + self.assertEqual(3, decoder.decode_32bit_uint()) + self.assertEqual(4, decoder.decode_64bit_uint()) + self.assertEqual(-1, decoder.decode_8bit_int()) + self.assertEqual(-2, decoder.decode_16bit_int()) + self.assertEqual(-3, decoder.decode_32bit_int()) + self.assertEqual(-4, decoder.decode_64bit_int()) + self.assertEqual(1.25, decoder.decode_32bit_float()) + self.assertEqual(6.25, decoder.decode_64bit_float()) + self.assertEqual(None, decoder.skip_bytes(2)) self.assertEqual(b'test', decoder.decode_string(4)) self.assertEqual(self.bitstring, decoder.decode_bits()) def test_payload_decoder_reset(self): - """ Test the payload decoder reset functionality """ + """Test the payload decoder reset functionality""" decoder = BinaryPayloadDecoder(b'\x12\x34') self.assertEqual(0x12, decoder.decode_8bit_uint()) self.assertEqual(0x34, decoder.decode_8bit_uint()) @@ -175,7 +175,7 @@ def test_payload_decoder_reset(self): self.assertEqual(0x3412, decoder.decode_16bit_uint()) def test_payload_decoder_register_factory(self): - """ Test the payload decoder reset functionality """ + """Test the payload decoder reset functionality""" payload = [1, 2, 3, 4] decoder = BinaryPayloadDecoder.fromRegisters(payload, byteorder=Endian.Little) encoded = b'\x00\x01\x00\x02\x00\x03\x00\x04' @@ -186,10 +186,10 @@ def test_payload_decoder_register_factory(self): self.assertEqual(encoded, decoder.decode_string(8)) self.assertRaises(ParameterException, - lambda: BinaryPayloadDecoder.fromRegisters('abcd')) + lambda: BinaryPayloadDecoder.fromRegisters('abcd')) def test_payload_decoder_coil_factory(self): - """ Test the payload decoder reset functionality """ + """Test the payload decoder reset functionality""" payload = [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1] decoder = BinaryPayloadDecoder.fromCoils(payload, byteorder=Endian.Little) encoded = b'\x88\x11' @@ -200,11 +200,11 @@ def test_payload_decoder_coil_factory(self): self.assertEqual(encoded, decoder.decode_string(2)) self.assertRaises(ParameterException, - lambda: BinaryPayloadDecoder.fromCoils('abcd')) + lambda: BinaryPayloadDecoder.fromCoils('abcd')) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_pdu.py b/test/test_pdu.py index 36a551428..039415502 100644 --- a/test/test_pdu.py +++ b/test/test_pdu.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test pdu. """ +"""Test pdu.""" import unittest from pymodbus.pdu import ( ModbusResponse, @@ -12,26 +12,27 @@ NotImplementedException, ) + class SimplePduTest(unittest.TestCase): - """ Unittest for the pymod.pdu module. """ + """Unittest for the pymod.pdu module.""" def setUp(self): - """ Initializes the test environment """ + """Initialize the test environment""" self.bad_requests = ( - ModbusRequest(), - ModbusResponse(), + ModbusRequest(), + ModbusResponse(), ) self.illegal = IllegalFunctionRequest(1) - self.exception = ExceptionResponse(1,1) + self.exception = ExceptionResponse(1, 1) def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.bad_requests del self.illegal del self.exception def test_not_impelmented(self): - """ Test a base classes for not implemented functions """ + """Test a base classes for not implemented functions""" for request in self.bad_requests: self.assertRaises(NotImplementedException, request.encode) @@ -39,7 +40,7 @@ def test_not_impelmented(self): self.assertRaises(NotImplementedException, request.decode, None) def test_error_methods(self): - """ Test all error methods """ + """Test all error methods""" self.illegal.decode("12345") self.illegal.execute(None) @@ -49,40 +50,40 @@ def test_error_methods(self): self.assertEqual(self.exception.exception_code, 1) def test_request_exception_factory(self): - """ Test all error methods """ + """Test all error methods""" request = ModbusRequest() request.function_code = 1 - errors = dict((ModbusExceptions.decode(c), c) for c in range(1,20)) + errors = dict((ModbusExceptions.decode(c), c) for c in range(1, 20)) for error, code in iter(errors.items()): result = request.doException(code) self.assertEqual(str(result), f"Exception Response(129, 1, {error})") def test_calculate_rtu_frame_size(self): - """ Test the calculation of Modbus/RTU frame sizes """ + """Test the calculation of Modbus/RTU frame sizes""" self.assertRaises(NotImplementedException, ModbusRequest.calculateRtuFrameSize, b'') - ModbusRequest._rtu_frame_size = 5 # pylint: disable=protected-access + ModbusRequest._rtu_frame_size = 5 # pylint: disable=protected-access self.assertEqual(ModbusRequest.calculateRtuFrameSize(b''), 5) del ModbusRequest._rtu_frame_size - ModbusRequest._rtu_byte_count_pos = 2 # pylint: disable=protected-access + ModbusRequest._rtu_byte_count_pos = 2 # pylint: disable=protected-access self.assertEqual(ModbusRequest.calculateRtuFrameSize( b'\x11\x01\x05\xcd\x6b\xb2\x0e\x1b\x45\xe6'), 0x05 + 5) del ModbusRequest._rtu_byte_count_pos self.assertRaises(NotImplementedException, ModbusResponse.calculateRtuFrameSize, b'') - ModbusResponse._rtu_frame_size = 12 # pylint: disable=protected-access + ModbusResponse._rtu_frame_size = 12 # pylint: disable=protected-access self.assertEqual(ModbusResponse.calculateRtuFrameSize(b''), 12) del ModbusResponse._rtu_frame_size - ModbusResponse._rtu_byte_count_pos = 2 # pylint: disable=protected-access + ModbusResponse._rtu_byte_count_pos = 2 # pylint: disable=protected-access self.assertEqual(ModbusResponse.calculateRtuFrameSize( b'\x11\x01\x05\xcd\x6b\xb2\x0e\x1b\x45\xe6'), 0x05 + 5) del ModbusResponse._rtu_byte_count_pos -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_ptwisted.py b/test/test_ptwisted.py index 3df0bc822..7d04013da 100644 --- a/test/test_ptwisted.py +++ b/test/test_ptwisted.py @@ -1,22 +1,25 @@ #!/usr/bin/env python3 -""" Test ptwisted. """ +"""Test ptwisted.""" import unittest -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class TwistedInternalCodeTest(unittest.TestCase): - """ Unittest for the pymodbus.internal.ptwisted code. """ + """Unittest for the pymodbus.internal.ptwisted code.""" - #-----------------------------------------------------------------------# - # Setup/TearDown - #-----------------------------------------------------------------------# + # -----------------------------------------------------------------------# + # Setup/TearDown + # -----------------------------------------------------------------------# def test_install_conch(self): - """ Test that we can install the conch backend """ + """Test that we can install the conch backend""" + -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_register_read_messages.py b/test/test_register_read_messages.py index 98627d3b0..c3cdc101e 100644 --- a/test/test_register_read_messages.py +++ b/test/test_register_read_messages.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test register read messages. """ +"""Test register read messages.""" import unittest from pymodbus.register_read_message import ( @@ -16,12 +16,14 @@ from .modbus_mocks import MockContext, FakeList -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class ReadRegisterMessagesTest(unittest.TestCase): - """ Register Message Test Fixture - -------------------------------- + """Register Message Test Fixture. + This fixture tests the functionality of all the register based request/response messages: @@ -30,130 +32,131 @@ class ReadRegisterMessagesTest(unittest.TestCase): """ def setUp(self): - """ Initializes the test environment and builds request/result - encoding pairs - """ + """Initialize the test environment and builds request/result encoding pairs.""" arguments = { - 'read_address': 1, 'read_count': 5, - 'write_address': 1, 'write_registers': [0x00]*5, + 'read_address': 1, 'read_count': 5, + 'write_address': 1, 'write_registers': [0x00] * 5, } - self.value = 0xabcd + self.value = 0xabcd self.values = [0xa, 0xb, 0xc] - self.request_read = { - ReadRegistersRequestBase(1, 5) :b'\x00\x01\x00\x05', - ReadHoldingRegistersRequest(1, 5) :b'\x00\x01\x00\x05', - ReadInputRegistersRequest(1,5) :b'\x00\x01\x00\x05', - ReadWriteMultipleRegistersRequest(**arguments) :b'\x00\x01\x00\x05\x00\x01\x00' - b'\x05\x0a\x00\x00\x00\x00\x00' - b'\x00\x00\x00\x00\x00', + self.request_read = { + ReadRegistersRequestBase(1, 5): b'\x00\x01\x00\x05', + ReadHoldingRegistersRequest(1, 5): b'\x00\x01\x00\x05', + ReadInputRegistersRequest(1, 5): b'\x00\x01\x00\x05', + ReadWriteMultipleRegistersRequest(**arguments): b'\x00\x01\x00\x05\x00\x01\x00' + b'\x05\x0a\x00\x00\x00\x00\x00' + b'\x00\x00\x00\x00\x00', } - self.response_read = { - ReadRegistersResponseBase(self.values) :b'\x06\x00\x0a\x00\x0b\x00\x0c', - ReadHoldingRegistersResponse(self.values) :b'\x06\x00\x0a\x00\x0b\x00\x0c', - ReadInputRegistersResponse(self.values) :b'\x06\x00\x0a\x00\x0b\x00\x0c', - ReadWriteMultipleRegistersResponse(self.values) :b'\x06\x00\x0a\x00\x0b\x00\x0c', + self.response_read = { + ReadRegistersResponseBase(self.values): b'\x06\x00\x0a\x00\x0b\x00\x0c', + ReadHoldingRegistersResponse(self.values): b'\x06\x00\x0a\x00\x0b\x00\x0c', + ReadInputRegistersResponse(self.values): b'\x06\x00\x0a\x00\x0b\x00\x0c', + ReadWriteMultipleRegistersResponse(self.values): b'\x06\x00\x0a\x00\x0b\x00\x0c', } def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment.""" del self.request_read del self.response_read def test_read_register_response_base(self): - """ Test read register response. """ + """Test read register response.""" response = ReadRegistersResponseBase(list(range(10))) for index in range(10): self.assertEqual(response.getRegister(index), index) def test_register_read_requests(self): - """ Test register read requests. """ + """Test register read requests.""" for request, response in iter(self.request_read.items()): self.assertEqual(request.encode(), response) def test_register_read_responses(self): - """ Test register read response. """ + """Test register read response.""" for request, response in iter(self.response_read.items()): self.assertEqual(request.encode(), response) def test_register_read_response_decode(self): - """ Test register read response. """ + """Test register read response.""" registers = [ - [0x0a,0x0b,0x0c], - [0x0a,0x0b,0x0c], - [0x0a,0x0b,0x0c], - [0x0a,0x0b,0x0c, 0x0a,0x0b,0x0c], + [0x0a, 0x0b, 0x0c], + [0x0a, 0x0b, 0x0c], + [0x0a, 0x0b, 0x0c], + [0x0a, 0x0b, 0x0c, 0x0a, 0x0b, 0x0c], ] - values = sorted(self.response_read.items(), key=lambda x: str(x)) # pylint: disable=unnecessary-lambda + values = sorted(self.response_read.items(), key=lambda x: str(x)) # pylint: disable=unnecessary-lambda for packet, register in zip(values, registers): request, response = packet request.decode(response) self.assertEqual(request.registers, register) def test_register_read_requests_count_errors(self): - """ This tests that the register request messages + """This tests that the register request messages. + will break on counts that are out of range """ mock = FakeList(0x800) requests = [ ReadHoldingRegistersRequest(1, 0x800), - ReadInputRegistersRequest(1,0x800), + ReadInputRegistersRequest(1, 0x800), ReadWriteMultipleRegistersRequest(read_address=1, - read_count=0x800, write_address=1, write_registers=5), + read_count=0x800, write_address=1, write_registers=5), ReadWriteMultipleRegistersRequest(read_address=1, - read_count=5, write_address=1, write_registers=mock), + read_count=5, write_address=1, write_registers=mock), ] for request in requests: result = request.execute(None) self.assertEqual(ModbusExceptions.IllegalValue, - result.exception_code) + result.exception_code) def test_register_read_requests_validate_errors(self): - """ This tests that the register request messages + """This tests that the register request messages. + will break on counts that are out of range """ context = MockContext() requests = [ ReadHoldingRegistersRequest(-1, 5), - ReadInputRegistersRequest(-1,5), - #ReadWriteMultipleRegistersRequest(-1,5,1,5), - #ReadWriteMultipleRegistersRequest(1,5,-1,5), + ReadInputRegistersRequest(-1, 5), + # ReadWriteMultipleRegistersRequest(-1,5,1,5), + # ReadWriteMultipleRegistersRequest(1,5,-1,5), ] for request in requests: result = request.execute(context) self.assertEqual(ModbusExceptions.IllegalAddress, - result.exception_code) + result.exception_code) def test_register_read_requests_execute(self): - """ This tests that the register request messages + """This tests that the register request messages. + will break on counts that are out of range """ context = MockContext(True) requests = [ ReadHoldingRegistersRequest(-1, 5), - ReadInputRegistersRequest(-1,5), + ReadInputRegistersRequest(-1, 5), ] for request in requests: response = request.execute(context) self.assertEqual(request.function_code, response.function_code) def test_read_write_multiple_registers_request(self): - """ Test read/write multiple registers. """ + """Test read/write multiple registers.""" context = MockContext(True) request = ReadWriteMultipleRegistersRequest(read_address=1, - read_count=10, write_address=1, write_registers=[0x00]) + read_count=10, write_address=1, write_registers=[0x00]) response = request.execute(context) self.assertEqual(request.function_code, response.function_code) def test_read_write_multiple_registers_validate(self): - """ Test read/write multiple registers. """ + """Test read/write multiple registers.""" context = MockContext() - context.validate = lambda f,a,c: a == 1 + context.validate = lambda f, a, c: a == 1 request = ReadWriteMultipleRegistersRequest(read_address=1, - read_count=10, write_address=2, write_registers=[0x00]) + read_count=10, write_address=2, write_registers=[0x00]) response = request.execute(context) self.assertEqual(response.exception_code, ModbusExceptions.IllegalAddress) - context.validate = lambda f,a,c: a == 2 + context.validate = lambda f, a, c: a == 2 response = request.execute(context) self.assertEqual(response.exception_code, ModbusExceptions.IllegalAddress) @@ -162,26 +165,27 @@ def test_read_write_multiple_registers_validate(self): self.assertEqual(response.exception_code, ModbusExceptions.IllegalValue) def test_read_write_multiple_registers_request_decode(self): - """ Test read/write multiple registers. """ - request, response = next((k,v) for k,v in self.request_read.items() - if getattr(k, 'function_code', 0) == 23) + """Test read/write multiple registers.""" + request, response = next((k, v) for k, v in self.request_read.items() + if getattr(k, 'function_code', 0) == 23) request.decode(response) self.assertEqual(request.read_address, 0x01) self.assertEqual(request.write_address, 0x01) self.assertEqual(request.read_count, 0x05) self.assertEqual(request.write_count, 0x05) self.assertEqual(request.write_byte_count, 0x0a) - self.assertEqual(request.write_registers, [0x00]*5) + self.assertEqual(request.write_registers, [0x00] * 5) def test_serializing_to_string(self): - """ Test serializing to string. """ + """Test serializing to string.""" for request in iter(self.request_read.keys()): - self.assertTrue(str(request) is not None) #NOSONAR + self.assertTrue(str(request) is not None) # NOSONAR for request in iter(self.response_read.keys()): - self.assertTrue(str(request) is not None) #NOSONAR + self.assertTrue(str(request) is not None) # NOSONAR + -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_register_write_messages.py b/test/test_register_write_messages.py index c07534540..4742e1dd7 100644 --- a/test/test_register_write_messages.py +++ b/test/test_register_write_messages.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test register write messages. """ +"""Test register write messages.""" import unittest from pymodbus.register_write_message import ( MaskWriteRegisterRequest, @@ -15,12 +15,14 @@ from .modbus_mocks import MockContext -#---------------------------------------------------------------------------# -# Fixture -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Fixture +# ---------------------------------------------------------------------------# + + class WriteRegisterMessagesTest(unittest.TestCase): - """ Register Message Test Fixture - -------------------------------- + """Register Message Test Fixture. + This fixture tests the functionality of all the register based request/response messages: @@ -29,60 +31,58 @@ class WriteRegisterMessagesTest(unittest.TestCase): """ def setUp(self): - """ Initializes the test environment and builds request/result - encoding pairs - """ - self.value = 0xabcd + """Initialize the test environment and builds request/result encoding pairs.""" + self.value = 0xabcd self.values = [0xa, 0xb, 0xc] builder = BinaryPayloadBuilder(byteorder=Endian.Big) builder.add_16bit_uint(0x1234) self.payload = builder.build() - self.write = { - WriteSingleRegisterRequest(1, self.value) : + self.write = { + WriteSingleRegisterRequest(1, self.value): b'\x00\x01\xab\xcd', - WriteSingleRegisterResponse(1, self.value) : + WriteSingleRegisterResponse(1, self.value): b'\x00\x01\xab\xcd', - WriteMultipleRegistersRequest(1, self.values) : + WriteMultipleRegistersRequest(1, self.values): b'\x00\x01\x00\x03\x06\x00\n\x00\x0b\x00\x0c', - WriteMultipleRegistersResponse(1, 5) : + WriteMultipleRegistersResponse(1, 5): b'\x00\x01\x00\x05', WriteSingleRegisterRequest(1, self.payload[0], - skip_encode=True): b'\x00\x01\x12\x34', + skip_encode=True): b'\x00\x01\x12\x34', WriteMultipleRegistersRequest(1, self.payload, - skip_encode=True): b'\x00\x01\x00\x01\x02\x12\x34', + skip_encode=True): b'\x00\x01\x00\x01\x02\x12\x34', } def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.write def test_register_write_requests_encode(self): - """ Test register write requests encode. """ + """Test register write requests encode.""" for request, response in iter(self.write.items()): self.assertEqual(request.encode(), response) def test_register_write_requests_decode(self): - """ Test register write requests decode. """ - addresses = [1,1,1,1] - values = sorted(self.write.items(), key=lambda x: str(x)) # pylint: disable=unnecessary-lambda + """Test register write requests decode.""" + addresses = [1, 1, 1, 1] + values = sorted(self.write.items(), key=lambda x: str(x)) # pylint: disable=unnecessary-lambda for packet, address in zip(values, addresses): request, response = packet request.decode(response) self.assertEqual(request.address, address) def test_invalid_write_multiple_registers_request(self): - """ Test invalid write multiple registers request. """ + """Test invalid write multiple registers request.""" request = WriteMultipleRegistersRequest(0, None) self.assertEqual(request.values, []) def test_serializing_to_string(self): - """ Test serializing to string. """ + """Test serializing to string.""" for request in iter(self.write.keys()): - self.assertTrue(str(request) is not None) #NOSONAR + self.assertTrue(str(request) is not None) # NOSONAR def test_write_single_register_request(self): - """ Test write single register request. """ + """Test write single register request.""" context = MockContext() request = WriteSingleRegisterRequest(0x00, 0xf0000) result = request.execute(context) @@ -97,22 +97,22 @@ def test_write_single_register_request(self): self.assertEqual(result.function_code, request.function_code) def test_write_multiple_register_request(self): - """ test write multiple register request. """ + """Test write multiple register request.""" context = MockContext() - request = WriteMultipleRegistersRequest(0x00, [0x00]*10) + request = WriteMultipleRegistersRequest(0x00, [0x00] * 10) result = request.execute(context) self.assertEqual(result.exception_code, ModbusExceptions.IllegalAddress) - request.count = 0x05 # bytecode != code * 2 + request.count = 0x05 # bytecode != code * 2 result = request.execute(context) self.assertEqual(result.exception_code, ModbusExceptions.IllegalValue) - request.count = 0x800 # outside of range + request.count = 0x800 # outside of range result = request.execute(context) self.assertEqual(result.exception_code, ModbusExceptions.IllegalValue) context.valid = True - request = WriteMultipleRegistersRequest(0x00, [0x00]*10) + request = WriteMultipleRegistersRequest(0x00, [0x00] * 10) result = request.execute(context) self.assertEqual(result.function_code, request.function_code) @@ -121,13 +121,13 @@ def test_write_multiple_register_request(self): # -----------------------------------------------------------------------# def test_mask_write_register_request_encode(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" handle = MaskWriteRegisterRequest(0x0000, 0x0101, 0x1010) result = handle.encode() self.assertEqual(result, b'\x00\x00\x01\x01\x10\x10') def test_mask_write_register_request_decode(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" request = b'\x00\x04\x00\xf2\x00\x25' handle = MaskWriteRegisterRequest() handle.decode(request) @@ -136,14 +136,14 @@ def test_mask_write_register_request_decode(self): self.assertEqual(handle.or_mask, 0x0025) def test_mask_write_register_request_execute(self): - """ Test write register request valid execution """ + """Test write register request valid execution""" context = MockContext(valid=True, default=0x0000) handle = MaskWriteRegisterRequest(0x0000, 0x0101, 0x1010) result = handle.execute(context) self.assertTrue(isinstance(result, MaskWriteRegisterResponse)) def test_mask_write_register_request_invalid_execute(self): - """ Test write register request execute with invalid data """ + """Test write register request execute with invalid data""" context = MockContext(valid=False, default=0x0000) handle = MaskWriteRegisterRequest(0x0000, -1, 0x1010) result = handle.execute(context) @@ -165,13 +165,13 @@ def test_mask_write_register_request_invalid_execute(self): # -----------------------------------------------------------------------# def test_mask_write_register_response_encode(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" handle = MaskWriteRegisterResponse(0x0000, 0x0101, 0x1010) result = handle.encode() self.assertEqual(result, b'\x00\x00\x01\x01\x10\x10') def test_mask_write_register_response_decode(self): - """ Test basic bit message encoding/decoding """ + """Test basic bit message encoding/decoding""" request = b'\x00\x04\x00\xf2\x00\x25' handle = MaskWriteRegisterResponse() handle.decode(request) @@ -180,9 +180,8 @@ def test_mask_write_register_response_decode(self): self.assertEqual(handle.or_mask, 0x0025) - -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_remote_datastore.py b/test/test_remote_datastore.py index c73a91be6..996cb4330 100644 --- a/test/test_remote_datastore.py +++ b/test/test_remote_datastore.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test remote datastore. """ +"""Test remote datastore.""" import unittest from pymodbus.exceptions import NotImplementedException from pymodbus.datastore.remote import RemoteSlaveContext @@ -9,59 +9,61 @@ from pymodbus.pdu import ExceptionResponse from .modbus_mocks import mock + class RemoteModbusDataStoreTest(unittest.TestCase): - """ Unittest for the pymodbus.datastore.remote module. """ + """Unittest for the pymodbus.datastore.remote module.""" def test_remote_slave_context(self): - """ Test a modbus remote slave context """ + """Test a modbus remote slave context""" context = RemoteSlaveContext(None) self.assertNotEqual(str(context), None) - self.assertRaises(NotImplementedException, lambda: context.reset()) # pylint: disable=unnecessary-lambda + self.assertRaises(NotImplementedException, lambda: context.reset()) # pylint: disable=unnecessary-lambda - def test_remote_slave_set_values(self): # pylint: disable=no-self-use - """ Test setting values against a remote slave context """ - client = mock() - client.write_coils = lambda a,b: WriteMultipleCoilsResponse() + def test_remote_slave_set_values(self): # pylint: disable=no-self-use + """Test setting values against a remote slave context""" + client = mock() + client.write_coils = lambda a, b: WriteMultipleCoilsResponse() context = RemoteSlaveContext(client) context.setValues(1, 0, [1]) def test_remote_slave_get_values(self): - """ Test getting values from a remote slave context """ - client = mock() - client.read_coils = lambda a,b: ReadCoilsResponse([1]*10) - client.read_input_registers = lambda a,b: ReadInputRegistersResponse([10]*10) - client.read_holding_registers = lambda a,b: ExceptionResponse(0x15) + """Test getting values from a remote slave context""" + client = mock() + client.read_coils = lambda a, b: ReadCoilsResponse([1] * 10) + client.read_input_registers = lambda a, b: ReadInputRegistersResponse([10] * 10) + client.read_holding_registers = lambda a, b: ExceptionResponse(0x15) context = RemoteSlaveContext(client) - result = context.getValues(1, 0, 10) - self.assertEqual(result, [1]*10) + result = context.getValues(1, 0, 10) + self.assertEqual(result, [1] * 10) - result = context.getValues(4, 0, 10) - self.assertEqual(result, [10]*10) + result = context.getValues(4, 0, 10) + self.assertEqual(result, [10] * 10) - result = context.getValues(3, 0, 10) - self.assertNotEqual(result, [10]*10) + result = context.getValues(3, 0, 10) + self.assertNotEqual(result, [10] * 10) def test_remote_slave_validate_values(self): - """ Test validating against a remote slave context """ - client = mock() - client.read_coils = lambda a,b: ReadCoilsResponse([1]*10) - client.read_input_registers = lambda a,b: ReadInputRegistersResponse([10]*10) - client.read_holding_registers = lambda a,b: ExceptionResponse(0x15) + """Test validating against a remote slave context""" + client = mock() + client.read_coils = lambda a, b: ReadCoilsResponse([1] * 10) + client.read_input_registers = lambda a, b: ReadInputRegistersResponse([10] * 10) + client.read_holding_registers = lambda a, b: ExceptionResponse(0x15) context = RemoteSlaveContext(client) - result = context.validate(1, 0, 10) + result = context.validate(1, 0, 10) self.assertTrue(result) - result = context.validate(4, 0, 10) + result = context.validate(4, 0, 10) self.assertTrue(result) - result = context.validate(3, 0, 10) + result = context.validate(3, 0, 10) self.assertFalse(result) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_server_async.py b/test/test_server_async.py index ce51bb49e..0ed1bf036 100644 --- a/test/test_server_async.py +++ b/test/test_server_async.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test server async. """ +"""Test server async.""" import sys import platform from threading import Thread @@ -33,25 +33,24 @@ class AsynchronousServerTest(unittest.TestCase): - """ Unittest for the pymodbus.server.asynchronous module. """ + """Unittest for the pymodbus.server.asynchronous module.""" # ----------------------------------------------------------------------- # # Setup/TearDown # ----------------------------------------------------------------------- # def setUp(self): - """ Initializes the test environment. """ + """Initialize the test environment.""" values = dict((i, '') for i in range(10)) ModbusDeviceIdentification(info=values) def tearDown(self): - """ Cleans up the test environment """ - + """Clean up the test environment""" # ----------------------------------------------------------------------- # # Test ModbusTcpProtocol # ----------------------------------------------------------------------- # def test_tcp_server_startup(self): - """ Test that the modbus tcp asynchronous server starts correctly """ + """Test that the modbus tcp asynchronous server starts correctly""" with patch('twisted.internet.reactor') as mock_reactor: console = False call_count = 1 @@ -60,7 +59,7 @@ def test_tcp_server_startup(self): self.assertEqual(mock_reactor.run.call_count, 1) def test_connection_made(self): - """ Test connection made. """ + """Test connection made.""" protocol = ModbusTcpProtocol() protocol.transport = MagicMock() protocol.factory = MagicMock() @@ -68,13 +67,13 @@ def test_connection_made(self): protocol.connectionMade() self.assertIsInstance(protocol.framer, ModbusSocketFramer) - def test_connection_lost(self): # pylint: disable=no-self-use - """ Test connection lost. """ + def test_connection_lost(self): # pylint: disable=no-self-use + """Test connection lost.""" protocol = ModbusTcpProtocol() protocol.connectionLost("What ever reason") def test_data_received(self): - """ Test data received. """ + """Test data received.""" protocol = ModbusTcpProtocol() # mock_data = "Hello world!" mock_data = b"\x00\x01\x12\x34\x00\x04\xff\x02\x12\x34" @@ -93,46 +92,47 @@ def test_data_received(self): self.assertEqual(protocol.dataReceived(mock_data), None) def test_tcp_execute_success(self): - """ Test tcp execute. """ + """Test tcp execute.""" protocol = ModbusTcpProtocol() protocol.store = MagicMock() request = MagicMock() - protocol._send = MagicMock() # pylint: disable=protected-access + protocol._send = MagicMock() # pylint: disable=protected-access # test if _send being called - protocol._execute(request) # pylint: disable=protected-access - self.assertTrue(protocol._send.called) # pylint: disable=protected-access + protocol._execute(request) # pylint: disable=protected-access + self.assertTrue(protocol._send.called) # pylint: disable=protected-access def test_tcp_execute_failure(self): - """ Test tcp execute. """ + """Test tcp execute.""" protocol = ModbusTcpProtocol() protocol.factory = MagicMock() protocol.factory.store = MagicMock() protocol.store = MagicMock() protocol.factory.ignore_missing_slaves = False request = MagicMock() - protocol._send = MagicMock() # pylint: disable=protected-access + protocol._send = MagicMock() # pylint: disable=protected-access # CASE-1: test NoSuchSlaveException exceptions request.execute.side_effect = NoSuchSlaveException() - protocol._execute(request) # pylint: disable=protected-access + protocol._execute(request) # pylint: disable=protected-access self.assertTrue(request.doException.called) # CASE-2: NoSuchSlaveException with ignore_missing_slaves = true protocol.ignore_missing_slaves = True request.execute.side_effect = NoSuchSlaveException() - self.assertEqual(protocol._execute(request), None) # pylint: disable=protected-access + self.assertEqual(protocol._execute(request), None) # pylint: disable=protected-access # test other exceptions request.execute.side_effect = ModbusIOException() - protocol._execute(request) # pylint: disable=protected-access - self.assertTrue(protocol._send.called) # pylint: disable=protected-access + protocol._execute(request) # pylint: disable=protected-access + self.assertTrue(protocol._send.called) # pylint: disable=protected-access def test_send_tcp(self): - """ Test send tcp. """ + """Test send tcp.""" + + class MockMsg: # pylint: disable=too-few-public-methods + """Mock message.""" - class MockMsg: # pylint: disable=too-few-public-methods - """ Mock message. """ def __init__(self, msg, resp=False): self.should_respond = resp self.msg = msg @@ -147,19 +147,19 @@ def __init__(self, msg, resp=False): protocol.framer.buildPacket = MagicMock(return_value=mock_msg) protocol.transport = MagicMock() - protocol._send(mock_data) # pylint: disable=protected-access + protocol._send(mock_data) # pylint: disable=protected-access self.assertTrue(protocol.framer.buildPacket.called) self.assertTrue(protocol.transport.write.called) mock_data = MockMsg(resp=False, msg="helloworld") - self.assertEqual(protocol._send(mock_data), None) # pylint: disable=protected-access + self.assertEqual(protocol._send(mock_data), None) # pylint: disable=protected-access # ----------------------------------------------------------------------- # # Test ModbusServerFactory # ----------------------------------------------------------------------- # def test_modbus_server_factory(self): - """ Test the base class for all the clients """ + """Test the base class for all the clients""" factory = ModbusServerFactory(store=None) self.assertEqual(factory.control.Identity.VendorName, '') @@ -171,7 +171,7 @@ def test_modbus_server_factory(self): # Test ModbusUdpProtocol # ----------------------------------------------------------------------- # def test_udp_server_initialize(self): - """ Test UDP server. """ + """Test UDP server.""" protocol = ModbusUdpProtocol(store=None) self.assertEqual(protocol.control.Identity.VendorName, '') @@ -180,7 +180,7 @@ def test_udp_server_initialize(self): self.assertEqual(protocol.control.Identity.VendorName, 'VendorName') def test_udp_server_startup(self): - """ Test that the modbus udp asynchronous server starts correctly """ + """Test that the modbus udp asynchronous server starts correctly""" with patch('twisted.internet.reactor') as mock_reactor: StartUdpServer(context=None) self.assertEqual(mock_reactor.listenUDP.call_count, 1) @@ -188,16 +188,16 @@ def test_udp_server_startup(self): @no_twisted_serial_on_windows_with_pypy @patch("twisted.internet.serialport.SerialPort") - def test_serial_server_startup(self, mock_sp): # pylint: disable=unused-argument - """ Test that the modbus serial asynchronous server starts correctly """ + def test_serial_server_startup(self, mock_sp): # pylint: disable=unused-argument + """Test that the modbus serial asynchronous server starts correctly""" with patch('twisted.internet.reactor') as mock_reactor: StartSerialServer(context=None, port=pytest.SERIAL_PORT) self.assertEqual(mock_reactor.run.call_count, 1) @no_twisted_serial_on_windows_with_pypy @patch("twisted.internet.serialport.SerialPort") - def test_stop_server_from_main_thread(self, mock_sp): # pylint: disable=unused-argument - """ Stop asynchronous server. """ + def test_stop_server_from_main_thread(self, mock_sp): # pylint: disable=unused-argument + """Stop asynchronous server.""" with patch('twisted.internet.reactor') as mock_reactor: StartSerialServer(context=None, port=pytest.SERIAL_PORT) self.assertEqual(mock_reactor.run.call_count, 1) @@ -206,8 +206,8 @@ def test_stop_server_from_main_thread(self, mock_sp): # pylint: disable=unused-a @no_twisted_serial_on_windows_with_pypy @patch("twisted.internet.serialport.SerialPort") - def test_stop_server_from_thread(self, mock_sp): # pylint: disable=unused-argument - """ Stop asynchronous server from child thread. """ + def test_stop_server_from_thread(self, mock_sp): # pylint: disable=unused-argument + """Stop asynchronous server from child thread.""" with patch('twisted.internet.reactor') as mock_reactor: StartSerialServer(context=None, port=pytest.SERIAL_PORT) self.assertEqual(mock_reactor.run.call_count, 1) @@ -217,19 +217,19 @@ def test_stop_server_from_thread(self, mock_sp): # pylint: disable=unused-argume self.assertEqual(mock_reactor.callFromThread.call_count, 1) def test_datagram_received(self): - """ Test datagram received. """ + """Test datagram received.""" mock_data = b"\x00\x01\x12\x34\x00\x04\xff\x02\x12\x34" mock_addr = 0x01 protocol = ModbusUdpProtocol(store=None) protocol.framer.processIncomingPacket = MagicMock() protocol.control.ListenOnly = False - protocol._execute = MagicMock() # pylint: disable=protected-access + protocol._execute = MagicMock() # pylint: disable=protected-access protocol.datagramReceived(mock_data, mock_addr) self.assertTrue(protocol.framer.processIncomingPacket.called) def test_send_udp(self): - """ Test send UDP. """ + """Test send UDP.""" protocol = ModbusUdpProtocol(store=None) mock_data = b"\x00\x01\x12\x34\x00\x04\xff\x02\x12\x34" mock_addr = 0x01 @@ -239,56 +239,56 @@ def test_send_udp(self): protocol.framer.buildPacket = MagicMock(return_value=mock_data) protocol.transport = MagicMock() - protocol._send(mock_data, mock_addr) # pylint: disable=protected-access + protocol._send(mock_data, mock_addr) # pylint: disable=protected-access self.assertTrue(protocol.framer.buildPacket.called) self.assertTrue(protocol.transport.write.called) def test_udp_execute_success(self): - """ Test UDP execute success. """ + """Test UDP execute success.""" protocol = ModbusUdpProtocol(store=None) mock_addr = 0x01 protocol.store = MagicMock() request = MagicMock() - protocol._send = MagicMock() # pylint: disable=protected-access + protocol._send = MagicMock() # pylint: disable=protected-access # test if _send being called - protocol._execute(request, mock_addr) # pylint: disable=protected-access - self.assertTrue(protocol._send.called) # pylint: disable=protected-access + protocol._execute(request, mock_addr) # pylint: disable=protected-access + self.assertTrue(protocol._send.called) # pylint: disable=protected-access def test_udp_execute_failure(self): - """ Test UDP execute failure. """ + """Test UDP execute failure.""" protocol = ModbusUdpProtocol(store=None) mock_addr = 0x01 protocol.store = MagicMock() request = MagicMock() - protocol._send = MagicMock() # pylint: disable=protected-access + protocol._send = MagicMock() # pylint: disable=protected-access # CASE-1: test NoSuchSlaveException exceptions request.execute.side_effect = NoSuchSlaveException() - protocol._execute(request, mock_addr) # pylint: disable=protected-access + protocol._execute(request, mock_addr) # pylint: disable=protected-access self.assertTrue(request.doException.called) # CASE-2: NoSuchSlaveException with ignore_missing_slaves = true protocol.ignore_missing_slaves = True request.execute.side_effect = NoSuchSlaveException() - self.assertEqual(protocol._execute(request, mock_addr), None) # pylint: disable=protected-access + self.assertEqual(protocol._execute(request, mock_addr), None) # pylint: disable=protected-access # test other exceptions request.execute.side_effect = ModbusIOException() - protocol._execute(request, mock_addr) # pylint: disable=protected-access - self.assertTrue(protocol._send.called) # pylint: disable=protected-access + protocol._execute(request, mock_addr) # pylint: disable=protected-access + self.assertTrue(protocol._send.called) # pylint: disable=protected-access def test_stop_server(self): - """ Test stop server. """ - from twisted.internet import reactor # pylint: disable=import-outside-toplevel + """Test stop server.""" + from twisted.internet import reactor # pylint: disable=import-outside-toplevel reactor.stop = MagicMock() StopServer() self.assertTrue(reactor.stop.called) def test_is_main_thread(self): - """ Test is main thread. """ + """Test is main thread.""" self.assertTrue(_is_main_thread()) diff --git a/test/test_server_asyncio.py b/test/test_server_asyncio.py index bebb7a6e1..586abef95 100755 --- a/test/test_server_asyncio.py +++ b/test/test_server_asyncio.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test server asyncio. """ +"""Test server asyncio.""" import logging import asyncio import time @@ -26,8 +26,8 @@ _logger = logging.getLogger() -class AsyncioServerTest(asynctest.TestCase): # pylint: disable=too-many-public-methods - """ Unittest for the pymodbus.server.asyncio module. +class AsyncioServerTest(asynctest.TestCase): # pylint: disable=too-many-public-methods + """Unittest for the pymodbus.server.asyncio module. The scope of this unit test is the life-cycle management of the network connections and server objects. @@ -36,10 +36,10 @@ class AsyncioServerTest(asynctest.TestCase): # pylint: disable=too-many-public-m """ # -----------------------------------------------------------------------# - # Setup/TearDown + # Setup/TearDown # -----------------------------------------------------------------------# def setUp(self): - """ Initialize the test environment by setting up a dummy store and context. """ + """Initialize the test environment by setting up a dummy store and context.""" self.store = ModbusSlaveContext(di=ModbusSequentialDataBlock(0, [17] * 100), co=ModbusSequentialDataBlock(0, [17] * 100), hr=ModbusSequentialDataBlock(0, [17] * 100), @@ -47,31 +47,31 @@ def setUp(self): self.context = ModbusServerContext(slaves=self.store, single=True) def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" # -----------------------------------------------------------------------# - # Test ModbusConnectedRequestHandler - #-----------------------------------------------------------------------# + # Test ModbusConnectedRequestHandler + # -----------------------------------------------------------------------# async def test_start_tcp_server(self): - """ Test that the modbus tcp asyncio server starts correctly """ + """Test that the modbus tcp asyncio server starts correctly""" identity = ModbusDeviceIdentification(info_name={'VendorName': 'VendorName'}) - self.loop = asynctest.Mock(self.loop) # pylint: disable=attribute-defined-outside-init - server = await StartTcpServer(context=self.context,loop=self.loop,identity=identity) + self.loop = asynctest.Mock(self.loop) # pylint: disable=attribute-defined-outside-init + server = await StartTcpServer(context=self.context, loop=self.loop, identity=identity) self.assertEqual(server.control.Identity.VendorName, 'VendorName') self.loop.create_server.assert_called_once() async def test_tcp_server_serve_no_defer(self): - """ Test StartTcpServer without deferred start (immediate execution of server) """ - with patch('asyncio.base_events.Server.serve_forever', #NOSONAR - new_callable=asynctest.CoroutineMock) as serve: - await StartTcpServer(context=self.context,address=("127.0.0.1", - 0), loop=self.loop, defer_start=False) + """Test StartTcpServer without deferred start (immediate execution of server)""" + with patch('asyncio.base_events.Server.serve_forever', # NOSONAR + new_callable=asynctest.CoroutineMock) as serve: + await StartTcpServer(context=self.context, address=("127.0.0.1", + 0), loop=self.loop, defer_start=False) serve.assert_awaited() async def test_tcp_server_serve_forever_twice(self): - """ Call on serve_forever() twice should result in a runtime error """ - server = await StartTcpServer(context=self.context,address=("127.0.0.1", 0), loop=self.loop) + """Call on serve_forever() twice should result in a runtime error""" + server = await StartTcpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving with self.assertRaises(RuntimeError): @@ -80,48 +80,48 @@ async def test_tcp_server_serve_forever_twice(self): server.server_close() async def test_tcp_server_receive_data(self): - """ Test data sent on socket is received by internals - doesn't not process data """ + """Test data sent on socket is received by internals - doesn't not process data""" data = b'\x01\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\x19' - server = await StartTcpServer(context=self.context,address=("127.0.0.1", 0),loop=self.loop) + server = await StartTcpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving - with patch('pymodbus.transaction.ModbusSocketFramer.processIncomingPacket', #NOSONAR - new_callable=Mock) as process: + with patch('pymodbus.transaction.ModbusSocketFramer.processIncomingPacket', # NOSONAR + new_callable=Mock) as process: # process = server.framer.processIncomingPacket = Mock() connected = self.loop.create_future() random_port = server.server.sockets[0].getsockname()[1] # get the random server port class BasicClient(asyncio.BaseProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - """ Connection made. """ - self.transport = transport # pylint: disable=attribute-defined-outside-init + """Get Connection made.""" + self.transport = transport # pylint: disable=attribute-defined-outside-init self.transport.write(data) connected.set_result(True) def eof_received(self): - """ EOF received. """ + """EOF received.""" - await self.loop.create_connection(BasicClient, host='127.0.0.1',port=random_port) - await asyncio.sleep(0.1) # this may be better done + await self.loop.create_connection(BasicClient, host='127.0.0.1', port=random_port) + await asyncio.sleep(0.1) # this may be better done # by making an internal hook in the actual implementation # if this unit test fails on a machine, # see if increasing the sleep time makes a difference, # if it does blame author for a fix process.assert_called_once() - self.assertTrue( process.call_args[1]["data"] == data ) + self.assertTrue(process.call_args[1]["data"] == data) server.server_close() @pytest.mark.skipif(pytest.IS_WINDOWS, reason="To fix") async def test_tcp_server_roundtrip(self): - """ Test sending and receiving data on tcp socket """ - data = b"\x01\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\x01" # unit 1, read register + """Test sending and receiving data on tcp socket""" + data = b"\x01\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\x01" # unit 1, read register expected_response = b'\x01\x00\x00\x00\x00\x05\x01\x03\x02\x00\x11' - # value of 17 as per context - server = await StartTcpServer(context=self.context,address=("127.0.0.1", 0),loop=self.loop) + # value of 17 as per context + server = await StartTcpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving random_port = server.server.sockets[0].getsockname()[1] # get the random server port @@ -129,25 +129,25 @@ async def test_tcp_server_roundtrip(self): received_value = None class BasicClient(asyncio.BaseProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - """ Connection made. """ - self.transport = transport # pylint: disable=attribute-defined-outside-init + """Get Connection made.""" + self.transport = transport # pylint: disable=attribute-defined-outside-init self.transport.write(data) connected.set_result(True) - def data_received(self, data): # pylint: disable=no-self-use - """ Data received. """ + def data_received(self, data): # pylint: disable=no-self-use + """Get Data received.""" nonlocal received_value, done received_value = data done.set_result(True) def eof_received(self): - """ EOF received. """ + """EOF received.""" transport, _ = await self.loop.create_connection(BasicClient, - host='127.0.0.1', port=random_port) + host='127.0.0.1', port=random_port) await asyncio.wait_for(done, timeout=0.1) self.assertEqual(received_value, expected_response) @@ -158,10 +158,9 @@ def eof_received(self): @pytest.mark.skipif(pytest.IS_WINDOWS, reason="To fix") async def test_tcp_server_connection_lost(self): - """ Test tcp stream interruption """ - + """Test tcp stream interruption""" server = await StartTcpServer(context=self.context, - address=("127.0.0.1", 0), loop=self.loop) + address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving random_port = server.server.sockets[0].getsockname()[1] # get the random server port @@ -169,15 +168,15 @@ async def test_tcp_server_connection_lost(self): time.sleep(1) class BasicClient(asyncio.BaseProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - """ Connection made. """ - self.transport = transport # pylint: disable=attribute-defined-outside-init + """Get Connection made.""" + self.transport = transport # pylint: disable=attribute-defined-outside-init step1.set_result(True) _, protocol = await self.loop.create_connection(BasicClient, - host='127.0.0.1', port=random_port) + host='127.0.0.1', port=random_port) await step1 # On Windows we seem to need to give this an extra chance to finish, # otherwise there ends up being an active connection at the assert. @@ -185,17 +184,16 @@ def connection_made(self, transport): self.assertEqual(len(server.active_connections), 1) protocol.transport.close() - # close isn't synchronous and there's no - # notification that it's done + # close isn't synchronous and there's no + # notification that it's done await asyncio.sleep(0.2) # so we have to wait a bit self.assertFalse(server.active_connections) server.server_close() - async def test_tcp_server_close_active_connection(self): - """ Test server_close() while there are active TCP connections """ - server = await StartTcpServer(context=self.context,address=("127.0.0.1", 0),loop=self.loop) + """Test server_close() while there are active TCP connections""" + server = await StartTcpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving @@ -206,11 +204,11 @@ async def test_tcp_server_close_active_connection(self): self.loop.create_future() class BasicClient(asyncio.BaseProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - """ Connection made. """ - self.transport = transport # pylint: disable=attribute-defined-outside-init + """Get Connection made.""" + self.transport = transport # pylint: disable=attribute-defined-outside-init step1.set_result(True) await self.loop.create_connection(BasicClient, host='127.0.0.1', port=random_port) @@ -224,15 +222,14 @@ def connection_made(self, transport): # close isn't synchronous and there's no notification that it's done # so we have to wait a bit await asyncio.sleep(0.5) - self.assertTrue( not server.active_connections ) - + self.assertTrue(not server.active_connections) async def test_tcp_server_no_slave(self): - """ Test unknown slave unit exception """ - context = ModbusServerContext(slaves={0x01: self.store, 0x02: self.store }, single=False) + """Test unknown slave unit exception""" + context = ModbusServerContext(slaves={0x01: self.store, 0x02: self.store}, single=False) data = b"\x01\x00\x00\x00\x00\x06\x05\x03\x00\x00\x00\x01" - # get slave 5 function 3 (holding register) - server = await StartTcpServer(context=context,address=("127.0.0.1", 0),loop=self.loop) + # get slave 5 function 3 (holding register) + server = await StartTcpServer(context=context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving random_port = server.server.sockets[0].getsockname()[1] # get the random server port @@ -241,22 +238,22 @@ async def test_tcp_server_no_slave(self): eof = self.loop.create_future() class BasicClient(asyncio.BaseProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - """ Connection made. """ - self.transport = transport # pylint: disable=attribute-defined-outside-init + """Get Connection made.""" + self.transport = transport # pylint: disable=attribute-defined-outside-init transport.write(data) connect.set_result(True) _logger.debug("Client connected") - def data_received(self, data): #NOSONAR pylint: disable=no-self-use,unused-argument - """ Data received. """ + def data_received(self, data): # NOSONAR pylint: disable=no-self-use,unused-argument + """Get Data received.""" receive.set_result(True) _logger.debug("Client received data") - def eof_received(self): # pylint: disable=no-self-use - """ EOF received. """ + def eof_received(self): # pylint: disable=no-self-use + """Get EOF received.""" eof.set_result(True) _logger.debug("Client stream eof") @@ -265,12 +262,11 @@ def eof_received(self): # pylint: disable=no-self-use self.assertFalse(eof.done()) server.server_close() - async def test_tcp_server_modbus_error(self): - """ Test sending garbage data on a TCP socket should drop the connection """ + """Test sending garbage data on a TCP socket should drop the connection""" data = b"\x01\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\x01" - # get slave 5 function 3 (holding register) - server = await StartTcpServer(context=self.context,address=("127.0.0.1", 0),loop=self.loop) + # get slave 5 function 3 (holding register) + server = await StartTcpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving @@ -281,69 +277,69 @@ async def test_tcp_server_modbus_error(self): random_port = server.server.sockets[0].getsockname()[1] # get the random server port class BasicClient(asyncio.BaseProtocol): - """ Basic client. """ + """Basic client.""" + def connection_made(self, transport): - """ Connection made. """ + """Get connection made.""" _logger.debug("Client connected") - self.transport = transport # pylint: disable=attribute-defined-outside-init + self.transport = transport # pylint: disable=attribute-defined-outside-init transport.write(data) connect.set_result(True) - def data_received(self, data): #NOSONAR pylint: disable=no-self-use,unused-argument - """ Data receivec. """ + def data_received(self, data): # NOSONAR pylint: disable=no-self-use,unused-argument + """Get data received.""" _logger.debug("Client received data") receive.set_result(True) - def eof_received(self): # pylint: disable=no-self-use - """ EOF received. """ + def eof_received(self): # pylint: disable=no-self-use + """EOF received.""" _logger.debug("Client stream eof") eof.set_result(True) transport, _ = await self.loop.create_connection(BasicClient, - host='127.0.0.1', port=random_port) + host='127.0.0.1', port=random_port) await asyncio.wait_for(connect, timeout=0.1) await asyncio.wait_for(receive, timeout=0.1) self.assertFalse(eof.done()) transport.close() server.server_close() - async def test_tcp_server_internal_exception(self): - """ Test sending garbage data on a TCP socket should drop the connection """ + """Test sending garbage data on a TCP socket should drop the connection""" data = b"\x01\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\x01" - # get slave 5 function 3 (holding register) - server = await StartTcpServer(context=self.context,address=("127.0.0.1", 0),loop=self.loop) + # get slave 5 function 3 (holding register) + server = await StartTcpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving with patch("pymodbus.register_read_message.ReadHoldingRegistersRequest.execute", side_effect=Exception): connect, receive, eof = self.loop.create_future(),\ - self.loop.create_future(), self.loop.create_future() + self.loop.create_future(), self.loop.create_future() random_port = server.server.sockets[0].getsockname()[1] # get the random server port class BasicClient(asyncio.BaseProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - """ Connection made. """ + """Get connection made.""" _logger.debug("Client connected") - self.transport = transport # pylint: disable=attribute-defined-outside-init + self.transport = transport # pylint: disable=attribute-defined-outside-init transport.write(data) connect.set_result(True) - def data_received(self, data): #NOSONAR pylint: disable=no-self-use,unused-argument - """ Data received. """ + def data_received(self, data): # NOSONAR pylint: disable=no-self-use,unused-argument + """Get data received.""" _logger.debug("Client received data") receive.set_result(True) - def eof_received(self): # pylint: disable=no-self-use - """ EOF received. """ + def eof_received(self): # pylint: disable=no-self-use + """EOF received.""" _logger.debug("Client stream eof") eof.set_result(True) transport, _ = await self.loop.create_connection(BasicClient, - host='127.0.0.1', port=random_port) + host='127.0.0.1', port=random_port) await asyncio.wait_for(connect, timeout=0.1) await asyncio.wait_for(receive, timeout=0.1) self.assertFalse(eof.done()) @@ -355,30 +351,30 @@ def eof_received(self): # pylint: disable=no-self-use # -----------------------------------------------------------------------# async def test_start_tls_server(self): - """ Test that the modbus tls asyncio server starts correctly """ + """Test that the modbus tls asyncio server starts correctly""" with patch.object(ssl.SSLContext, 'load_cert_chain'): identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) - self.loop = asynctest.Mock(self.loop) # pylint: disable=attribute-defined-outside-init + self.loop = asynctest.Mock(self.loop) # pylint: disable=attribute-defined-outside-init server = await StartTlsServer(context=self.context, loop=self.loop, identity=identity) self.assertEqual(server.control.Identity.VendorName, 'VendorName') self.assertTrue(server.sslctx is not None) self.loop.create_server.assert_called_once() async def test_tls_server_serve_forever(self): - """ Test StartTcpServer serve_forever() method """ + """Test StartTcpServer serve_forever() method""" with patch('asyncio.base_events.Server.serve_forever', - new_callable=asynctest.CoroutineMock) as serve: + new_callable=asynctest.CoroutineMock) as serve: with patch.object(ssl.SSLContext, 'load_cert_chain'): server = await StartTlsServer(context=self.context, - address=("127.0.0.1", 0), loop=self.loop) + address=("127.0.0.1", 0), loop=self.loop) await server.serve_forever() serve.assert_awaited() async def test_tls_server_serve_forever_twice(self): - """ Call on serve_forever() twice should result in a runtime error """ + """Call on serve_forever() twice should result in a runtime error""" with patch.object(ssl.SSLContext, 'load_cert_chain'): server = await StartTlsServer(context=self.context, - address=("127.0.0.1", 0), loop=self.loop) + address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving with pytest.raises(RuntimeError): @@ -390,26 +386,25 @@ async def test_tls_server_serve_forever_twice(self): # -----------------------------------------------------------------------# async def test_start_udp_server(self): - """ Test that the modbus udp asyncio server starts correctly """ + """Test that the modbus udp asyncio server starts correctly""" identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) - self.loop = asynctest.Mock(self.loop) # pylint: disable=attribute-defined-outside-init - server = await StartUdpServer(context=self.context,loop=self.loop,identity=identity) + self.loop = asynctest.Mock(self.loop) # pylint: disable=attribute-defined-outside-init + server = await StartUdpServer(context=self.context, loop=self.loop, identity=identity) self.assertEqual(server.control.Identity.VendorName, 'VendorName') self.loop.create_datagram_endpoint.assert_called_once() async def test_udp_server_serve_forever_start(self): - """ Test StartUdpServer serve_forever() method """ + """Test StartUdpServer serve_forever() method""" with patch('asyncio.base_events.Server.serve_forever', - new_callable=asynctest.CoroutineMock) as serve: + new_callable=asynctest.CoroutineMock) as serve: server = await StartTcpServer(context=self.context, - address=("127.0.0.1", 0), loop=self.loop) + address=("127.0.0.1", 0), loop=self.loop) await server.serve_forever() serve.assert_awaited() - async def test_udp_server_serve_forever_close(self): - """ Test StartUdpServer serve_forever() method """ - server = await StartUdpServer(context=self.context,address=("127.0.0.1", 0), loop=self.loop) + """Test StartUdpServer serve_forever() method""" + server = await StartUdpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving @@ -421,51 +416,49 @@ async def test_udp_server_serve_forever_close(self): self.assertTrue(server.protocol.is_closing()) async def test_udp_server_serve_forever_twice(self): - """ Call on serve_forever() twice should result in a runtime error """ + """Call on serve_forever() twice should result in a runtime error""" identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) - server = await StartUdpServer(context=self.context,address=("127.0.0.1", 0), - loop=self.loop,identity=identity) + server = await StartUdpServer(context=self.context, address=("127.0.0.1", 0), + loop=self.loop, identity=identity) asyncio.create_task(server.serve_forever()) await server.serving with self.assertRaises(RuntimeError): await server.serve_forever() server.server_close() - async def test_udp_server_receive_data(self): - """ Test that the sending data on datagram socket gets data pushed to framer """ - server = await StartUdpServer(context=self.context,address=("127.0.0.1", 0),loop=self.loop) + """Test that the sending data on datagram socket gets data pushed to framer""" + server = await StartUdpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving with patch('pymodbus.transaction.ModbusSocketFramer.processIncomingPacket', - new_callable=Mock) as process: + new_callable=Mock) as process: server.endpoint.datagram_received(data=b"12345", addr=("127.0.0.1", 12345)) await asyncio.sleep(0.1) process.seal() process.assert_called_once() - self.assertTrue( process.call_args[1]["data"] == b"12345" ) + self.assertTrue(process.call_args[1]["data"] == b"12345") server.server_close() - async def test_udp_server_send_data(self): - """ Test that the modbus udp asyncio server correctly sends data outbound """ + """Test that the modbus udp asyncio server correctly sends data outbound""" ModbusDeviceIdentification(info={0x00: 'VendorName'}) data = b'x\01\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\x19' - server = await StartUdpServer(context=self.context,address=("127.0.0.1", 0)) + server = await StartUdpServer(context=self.context, address=("127.0.0.1", 0)) asyncio.create_task(server.serve_forever()) await server.serving - random_port = server.protocol._sock.getsockname()[1] # pylint: disable=protected-access + random_port = server.protocol._sock.getsockname()[1] # pylint: disable=protected-access received = server.endpoint.datagram_received = Mock(wraps=server.endpoint.datagram_received) done = self.loop.create_future() received_value = None class BasicClient(asyncio.DatagramProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - self.transport = transport # pylint: disable=attribute-defined-outside-init + self.transport = transport # pylint: disable=attribute-defined-outside-init self.transport.sendto(data) def datagram_received(self, data, addr): @@ -475,8 +468,8 @@ def datagram_received(self, data, addr): done.set_result(True) self.transport.close() - await self.loop.create_datagram_endpoint( BasicClient, - remote_addr=('127.0.0.1', random_port)) + await self.loop.create_datagram_endpoint(BasicClient, + remote_addr=('127.0.0.1', random_port)) await asyncio.sleep(0.1) @@ -488,27 +481,26 @@ def datagram_received(self, data, addr): self.assertTrue(server.protocol.is_closing()) await asyncio.sleep(0.1) - async def test_udp_server_roundtrip(self): - """ Test sending and receiving data on udp socket""" - data = b"\x01\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\x01" # unit 1, read register + """Test sending and receiving data on udp socket""" + data = b"\x01\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\x01" # unit 1, read register expected_response = b'\x01\x00\x00\x00\x00\x05'\ - b'\x01\x03\x02\x00\x11' # value of 17 as per context - server = await StartUdpServer(context=self.context,address=("127.0.0.1", 0),loop=self.loop) + b'\x01\x03\x02\x00\x11' # value of 17 as per context + server = await StartUdpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving - random_port = server.protocol._sock.getsockname()[1] # pylint: disable=protected-access + random_port = server.protocol._sock.getsockname()[1] # pylint: disable=protected-access _, done = self.loop.create_future(), self.loop.create_future() received_value = None class BasicClient(asyncio.DatagramProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - self.transport = transport # pylint: disable=attribute-defined-outside-init + self.transport = transport # pylint: disable=attribute-defined-outside-init self.transport.sendto(data) def datagram_received(self, data, addr): @@ -518,7 +510,7 @@ def datagram_received(self, data, addr): done.set_result(True) transport, _ = await self.loop.create_datagram_endpoint(BasicClient, - remote_addr=('127.0.0.1', random_port)) + remote_addr=('127.0.0.1', random_port)) await asyncio.wait_for(done, timeout=0.1) self.assertEqual(received_value, expected_response) @@ -528,24 +520,25 @@ def datagram_received(self, data, addr): server.server_close() async def test_udp_server_exception(self): - """ Test sending garbage data on a TCP socket should drop the connection """ + """Test sending garbage data on a TCP socket should drop the connection""" garbage = b'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' - server = await StartUdpServer(context=self.context,address=("127.0.0.1", 0),loop=self.loop) + server = await StartUdpServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving with patch('pymodbus.transaction.ModbusSocketFramer.processIncomingPacket', new_callable=lambda: Mock(side_effect=Exception)): connect, receive, _ = self.loop.create_future(),\ - self.loop.create_future(), self.loop.create_future() - random_port = server.protocol._sock.getsockname()[1] # get the random server port pylint: disable=protected-access + self.loop.create_future(), self.loop.create_future() + # get the random server port pylint: disable=protected-access + random_port = server.protocol._sock.getsockname()[1] class BasicClient(asyncio.DatagramProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): _logger.debug("Client connected") - self.transport = transport # pylint: disable=attribute-defined-outside-init + self.transport = transport # pylint: disable=attribute-defined-outside-init transport.sendto(garbage) connect.set_result(True) @@ -558,58 +551,58 @@ def datagram_received(self, data, addr): remote_addr=('127.0.0.1', random_port)) await asyncio.wait_for(connect, timeout=0.1) self.assertFalse(receive.done()) - self.assertFalse(server.protocol._sock._closed) # pylint: disable=protected-access + self.assertFalse(server.protocol._sock._closed) # pylint: disable=protected-access server.server_close() # -----------------------------------------------------------------------# # Test ModbusServerFactory # -----------------------------------------------------------------------# - def test_modbus_server_factory(self): # pylint: disable=no-self-use - """ Test the base class for all the clients """ + def test_modbus_server_factory(self): # pylint: disable=no-self-use + """Test the base class for all the clients""" with pytest.warns(DeprecationWarning): ModbusServerFactory(store=None) - def test_stop_server(self): # pylint: disable=no-self-use - """ Test stop server. """ + def test_stop_server(self): # pylint: disable=no-self-use + """Test stop server.""" with pytest.warns(DeprecationWarning): StopServer() async def test_tcp_server_exception(self): - """ Sending garbage data on a TCP socket should drop the connection """ + """Sending garbage data on a TCP socket should drop the connection""" garbage = b'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' server = await StartTcpServer(context=self.context, - address=("127.0.0.1", 0), loop=self.loop) + address=("127.0.0.1", 0), loop=self.loop) asyncio.create_task(server.serve_forever()) await server.serving with patch('pymodbus.transaction.ModbusSocketFramer.processIncomingPacket', new_callable=lambda: Mock(side_effect=Exception)): connect, receive, eof = self.loop.create_future(),\ - self.loop.create_future(), self.loop.create_future() + self.loop.create_future(), self.loop.create_future() random_port = server.server.sockets[0].getsockname()[1] # get the random server port class BasicClient(asyncio.BaseProtocol): - """ Basic client. """ + """Basic client.""" def connection_made(self, transport): - """ Connection made. """ + """Get connection made.""" _logger.debug("Client connected") - self.transport = transport # pylint: disable=attribute-defined-outside-init + self.transport = transport # pylint: disable=attribute-defined-outside-init transport.write(garbage) connect.set_result(True) - def data_received(self, data): #NOSONAR pylint: disable=no-self-use,unused-argument - """ Data received. """ + def data_received(self, data): # NOSONAR pylint: disable=no-self-use,unused-argument + """Get data received.""" _logger.debug("Client received data") receive.set_result(True) - def eof_received(self): # pylint: disable=no-self-use - """ Eof received. """ + def eof_received(self): # pylint: disable=no-self-use + """Eof received.""" _logger.debug("Client stream eof") eof.set_result(True) _, _ = await self.loop.create_connection(BasicClient, host='127.0.0.1', - port=random_port) + port=random_port) await asyncio.wait_for(connect, timeout=0.1) await asyncio.wait_for(eof, timeout=0.1) # neither of these should timeout if the test is successful diff --git a/test/test_server_context.py b/test/test_server_context.py index 979dce587..98357620b 100644 --- a/test/test_server_context.py +++ b/test/test_server_context.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test server context. """ +"""Test server context.""" import unittest from pymodbus.datastore import ( ModbusSlaveContext, @@ -7,96 +7,93 @@ ) from pymodbus.exceptions import NoSuchSlaveException + class ModbusServerSingleContextTest(unittest.TestCase): - """ This is the unittest for the pymodbus.datastore.ModbusServerContext - using a single slave context. - """ + """This is the unittest for the pymodbus.datastore.ModbusServerContext using a single slave context.""" def setUp(self): - """ Sets up the test environment """ + """Set up the test environment""" self.slave = ModbusSlaveContext() self.context = ModbusServerContext(slaves=self.slave, single=True) def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.context def test_single_context_gets(self): - """ Test getting on a single context """ + """Test getting on a single context""" for slave_id in range(0, 0xff): self.assertEqual(self.slave, self.context[slave_id]) def test_single_context_deletes(self): - """ Test removing on multiple context """ + """Test removing on multiple context""" def _test(): del self.context[0x00] self.assertRaises(NoSuchSlaveException, _test) def test_single_context_iter(self): - """ Test iterating over a single context """ + """Test iterating over a single context""" expected = (0, self.slave) for slave in self.context: self.assertEqual(slave, expected) def test_single_context_default(self): - """ Test that the single context default values work """ + """Test that the single context default values work""" self.context = ModbusServerContext() slave = self.context[0x00] self.assertEqual(slave, {}) def test_single_context_set(self): - """ Test a setting a single slave context """ + """Test a setting a single slave context""" slave = ModbusSlaveContext() self.context[0x00] = slave actual = self.context[0x00] self.assertEqual(slave, actual) def test_single_context_register(self): - """ Test single context register. """ + """Test single context register.""" request_db = [1, 2, 3] slave = ModbusSlaveContext() slave.register(0xff, 'custom_request', request_db) - self.assertEqual(slave.store["custom_request"],request_db) - self.assertEqual(slave.decode(0xff),'custom_request') + self.assertEqual(slave.store["custom_request"], request_db) + self.assertEqual(slave.decode(0xff), 'custom_request') class ModbusServerMultipleContextTest(unittest.TestCase): - """ This is the unittest for the pymodbus.datastore.ModbusServerContext - using multiple slave contexts. - """ + """This is the unittest for the pymodbus.datastore.ModbusServerContext using multiple slave contexts.""" def setUp(self): - """ Sets up the test environment """ - self.slaves = dict((id, ModbusSlaveContext()) for id in range(10)) + """Set up the test environment""" + self.slaves = dict((id, ModbusSlaveContext()) for id in range(10)) self.context = ModbusServerContext(slaves=self.slaves, single=False) def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.context def test_multiple_context_gets(self): - """ Test getting on multiple context """ + """Test getting on multiple context""" for slave_id in range(0, 10): self.assertEqual(self.slaves[slave_id], self.context[slave_id]) def test_multiple_context_deletes(self): - """ Test removing on multiple context """ + """Test removing on multiple context""" del self.context[0x00] self.assertRaises(NoSuchSlaveException, lambda: self.context[0x00]) def test_multiple_context_iter(self): - """ Test iterating over multiple context """ + """Test iterating over multiple context""" for slave_id, slave in self.context: self.assertEqual(slave, self.slaves[slave_id]) self.assertTrue(slave_id in self.context) def test_multiple_context_default(self): - """ Test that the multiple context default values work """ + """Test that the multiple context default values work""" self.context = ModbusServerContext(single=False) self.assertRaises(NoSuchSlaveException, lambda: self.context[0x00]) def test_multiple_context_set(self): - """ Test a setting multiple slave contexts """ + """Test a setting multiple slave contexts""" slaves = dict((id, ModbusSlaveContext()) for id in range(10)) for slave_id, slave in iter(slaves.items()): self.context[slave_id] = slave @@ -104,8 +101,9 @@ def test_multiple_context_set(self): actual = self.context[slave_id] self.assertEqual(slave, actual) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_server_sync.py b/test/test_server_sync.py index a3503fad7..6ffcc440d 100644 --- a/test/test_server_sync.py +++ b/test/test_server_sync.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test server sync. """ +"""Test server sync.""" import ssl import socket import unittest @@ -36,10 +36,10 @@ # Mock Classes # --------------------------------------------------------------------------- # class MockServer: # noqa: E302 pylint: disable=too-few-public-methods - """ Mock server. """ + """Mock server.""" def __init__(self): - """ Init. """ + """Init.""" self.framer = lambda _, client=None: "framer" self.decoder = "decoder" self.threads = [] @@ -47,25 +47,27 @@ def __init__(self): # --------------------------------------------------------------------------- # # Fixture # --------------------------------------------------------------------------- # + + class SynchronousServerTest(unittest.TestCase): # noqa: E302 - """ Unittest for the pymodbus.server.sync module. """ + """Unittest for the pymodbus.server.sync module.""" # ----------------------------------------------------------------------- # # Test Base Request Handler # ----------------------------------------------------------------------- # def test_base_handler_undefined_methods(self): - """ Test the base handler undefined methods""" + """Test the base handler undefined methods""" handler = socketserver.BaseRequestHandler(None, None, None) handler.__class__ = ModbusBaseRequestHandler - self.assertRaises(NotImplementedException, lambda: handler.send(None)) # pylint: disable=no-member - self.assertRaises(NotImplementedException, lambda: handler.handle()) # pylint: disable=unnecessary-lambda + self.assertRaises(NotImplementedException, lambda: handler.send(None)) # pylint: disable=no-member + self.assertRaises(NotImplementedException, lambda: handler.handle()) # pylint: disable=unnecessary-lambda def test_base_handler_methods(self): - """ Test the base class for all the clients """ + """Test the base class for all the clients""" request = ReadCoilsRequest(1, 1) address = ('server', 12345) - server = MockServer() # noqa: E221 + server = MockServer() # noqa: E221 with patch.object(ModbusBaseRequestHandler, 'handle') as mock_handle: with patch.object(ModbusBaseRequestHandler, 'send') as mock_send: mock_handle.return_value = True @@ -85,22 +87,22 @@ def test_base_handler_methods(self): # Test Single Request Handler # ----------------------------------------------------------------------- # def test_modbus_single_request_handler_send(self): - """ Test modbus single request handler. """ + """Test modbus single request handler.""" handler = socketserver.BaseRequestHandler(None, None, None) handler.__class__ = ModbusSingleRequestHandler handler.framer = Mock() handler.framer.buildPacket.return_value = b"message" handler.request = Mock() request = ReadCoilsResponse([1]) - handler.send(request) # pylint: disable=no-member + handler.send(request) # pylint: disable=no-member self.assertEqual(handler.request.send.call_count, 1) request.should_respond = False - handler.send(request) # pylint: disable=no-member + handler.send(request) # pylint: disable=no-member self.assertEqual(handler.request.send.call_count, 1) def test_modbus_single_request_handler_handle(self): - """ Test modbus single request handler. """ + """Test modbus single request handler.""" handler = socketserver.BaseRequestHandler(None, None, None) handler.__class__ = ModbusSingleRequestHandler handler.framer = Mock() @@ -116,7 +118,7 @@ def test_modbus_single_request_handler_handle(self): self.assertEqual(handler.framer.processIncomingPacket.call_count, 0) # run forever if we are running - def _callback1(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument + def _callback1(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument handler.running = False # stop infinite loop handler.framer.processIncomingPacket.side_effect = _callback1 handler.running = True @@ -127,7 +129,7 @@ def _callback1(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument self.assertEqual(handler.framer.processIncomingPacket.call_count, 1) # exceptions are simply ignored - def _callback2(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument + def _callback2(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument if handler.framer.processIncomingPacket.call_count == 2: raise Exception("example exception") handler.running = False # stop infinite loop @@ -141,22 +143,22 @@ def _callback2(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument # Test Connected Request Handler # ----------------------------------------------------------------------- # def test_modbus_connected_request_handler_send(self): - """ Test modbus connected request handler. """ + """Test modbus connected request handler.""" handler = socketserver.BaseRequestHandler(None, None, None) handler.__class__ = ModbusConnectedRequestHandler handler.framer = Mock() handler.framer.buildPacket.return_value = b"message" handler.request = Mock() request = ReadCoilsResponse([1]) - handler.send(request) # pylint: disable=no-member + handler.send(request) # pylint: disable=no-member self.assertEqual(handler.request.send.call_count, 1) request.should_respond = False - handler.send(request) # pylint: disable=no-member + handler.send(request) # pylint: disable=no-member self.assertEqual(handler.request.send.call_count, 1) def test_modbus_connected_request_handler_handle(self): - """ Test modbus connected request handler. """ + """Test modbus connected request handler.""" handler = socketserver.BaseRequestHandler(None, None, None) handler.__class__ = ModbusConnectedRequestHandler handler.server = Mock() @@ -171,7 +173,7 @@ def test_modbus_connected_request_handler_handle(self): self.assertEqual(handler.framer.processIncomingPacket.call_count, 0) # run forever if we are running - def _callback(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument + def _callback(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument handler.running = False # stop infinite loop handler.framer.processIncomingPacket.side_effect = _callback @@ -201,7 +203,7 @@ def _callback(parm1, parm2, *args, **kwargs): # pylint: disable=unused-argument # Test Disconnected Request Handler # ----------------------------------------------------------------------- # def test_modbus_disconnected_request_handler_send(self): - """ Test modbus disconnect request handler. """ + """Test modbus disconnect request handler.""" handler = socketserver.BaseRequestHandler(None, None, None) handler.__class__ = ModbusDisconnectedRequestHandler handler.framer = Mock() @@ -210,15 +212,15 @@ def test_modbus_disconnected_request_handler_send(self): handler.request = Mock() handler.socket = Mock() request = ReadCoilsResponse([1]) - handler.send(request) # pylint: disable=no-member + handler.send(request) # pylint: disable=no-member self.assertEqual(handler.socket.sendto.call_count, 1) request.should_respond = False - handler.send(request) # pylint:disable=no-member + handler.send(request) # pylint:disable=no-member self.assertEqual(handler.socket.sendto.call_count, 1) def test_modbus_disconnected_request_handler_handle(self): - """ Test modbus disconned request handler. """ + """Test modbus disconned request handler.""" handler = socketserver.BaseRequestHandler(None, None, None) handler.__class__ = ModbusDisconnectedRequestHandler handler.framer = Mock() @@ -232,7 +234,7 @@ def test_modbus_disconnected_request_handler_handle(self): self.assertEqual(handler.framer.processIncomingPacket.call_count, 0) # run forever if we are running - def _callback(parm1, parm2): # pylint: disable=unused-argument + def _callback(parm1, parm2): # pylint: disable=unused-argument handler.running = False # stop infinite loop handler.framer.processIncomingPacket.side_effect = _callback @@ -264,7 +266,7 @@ def _callback(parm1, parm2): # pylint: disable=unused-argument # Test TCP Server # ----------------------------------------------------------------------- # def test_tcp_server_close(self): - """ test that the synchronous TCP server closes correctly """ + """Test that the synchronous TCP server closes correctly""" identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) server = ModbusTcpServer(context=None, identity=identity, bind_and_activate=False) server.threads.append(Mock(**{'running': True})) @@ -273,7 +275,7 @@ def test_tcp_server_close(self): self.assertFalse(server.threads[0].running) def test_tcp_server_process(self): - """ test that the synchronous TCP server processes requests """ + """Test that the synchronous TCP server processes requests""" with patch('socketserver.ThreadingTCPServer') as mock_server: server = ModbusTcpServer(None) server.process_request('request', 'client') @@ -283,7 +285,7 @@ def test_tcp_server_process(self): # Test TLS Server # ----------------------------------------------------------------------- # def test_tls_ssl_ctx_provider(self): - """ test that sslctx_provider() produce SSLContext correctly """ + """Test that sslctx_provider() produce SSLContext correctly""" with patch.object(ssl.SSLContext, 'load_cert_chain'): sslctx = sslctx_provider(reqclicert=True) self.assertIsNotNone(sslctx) @@ -295,7 +297,7 @@ def test_tls_ssl_ctx_provider(self): self.assertEqual(sslctx_new, sslctx_old) def test_tls_server_init(self): - """ test that the synchronous TLS server initial correctly """ + """Test that the synchronous TLS server initial correctly""" with patch.object(socketserver.TCPServer, 'server_activate'): with patch.object(ssl.SSLContext, 'load_cert_chain'): identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) @@ -310,7 +312,7 @@ def test_tls_server_init(self): server.server_close() def test_tls_server_close(self): - """ test that the synchronous TLS server closes correctly """ + """Test that the synchronous TLS server closes correctly""" with patch.object(ssl.SSLContext, 'load_cert_chain'): identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) server = ModbusTlsServer(context=None, identity=identity, @@ -321,7 +323,7 @@ def test_tls_server_close(self): self.assertFalse(server.threads[0].running) def test_tls_server_process(self): - """ test that the synchronous TLS server processes requests """ + """Test that the synchronous TLS server processes requests""" with patch('socketserver.ThreadingTCPServer') as mock_server: with patch.object(ssl.SSLContext, 'load_cert_chain'): server = ModbusTlsServer(None) @@ -332,7 +334,7 @@ def test_tls_server_process(self): # Test UDP Server # ----------------------------------------------------------------------- # def test_udp_server_close(self): - """ test that the synchronous UDP server closes correctly """ + """Test that the synchronous UDP server closes correctly""" identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) server = ModbusUdpServer(context=None, identity=identity, bind_and_activate=False) @@ -343,7 +345,7 @@ def test_udp_server_close(self): self.assertFalse(server.threads[0].running) def test_udp_server_process(self): - """ test that the synchronous UDP server processes requests """ + """Test that the synchronous UDP server processes requests""" with patch('socketserver.ThreadingUDPServer') as mock_server: server = ModbusUdpServer(None) request = ('data', 'socket') @@ -354,26 +356,26 @@ def test_udp_server_process(self): # Test Serial Server # ----------------------------------------------------------------------- # def test_serial_server_connect(self): - """ Test serial server connect. """ + """Test serial server connect.""" with patch.object(serial, 'Serial') as mock_serial: - mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda + mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda mock_serial.read = lambda size: '\x00' * size identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) server = ModbusSerialServer(context=None, identity=identity, port="dummy") self.assertEqual(server.handler.__class__.__name__, "CustomSingleRequestHandler") self.assertEqual(server.control.Identity.VendorName, 'VendorName') - server._connect() # pylint: disable=protected-access + server._connect() # pylint: disable=protected-access with patch.object(serial, 'Serial') as mock_serial: - mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda + mock_serial.write = lambda x: len(x) # pylint: disable=unnecessary-lambda mock_serial.read = lambda size: '\x00' * size mock_serial.side_effect = serial.SerialException() server = ModbusSerialServer(None, port="dummy") self.assertEqual(server.socket, None) - def test_serial_server_serve_forever(self): # pylint: disable=no-self-use - """ test that the synchronous serial server closes correctly """ + def test_serial_server_serve_forever(self): # pylint: disable=no-self-use + """Test that the synchronous serial server closes correctly""" with patch.object(serial, 'Serial'): with patch('pymodbus.server.sync.CustomSingleRequestHandler') as mock_handler: server = ModbusSerialServer(None) @@ -382,8 +384,8 @@ def test_serial_server_serve_forever(self): # pylint: disable=no-self-use server.serve_forever() instance.response_manipulator.assert_any_call() - def test_serial_server_close(self): # pylint: disable=no-self-use - """ test that the synchronous serial server closes correctly """ + def test_serial_server_close(self): # pylint: disable=no-self-use + """Test that the synchronous serial server closes correctly""" with patch.object(serial, 'Serial') as mock_serial: instance = mock_serial.return_value server = ModbusSerialServer(None) @@ -393,25 +395,25 @@ def test_serial_server_close(self): # pylint: disable=no-self-use # ----------------------------------------------------------------------- # # Test Synchronous Factories # ----------------------------------------------------------------------- # - def test_start_tcp_server(self): # pylint: disable=no-self-use - """ Test the tcp server starting factory """ + def test_start_tcp_server(self): # pylint: disable=no-self-use + """Test the tcp server starting factory""" with patch.object(ModbusTcpServer, 'serve_forever'): StartTcpServer(bind_and_activate=False) - def test_start_tls_server(self): # pylint: disable=no-self-use - """ Test the tls server starting factory """ + def test_start_tls_server(self): # pylint: disable=no-self-use + """Test the tls server starting factory""" with patch.object(ModbusTlsServer, 'serve_forever'): with patch.object(ssl.SSLContext, 'load_cert_chain'): StartTlsServer(bind_and_activate=False) - def test_start_udp_server(self): # pylint: disable=no-self-use - """ Test the udp server starting factory """ + def test_start_udp_server(self): # pylint: disable=no-self-use + """Test the udp server starting factory""" with patch.object(ModbusUdpServer, 'serve_forever'): with patch.object(socketserver.UDPServer, 'server_bind'): StartUdpServer() - def test_start_serial_server(self): # pylint: disable=no-self-use - """ Test the serial server starting factory """ + def test_start_serial_server(self): # pylint: disable=no-self-use + """Test the serial server starting factory""" with patch.object(ModbusSerialServer, 'serve_forever'): StartSerialServer(port=pytest.SERIAL_PORT) diff --git a/test/test_transaction.py b/test/test_transaction.py index 3f9636fae..4689ca4c3 100755 --- a/test/test_transaction.py +++ b/test/test_transaction.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -""" Test transaction. """ +"""Test transaction.""" import unittest from itertools import count from binascii import a2b_hex @@ -28,27 +28,27 @@ ) -class ModbusTransactionTest(unittest.TestCase): # pylint: disable=too-many-public-methods - """ Unittest for the pymodbus.transaction module. """ +class ModbusTransactionTest(unittest.TestCase): # pylint: disable=too-many-public-methods + """Unittest for the pymodbus.transaction module.""" # ----------------------------------------------------------------------- # # Test Construction # ----------------------------------------------------------------------- # def setUp(self): - """ Sets up the test environment """ - self.client = None - self.decoder = ServerDecoder() - self._tcp = ModbusSocketFramer(decoder=self.decoder, client=None) - self._tls = ModbusTlsFramer(decoder=self.decoder, client=None) - self._rtu = ModbusRtuFramer(decoder=self.decoder, client=None) - self._ascii = ModbusAsciiFramer(decoder=self.decoder, client=None) - self._binary = ModbusBinaryFramer(decoder=self.decoder, client=None) + """Set up the test environment""" + self.client = None + self.decoder = ServerDecoder() + self._tcp = ModbusSocketFramer(decoder=self.decoder, client=None) + self._tls = ModbusTlsFramer(decoder=self.decoder, client=None) + self._rtu = ModbusRtuFramer(decoder=self.decoder, client=None) + self._ascii = ModbusAsciiFramer(decoder=self.decoder, client=None) + self._binary = ModbusBinaryFramer(decoder=self.decoder, client=None) self._manager = DictTransactionManager(self.client) self._queue_manager = FifoTransactionManager(self.client) self._tm = ModbusTransactionManager(self.client) def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self._manager del self._tcp del self._tls @@ -60,16 +60,16 @@ def tearDown(self): # ----------------------------------------------------------------------- # def test_calculate_expected_response_length(self): - """ Test calculate expected response length. """ + """Test calculate expected response length.""" self._tm.client = MagicMock() self._tm.client.framer = MagicMock() - self._tm._set_adu_size() # pylint: disable=protected-access - self.assertEqual(self._tm._calculate_response_length(0), None) # pylint: disable=protected-access + self._tm._set_adu_size() # pylint: disable=protected-access + self.assertEqual(self._tm._calculate_response_length(0), None) # pylint: disable=protected-access self._tm.base_adu_size = 10 - self.assertEqual(self._tm._calculate_response_length(5), 15) # pylint: disable=protected-access + self.assertEqual(self._tm._calculate_response_length(5), 15) # pylint: disable=protected-access def test_calculate_exception_length(self): - """ Test calculate exception length. """ + """Test calculate exception length.""" for framer, exception_length in (('ascii', 11), ('binary', 7), ('rtu', 5), @@ -90,18 +90,18 @@ def test_calculate_exception_length(self): else: self._tm.client.framer = MagicMock() - self._tm._set_adu_size() # pylint: disable=protected-access - self.assertEqual(self._tm._calculate_exception_length(), # pylint: disable=protected-access + self._tm._set_adu_size() # pylint: disable=protected-access + self.assertEqual(self._tm._calculate_exception_length(), # pylint: disable=protected-access exception_length) @patch('pymodbus.transaction.time') def test_execute(self, mock_time): - """ Test execute. """ + """Test execute.""" mock_time.time.side_effect = count() client = MagicMock() client.framer = self._ascii - client.framer._buffer = b'deadbeef' # pylint: disable=protected-access + client.framer._buffer = b'deadbeef' # pylint: disable=protected-access client.framer.processIncomingPacket = MagicMock() client.framer.processIncomingPacket.return_value = None client.framer.buildPacket = MagicMock() @@ -119,7 +119,7 @@ def test_execute(self, mock_time): request.unit_id = 1 request.function_code = 222 trans = ModbusTransactionManager(client) - trans._recv = MagicMock(return_value=b'abcdef') # pylint: disable=protected-access + trans._recv = MagicMock(return_value=b'abcdef') # pylint: disable=protected-access self.assertEqual(trans.retries, 3) self.assertEqual(trans.retry_on_empty, False) @@ -128,7 +128,7 @@ def test_execute(self, mock_time): response = trans.execute(request) self.assertEqual(response, 'response') # No response - trans._recv = MagicMock(return_value=b'abcdef') # pylint: disable=protected-access + trans._recv = MagicMock(return_value=b'abcdef') # pylint: disable=protected-access # tm._transact.return_value = (b'', None) trans.transactions = [] trans.getTransaction = MagicMock() @@ -138,13 +138,13 @@ def test_execute(self, mock_time): # No response with retries trans.retry_on_empty = True - trans._recv = MagicMock(side_effect=iter([b'', b'abcdef'])) # pylint: disable=protected-access + trans._recv = MagicMock(side_effect=iter([b'', b'abcdef'])) # pylint: disable=protected-access # tm._transact.side_effect = [(b'', None), (b'abcdef', None)] response = trans.execute(request) self.assertIsInstance(response, ModbusIOException) # wrong handle_local_echo - trans._recv = MagicMock(side_effect=iter([b'abcdef', b'deadbe', b'123456'])) # pylint: disable=protected-access + trans._recv = MagicMock(side_effect=iter([b'abcdef', b'deadbe', b'123456'])) # pylint: disable=protected-access client.handle_local_echo = True trans.retry_on_empty = False trans.retry_on_invalid = False @@ -154,13 +154,14 @@ def test_execute(self, mock_time): # retry on invalid response trans.retry_on_invalid = True - trans._recv = MagicMock(side_effect=iter([b'', b'abcdef', b'deadbe', b'123456'])) # pylint: disable=protected-access + trans._recv = MagicMock(side_effect=iter( # pylint: disable=protected-access + [b'', b'abcdef', b'deadbe', b'123456'])) # pylint: disable=protected-access # tm._transact.side_effect = [(b'', None), (b'abcdef', None)] response = trans.execute(request) self.assertIsInstance(response, ModbusIOException) # Unable to decode response - trans._recv = MagicMock(side_effect=ModbusIOException()) # pylint: disable=protected-access + trans._recv = MagicMock(side_effect=ModbusIOException()) # pylint: disable=protected-access # tm._transact.side_effect = [(b'abcdef', None)] client.framer.processIncomingPacket.side_effect = MagicMock(side_effect=ModbusIOException()) self.assertIsInstance(trans.execute(request), ModbusIOException) @@ -172,40 +173,39 @@ def test_execute(self, mock_time): self.assertEqual(response, b'Broadcast write sent - ' b'no response expected') - # ----------------------------------------------------------------------- # # Dictionary based transaction manager # ----------------------------------------------------------------------- # def test_dict_transaction_manager_tid(self): - """ Test the dict transaction manager TID """ + """Test the dict transaction manager TID""" for tid in range(1, self._manager.getNextTID() + 10): - self.assertEqual(tid+1, self._manager.getNextTID()) + self.assertEqual(tid + 1, self._manager.getNextTID()) self._manager.reset() self.assertEqual(1, self._manager.getNextTID()) def test_get_dict_fifo_transaction_manager_transaction(self): - """ Test the dict transaction manager """ - class Request: # pylint: disable=too-few-public-methods - """ Request. """ + """Test the dict transaction manager""" + class Request: # pylint: disable=too-few-public-methods + """Request.""" self._manager.reset() handle = Request() - handle.transaction_id = self._manager.getNextTID() # pylint: disable=attribute-defined-outside-init - handle.message = b"testing" # pylint: disable=attribute-defined-outside-init + handle.transaction_id = self._manager.getNextTID() # pylint: disable=attribute-defined-outside-init + handle.message = b"testing" # pylint: disable=attribute-defined-outside-init self._manager.addTransaction(handle) result = self._manager.getTransaction(handle.transaction_id) self.assertEqual(handle.message, result.message) def test_delete_dict_fifo_transaction_manager_transaction(self): - """ Test the dict transaction manager """ - class Request: # pylint: disable=too-few-public-methods - """ Request. """ + """Test the dict transaction manager""" + class Request: # pylint: disable=too-few-public-methods + """Request.""" self._manager.reset() handle = Request() - handle.transaction_id = self._manager.getNextTID() # pylint: disable=attribute-defined-outside-init - handle.message = b"testing" # pylint: disable=attribute-defined-outside-init + handle.transaction_id = self._manager.getNextTID() # pylint: disable=attribute-defined-outside-init + handle.message = b"testing" # pylint: disable=attribute-defined-outside-init self._manager.addTransaction(handle) self._manager.delTransaction(handle.transaction_id) @@ -215,34 +215,34 @@ class Request: # pylint: disable=too-few-public-methods # Queue based transaction manager # ----------------------------------------------------------------------- # def test_fifo_transaction_manager_tid(self): - """ Test the fifo transaction manager TID """ + """Test the fifo transaction manager TID""" for tid in range(1, self._queue_manager.getNextTID() + 10): - self.assertEqual(tid+1, self._queue_manager.getNextTID()) + self.assertEqual(tid + 1, self._queue_manager.getNextTID()) self._queue_manager.reset() self.assertEqual(1, self._queue_manager.getNextTID()) def test_get_fifo_transaction_manager_transaction(self): - """ Test the fifo transaction manager """ - class Request: # pylint: disable=too-few-public-methods - """ Request. """ + """Test the fifo transaction manager""" + class Request: # pylint: disable=too-few-public-methods + """Request.""" self._queue_manager.reset() handle = Request() - handle.transaction_id = self._queue_manager.getNextTID() # pylint: disable=attribute-defined-outside-init - handle.message = b"testing" # pylint: disable=attribute-defined-outside-init + handle.transaction_id = self._queue_manager.getNextTID() # pylint: disable=attribute-defined-outside-init + handle.message = b"testing" # pylint: disable=attribute-defined-outside-init self._queue_manager.addTransaction(handle) result = self._queue_manager.getTransaction(handle.transaction_id) self.assertEqual(handle.message, result.message) def test_delete_fifo_transaction_manager_transaction(self): - """ Test the fifo transaction manager """ - class Request: # pylint: disable=too-few-public-methods - """ Request. """ + """Test the fifo transaction manager""" + class Request: # pylint: disable=too-few-public-methods + """Request.""" self._queue_manager.reset() handle = Request() - handle.transaction_id = self._queue_manager.getNextTID() # pylint: disable=attribute-defined-outside-init - handle.message = b"testing" # pylint: disable=attribute-defined-outside-init + handle.transaction_id = self._queue_manager.getNextTID() # pylint: disable=attribute-defined-outside-init + handle.message = b"testing" # pylint: disable=attribute-defined-outside-init self._queue_manager.addTransaction(handle) self._queue_manager.delTransaction(handle.transaction_id) @@ -252,7 +252,7 @@ class Request: # pylint: disable=too-few-public-methods # TCP tests # ----------------------------------------------------------------------- # def test_tcp_framer_transaction_ready(self): - """ Test a tcp frame transaction """ + """Test a tcp frame transaction""" msg = b"\x00\x01\x12\x34\x00\x04\xff\x02\x12\x34" self.assertFalse(self._tcp.isFrameReady()) self.assertFalse(self._tcp.checkFrame()) @@ -265,7 +265,7 @@ def test_tcp_framer_transaction_ready(self): self.assertEqual(b'', self._ascii.getFrame()) def test_tcp_framer_transaction_full(self): - """ Test a full tcp frame transaction """ + """Test a full tcp frame transaction""" msg = b"\x00\x01\x12\x34\x00\x04\xff\x02\x12\x34" self._tcp.addToFrame(msg) self.assertTrue(self._tcp.checkFrame()) @@ -274,7 +274,7 @@ def test_tcp_framer_transaction_full(self): self._tcp.advanceFrame() def test_tcp_framer_transaction_half(self): - """ Test a half completed tcp frame transaction """ + """Test a half completed tcp frame transaction""" msg1 = b"\x00\x01\x12\x34\x00" msg2 = b"\x04\xff\x02\x12\x34" self._tcp.addToFrame(msg1) @@ -288,7 +288,7 @@ def test_tcp_framer_transaction_half(self): self._tcp.advanceFrame() def test_tcp_framer_transaction_half2(self): - """ Test a half completed tcp frame transaction """ + """Test a half completed tcp frame transaction""" msg1 = b"\x00\x01\x12\x34\x00\x04\xff" msg2 = b"\x02\x12\x34" self._tcp.addToFrame(msg1) @@ -302,7 +302,7 @@ def test_tcp_framer_transaction_half2(self): self._tcp.advanceFrame() def test_tcp_framer_transaction_half3(self): - """ Test a half completed tcp frame transaction """ + """Test a half completed tcp frame transaction""" msg1 = b"\x00\x01\x12\x34\x00\x04\xff\x02\x12" msg2 = b"\x34" self._tcp.addToFrame(msg1) @@ -316,7 +316,7 @@ def test_tcp_framer_transaction_half3(self): self._tcp.advanceFrame() def test_tcp_framer_transaction_short(self): - """ Test that we can get back on track after an invalid message """ + """Test that we can get back on track after an invalid message""" msg1 = b"\x99\x99\x99\x99\x00\x01\x00\x01" msg2 = b"\x00\x01\x12\x34\x00\x04\xff\x02\x12\x34" self._tcp.addToFrame(msg1) @@ -325,18 +325,18 @@ def test_tcp_framer_transaction_short(self): self.assertEqual(b'', result) self._tcp.advanceFrame() self._tcp.addToFrame(msg2) - self.assertEqual(10, len(self._tcp._buffer)) # pylint: disable=protected-access + self.assertEqual(10, len(self._tcp._buffer)) # pylint: disable=protected-access self.assertTrue(self._tcp.checkFrame()) result = self._tcp.getFrame() self.assertEqual(msg2[7:], result) self._tcp.advanceFrame() def test_tcp_framer_populate(self): - """ Test a tcp frame packet build """ + """Test a tcp frame packet build""" expected = ModbusRequest() expected.transaction_id = 0x0001 - expected.protocol_id = 0x1234 - expected.unit_id = 0xff + expected.protocol_id = 0x1234 + expected.unit_id = 0xff msg = b"\x00\x01\x12\x34\x00\x04\xff\x02\x12\x34" self._tcp.addToFrame(msg) self.assertTrue(self._tcp.checkFrame()) @@ -347,14 +347,14 @@ def test_tcp_framer_populate(self): self._tcp.advanceFrame() def test_tcp_framer_packet(self): - """ Test a tcp frame packet build """ + """Test a tcp frame packet build""" old_encode = ModbusRequest.encode ModbusRequest.encode = lambda self: b'' message = ModbusRequest() message.transaction_id = 0x0001 - message.protocol_id = 0x1234 - message.unit_id = 0xff - message.function_code = 0x01 + message.protocol_id = 0x1234 + message.unit_id = 0xff + message.function_code = 0x01 expected = b"\x00\x01\x12\x34\x00\x02\xff\x01" actual = self._tcp.buildPacket(message) self.assertEqual(expected, actual) @@ -364,7 +364,7 @@ def test_tcp_framer_packet(self): # TLS tests # ----------------------------------------------------------------------- # def framer_tls_framer_transaction_ready(self): - """ Test a tls frame transaction """ + """Test a tls frame transaction""" msg = b"\x01\x12\x34\x00\x08" self.assertFalse(self._tls.isFrameReady()) self.assertFalse(self._tls.checkFrame()) @@ -377,7 +377,7 @@ def framer_tls_framer_transaction_ready(self): self.assertEqual(b'', self._tls.getFrame()) def framer_tls_framer_transaction_full(self): - """ Test a full tls frame transaction """ + """Test a full tls frame transaction""" msg = b"\x01\x12\x34\x00\x08" self._tls.addToFrame(msg) self.assertTrue(self._tls.checkFrame()) @@ -386,7 +386,7 @@ def framer_tls_framer_transaction_full(self): self._tls.advanceFrame() def framer_tls_framer_transaction_half(self): - """ Test a half completed tls frame transaction """ + """Test a half completed tls frame transaction""" msg1 = b"" msg2 = b"\x01\x12\x34\x00\x08" self._tls.addToFrame(msg1) @@ -400,7 +400,7 @@ def framer_tls_framer_transaction_half(self): self._tls.advanceFrame() def framer_tls_framer_transaction_short(self): - """ Test that we can get back on track after an invalid message """ + """Test that we can get back on track after an invalid message""" msg1 = b"" msg2 = b"\x01\x12\x34\x00\x08" self._tls.addToFrame(msg1) @@ -409,14 +409,14 @@ def framer_tls_framer_transaction_short(self): self.assertEqual(b'', result) self._tls.advanceFrame() self._tls.addToFrame(msg2) - self.assertEqual(5, len(self._tls._buffer)) # pylint: disable=protected-access + self.assertEqual(5, len(self._tls._buffer)) # pylint: disable=protected-access self.assertTrue(self._tls.checkFrame()) result = self._tls.getFrame() self.assertEqual(msg2[0:], result) self._tls.advanceFrame() def framer_tls_framer_decode(self): - """ Testmessage decoding """ + """Testmessage decoding""" msg1 = b"" msg2 = b"\x01\x12\x34\x00\x08" result = self._tls.decode_data(msg1) @@ -426,71 +426,72 @@ def framer_tls_framer_decode(self): self._tls.advanceFrame() def framer_tls_incoming_packet(self): - """ Framer tls incoming packet. """ + """Framer tls incoming packet.""" msg = b"\x01\x12\x34\x00\x08" unit = 0x01 - def mock_callback(self): # pylint: disable=unused-argument - """ Mock callback. """ - self._tls._process = MagicMock() # pylint: disable=protected-access + def mock_callback(self): # pylint: disable=unused-argument + """Mock callback.""" + + self._tls._process = MagicMock() # pylint: disable=protected-access self._tls.isFrameReady = MagicMock(return_value=False) self._tls.processIncomingPacket(msg, mock_callback, unit) self.assertEqual(msg, self._tls.getRawFrame()) self._tls.advanceFrame() self._tls.isFrameReady = MagicMock(return_value=True) - self._tls._validate_unit_id = MagicMock(return_value=False) # pylint: disable=protected-access + self._tls._validate_unit_id = MagicMock(return_value=False) # pylint: disable=protected-access self._tls.processIncomingPacket(msg, mock_callback, unit) self.assertEqual(b'', self._tls.getRawFrame()) self._tls.advanceFrame() - self._tls._validate_unit_id = MagicMock(return_value=True) # pylint: disable=protected-access + self._tls._validate_unit_id = MagicMock(return_value=True) # pylint: disable=protected-access self._tls.processIncomingPacket(msg, mock_callback, unit) self.assertEqual(msg, self._tls.getRawFrame()) self._tls.advanceFrame() def framer_tls_process(self): - """ Framer tls process. """ - class MockResult: # pylint: disable=too-few-public-methods - """ Mock result. """ + """Framer tls process.""" + class MockResult: # pylint: disable=too-few-public-methods + """Mock result.""" def __init__(self, code): - """ Init. """ + """Init.""" self.function_code = code - def mock_callback(self): # pylint: disable=unused-argument - """ Mock callback. """ + def mock_callback(self): # pylint: disable=unused-argument + """Mock callback.""" self._tls.decoder.decode = MagicMock(return_value=None) self.assertRaises(ModbusIOException, - lambda: self._tls._process(mock_callback)) # pylint: disable=protected-access + lambda: self._tls._process(mock_callback)) # pylint: disable=protected-access result = MockResult(0x01) self._tls.decoder.decode = MagicMock(return_value=result) self.assertRaises(InvalidMessageReceivedException, - lambda: self._tls._process(mock_callback, error=True)) # pylint: disable=protected-access + lambda: self._tls._process(mock_callback, error=True)) # pylint: disable=protected-access - self._tls._process(mock_callback) # pylint: disable=protected-access + self._tls._process(mock_callback) # pylint: disable=protected-access self.assertEqual(b'', self._tls.getRawFrame()) def framer_tls_framer_populate(self): - """ Test a tls frame packet build """ + """Test a tls frame packet build""" ModbusRequest() msg = b"\x01\x12\x34\x00\x08" self._tls.addToFrame(msg) self.assertTrue(self._tls.checkFrame()) actual = ModbusRequest() - result = self._tls.populateResult(actual) # pylint: disable=assignment-from-none + result = self._tls.populateResult(actual) # pylint: disable=assignment-from-none self.assertEqual(None, result) self._tls.advanceFrame() def framer_tls_framer_packet(self): - """ Test a tls frame packet build """ + """Test a tls frame packet build""" old_encode = ModbusRequest.encode ModbusRequest.encode = lambda self: b'' message = ModbusRequest() - message.function_code = 0x01 + message.function_code = 0x01 expected = b"\x01" actual = self._tls.buildPacket(message) self.assertEqual(expected, actual) @@ -500,7 +501,7 @@ def framer_tls_framer_packet(self): # RTU tests # ----------------------------------------------------------------------- # def test_rtu_framer_transaction_ready(self): - """ Test if the checks for a complete frame work """ + """Test if the checks for a complete frame work""" self.assertFalse(self._rtu.isFrameReady()) msg_parts = [b"\x00\x01\x00", b"\x00\x00\x01\xfc\x1b"] @@ -513,7 +514,7 @@ def test_rtu_framer_transaction_ready(self): self.assertTrue(self._rtu.checkFrame()) def test_rtu_framer_transaction_full(self): - """ Test a full rtu frame transaction """ + """Test a full rtu frame transaction""" msg = b"\x00\x01\x00\x00\x00\x01\xfc\x1b" stripped_msg = msg[1:-2] self._rtu.addToFrame(msg) @@ -523,7 +524,7 @@ def test_rtu_framer_transaction_full(self): self._rtu.advanceFrame() def test_rtu_framer_transaction_half(self): - """ Test a half completed rtu frame transaction """ + """Test a half completed rtu frame transaction""" msg_parts = [b"\x00\x01\x00", b"\x00\x00\x01\xfc\x1b"] stripped_msg = b"".join(msg_parts)[1:-2] self._rtu.addToFrame(msg_parts[0]) @@ -536,14 +537,14 @@ def test_rtu_framer_transaction_half(self): self._rtu.advanceFrame() def test_rtu_framer_populate(self): - """ Test a rtu frame packet build """ + """Test a rtu frame packet build""" request = ModbusRequest() msg = b"\x00\x01\x00\x00\x00\x01\xfc\x1b" self._rtu.addToFrame(msg) self._rtu.populateHeader() self._rtu.populateResult(request) - header_dict = self._rtu._header # pylint: disable=protected-access + header_dict = self._rtu._header # pylint: disable=protected-access self.assertEqual(len(msg), header_dict['len']) self.assertEqual(int(msg[0]), header_dict['uid']) self.assertEqual(msg[-2:], header_dict['crc']) @@ -551,33 +552,34 @@ def test_rtu_framer_populate(self): self.assertEqual(0x00, request.unit_id) def test_rtu_framer_packet(self): - """ Test a rtu frame packet build """ + """Test a rtu frame packet build""" old_encode = ModbusRequest.encode ModbusRequest.encode = lambda self: b'' message = ModbusRequest() - message.unit_id = 0xff - message.function_code = 0x01 - expected = b"\xff\x01\x81\x80" # only header + CRC - no data + message.unit_id = 0xff + message.function_code = 0x01 + expected = b"\xff\x01\x81\x80" # only header + CRC - no data actual = self._rtu.buildPacket(message) self.assertEqual(expected, actual) ModbusRequest.encode = old_encode def test_rtu_decode_exception(self): - """ Test that the RTU framer can decode errors """ + """Test that the RTU framer can decode errors""" message = b"\x00\x90\x02\x9c\x01" self._rtu.addToFrame(message) result = self._rtu.checkFrame() self.assertTrue(result) def test_process(self): - """ Test process. """ - class MockResult: # pylint: disable=too-few-public-methods - """ Mock result. """ + """Test process.""" + class MockResult: # pylint: disable=too-few-public-methods + """Mock result.""" + def __init__(self, code): self.function_code = code - def mock_callback(self): # pylint: disable=unused-argument - """ Mock callback. """ + def mock_callback(self): # pylint: disable=unused-argument + """Mock callback.""" mock_result = MockResult(code=0) self._rtu.getRawFrame = self._rtu.getFrame = MagicMock() @@ -586,26 +588,28 @@ def mock_callback(self): # pylint: disable=unused-argument self._rtu.populateResult = MagicMock() self._rtu.advanceFrame = MagicMock() - self._rtu._process(mock_callback) # pylint: disable=protected-access + self._rtu._process(mock_callback) # pylint: disable=protected-access self._rtu.populateResult.assert_called_with(mock_result) self._rtu.advanceFrame.assert_called_with() self.assertTrue(self._rtu.advanceFrame.called) - #Check errors + # Check errors self._rtu.decoder.decode = MagicMock(return_value=None) - self.assertRaises(ModbusIOException, lambda: self._rtu._process(mock_callback)) # pylint: disable=protected-access + self.assertRaises(ModbusIOException, lambda: self._rtu._process( # pylint: disable=protected-access + mock_callback)) def test_rtu_process_incoming_packets(self): - """ Test rtu process incoming packets. """ + """Test rtu process incoming packets.""" mock_data = b"\x00\x01\x00\x00\x00\x01\xfc\x1b" unit = 0x00 - def mock_callback(self): # pylint: disable=unused-argument - """ Mock callback. """ + + def mock_callback(self): # pylint: disable=unused-argument + """Mock callback.""" self._rtu.addToFrame = MagicMock() - self._rtu._process = MagicMock() # pylint: disable=protected-access + self._rtu._process = MagicMock() # pylint: disable=protected-access self._rtu.isFrameReady = MagicMock(return_value=False) - self._rtu._buffer = mock_data # pylint: disable=protected-access + self._rtu._buffer = mock_data # pylint: disable=protected-access self._rtu.processIncomingPacket(mock_data, mock_callback, unit) @@ -613,7 +617,7 @@ def mock_callback(self): # pylint: disable=unused-argument # ASCII tests # ----------------------------------------------------------------------- # def test_ascii_framer_transaction_ready(self): - """ Test a ascii frame transaction """ + """Test a ascii frame transaction""" msg = b':F7031389000A60\r\n' self.assertFalse(self._ascii.isFrameReady()) self.assertFalse(self._ascii.checkFrame()) @@ -626,7 +630,7 @@ def test_ascii_framer_transaction_ready(self): self.assertEqual(b'', self._ascii.getFrame()) def test_ascii_framer_transaction_full(self): - """ Test a full ascii frame transaction """ + """Test a full ascii frame transaction""" msg = b'sss:F7031389000A60\r\n' pack = a2b_hex(msg[6:-4]) self._ascii.addToFrame(msg) @@ -636,7 +640,7 @@ def test_ascii_framer_transaction_full(self): self._ascii.advanceFrame() def test_ascii_framer_transaction_half(self): - """ Test a half completed ascii frame transaction """ + """Test a half completed ascii frame transaction""" msg1 = b'sss:F7031389' msg2 = b'000A60\r\n' pack = a2b_hex(msg1[6:] + msg2[:-4]) @@ -651,29 +655,30 @@ def test_ascii_framer_transaction_half(self): self._ascii.advanceFrame() def test_ascii_framer_populate(self): - """ Test a ascii frame packet build """ + """Test a ascii frame packet build""" request = ModbusRequest() self._ascii.populateResult(request) self.assertEqual(0x00, request.unit_id) def test_ascii_framer_packet(self): - """ Test a ascii frame packet build """ + """Test a ascii frame packet build""" old_encode = ModbusRequest.encode ModbusRequest.encode = lambda self: b'' message = ModbusRequest() - message.unit_id = 0xff - message.function_code = 0x01 + message.unit_id = 0xff + message.function_code = 0x01 expected = b":FF0100\r\n" actual = self._ascii.buildPacket(message) self.assertEqual(expected, actual) ModbusRequest.encode = old_encode def test_ascii_process_incoming_packets(self): - """ Test ascii process incoming packet. """ + """Test ascii process incoming packet.""" mock_data = b':F7031389000A60\r\n' unit = 0x00 - def mock_callback(mock_data, *args, **kwargs): # pylint: disable=unused-argument - """ Mock callback. """ + + def mock_callback(mock_data, *args, **kwargs): # pylint: disable=unused-argument + """Mock callback.""" self._ascii.processIncomingPacket(mock_data, mock_callback, unit) @@ -685,8 +690,8 @@ def mock_callback(mock_data, *args, **kwargs): # pylint: disable=unused-argument # Binary tests # ----------------------------------------------------------------------- # def test_binary_framer_transaction_ready(self): - """ Test a binary frame transaction """ - msg = b'\x7b\x01\x03\x00\x00\x00\x05\x85\xC9\x7d' + """Test a binary frame transaction""" + msg = b'\x7b\x01\x03\x00\x00\x00\x05\x85\xC9\x7d' self.assertFalse(self._binary.isFrameReady()) self.assertFalse(self._binary.checkFrame()) self._binary.addToFrame(msg) @@ -698,8 +703,8 @@ def test_binary_framer_transaction_ready(self): self.assertEqual(b'', self._binary.getFrame()) def test_binary_framer_transaction_full(self): - """ Test a full binary frame transaction """ - msg = b'\x7b\x01\x03\x00\x00\x00\x05\x85\xC9\x7d' + """Test a full binary frame transaction""" + msg = b'\x7b\x01\x03\x00\x00\x00\x05\x85\xC9\x7d' pack = msg[2:-3] self._binary.addToFrame(msg) self.assertTrue(self._binary.checkFrame()) @@ -708,7 +713,7 @@ def test_binary_framer_transaction_full(self): self._binary.advanceFrame() def test_binary_framer_transaction_half(self): - """ Test a half completed binary frame transaction """ + """Test a half completed binary frame transaction""" msg1 = b'\x7b\x01\x03\x00' msg2 = b'\x00\x00\x05\x85\xC9\x7d' pack = msg1[2:] + msg2[:-3] @@ -723,28 +728,29 @@ def test_binary_framer_transaction_half(self): self._binary.advanceFrame() def test_binary_framer_populate(self): - """ Test a binary frame packet build """ + """Test a binary frame packet build""" request = ModbusRequest() self._binary.populateResult(request) self.assertEqual(0x00, request.unit_id) def test_binary_framer_packet(self): - """ Test a binary frame packet build """ + """Test a binary frame packet build""" old_encode = ModbusRequest.encode ModbusRequest.encode = lambda self: b'' message = ModbusRequest() - message.unit_id = 0xff - message.function_code = 0x01 + message.unit_id = 0xff + message.function_code = 0x01 expected = b'\x7b\xff\x01\x81\x80\x7d' actual = self._binary.buildPacket(message) self.assertEqual(expected, actual) ModbusRequest.encode = old_encode def test_binary_process_incoming_packet(self): - """ Test binary process incoming packet. """ + """Test binary process incoming packet.""" mock_data = b'\x7b\x01\x03\x00\x00\x00\x05\x85\xC9\x7d' unit = 0x00 - def mock_callback(mock_data): # pylint: disable=unused-argument + + def mock_callback(mock_data): # pylint: disable=unused-argument pass self._binary.processIncomingPacket(mock_data, mock_callback, unit) diff --git a/test/test_utilities.py b/test/test_utilities.py index c9c9900e9..5b2d264cd 100644 --- a/test/test_utilities.py +++ b/test/test_utilities.py @@ -1,43 +1,47 @@ #!/usr/bin/env python3 -""" Test utilities. """ +"""Test utilities.""" import unittest import struct from pymodbus.utilities import pack_bitstring, unpack_bitstring from pymodbus.utilities import checkCRC, checkLRC from pymodbus.utilities import dict_property, default -_test_master = {4 : 'd'} -class DictPropertyTester: # pylint: disable=too-few-public-methods - """ Dictionary property test. """ +_test_master = {4: 'd'} + + +class DictPropertyTester: # pylint: disable=too-few-public-methods + """Dictionary property test.""" + def __init__(self): - self.test = {1 : 'a'} - self._test = {2 : 'b'} - self.__test = {3 : 'c'} #NOSONAR pylint: disable=unused-private-member + """Initialize.""" + self.test = {1: 'a'} + self._test = {2: 'b'} + self.__test = {3: 'c'} # NOSONAR pylint: disable=unused-private-member l_1 = dict_property(lambda s: s.test, 1) - l_2 = dict_property(lambda s: s._test, 2) # pylint: disable=protected-access - l_3 = dict_property(lambda s: s.__test, 3) # pylint: disable=protected-access + l_2 = dict_property(lambda s: s._test, 2) # pylint: disable=protected-access + l_3 = dict_property(lambda s: s.__test, 3) # pylint: disable=protected-access s_1 = dict_property('test', 1) s_2 = dict_property('_test', 2) g_1 = dict_property(_test_master, 4) class SimpleUtilityTest(unittest.TestCase): - """ Unittest for the pymod.utilities module. """ + """Unittest for the pymod.utilities module.""" def setUp(self): - """ Initializes the test environment """ + """Initialize the test environment""" self.data = struct.pack('>HHHH', 0x1234, 0x2345, 0x3456, 0x4567) self.string = b"test the computation" self.bits = [True, False, True, False, True, False, True, False] def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" del self.bits del self.string def test_dict_property(self): - """ Test all string <=> bit packing functions """ + """Test all string <=> bit packing functions""" result = DictPropertyTester() self.assertEqual(result.l_1, 'a') self.assertEqual(result.l_2, 'b') @@ -57,32 +61,33 @@ def test_dict_property(self): self.assertEqual(result.g_1, 'x') def test_default_value(self): - """ Test all string <=> bit packing functions """ + """Test all string <=> bit packing functions""" self.assertEqual(default(1), 0) self.assertEqual(default(1.1), 0.0) - self.assertEqual(default(1+1j), 0j) + self.assertEqual(default(1 + 1j), 0j) self.assertEqual(default('string'), '') - self.assertEqual(default([1,2,3]), []) - self.assertEqual(default({1:1}), {}) + self.assertEqual(default([1, 2, 3]), []) + self.assertEqual(default({1: 1}), {}) self.assertEqual(default(True), False) def test_bit_packing(self): - """ Test all string <=> bit packing functions """ + """Test all string <=> bit packing functions""" self.assertEqual(unpack_bitstring(b'\x55'), self.bits) self.assertEqual(pack_bitstring(self.bits), b'\x55') def test_longitudinal_redundancycheck(self): - """ Test the longitudinal redundancy check code """ + """Test the longitudinal redundancy check code""" self.assertTrue(checkLRC(self.data, 0x1c)) self.assertTrue(checkLRC(self.string, 0x0c)) def test_cyclic_redundancy_check(self): - """ Test the cyclic redundancy check code """ + """Test the cyclic redundancy check code""" self.assertTrue(checkCRC(self.data, 0xe2db)) self.assertTrue(checkCRC(self.string, 0x889e)) -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/test/test_version.py b/test/test_version.py index 532f38ab8..2ca99f1bd 100644 --- a/test/test_version.py +++ b/test/test_version.py @@ -1,25 +1,27 @@ #!/usr/bin/env python3 -""" Test version. """ +"""Test version.""" import unittest from pymodbus.version import Version + class ModbusVersionTest(unittest.TestCase): - """ Unittest for the pymodbus._version code. """ + """Unittest for the pymodbus._version code.""" def setUp(self): - """ Initializes the test environment """ + """Initialize the test environment""" def tearDown(self): - """ Cleans up the test environment """ + """Clean up the test environment""" def test_version_class(self): - """ Test version class. """ - version = Version('test', 1,2,3, "sometag") + """Test version class.""" + version = Version('test', 1, 2, 3, "sometag") self.assertEqual(version.short(), '1.2.3.sometag') self.assertEqual(str(version), '[test, version 1.2.3.sometag]') -#---------------------------------------------------------------------------# -# Main -#---------------------------------------------------------------------------# + +# ---------------------------------------------------------------------------# +# Main +# ---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main() diff --git a/tox.ini b/tox.ini index 7167d74e3..2598e4e46 100644 --- a/tox.ini +++ b/tox.ini @@ -73,10 +73,3 @@ commands = coverage combine coverage_reports coverage report --fail-under=85 --ignore-errors -[flake8] -exclude = .tox -ignore = D211,D400,E731 -max-line-length = 120 - -[pylint] -