0

我有单元测试

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 单元测试的新手,当我必须连接到数据库时不知道如何测试。请指教

4

1 回答 1

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())
于 2013-03-30T05:48:43.443 回答