简体   繁体   中英

python - Flask basic auth testing with pytest

I'm currently using Flask-HTTPAuth for basic authentication within my project. I've tested it by hand using curl and base64 tokens and it does indeed work. However I'm running into problems creating tests proving it works. This is my current test and it always turns back 401:

class 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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