Skip to content

Commit 0c1e566

Browse files
authored
[cleanup] Unique constants in tests + env variable for inference tests (#2855)
* Unique constants in tests + remove deprecated old token path + env variable for inference tests * fix tests * fix test
1 parent b19ab11 commit 0c1e566

File tree

5 files changed

+28
-48
lines changed

5 files changed

+28
-48
lines changed

src/huggingface_hub/constants.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,13 @@ def _as_int(value: Optional[str]) -> Optional[int]:
6363

6464
_HF_DEFAULT_ENDPOINT = "https://huggingface.co"
6565
_HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"
66-
ENDPOINT = os.getenv("HF_ENDPOINT", "").rstrip("/") or (
67-
_HF_DEFAULT_STAGING_ENDPOINT if _staging_mode else _HF_DEFAULT_ENDPOINT
68-
)
69-
66+
ENDPOINT = os.getenv("HF_ENDPOINT", _HF_DEFAULT_ENDPOINT).rstrip("/")
7067
HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
68+
69+
if _staging_mode:
70+
ENDPOINT = _HF_DEFAULT_STAGING_ENDPOINT
71+
HUGGINGFACE_CO_URL_TEMPLATE = _HF_DEFAULT_STAGING_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
72+
7173
HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"
7274
HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"
7375
HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"
@@ -143,18 +145,15 @@ def _as_int(value: Optional[str]) -> Optional[int]:
143145
or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/
144146
)
145147

146-
# In the past, token was stored in a hardcoded location
147-
# `_OLD_HF_TOKEN_PATH` is deprecated and will be removed "at some point".
148-
# See https://github.com/huggingface/huggingface_hub/issues/1232
149-
_OLD_HF_TOKEN_PATH = os.path.expanduser("~/.huggingface/token")
150148
HF_TOKEN_PATH = os.environ.get("HF_TOKEN_PATH", os.path.join(HF_HOME, "token"))
151149
HF_STORED_TOKENS_PATH = os.path.join(os.path.dirname(HF_TOKEN_PATH), "stored_tokens")
152150

153151
if _staging_mode:
154152
# In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens
153+
# In practice in `huggingface_hub` tests, we monkeypatch these values with temporary directories. The following
154+
# lines are only used in third-party libraries tests (e.g. `transformers`, `diffusers`, etc.).
155155
_staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging")
156156
HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub")
157-
_OLD_HF_TOKEN_PATH = os.path.join(_staging_home, "_old_token")
158157
HF_TOKEN_PATH = os.path.join(_staging_home, "token")
159158

160159
# Here, `True` will disable progress bars globally without possibility of enabling it

src/huggingface_hub/utils/_hf_folder.py

Lines changed: 4 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
# limitations under the License.
1515
"""Contain helper class to retrieve/store token from/to local cache."""
1616

17-
import warnings
1817
from pathlib import Path
1918
from typing import Optional
2019

@@ -23,10 +22,6 @@
2322

2423

2524
class HfFolder:
26-
path_token = Path(constants.HF_TOKEN_PATH)
27-
# Private attribute. Will be removed in v0.15
28-
_old_path_token = Path(constants._OLD_HF_TOKEN_PATH)
29-
3025
# TODO: deprecate when adapted in transformers/datasets/gradio
3126
# @_deprecate_method(version="1.0", message="Use `huggingface_hub.login` instead.")
3227
@classmethod
@@ -41,8 +36,9 @@ def save_token(cls, token: str) -> None:
4136
token (`str`):
4237
The token to save to the [`HfFolder`]
4338
"""
44-
cls.path_token.parent.mkdir(parents=True, exist_ok=True)
45-
cls.path_token.write_text(token)
39+
path_token = Path(constants.HF_TOKEN_PATH)
40+
path_token.parent.mkdir(parents=True, exist_ok=True)
41+
path_token.write_text(token)
4642

4743
# TODO: deprecate when adapted in transformers/datasets/gradio
4844
# @_deprecate_method(version="1.0", message="Use `huggingface_hub.get_token` instead.")
@@ -57,12 +53,6 @@ def get_token(cls) -> Optional[str]:
5753
Returns:
5854
`str` or `None`: The token, `None` if it doesn't exist.
5955
"""
60-
# 0. Check if token exist in old path but not new location
61-
try:
62-
cls._copy_to_new_path_and_warn()
63-
except Exception: # if not possible (e.g. PermissionError), do not raise
64-
pass
65-
6656
return get_token()
6757

