Skip to content

Commit

Permalink
update tests and README (#8)
Browse files Browse the repository at this point in the history
* update tests and README

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
PythonFZ and pre-commit-ci[bot] authored Oct 13, 2024
1 parent 5068f74 commit 740c2de
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@ pip install znfields

## Example

The `znfields.field` supports all arguments from `dataclasses.field` with the additional `getter` argument.
The `znfields.field` supports all arguments from `dataclasses.field` with the
additional `getter` argument.

```python
import dataclasses
import znfields

def example1_parameter_getter(self, name):
def parameter_getter(self, name):
return f"{name}:{self.__dict__[name]}"

@dataclasses.dataclass
class Example3(znfields.Base):
parameter: float = znfields.field(getter=example1_parameter_getter)
class ClassWithParameter(znfields.Base):
parameter: float = znfields.field(getter=parameter_getter)
```
31 changes: 30 additions & 1 deletion tests/test_znfields.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,43 @@
import dataclasses
import znfields

import pytest

import znfields


def example1_parameter_getter(self, name):
return f"{name}:{self.__dict__[name]}"


def stringify_list(self, name):
content = self.__dict__[name]
self.__dict__[name] = [str(x) for x in content]
# Can not return a copy to append to, but must be the same object
return self.__dict__[name]


@dataclasses.dataclass
class Example1(znfields.Base):
parameter: float = znfields.field(getter=example1_parameter_getter)


@dataclasses.dataclass
class Example1WithDefault(znfields.Base):
parameter: float = znfields.field(getter=example1_parameter_getter, default=1)


@dataclasses.dataclass
class Example1WithDefaultFactory(znfields.Base):
parameter: list = znfields.field(getter=stringify_list, default_factory=list)


def test_example1():
example = Example1(parameter=1)
assert example.parameter == "parameter:1"

exampe_w_default = Example1WithDefault()
assert exampe_w_default.parameter == "parameter:1"


def test_example1_with_update():
example = Example1(parameter=1)
Expand Down Expand Up @@ -125,3 +147,10 @@ class MyDataClass(znfields.Base):
def test_metadata_must_be_dict():
with pytest.raises(TypeError):
znfields.field(metadata="not a dict", getter=lambda instance, name: None)


def test_default_factory():
example = Example1WithDefaultFactory()
assert example.parameter == []
example.parameter.append(1)
assert example.parameter == ["1"]

0 comments on commit 740c2de

Please sign in to comment.