Skip to content

Commit

Permalink
Define HBA as a dataclass
Browse files Browse the repository at this point in the history
  • Loading branch information
pgiraud committed Dec 12, 2024
1 parent 2217077 commit e942271
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
26 changes: 11 additions & 15 deletions pgtoolkit/hba.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
import sys
import warnings
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import IO, Any

Expand Down Expand Up @@ -209,20 +210,20 @@ def __str__(self) -> str:
widths = [8, 16, 16, 16, 8]

fmt = ""
for i, field in enumerate(self.COMMON_FIELDS):
for i, field_ in enumerate(self.COMMON_FIELDS):
try:
width = widths[i]
except IndexError:
width = 0

if field not in self.fields:
if field_ not in self.fields:
fmt += " " * width
continue

if width:
fmt += "%%(%s)-%ds " % (field, width - 1)
fmt += "%%(%s)-%ds " % (field_, width - 1)
else:
fmt += f"%({field})s "
fmt += f"%({field_})s "
# Serialize database and user list using property.
values = dict(self.__dict__, databases=self.database, users=self.user)
line = fmt.rstrip() % values
Expand Down Expand Up @@ -298,6 +299,7 @@ def matches(self, **attrs: str) -> bool:
return True


@dataclass
class HBA:
"""Represents pg_hba.conf records
Expand All @@ -317,18 +319,12 @@ class HBA:
.. automethod:: merge
"""

lines: list[HBAComment | HBARecord]
path: str | Path | None
lines: list[HBAComment | HBARecord] = field(default_factory=list)
path: str | Path | None = None

def __init__(self, entries: Iterable[HBAComment | HBARecord] | None = None) -> None:
"""HBA constructor
:param entries: A list of HBAComment or HBARecord. Optional.
"""
if entries and not isinstance(entries, list):
raise ValueError("%s should be a list" % entries)
self.lines = list(entries) if entries is not None else []
self.path = None
def __post_init__(self) -> None:
if self.lines and not isinstance(self.lines, list):
raise ValueError("%s should be a list" % self.lines)

def __iter__(self) -> Iterator[HBARecord]:
"""Iterate on records, ignoring comments and blank lines."""
Expand Down
14 changes: 13 additions & 1 deletion tests/test_hba.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,18 @@ def test_hba(mocker):
hba.save(mocker.Mock(name="file"))


def test_hba_path(tmp_path):
from pgtoolkit.hba import HBA

hba = HBA()
assert hba.path is None

p = tmp_path / "filename"
hba = HBA([], p)
assert hba.path == p
hba.save()


def test_hba_create():
from pgtoolkit.hba import HBA, HBAComment, HBARecord

Expand All @@ -175,7 +187,7 @@ def test_hba_create():
assert ["all"] == r.databases

# Should be a list
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="should be a list"):
HBA("blah")


Expand Down

0 comments on commit e942271

Please sign in to comment.