我有课
TestSecured
在其中,我有一些方法可以获取受保护的端点,所以你需要一个jwt来发出请求。我正在尝试优化我的测试类,这样我就不需要登录3次,只需要登录1次,并在我的3个测试方法中使用相同的令牌。
@pytest.mark.usefixtures("client", "auth", "setup_user_and_token")
class TestSecured:
def test_get_operations(self, client, setup_user_and_token):
# headers = {'Authorization' : f'Beare {setup_user_and_token}'}
response = client.get(f'{SECURED_ROUTE}get-operations', headers=setup_user_and_token)
assert response.status_code == 200
def test_post_operation(self, client, auth):
return "ok"
def test_post_ope2(self,client,auth):
print("ok")
如果我用以下命令在每个方法中设置标头,它就可以工作了
setup_user_and_token()
我创造的装置。
@pytest.fixture(scope="class")
def setup_user_and_token(auth):
response = auth.login()
token = response.get_json()['access_token']
return {'Authorization' : f'Bearer {token}'}
但我想用
setup_class()
只做一次。我怎样才能做到这一点?
编辑:
下面是我的
conftest.py
我定义了一些夹具的文件:
@pytest.fixture
def app():
app = create_app({
'TESTING' : True,
})
yield app
with app.app_context():
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
class AuthActions(object):
def __init__(self, client):
self._client = client
def login(self, username='test_user', password='test_pass'):
return self._client.post(
'/auth/login',
json={'username': username, 'password': password}
)
def logout(self):
return self._client.get('/auth/logout')
def auth(client):
return AuthActions(client)
@pytest.fixture(scope="class")
def setup_user_and_token(auth):
response = auth.login()
token = response.get_json()['access_token']
return {'Authorization' : f'Bearer {token}'}