You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
With pytest, I'm preparing the test_clients in a fixture, like in this minimal working example:
importosfromflaskimportFlask, render_template_stringimportflask_mailfromflask_securityimportSecurity, current_user, auth_required, hash_password, \
SQLAlchemySessionUserDatastore, UserMixin, RoleMixinfromflask.json.tagimportTaggedJSONSerializerfromitsdangerousimportURLSafeTimedSerializerimportpytestfromsqlalchemyimportcreate_engine, Boolean, DateTime, Column, Integer, \
String, ForeignKey, UnicodeTextfromsqlalchemy.ormimportrelationship, backref, scoped_session, sessionmakerfromsqlalchemy.ext.declarativeimportdeclarative_baseengine=create_engine('sqlite:///:memory:')
db_session=scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base=declarative_base()
Base.query=db_session.query_property()
classRolesUsers(Base):
__tablename__='roles_users'id=Column(Integer(), primary_key=True)
user_id=Column('user_id', Integer(), ForeignKey('user.id'))
role_id=Column('role_id', Integer(), ForeignKey('role.id'))
classRole(Base, RoleMixin):
__tablename__='role'id=Column(Integer(), primary_key=True)
name=Column(String(80), unique=True)
description=Column(String(255))
permissions=Column(UnicodeText)
classUser(Base, UserMixin):
__tablename__='user'id=Column(Integer, primary_key=True)
email=Column(String(255), unique=True)
username=Column(String(255), unique=True, nullable=True)
password=Column(String(255), nullable=False)
last_login_at=Column(DateTime())
current_login_at=Column(DateTime())
last_login_ip=Column(String(100))
current_login_ip=Column(String(100))
login_count=Column(Integer)
active=Column(Boolean())
fs_uniquifier=Column(String(255), unique=True, nullable=False)
confirmed_at=Column(DateTime())
roles=relationship('Role', secondary='roles_users',
backref=backref('users', lazy='dynamic'))
definit_db():
# import all modules here that might define models so that# they will be registered properly on the metadata. Otherwise# you will have to import them first before calling init_db()Base.metadata.create_all(bind=engine)
# Create appapp=Flask(__name__)
app.config['DEBUG'] =Trueapp.config['TESTING'] =True# Generate a nice key using secrets.token_urlsafe()app.config['SECRET_KEY'] =os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw')
app.config['WTF_CSRF_ENABLED'] =False# Bcrypt is set as default SECURITY_PASSWORD_HASH, which requires a salt# Generate a good salt using: secrets.SystemRandom().getrandbits(128)app.config['SECURITY_PASSWORD_SALT'] =os.environ.get("SECURITY_PASSWORD_SALT", '146585145368132386173505678016728509634')
app.config['SECURITY_REGISTERABLE'] =Trueapp.config['SECURITY_EMAIL_VALIDATOR_ARGS'] = {"check_deliverability": False}
app.config['SECURITY_PASSWORD_HASH'] ="plaintext"# Setup Flask-Securityuser_datastore=SQLAlchemySessionUserDatastore(db_session, User, Role)
app.security=Security(app, user_datastore)
# flask-mail extensionmail=flask_mail.Mail()
# initialize mail extensionmail.init_app(app)
# Views@app.route("/")@auth_required()defhome():
returnrender_template_string('Hello {{email}} !', email=current_user.email)
# one time setupwithapp.app_context():
# Create a user to test withinit_db()
if__name__=='__main__':
# run application (can also use flask run)app.run()
@pytest.fixture()defapplication():
withapp.app_context():
ifnotapp.security.datastore.find_user(email="[email protected]"):
app.security.datastore.create_user(email="[email protected]", password=hash_password("password"))
db_session.commit()
yieldapp@pytest.fixture()defclient_a(application):
client_a=application.test_client()
response=client_a.post("/register", data=dict(
email="[email protected]",
password="client A password",
password_confirm="client A password"),
follow_redirects=False
)
yieldclient_a@pytest.fixture()defclient_b(application):
client_b=application.test_client()
response_b=client_b.post(
"/register", data=dict(
email="[email protected]",
password="client B password",
password_confirm="client B password"
),
follow_redirects=False
)
yieldclient_bdefget_existing_session(client):
cookie=next(
(cookieforcookieinclient.cookie_jarifcookie.name=="session"), None
)
ifcookie:
serializer=URLSafeTimedSerializer("secret", serializer=TaggedJSONSerializer())
val=serializer.loads_unsafe(cookie.value)
returnval[1]
deftest_multi_clients_min(application, client_a, client_b):
client_a_session=get_existing_session(client_a)
client_b_session=get_existing_session(client_b)
assertclient_a_session["_user_id"] !=client_b_session["_user_id"]
It would be awesome if this would be possible with pytest-flask without logging in/out after every request that comes from a differnt user, as it would probably be much cleaner than with pytest alone.
The text was updated successfully, but these errors were encountered:
Is it possible to test with multiple clients, each logged in as different user to integration-test workflows, that involve multiple users?
I'm currently using flask-security and pytest for testing and wanted to give pytest-flask a try.
For example:
With pytest, I'm preparing the test_clients in a fixture, like in this minimal working example:
It would be awesome if this would be possible with pytest-flask without logging in/out after every request that comes from a differnt user, as it would probably be much cleaner than with pytest alone.
The text was updated successfully, but these errors were encountered: