Skip to content

Commit c116c76

Browse files
authored
Fix sonarqube issues (#328)
* fix pytest.raises syntax in audio test * fix pytest.raises syntax in core_api_base test * fix pytest.raises syntax in mseed test * replace float equality asserts with np.isclose() * pass AudioData.write() subtype parameter as keyword-only * extract nested conditions * fix multirule noqa syntax * set subtype as keyword-only parameter * remove double negation in equality test * remove nested conditions * set sx as keyword-only parameter in write() method * use typing.Generator in return type * remove redundant return * extract nested conditions * use list comprehension * rename builtin format variable * comment empty function rather than raw pass * rename unused request variable with _ * remove redundant list comprehension * refactor pytest.raise call * add typing.Generator annotation * add docstring in empty dunder override * fix pytest raises syntax * remove unnecessary list assignment * fix pytest syntax * replace unused var name with _ * test_spectro linting * fix pytest raises syntax
1 parent b3c1215 commit c116c76

20 files changed

Lines changed: 136 additions & 150 deletions

src/osekit/core_api/audio_data.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -263,8 +263,8 @@ def get_value_calibrated(self) -> np.ndarray:
263263
def write(
264264
self,
265265
folder: Path,
266-
subtype: str | None = None,
267266
*,
267+
subtype: str | None = None,
268268
link: bool = False,
269269
) -> None:
270270
"""Write the audio data to file.
@@ -349,13 +349,12 @@ def split(
349349
The list of ``AudioData`` subdata objects.
350350
351351
"""
352-
normalization_values = (
353-
None
354-
if not pass_normalization
355-
else self.normalization_values
356-
if any(self.normalization_values.values())
357-
else self.get_normalization_values()
358-
)
352+
if not pass_normalization:
353+
normalization_values = None
354+
elif any(self.normalization_values.values()):
355+
normalization_values = self.normalization_values
356+
else:
357+
normalization_values = self.get_normalization_values()
359358
return super().split(
360359
nb_subdata=nb_subdata,
361360
normalization_values=normalization_values,
@@ -440,13 +439,12 @@ def split_frames(
440439
if stop_frame == -1
441440
else self.begin + Timedelta(seconds=stop_frame / self.sample_rate)
442441
)
443-
normalization_values = (
444-
None
445-
if not pass_normalization
446-
else self.normalization_values
447-
if any(self.normalization_values.values())
448-
else self.get_normalization_values()
449-
)
442+
if not pass_normalization:
443+
normalization_values = None
444+
elif any(self.normalization_values.values()):
445+
normalization_values = self.normalization_values
446+
else:
447+
normalization_values = self.get_normalization_values()
450448
return AudioData.from_files(
451449
list(self.files),
452450
start_timestamp,

src/osekit/core_api/audio_dataset.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,13 @@ def instrument(self, instrument: Instrument | None) -> None:
100100
for data in self.data:
101101
data.instrument = instrument
102102

103+
@staticmethod
103104
def _write_audio(
104-
self,
105105
data: AudioData,
106106
folder: Path,
107107
subtype: str | None = None,
108-
link: bool = False, # noqa: FBT001, FBT002,
108+
*,
109+
link: bool = False,
109110
) -> AudioData:
110111
"""Write audio data to disk."""
111112
data.write(folder=folder, subtype=subtype, link=link)
@@ -114,28 +115,29 @@ def _write_audio(
114115
def write(
115116
self,
116117
folder: Path,
117-
subtype: str | None = None,
118-
link: bool = False, # noqa: FBT001, FBT002,
119118
first: int = 0,
120119
last: int | None = None,
120+
*,
121+
subtype: str | None = None,
122+
link: bool = False,
121123
) -> None:
122124
"""Write all data objects in the specified folder.
123125
124126
Parameters
125127
----------
126128
folder: Path
127129
Folder in which to write the data.
130+
first: int
131+
Index of the first ``AudioData`` object to write.
132+
last: int | None
133+
Index after the last ``AudioData`` object to write.
128134
subtype: str | None
129135
Subtype as provided by the soundfile module.
130136
Defaulted as the default 16-bit PCM for WAV audio files.
131137
link: bool
132138
If ``True``, each ``AudioData`` will be bound to the corresponding written file.
133139
Their items will be replaced with a single item, which will match the whole
134140
new ``AudioFile``.
135-
first: int
136-
Index of the first ``AudioData`` object to write.
137-
last: int | None
138-
Index after the last ``AudioData`` object to write.
139141
140142
141143
"""

src/osekit/core_api/base_item.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,4 @@ def __eq__(self, other: BaseItem[TFile]) -> bool:
8181
return False
8282
if self.begin != other.begin:
8383
return False
84-
return not self.end != other.end
84+
return self.end == other.end

src/osekit/core_api/spectro_data.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -244,13 +244,8 @@ def v_lim(self) -> tuple[float, float]:
244244

245245
@v_lim.setter
246246
def v_lim(self, v_lim: tuple[float, float] | None) -> None:
247-
v_lim = (
248-
v_lim
249-
if v_lim is not None
250-
else (-120.0, 0.0)
251-
if self.db_type == "FS"
252-
else (0.0, 170.0)
253-
)
247+
if v_lim is None:
248+
v_lim = (-120.0, 0.0) if self.db_type == "FS" else (0.0, 170.0)
254249
self._v_lim = v_lim
255250

256251
def get_value(self) -> np.ndarray:
@@ -527,8 +522,8 @@ def save_spectrogram(
527522
def write(
528523
self,
529524
folder: Path,
530-
sx: np.ndarray | None = None,
531525
*,
526+
sx: np.ndarray | None = None,
532527
link: bool = False,
533528
) -> None:
534529
"""Write the Spectro data to file.

src/osekit/logging_context.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,8 @@
1313
"""
1414

1515
import logging
16-
from collections.abc import Generator
16+
import typing
1717
from contextlib import contextmanager
18-
from typing import Any
1918

2019

2120
class LoggingContext:
@@ -29,7 +28,7 @@ def __init__(self) -> None:
2928
self.logger = logging.root
3029

3130
@contextmanager
32-
def set_logger(self, logger: logging.Logger) -> Generator[None, Any, None]:
31+
def set_logger(self, logger: logging.Logger) -> typing.Generator:
3332
"""Set a contextmanager for calling utils functions with a specific logger.
3433
3534
Parameters

src/osekit/public_api/dataset.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,6 @@ def _sort_dataset(self, dataset: type[DatasetChild]) -> None:
616616
return
617617
if type(dataset) is SpectroDataset | LTASDataset:
618618
self._sort_spectro_dataset(dataset)
619-
return
620619

621620
def _sort_audio_dataset(self, dataset: AudioDataset) -> None:
622621
dataset.move_files(self._get_audio_dataset_subpath(dataset))
@@ -789,15 +788,12 @@ def from_dict(cls, dictionary: dict) -> Dataset:
789788
"""
790789
datasets = {}
791790
for name, dataset in dictionary["datasets"].items():
792-
dataset_class = (
793-
AudioDataset
794-
if dataset["class"] == "AudioDataset"
795-
else SpectroDataset
796-
if dataset["class"] == "SpectroDataset"
797-
else LTASDataset
798-
if dataset["class"] == "LTASDataset"
799-
else BaseDataset
800-
)
791+
dataset_class = {
792+
"AudioDataset": AudioDataset,
793+
"SpectroDataset": SpectroDataset,
794+
"LTASDataset": LTASDataset,
795+
}[dataset["class"]]
796+
801797
datasets[name] = {
802798
"class": dataset["class"],
803799
"analysis": dataset["analysis"],

src/osekit/utils/multiprocess_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,14 @@ def multiprocess(
4141
4242
"""
4343
if bypass_multiprocessing or not config.multiprocessing["is_active"]:
44-
return list(
44+
return [
4545
func(element, *args, **kwargs)
4646
for element in tqdm(
4747
enumerable,
4848
disable=os.getenv("DISABLE_TQDM", "False").lower()
4949
in ("true", "1", "t"),
5050
)
51-
)
51+
]
5252

5353
partial_func = partial(func, *args, **kwargs)
5454

tests/conftest.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import os
55
import sys
6-
from collections.abc import Generator
6+
import typing
77
from pathlib import Path
88
from unittest.mock import MagicMock
99

@@ -45,7 +45,7 @@ def audio_files(
4545
series_type = request.param.get("series_type", "repeat")
4646
sine_frequency = request.param.get("sine_frequency", 1000.0)
4747
magnitude = request.param.get("magnitude", 1.0)
48-
format = request.param.get("format", "wav")
48+
audio_format = request.param.get("format", "wav")
4949
else:
5050
sample_rate = 48_000
5151
duration = 1.0
@@ -54,9 +54,9 @@ def audio_files(
5454
series_type = "repeat"
5555
sine_frequency = 1000.0
5656
magnitude = 1.0
57-
format = "wav"
57+
audio_format = "wav"
5858

59-
nb_samples = int(round(duration * sample_rate))
59+
nb_samples = round(duration * sample_rate)
6060
data = generate_sample_audio(
6161
nb_files=nb_files,
6262
nb_samples=nb_samples,
@@ -88,14 +88,14 @@ def audio_files(
8888
for index, begin_time in enumerate(file_begin_timestamps):
8989
time_str = begin_time.strftime(format=datetime_format)
9090
idx = 0
91-
while (file := tmp_path / f"audio_{time_str}_{idx}.{format}").exists():
91+
while (file := tmp_path / f"audio_{time_str}_{idx}.{audio_format}").exists():
9292
idx += 1
9393
files.append(file)
9494
kwargs = {
9595
"file": file,
9696
"data": data[index],
9797
"samplerate": sample_rate,
98-
"subtype": "DOUBLE" if format.lower() == "wav" else "PCM_24",
98+
"subtype": "DOUBLE" if audio_format.lower() == "wav" else "PCM_24",
9999
}
100100
sf.write(**kwargs)
101101
output = [AudioFile(path=f, strptime_format=datetime_format) for f in files]
@@ -111,7 +111,7 @@ def patch_filehandlers(
111111
return
112112

113113
def disabled_filewrite(self: any, record: any) -> None:
114-
pass
114+
"""Prevent the logger from actually writing files."""
115115

116116
monkeypatch.setattr(logging.FileHandler, "emit", disabled_filewrite)
117117

@@ -217,7 +217,7 @@ def mocked_get_raw_value(self: AudioData) -> np.ndarray:
217217

218218

219219
@pytest.fixture(autouse=True)
220-
def restore_config() -> Generator:
220+
def restore_config() -> typing.Generator:
221221
resample_quality_settings = {**config.resample_quality_settings}
222222
multiprocessing = {**config.multiprocessing}
223223
yield

tests/test_audio.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def test_audio_file_read(
218218
stop: pd.Timestamp,
219219
expected: np.ndarray,
220220
) -> None:
221-
files, request = audio_files
221+
files, _ = audio_files
222222
assert np.allclose(files[0].read(start, stop)[:, 0], expected, atol=1e-7)
223223

224224

@@ -448,7 +448,7 @@ def test_audio_item(
448448
stop: pd.Timestamp | None,
449449
expected: np.ndarray,
450450
) -> None:
451-
files, request = audio_files
451+
files, _ = audio_files
452452
item = AudioItem(files[0], start, stop)
453453
assert np.array_equal(item.get_value()[:, 0], expected)
454454
assert item.shape == item.get_value().shape
@@ -710,7 +710,7 @@ def test_audio_resample_sample_count(
710710
sample_rate: int,
711711
expected_nb_samples: int,
712712
) -> None:
713-
audio_files, request = audio_files
713+
audio_files, _ = audio_files
714714
data = AudioData.from_files(audio_files, begin=start, end=stop)
715715
data.sample_rate = sample_rate
716716
assert data.get_value().shape[0] == expected_nb_samples
@@ -1745,7 +1745,7 @@ def test_split_data_normalization_pass(patch_audio_data: None) -> None:
17451745
ad = AudioData()
17461746
ad.mocked_value = [1, 2, 3]
17471747
original_normalization_values = ad.get_normalization_values()
1748-
assert all(v for v in original_normalization_values.values())
1748+
assert all(original_normalization_values.values())
17491749

17501750
assert all(
17511751
part.normalization_values == original_normalization_values
@@ -1867,10 +1867,10 @@ def test_split_frames_errors(patch_audio_data: None) -> None:
18671867
"Start_frame must be greater than or equal to 0.",
18681868
"Stop_frame must be lower than the length of the data.",
18691869
]
1870-
with pytest.raises(ValueError, match=error_msgs[0]) as e:
1871-
assert ad.split_frames(start_frame=-1, stop_frame=2) == e
1872-
with pytest.raises(ValueError, match=error_msgs[1]) as e:
1873-
assert ad.split_frames(start_frame=0, stop_frame=100) == e
1870+
with pytest.raises(ValueError, match=error_msgs[0]):
1871+
ad.split_frames(start_frame=-1, stop_frame=2)
1872+
with pytest.raises(ValueError, match=error_msgs[1]):
1873+
ad.split_frames(start_frame=0, stop_frame=100)
18741874

18751875

18761876
@pytest.mark.parametrize(

tests/test_core_api_base.py

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ class DummyItem(BaseItem[DummyFile]): ...
2929
class DummyData(BaseData[DummyItem, DummyFile]):
3030
item_cls = DummyItem
3131

32-
def write(self, folder: Path, link: bool = False) -> None: ...
32+
def write(self, folder: Path, *, link: bool = False) -> None: ...
3333

3434
def link(self, folder: Path) -> None: ...
3535

@@ -134,8 +134,8 @@ def test_base_file_with_no_begin_error() -> None:
134134
with pytest.raises(
135135
ValueError,
136136
match=r"Either begin or strptime_format must be specified",
137-
) as e:
138-
assert DummyFile(path=r"foo") == e
137+
):
138+
DummyFile(path=r"foo")
139139

140140

141141
@pytest.mark.parametrize(
@@ -503,21 +503,18 @@ def test_base_dataset_from_files_overlap_errors(overlap: float, mode: str) -> No
503503
with pytest.raises(
504504
ValueError,
505505
match=rf"Overlap \({overlap}\) must be between 0 and 1.",
506-
) as e:
507-
assert (
508-
DummyDataset.from_files(
509-
[
510-
DummyFile(
511-
path=Path("foo"),
512-
begin=Timestamp("2016-02-05 00:00:00"),
513-
end=Timestamp("2016-02-05 00:10:00"),
514-
),
515-
],
516-
data_duration=Timedelta(seconds=1),
517-
mode=mode,
518-
overlap=overlap,
519-
)
520-
== e
506+
):
507+
DummyDataset.from_files(
508+
[
509+
DummyFile(
510+
path=Path("foo"),
511+
begin=Timestamp("2016-02-05 00:00:00"),
512+
end=Timestamp("2016-02-05 00:10:00"),
513+
),
514+
],
515+
data_duration=Timedelta(seconds=1),
516+
mode=mode,
517+
overlap=overlap,
521518
)
522519

523520

0 commit comments

Comments
 (0)