简体   繁体   English

python - 使用 pytest 进行 Flask 基本身份验证测试

[英]python - Flask basic auth testing with pytest

I'm currently using Flask-HTTPAuth for basic authentication within my project.我目前在我的项目中使用 Flask-HTTPAuth 进行基本身份验证。 I've tested it by hand using curl and base64 tokens and it does indeed work.我已经使用 curl 和 base64 令牌手动测试了它,它确实有效。 However I'm running into problems creating tests proving it works.但是,我在创建测试以证明它有效时遇到了问题。 This is my current test and it always turns back 401:这是我当前的测试,它总是返回 401:

class TestLoginApi类 TestLoginApi

def setup(self):
    myapp.app.config.from_object("config.TestingConfig")
    self.app = myapp.app.test_client()
    client = MongoClient(myapp.app.config['DATABASE_URL'])
    db = client.get_default_database()
    assert list(db.collection_names()) == []

    db.users.insert_one({'name': 'testuser', 'password': 'testpassword'})

def teardown(self):
    client = MongoClient(myapp.app.config['DATABASE_URL'])
    client.drop_database(client.get_default_database())

def test_not_logged_in(self):
    rv = self.app.get('/api/v1/login/')
    assert rv.status_code == 401

def test_correct_password(self):
    d = Headers()
    d.add('Authorization', 'Basic dGVzdHVzZXI6dGVzdHBhc3N3b3Jk')
    rv = self.app.get('/api/v1/login/', headers=d,
        content_type='application/json')
    assert rv.status_code == 200

I've also tried changing the following:我还尝试更改以下内容:

def test_correct_password(self):
        d = Headers()
        d.add('Authorization', 'Basic dGVzdHVzZXI6dGVzdHBhc3N3b3Jk')
        rv = self.app.get('/api/v1/login/', headers=d,
            content_type='application/json')
        assert rv.status_code == 200

to this with no success:对此没有成功:

def test_correct_password(self):
         rv = self.app.get('/api/v1/login/', headers={"Authorization": "Basic {user}".format(user=base64.b64encode(b"testuser:testpassword"))})
         assert rv.status_code == 200

You can test authorization like this:您可以像这样测试授权:

import base64

valid_credentials = base64.b64encode(b"testuser:testpassword").decode("utf-8")
response = self.app.get(
    "/api/v1/login/",
    headers={"Authorization": "Basic " + valid_credentials}
)
assert response.status_code == 200

I think you would enjoy my github project , which has a tons of different tests for Flask-HTTPAuth.我想你会喜欢我的 github 项目,它有大量不同的 Flask-HTTPAuth 测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM