Skip to content
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
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,8 @@ jobs:
run: |
python -m pip install --upgrade pip
python -m pip install .
python -m pip install ruff
- name: Lint
run: python -m ruff check .
- name: Test with python unittest
run: python -m unittest
79 changes: 79 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,82 @@ include = ["trsfile", "trsfile.*"]
[tool.setuptools_scm]
# This writes the computed version into the package at build time
write_to = "trsfile/VERSION.txt"

[tool.ruff]
# Exclude a variety of commonly ignored directories.
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".ipynb_checkpoints",
".mypy_cache",
".nox",
".pants.d",
".pyenv",
".pytest_cache",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
".vscode",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"site-packages",
"venv",
]

# Same as Black.
line-length = 88
indent-width = 4

# Assume Python 3.10
target-version = "py310"

[tool.ruff.lint]
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default.
select = ["E4", "E7", "E9", "F"]
ignore = []

# Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]
unfixable = []

# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"

[tool.ruff.format]
# Like Black, use double quotes for strings.
quote-style = "double"

# Like Black, indent with spaces, rather than tabs.
indent-style = "space"

# Like Black, respect magic trailing commas.
skip-magic-trailing-comma = false

# Like Black, automatically detect the appropriate line ending.
line-ending = "auto"

# Enable auto-formatting of code examples in docstrings. Markdown,
# reStructuredText code/literal blocks and doctests are all supported.
#
# This is currently disabled by default, but it is planned for this
# to be opt-out in the future.
docstring-code-format = false

# Set the line length limit used when formatting code snippets in
# docstrings.
#
# This only has an effect when the `docstring-code-format` setting is
# enabled.
docstring-code-line-length = "dynamic"
4 changes: 2 additions & 2 deletions tests/test_creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def test_write_closed(self):
with self.assertRaises(ValueError):
print(trs_traces)

def test_write_different_trace_sizes(self):
def test_write_different_trace_sizes2(self):
trace_count = 100
sample_count = 1000

Expand Down Expand Up @@ -316,7 +316,7 @@ def test_read(self):

def test_read_non_existing(self):
with self.assertRaises(FileNotFoundError):
with trsfile.open(self.tmp_path, 'r') as trs_traces:
with trsfile.open(self.tmp_path, 'r'):
pass

def test_append(self):
Expand Down
26 changes: 23 additions & 3 deletions tests/test_parametermap.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
from unittest import TestCase

from trsfile.parametermap import TraceSetParameterMap, TraceParameterDefinitionMap, TraceParameterMap, RawTraceData
from trsfile.standardparameters import StandardTraceSetParameters, StandardTraceParameters
from trsfile.traceparameter import *
from trsfile.parametermap import (
RawTraceData,
TraceParameterDefinitionMap,
TraceParameterMap,
TraceSetParameterMap,
)
from trsfile.standardparameters import (
StandardTraceParameters,
StandardTraceSetParameters,
)
from trsfile.traceparameter import (
BooleanArrayParameter,
ByteArrayParameter,
DoubleArrayParameter,
FloatArrayParameter,
IntegerArrayParameter,
LongArrayParameter,
ParameterType,
ShortArrayParameter,
StringParameter,
TraceParameterDefinition,
)
from io import BytesIO


class TestTraceSetParameterMap(TestCase):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_trsfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ def test_iterator(self):

def test_read_only(self):
"""Check if the TrsFile is read only"""
with self.assertRaises(TypeError) as cm:
with self.assertRaises(TypeError):
self.trs_file[0] = None

with self.assertRaises(TypeError) as cm:
with self.assertRaises(TypeError):
del self.trs_file[0]

def test_slice(self):
Expand Down
4 changes: 2 additions & 2 deletions trsfile/compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def __init__(self, *aliases):
self.aliases = set(aliases)

def __call__(self, obj):
if type(obj) == property:
if isinstance(obj, property):
obj.fget._aliases = self.aliases
else:
obj._aliases = self.aliases
Expand All @@ -34,7 +34,7 @@ def inner(*args, **kwargs):
for name, method in aliased_class_dict.items():
aliases = None

if (type(method) == property) and hasattr(method.fget, '_aliases'):
if isinstance(method, property) and hasattr(method.fget, '_aliases'):
aliases = method.fget._aliases
elif hasattr(method, '_aliases'):
aliases = method._aliases
Expand Down
8 changes: 4 additions & 4 deletions trsfile/converters/chipwhisperer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
from chipwhisperer.common.api.ProjectFormat import Project

from trsfile import TraceSet, Header, TracePadding, Trace, SampleCoding
from trsfile.parametermap import TraceSetParameterMap, TraceParameterDefinitionMap, TraceParameterMap
from trsfile.traceparameter import TraceParameterDefinition, ParameterType, StringParameter, ByteArrayParameter
from trsfile.parametermap import TraceSetParameterMap, TraceParameterMap
from trsfile.traceparameter import StringParameter, ByteArrayParameter


