def test_should_return_401_if_load_account_by_id_raise_jwt_exception(
        mock_load: MagicMock, mock_get_collection: MagicMock,
        sut: AuthMiddleware):
    mock_load.side_effect = InvalidTokenError()
    mock_get_collection.return_value = mongomock.MongoClient().db.collection
    http_response = sut.handle(
        HttpRequest(headers={"x-access-token": "any_token"}, body=None))
    assert http_response.status_code == 401
    assert http_response.body["message"] == "Unauthorized"
def test_should_return_500_if_load_account_by_id_raise_exception(
        mock_load: MagicMock, mock_get_collection: MagicMock,
        sut: AuthMiddleware):
    mock_load.side_effect = Exception("Error on matrix")
    mock_get_collection.return_value = mongomock.MongoClient().db.collection
    http_response = sut.handle(
        HttpRequest(headers={"x-access-token": "any_token"}, body=None))
    assert http_response.status_code == 500
    assert http_response.body["message"] == "Internal server error"
def make_auth_middleware(role: str = None):
    account_collection = get_collection("accounts")
    load_account_by_id_repo = AccountMongoRepo(account_collection)
    decrypter = JwtAdapter(
        secret=env.JWT_SECRET_KEY,
        expiration_time=datetime.utcnow() + timedelta(hours=env.JWT_EXPIRATION_TIME),
        algorithm="HS256",
    )
    db_load_account_by_token = DbLoadAccountById(decrypter, load_account_by_id_repo)

    return AuthMiddleware(load_account_by_id=db_load_account_by_token, role=role)
def test_should_return_200_if_load_account_by_id_returns_an_account(
    sut: AuthMiddleware, ):
    http_response = sut.handle(
        HttpRequest(headers={"x-access-token": "any_token"}, body=None))
    assert http_response.status_code == 200
    assert http_response.body
def test_should_return_403_if_load_account_by_id_returns_none(
        mock_load: MagicMock, sut: AuthMiddleware):
    mock_load.return_value = None
    http_response = sut.handle(
        HttpRequest(headers={"x-access-token": "any_token"}, body=None))
    assert http_response.status_code == 403
def test_should_calls_load_account_by_id_correct_values(
        mock_load: MagicMock, sut: AuthMiddleware):
    sut.handle(HttpRequest(headers={"x-access-token": "any_token"}, body=None))
    mock_load.assert_called_with(access_token="any_token", role=None)
def test_should_return_403_if_no_access_token_exists_in_headers(
        sut: AuthMiddleware):
    http_response = sut.handle(HttpRequest(headers=None, body=None))
    assert http_response.status_code == 403
    assert http_response.body["message"] == "Access danied"
def sut():
    load_account_by_id_stub = LoadAccountByIdStub()
    yield AuthMiddleware(load_account_by_id_stub)