6858
# TODO: deprecate when adapted in transformers/datasets/gradio
@@ -73,24 +63,6 @@ def delete_token(cls) -> None:
7363
Deletes the token from storage. Does not fail if token does not exist.
7464
"""
7565
try:
76-
cls.path_token.unlink()
77-
except FileNotFoundError:
78-
pass
79-
80-
try:
81-
cls._old_path_token.unlink()
66+
Path(constants.HF_TOKEN_PATH).unlink()
8267
except FileNotFoundError:
8368
pass
84-
85-
@classmethod
86-
def _copy_to_new_path_and_warn(cls):
87-
if cls._old_path_token.exists() and not cls.path_token.exists():
88-
cls.save_token(cls._old_path_token.read_text())
89-
warnings.warn(
90-
f"A token has been found in `{cls._old_path_token}`. This is the old"
91-
" path where tokens were stored. The new location is"
92-
f" `{cls.path_token}` which is configurable using `HF_HOME` environment"
93-
" variable. Your token has been copied to this new location. You can"
94-
" now safely delete the old token file manually or use"
95-
" `huggingface-cli logout`."
96-
)

tests/conftest.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,24 @@
66
from _pytest.fixtures import SubRequest
77

88
import huggingface_hub
9+
from huggingface_hub import constants
910
from huggingface_hub.utils import SoftTemporaryDirectory, logging
1011

1112
from .testing_utils import set_write_permission_and_retry
1213

1314

15+
@pytest.fixture(autouse=True, scope="function")
16+
def patch_constants(mocker):
17+
with SoftTemporaryDirectory() as cache_dir:
18+
mocker.patch.object(constants, "HF_HOME", cache_dir)
19+
mocker.patch.object(constants, "HF_HUB_CACHE", os.path.join(cache_dir, "hub"))
20+
mocker.patch.object(constants, "HUGGINGFACE_HUB_CACHE", os.path.join(cache_dir, "hub"))
21+
mocker.patch.object(constants, "HF_ASSETS_CACHE", os.path.join(cache_dir, "assets"))
22+
mocker.patch.object(constants, "HF_TOKEN_PATH", os.path.join(cache_dir, "token"))
23+
mocker.patch.object(constants, "HF_STORED_TOKENS_PATH", os.path.join(cache_dir, "stored_tokens"))
24+
yield
25+
26+
1427
logger = logging.get_logger(__name__)
1528

1629

tests/test_inference_client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,9 @@
106106
},
107107
}
108108
API_KEY_ENV_VARIABLES = {
109-
"hf-inference": "HF_TOKEN",
109+
"hf-inference": "HF_INFERENCE_TEST_TOKEN",
110110
"fal-ai": "FAL_AI_KEY",
111-
"fireworks-ai": "HF_TOKEN",
111+
"fireworks-ai": "HF_INFERENCE_TEST_TOKEN",
112112
"replicate": "REPLICATE_KEY",
113113
"sambanova": "SAMBANOVA_API_KEY",
114114
"together": "TOGETHER_API_KEY",

tests/testing_utils.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,7 @@
1515
import pytest
1616
import requests
1717

18-
from huggingface_hub.utils import (
19-
is_package_available,
20-
logging,
21-
reset_sessions,
22-
)
18+
from huggingface_hub.utils import is_package_available, logging, reset_sessions
2319
from tests.testing_constants import ENDPOINT_PRODUCTION, ENDPOINT_PRODUCTION_URL_SCHEME
2420

2521

0 commit comments

Comments
 (0)