def to_trs(path_to_project: str, output_path: str, trace_index: int = 0):
Expand Down Expand Up @@ -37,7 +37,7 @@ def to_trs(path_to_project: str, output_path: str, trace_index: int = 0):
extra_parameters = CWSettings.read(
os.path.join(trace_folder, container.config.attr('prefix') + 'settings.cwset'))
traceset_parameters.update(extra_parameters)
except:
except Exception:
print('Warning: Failed to read additional settings. Trace reading will continue without additional settings.')

with TraceSet(path=output_path,
Expand All @@ -58,7 +58,7 @@ def to_trs(path_to_project: str, output_path: str, trace_index: int = 0):
def read_or_default(config, attr: str, default: Any = ''):
try:
return config.attr(attr)
except:
except Exception:
return default


Expand Down
4 changes: 2 additions & 2 deletions trsfile/engine/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def __init__(self, path, mode = 'x', **options):
try:
while self.path.is_dir():
time.sleep(0.001)
except:
except Exception:
pass

# Create the temporary folder and initialize this class
Expand Down Expand Up @@ -124,7 +124,7 @@ def __initialize_headers(self):

# Add any mandatory headers that are missing
for header in Header.get_mandatory():
if not header in headers:
if header not in headers:
headers[header] = header.default

# Store these default headers
Expand Down
2 changes: 1 addition & 1 deletion trsfile/engine/trs.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ def __create_headers(self, headers: Optional[Dict[Header, Any]]):

# Add any mandatory headers that are missing
for header in Header.get_mandatory():
if not header in self.headers:
if header not in self.headers:
self.headers[header] = header.default

# Make sure correct trs version is set
Expand Down
40 changes: 31 additions & 9 deletions trsfile/parametermap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,38 @@
import copy
import numbers
import warnings
from typing import Any, Union, List, Dict
from typing import Any, Union, List, Dict, TYPE_CHECKING

if TYPE_CHECKING:
from trsfile.common import Header

from trsfile.compatibility import alias, aliased
from trsfile.standardparameters import StandardTraceSetParameters, StandardTraceParameters
from trsfile.traceparameter import TraceSetParameter, TraceParameter, TraceParameterDefinition, ParameterType, \
BooleanArrayParameter, ByteArrayParameter, StringParameter, DoubleArrayParameter, IntegerArrayParameter, \
LongArrayParameter, ShortArrayParameter
from trsfile.utils import *
from trsfile.standardparameters import (
StandardTraceParameters,
StandardTraceSetParameters,
)
from trsfile.traceparameter import (
BooleanArrayParameter,
ByteArrayParameter,
DoubleArrayParameter,
IntegerArrayParameter,
LongArrayParameter,
ParameterType,
ShortArrayParameter,
StringParameter,
TraceParameter,
TraceParameterDefinition,
TraceSetParameter,
)
from trsfile.utils import (
encode_as_short,
read_parameter_name,
read_short,
StringKeyOrderedDict,
UTF_8,
)
from io import BytesIO

UTF_8 = 'utf-8'
SHORT_MIN = -2**15
SHORT_MAX = 2**15-1
INT_MIN = -2**31
Expand Down Expand Up @@ -120,7 +142,7 @@ def get_typed_parameter(param_value: ParameterValueType) -> type:
"""Get the subclass of TraceParameter needed to hold a given value
Throws an error if the value cannot be stored in any TraceParameter subclass"""
value_type = ParameterMapUtil._get_type(param_value)
if value_type == list:
if value_type is list:
value_type = ParameterMapUtil._get_type_of_list_elems(param_value)
return ParameterMapUtil.TYPE_TO_PARAMETER[value_type]

Expand Down Expand Up @@ -238,7 +260,7 @@ def add_standard_parameter(self, std_trace_set_param: StandardTraceSetParameters
self[std_trace_set_param.identifier] = typed_param(ParameterMapUtil.to_list_if_listable(value))
return self

def fill_from_headers(self, headers: Dict['Header', Any]) -> TraceSetParameterMap:
def fill_from_headers(self, headers: Dict["Header", Any]) -> TraceSetParameterMap:
"""Add to this trace set parameter map all data that is in the header
and for which standard trace set parameters exist.
Data that already exists in the map will not be overwritten.
Expand Down
2 changes: 1 addition & 1 deletion trsfile/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ def read_short(io_bytes: BytesIO):

class StringKeyOrderedDict(OrderedDict):
def __setitem__(self, key, value):
if not type(key) is str:
if not isinstance(key, str):
raise TypeError('The key for an item in a {} must be of type \'str\'.'.format(self.__class__.__name__))
super().__setitem__(key, value)