File size: 7,949 Bytes
a6bfba7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import os
import pytest
import asyncio
import httpx
from unittest.mock import patch, MagicMock, AsyncMock
from dotenv import load_dotenv

from stackoverflow_mcp.api import StackExchangeAPI
from stackoverflow_mcp.types import SearchResult

# Load test environment variables
load_dotenv(".env.test")


@pytest.fixture
def api_key():
    """Return API key from environment or None."""
    return os.getenv("STACK_EXCHANGE_API_KEY")


@pytest.fixture
def api(api_key):
    """Create a StackExchangeAPI instance for testing."""
    api = StackExchangeAPI(api_key=api_key)
    yield api
    # Clean up
    asyncio.run(api.close())


@pytest.fixture
def mock_search_response():
    """Create a mock search response."""
    response = MagicMock()
    response.raise_for_status = MagicMock()
    response.json = MagicMock(return_value={
        "items": [
            {
                "question_id": 12345,
                "title": "How to unittest a Flask application?",
                "body": "<p>I'm trying to test my Flask application with unittest.</p>",
                "score": 25,
                "answer_count": 3,
                "is_answered": True,
                "accepted_answer_id": 54321,
                "creation_date": 1609459200,
                "last_activity_date": 1609459200,
                "view_count": 1000,
                "tags": ["python", "flask", "testing", "unittest"],
                "link": "https://stackoverflow.com/q/12345",
                "closed_date": None,
                "owner": {
                    "user_id": 101,
                    "display_name": "Test User",
                    "reputation": 1000
                }
            }
        ],
        "has_more": False,
        "quota_max": 300,
        "quota_remaining": 299
    })
    return response


# REAL API TESTS

@pytest.mark.asyncio
@pytest.mark.real_api
async def test_search_by_query_real(api):
    """Test searching by query using real API."""
    # Skip if no API key
    if not os.getenv("STACK_EXCHANGE_API_KEY"):
        pytest.skip("API key required for real API tests")
    
    results = await api.search_by_query(
        query="python unittest flask",
        tags=["python", "flask"],
        limit=3
    )
    
    # Basic validation
    assert isinstance(results, list)
    if results:  # May be empty if no results match
        assert isinstance(results[0], SearchResult)
        assert results[0].question.title is not None
        assert "python" in [tag.lower() for tag in results[0].question.tags]


@pytest.mark.asyncio
@pytest.mark.real_api
async def test_advanced_search_real(api):
    """Test advanced search using real API."""
    # Skip if no API key
    if not os.getenv("STACK_EXCHANGE_API_KEY"):
        pytest.skip("API key required for real API tests")
    
    results = await api.advanced_search(
        query="database connection",
        tags=["python"],
        min_score=10,
        has_accepted_answer=True,
        limit=2
    )
    
    # Basic validation
    assert isinstance(results, list)
    if results:  # May be empty if no results match
        assert isinstance(results[0], SearchResult)
        assert results[0].question.score >= 10
        assert "python" in [tag.lower() for tag in results[0].question.tags]


# MOCK TESTS

@pytest.mark.asyncio
async def test_search_by_query_mock(api, mock_search_response):
    """Test searching by query with mocked response."""
    with patch.object(httpx.AsyncClient, 'get', return_value=mock_search_response):
        results = await api.search_by_query(
            query="flask unittest",
            tags=["python", "flask"],
            min_score=10,
            limit=5
        )
        
        assert len(results) == 1
        assert results[0].question.question_id == 12345
        assert results[0].question.title == "How to unittest a Flask application?"
        assert "python" in results[0].question.tags
        assert "flask" in results[0].question.tags


@pytest.mark.asyncio
async def test_empty_search_results(api):
    """Test empty search results handling."""
    empty_response = MagicMock()
    empty_response.raise_for_status = MagicMock()
    empty_response.json = MagicMock(return_value={"items": []})
    
    with patch.object(httpx.AsyncClient, 'get', return_value=empty_response):
        results = await api.search_by_query(
            query="definitely will not find anything 89797979",
            limit=1
        )
        
        assert isinstance(results, list)
        assert len(results) == 0


@pytest.mark.asyncio
async def test_search_with_min_score_filtering(api, mock_search_response):
    """Test that min_score parameter properly filters results."""
    with patch.object(httpx.AsyncClient, 'get', return_value=mock_search_response):
        # Should return results (mock score is 25)
        results_included = await api.search_by_query(
            query="flask unittest",
            min_score=20,
            limit=5
        )
        assert len(results_included) == 1
        
        # Should filter out results
        results_filtered = await api.search_by_query(
            query="flask unittest",
            min_score=30,
            limit=5
        )
        assert len(results_filtered) == 0


@pytest.mark.asyncio
async def test_search_with_multiple_tags(api, mock_search_response):
    """Test searching with multiple tags."""
    with patch.object(httpx.AsyncClient, 'get', return_value=mock_search_response):
        results = await api.search_by_query(
            query="test",
            tags=["python", "flask", "django"],
            limit=5
        )
        
        # Verify the tags were properly passed to the request
        call_args = httpx.AsyncClient.get.call_args
        params = call_args[1]['params']
        assert 'tagged' in params
        assert params['tagged'] == "python;flask;django"


@pytest.mark.asyncio
async def test_search_with_excluded_tags(api, mock_search_response):
    """Test searching with excluded tags."""
    with patch.object(httpx.AsyncClient, 'get', return_value=mock_search_response):
        results = await api.search_by_query(
            query="test",
            excluded_tags=["javascript", "c#"],
            limit=5
        )
        
        # Verify the excluded tags were properly passed to the request
        call_args = httpx.AsyncClient.get.call_args
        params = call_args[1]['params']
        assert 'nottagged' in params
        assert params['nottagged'] == "javascript;c#"


@pytest.mark.asyncio
async def test_search_with_advanced_parameters(api, mock_search_response):
    """Test advanced search with multiple parameters."""
    with patch.object(httpx.AsyncClient, 'get', return_value=mock_search_response):
        results = await api.advanced_search(
            query="flask test",
            tags=["python"],
            title="unittest",
            has_accepted_answer=True,
            sort_by="relevance",
            limit=5
        )
        
        # Verify parameters were properly passed
        call_args = httpx.AsyncClient.get.call_args
        params = call_args[1]['params']
        assert params['q'] == "flask test"
        assert params['tagged'] == "python"
        assert params['title'] == "unittest"
        assert params['accepted'] == "true"
        assert params['sort'] == "relevance"
        assert params['pagesize'] == "5"


@pytest.mark.asyncio
async def test_search_api_error(api):
    """Test handling of API errors."""
    error_response = MagicMock()
    error_response.raise_for_status = MagicMock(
        side_effect=httpx.HTTPStatusError(
            "500 Internal Server Error",
            request=MagicMock(),
            response=MagicMock(status_code=500)
        )
    )
    
    with patch.object(httpx.AsyncClient, 'get', return_value=error_response):
        with pytest.raises(httpx.HTTPStatusError):
            await api.search_by_query("test query")