CoolFace
Apppublic

mydatascraper/competitor_compare

sourceHugging Faceupdated 2mo agoView on Hugging Face
0likes
test_api.py143 linesDownload Raw Back to tests
1"""
2API integration tests - demonstrates all endpoints working.
3"""
4import pytest
5from httpx import AsyncClient, ASGITransport
6from app.main import app
7
8API_KEY = "gprice_mvp_demo_key_2024"
9HEADERS = {"X-API-Key": API_KEY}
10
11
12@pytest.fixture
13def client():
14    transport = ASGITransport(app=app)
15    return AsyncClient(transport=transport, base_url="http://test")
16
17
18@pytest.mark.asyncio
19async def test_health(client):
20    async with client as c:
21        r = await c.get("/health")
22        assert r.status_code == 200
23        data = r.json()
24        assert data["status"] in ("healthy", "degraded")
25        print(f"Health: {data}")
26
27
28@pytest.mark.asyncio
29async def test_auth_required(client):
30    async with client as c:
31        r = await c.get("/products/")
32        assert r.status_code == 401
33
34
35@pytest.mark.asyncio
36async def test_search_products(client):
37    async with client as c:
38        r = await c.get("/products/", headers=HEADERS, params={"q": "milk"})
39        assert r.status_code == 200
40        data = r.json()
41        print(f"Product search 'milk': {data['total']} results")
42
43
44@pytest.mark.asyncio
45async def test_search_by_category(client):
46    async with client as c:
47        r = await c.get(
48            "/products/", headers=HEADERS, params={"category": "produce"}
49        )
50        assert r.status_code == 200
51        data = r.json()
52        print(f"Produce products: {data['total']}")
53
54
55@pytest.mark.asyncio
56async def test_get_prices(client):
57    async with client as c:
58        r = await c.get(
59            "/prices/", headers=HEADERS, params={"upc": "00000000001"}
60        )
61        assert r.status_code == 200
62
63
64@pytest.mark.asyncio
65async def test_compare_prices(client):
66    async with client as c:
67        # Bananas UPC
68        r = await c.get("/compare/00000000001", headers=HEADERS)
69        assert r.status_code == 200
70        data = r.json()
71        if data.get("prices"):
72            print(f"\nPrice comparison for {data['product']['name']}:")
73            for p in data["prices"]:
74                print(f"  {p['retailer']}: ${p['effective_price']:.2f}")
75            if data.get("cheapest"):
76                print(f"  Cheapest: {data['cheapest']['retailer']}")
77            if data.get("price_spread"):
78                print(f"  Spread: ${data['price_spread']:.2f} ({data['price_spread_pct']}%)")
79
80
81@pytest.mark.asyncio
82async def test_basket_comparison(client):
83    async with client as c:
84        basket = {
85            "items": [
86                {"upc": "00000000001", "quantity": 2},  # Bananas
87                {"upc": "00000000100", "quantity": 1},  # Whole Milk
88                {"upc": "00000000302", "quantity": 1},  # Cheerios
89                {"upc": "00000000106", "quantity": 1},  # Eggs
90                {"upc": "00000000200", "quantity": 1},  # Chicken Breast
91            ]
92        }
93        r = await c.post("/compare/basket", headers=HEADERS, json=basket)
94        assert r.status_code == 200
95        data = r.json()
96        print(f"\nBasket comparison ({data['basket_size']} items):")
97        for rt in data["retailers"]:
98            print(f"  {rt['retailer']}: ${rt['total']:.2f} "
99                  f"({rt['items_found']}/{data['basket_size']} found)")
100        if data.get("cheapest_retailer"):
101            print(f"  Cheapest: {data['cheapest_retailer']}")
102            print(f"  Savings: ${data.get('savings_vs_most_expensive', 0):.2f}")
103
104
105@pytest.mark.asyncio
106async def test_stores(client):
107    async with client as c:
108        r = await c.get(
109            "/stores/", headers=HEADERS, params={"retailer": "walmart"}
110        )
111        assert r.status_code == 200
112        data = r.json()
113        print(f"\nWalmart stores: {len(data)}")
114
115
116@pytest.mark.asyncio
117async def test_bulk_export(client):
118    async with client as c:
119        r = await c.post(
120            "/bulk/export",
121            headers=HEADERS,
122            json={
123                "format": "csv",
124                "destination": "local",
125                "retailers": ["walmart", "aldi"],
126            },
127        )
128        assert r.status_code == 200
129        data = r.json()
130        print(f"\nBulk export: {data['record_count']} records, "
131              f"status={data['status']}")
132
133
134@pytest.mark.asyncio
135async def test_coverage(client):
136    async with client as c:
137        r = await c.get("/coverage", headers=HEADERS)
138        assert r.status_code == 200
139        data = r.json()
140        print("\nData coverage:")
141        for cov in data:
142            print(f"  {cov['retailer']}: {cov['total_products']} products, "
143                  f"{cov['total_stores']} stores")