Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidRequestError: Instance '<User at 0x7f65938a7510>' is not persisted

I want to perform such a test in the framework Flask and gets the message:

InvalidRequestError: Instance '<User at 0x7f65938a7510>' is not persisted

  File "tests.py", line 31, in test_removeProfil
    db.session.delete(user)

My test code:

class TestCase(unittest.TestCase):

    def test_removeProfil(self):
        user = User(name="John", age=33, email="[email protected]")
        db.session.delete(user)
        db.session.commit()
        self.assertNotEqual(user.name, "John")
        self.assertNotEqual(user.age, 33)
        self.assertNotEqual(user.email, "[email protected]")
like image 974
Mark Avatar asked Oct 27 '14 22:10

Mark


2 Answers

You are trying to delete a new instance, rather than an instance you got from the database. Either you meant to use db.session.add(), or you meant to use user = User.query.filter_by(email='[email protected]').first() (or something similar) and delete that.

You might also have trouble accessing attributes of the deleted instance (assuming you delete it correctly as above). When you commit a session, all instances in that session are expired. Trying to access an expired attribute triggers a database lookup, but there can be no lookup for this object because it was deleted.

You can turn expire_on_commit off, but that is not the normal behavior and will probably cause you other problems.

You could also try calling make_transient on it.

Ultimately, you should really just abandon instances that have been deleted. There is probably a better way to do whatever you are trying to accomplish.

like image 143
davidism Avatar answered Nov 07 '22 12:11

davidism


When you call

user = User(name="John", age=33, email="[email protected]")

you create python object, not object in db. So you need first add it to db

db.session.add(user)
db.session.commit()

after it you can delete it from db

db.session.delete(user)
db.session.commit()

and your assertNotEqual have no sence. You should test that result of select from db before and after delete is different

like image 32
Ryabchenko Alexander Avatar answered Nov 07 '22 11:11

Ryabchenko Alexander