jeancochrane / jeancochrane/pytest-flask-sqlalchemy

Objects left on transient state

Open
#47 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
253
Forks
45
PR merge metrics
No merged PRs in 30d

Description

I'm finding that my objects are left on a transient state, and that attributes have the wrong type. I've review the docs and other issues on the issue tracker, and I can't see what I am doing wrong.

I have a `pytest.ini` file with:
```
[pytest]
mocked-sessions = my_project.models.db.session
```

And a `conftest.py`:
```python
import pytest

from my_project.api.app import create_app
from my_project.models import db

@pytest.fixture(scope="session")
def app():
app = create_app("my_config_file.py")
app.testing = True
return app

@pytest.fixture(scope="session")
def _db(app):
return db
```

If you are curious about `create_app`, it's a straightforward Flask app factory:
```python
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)

from my_project.models import db

db.init_app(app)

from my_project.api.schemas import ma

ma.init_app(app)

from my_project.api.resources import api

api.init_app(app)

return app
```

I have this simple test which POSTs a string and a date, used to instantiate and commit a SQLAlchemy model:
```python
@pytest.mark.usefixtures("client_class")
class TestMyRoute:
def test_create_simple(self, db_session):
request_payload = {"name": "foo", "my_date": "2022-07-29"}
resp = self.client.post(LicenseConfigurationCollection.route, json=request_payload)
assert resp.status_code == HTTPStatus.OK
assert is_sub_dict(request_payload,resp.json["data"])
```

The serialization of this response fails. If I set a breakpoint, I see that just before generating the response, after the object has been created, added to the session and commited, this is how the object looks like:
```
(Pdb) obj

(Pdb) obj.my_date
'2022-07-29'
(Pdb) obj.id
(Pdb) obj.created
(Pdb)
```
As you can see, the date is on string format, which is not correct as it should be a `datetime.date`, given that it's declared on the model as `my_date = db.Column(db.Date, nullable=True)`. Also, `id` and `created` are not initialized either, as expected of a transient object.

The created object is added to the session and it is committed properly. Proof is that if I remove the `db_session` fixture, the code works and the record is created on the DB. Using postman I am also able to verify it. Any insight?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.