Pickle funktioniert, aber PyTest versagtPython

Python-Programme
Anonymous
 Pickle funktioniert, aber PyTest versagt

Post by Anonymous »

Ich habe ein Modul erstellt, das eine Funktion enthält. Es funktioniert gut, aber es fällt PyTest nicht, zurück; < /p>

Code: Select all

>           pickle.dump(obj, file_handle, protocol=protocol)
E           AttributeError: Can't pickle local object 'test_object..TestObject'
< /code>
Laufen: < /p>

 Python 3.12 < /li>
 PyTest -Version: 8.3.5 < /li>
< /ul>
# lib.persist.py
from pathlib import Path
import pickle

def obj_pickle(obj: object, dir:Path, protocol: int = pickle.HIGHEST_PROTOCOL) -> None:
"""
Pickle an object to a byte file.
"""
if not dir.exists():
dir.mkdir(parents=True, exist_ok=True)
path = Path(dir, obj.instance_name + '.pkl')
with open(path, "wb") as file_handle:
pickle.dump(obj, file_handle, protocol=protocol)
print(f"{obj.__class__.__name__} object {obj.instance_name} saved to {path}")
< /code>
# tests.test_persist.py
from pathlib import Path

import pytest

from lib.persist import obj_pickle

TEST_DIR = Path("test_dir")

@pytest.fixture
def test_object():
class TestObject():
def __init__(self, instance_file_name):
self.instance_file_name = instance_file_name
self.data = "This is a test object."

test_object = TestObject("test_object_file")

return test_object

def test_obj_pickle(test_object):
obj_pickle(test_object, Path(TEST_DIR))
path = Path(TEST_DIR, "test_object_file" + ".pkl")
assert path.exists()

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post