fix import format

This commit is contained in:
Kohaku-Blueleaf
2025-10-22 03:27:58 +08:00
parent 105d7ff6c2
commit f667b4b7fe
8 changed files with 30 additions and 124 deletions

View File

@@ -1,6 +1,7 @@
"""Base test classes and utilities for KohakuHub API tests."""
import os
import shutil
import tempfile
from pathlib import Path
from typing import Any
@@ -219,8 +220,6 @@ class BaseTestCase:
@classmethod
def teardown_class(cls):
"""Cleanup test class."""
import shutil
if hasattr(cls, "temp_dir") and Path(cls.temp_dir).exists():
shutil.rmtree(cls.temp_dir)

View File

@@ -6,10 +6,10 @@ Uses actual Pydantic models from the source code.
import uuid
import pytest
from tests.base import HTTPClient
from tests.config import config
from kohakuhub.auth.routes import CreateTokenRequest, LoginRequest, RegisterRequest
from kohakuhub.api.repo.routers.crud import CreateRepoPayload
class TestAuthentication:
@@ -26,9 +26,6 @@ class TestAuthentication:
def test_register_login_logout_flow(self, http_client):
"""Test complete user registration, login, and logout flow."""
# Import actual Pydantic models
from kohakuhub.auth.routes import RegisterRequest, LoginRequest
# Use unique username for this test
unique_id = uuid.uuid4().hex[:6]
test_username = f"user-{unique_id}" # Matches ^[a-z0-9][a-z0-9-]{2,62}$
@@ -76,8 +73,6 @@ class TestAuthentication:
def test_token_creation_and_usage(self, authenticated_http_client):
"""Test API token creation and usage."""
from kohakuhub.auth.routes import CreateTokenRequest
# 1. Create token using actual model
unique_id = uuid.uuid4().hex[:6]
token_payload = CreateTokenRequest(name=f"token-{unique_id}")
@@ -137,8 +132,6 @@ class TestAuthentication:
def test_invalid_credentials(self, http_client):
"""Test login with invalid credentials."""
from kohakuhub.auth.routes import LoginRequest
payload = LoginRequest(username="nonexistent", password="wrongpass")
resp = http_client.post("/api/auth/login", json=payload.model_dump())
@@ -151,8 +144,6 @@ class TestAuthentication:
assert resp.status_code == 401, "Should require authentication"
# Try to create repo without auth
from kohakuhub.api.repo.routers.crud import CreateRepoPayload
payload = CreateRepoPayload(type="model", name="test-repo")
resp = http_client.post("/api/repos/create", json=payload.model_dump())
@@ -160,8 +151,6 @@ class TestAuthentication:
def test_duplicate_registration(self, http_client):
"""Test that duplicate usernames are rejected."""
from kohakuhub.auth.routes import RegisterRequest
unique_id = uuid.uuid4().hex[:6]
test_username = f"dup-{unique_id}"
test_email = f"dup-{unique_id}@example.com"
@@ -187,8 +176,6 @@ class TestAuthentication:
def test_duplicate_email_registration(self, http_client):
"""Test that duplicate emails are rejected."""
from kohakuhub.auth.routes import RegisterRequest
unique_id = uuid.uuid4().hex[:6]
test_username = f"email-{unique_id}"
test_email = f"email-{unique_id}@example.com"

View File

@@ -7,11 +7,16 @@ Tests the complete workflow of:
- LFS recoverability checks
"""
import base64
import json
import os
import shutil
import tempfile
import time
from pathlib import Path
import pytest
import requests
from tests.base import HTTPClient
@@ -27,8 +32,6 @@ class TestBranchRevert:
test_content = os.urandom(100) # Random bytes
lfs_content = os.urandom(2000000) # 2MB random LFS file
import tempfile
temp_dir = Path(tempfile.mkdtemp())
(temp_dir / "revert-test.txt").write_bytes(test_content)
(temp_dir / "revert-test-lfs.bin").write_bytes(lfs_content)
@@ -73,16 +76,12 @@ class TestBranchRevert:
assert "revert-test-lfs.bin" not in files_after
# Cleanup
import shutil
shutil.rmtree(temp_dir)
def test_revert_non_conflicting(self, temp_repo):
"""Revert non-latest but non-conflicting commit with LFS."""
repo_id, repo_type, hf_client = temp_repo
import tempfile
temp_dir = Path(tempfile.mkdtemp())
# Commit 1: Add file1 with LFS (random content)
@@ -136,8 +135,6 @@ class TestBranchRevert:
assert "set1/file1.txt" not in files
# Cleanup
import shutil
shutil.rmtree(temp_dir)
@@ -148,8 +145,6 @@ class TestBranchReset:
"""Reset should create new commit, not delete history."""
repo_id, repo_type, hf_client = temp_repo
import tempfile
temp_dir = Path(tempfile.mkdtemp())
# Create 3 commits with random content
@@ -200,8 +195,6 @@ class TestBranchReset:
assert Path(downloaded).exists()
# Cleanup
import shutil
shutil.rmtree(temp_dir)
@pytest.mark.lfs
@@ -209,8 +202,6 @@ class TestBranchReset:
"""Reset with LFS files (should preserve LFS objects)."""
repo_id, repo_type, hf_client = temp_repo
import tempfile
temp_dir = Path(tempfile.mkdtemp())
# Create 3 versions with LFS (random content)
@@ -252,8 +243,6 @@ class TestBranchReset:
assert Path(downloaded).stat().st_size == 2000000 # 2MB
# Cleanup
import shutil
shutil.rmtree(temp_dir)
@@ -264,8 +253,6 @@ class TestBranchMerge:
"""Merge dev branch into main."""
repo_id, repo_type, hf_client = temp_repo
import tempfile
temp_dir = Path(tempfile.mkdtemp())
# Create initial file on main with random content
@@ -287,9 +274,6 @@ class TestBranchMerge:
assert resp.status_code == 200
# Upload different files to dev branch using direct API
import base64
import json
dev_txt_content = os.urandom(200) # Random content
dev_lfs_content = os.urandom(2000000) # Random 2MB LFS
@@ -321,8 +305,6 @@ class TestBranchMerge:
)
# Dev LFS file - upload to S3 first
import hashlib
sha256 = hashlib.sha256(dev_lfs_content).hexdigest()
# Get LFS upload URL
@@ -338,8 +320,6 @@ class TestBranchMerge:
upload_url = lfs_resp.json()["objects"][0]["actions"]["upload"]["href"]
# Upload to S3
import requests
s3_resp = requests.put(upload_url, data=dev_lfs_content)
assert s3_resp.status_code in (200, 204)
@@ -381,8 +361,6 @@ class TestBranchMerge:
assert "dev-lfs.bin" in files
# Cleanup
import shutil
shutil.rmtree(temp_dir)

View File

@@ -6,10 +6,14 @@ Covers both small files (inline) and large files (LFS).
import hashlib
import os
import shutil
import tempfile
from pathlib import Path
import pytest
from tests.base import HTTPClient
class TestFileOperations:
"""Test file upload, download, and deletion operations."""
@@ -19,8 +23,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Create small test file in temp directory
import tempfile
test_content = b"Hello, KohakuHub! This is a small test file."
test_file = (
Path(tempfile.gettempdir()) / f"test_small_{os.urandom(4).hex()}.txt"
@@ -52,8 +54,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Create temp folder with files
import tempfile
temp_dir = Path(tempfile.mkdtemp())
(temp_dir / "file1.txt").write_bytes(b"File 1 content")
(temp_dir / "file2.txt").write_bytes(b"File 2 content")
@@ -76,8 +76,6 @@ class TestFileOperations:
assert "uploaded_folder/subdir/file3.txt" in files
# Cleanup
import shutil
shutil.rmtree(temp_dir)
def test_download_file_hf_client(self, temp_repo):
@@ -85,8 +83,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Upload a file first
import tempfile
test_content = b"Download test content"
test_file = (
Path(tempfile.gettempdir()) / f"test_download_{os.urandom(4).hex()}.txt"
@@ -118,8 +114,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Upload a file first
import tempfile
test_content = b"File to be deleted"
test_file = (
Path(tempfile.gettempdir()) / f"test_delete_{os.urandom(4).hex()}.txt"
@@ -157,8 +151,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Upload multiple files
import tempfile
temp_dir = Path(tempfile.mkdtemp())
files_to_upload = {
"file1.txt": b"Content 1",
@@ -186,8 +178,6 @@ class TestFileOperations:
assert "subdir/file3.txt" in files
# Cleanup
import shutil
shutil.rmtree(temp_dir)
def test_file_metadata_head_request(self, random_user, temp_repo):
@@ -196,8 +186,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Upload a file
import tempfile
test_content = b"Metadata test content"
test_file = (
Path(tempfile.gettempdir()) / f"test_metadata_{os.urandom(4).hex()}.txt"
@@ -212,8 +200,6 @@ class TestFileOperations:
)
# HEAD request to get metadata using repo owner's token
from tests.base import HTTPClient
user_http_client = HTTPClient(token=token)
namespace, repo_name = repo_id.split("/")
@@ -235,8 +221,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Upload file with custom message
import tempfile
test_content = b"Commit message test"
test_file = (
Path(tempfile.gettempdir()) / f"test_commit_{os.urandom(4).hex()}.txt"
@@ -265,8 +249,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Create file with random content
import tempfile
test_content = os.urandom(100 * 1000) # 100KB random data
original_hash = hashlib.sha256(test_content).hexdigest()
@@ -320,8 +302,6 @@ class TestFileOperations:
repo_id, repo_type, hf_client = temp_repo
# Upload some files
import tempfile
temp_dir = Path(tempfile.mkdtemp())
(temp_dir / "file1.txt").write_bytes(b"Content 1")
(temp_dir / "dir1").mkdir()
@@ -335,8 +315,6 @@ class TestFileOperations:
)
# Query tree endpoint using repo owner's token
from tests.base import HTTPClient
user_http_client = HTTPClient(token=token)
namespace, repo_name = repo_id.split("/")
@@ -352,6 +330,4 @@ class TestFileOperations:
assert "file1.txt" in paths
# Cleanup
import shutil
shutil.rmtree(temp_dir)

View File

@@ -12,6 +12,8 @@ from pathlib import Path
import pytest
from tests.base import HTTPClient
class TestLFSOperations:
"""Test LFS file operations for large files."""
@@ -60,8 +62,6 @@ class TestLFSOperations:
repo_id, repo_type, hf_client = temp_repo
# Create 50MB file
import tempfile
size_mb = 50
test_content = os.urandom(size_mb * 1000 * 1000)
original_hash = hashlib.sha256(test_content).hexdigest()
@@ -98,8 +98,6 @@ class TestLFSOperations:
repo_id, repo_type, hf_client = temp_repo
# Create 5MB file (below LFS threshold)
import tempfile
size_mb = 5
test_content = os.urandom(size_mb * 1000 * 1000)
@@ -180,8 +178,6 @@ class TestLFSOperations:
repo_id, repo_type, hf_client = temp_repo
# Create HTTP client with the same user's token
from tests.base import HTTPClient
user_http_client = HTTPClient(token=token)
# Prepare LFS batch request
@@ -222,8 +218,6 @@ class TestLFSOperations:
repo_id, repo_type, hf_client = temp_repo
# Create temp folder with mixed sizes
import tempfile
temp_dir = Path(tempfile.mkdtemp())
# Small files (regular upload)
@@ -265,8 +259,6 @@ class TestLFSOperations:
repo_id, repo_type, hf_client = temp_repo
# Upload LFS file
import tempfile
test_content = os.urandom(15 * 1000 * 1000) # 15MB
test_file = (
Path(tempfile.gettempdir()) / f"test_lfs_meta_{os.urandom(4).hex()}.bin"
@@ -281,8 +273,6 @@ class TestLFSOperations:
)
# Query tree with expand=true to get LFS metadata using repo owner's token
from tests.base import HTTPClient
user_http_client = HTTPClient(token=token)
namespace, repo_name = repo_id.split("/")

View File

@@ -6,8 +6,12 @@ Uses actual Pydantic models from source code.
import uuid
import pytest
from kohakuhub.api.org.router import (
AddMemberPayload,
CreateOrganizationPayload,
UpdateMemberRolePayload,
)
from kohakuhub.auth.routes import RegisterRequest
from tests.config import config
@@ -16,8 +20,6 @@ class TestOrganization:
def test_create_organization(self, authenticated_http_client):
"""Test organization creation."""
from kohakuhub.api.org.router import CreateOrganizationPayload
unique_id = uuid.uuid4().hex[:6]
org_name = f"org-{unique_id}"
@@ -50,9 +52,6 @@ class TestOrganization:
def test_add_remove_member(self, authenticated_http_client, test_org):
"""Test adding and removing organization members."""
from kohakuhub.auth.routes import RegisterRequest
from kohakuhub.api.org.router import AddMemberPayload
# Create a new user to add as member
unique_id = uuid.uuid4().hex[:6]
member_username = f"mem-{unique_id}"
@@ -98,9 +97,6 @@ class TestOrganization:
def test_update_member_role(self, authenticated_http_client, test_org):
"""Test updating organization member role."""
from kohakuhub.auth.routes import RegisterRequest
from kohakuhub.api.org.router import AddMemberPayload, UpdateMemberRolePayload
# Create a new user
unique_id = uuid.uuid4().hex[:6]
member_username = f"mem-{unique_id}"
@@ -157,8 +153,6 @@ class TestOrganization:
def test_duplicate_organization(self, authenticated_http_client, test_org):
"""Test that creating duplicate organization fails."""
from kohakuhub.api.org.router import CreateOrganizationPayload
# Try to create organization with same name
payload = CreateOrganizationPayload(name=test_org, description="Duplicate org")

View File

@@ -9,6 +9,11 @@ import uuid
import pytest
from huggingface_hub.utils import HfHubHTTPError
from kohakuhub.api.repo.routers.crud import (
CreateRepoPayload,
DeleteRepoPayload,
MoveRepoPayload,
)
from tests.config import config
@@ -38,8 +43,6 @@ class TestRepositoryCRUD:
def test_create_repo_http_client(self, authenticated_http_client):
"""Test repository creation using custom HTTP client with Pydantic model."""
from kohakuhub.api.repo.routers.crud import CreateRepoPayload
unique_id = uuid.uuid4().hex[:6]
repo_name = f"htc-{unique_id}" # htc = http-create
@@ -65,8 +68,6 @@ class TestRepositoryCRUD:
assert resp.status_code == 200, f"Get repo info failed: {resp.text}"
# Cleanup using actual delete model
from kohakuhub.api.repo.routers.crud import DeleteRepoPayload
delete_payload = DeleteRepoPayload(
type="model", name=repo_name, organization=None
)
@@ -189,8 +190,6 @@ class TestRepositoryCRUD:
def test_move_repo(self, authenticated_http_client, hf_client):
"""Test moving/renaming repository."""
from kohakuhub.api.repo.routers.crud import MoveRepoPayload
unique_id = uuid.uuid4().hex[:6]
old_name = f"old-{unique_id}"
new_name = f"new-{unique_id}"
@@ -244,8 +243,6 @@ class TestRepositoryCRUD:
def test_create_org_repo(self, authenticated_http_client, hf_client, test_org):
"""Test creating repository under organization."""
from kohakuhub.api.repo.routers.crud import CreateRepoPayload
unique_id = uuid.uuid4().hex[:6]
repo_name = f"org-{unique_id}"

View File

@@ -3,6 +3,11 @@
Tests repository metadata, listing, filtering, and privacy.
"""
import shutil
import tempfile
import uuid
from pathlib import Path
import pytest
from tests.base import HTTPClient
@@ -41,8 +46,6 @@ class TestRepositoryInfo:
def test_list_repos_by_author(self, random_user):
"""Test listing repositories by author."""
import uuid
username, token, hf_client = random_user
unique_id = uuid.uuid4().hex[:6]
@@ -74,9 +77,6 @@ class TestRepositoryInfo:
assert len(repos) <= 5
def test_list_namespace_repos(self, random_user):
"""Test listing all repos under a namespace (user)."""
import uuid
username, token, hf_client = random_user
unique_id = uuid.uuid4().hex[:6]
@@ -109,8 +109,6 @@ class TestRepositoryInfo:
def test_private_repo_visibility(self, random_user):
"""Test that private repositories are only visible to owner."""
import uuid
username, token, hf_client = random_user
unique_id = uuid.uuid4().hex[:6]
@@ -146,9 +144,6 @@ class TestRepositoryInfo:
repo_id, repo_type, hf_client = temp_repo
# Upload file to create commit
import tempfile
from pathlib import Path
temp_file = Path(tempfile.mktemp())
temp_file.write_bytes(b"Test content")
@@ -204,9 +199,6 @@ class TestRepositoryInfo:
repo_id, repo_type, hf_client = temp_repo
# Upload some files
import tempfile
from pathlib import Path
temp_dir = Path(tempfile.mkdtemp())
(temp_dir / "README.md").write_bytes(b"# Test Repo")
(temp_dir / "config.json").write_bytes(b'{"key": "value"}')
@@ -228,8 +220,6 @@ class TestRepositoryInfo:
assert "data/file.txt" in files
# Cleanup
import shutil
shutil.rmtree(temp_dir)
def test_tree_recursive_listing(self, random_user, temp_repo):
@@ -238,9 +228,6 @@ class TestRepositoryInfo:
repo_id, repo_type, hf_client = temp_repo
# Upload nested structure
import tempfile
from pathlib import Path
temp_dir = Path(tempfile.mkdtemp())
(temp_dir / "level1").mkdir()
(temp_dir / "level1" / "file1.txt").write_bytes(b"File 1")
@@ -271,6 +258,4 @@ class TestRepositoryInfo:
assert any("level1/level2/file2.txt" in p for p in paths)
# Cleanup
import shutil
shutil.rmtree(temp_dir)