Skip to content

Linted tests, fixed duplicate-code failures #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ repos:
- id: pylint
name: pylint (library code)
types: [python]
exclude: "^(docs/|examples/|setup.py$)"
exclude: "^(docs/|tests/|examples/|setup.py$)"
- repo: local
hooks:
- id: pylint_examples
Expand All @@ -32,3 +32,11 @@ repos:
entry: /usr/bin/env bash -c
args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name $example; done)']
language: system
- repo: local
hooks:
- id: pylint_tests
name: pylint (tests code)
description: Run pylint rules on "tests/*.py" files
entry: /usr/bin/env bash -c
args: ['([[ ! -d "tests" ]] || for test in $(find . -path "./tests/*.py"); do pylint --disable=missing-docstring $test; done)']
language: system
8 changes: 4 additions & 4 deletions adafruit_imageload/bmp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ def load(file, *, bitmap=None, palette=None):
# bmp_header_length = int.from_bytes(file.read(4), 'little')
# print(bmp_header_length)
file.seek(0x12) # Width of the bitmap in pixels
width = int.from_bytes(file.read(4), "little")
_width = int.from_bytes(file.read(4), "little")
try:
height = int.from_bytes(file.read(4), "little")
_height = int.from_bytes(file.read(4), "little")
except OverflowError as error:
raise NotImplementedError(
"Negative height BMP files are not supported on builds without longint"
Expand All @@ -58,8 +58,8 @@ def load(file, *, bitmap=None, palette=None):

return indexed.load(
file,
width,
height,
_width,
_height,
data_start,
colors,
color_depth,
Expand Down
14 changes: 7 additions & 7 deletions adafruit_imageload/pnm/pgm/ascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def load(file, width, height, bitmap=None, palette=None):
Load a PGM ascii file (P2)
"""
data_start = file.tell() # keep this so we can rewind
palette_colors = set()
_palette_colors = set()
pixel = bytearray()
# build a set of all colors present in the file, so palette and bitmap can be constructed
while True:
Expand All @@ -30,14 +30,14 @@ def load(file, width, height, bitmap=None, palette=None):
break
if not byte.isdigit():
int_pixel = int("".join(["%c" % char for char in pixel]))
palette_colors.add(int_pixel)
_palette_colors.add(int_pixel)
pixel = bytearray()
pixel += byte
if palette:
palette = build_palette(palette, palette_colors)
palette = build_palette(palette, _palette_colors)
if bitmap:
bitmap = bitmap(width, height, len(palette_colors))
palette_colors = list(palette_colors)
bitmap = bitmap(width, height, len(_palette_colors))
_palette_colors = list(_palette_colors)
file.seek(data_start)
for y in range(height):
for x in range(width):
Expand All @@ -48,11 +48,11 @@ def load(file, width, height, bitmap=None, palette=None):
break
pixel += byte
int_pixel = int("".join(["%c" % char for char in pixel]))
bitmap[x, y] = palette_colors.index(int_pixel)
bitmap[x, y] = _palette_colors.index(int_pixel)
return bitmap, palette


def build_palette(palette_class, palette_colors):
def build_palette(palette_class, palette_colors): # pylint: disable=duplicate-code
"""
construct the Palette, and populate it with the set of palette_colors
"""
Expand Down
6 changes: 3 additions & 3 deletions adafruit_imageload/pnm/pgm/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def build_palette(palette_class, palette_colors):
"""
construct the Palette, and populate it with the set of palette_colors
"""
palette = palette_class(len(palette_colors))
_palette = palette_class(len(palette_colors))
for counter, color in enumerate(palette_colors):
palette[counter] = bytes([color, color, color])
return palette
_palette[counter] = bytes([color, color, color])
return _palette
24 changes: 14 additions & 10 deletions tests/displayio_shared_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
====================================================

The classes in this file are designed to emulate Circuitpython's displayio classes
for Bitmap and Palette. These mimic classes should have the same methods and interface as the real interface,
but with extra validation checks, warnings, and messages to facilitate debugging.
for Bitmap and Palette. These mimic classes should have the same methods and interface as the real
interface, but with extra validation checks, warnings, and messages to facilitate debugging.

Code that can be run successfully against these classes will have a good chance of
working correctly on hardware running Circuitpython, but without needing to upload code to a board
Expand All @@ -37,7 +37,7 @@
from typing import Union


class Bitmap_C_Interface(object):
class Bitmap_C_Interface:
"""
A class to simulate the displayio.Bitmap class for testing, based on
https://circuitpython.readthedocs.io/en/latest/shared-bindings/displayio/Bitmap.html
Expand Down Expand Up @@ -88,8 +88,10 @@ def __getitem__(self, item: Union[tuple, int]) -> bytearray:
raise RuntimeError(f"get position out of range {item}")
try:
return self.data[item]
except KeyError:
raise RuntimeError("no data at {} [{}]".format(self._decode(item), item))
except KeyError as err:
raise RuntimeError(
"no data at {} [{}]".format(self._decode(item), item)
) from err

def validate(self, detect_empty_image=True) -> None:
"""
Expand All @@ -103,8 +105,8 @@ def validate(self, detect_empty_image=True) -> None:
for x in range(self.width):
try:
seen_colors.add(self[x, y])
except KeyError:
raise ValueError(f"missing data at {x},{y}")
except KeyError as err:
raise ValueError(f"missing data at {x},{y}") from err
if detect_empty_image and len(seen_colors) < 2:
raise ValueError(
"image detected as only one color. set detect_empty_image=False to ignore"
Expand All @@ -131,7 +133,7 @@ def __str__(self) -> str:
return out


class Palette_C_Interface(object):
class Palette_C_Interface:
"""
A class to simulates the displayio.Palette class for testing, based on
https://circuitpython.readthedocs.io/en/latest/shared-bindings/displayio/Palette.html
Expand Down Expand Up @@ -191,8 +193,10 @@ def validate(self):
for i in range(self.num_colors):
try:
self.colors
except IndexError:
raise ValueError("missing color `{}` in palette color list".format(i))
except IndexError as err:
raise ValueError(
"missing color `{}` in palette color list".format(i)
) from err

def __str__(self):
"""
Expand Down
33 changes: 20 additions & 13 deletions tests/test_palette_c_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@


class TestPalette_C_Interface(TestCase):
def test_init_mono(self):
@staticmethod
def test_init_mono():
Palette_C_Interface(1)

def test_init_color(self):
@staticmethod
def test_init_color():
Palette_C_Interface(256)

def test_set_int(self):
@staticmethod
def test_set_int():
palette = Palette_C_Interface(1)
palette[0] = 0xFFFFFF

Expand All @@ -48,7 +51,8 @@ def test_get_int(self):
palette[0] = 0xFFFFFF
self.assertEqual(0xFFFFFF, palette[0])

def test_set_byte(self):
@staticmethod
def test_set_byte():
palette = Palette_C_Interface(1)
palette[0] = b"\xFF\xFF\xFF"

Expand All @@ -57,7 +61,8 @@ def test_get_byte(self):
palette[0] = b"\xFF\xFF\xFF"
self.assertEqual(b"\xFF\xFF\xFF", palette[0])

def test_set_bytearray(self):
@staticmethod
def test_set_bytearray():
palette = Palette_C_Interface(1)
palette[0] = bytearray(b"\xFF\xFF\xFF")

Expand All @@ -66,20 +71,21 @@ def test_prevents_out_of_range(self):
try:
palette[1] = 0xFFFFFF
self.fail("exception should have already thrown")
except ValueError as e:
if "greater than allowed" not in str(e):
except ValueError as err:
if "greater than allowed" not in str(err):
raise

def test_prevents_set_non_allowed(self):
palette = Palette_C_Interface(1)
try:
palette[0] = "\xFF\xFF\xFF" # attempt with a string, which is not allowed
self.fail("exception should have thrown")
except ValueError as e:
if "should be" not in str(e):
except ValueError as err:
if "should be" not in str(err):
raise

def test_validate_success(self):
@staticmethod
def test_validate_success():
palette = Palette_C_Interface(1)
palette[0] = b"\xFF\xFF\xFF"
palette.validate()
Expand All @@ -90,11 +96,12 @@ def test_validate_fails(self):
try:
palette.validate()
self.fail("exception should have thrown")
except IndexError as e:
if "palette was initialized" not in str(e):
except IndexError as err:
if "palette was initialized" not in str(err):
raise

def test_str(self):
@staticmethod
def test_str():
palette = Palette_C_Interface(1)
palette[0] = b"\xFF\xFF\xFF"
print(str(palette))
6 changes: 3 additions & 3 deletions tests/test_pbm_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@


class TestPbmLoad(TestCase):
def test_load_fails_with_no_header_data(self):
def test_load_fails_with_no_header_data(self): # pylint: disable=invalid-name
file = BytesIO(b"some initial binary data: \x00\x01")
try:
pnm.load(
file, b"P1", bitmap=Bitmap_C_Interface, palette=Palette_C_Interface
)
self.fail("should have failed")
except Exception as caught_exception:
except Exception as caught_exception: # pylint: disable=broad-except
if "Unsupported image format" not in str(caught_exception):
raise

Expand Down Expand Up @@ -102,7 +102,7 @@ def test_load_works_p4_binary(self):
self.assertEqual(15, bitmap.height)
bitmap.validate()

def test_load_works_p4_binary_high_res(self):
def test_load_works_p4_binary_high_res(self): # pylint: disable=invalid-name
test_file = os.path.join(
os.path.dirname(__file__),
"..",
Expand Down