Skip to content
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

Remove unnecessary function and lots of linting #132

Merged
merged 78 commits into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from 75 commits
Commits
Show all changes
78 commits
Select commit Hold shift + click to select a range
dfce7e4
IOError is now OSError in CPython, do not need to inherit from object
fsoubelet Aug 15, 2024
2fb0b27
use PEP 585 annotations
fsoubelet Aug 15, 2024
298143e
delay annotations to allow TfsCollection hints
fsoubelet Aug 15, 2024
678112c
remove trailing whitespaces
fsoubelet Aug 15, 2024
7e6e6fd
type checking block
fsoubelet Aug 15, 2024
155bf59
remove trailing whitespaces
fsoubelet Aug 15, 2024
64024e8
__new__ is classmethod, should have cls as first argument
fsoubelet Aug 15, 2024
45c2627
no implicit none
fsoubelet Aug 15, 2024
27dbefd
error messages should be defined outside raise statement
fsoubelet Aug 15, 2024
cd57cfa
ignore unused args and kwargs in abstractmethod signature
fsoubelet Aug 15, 2024
18c4401
unnecessary else
fsoubelet Aug 15, 2024
a9255a2
ignore for legitimate reasons, minor formatting
fsoubelet Aug 15, 2024
8c3a929
use PEP 585 annotations
fsoubelet Aug 15, 2024
c267c8b
no pass statement in exception definition
fsoubelet Aug 15, 2024
8c702db
get Sequence from collections.abc
fsoubelet Aug 15, 2024
fe40bc2
remove trailing whitespaces
fsoubelet Aug 15, 2024
4c22c94
use PEP 585 annotations
fsoubelet Aug 15, 2024
504e544
mutable class var should be type hinted ClassVar
fsoubelet Aug 15, 2024
73cca17
Exception must not use a string literal, assign to variable first
fsoubelet Aug 15, 2024
d2c2e31
Exception must not use a string literal, assign to variable first
fsoubelet Aug 15, 2024
c8eb8ce
reraise from previous error
fsoubelet Aug 15, 2024
5a740da
also reraise from full stacktrace here
fsoubelet Aug 15, 2024
efd6a4c
PEP 604 unions and avoid implicit optional
fsoubelet Aug 15, 2024
f6c16a0
type checking block
fsoubelet Aug 15, 2024
444b9ef
let ruff know we target python 3.9
fsoubelet Aug 15, 2024
ad1899a
PEP 604 unions
fsoubelet Aug 15, 2024
608d5d6
put annotation-only type in TYPE_CHECKING block
fsoubelet Aug 15, 2024
4cadb94
Use key in dict instead of key in dict.keys()
fsoubelet Aug 15, 2024
91b5dcc
remove trailing whitespaces
fsoubelet Aug 15, 2024
55792a6
Exception must not use a string literal, assign to variable first
fsoubelet Aug 15, 2024
30a2e16
use contextlib to suppress a specific error instead of try-except-pass
fsoubelet Aug 15, 2024
f6d408c
use PEP 585 annotations
fsoubelet Aug 15, 2024
16aafd9
PEP 604 unions and avoid implicit optional
fsoubelet Aug 15, 2024
4bbaeb5
stop caring about boolean arg
fsoubelet Aug 15, 2024
3072887
Exception must not use a string literal, assign to variable first
fsoubelet Aug 15, 2024
d744629
reraise from previous error
fsoubelet Aug 15, 2024
c54bf6e
use PEP 585 annotations
fsoubelet Aug 15, 2024
8269df6
stop caring about boolean arg
fsoubelet Aug 15, 2024
b354c92
PEP 604 unions
fsoubelet Aug 15, 2024
b8b4fdc
put annotation-only type in TYPE_CHECKING block
fsoubelet Aug 15, 2024
9275220
stop caring about boolean arg
fsoubelet Aug 15, 2024
41dbf3d
Exception must not use a string literal, assign to variable first
fsoubelet Aug 15, 2024
efb46af
lets not overwrite the loop variable
fsoubelet Aug 15, 2024
eaef978
use PEP 585 annotations
fsoubelet Aug 15, 2024
00df787
PEP 604 unions and avoid implicit optional
fsoubelet Aug 15, 2024
7c55048
stop caring about boolean arg
fsoubelet Aug 15, 2024
e78e923
remove trailing whitespaces
fsoubelet Aug 15, 2024
78f0bff
unnecessary else after return
fsoubelet Aug 15, 2024
6a3ee88
no need to restate the raise error name
fsoubelet Aug 15, 2024
a9ea55d
remove _autoset_pandas_types as we prohibit pandas <2.1 and the need …
fsoubelet Aug 15, 2024
696f694
Exception must not use a string literal, assign to variable first
fsoubelet Aug 15, 2024
a4e0072
use startswith with a tuple instead of several checks
fsoubelet Aug 15, 2024
7d6ce93
use single if statement instead of nested ones
fsoubelet Aug 15, 2024
3fec4de
unnecessary assignment before return
fsoubelet Aug 15, 2024
c1549c0
elifs can be ifs since theyre after return statements
fsoubelet Aug 15, 2024
9b9a615
minimal formatting
fsoubelet Aug 15, 2024
2842aff
Use key in dict instead of key in dict.keys()
fsoubelet Aug 15, 2024
21f299c
stop caring about boolean arg
fsoubelet Aug 15, 2024
d5d9ad8
set match in pytest.raises as it was too broad
fsoubelet Aug 15, 2024
b1d9e48
Use key in dict instead of key in dict.keys()
fsoubelet Aug 15, 2024
827595e
remove unused caplogs
fsoubelet Aug 15, 2024
5492297
set match in pytest.raises as it was too broad
fsoubelet Aug 15, 2024
4df0b4d
should assign in access expressions
fsoubelet Aug 15, 2024
a9ad1fd
asserts should only check one thing
fsoubelet Aug 15, 2024
9ffd6ae
unused import and orders
fsoubelet Aug 15, 2024
e1bd0cc
set match in pytest.raises as it was too broad
fsoubelet Aug 15, 2024
7a9680c
Use key in dict instead of key in dict.keys()
fsoubelet Aug 15, 2024
419c416
remove unused caplogs
fsoubelet Aug 15, 2024
dcdcbf2
pandas as pd, numpy as np
fsoubelet Aug 15, 2024
7440023
remove unused caplogs
fsoubelet Aug 15, 2024
41748ec
use dict literal
fsoubelet Aug 15, 2024
83d9da8
oops
fsoubelet Aug 15, 2024
862e9e4
help josch's eyes
fsoubelet Aug 15, 2024
c160f80
bit more formatting consistency
fsoubelet Aug 15, 2024
8142219
no need for these skipifs as the condition no longer applies
fsoubelet Aug 15, 2024
f056f4b
again an unused import
fsoubelet Aug 15, 2024
f2ceff2
add in progress to the changelog
fsoubelet Aug 15, 2024
18881a7
noqa on the correct line again
fsoubelet Aug 15, 2024
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
5 changes: 2 additions & 3 deletions doc/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# TFS-Pandas documentation build configuration file, created by
# sphinx-quickstart on Tue Feb 6 12:10:18 2018.
Expand Down Expand Up @@ -54,7 +53,7 @@ def about_package(init_posixpath: pathlib.Path) -> dict:
"sphinx.ext.coverage", # Collect doc coverage stats
"sphinx.ext.doctest", # Test snippets in the documentation
"sphinx.ext.githubpages", # Publish HTML docs in GitHub Pages
"sphinx.ext.intersphinx", # Link to other projects documentation
"sphinx.ext.intersphinx", # Link to other projects' documentation
"sphinx.ext.mathjax", # Render math via JavaScript
"sphinx.ext.napoleon", # Support for NumPy and Google style docstrings
"sphinx.ext.todo", # Support for todo items
Expand Down Expand Up @@ -244,4 +243,4 @@ def about_package(init_posixpath: pathlib.Path) -> dict:
"matplotlib": ("https://matplotlib.org/stable/", None),
"scipy": ("https://docs.scipy.org/doc/scipy/", None),
"cpymad": ("https://hibtc.github.io/cpymad/", None),
}
}
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,9 @@ homepage = "https://github.com/pylhc/tfs"
repository = "https://github.com/pylhc/tfs"
documentation = "https://pylhc.github.io/tfs/ "
changelog = "https://github.com/pylhc/tfs/blob/master/CHANGELOG.md"


