Skip to content

Commit

Permalink
Fix writing with pre-opened file (#54)
Browse files Browse the repository at this point in the history
* Fixing #53

* Add regression test for the failing case.
  • Loading branch information
NowanIlfideme authored Apr 26, 2023
1 parent 8929096 commit 4b54ea8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/pydantic_yaml/dumper.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def _chk_model(model: Any) -> BaseModel:
raise TypeError(f"We can currently only write `pydantic.BaseModel`, but recieved: {model!r}")


def _write_yaml_model(stream: IOBase, model: BaseModel, **kwargs):
def _write_yaml_model(stream: IOBase, model: BaseModel, **kwargs) -> None:
"""Write YAML model to the stream object.
This uses JSON dumping as an intermediary.
Expand Down Expand Up @@ -88,6 +88,7 @@ def to_yaml_file(file: Union[Path, str, IOBase], model: BaseModel, **kwargs) ->
model = _chk_model(model)
if isinstance(file, IOBase):
_write_yaml_model(file, model, **kwargs)
return

if isinstance(file, str):
file = Path(file).resolve()
Expand Down
9 changes: 8 additions & 1 deletion src/test/test_basic.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"""Tests for basic functionality."""

from pathlib import Path
from typing import Type

import pydantic
import pytest
from pydantic import BaseModel

from pydantic_yaml import parse_yaml_file_as, parse_yaml_raw_as, to_yaml_str
from pydantic_yaml import parse_yaml_file_as, parse_yaml_raw_as, to_yaml_str, to_yaml_file
from pydantic_yaml.examples.base_models import (
A,
B,
Expand Down Expand Up @@ -77,3 +78,9 @@ def test_secret_yes_rt():
mdl = parse_yaml_raw_as(SecretTstModelDumpable, raw)
assert mdl.ss.get_secret_value() == "123"
assert mdl.sb.get_secret_value() == b"321"


def test_write_open_file(tmpdir):
"""Test writing to a pre-opened file."""
with (Path(tmpdir) / "test_write_open_file.yaml").open(mode="w") as f:
to_yaml_file(f, A(a="a"))

0 comments on commit 4b54ea8

Please sign in to comment.