diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..21c125c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +.py text eol=lf +.rst text eol=lf +.txt text eol=lf +.yaml text eol=lf +.toml text eol=lf +.license text eol=lf +.md text eol=lf diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70ade69..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,21 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries # # SPDX-License-Identifier: Unlicense repos: - - repo: https://github.com/python/black - rev: 23.3.0 - hooks: - - id: black - - repo: https://github.com/fsfe/reuse-tool - rev: v1.1.2 - hooks: - - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/pycqa/pylint - rev: v2.17.4 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index f945e92..0000000 --- a/.pylintrc +++ /dev/null @@ -1,399 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins=pylint.extensions.no_self_use - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call -disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=builtins.Exception diff --git a/README.rst b/README.rst index 88b8f6f..3be3044 100644 --- a/README.rst +++ b/README.rst @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_MIDI/actions/ :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff A CircuitPython helper for encoding/decoding MIDI packets over a MIDI or UART connection. diff --git a/adafruit_midi/__init__.py b/adafruit_midi/__init__.py index fa6b4cd..c629a22 100755 --- a/adafruit_midi/__init__.py +++ b/adafruit_midi/__init__.py @@ -25,8 +25,9 @@ https://github.com/adafruit/circuitpython/releases """ + try: - from typing import Union, Tuple, Any, List, Optional, Dict, BinaryIO + from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union except ImportError: pass @@ -64,7 +65,7 @@ def __init__( in_channel: Optional[Union[int, Tuple[int, ...]]] = None, out_channel: int = 0, in_buf_size: int = 30, - debug: bool = False + debug: bool = False, ): if midi_in is None and midi_out is None: raise ValueError("No midi_in or midi_out provided") @@ -132,9 +133,7 @@ def receive(self) -> Optional[MIDIMessage]: self._in_buf.extend(bytes_in) del bytes_in - (msg, endplusone, skipped) = MIDIMessage.from_message_bytes( - self._in_buf, self._in_channel - ) + (msg, endplusone, skipped) = MIDIMessage.from_message_bytes(self._in_buf, self._in_channel) if endplusone != 0: # This is not particularly efficient as it's copying most of bytearray # and deleting old one @@ -158,14 +157,12 @@ def send(self, msg: MIDIMessage, channel: Optional[int] = None) -> None: if isinstance(msg, MIDIMessage): msg.channel = channel # bytes(object) does not work in uPy - data = msg.__bytes__() # pylint: disable=unnecessary-dunder-call + data = msg.__bytes__() else: data = bytearray() for each_msg in msg: each_msg.channel = channel - data.extend( - each_msg.__bytes__() # pylint: disable=unnecessary-dunder-call - ) + data.extend(each_msg.__bytes__()) self._send(data, len(data)) diff --git a/adafruit_midi/control_change.py b/adafruit_midi/control_change.py index 9582bbc..97fd057 100644 --- a/adafruit_midi/control_change.py +++ b/adafruit_midi/control_change.py @@ -43,9 +43,7 @@ def __init__(self, control, value, *, channel=None): self._raise_valueerror_oor() def __bytes__(self): - return bytes( - [self._STATUS | (self.channel & self.CHANNELMASK), self.control, self.value] - ) + return bytes([self._STATUS | (self.channel & self.CHANNELMASK), self.control, self.value]) @classmethod def from_bytes(cls, msg_bytes): diff --git a/adafruit_midi/midi_message.py b/adafruit_midi/midi_message.py index 315efb0..9a89f48 100755 --- a/adafruit_midi/midi_message.py +++ b/adafruit_midi/midi_message.py @@ -26,7 +26,7 @@ __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MIDI.git" try: - from typing import Union, Tuple, Any, List, Optional + from typing import Any, List, Optional, Tuple, Union except ImportError: pass @@ -35,9 +35,7 @@ NOTE_OFFSET = [21, 23, 12, 14, 16, 17, 19] -def channel_filter( - channel: int, channel_spec: Optional[Union[int, Tuple[int, ...]]] -) -> bool: +def channel_filter(channel: int, channel_spec: Optional[Union[int, Tuple[int, ...]]]) -> bool: """ Utility function to return True iff the given channel matches channel_spec. """ @@ -103,9 +101,7 @@ def _raise_valueerror_oor() -> None: # Each element is ((status, mask), class) # order is more specific masks first # Add better type hints for status, mask, class referenced above - _statusandmask_to_class: List[ - Tuple[Tuple[Optional[bytes], Optional[int]], "MIDIMessage"] - ] = [] + _statusandmask_to_class: List[Tuple[Tuple[Optional[bytes], Optional[int]], "MIDIMessage"]] = [] def __init__(self, *, channel: Optional[int] = None) -> None: self._channel = channel # dealing with pylint inadequacy @@ -140,7 +136,6 @@ def register_message_type(cls) -> None: insert_idx, ((cls._STATUS, cls._STATUSMASK), cls) ) - # pylint: disable=too-many-arguments @classmethod def _search_eom_status( cls, @@ -158,7 +153,6 @@ def _search_eom_status( # Look for a status byte # Second rule of the MIDI club is status bytes have MSB set if buf[msgendidxplusone] & 0x80: - # pylint: disable=simplifiable-if-statement if buf[msgendidxplusone] == eom_status: good_termination = True else: @@ -215,7 +209,6 @@ def _match_message_status( msgendidxplusone, ) - # pylint: disable=too-many-locals,too-many-branches @classmethod def from_message_bytes( cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]] @@ -255,9 +248,7 @@ def from_message_bytes( complete_message, bad_termination, msgendidxplusone, - ) = cls._match_message_status( - midibytes, msgstartidx, msgendidxplusone, endidx - ) + ) = cls._match_message_status(midibytes, msgstartidx, msgendidxplusone, endidx) channel_match_orna = True if complete_message and not bad_termination: try: @@ -299,7 +290,6 @@ def __bytes__(self) -> bytes: # databytes value present to keep interface uniform but unused # A default method for constructing message objects with no data. # Returns the new object. - # pylint: disable=unused-argument @classmethod def from_bytes(cls, msg_bytes: bytes) -> "MIDIMessage": """Creates an object from the byte stream of the wire protocol @@ -310,10 +300,7 @@ def __str__(self) -> str: """Print an instance""" cls = self.__class__ if slots := getattr(cls, "_message_slots", None): - # pylint: disable=not-an-iterable - args = ", ".join( - f"{name}={repr(getattr(self, name, None))}" for name in slots - ) + args = ", ".join(f"{name}={repr(getattr(self, name, None))}" for name in slots) else: args = "..." return f"{self.__class__.__name__}({args})" diff --git a/adafruit_midi/note_off.py b/adafruit_midi/note_off.py index 3e0f942..38d80e4 100644 --- a/adafruit_midi/note_off.py +++ b/adafruit_midi/note_off.py @@ -22,7 +22,7 @@ __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MIDI.git" -class NoteOff(MIDIMessage): # pylint: disable=duplicate-code +class NoteOff(MIDIMessage): """Note Off Change MIDI message. :param note: The note (key) number either as an ``int`` (0-127) or a diff --git a/adafruit_midi/note_on.py b/adafruit_midi/note_on.py index eb3920c..3020d23 100644 --- a/adafruit_midi/note_on.py +++ b/adafruit_midi/note_on.py @@ -47,9 +47,7 @@ def __init__(self, note, velocity=127, *, channel=None): self._raise_valueerror_oor() def __bytes__(self): - return bytes( - [self._STATUS | (self.channel & self.CHANNELMASK), self.note, self.velocity] - ) + return bytes([self._STATUS | (self.channel & self.CHANNELMASK), self.note, self.velocity]) @classmethod def from_bytes(cls, msg_bytes): diff --git a/adafruit_midi/pitch_bend.py b/adafruit_midi/pitch_bend.py index c513593..a84cbeb 100644 --- a/adafruit_midi/pitch_bend.py +++ b/adafruit_midi/pitch_bend.py @@ -51,9 +51,7 @@ def __bytes__(self): @classmethod def from_bytes(cls, msg_bytes): - return cls( - msg_bytes[2] << 7 | msg_bytes[1], channel=msg_bytes[0] & cls.CHANNELMASK - ) + return cls(msg_bytes[2] << 7 | msg_bytes[1], channel=msg_bytes[0] & cls.CHANNELMASK) PitchBend.register_message_type() diff --git a/adafruit_midi/polyphonic_key_pressure.py b/adafruit_midi/polyphonic_key_pressure.py index f6ec395..810c24f 100644 --- a/adafruit_midi/polyphonic_key_pressure.py +++ b/adafruit_midi/polyphonic_key_pressure.py @@ -43,9 +43,7 @@ def __init__(self, note, pressure, *, channel=None): self._raise_valueerror_oor() def __bytes__(self): - return bytes( - [self._STATUS | (self.channel & self.CHANNELMASK), self.note, self.pressure] - ) + return bytes([self._STATUS | (self.channel & self.CHANNELMASK), self.note, self.pressure]) @classmethod def from_bytes(cls, msg_bytes): diff --git a/adafruit_midi/system_exclusive.py b/adafruit_midi/system_exclusive.py index 352e9e0..53cc3df 100644 --- a/adafruit_midi/system_exclusive.py +++ b/adafruit_midi/system_exclusive.py @@ -44,17 +44,12 @@ def __init__(self, manufacturer_id, data): super().__init__() def __bytes__(self): - return ( - bytes([self._STATUS]) - + self.manufacturer_id - + self.data - + bytes([self.ENDSTATUS]) - ) + return bytes([self._STATUS]) + self.manufacturer_id + self.data + bytes([self.ENDSTATUS]) @classmethod def from_bytes(cls, msg_bytes): # -1 on second arg is to avoid the ENDSTATUS which is passed - if msg_bytes[1] != 0: # pylint: disable=no-else-return + if msg_bytes[1] != 0: return cls(msg_bytes[1:2], msg_bytes[2:-1]) else: return cls(msg_bytes[1:4], msg_bytes[4:-1]) diff --git a/docs/api.rst b/docs/api.rst index c9cac8f..29b1262 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,6 +4,9 @@ .. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) .. use this format as the module name: "adafruit_foo.foo" +API Reference +############# + .. automodule:: adafruit_midi :members: diff --git a/docs/conf.py b/docs/conf.py index e69668e..8363ec4 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT @@ -48,9 +46,7 @@ creation_year = "2019" current_year = str(datetime.datetime.now().year) year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year + current_year if current_year == creation_year else creation_year + " - " + current_year ) copyright = year_duration + " Ladyada & Kevin J. Walters" author = "Ladyada & Kevin J. Walters" diff --git a/examples/midi_inoutdemo.py b/examples/midi_inoutdemo.py index e6b3faa..b35b5e2 100644 --- a/examples/midi_inoutdemo.py +++ b/examples/midi_inoutdemo.py @@ -6,8 +6,6 @@ import usb_midi import adafruit_midi - -# pylint: disable=unused-import from adafruit_midi.channel_pressure import ChannelPressure from adafruit_midi.control_change import ControlChange from adafruit_midi.midi_message import MIDIUnknownEvent @@ -57,11 +55,7 @@ if 0 <= new_note <= 127: midi.send(NoteOn(new_note, msg_in.velocity)) - elif ( - isinstance(msg_in, NoteOff) - or isinstance(msg_in, NoteOn) - and msg_in.velocity == 0 - ): + elif isinstance(msg_in, NoteOff) or isinstance(msg_in, NoteOn) and msg_in.velocity == 0: for offset in major_chord: new_note = msg_in.note + offset if 0 <= new_note <= 127: diff --git a/examples/midi_intest1.py b/examples/midi_intest1.py index 3bb5037..a22a5a2 100644 --- a/examples/midi_intest1.py +++ b/examples/midi_intest1.py @@ -7,7 +7,6 @@ import adafruit_midi -# pylint: disable=unused-import # from adafruit_midi.channel_pressure import ChannelPressure from adafruit_midi.control_change import ControlChange from adafruit_midi.note_off import NoteOff diff --git a/examples/midi_memorycheck.py b/examples/midi_memorycheck.py index d03ab6b..a63cbce 100644 --- a/examples/midi_memorycheck.py +++ b/examples/midi_memorycheck.py @@ -3,7 +3,6 @@ # Check memory usage -# pylint: disable=multiple-statements,unused-import,wrong-import-position,no-member # The disable for no-member should not really be required # probably a difference between Python 3 module and micropython diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..2dc0ceb --- /dev/null +++ b/ruff.toml @@ -0,0 +1,109 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +preview = true +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + "PLR0913", # too-many-arguments + "PLR0915", # too-many-statements + "PLR0917", # too-many-positional-arguments + "PLR0904", # too-many-public-methods + "PLR0912", # too-many-branches + "PLR0916", # too-many-boolean-expressions + "PLR6301", # could-be-static no-self-use + "PLC0415", # import outside toplevel + "PLC2701", # private import + "PLC2801", # dunder bytes call +] + +[format] +line-ending = "lf" diff --git a/tests/test_MIDIMessage_unittests.py b/tests/test_MIDIMessage_unittests.py index 1b938ad..ab1f271 100644 --- a/tests/test_MIDIMessage_unittests.py +++ b/tests/test_MIDIMessage_unittests.py @@ -2,14 +2,11 @@ # # SPDX-License-Identifier: MIT -# pylint: disable=invalid-name - import os import unittest verbose = int(os.getenv("TESTVERBOSE", "2")) -# pylint: disable=wrong-import-position # adafruit_midi had an import usb_midi import sys @@ -26,12 +23,9 @@ from adafruit_midi.note_on import NoteOn from adafruit_midi.system_exclusive import SystemExclusive -# pylint: enable=wrong-import-position - -# pylint: disable=invalid-name class Test_MIDIMessage_from_message_byte_tests(unittest.TestCase): - def test_NoteOn_basic(self): # pylint: disable=invalid-name + def test_NoteOn_basic(self): data = bytes([0x90, 0x30, 0x7F]) ichannel = 0 @@ -46,7 +40,7 @@ def test_NoteOn_basic(self): # pylint: disable=invalid-name self.assertEqual(skipped, 0) self.assertEqual(msg.channel, 0) - def test_NoteOn_awaitingthirdbyte(self): # pylint: disable=invalid-name + def test_NoteOn_awaitingthirdbyte(self): data = bytes([0x90, 0x30]) ichannel = 0 @@ -66,7 +60,7 @@ def test_NoteOn_awaitingthirdbyte(self): # pylint: disable=invalid-name ) self.assertEqual(skipped, 0) - def test_NoteOn_predatajunk(self): # pylint: disable=invalid-name + def test_NoteOn_predatajunk(self): data = bytes([0x20, 0x64, 0x90, 0x30, 0x32]) ichannel = 0 @@ -85,7 +79,7 @@ def test_NoteOn_predatajunk(self): # pylint: disable=invalid-name self.assertEqual(skipped, 2) self.assertEqual(msg.channel, 0) - def test_NoteOn_prepartialsysex(self): # pylint: disable=invalid-name + def test_NoteOn_prepartialsysex(self): data = bytes([0x01, 0x02, 0x03, 0x04, 0xF7, 0x90, 0x30, 0x32]) ichannel = 0 @@ -121,7 +115,7 @@ def test_NoteOn_prepartialsysex(self): # pylint: disable=invalid-name self.assertEqual(skipped, 0) self.assertEqual(msg.channel, 0) - def test_NoteOn_postNoteOn(self): # pylint: disable=invalid-name + def test_NoteOn_postNoteOn(self): data = bytes([0x90 | 0x08, 0x30, 0x7F, 0x90 | 0x08, 0x37, 0x64]) ichannel = 8 @@ -136,7 +130,7 @@ def test_NoteOn_postNoteOn(self): # pylint: disable=invalid-name self.assertEqual(skipped, 0) self.assertEqual(msg.channel, 8) - def test_NoteOn_postpartialNoteOn(self): # pylint: disable=invalid-name + def test_NoteOn_postpartialNoteOn(self): data = bytes([0x90, 0x30, 0x7F, 0x90, 0x37]) ichannel = 0 @@ -151,7 +145,7 @@ def test_NoteOn_postpartialNoteOn(self): # pylint: disable=invalid-name self.assertEqual(skipped, 0) self.assertEqual(msg.channel, 0) - def test_NoteOn_preotherchannel(self): # pylint: disable=invalid-name + def test_NoteOn_preotherchannel(self): data = bytes([0x90 | 0x05, 0x30, 0x7F, 0x90 | 0x03, 0x37, 0x64]) ichannel = 3 @@ -166,7 +160,7 @@ def test_NoteOn_preotherchannel(self): # pylint: disable=invalid-name self.assertEqual(skipped, 0) self.assertEqual(msg.channel, 3) - def test_NoteOn_preotherchannelplusintermediatejunk( # pylint: disable=invalid-name + def test_NoteOn_preotherchannelplusintermediatejunk( self, ): data = bytes([0x90 | 0x05, 0x30, 0x7F, 0x00, 0x00, 0x90 | 0x03, 0x37, 0x64]) @@ -179,13 +173,11 @@ def test_NoteOn_preotherchannelplusintermediatejunk( # pylint: disable=invalid- self.assertIsInstance(msg, NoteOn) self.assertEqual(msg.note, 0x37) self.assertEqual(msg.velocity, 0x64) - self.assertEqual( - msgendidxplusone, 8, "Both messages and junk are removed from buffer" - ) + self.assertEqual(msgendidxplusone, 8, "Both messages and junk are removed from buffer") self.assertEqual(skipped, 0) self.assertEqual(msg.channel, 3) - def test_NoteOn_wrongchannel(self): # pylint: disable=invalid-name + def test_NoteOn_wrongchannel(self): data = bytes([0x95, 0x30, 0x7F]) ichannel = 3 @@ -197,7 +189,7 @@ def test_NoteOn_wrongchannel(self): # pylint: disable=invalid-name self.assertEqual(msgendidxplusone, 3, "wrong channel message discarded") self.assertEqual(skipped, 0) - def test_NoteOn_partialandpreotherchannel1(self): # pylint: disable=invalid-name + def test_NoteOn_partialandpreotherchannel1(self): data = bytes([0x95, 0x30, 0x7F, 0x93]) ichannel = 3 @@ -206,12 +198,10 @@ def test_NoteOn_partialandpreotherchannel1(self): # pylint: disable=invalid-nam ) self.assertIsNone(msg) - self.assertEqual( - msgendidxplusone, 3, "first message discarded, second partial left" - ) + self.assertEqual(msgendidxplusone, 3, "first message discarded, second partial left") self.assertEqual(skipped, 0) - def test_NoteOn_partialandpreotherchannel2(self): # pylint: disable=invalid-name + def test_NoteOn_partialandpreotherchannel2(self): data = bytes([0x95, 0x30, 0x7F, 0x93, 0x37]) ichannel = 3 @@ -220,12 +210,10 @@ def test_NoteOn_partialandpreotherchannel2(self): # pylint: disable=invalid-nam ) self.assertIsNone(msg) - self.assertEqual( - msgendidxplusone, 3, "first message discarded, second partial left" - ) + self.assertEqual(msgendidxplusone, 3, "first message discarded, second partial left") self.assertEqual(skipped, 0) - def test_NoteOn_constructor_int(self): # pylint: disable=invalid-name + def test_NoteOn_constructor_int(self): object1 = NoteOn(60, 0x7F) self.assertEqual(object1.note, 60) @@ -250,7 +238,7 @@ def test_NoteOn_constructor_int(self): # pylint: disable=invalid-name self.assertEqual(object4.velocity, 127) self.assertIsNone(object4.channel) - def test_SystemExclusive_NoteOn(self): # pylint: disable=invalid-name + def test_SystemExclusive_NoteOn(self): data = bytes([0xF0, 0x42, 0x01, 0x02, 0x03, 0x04, 0xF7, 0x90 | 14, 0x30, 0x60]) ichannel = 14 @@ -262,9 +250,7 @@ def test_SystemExclusive_NoteOn(self): # pylint: disable=invalid-name self.assertEqual(msg.manufacturer_id, bytes([0x42])) # Korg self.assertEqual(msg.data, bytes([0x01, 0x02, 0x03, 0x04])) self.assertEqual(msgendidxplusone, 7) - self.assertEqual( - skipped, 0, "If SystemExclusive class is imported then this must be 0" - ) + self.assertEqual(skipped, 0, "If SystemExclusive class is imported then this must be 0") self.assertIsNone(msg.channel) (msg, msgendidxplusone, skipped) = adafruit_midi.MIDIMessage.from_message_bytes( @@ -278,7 +264,7 @@ def test_SystemExclusive_NoteOn(self): # pylint: disable=invalid-name self.assertEqual(skipped, 0) self.assertEqual(msg.channel, 14) - def test_SystemExclusive_NoteOn_premalterminatedsysex( # pylint: disable=invalid-name + def test_SystemExclusive_NoteOn_premalterminatedsysex( self, ): data = bytes([0xF0, 0x42, 0x01, 0x02, 0x03, 0x04, 0xF0, 0x90, 0x30, 0x32]) @@ -291,11 +277,9 @@ def test_SystemExclusive_NoteOn_premalterminatedsysex( # pylint: disable=invali self.assertIsNone(msg) self.assertEqual(msgendidxplusone, 7) - self.assertEqual( - skipped, 0, "If SystemExclusive class is imported then this must be 0" - ) + self.assertEqual(skipped, 0, "If SystemExclusive class is imported then this must be 0") - def test_Unknown_SinglebyteStatus(self): # pylint: disable=invalid-name + def test_Unknown_SinglebyteStatus(self): data = bytes([0xFD]) ichannel = 0 @@ -308,7 +292,7 @@ def test_Unknown_SinglebyteStatus(self): # pylint: disable=invalid-name self.assertEqual(skipped, 0) self.assertIsNone(msg.channel) - def test_Empty(self): # pylint: disable=invalid-name + def test_Empty(self): data = bytes([]) ichannel = 0 @@ -321,10 +305,8 @@ def test_Empty(self): # pylint: disable=invalid-name self.assertEqual(skipped, 0) -class Test_MIDIMessage_NoteOn_constructor( - unittest.TestCase -): # pylint: disable=invalid-name - def test_NoteOn_constructor_string(self): # pylint: disable=invalid-name +class Test_MIDIMessage_NoteOn_constructor(unittest.TestCase): + def test_NoteOn_constructor_string(self): object1 = NoteOn("C4", 0x64) self.assertEqual(object1.note, 60) self.assertEqual(object1.velocity, 0x64) @@ -337,37 +319,35 @@ def test_NoteOn_constructor_string(self): # pylint: disable=invalid-name self.assertEqual(object3.note, 61) self.assertEqual(object3.velocity, 0) - def test_NoteOn_constructor_valueerror1(self): # pylint: disable=invalid-name + def test_NoteOn_constructor_valueerror1(self): with self.assertRaises(ValueError): - NoteOn(60, 0x80) # pylint is happier if return value not stored + NoteOn(60, 0x80) - def test_NoteOn_constructor_valueerror2(self): # pylint: disable=invalid-name + def test_NoteOn_constructor_valueerror2(self): with self.assertRaises(ValueError): NoteOn(-1, 0x7F) - def test_NoteOn_constructor_valueerror3(self): # pylint: disable=invalid-name + def test_NoteOn_constructor_valueerror3(self): with self.assertRaises(ValueError): NoteOn(128, 0x7F) - def test_NoteOn_constructor_upperrange1(self): # pylint: disable=invalid-name + def test_NoteOn_constructor_upperrange1(self): object1 = NoteOn("G9", 0x7F) self.assertEqual(object1.note, 127) self.assertEqual(object1.velocity, 0x7F) - def test_NoteOn_constructor_upperrange2(self): # pylint: disable=invalid-name + def test_NoteOn_constructor_upperrange2(self): with self.assertRaises(ValueError): NoteOn("G#9", 0x7F) # just above max note - def test_NoteOn_constructor_bogusstring(self): # pylint: disable=invalid-name + def test_NoteOn_constructor_bogusstring(self): with self.assertRaises(ValueError): NoteOn("CC4", 0x7F) -class Test_MIDIMessage_NoteOff_constructor( # pylint: disable=invalid-name - unittest.TestCase -): +class Test_MIDIMessage_NoteOff_constructor(unittest.TestCase): # mostly cut and paste from NoteOn above - def test_NoteOff_constructor_string(self): # pylint: disable=invalid-name + def test_NoteOff_constructor_string(self): object1 = NoteOff("C4", 0x64) self.assertEqual(object1.note, 60) self.assertEqual(object1.velocity, 0x64) @@ -384,28 +364,28 @@ def test_NoteOff_constructor_string(self): # pylint: disable=invalid-name self.assertEqual(object4.note, 61) self.assertEqual(object4.velocity, 0) - def test_NoteOff_constructor_valueerror1(self): # pylint: disable=invalid-name + def test_NoteOff_constructor_valueerror1(self): with self.assertRaises(ValueError): NoteOff(60, 0x80) - def test_NoteOff_constructor_valueerror2(self): # pylint: disable=invalid-name + def test_NoteOff_constructor_valueerror2(self): with self.assertRaises(ValueError): NoteOff(-1, 0x7F) - def test_NoteOff_constructor_valueerror3(self): # pylint: disable=invalid-name + def test_NoteOff_constructor_valueerror3(self): with self.assertRaises(ValueError): NoteOff(128, 0x7F) - def test_NoteOff_constructor_upperrange1(self): # pylint: disable=invalid-name + def test_NoteOff_constructor_upperrange1(self): object1 = NoteOff("G9", 0x7F) self.assertEqual(object1.note, 127) self.assertEqual(object1.velocity, 0x7F) - def test_NoteOff_constructor_upperrange2(self): # pylint: disable=invalid-name + def test_NoteOff_constructor_upperrange2(self): with self.assertRaises(ValueError): NoteOff("G#9", 0x7F) # just above max note - def test_NoteOff_constructor_bogusstring(self): # pylint: disable=invalid-name + def test_NoteOff_constructor_bogusstring(self): with self.assertRaises(ValueError): NoteOff("CC4", 0x7F) diff --git a/tests/test_MIDI_unittests.py b/tests/test_MIDI_unittests.py index 178a760..1d320fa 100644 --- a/tests/test_MIDI_unittests.py +++ b/tests/test_MIDI_unittests.py @@ -2,8 +2,6 @@ # # SPDX-License-Identifier: MIT -# pylint: disable=invalid-name - import os import random import unittest @@ -11,7 +9,6 @@ verbose = int(os.getenv("TESTVERBOSE", "2")) -# pylint: disable=wrong-import-position # adafruit_midi had an import usb_midi import sys @@ -31,11 +28,9 @@ from adafruit_midi.pitch_bend import PitchBend from adafruit_midi.system_exclusive import SystemExclusive -# pylint: enable=wrong-import-position - # For loopback/echo tests -def MIDI_mocked_both_loopback(in_c, out_c): # pylint: disable=invalid-name +def MIDI_mocked_both_loopback(in_c, out_c): usb_data = bytearray() def write(buffer, length): @@ -58,14 +53,13 @@ def read(length): return midi -def MIDI_mocked_receive(in_c, data, read_sizes): # pylint: disable=invalid-name +def MIDI_mocked_receive(in_c, data, read_sizes): usb_data = bytearray(data) chunks = read_sizes chunk_idx = 0 def read(length): nonlocal usb_data, chunks, chunk_idx - # pylint: disable=no-else-return if length != 0 and chunk_idx < len(chunks): # min() to ensure we only read what's asked for and present poppedbytes = usb_data[0 : min(length, chunks[chunk_idx])] @@ -76,7 +70,7 @@ def read(length): chunks[chunk_idx] -= len(poppedbytes) return bytes(poppedbytes) else: - return bytes() + return b"" mockedportin = Mock() mockedportin.read = read @@ -87,8 +81,7 @@ def read(length): return midi -class Test_MIDI_constructor(unittest.TestCase): # pylint: disable=invalid-name - # pylint: enable=invalid-name +class Test_MIDI_constructor(unittest.TestCase): def test_no_inout(self): # constructor likes a bit of in out with self.assertRaises(ValueError): @@ -96,8 +89,7 @@ def test_no_inout(self): class Test_MIDI(unittest.TestCase): - # pylint: disable=too-many-branches - def test_captured_data_one_byte_reads(self): # pylint: disable=invalid-name + def test_captured_data_one_byte_reads(self): channel = 0 # From an M-Audio AXIOM controller raw_data = bytearray( @@ -110,7 +102,7 @@ def test_captured_data_one_byte_reads(self): # pylint: disable=invalid-name ) midi = MIDI_mocked_receive(channel, raw_data, [1] * len(raw_data)) - for unused in range(100): # pylint: disable=unused-variable + for unused in range(100): msg = midi.receive() if msg is not None: break @@ -121,7 +113,7 @@ def test_captured_data_one_byte_reads(self): # pylint: disable=invalid-name # for loops currently absorb any Nones but could # be set to read precisely the expected number... - for unused in range(100): # pylint: disable=unused-variable + for unused in range(100): msg = midi.receive() if msg is not None: break @@ -129,7 +121,7 @@ def test_captured_data_one_byte_reads(self): # pylint: disable=invalid-name self.assertEqual(msg.pressure, 0x10) self.assertEqual(msg.channel, channel) - for unused in range(100): # pylint: disable=unused-variable + for unused in range(100): msg = midi.receive() if msg is not None: break @@ -138,7 +130,7 @@ def test_captured_data_one_byte_reads(self): # pylint: disable=invalid-name self.assertEqual(msg.velocity, 0x66) self.assertEqual(msg.channel, channel) - for unused in range(100): # pylint: disable=unused-variable + for unused in range(100): msg = midi.receive() if msg is not None: break @@ -147,7 +139,7 @@ def test_captured_data_one_byte_reads(self): # pylint: disable=invalid-name self.assertEqual(msg.value, 0x08) self.assertEqual(msg.channel, channel) - for unused in range(100): # pylint: disable=unused-variable + for unused in range(100): msg = midi.receive() if msg is not None: break @@ -156,7 +148,7 @@ def test_captured_data_one_byte_reads(self): # pylint: disable=invalid-name self.assertEqual(msg.velocity, 0x74) self.assertEqual(msg.channel, channel) - for unused in range(100): # pylint: disable=unused-variable + for unused in range(100): msg = midi.receive() if msg is not None: break @@ -164,11 +156,11 @@ def test_captured_data_one_byte_reads(self): # pylint: disable=invalid-name self.assertEqual(msg.pitch_bend, 8195) self.assertEqual(msg.channel, channel) - for unused in range(100): # pylint: disable=unused-variable + for unused in range(100): msg = midi.receive() self.assertIsNone(msg) - def test_unknown_before_NoteOn(self): # pylint: disable=invalid-name + def test_unknown_before_NoteOn(self): channel = 0 # From an M-Audio AXIOM controller raw_data = bytes( @@ -191,7 +183,7 @@ def test_unknown_before_NoteOn(self): # pylint: disable=invalid-name self.assertEqual(msg.channel, channel) # See https://github.com/adafruit/Adafruit_CircuitPython_MIDI/issues/8 - def test_running_status_when_implemented(self): # pylint: disable=invalid-name + def test_running_status_when_implemented(self): channel = 8 raw_data = ( bytes(NoteOn("C5", 0x7F, channel=channel)) @@ -200,10 +192,10 @@ def test_running_status_when_implemented(self): # pylint: disable=invalid-name ) midi = MIDI_mocked_receive(channel, raw_data, [3 + 3 + 2 + 3 + 3]) - self.assertIsInstance(midi, adafruit_midi.MIDI) # silence pylint! + self.assertIsInstance(midi, adafruit_midi.MIDI) # self.assertEqual(TOFINISH, WHENIMPLEMENTED) - def test_somegood_somemissing_databytes(self): # pylint: disable=invalid-name + def test_somegood_somemissing_databytes(self): channel = 8 raw_data = ( bytes(NoteOn("C5", 0x7F, channel=channel)) @@ -290,26 +282,23 @@ def test_smallsysex_bytes_type(self): self.assertEqual(message.manufacturer_id, bytes([0x1F])) self.assertIsInstance(message.manufacturer_id, bytes) - # check this really is immutable (pylint also picks this up!) + # check this really is immutable with self.assertRaises(TypeError): - message.data[0] = 0 # pylint: disable=unsupported-assignment-operation + message.data[0] = 0 self.assertEqual(message.data, bytes([100, 150, 200])) self.assertIsInstance(message.data, bytes) - # pylint: disable=too-many-locals def test_larger_than_buffer_sysex(self): channel = 0 monster_data_len = 500 raw_data = ( bytes(NoteOn("C5", 0x7F, channel=channel)) - + bytes( - SystemExclusive([0x02], [d & 0x7F for d in range(monster_data_len)]) - ) + + bytes(SystemExclusive([0x02], [d & 0x7F for d in range(monster_data_len)])) + bytes(NoteOn("D5", 0x7F, channel=channel)) ) midi = MIDI_mocked_receive(channel, raw_data, [len(raw_data)]) - buffer_len = midi._in_buf_size # pylint: disable=protected-access + buffer_len = midi._in_buf_size self.assertTrue( monster_data_len > buffer_len, "checking our SysEx truly is larger than buffer", @@ -322,7 +311,6 @@ def test_larger_than_buffer_sysex(self): self.assertEqual(msg1.channel, channel) # (Ab)using python's rounding down for negative division - # pylint: disable=unused-variable for unused in range(-(-(1 + 1 + monster_data_len + 1) // buffer_len) - 1): msg2 = midi.receive() self.assertIsNone(msg2) @@ -349,8 +337,7 @@ def test_larger_than_buffer_sysex(self): self.assertIsNone(msg6) -# pylint does not like mock_calls - must be a better way to handle this? -# pylint: disable=no-member +# mock_calls handling class Test_MIDI_send(unittest.TestCase): def test_send_basic_single(self): # def printit(buffer, len): @@ -363,48 +350,32 @@ def test_send_basic_single(self): # Test sending some NoteOn and NoteOff to various channels nextcall = 0 midi.send(NoteOn(0x60, 0x7F)) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x92\x60\x7f", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x92\x60\x7f", 3)) nextcall += 1 midi.send(NoteOn(0x64, 0x3F)) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x92\x64\x3f", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x92\x64\x3f", 3)) nextcall += 1 midi.send(NoteOn(0x67, 0x1F)) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x92\x67\x1f", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x92\x67\x1f", 3)) nextcall += 1 midi.send(NoteOn(0x60, 0x00)) # Alternative to NoteOff - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x92\x60\x00", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x92\x60\x00", 3)) nextcall += 1 midi.send(NoteOff(0x64, 0x01)) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x82\x64\x01", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x82\x64\x01", 3)) nextcall += 1 midi.send(NoteOff(0x67, 0x02)) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x82\x67\x02", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x82\x67\x02", 3)) nextcall += 1 # Setting channel to non default midi.send(NoteOn(0x6C, 0x7F), channel=9) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x99\x6c\x7f", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x99\x6c\x7f", 3)) nextcall += 1 midi.send(NoteOff(0x6C, 0x7F), channel=9) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x89\x6c\x7f", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x89\x6c\x7f", 3)) nextcall += 1 def test_send_badnotes(self): @@ -415,9 +386,7 @@ def test_send_badnotes(self): # Test sending some NoteOn and NoteOff to various channels nextcall = 0 midi.send(NoteOn(60, 0x7F)) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x92\x3c\x7f", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x92\x3c\x7f", 3)) nextcall += 1 with self.assertRaises(ValueError): midi.send(NoteOn(64, 0x80)) # Velocity > 127 - illegal value @@ -427,9 +396,7 @@ def test_send_badnotes(self): # test after exceptions to ensure sending is still ok midi.send(NoteOn(72, 0x7F)) - self.assertEqual( - mockedportout.write.mock_calls[nextcall], call(b"\x92\x48\x7f", 3) - ) + self.assertEqual(mockedportout.write.mock_calls[nextcall], call(b"\x92\x48\x7f", 3)) nextcall += 1 def test_send_basic_sequences(self): @@ -460,7 +427,7 @@ def test_send_basic_sequences(self): ) nextcall += 1 - def test_termination_with_random_data(self): # pylint: disable=invalid-name + def test_termination_with_random_data(self): """Test with a random stream of bytes to ensure that the parsing code termates and returns, i.e. does not go into any infinite loops. """ @@ -470,7 +437,7 @@ def test_termination_with_random_data(self): # pylint: disable=invalid-name midi = MIDI_mocked_receive(channel, raw_data, [len(raw_data)]) noinfiniteloops = False - for unused in range(len(raw_data)): # pylint: disable=unused-variable + for unused in range(len(raw_data)): midi.receive() # not interested in returned tuple noinfiniteloops = True # interested in getting to here diff --git a/tests/test_note_parser.py b/tests/test_note_parser.py index 2d29373..179fc8a 100644 --- a/tests/test_note_parser.py +++ b/tests/test_note_parser.py @@ -7,7 +7,6 @@ verbose = int(os.getenv("TESTVERBOSE", "2")) -# pylint: disable=wrong-import-position # adafruit_midi had an import usb_midi import sys @@ -18,8 +17,6 @@ from adafruit_midi.midi_message import note_parser -# pylint: enable=wrong-import-position - class Test_note_parser(unittest.TestCase): def text_int_passthru(self):