standard-tests: Add ruff rule UP (pyupgrade) (#31842)

See https://docs.astral.sh/ruff/rules/#pyupgrade-up
All auto-fixed
This commit is contained in:
Christophe Bornet 2025-07-03 16:12:31 +02:00 committed by GitHub
parent 802d2bf249
commit cd7dce687a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 63 additions and 71 deletions

View File

@ -1,5 +1,4 @@
from abc import ABC
from typing import Type
class BaseStandardTests(ABC):
@ -16,7 +15,7 @@ class BaseStandardTests(ABC):
# find path to standard test implementations
comparison_class = None
def explore_bases(cls: Type) -> None:
def explore_bases(cls: type) -> None:
nonlocal comparison_class
for base in cls.__bases__:
if base.__module__.startswith("langchain_tests."):

View File

@ -7,7 +7,8 @@ We don't recommend implementing externally managed BaseStore abstractions at thi
"""
from abc import abstractmethod
from typing import AsyncGenerator, Generator, Generic, Tuple, TypeVar
from collections.abc import AsyncGenerator, Generator
from typing import Generic, TypeVar
import pytest
from langchain_core.stores import BaseStore
@ -38,11 +39,11 @@ class BaseStoreSyncTests(BaseStandardTests, Generic[V]):
@abstractmethod
@pytest.fixture()
def three_values(self) -> Tuple[V, V, V]:
def three_values(self) -> tuple[V, V, V]:
"""Three example values that will be used in the tests."""
pass
def test_three_values(self, three_values: Tuple[V, V, V]) -> None:
def test_three_values(self, three_values: tuple[V, V, V]) -> None:
"""Test that the fixture provides three values."""
assert isinstance(three_values, tuple)
assert len(three_values) == 3
@ -53,7 +54,7 @@ class BaseStoreSyncTests(BaseStandardTests, Generic[V]):
assert kv_store.mget(keys) == [None, None, None]
def test_set_and_get_values(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test setting and getting values in the key-value store."""
foo = three_values[0]
@ -72,7 +73,7 @@ class BaseStoreSyncTests(BaseStandardTests, Generic[V]):
assert kv_store.mget(keys) == [None]
def test_delete_values(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test deleting values from the key-value store."""
foo = three_values[0]
@ -83,7 +84,7 @@ class BaseStoreSyncTests(BaseStandardTests, Generic[V]):
assert kv_store.mget(["foo", "bar"]) == [None, bar]
def test_delete_bulk_values(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test that we can delete several values at once."""
foo, bar, buz = three_values
@ -98,7 +99,7 @@ class BaseStoreSyncTests(BaseStandardTests, Generic[V]):
kv_store.mdelete(["foo", "bar", "baz"])
def test_set_values_is_idempotent(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Setting values by key should be idempotent."""
foo, bar, _ = three_values
@ -109,7 +110,7 @@ class BaseStoreSyncTests(BaseStandardTests, Generic[V]):
assert sorted(kv_store.yield_keys()) == ["bar", "foo"]
def test_get_can_get_same_value(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test that the same value can be retrieved multiple times."""
foo, bar, _ = three_values
@ -119,7 +120,7 @@ class BaseStoreSyncTests(BaseStandardTests, Generic[V]):
assert kv_store.mget(["foo", "bar", "foo", "bar"]) == [foo, bar, foo, bar]
def test_overwrite_values_by_key(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test that we can overwrite values by key using mset."""
foo, bar, buzz = three_values
@ -134,7 +135,7 @@ class BaseStoreSyncTests(BaseStandardTests, Generic[V]):
assert kv_store.mget(["foo", "bar"]) == [buzz, bar]
def test_yield_keys(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test that we can yield keys from the store."""
foo, bar, _buzz = three_values
@ -169,11 +170,11 @@ class BaseStoreAsyncTests(BaseStandardTests):
@abstractmethod
@pytest.fixture()
def three_values(self) -> Tuple[V, V, V]:
def three_values(self) -> tuple[V, V, V]:
"""Three example values that will be used in the tests."""
pass
async def test_three_values(self, three_values: Tuple[V, V, V]) -> None:
async def test_three_values(self, three_values: tuple[V, V, V]) -> None:
"""Test that the fixture provides three values."""
assert isinstance(three_values, tuple)
assert len(three_values) == 3
@ -184,7 +185,7 @@ class BaseStoreAsyncTests(BaseStandardTests):
assert await kv_store.amget(keys) == [None, None, None]
async def test_set_and_get_values(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test setting and getting values in the key-value store."""
foo = three_values[0]
@ -203,7 +204,7 @@ class BaseStoreAsyncTests(BaseStandardTests):
assert await kv_store.amget(keys) == [None]
async def test_delete_values(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test deleting values from the key-value store."""
foo = three_values[0]
@ -214,7 +215,7 @@ class BaseStoreAsyncTests(BaseStandardTests):
assert await kv_store.amget(["foo", "bar"]) == [None, bar]
async def test_delete_bulk_values(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test that we can delete several values at once."""
foo, bar, buz = three_values
@ -229,7 +230,7 @@ class BaseStoreAsyncTests(BaseStandardTests):
await kv_store.amdelete(["foo", "bar", "baz"])
async def test_set_values_is_idempotent(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Setting values by key should be idempotent."""
foo, bar, _ = three_values
@ -240,7 +241,7 @@ class BaseStoreAsyncTests(BaseStandardTests):
assert sorted(kv_store.yield_keys()) == ["bar", "foo"]
async def test_get_can_get_same_value(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test that the same value can be retrieved multiple times."""
foo, bar, _ = three_values
@ -255,7 +256,7 @@ class BaseStoreAsyncTests(BaseStandardTests):
]
async def test_overwrite_values_by_key(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test that we can overwrite values by key using mset."""
foo, bar, buzz = three_values
@ -270,7 +271,7 @@ class BaseStoreAsyncTests(BaseStandardTests):
assert await kv_store.amget(["foo", "bar"]) == [buzz, bar]
async def test_yield_keys(
self, kv_store: BaseStore[str, V], three_values: Tuple[V, V, V]
self, kv_store: BaseStore[str, V], three_values: tuple[V, V, V]
) -> None:
"""Test that we can yield keys from the store."""
foo, bar, _buzz = three_values

View File

@ -1,7 +1,7 @@
import base64
import inspect
import json
from typing import Any, List, Literal, Optional, cast
from typing import Annotated, Any, Literal, Optional, cast
from unittest.mock import MagicMock
import httpx
@ -29,7 +29,7 @@ from pydantic import BaseModel, Field
from pydantic.v1 import BaseModel as BaseModelV1
from pydantic.v1 import Field as FieldV1
from pytest_benchmark.fixture import BenchmarkFixture # type: ignore[import-untyped]
from typing_extensions import Annotated, TypedDict
from typing_extensions import TypedDict
from vcr.cassette import Cassette
from langchain_tests.unit_tests.chat_models import (
@ -2680,7 +2680,7 @@ class ChatModelIntegrationTests(ChatModelTests):
"cache_control": {"type": "ephemeral"},
}
human_content: List[dict] = [
human_content: list[dict] = [
{
"type": "text",
"text": "what's your favorite color in this image",

View File

@ -1,5 +1,3 @@
from typing import List
from langchain_core.embeddings import Embeddings
from langchain_tests.unit_tests.embeddings import EmbeddingsTests
@ -49,7 +47,7 @@ class EmbeddingsIntegrationTests(EmbeddingsTests):
""" # noqa: E501
embedding_1 = model.embed_query("foo")
assert isinstance(embedding_1, List)
assert isinstance(embedding_1, list)
assert isinstance(embedding_1[0], float)
embedding_2 = model.embed_query("bar")
@ -71,7 +69,7 @@ class EmbeddingsIntegrationTests(EmbeddingsTests):
embeddings = model.embed_documents(documents)
assert len(embeddings) == len(documents)
assert all(isinstance(embedding, List) for embedding in embeddings)
assert all(isinstance(embedding, list) for embedding in embeddings)
assert all(isinstance(embedding[0], float) for embedding in embeddings)
assert len(embeddings[0]) > 0
assert all(len(embedding) == len(embeddings[0]) for embedding in embeddings)
@ -88,7 +86,7 @@ class EmbeddingsIntegrationTests(EmbeddingsTests):
""" # noqa: E501
embedding_1 = await model.aembed_query("foo")
assert isinstance(embedding_1, List)
assert isinstance(embedding_1, list)
assert isinstance(embedding_1[0], float)
embedding_2 = await model.aembed_query("bar")
@ -110,7 +108,7 @@ class EmbeddingsIntegrationTests(EmbeddingsTests):
embeddings = await model.aembed_documents(documents)
assert len(embeddings) == len(documents)
assert all(isinstance(embedding, List) for embedding in embeddings)
assert all(isinstance(embedding, list) for embedding in embeddings)
assert all(isinstance(embedding[0], float) for embedding in embeddings)
assert len(embeddings[0]) > 0
assert all(len(embedding) == len(embeddings[0]) for embedding in embeddings)

View File

@ -11,7 +11,7 @@ time.
import inspect
import uuid
from abc import ABC, abstractmethod
from typing import AsyncGenerator, Generator
from collections.abc import AsyncGenerator, Generator
import pytest
from langchain_core.documents import Document

View File

@ -1,5 +1,4 @@
from abc import abstractmethod
from typing import Type
import pytest
from langchain_core.documents import Document
@ -15,7 +14,7 @@ class RetrieversIntegrationTests(BaseStandardTests):
@property
@abstractmethod
def retriever_constructor(self) -> Type[BaseRetriever]:
def retriever_constructor(self) -> type[BaseRetriever]:
"""
A BaseRetriever subclass to be tested.
"""

View File

@ -5,7 +5,7 @@
import inspect
import os
from abc import abstractmethod
from typing import Any, Dict, List, Literal, Optional, Tuple, Type
from typing import Any, Literal, Optional
from unittest import mock
import pytest
@ -78,7 +78,7 @@ class ChatModelTests(BaseStandardTests):
@property
@abstractmethod
def chat_model_class(self) -> Type[BaseChatModel]:
def chat_model_class(self) -> type[BaseChatModel]:
"""The chat model class to test, e.g., ``ChatParrotLink``."""
...
@ -214,9 +214,9 @@ class ChatModelTests(BaseStandardTests):
@property
def supported_usage_metadata_details(
self,
) -> Dict[
) -> dict[
Literal["invoke", "stream"],
List[
list[
Literal[
"audio_input",
"audio_output",
@ -804,7 +804,7 @@ class ChatModelUnitTests(ChatModelTests):
return params
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
def init_from_env_params(self) -> tuple[dict, dict, dict]:
"""(tuple) environment variables, additional initialization args, and expected
instance attributes for testing initialization from environment variables."""
return {}, {}, {}
@ -958,7 +958,7 @@ class ChatModelUnitTests(ChatModelTests):
ls_model_type: Literal["chat"]
ls_temperature: Optional[float]
ls_max_tokens: Optional[int]
ls_stop: Optional[List[str]]
ls_stop: Optional[list[str]]
ls_params = model._get_ls_params()
try:

View File

@ -1,6 +1,5 @@
import os
from abc import abstractmethod
from typing import Tuple, Type
from unittest import mock
import pytest
@ -17,7 +16,7 @@ class EmbeddingsTests(BaseStandardTests):
@property
@abstractmethod
def embeddings_class(self) -> Type[Embeddings]: ...
def embeddings_class(self) -> type[Embeddings]: ...
@property
def embedding_model_params(self) -> dict:
@ -103,7 +102,7 @@ class EmbeddingsUnitTests(EmbeddingsTests):
assert model is not None
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
def init_from_env_params(self) -> tuple[dict, dict, dict]:
"""This property is used in unit tests to test initialization from environment
variables. It should return a tuple of three dictionaries that specify the
environment variables, additional initialization args, and expected instance

View File

@ -1,6 +1,6 @@
import os
from abc import abstractmethod
from typing import Tuple, Type, Union
from typing import Union
from unittest import mock
import pytest
@ -19,7 +19,7 @@ class ToolsTests(BaseStandardTests):
@property
@abstractmethod
def tool_constructor(self) -> Union[Type[BaseTool], BaseTool]:
def tool_constructor(self) -> Union[type[BaseTool], BaseTool]:
"""
Returns a class or instance of a tool to be tested.
"""
@ -64,7 +64,7 @@ class ToolsUnitTests(ToolsTests):
"""
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
def init_from_env_params(self) -> tuple[dict, dict, dict]:
"""Return env vars, init args, and expected instance attrs for initializing
from env vars."""
return {}, {}, {}

View File

@ -55,7 +55,8 @@ ignore_missing_imports = true
target-version = "py39"
[tool.ruff.lint]
select = ["E", "F", "I", "T201"]
select = ["E", "F", "I", "T201", "UP",]
ignore = ["UP007",]
[tool.coverage.run]
omit = ["tests/*"]

View File

@ -1,4 +1,5 @@
from typing import Any, Dict, Iterator, List, Optional
from collections.abc import Iterator
from typing import Any, Optional
from langchain_core.callbacks import (
CallbackManagerForLLMRun,
@ -40,13 +41,13 @@ class ChatParrotLink(BaseChatModel):
temperature: Optional[float] = None
max_tokens: Optional[int] = None
timeout: Optional[int] = None
stop: Optional[List[str]] = None
stop: Optional[list[str]] = None
max_retries: int = 2
def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
messages: list[BaseMessage],
stop: Optional[list[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
@ -91,8 +92,8 @@ class ChatParrotLink(BaseChatModel):
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
messages: list[BaseMessage],
stop: Optional[list[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Iterator[ChatGenerationChunk]:
@ -156,7 +157,7 @@ class ChatParrotLink(BaseChatModel):
return "echoing-chat-model-advanced"
@property
def _identifying_params(self) -> Dict[str, Any]:
def _identifying_params(self) -> dict[str, Any]:
"""Return a dictionary of identifying parameters.
This information is used by the LangChain callback system, which

View File

@ -1,4 +1,4 @@
from typing import Any, Type
from typing import Any
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
@ -17,7 +17,7 @@ class ParrotRetriever(BaseRetriever):
class TestParrotRetrieverIntegration(RetrieversIntegrationTests):
@property
def retriever_constructor(self) -> Type[ParrotRetriever]:
def retriever_constructor(self) -> type[ParrotRetriever]:
return ParrotRetriever
@property

View File

@ -1,4 +1,4 @@
from typing import Literal, Type
from typing import Literal
from langchain_core.tools import BaseTool
@ -29,7 +29,7 @@ class ParrotMultiplyArtifactTool(BaseTool): # type: ignore
class TestParrotMultiplyToolUnit(ToolsUnitTests):
@property
def tool_constructor(self) -> Type[ParrotMultiplyTool]:
def tool_constructor(self) -> type[ParrotMultiplyTool]:
return ParrotMultiplyTool
@property
@ -52,7 +52,7 @@ class TestParrotMultiplyToolUnit(ToolsUnitTests):
class TestParrotMultiplyToolIntegration(ToolsIntegrationTests):
@property
def tool_constructor(self) -> Type[ParrotMultiplyTool]:
def tool_constructor(self) -> type[ParrotMultiplyTool]:
return ParrotMultiplyTool
@property
@ -75,7 +75,7 @@ class TestParrotMultiplyToolIntegration(ToolsIntegrationTests):
class TestParrotMultiplyArtifactToolIntegration(ToolsIntegrationTests):
@property
def tool_constructor(self) -> Type[ParrotMultiplyArtifactTool]:
def tool_constructor(self) -> type[ParrotMultiplyArtifactTool]:
return ParrotMultiplyArtifactTool
@property

View File

@ -2,8 +2,6 @@
Test the standard tests on the custom chat model in the docs
"""
from typing import Type
from langchain_tests.integration_tests import ChatModelIntegrationTests
from langchain_tests.unit_tests import ChatModelUnitTests
@ -12,7 +10,7 @@ from .custom_chat_model import ChatParrotLink
class TestChatParrotLinkUnit(ChatModelUnitTests):
@property
def chat_model_class(self) -> Type[ChatParrotLink]:
def chat_model_class(self) -> type[ChatParrotLink]:
return ChatParrotLink
@property
@ -22,7 +20,7 @@ class TestChatParrotLinkUnit(ChatModelUnitTests):
class TestChatParrotLinkIntegration(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> Type[ChatParrotLink]:
def chat_model_class(self) -> type[ChatParrotLink]:
return ChatParrotLink
@property

View File

@ -1,5 +1,3 @@
from typing import Type
from langchain_core.embeddings import DeterministicFakeEmbedding, Embeddings
from langchain_tests.integration_tests import EmbeddingsIntegrationTests
@ -8,7 +6,7 @@ from langchain_tests.unit_tests import EmbeddingsUnitTests
class TestFakeEmbeddingsUnit(EmbeddingsUnitTests):
@property
def embeddings_class(self) -> Type[Embeddings]:
def embeddings_class(self) -> type[Embeddings]:
return DeterministicFakeEmbedding
@property
@ -18,7 +16,7 @@ class TestFakeEmbeddingsUnit(EmbeddingsUnitTests):
class TestFakeEmbeddingsIntegration(EmbeddingsIntegrationTests):
@property
def embeddings_class(self) -> Type[Embeddings]:
def embeddings_class(self) -> type[Embeddings]:
return DeterministicFakeEmbedding
@property

View File

@ -1,7 +1,5 @@
"""Tests for the InMemoryStore class."""
from typing import Tuple
import pytest
from langchain_core.stores import InMemoryStore
@ -13,7 +11,7 @@ from langchain_tests.integration_tests.base_store import (
class TestInMemoryStore(BaseStoreSyncTests):
@pytest.fixture
def three_values(self) -> Tuple[str, str, str]:
def three_values(self) -> tuple[str, str, str]:
return "foo", "bar", "buzz"
@pytest.fixture
@ -23,7 +21,7 @@ class TestInMemoryStore(BaseStoreSyncTests):
class TestInMemoryStoreAsync(BaseStoreAsyncTests):
@pytest.fixture
def three_values(self) -> Tuple[str, str, str]: # type: ignore
def three_values(self) -> tuple[str, str, str]: # type: ignore
return "foo", "bar", "buzz"
@pytest.fixture