ecmwf / ecmwf-api-client

Python API to access ECMWF archive
Apache License 2.0
66 stars 20 forks source link

Validation of credentials without querying anything? #16

Open din14970 opened 2 years ago

din14970 commented 2 years ago

I'm trying to write unit tests that will only run if valid credentials are found on the system running the tests. I'm using the get_api_key function but this will only query the information that is found on the system, not validate it. Is there an easy way to validate the credentials using the API?

cristian-codorean commented 2 years ago

@din14970, what about something like the following, valid for API client versions 1.6.3 or older:

import requests

from ecmwfapi.api import ANONYMOUS_APIKEY_VALUES
from ecmwfapi.api import Connection

def test_anonymous_apikey_using_requests():
    token, url, email = ANONYMOUS_APIKEY_VALUES

    response = requests.get(
        "{}/{}".format(url, "who-am-i"),
        headers={
            "Accept": "application/json",
            "From": email,
            "X-ECMWF-KEY": token,
        },
    )

    assert response.status_code == 200

def test_anonymous_apikey_using_connection():
    token, url, email = ANONYMOUS_APIKEY_VALUES

    connection = Connection(url, email=email, key=token)

    try:
        connection.call("{}/{}".format(url, "who-am-i"))
    except:
        assert False

Note one possible test directly queries the API using Python's requests. The other test uses the Connection object in the library so that the call to the API, and whatever else the library does, is abstracted.

Might look into adding these tests to the library itself.