tests.conftest   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 42
dl 0
loc 65
rs 10
c 0
b 0
f 0
wmc 15

7 Functions

Rating   Name   Duplication   Size   Complexity  
A mock_settings_env_vars() 0 7 2
A pytest_addoption() 0 6 1
A pytest_collection_modifyitems() 0 8 4
A pytest_configure() 0 2 1
A mock_get_text_embedding() 0 8 3
A mock_embeddings() 0 11 3
A mock_get_text_embeddings() 0 3 1
1
import os
2
from unittest.mock import patch
3
4
import pytest
5
6
7
@pytest.fixture()
8
def mock_embeddings():
9
    with patch(
10
        "llama_index.embeddings.openai.OpenAIEmbedding._get_text_embeddings",
11
        side_effect=mock_get_text_embeddings,
12
    ):
13
        with patch(
14
            "llama_index.embeddings.openai.OpenAIEmbedding._get_text_embedding",
15
            side_effect=mock_get_text_embedding,
16
        ):
17
            yield
18
19
20
@pytest.fixture(autouse=True)
21
def mock_settings_env_vars():
22
    with patch.dict(
23
        os.environ,
24
        {"OPENAI_API_KEY": "sk-TEST00000000000000000000000000000000000000000000"},
25
    ):
26
        yield
27
28
29
def mock_get_text_embedding(text: str) -> list[float]:
30
    """Mock get text embedding."""
31
    if text == "Hello world.":
32
        return [1, 0, 0, 0, 0]
33
    elif text == "This is a test.":
34
        return [0, 1, 0, 0, 0]
35
    else:
36
        raise ValueError("Invalid text for `mock_get_text_embedding`.")
37
38
39
def mock_get_text_embeddings(texts: list[str]) -> list[list[float]]:
40
    """Mock get text embeddings."""
41
    return [mock_get_text_embedding(text) for text in texts]
42
43
44
def pytest_addoption(parser):
45
    parser.addoption(
46
        "--integration",
47
        action="store_true",
48
        default=False,
49
        help="run integration tests that call OpenAI",
50
    )
51
52
53
def pytest_configure(config):
54
    config.addinivalue_line("markers", "integration: mark test as skipped by default")
55
56
57
def pytest_collection_modifyitems(config, items):
58
    if config.getoption("--integration"):
59
        # --runslow given in cli: do not skip slow tests
60
        return
61
    skip_integration = pytest.mark.skip(reason="need --integration option to run")
62
    for item in items:
63
        if "integration" in item.keywords:
64
            item.add_marker(skip_integration)
65