title: Flask-SQLALchemy Unit Test Problems
body: <p>I'm writing a web app by imitating <a href="http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-unit-testing" rel="nofollow">The Flask Mega-Tutorial</a>.</p>
  
  <p>As I was trying to add some unit test cases to my code. I found that the test cases in the Tutorial had many duplicated codes.</p>
  
  <p>Here is the code segments:</p>
  
  <pre><code>def test_avatar(self):
      u = User(nickname='john', email='john@example.com')
      avatar = u.avatar(128)
      expected = 'http://www.gravatar.com/avatar/d4c74594d841139328695756648b6bd6'
      ...
  
  def test_make_unique_nickname(self):
      u = User(nickname='john', email='john@example.com')
      db.session.add(u)
      db.session.commit()
      ...
  </code></pre>
  
  <p>The problem is that every time I want to test a new case I have to repeat this process：</p>
  
  <pre><code>u = User(nickname='john', email='john@example.com')
  db.session.add(u)
  db.session.commit()
  </code></pre>
  
  <p>So, I moved this process out and made it like this:</p>
  
  <pre><code>import unittest
  
  from config import basedir
  from app import app, db
  from app.models import User
  
  u = User(nickname='john', email='john@example.com')  # I put this out because some cases may want to use this stuff.
  
  def _init_database():
      db.session.add(u)
      db.session.commit(u)
  
  class TestCase(unittest.TestCase):
      def setUp(self):
          app.config['TESTING'] = True
          app.config['WTF_CSRF_ENABLED'] = False
          app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:')
          self.app = app.test_client()
          db.create_all()
          _init_database()  # init database every time
  
      def tearDown(self):
          db.session.remove()
          db.drop_all()
  
      def test_case_1(self):
          self.assertTrue(User.query.count() == 1)  # case 1
  
      def test_case_2(self):
          self.assertTrue(User.query.count() == 1)  # case 1
  
  if __name__ == '__main__':
      unittest.main()
  </code></pre>
  
  <p>As you can see, two test cases are the same. However, <strong>only one case can pass. the other one will fail</strong>.</p>
  
  <p>But if I move <code>u = User(nickname='john', email='john@example.com')</code> into <code>_init_database()</code>:</p>
  
  <pre><code>def _init_database():
      u = User(nickname='john', email='john@example.com')
      db.session.add(u)
      db.session.commit(u)
  </code></pre>
  
  <p>every thing is fine now.</p>
  
  <p>I really don't know why! Could you help me?</p>