Examples from https://stackoverflow.com/questions/69152143/private-attributes-in-pydantic
I added the bottom two tests in test.py
, while post_pydantic.py
is unmodified from https://stackoverflow.com/a/71742829/10778553
Output from running pytest looks like
$ pytest test.py
======================================================================================================================== test session starts =========================================================================================================================
platform win32 -- Python 3.9.1, pytest-7.1.2, pluggy-1.0.0
rootdir: C:\Users\jdcottle\Documents\test
collected 3 items
test.py .FF [100%]
============================================================================================================================== FAILURES ==============================================================================================================================
_________________________________________________________________________________________________________________ test_random_function_has_no_access _________________________________________________________________________________________________________________
def test_random_function_has_no_access():
"""Verify that random functions can't set private attributes on models. """
def edit_post(self, post: post_pydantic.Post, new_title: str):
"""Nefarious function attempting to circumvent protections. """
post.title = new_title
post_id = uuid4()
post = post_pydantic.Post(post_id=post_id, title="Test Title")
with pytest.raises(Exception):
> edit_post(None, post, new_title="This should not work")
E Failed: DID NOT RAISE <class 'Exception'>
test.py:37: Failed
__________________________________________________________________________________________________________________ test_random_class_has_no_access ___________________________________________________________________________________________________________________
def test_random_class_has_no_access():
"""Verify that random classes can't set private attributes on models. """
post_id = uuid4()
post = post_pydantic.Post(post_id=post_id, title="Test Title")
with pytest.raises(Exception):
> Foo(post)
E Failed: DID NOT RAISE <class 'Exception'>
test.py:54: Failed
====================================================================================================================== short test summary info =======================================================================================================================
FAILED test.py::test_random_function_has_no_access - Failed: DID NOT RAISE <class 'Exception'>
FAILED test.py::test_random_class_has_no_access - Failed: DID NOT RAISE <class 'Exception'>
==================================================================================================================== 2 failed, 1 passed in 0.53s =====================================================================================================================