我有单元测试
class TestUser(TestCase):
def setUp(self):
print 'setting db up'
db.create_all()
def test_new_user(self):
user = User('test_new_user@none.com', 'welcome')
db.session.add(user)
db.session.commit()
users_in_db = User.query.all()
self.assertEquals(1, len(users_in_db))
self.assertEquals(user.email, users_in_db[0].email)
self.assertEquals(user._password, users_in_db[0]._password)
def tearDown(self):
print 'destroying db'
db.drop_all()
当我在命令行上运行时,我看到了
python -m unittest discover
secret key: test secret key
db url: postgresql+psycopg2://testuser:testpasswd@localhost/mydb
setting db up
destroying db
但它永远不会出现,继续悬挂,我做错了什么? 我是python单元测试的新手,不知道如何测试我必须连接到数据库。请指教
答案 0 :(得分:0)
经过一段时间的努力并环顾四周后,以下内容开始为我效劳。 它的效率很低,因为它会丢弃所有表并为每次测试再次创建它们,但是现在根据用例,它很好,稍后将添加优化。
Donald Knuth也说道。
“过早的优化是所有邪恶的根本原因”
class TestUser(TestCase):
def setUp(self):
db.create_all()
def session_commit(self):
try:
db.session.commit()
except:
db.session.rollback()
finally:
pass
def test_new_user(self):
"""
test that new user is persisted in database
"""
user = User('test_new_user@none.com', 'welcome')
db.session.add(user)
self.session_commit()
users_in_db = db.session.query(User).all()
self.assertEquals(1, len(users_in_db))
self.assertEquals(user.email, users_in_db[0].email)
self.assertEquals(user._password, users_in_db[0]._password)
def tearDown(self):
db.session.close()
for tbl in reversed(db.metadata.sorted_tables):
db.engine.execute(tbl.delete())