I have an app with SQLAlchemy, initialized:
config_name = os.getenv('FLASK_CONFIG') or 'default'
app = Flask(__name__)
db = SQLAlchemy(app)
db.init_app(app)
and a view I'm working on that just returns all users in json format:
@app.route('/users', methods=['GET'])
def users():
users = db.session.query(User)
output = {'users': [user.to_json() for user in users]}
return jsonify(**output)
And my test:
class UserViewTest(BaseTestCase, CreateUserMixin):
def test_users(self):
user1 = self._make_user() # defined in the above mixin
user2 = self._make_user()
user2.email = 'hello@abc.com'
user2.username = 'hello@abc.com'
db.session.add_all([user1, user2])
db.session.flush()
response = app.test_client().get('/users')
I run my tests with FLASK_CONFIG=testing nosetests
(and I checked, app.testing is set to true).
Running this against my psql database, I'm finding these users I added to the database are being saved!
triller_social_test=# SELECT username FROM users;
username
---------------
foobar
hello@abc.com
(2 rows)
How do I stop this from happening? I tried overwriting db.session.commit() to do nothing, but the database rollsback when I call the view. Is there an alternative to using test_client()
? I can't call the method directly, since jsonify
doesn't allow me to return data anywhere besides a response.
Update: Here's my temporary(?) solution:
def json_response_converter(dict_):
if config_name == 'testing':
return dict_
else:
return jsonify(**dict_)
Now I don't need to use jsonify() in my tests