blocket-cli 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- blocket_cli-0.1.0/.github/workflows/ci.yml +32 -0
- blocket_cli-0.1.0/.github/workflows/publish.yml +19 -0
- blocket_cli-0.1.0/.gitignore +6 -0
- blocket_cli-0.1.0/LICENSE +21 -0
- blocket_cli-0.1.0/PKG-INFO +108 -0
- blocket_cli-0.1.0/README.md +86 -0
- blocket_cli-0.1.0/blocket_cli/__init__.py +3 -0
- blocket_cli-0.1.0/blocket_cli/api.py +159 -0
- blocket_cli-0.1.0/blocket_cli/cli.py +111 -0
- blocket_cli-0.1.0/blocket_cli/format.py +107 -0
- blocket_cli-0.1.0/blocket_cli/py.typed +0 -0
- blocket_cli-0.1.0/pyproject.toml +41 -0
- blocket_cli-0.1.0/tests/__init__.py +0 -0
- blocket_cli-0.1.0/tests/test_api.py +75 -0
- blocket_cli-0.1.0/tests/test_cli.py +111 -0
- blocket_cli-0.1.0/tests/test_format.py +102 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [main]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
lint:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
steps:
|
|
13
|
+
- uses: actions/checkout@v4
|
|
14
|
+
- uses: actions/setup-python@v5
|
|
15
|
+
with:
|
|
16
|
+
python-version: "3.12"
|
|
17
|
+
- run: pip install ruff
|
|
18
|
+
- run: ruff check .
|
|
19
|
+
- run: ruff format --check .
|
|
20
|
+
|
|
21
|
+
test:
|
|
22
|
+
runs-on: ubuntu-latest
|
|
23
|
+
strategy:
|
|
24
|
+
matrix:
|
|
25
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
26
|
+
steps:
|
|
27
|
+
- uses: actions/checkout@v4
|
|
28
|
+
- uses: actions/setup-python@v5
|
|
29
|
+
with:
|
|
30
|
+
python-version: ${{ matrix.python-version }}
|
|
31
|
+
- run: pip install -e ".[dev]"
|
|
32
|
+
- run: pytest -v
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
publish:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
permissions:
|
|
11
|
+
id-token: write
|
|
12
|
+
steps:
|
|
13
|
+
- uses: actions/checkout@v4
|
|
14
|
+
- uses: actions/setup-python@v5
|
|
15
|
+
with:
|
|
16
|
+
python-version: "3.12"
|
|
17
|
+
- run: pip install build
|
|
18
|
+
- run: python -m build
|
|
19
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lennart Johansson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: blocket-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fast CLI for searching Blocket.se — optimized for agents and scripting
|
|
5
|
+
Author: Lennart Johansson
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: blocket,cli,marketplace,search,sweden
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Utilities
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Requires-Dist: click>=8.0
|
|
17
|
+
Requires-Dist: httpx>=0.27
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
20
|
+
Requires-Dist: ruff>=0.9; extra == 'dev'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# blocket-cli
|
|
24
|
+
|
|
25
|
+
[](https://github.com/lennart-johansson/blocket-cli/actions/workflows/ci.yml)
|
|
26
|
+
[](https://python.org)
|
|
27
|
+
[](LICENSE)
|
|
28
|
+
|
|
29
|
+
Fast CLI for searching [Blocket.se](https://www.blocket.se) — Sweden's largest marketplace.
|
|
30
|
+
|
|
31
|
+
Designed for agents, scripts, and quick terminal lookups. Minimal dependencies, structured output.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install blocket-cli
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Or with [uv](https://docs.astral.sh/uv/):
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
uv tool install blocket-cli
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
|
|
47
|
+
### Search listings
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
blocket search "soffa"
|
|
51
|
+
blocket search "iphone 15" -l stockholm --price-max 8000
|
|
52
|
+
blocket search "mountainbike" -c sports --sort price-asc -n 10
|
|
53
|
+
blocket search "ps5" -c electronics -o json | jq '.results[:3]'
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Get ad details
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
blocket ad 20851738
|
|
60
|
+
blocket ad 20851738 -o json
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Browse filters
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
blocket categories
|
|
67
|
+
blocket locations
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Output formats
|
|
71
|
+
|
|
72
|
+
| Flag | Format | Use case |
|
|
73
|
+
|------|--------|----------|
|
|
74
|
+
| (default) | Human-readable table | Terminal browsing |
|
|
75
|
+
| `-o json` | Compact JSON | Piping to `jq`, API consumption |
|
|
76
|
+
| `-o jsonl` | One JSON object per line | Streaming, log processing |
|
|
77
|
+
|
|
78
|
+
## Search options
|
|
79
|
+
|
|
80
|
+
| Option | Description |
|
|
81
|
+
|--------|-------------|
|
|
82
|
+
| `-l`, `--location` | Filter by Swedish county (e.g. `stockholm`, `skane`) |
|
|
83
|
+
| `-c`, `--category` | Filter by category (e.g. `electronics`, `furniture`) |
|
|
84
|
+
| `--price-min` | Minimum price in SEK |
|
|
85
|
+
| `--price-max` | Maximum price in SEK |
|
|
86
|
+
| `--sort` | Sort order (`relevance`, `price-asc`, `price-desc`, `date`) |
|
|
87
|
+
| `-n`, `--limit` | Max results to display |
|
|
88
|
+
| `-p`, `--page` | Page number |
|
|
89
|
+
| `-o`, `--output` | Output format (`table`, `json`, `jsonl`) |
|
|
90
|
+
|
|
91
|
+
## Agent integration
|
|
92
|
+
|
|
93
|
+
The JSON output is designed for LLM agents and automation:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
# Structured search results
|
|
97
|
+
blocket search "cykel" -l stockholm --price-max 5000 -o json
|
|
98
|
+
|
|
99
|
+
# Stream results line by line
|
|
100
|
+
blocket search "soffa" -o jsonl
|
|
101
|
+
|
|
102
|
+
# Filter by category
|
|
103
|
+
blocket search "lampa" -c furniture -o json | jq '[.results[] | {title: .heading, price: .price.amount, location}]'
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# blocket-cli
|
|
2
|
+
|
|
3
|
+
[](https://github.com/lennart-johansson/blocket-cli/actions/workflows/ci.yml)
|
|
4
|
+
[](https://python.org)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
Fast CLI for searching [Blocket.se](https://www.blocket.se) — Sweden's largest marketplace.
|
|
8
|
+
|
|
9
|
+
Designed for agents, scripts, and quick terminal lookups. Minimal dependencies, structured output.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install blocket-cli
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Or with [uv](https://docs.astral.sh/uv/):
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
uv tool install blocket-cli
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
### Search listings
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
blocket search "soffa"
|
|
29
|
+
blocket search "iphone 15" -l stockholm --price-max 8000
|
|
30
|
+
blocket search "mountainbike" -c sports --sort price-asc -n 10
|
|
31
|
+
blocket search "ps5" -c electronics -o json | jq '.results[:3]'
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Get ad details
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
blocket ad 20851738
|
|
38
|
+
blocket ad 20851738 -o json
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Browse filters
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
blocket categories
|
|
45
|
+
blocket locations
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Output formats
|
|
49
|
+
|
|
50
|
+
| Flag | Format | Use case |
|
|
51
|
+
|------|--------|----------|
|
|
52
|
+
| (default) | Human-readable table | Terminal browsing |
|
|
53
|
+
| `-o json` | Compact JSON | Piping to `jq`, API consumption |
|
|
54
|
+
| `-o jsonl` | One JSON object per line | Streaming, log processing |
|
|
55
|
+
|
|
56
|
+
## Search options
|
|
57
|
+
|
|
58
|
+
| Option | Description |
|
|
59
|
+
|--------|-------------|
|
|
60
|
+
| `-l`, `--location` | Filter by Swedish county (e.g. `stockholm`, `skane`) |
|
|
61
|
+
| `-c`, `--category` | Filter by category (e.g. `electronics`, `furniture`) |
|
|
62
|
+
| `--price-min` | Minimum price in SEK |
|
|
63
|
+
| `--price-max` | Maximum price in SEK |
|
|
64
|
+
| `--sort` | Sort order (`relevance`, `price-asc`, `price-desc`, `date`) |
|
|
65
|
+
| `-n`, `--limit` | Max results to display |
|
|
66
|
+
| `-p`, `--page` | Page number |
|
|
67
|
+
| `-o`, `--output` | Output format (`table`, `json`, `jsonl`) |
|
|
68
|
+
|
|
69
|
+
## Agent integration
|
|
70
|
+
|
|
71
|
+
The JSON output is designed for LLM agents and automation:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
# Structured search results
|
|
75
|
+
blocket search "cykel" -l stockholm --price-max 5000 -o json
|
|
76
|
+
|
|
77
|
+
# Stream results line by line
|
|
78
|
+
blocket search "soffa" -o jsonl
|
|
79
|
+
|
|
80
|
+
# Filter by category
|
|
81
|
+
blocket search "lampa" -c furniture -o json | jq '[.results[] | {title: .heading, price: .price.amount, location}]'
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
MIT
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Blocket.se search API client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from html.parser import HTMLParser
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
BASE = "https://www.blocket.se"
|
|
11
|
+
SEARCH_URL = f"{BASE}/recommerce/forsale/search/api/search/SEARCH_ID_BAP_COMMON"
|
|
12
|
+
|
|
13
|
+
HEADERS = {
|
|
14
|
+
"User-Agent": "blocket-cli/0.1.0 (https://github.com/lennart-johansson/blocket-cli)",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
LOCATIONS = {
|
|
18
|
+
"blekinge": "0.300010",
|
|
19
|
+
"dalarna": "0.300020",
|
|
20
|
+
"gotland": "0.300009",
|
|
21
|
+
"gavleborg": "0.300021",
|
|
22
|
+
"halland": "0.300013",
|
|
23
|
+
"jamtland": "0.300023",
|
|
24
|
+
"jonkoping": "0.300006",
|
|
25
|
+
"kalmar": "0.300008",
|
|
26
|
+
"kronoberg": "0.300007",
|
|
27
|
+
"norrbotten": "0.300025",
|
|
28
|
+
"skane": "0.300012",
|
|
29
|
+
"stockholm": "0.300001",
|
|
30
|
+
"sodermanland": "0.300004",
|
|
31
|
+
"uppsala": "0.300003",
|
|
32
|
+
"varmland": "0.300017",
|
|
33
|
+
"vasterbotten": "0.300024",
|
|
34
|
+
"vasternorrland": "0.300022",
|
|
35
|
+
"vastmanland": "0.300019",
|
|
36
|
+
"vastra-gotaland": "0.300014",
|
|
37
|
+
"orebro": "0.300018",
|
|
38
|
+
"ostergotland": "0.300005",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
CATEGORIES = {
|
|
42
|
+
"business": "0.91",
|
|
43
|
+
"home-garden": "0.67",
|
|
44
|
+
"pets": "0.77",
|
|
45
|
+
"electronics": "0.93",
|
|
46
|
+
"vehicle-parts": "0.90",
|
|
47
|
+
"family": "0.68",
|
|
48
|
+
"fashion": "0.71",
|
|
49
|
+
"art": "0.76",
|
|
50
|
+
"furniture": "0.78",
|
|
51
|
+
"sports": "0.69",
|
|
52
|
+
"hobby": "0.86",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
# Swedish display names for categories
|
|
56
|
+
CATEGORY_LABELS = {
|
|
57
|
+
"business": "Affärsverksamhet",
|
|
58
|
+
"home-garden": "Bygg och trädgård",
|
|
59
|
+
"pets": "Djur och tillbehör",
|
|
60
|
+
"electronics": "Elektronik och vitvaror",
|
|
61
|
+
"vehicle-parts": "Fordonstillbehör",
|
|
62
|
+
"family": "Föräldrar och barn",
|
|
63
|
+
"fashion": "Kläder, kosmetika och accessoarer",
|
|
64
|
+
"art": "Konst och antikt",
|
|
65
|
+
"furniture": "Möbler och inredning",
|
|
66
|
+
"sports": "Sport och friluftsliv",
|
|
67
|
+
"hobby": "Underhållning och hobby",
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _resolve_location(name: str) -> str:
|
|
72
|
+
code = LOCATIONS.get(name.lower())
|
|
73
|
+
if not code:
|
|
74
|
+
raise ValueError(f"Unknown location '{name}'. Valid: {', '.join(sorted(LOCATIONS))}")
|
|
75
|
+
return code
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _resolve_category(name: str) -> str:
|
|
79
|
+
code = CATEGORIES.get(name.lower())
|
|
80
|
+
if not code:
|
|
81
|
+
raise ValueError(f"Unknown category '{name}'. Valid: {', '.join(sorted(CATEGORIES))}")
|
|
82
|
+
return code
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def search(
|
|
86
|
+
query: str,
|
|
87
|
+
*,
|
|
88
|
+
location: str | None = None,
|
|
89
|
+
category: str | None = None,
|
|
90
|
+
price_min: int | None = None,
|
|
91
|
+
price_max: int | None = None,
|
|
92
|
+
sort: str | None = None,
|
|
93
|
+
page: int = 1,
|
|
94
|
+
) -> dict:
|
|
95
|
+
"""Search listings on Blocket."""
|
|
96
|
+
params: list[tuple[str, str]] = [("q", query), ("page", str(page))]
|
|
97
|
+
if location:
|
|
98
|
+
params.append(("location", _resolve_location(location)))
|
|
99
|
+
if category:
|
|
100
|
+
params.append(("category", _resolve_category(category)))
|
|
101
|
+
if price_min is not None:
|
|
102
|
+
params.append(("price_from", str(price_min)))
|
|
103
|
+
if price_max is not None:
|
|
104
|
+
params.append(("price_to", str(price_max)))
|
|
105
|
+
if sort:
|
|
106
|
+
params.append(("sort", sort))
|
|
107
|
+
|
|
108
|
+
r = httpx.get(SEARCH_URL, params=params, headers=HEADERS, timeout=15, follow_redirects=True)
|
|
109
|
+
r.raise_for_status()
|
|
110
|
+
return r.json()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def get_ad(ad_id: int | str) -> dict:
|
|
114
|
+
"""Fetch full ad details from the item page's structured data."""
|
|
115
|
+
# Try recommerce first (most common), fall back to mobility
|
|
116
|
+
for path in ("recommerce/forsale/item", "mobility/item"):
|
|
117
|
+
url = f"{BASE}/{path}/{ad_id}"
|
|
118
|
+
r = httpx.get(url, headers=HEADERS, timeout=15, follow_redirects=True)
|
|
119
|
+
if r.status_code == 200:
|
|
120
|
+
result = _extract_product_data(r.text)
|
|
121
|
+
if result:
|
|
122
|
+
return result
|
|
123
|
+
|
|
124
|
+
return {"error": f"Could not find ad {ad_id}"}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _extract_product_data(html: str) -> dict | None:
|
|
128
|
+
"""Extract JSON-LD Product data from HTML."""
|
|
129
|
+
|
|
130
|
+
class _LDJsonExtractor(HTMLParser):
|
|
131
|
+
def __init__(self):
|
|
132
|
+
super().__init__()
|
|
133
|
+
self._capture = False
|
|
134
|
+
self.scripts: list[str] = []
|
|
135
|
+
|
|
136
|
+
def handle_starttag(self, tag, attrs):
|
|
137
|
+
if tag == "script" and dict(attrs).get("type") == "application/ld+json":
|
|
138
|
+
self._capture = True
|
|
139
|
+
|
|
140
|
+
def handle_data(self, data):
|
|
141
|
+
if self._capture:
|
|
142
|
+
self.scripts.append(data)
|
|
143
|
+
|
|
144
|
+
def handle_endtag(self, tag):
|
|
145
|
+
if tag == "script":
|
|
146
|
+
self._capture = False
|
|
147
|
+
|
|
148
|
+
parser = _LDJsonExtractor()
|
|
149
|
+
parser.feed(html)
|
|
150
|
+
|
|
151
|
+
for script in parser.scripts:
|
|
152
|
+
try:
|
|
153
|
+
data = json.loads(script)
|
|
154
|
+
if isinstance(data, dict) and data.get("@type") == "Product":
|
|
155
|
+
return data
|
|
156
|
+
except json.JSONDecodeError:
|
|
157
|
+
continue
|
|
158
|
+
|
|
159
|
+
return None
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Blocket CLI — search Blocket.se from the terminal."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from . import api, format
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@click.group()
|
|
13
|
+
@click.version_option()
|
|
14
|
+
def main():
|
|
15
|
+
"""Search Blocket.se from the command line.
|
|
16
|
+
|
|
17
|
+
Fast, minimal CLI for searching Sweden's largest marketplace.
|
|
18
|
+
Designed for scripting, agents, and quick lookups.
|
|
19
|
+
"""
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@main.command()
|
|
24
|
+
@click.argument("query")
|
|
25
|
+
@click.option("-l", "--location", help="County filter (e.g. stockholm, skane)")
|
|
26
|
+
@click.option("-c", "--category", help="Category filter (use 'blocket categories' to list)")
|
|
27
|
+
@click.option("--price-min", type=int, help="Minimum price (SEK)")
|
|
28
|
+
@click.option("--price-max", type=int, help="Maximum price (SEK)")
|
|
29
|
+
@click.option(
|
|
30
|
+
"--sort",
|
|
31
|
+
type=click.Choice(["relevance", "price-asc", "price-desc", "date"], case_sensitive=False),
|
|
32
|
+
help="Sort order",
|
|
33
|
+
)
|
|
34
|
+
@click.option("-n", "--limit", type=int, help="Max results to show")
|
|
35
|
+
@click.option("-p", "--page", type=int, default=1, help="Page number")
|
|
36
|
+
@click.option("-o", "--output", type=click.Choice(["table", "json", "jsonl"]), default="table", help="Output format")
|
|
37
|
+
@click.option("--raw", is_flag=True, help="Full API response (default: slim agent-friendly fields)")
|
|
38
|
+
def search(
|
|
39
|
+
query: str,
|
|
40
|
+
location: str | None,
|
|
41
|
+
category: str | None,
|
|
42
|
+
price_min: int | None,
|
|
43
|
+
price_max: int | None,
|
|
44
|
+
sort: str | None,
|
|
45
|
+
limit: int | None,
|
|
46
|
+
page: int,
|
|
47
|
+
output: str,
|
|
48
|
+
raw: bool,
|
|
49
|
+
):
|
|
50
|
+
"""Search listings on Blocket.
|
|
51
|
+
|
|
52
|
+
\b
|
|
53
|
+
Examples:
|
|
54
|
+
blocket search "soffa" -l stockholm --price-max 5000
|
|
55
|
+
blocket search "iphone 15" -c electronics --sort price-asc
|
|
56
|
+
blocket search "cykel" -c sports -o json
|
|
57
|
+
"""
|
|
58
|
+
sort_map = {
|
|
59
|
+
"relevance": "RELEVANCE",
|
|
60
|
+
"price-asc": "PRICE_ASC",
|
|
61
|
+
"price-desc": "PRICE_DESC",
|
|
62
|
+
"date": "PUBLISHED_DESC",
|
|
63
|
+
}
|
|
64
|
+
try:
|
|
65
|
+
data = api.search(
|
|
66
|
+
query,
|
|
67
|
+
location=location,
|
|
68
|
+
category=category,
|
|
69
|
+
price_min=price_min,
|
|
70
|
+
price_max=price_max,
|
|
71
|
+
sort=sort_map.get(sort, sort) if sort else None,
|
|
72
|
+
page=page,
|
|
73
|
+
)
|
|
74
|
+
format.print_results(data, output=output, limit=limit, raw=raw)
|
|
75
|
+
except Exception as e:
|
|
76
|
+
click.echo(f"Error: {e}", err=True)
|
|
77
|
+
sys.exit(1)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@main.command()
|
|
81
|
+
@click.argument("ad_id")
|
|
82
|
+
@click.option("-o", "--output", type=click.Choice(["table", "json"]), default="table", help="Output format")
|
|
83
|
+
def ad(ad_id: str, output: str):
|
|
84
|
+
"""Get full details for a specific ad.
|
|
85
|
+
|
|
86
|
+
\b
|
|
87
|
+
Examples:
|
|
88
|
+
blocket ad 20851738
|
|
89
|
+
blocket ad 20851738 -o json
|
|
90
|
+
"""
|
|
91
|
+
try:
|
|
92
|
+
data = api.get_ad(ad_id)
|
|
93
|
+
format.print_ad(data, output=output)
|
|
94
|
+
except Exception as e:
|
|
95
|
+
click.echo(f"Error: {e}", err=True)
|
|
96
|
+
sys.exit(1)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@main.command()
|
|
100
|
+
def categories():
|
|
101
|
+
"""List available categories."""
|
|
102
|
+
for name in sorted(api.CATEGORIES):
|
|
103
|
+
label = api.CATEGORY_LABELS.get(name, "")
|
|
104
|
+
click.echo(f"{name:<20} {label}")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@main.command()
|
|
108
|
+
def locations():
|
|
109
|
+
"""List available locations (Swedish counties)."""
|
|
110
|
+
for name in sorted(api.LOCATIONS):
|
|
111
|
+
click.echo(name)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Output formatting for Blocket CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _json_compact(data: Any) -> str:
|
|
12
|
+
return json.dumps(data, ensure_ascii=False, separators=(",", ":"))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _slim(doc: dict) -> dict:
|
|
16
|
+
"""Strip a listing to agent-essential fields."""
|
|
17
|
+
price = doc.get("price", {})
|
|
18
|
+
out: dict[str, Any] = {
|
|
19
|
+
"id": doc.get("id"),
|
|
20
|
+
"heading": doc.get("heading"),
|
|
21
|
+
"price": price.get("amount"),
|
|
22
|
+
"currency": price.get("currency_code", "SEK"),
|
|
23
|
+
"location": doc.get("location"),
|
|
24
|
+
"url": doc.get("canonical_url"),
|
|
25
|
+
}
|
|
26
|
+
ts = doc.get("timestamp")
|
|
27
|
+
if ts:
|
|
28
|
+
out["date"] = datetime.fromtimestamp(ts / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
|
|
29
|
+
for extra in doc.get("extras", []):
|
|
30
|
+
if extra.get("id") == "brand" and extra.get("values"):
|
|
31
|
+
out["brand"] = extra["values"][0]
|
|
32
|
+
return out
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def print_results(data: dict, *, output: str = "table", limit: int | None = None, raw: bool = False) -> None:
|
|
36
|
+
"""Print search results."""
|
|
37
|
+
docs = data.get("docs", [])
|
|
38
|
+
total = data.get("metadata", {}).get("result_size", {}).get("match_count", len(docs))
|
|
39
|
+
|
|
40
|
+
if limit:
|
|
41
|
+
docs = docs[:limit]
|
|
42
|
+
|
|
43
|
+
if output == "json":
|
|
44
|
+
results = docs if raw else [_slim(d) for d in docs]
|
|
45
|
+
print(_json_compact({"total": total, "results": results}))
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
if output == "jsonl":
|
|
49
|
+
for doc in docs:
|
|
50
|
+
print(_json_compact(doc if raw else _slim(doc)))
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
if not docs:
|
|
54
|
+
print("No results found.", file=sys.stderr)
|
|
55
|
+
return
|
|
56
|
+
|
|
57
|
+
print(f"Found {total:,} listings (showing {len(docs)}):\n")
|
|
58
|
+
|
|
59
|
+
for doc in docs:
|
|
60
|
+
price = doc.get("price", {})
|
|
61
|
+
amount = price.get("amount")
|
|
62
|
+
currency = price.get("price_unit", "kr")
|
|
63
|
+
location = doc.get("location", "")
|
|
64
|
+
heading = doc.get("heading", "Untitled")
|
|
65
|
+
url = doc.get("canonical_url", "")
|
|
66
|
+
|
|
67
|
+
price_str = f"{amount:,} {currency}".replace(",", " ") if amount else "—"
|
|
68
|
+
|
|
69
|
+
print(f" {heading}")
|
|
70
|
+
print(f" {price_str} · {location}")
|
|
71
|
+
print(f" {url}")
|
|
72
|
+
print()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def print_ad(data: dict, *, output: str = "table") -> None:
|
|
76
|
+
"""Print ad details."""
|
|
77
|
+
if output == "json":
|
|
78
|
+
print(_json_compact(data))
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
if "error" in data:
|
|
82
|
+
print(f"Error: {data['error']}", file=sys.stderr)
|
|
83
|
+
return
|
|
84
|
+
|
|
85
|
+
title = data.get("name", data.get("title", "Untitled"))
|
|
86
|
+
desc = data.get("description", "")
|
|
87
|
+
offers = data.get("offers", {})
|
|
88
|
+
price = offers.get("price", "")
|
|
89
|
+
currency = offers.get("priceCurrency", "SEK")
|
|
90
|
+
condition = data.get("itemCondition", "").split("/")[-1] if data.get("itemCondition") else ""
|
|
91
|
+
brand = ""
|
|
92
|
+
if isinstance(data.get("brand"), dict):
|
|
93
|
+
brand = data["brand"].get("name", "")
|
|
94
|
+
url = data.get("url", "")
|
|
95
|
+
|
|
96
|
+
print(title)
|
|
97
|
+
print("=" * min(len(title), 60))
|
|
98
|
+
if brand:
|
|
99
|
+
print(f"Brand: {brand}")
|
|
100
|
+
if price:
|
|
101
|
+
print(f"Price: {price} {currency}")
|
|
102
|
+
if condition:
|
|
103
|
+
print(f"Condition: {condition}")
|
|
104
|
+
if desc:
|
|
105
|
+
print(f"\n{desc}")
|
|
106
|
+
if url:
|
|
107
|
+
print(f"\n{url}")
|
|
File without changes
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "blocket-cli"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Fast CLI for searching Blocket.se — optimized for agents and scripting"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
requires-python = ">=3.10"
|
|
8
|
+
authors = [{ name = "Lennart Johansson" }]
|
|
9
|
+
keywords = ["blocket", "cli", "search", "marketplace", "sweden"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 4 - Beta",
|
|
12
|
+
"Environment :: Console",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"License :: OSI Approved :: MIT License",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Topic :: Utilities",
|
|
17
|
+
]
|
|
18
|
+
dependencies = [
|
|
19
|
+
"click>=8.0",
|
|
20
|
+
"httpx>=0.27",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
blocket = "blocket_cli.cli:main"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = ["pytest>=8.0", "ruff>=0.9"]
|
|
28
|
+
|
|
29
|
+
[tool.ruff]
|
|
30
|
+
target-version = "py310"
|
|
31
|
+
line-length = 120
|
|
32
|
+
|
|
33
|
+
[tool.ruff.lint]
|
|
34
|
+
select = ["E", "F", "I", "UP", "B", "SIM"]
|
|
35
|
+
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
testpaths = ["tests"]
|
|
38
|
+
|
|
39
|
+
[build-system]
|
|
40
|
+
requires = ["hatchling"]
|
|
41
|
+
build-backend = "hatchling.build"
|
|
File without changes
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Tests for the API client (no network calls)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from blocket_cli.api import (
|
|
10
|
+
CATEGORIES,
|
|
11
|
+
LOCATIONS,
|
|
12
|
+
_extract_product_data,
|
|
13
|
+
_resolve_category,
|
|
14
|
+
_resolve_location,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TestResolveLocation:
|
|
19
|
+
def test_valid(self):
|
|
20
|
+
assert _resolve_location("stockholm") == "0.300001"
|
|
21
|
+
|
|
22
|
+
def test_case_insensitive(self):
|
|
23
|
+
assert _resolve_location("Stockholm") == "0.300001"
|
|
24
|
+
|
|
25
|
+
def test_invalid(self):
|
|
26
|
+
with pytest.raises(ValueError, match="Unknown location 'narnia'"):
|
|
27
|
+
_resolve_location("narnia")
|
|
28
|
+
|
|
29
|
+
def test_all_locations_have_codes(self):
|
|
30
|
+
for name, code in LOCATIONS.items():
|
|
31
|
+
assert code.startswith("0.3000"), f"{name} has unexpected code {code}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class TestResolveCategory:
|
|
35
|
+
def test_valid(self):
|
|
36
|
+
assert _resolve_category("electronics") == "0.93"
|
|
37
|
+
|
|
38
|
+
def test_case_insensitive(self):
|
|
39
|
+
assert _resolve_category("Electronics") == "0.93"
|
|
40
|
+
|
|
41
|
+
def test_invalid(self):
|
|
42
|
+
with pytest.raises(ValueError, match="Unknown category 'weapons'"):
|
|
43
|
+
_resolve_category("weapons")
|
|
44
|
+
|
|
45
|
+
def test_all_categories_have_codes(self):
|
|
46
|
+
for name, code in CATEGORIES.items():
|
|
47
|
+
assert code.startswith("0."), f"{name} has unexpected code {code}"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class TestExtractProductData:
|
|
51
|
+
def test_extracts_product(self):
|
|
52
|
+
product = {"@type": "Product", "name": "Soffa", "offers": {"price": "500"}}
|
|
53
|
+
html = f'<html><head><script type="application/ld+json">{json.dumps(product)}</script></head></html>'
|
|
54
|
+
assert _extract_product_data(html) == product
|
|
55
|
+
|
|
56
|
+
def test_ignores_non_product(self):
|
|
57
|
+
other = {"@type": "Organization", "name": "Blocket"}
|
|
58
|
+
html = f'<html><script type="application/ld+json">{json.dumps(other)}</script></html>'
|
|
59
|
+
assert _extract_product_data(html) is None
|
|
60
|
+
|
|
61
|
+
def test_handles_multiple_scripts(self):
|
|
62
|
+
org = {"@type": "Organization", "name": "Blocket"}
|
|
63
|
+
product = {"@type": "Product", "name": "Cykel"}
|
|
64
|
+
html = (
|
|
65
|
+
f'<script type="application/ld+json">{json.dumps(org)}</script>'
|
|
66
|
+
f'<script type="application/ld+json">{json.dumps(product)}</script>'
|
|
67
|
+
)
|
|
68
|
+
assert _extract_product_data(html) == product
|
|
69
|
+
|
|
70
|
+
def test_handles_invalid_json(self):
|
|
71
|
+
html = '<script type="application/ld+json">not json</script>'
|
|
72
|
+
assert _extract_product_data(html) is None
|
|
73
|
+
|
|
74
|
+
def test_handles_no_scripts(self):
|
|
75
|
+
assert _extract_product_data("<html><body>Hello</body></html>") is None
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Tests for CLI commands (mocked HTTP)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from unittest.mock import patch
|
|
7
|
+
|
|
8
|
+
from click.testing import CliRunner
|
|
9
|
+
|
|
10
|
+
from blocket_cli.cli import main
|
|
11
|
+
|
|
12
|
+
SEARCH_RESPONSE = {
|
|
13
|
+
"docs": [
|
|
14
|
+
{
|
|
15
|
+
"id": "1",
|
|
16
|
+
"heading": "Test soffa",
|
|
17
|
+
"price": {"amount": 2000, "currency_code": "SEK", "price_unit": "kr"},
|
|
18
|
+
"location": "Stockholm",
|
|
19
|
+
"canonical_url": "https://www.blocket.se/item/1",
|
|
20
|
+
"timestamp": 1700000000000,
|
|
21
|
+
"extras": [],
|
|
22
|
+
"image_urls": ["https://img.com/1.jpg"],
|
|
23
|
+
"coordinates": {"lat": 59.0, "lon": 18.0},
|
|
24
|
+
}
|
|
25
|
+
],
|
|
26
|
+
"metadata": {"result_size": {"match_count": 1}},
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _mock_search(*args, **kwargs):
|
|
31
|
+
return SEARCH_RESPONSE
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _mock_get_ad(*args, **kwargs):
|
|
35
|
+
return {
|
|
36
|
+
"@type": "Product",
|
|
37
|
+
"name": "Test soffa",
|
|
38
|
+
"description": "En fin soffa",
|
|
39
|
+
"offers": {"price": "2000", "priceCurrency": "SEK"},
|
|
40
|
+
"url": "https://www.blocket.se/item/1",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TestSearchCommand:
|
|
45
|
+
def test_table_output(self):
|
|
46
|
+
with patch("blocket_cli.cli.api.search", _mock_search):
|
|
47
|
+
result = CliRunner().invoke(main, ["search", "soffa"])
|
|
48
|
+
assert result.exit_code == 0
|
|
49
|
+
assert "Test soffa" in result.output
|
|
50
|
+
assert "2 000 kr" in result.output
|
|
51
|
+
|
|
52
|
+
def test_json_output_is_slim(self):
|
|
53
|
+
with patch("blocket_cli.cli.api.search", _mock_search):
|
|
54
|
+
result = CliRunner().invoke(main, ["search", "soffa", "-o", "json"])
|
|
55
|
+
data = json.loads(result.output)
|
|
56
|
+
listing = data["results"][0]
|
|
57
|
+
assert listing["id"] == "1"
|
|
58
|
+
assert listing["price"] == 2000
|
|
59
|
+
assert "image_urls" not in listing
|
|
60
|
+
assert "coordinates" not in listing
|
|
61
|
+
|
|
62
|
+
def test_json_raw_output(self):
|
|
63
|
+
with patch("blocket_cli.cli.api.search", _mock_search):
|
|
64
|
+
result = CliRunner().invoke(main, ["search", "soffa", "-o", "json", "--raw"])
|
|
65
|
+
data = json.loads(result.output)
|
|
66
|
+
listing = data["results"][0]
|
|
67
|
+
assert "image_urls" in listing
|
|
68
|
+
assert "coordinates" in listing
|
|
69
|
+
|
|
70
|
+
def test_limit(self):
|
|
71
|
+
with patch("blocket_cli.cli.api.search", _mock_search):
|
|
72
|
+
result = CliRunner().invoke(main, ["search", "soffa", "-o", "json", "-n", "1"])
|
|
73
|
+
data = json.loads(result.output)
|
|
74
|
+
assert len(data["results"]) == 1
|
|
75
|
+
|
|
76
|
+
def test_invalid_category(self):
|
|
77
|
+
result = CliRunner().invoke(main, ["search", "x", "-c", "badcat"])
|
|
78
|
+
assert result.exit_code == 1
|
|
79
|
+
assert "Unknown category" in result.output
|
|
80
|
+
|
|
81
|
+
def test_invalid_location(self):
|
|
82
|
+
result = CliRunner().invoke(main, ["search", "x", "-l", "narnia"])
|
|
83
|
+
assert result.exit_code == 1
|
|
84
|
+
assert "Unknown location" in result.output
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class TestAdCommand:
|
|
88
|
+
def test_table_output(self):
|
|
89
|
+
with patch("blocket_cli.cli.api.get_ad", _mock_get_ad):
|
|
90
|
+
result = CliRunner().invoke(main, ["ad", "1"])
|
|
91
|
+
assert result.exit_code == 0
|
|
92
|
+
assert "Test soffa" in result.output
|
|
93
|
+
assert "2000 SEK" in result.output
|
|
94
|
+
|
|
95
|
+
def test_json_output(self):
|
|
96
|
+
with patch("blocket_cli.cli.api.get_ad", _mock_get_ad):
|
|
97
|
+
result = CliRunner().invoke(main, ["ad", "1", "-o", "json"])
|
|
98
|
+
data = json.loads(result.output)
|
|
99
|
+
assert data["name"] == "Test soffa"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class TestListCommands:
|
|
103
|
+
def test_categories(self):
|
|
104
|
+
result = CliRunner().invoke(main, ["categories"])
|
|
105
|
+
assert result.exit_code == 0
|
|
106
|
+
assert "electronics" in result.output
|
|
107
|
+
|
|
108
|
+
def test_locations(self):
|
|
109
|
+
result = CliRunner().invoke(main, ["locations"])
|
|
110
|
+
assert result.exit_code == 0
|
|
111
|
+
assert "stockholm" in result.output
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Tests for output formatting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from blocket_cli.format import _slim
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TestSlim:
|
|
11
|
+
def test_essential_fields(self):
|
|
12
|
+
doc = {
|
|
13
|
+
"id": "123",
|
|
14
|
+
"heading": "Test item",
|
|
15
|
+
"price": {"amount": 500, "currency_code": "SEK", "price_unit": "kr"},
|
|
16
|
+
"location": "Stockholm",
|
|
17
|
+
"canonical_url": "https://www.blocket.se/item/123",
|
|
18
|
+
"timestamp": 1700000000000,
|
|
19
|
+
}
|
|
20
|
+
result = _slim(doc)
|
|
21
|
+
assert result == {
|
|
22
|
+
"id": "123",
|
|
23
|
+
"heading": "Test item",
|
|
24
|
+
"price": 500,
|
|
25
|
+
"currency": "SEK",
|
|
26
|
+
"location": "Stockholm",
|
|
27
|
+
"url": "https://www.blocket.se/item/123",
|
|
28
|
+
"date": "2023-11-14",
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
def test_strips_images_and_coordinates(self):
|
|
32
|
+
doc = {
|
|
33
|
+
"id": "1",
|
|
34
|
+
"heading": "X",
|
|
35
|
+
"price": {"amount": 100, "currency_code": "SEK"},
|
|
36
|
+
"location": "A",
|
|
37
|
+
"canonical_url": "https://example.com",
|
|
38
|
+
"image": {"url": "https://img.com/1.jpg", "width": 800, "height": 600},
|
|
39
|
+
"image_urls": ["https://img.com/1.jpg", "https://img.com/2.jpg"],
|
|
40
|
+
"coordinates": {"lat": 59.0, "lon": 18.0},
|
|
41
|
+
"flags": ["private"],
|
|
42
|
+
"labels": [{"id": "private", "text": "Privat"}],
|
|
43
|
+
"ad_type": 67,
|
|
44
|
+
"distance": 0.0,
|
|
45
|
+
"main_search_key": "SEARCH_ID_BAP_ALL",
|
|
46
|
+
}
|
|
47
|
+
result = _slim(doc)
|
|
48
|
+
assert "image" not in result
|
|
49
|
+
assert "image_urls" not in result
|
|
50
|
+
assert "coordinates" not in result
|
|
51
|
+
assert "flags" not in result
|
|
52
|
+
assert "labels" not in result
|
|
53
|
+
assert "ad_type" not in result
|
|
54
|
+
assert "distance" not in result
|
|
55
|
+
assert "main_search_key" not in result
|
|
56
|
+
|
|
57
|
+
def test_extracts_brand(self):
|
|
58
|
+
doc = {
|
|
59
|
+
"id": "1",
|
|
60
|
+
"heading": "Phone",
|
|
61
|
+
"price": {"amount": 3000, "currency_code": "SEK"},
|
|
62
|
+
"location": "Malmö",
|
|
63
|
+
"canonical_url": "https://example.com",
|
|
64
|
+
"extras": [{"id": "brand", "values": ["Apple"]}],
|
|
65
|
+
}
|
|
66
|
+
assert _slim(doc)["brand"] == "Apple"
|
|
67
|
+
|
|
68
|
+
def test_no_brand_when_missing(self):
|
|
69
|
+
doc = {
|
|
70
|
+
"id": "1",
|
|
71
|
+
"heading": "Thing",
|
|
72
|
+
"price": {"amount": 100, "currency_code": "SEK"},
|
|
73
|
+
"location": "A",
|
|
74
|
+
"canonical_url": "https://example.com",
|
|
75
|
+
"extras": [],
|
|
76
|
+
}
|
|
77
|
+
assert "brand" not in _slim(doc)
|
|
78
|
+
|
|
79
|
+
def test_no_timestamp(self):
|
|
80
|
+
doc = {
|
|
81
|
+
"id": "1",
|
|
82
|
+
"heading": "X",
|
|
83
|
+
"price": {},
|
|
84
|
+
"location": "A",
|
|
85
|
+
"canonical_url": "https://example.com",
|
|
86
|
+
}
|
|
87
|
+
result = _slim(doc)
|
|
88
|
+
assert "date" not in result
|
|
89
|
+
|
|
90
|
+
def test_output_is_json_serializable(self):
|
|
91
|
+
doc = {
|
|
92
|
+
"id": "1",
|
|
93
|
+
"heading": "Ö-ring",
|
|
94
|
+
"price": {"amount": 50, "currency_code": "SEK"},
|
|
95
|
+
"location": "Göteborg",
|
|
96
|
+
"canonical_url": "https://example.com",
|
|
97
|
+
"timestamp": 1700000000000,
|
|
98
|
+
"extras": [{"id": "brand", "values": ["IKEA"]}],
|
|
99
|
+
}
|
|
100
|
+
dumped = json.dumps(_slim(doc), ensure_ascii=False)
|
|
101
|
+
assert "Ö-ring" in dumped
|
|
102
|
+
assert "Göteborg" in dumped
|