title: Setting up database for testing in Flask
body: <p>I am developing my first Flask app. It is my side project, so I focus on good practises and design and take my time. I am a bit stuck on testing - I found some examples in docs and here on SO, but they either do not apply to my app or do not seem Pythonic/well designed.</p>
  <p>The relevant pieces of code are:</p>
  <pre><code># application module __init__.py
  def create_app(config):
      app = Flask(__name__)
      app.config.from_object('config.%s' % config.title())
      return app  
  
  config = os.getenv('CONFIG', 'development')
  app = create_app(config)
  db = SQLAlchemy(app)
  </code></pre>
  <h1></h1>
  <pre><code># config.py
  class Testing(Base):
      TESTING = True
      SQLALCHEMY_DATABASE_URI = \
          'sqlite:///' + os.path.join(_basedir, 'testing.sqlite')
  </code></pre>
  <h1></h1>
  <pre><code># models.py
  class User(db.Model):
      __tablename__ = 'user'
      id = db.Column(db.Integer, primary_key=True)
      username = db.Column(db.String(60), unique=True, nullable=False)
      password_hash = db.Column(db.String(60), nullable=False)
  </code></pre>
  <h1></h1>
  <pre><code># testing.py
  class TestCase(unittest.TestCase):
      
      def setUp(self):
          self.app = create_app('testing')
          # TODO: create connection to testing db
  
      def tearDown(self):
          # TODO: abort transaction
          pass
  </code></pre>
  <p>The question is: how to implement <code>setUp</code> and <code>tearDown</code> so that in my tests I can use my models and connection do testing database? If I just import <code>db</code>, it would work on development database.</p>
  <p>If it helps anything, I do not need to create testing db from scratch, I use Flask-Migrate and tests can assume the testing db is initialized and empty.</p>
  <p>Any comments are welcome, I do not mind refactoring if my design is flawed.</p>