[tool.ruff]

# Assume Python 3.9+
target-version = "py39"
32 changes: 16 additions & 16 deletions tests/test_collection.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
import pathlib

import pytest
from pandas.testing import assert_frame_equal

Expand Down Expand Up @@ -143,8 +143,8 @@ def test_buffer_flush_nowrite(self, _input_dir_str: str, _tfs_x: TfsDataFrame, _
assert_frame_equal(tfs_y, read_tfs(c.get_path("nofile_y"), index=c.INDEX))

c.allow_write = False
with pytest.raises(IOError):
c.flush()
with pytest.raises(OSError, match="Cannot flush TfsCollection"):
c.flush() # because allow_write is set to False

tfs_x_after_flush = read_tfs(c.get_path("file_x"), index=c.INDEX)
tfs_y_after_flush = read_tfs(c.get_path("nofile_y"), index=c.INDEX)
Expand All @@ -156,7 +156,7 @@ class TestFilenames:

def test_tfscollection_getfilename_not_implemented(self):
with pytest.raises(NotImplementedError):
TfsCollection._get_filename("doesnt matter")
TfsCollection._get_filename("doesnt matter") # noqa: SLF001

def test_get_filename(self, _input_dir_pathlib: pathlib.Path):
c = CollectionTest(_input_dir_pathlib, allow_write=False)
Expand Down Expand Up @@ -186,13 +186,13 @@ def test_filenames(self, _input_dir_pathlib: pathlib.Path):
assert c.filenames()["file_x"] == "file_x.tfs"
assert c.filenames()["nofile_y"] == "nofile_y.tfs"

assert all(f in c.filenames().keys() for f in exist_properties)
assert all(f in c.filenames().keys() for f in not_exist_properties)
assert all(f in c.filenames() for f in exist_properties)
assert all(f in c.filenames() for f in not_exist_properties)
assert all(f in c.filenames().values() for f in exist_files)
assert all(f in c.filenames().values() for f in not_exist_files)

assert all(f in c.filenames(exist=True).keys() for f in exist_properties)
assert all(f not in c.filenames(exist=True).keys() for f in not_exist_properties)
assert all(f in c.filenames(exist=True) for f in exist_properties)
assert all(f not in c.filenames(exist=True) for f in not_exist_properties)
assert all(f in c.filenames(exist=True).values() for f in exist_files)
assert all(f not in c.filenames(exist=True).values() for f in not_exist_files)

Expand Down Expand Up @@ -254,10 +254,10 @@ def _test_fun(df, a, b):
assert res_file[1] == 13

def test_buffer_clear(self, _dummy_collection):
_dummy_collection._buffer["some_key"] = 5
assert _dummy_collection._buffer["some_key"]
_dummy_collection._buffer["some_key"] = 5 # noqa: SLF001
assert _dummy_collection._buffer["some_key"] # noqa: SLF001
_dummy_collection.clear()
assert not _dummy_collection._buffer
assert not _dummy_collection._buffer # noqa: SLF001

def test_no_attribute(self, _dummy_collection):
with pytest.raises(AttributeError):
Expand All @@ -269,26 +269,26 @@ def _read_tfs(path):
return read_tfs(path).set_index("NAME", drop=False)


@pytest.fixture()
@pytest.fixture
def _tfs_x() -> TfsDataFrame:
return _read_tfs(INPUT_DIR / "file_x.tfs")


@pytest.fixture()
@pytest.fixture
def _tfs_y() -> TfsDataFrame:
return _read_tfs(INPUT_DIR / "file_y.tfs")


@pytest.fixture()
@pytest.fixture
def _input_dir_pathlib() -> pathlib.Path:
return INPUT_DIR


@pytest.fixture()
@pytest.fixture
def _input_dir_str() -> str:
return str(INPUT_DIR)


@pytest.fixture()
@pytest.fixture
def _dummy_collection() -> TfsCollection:
return TfsCollection("")
25 changes: 5 additions & 20 deletions tests/test_compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,6 @@
CURRENT_DIR = pathlib.Path(__file__).parent


# TODO: remove the skipif once Python 3.7 is EoL and we drop support for it
@pytest.mark.skipif(
sys.version_info < (3, 8),
reason="Not run on Python 3.7 for format protocol incompatibility reasons",
)
@pytest.mark.parametrize("extension", ["gz", "bz2", "zip", "xz", "zst", "tar", "tar.gz"])
def test_read_compressed_is_same_data(_tfs_filex, _tfs_compressed_filex_no_suffix, extension):
"""Compare the data from a compressed file with the original one."""
Expand All @@ -33,11 +28,6 @@ def test_read_compressed_is_same_data(_tfs_filex, _tfs_compressed_filex_no_suffi
assert_frame_equal(ref_df, test_df)


# TODO: remove the skipif once Python 3.7 is EoL and we drop support for it
@pytest.mark.skipif(
sys.version_info < (3, 8),
reason="Not run on Python 3.7 for format protocol incompatibility reasons",
)
@pytest.mark.parametrize("extension", ["gz", "bz2", "zip", "xz", "zst", "tar", "tar.gz"])
def test_write_read_compressed(_tfs_filey, tmp_path, extension):
"""Ensure that writing in compressed format preserves data."""
Expand All @@ -57,11 +47,6 @@ def test_write_read_compressed(_tfs_filey, tmp_path, extension):
assert_frame_equal(ref_df, test_df)


# TODO: remove the skipif once Python 3.7 is EoL and we drop support for it
@pytest.mark.skipif(
sys.version_info < (3, 8),
reason="Not run on Python 3.7 for format protocol incompatibility reasons",
)
@pytest.mark.parametrize("extension", ["gz", "bz2", "zip", "xz", "zst", "tar", "tar.gz"])
def test_read_headers_compressed(_tfs_compressed_filex_no_suffix, extension):
compressed_file = _path_with_added_extension(_tfs_compressed_filex_no_suffix, extension)
Expand All @@ -70,7 +55,7 @@ def test_read_headers_compressed(_tfs_compressed_filex_no_suffix, extension):
assert len(headers) > 0
assert len(str(headers)) > 0
assert all(
key in headers.keys()
key in headers
for key in ["TITLE", "DPP", "Q1", "Q1RMS", "NATQ1", "NATQ1RMS", "BPMCOUNT"]
)

Expand All @@ -86,23 +71,23 @@ def _path_with_added_extension(path: pathlib.Path, extension: str) -> pathlib.Pa
# ------ Fixtures ------ #


@pytest.fixture()
@pytest.fixture
def _tfs_filex() -> pathlib.Path:
return CURRENT_DIR / "inputs" / "file_x.tfs"


@pytest.fixture()
@pytest.fixture
def _tfs_filey() -> pathlib.Path:
return CURRENT_DIR / "inputs" / "file_y.tfs"


@pytest.fixture()
@pytest.fixture
def _tfs_compressed_filex_no_suffix() -> pathlib.Path:
"""Add the wanted compression suffix to this."""
return CURRENT_DIR / "inputs" / "compressed" / "file_x.tfs"


@pytest.fixture()
@pytest.fixture
def _tfs_compressed_filey_no_suffix() -> pathlib.Path:
"""Add the wanted compression suffix to this."""
return CURRENT_DIR / "inputs" / "compressed" / "file_y.tfs"
24 changes: 13 additions & 11 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,29 @@


class TestFailures:
def test_validate_raises_on_wrong_unique_behavior(self, caplog):
def test_validate_raises_on_wrong_unique_behavior(self):
df = TfsDataFrame(index=["A", "B", "A"], columns=["A", "B", "A"])
with pytest.raises(KeyError):
validate(df, "", non_unique_behavior="invalid")

@pytest.mark.parametrize("how", ["invalid", "not_left", "not_right"])
def test_merge_headers_raises_on_invalid_how_key(self, caplog, how):
def test_merge_headers_raises_on_invalid_how_key(self, how):
headers_left = OrderedDict()
headers_right = OrderedDict()

with pytest.raises(ValueError):
with pytest.raises(ValueError, match="Invalid 'how' argument"):
merge_headers(headers_left, headers_right, how=how)

def test_access_errors(self):
df = TfsDataFrame(index=["A", "B", "A"], columns=["A", "B", "A"], headers={"HEADER": 10})
with pytest.raises(AttributeError):
df.does_not_exist
_ = df.does_not_exist

with pytest.raises(KeyError):
df["does also not exist"]
_ = df["does also not exist"]

with pytest.raises(KeyError): # raises KeyError in pandas, TypeError in dict
df[[1, 2, 3]]
_ = df[[1, 2, 3]]


class TestTfsDataFrameMerging:
Expand Down Expand Up @@ -79,7 +79,8 @@ def test_headers_merging_left(self, _tfs_file_x_pathlib, _tfs_file_y_pathlib, ho
result = merge_headers(headers_left, headers_right, how=how)

assert isinstance(result, OrderedDict)
assert len(result) >= len(headers_left) and len(result) >= len(headers_right) # no key disappeared
assert len(result) >= len(headers_left) # no key disappeared
assert len(result) >= len(headers_right) # no key disappeared
for key in result: # check that we prioritized headers_left's contents
if key in headers_left and key in headers_right:
assert result[key] == headers_left[key]
Expand All @@ -91,7 +92,8 @@ def test_headers_merging_right(self, _tfs_file_x_pathlib, _tfs_file_y_pathlib, h
result = merge_headers(headers_left, headers_right, how=how)

assert isinstance(result, OrderedDict)
assert len(result) >= len(headers_left) and len(result) >= len(headers_right) # no key disappeared
assert len(result) >= len(headers_left) # no key disappeared
assert len(result) >= len(headers_right) # no key disappeared
for key in result: # check that we prioritized headers_right's contents
if key in headers_left and key in headers_right:
assert result[key] == headers_right[key]
Expand Down Expand Up @@ -132,7 +134,7 @@ def test_long_headers_print(self):
assert "Headers" in print_out

# Check that the ellipsis worked
assert not all(key in print_out for key in headers.keys())
assert not all(key in print_out for key in headers)
assert not all(str(val) in print_out for val in headers.values())
assert "..." in print_out

Expand Down Expand Up @@ -185,11 +187,11 @@ def test_concatenating_accepts_pandas_dataframes(
# ------ Fixtures ------ #


@pytest.fixture()
@pytest.fixture
def _tfs_file_x_pathlib() -> pathlib.Path:
return CURRENT_DIR / "inputs" / "file_x.tfs"


@pytest.fixture()
@pytest.fixture
def _tfs_file_y_pathlib() -> pathlib.Path:
return CURRENT_DIR / "inputs" / "file_x.tfs"
10 changes: 5 additions & 5 deletions tests/test_hdf.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import sys

import numpy as np
import pytest
from pathlib import Path

from tfs import TfsDataFrame, write_hdf, read_hdf
from pandas.testing import assert_frame_equal
import numpy as np
import pytest
from pandas._testing import assert_dict_equal
from pandas.testing import assert_frame_equal

from tfs import TfsDataFrame, read_hdf, write_hdf


class TestHDF:
Expand Down
Loading