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

时间:2017-08-02 05:59:56

标签: python testing flask pytest

我目前正在使用Flask-HTTPAuth在我的项目中进行基本身份验证。我使用curl和base64令牌手动测试它确实有效。然而,我遇到了创建测试证明它有效的问题。这是我目前的测试,它总是回到401:

类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

我也试过更改以下内容:

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

对此没有成功:

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

1 个答案:

答案 0 :(得分:5)

您可以像这样测试授权:

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 == '200 OK'

我想你会喜欢my github project,它有很多不同的Flask-HTTPAuth测试。