Skip to content

Commit

Permalink
fix all ruff PT011 and unignore that rule
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Jan 30, 2024
1 parent b5770cf commit 5beab45
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 53 deletions.
44 changes: 21 additions & 23 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -148,37 +148,35 @@ exclude_lines = [
target-version = "py39"
select = ["ALL"]
ignore = [
"ARG002", # unused method argument
"COM812", # trailing comma missing
"PD011", # pandas-use-of-dot-values
"PERF203", # try-except-in-loop
"PLR", # pylint-refactor
"PT004", # pytest-missing-fixture-name-underscore
"PT006", # pytest-parametrize-names-wrong-type
"RUF013", # implicit-optional
# TODO remove PT011, pytest.raises() should always check err msg
"ANN002",
"ANN003",
"ANN101", # missing self type annotation
"ANN101", # missing self type annotation
"ANN102",
"ANN401",
"ARG002", # unused method argument
"BLE001",
"C408", # Unnecessary (dict/list/tuple) call - remove call
"C901", # function too complex
"DTZ", # datetime-tz-now
"EM", # exception message must not use f-string literal
"ERA001", # found commented out code
"C408", # Unnecessary (dict/list/tuple) call - remove call
"C901", # function too complex
"COM812", # trailing comma missing
"DTZ", # datetime-tz-now
"EM", # exception message must not use f-string literal
"ERA001", # found commented out code
"FBT001",
"FBT002",
"FIX002",
"G004", # logging uses fstring
"PT011", # pytest-raises-too-broad
"PT013", # pytest-incorrect-pytest-import
"PTH", # prefer Pathlib to os.path
"S324", # use of insecure hash function
"SLF", # private member accessed outside class
"TD", # TODOs
"TRY003", # long message outside exception class
"G004", # logging uses fstring
"PD011", # pandas-use-of-dot-values
"PERF203", # try-except-in-loop
"PLR", # pylint-refactor
"PT004", # pytest-missing-fixture-name-underscore
"PT006", # pytest-parametrize-names-wrong-type
"PT013", # pytest-incorrect-pytest-import
"PTH", # prefer Pathlib to os.path
"RUF013", # implicit-optional
"S324", # use of insecure hash function
"SLF", # private member accessed outside class
"TD", # TODOs
"TRY003", # long message outside exception class
]
pydocstyle.convention = "numpy"
isort.known-first-party = ["atomate2"]
Expand Down
16 changes: 8 additions & 8 deletions src/atomate2/cp2k/sets/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,14 @@ def write_input(
}
inputs.update(self.optional_files)

for k, v in inputs.items():
fn = v.get("filename")
obj = v.get("object")
if v is not None and (overwrite or not (directory / k).exists()):
with zopen(directory / fn, "wt") as f:
f.write(str(obj))
elif not overwrite and (directory / fn).exists():
raise FileExistsError(f"{directory / fn} already exists.")
for key, val in inputs.items():
filename = val.get("filename")
obj = val.get("object")
if val is not None and (overwrite or not (directory / key).exists()):
with zopen(directory / filename, "wt") as file:
file.write(str(obj))
elif not overwrite and (directory / filename).exists():
raise FileExistsError(f"{directory / filename} already exists.")

Check warning on line 116 in src/atomate2/cp2k/sets/base.py

View check run for this annotation

Codecov / codecov/patch

src/atomate2/cp2k/sets/base.py#L116

Added line #L116 was not covered by tests

@staticmethod
def from_directory(
Expand Down
22 changes: 10 additions & 12 deletions src/atomate2/forcefields/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,18 +114,16 @@ def save(self, filename: str | PathLike) -> None:
-------
None
"""
with open(filename, "wb") as f:
pickle.dump(
{
"energy": self.energies,
"forces": self.forces,
"stresses": self.stresses,
"atom_positions": self.atom_positions,
"cell": self.cells,
"atomic_number": self.atoms.get_atomic_numbers(),
},
f,
)
traj_dict = {
"energy": self.energies,
"forces": self.forces,
"stresses": self.stresses,
"atom_positions": self.atom_positions,
"cell": self.cells,
"atomic_number": self.atoms.get_atomic_numbers(),
}
with open(filename, "wb") as file:
pickle.dump(traj_dict, file)


class Relaxer:
Expand Down
4 changes: 2 additions & 2 deletions src/atomate2/lobster/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -1313,9 +1313,9 @@ def read_saved_json(
dict
Returns a dictionary with lobster task json data corresponding to query.
"""
with gzip.open(filename, "rb") as f:
with gzip.open(filename, "rb") as file:
lobster_data = {}
objects = ijson.items(f, "item", use_float=True)
objects = ijson.items(file, "item", use_float=True)
for obj in objects:
if query is None:
for field, data in obj.items():
Expand Down
7 changes: 3 additions & 4 deletions tests/common/schemas/test_cclib.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,11 @@ def test_cclib_taskdoc(test_dir):

# Now we will try two possible extensions, but we will make sure that
# it fails because the newest log file (.txt) is not valid
with open(p / "test.txt", "w") as f:
f.write("I am a dummy log file")
with pytest.raises(Exception) as e:
with open(p / "test.txt", "w") as file:
file.write("I am a dummy log file")
with pytest.raises(ValueError, match="Could not parse"):
doc = TaskDocument.from_logfile(p, [".log", ".txt"]).dict()
os.remove(p / "test.txt")
assert "Could not parse" in str(e.value)

# Test a population analysis
doc = TaskDocument.from_logfile(p, "psi_test.out", analysis="MBO").dict()
Expand Down
3 changes: 1 addition & 2 deletions tests/forcefields/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ def test_relaxer(si_structure, test_dir, tmp_dir, optimizer, traj_file):
]

if optimizer is None:
# None is invalid, should raise ValueError
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="Optimizer cannot be None"):
Relaxer(calculator=LennardJones(), optimizer=optimizer)
return

Expand Down
7 changes: 5 additions & 2 deletions tests/vasp/flows/test_phonons.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,10 @@ def test_phonon_wf_only_displacements_kpath_raises_no_cell_change(
# automatically use fake VASP and write POTCAR.spec during the test
mock_vasp(ref_paths, fake_run_vasp_kwargs)

with pytest.raises(ValueError):
with pytest.raises(
ValueError,
match="can only use other kpath schemes with the primitive standard structure",
):
PhononMaker(
min_length=3.0,
bulk_relax_maker=None,
Expand Down Expand Up @@ -785,7 +788,7 @@ def test_phonon_wf_only_displacements_kpath_raises(mock_vasp, clean_dir, kpath_s

# automatically use fake VASP and write POTCAR.spec during the test
mock_vasp(ref_paths, fake_run_vasp_kwargs)
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="can only use other kpath schemes with the"):
PhononMaker(
min_length=3.0,
bulk_relax_maker=None,
Expand Down

0 comments on commit 5beab45

Please sign in to comment.