2016-05-03 50 views
2

model.py儲存的實體,似乎並沒有應用程序上下文中存在

from sqlalchemy.ext.declarative import declarative_base 
... 
Base = declarative_base() 

class Team(Base): 
    id = Column(String, unique=True, primary_key=True) 
    name = Column(String, nullable=False) 

engine = create_engine('sqlite://') 
Base.metadata.create_all(engine) 
Session = sessionmaker(bind=engine) 

test_app.py

from model import Team, Session, engine 
class TestApp(TestCase): 
    def setUp(self): 
     self.connection = engine.connect() 
     self.trans = self.connection.begin() 
     self.session = Session(bind=self.connection) 

    def tearDown(self): 
     self.session.close() 
     self.trans.rollback() 
     self.connection.close() 

    @patch('realtime_bot.rtmbot.RtmBot.start') 
    def test_app_creates_one_rtmbot(self, mck): 
     team = Team('1', 't1') 
     self.session.add(team) 
     self.session.commit() 
     app = MyApp() 
     app.start() 
     self.assertEqual(len(app.bots), 1) 

當我在此設置一個調試器測試,我可以看到內存中的db確實有一個Team實體。

但是,一旦app.start()啓動,db已經是空的了。

MyApp.py

from src.model import Session, Team 
class MyApp(object): 
    def __init__(self, directory): 
     super(MyApp, self).__init__() 
     self.bots = [] 
     self.session = Session() 

    def start(self): 
     teams = self.session.query(Team).all() 

我想這有可能與會議嗎?但是我從模型中導入了兩個,因此它應該是同一個實例。我有點卡在這裏,希望得到一些幫助。謝謝

回答

0

似乎沒有多少人在沒有Flask-Alchemy擴展的情況下使用純SQLAlchemy。

我終於找到了解決方案。

正如我所懷疑的,關鍵是在單元測試和應用程序本身內使用同一個會話。

MyApp.py

from src.model import Session, Team, engine 
class MyApp(object): 
    def __init__(self, directory): 
     super(MyApp, self).__init__() 
     self.bots = [] 
     self.connection = engine.connect() 
     self.session = Session(bind=self.connection) 

而在單元測試類:

class TestApp(TestCase): 
    def setUp(self): 
     self.connection = engine.connect() 
     self.trans = self.connection.begin() 
     self.app = MyApp() 
     self.session = self.app.session 
相關問題