File size: 4,308 Bytes
2d9b352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Unit tests for utility functions used in API comparison."""

from unittest.mock import AsyncMock, patch

import aiohttp
import pytest

from utils.utility import (
    validate_urls,
    validate_json_inputs,
    parse_json_input,
    compare_responses,
    json_line_diff,
    highlight_json_diff,
    fetch_api_responses
)


def test_validate_urls():
    """Test URL validation including valid, invalid, and duplicate cases."""
    validate_urls("http://example.com", "http://api.example.com")

    with pytest.raises(ValueError):
        validate_urls("not-a-url", "http://example.com")

    with pytest.raises(ValueError):
        validate_urls("http://example.com", "http://example.com")


def test_validate_json_inputs():
    """Test validation of JSON inputs, including valid and invalid cases."""
    validate_json_inputs(
        ('{"key": "value"}', "Test 1"),
        ('[]', "Test 2")
    )

    with pytest.raises(ValueError):
        validate_json_inputs(
            ('{invalid}', "Test Invalid"),
            ('{}', "Test Valid")
        )


def test_parse_json_input():
    """Test parsing of valid and invalid JSON strings."""
    assert parse_json_input('{"test": "data"}', "Test") == {"test": "data"}
    assert parse_json_input('[]', "Test") == []
    assert parse_json_input('{}', "Test") == {}

    with pytest.raises(ValueError):
        parse_json_input('{invalid}', "Test Invalid")


def test_compare_responses():
    """Test comparison of two JSON responses in tree and text views."""
    json1 = {"key1": "val1", "key2": "val2"}
    json2 = {"key1": "val1", "key3": "val3"}

    tree_diff = compare_responses(json1, json2, view="tree")
    assert isinstance(tree_diff, dict)
    assert "dictionary_item_removed" in str(tree_diff)
    assert "dictionary_item_added" in str(tree_diff)

    text_diff = compare_responses(json1, json2, view="text")
    assert isinstance(text_diff, str)
    assert "key2" in text_diff
    assert "key3" in text_diff


def test_json_line_diff():
    """Test line-by-line difference between two JSON objects."""
    json1 = {"test": "data1"}
    json2 = {"test": "data2"}

    diff = json_line_diff(json1, json2)
    assert isinstance(diff, str)
    assert "data1" in diff
    assert "data2" in diff


def test_highlight_json_diff():
    """Test HTML highlighting of differences between two JSON objects."""
    json1 = {"test": "data1"}
    json2 = {"test": "data2"}

    html1, html2 = highlight_json_diff(json1, json2)
    assert isinstance(html1, str)
    assert isinstance(html2, str)
    assert "data1" in html1
    assert "data2" in html2


@pytest.mark.asyncio
async def test_fetch_api_responses():
    """Test the fetch_api_responses function with proper async mocks, including SSL."""
    mock_data = {"test": "data"}

    # Mock a single response
    mock_response = AsyncMock()
    mock_response.json.return_value = mock_data
    mock_response.status = 200
    mock_response.__aenter__.return_value = mock_response

    # Create session mock
    mock_session = AsyncMock(spec=aiohttp.ClientSession)
    mock_session.__aenter__.return_value = mock_session
    mock_session.request.side_effect = [mock_response, mock_response]

    with patch('aiohttp.ClientSession', return_value=mock_session):
        responses = await fetch_api_responses(
            "http://api1.example.com", "GET", {}, {},
            "http://api2.example.com", "GET", {}, {}
        )

        assert len(responses) == 2
        response1, time1 = responses[0]
        response2, time2 = responses[1]

        assert response1['data'] == mock_data
        assert response2['data'] == mock_data
        assert response1['status'] == 200
        assert response2['status'] == 200
        assert isinstance(time1, float)
        assert isinstance(time2, float)
        assert mock_session.request.call_count == 2

        expected_kwargs = {
            'method': 'GET',
            'json': None,
            'params': {},
            'headers': {},
            'timeout': 30,
            'ssl': None
        }

        mock_session.request.assert_any_call(
            url="http://api1.example.com",
            **expected_kwargs
        )
        mock_session.request.assert_any_call(
            url="http://api2.example.com",
            **expected_kwargs
        )