Skip to content

Commit

Permalink
Add: Allow to create a binary file with temp_file context manager
Browse files Browse the repository at this point in the history
Extend temp_file context manager to support also creating binary files.
  • Loading branch information
bjoernricks committed Feb 26, 2024
1 parent 0bf1bac commit 893bcf2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
17 changes: 14 additions & 3 deletions pontos/testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@
import tempfile
from contextlib import contextmanager
from pathlib import Path
from typing import Any, AsyncIterator, Awaitable, Generator, Iterable, Optional
from typing import (
Any,
AsyncIterator,
Awaitable,
Generator,
Iterable,
Optional,
Union,
)

from pontos.git._git import exec_git
from pontos.helper import add_sys_path, ensure_unload_module, unload_module
Expand Down Expand Up @@ -136,7 +144,7 @@ def temp_git_repository(

@contextmanager
def temp_file(
content: Optional[str] = None,
content: Optional[Union[str, bytes]] = None,
*,
name: str = "test.toml",
change_into: bool = False,
Expand Down Expand Up @@ -166,7 +174,10 @@ def temp_file(
with temp_directory(change_into=change_into) as tmp_dir:
test_file = tmp_dir / name
if content:
test_file.write_text(content, encoding="utf8")
if isinstance(content, bytes):
test_file.write_bytes(content)
else:
test_file.write_text(content, encoding="utf8")
else:
test_file.touch()

Expand Down
9 changes: 9 additions & 0 deletions tests/testing/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#

import struct
import unittest
from pathlib import Path

Expand Down Expand Up @@ -109,6 +110,14 @@ def test_temp_file(self):

self.assertFalse(test_file.exists())

def test_temp_binary_file(self):
data = struct.pack(">if", 42, 2.71828182846)
with temp_file(data) as test_file:
self.assertTrue(test_file.exists())
self.assertEqual(data, test_file.read_bytes())

self.assertFalse(test_file.exists())

def test_temp_file_without_content(self):
with temp_file(name="foo.bar") as test_file:
self.assertTrue(test_file.exists())
Expand Down

0 comments on commit 893bcf2

Please sign in to comment.