blizzardapi2 2.1.19__tar.gz → 2.1.20__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.
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.github/workflows/black-check.yml +1 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.github/workflows/python-package.yml +30 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.pre-commit-config.yaml +1 -1
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.release-it.json +1 -1
- blizzardapi2-2.1.20/CLAUDE.md +69 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/CONTRIBUTING.md +2 -2
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/PKG-INFO +2 -2
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2.egg-info/PKG-INFO +2 -2
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2.egg-info/SOURCES.txt +10 -1
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2.egg-info/requires.txt +1 -1
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/package.json +1 -1
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/pyproject.toml +8 -4
- blizzardapi2-2.1.20/tests/__init__.py +0 -0
- blizzardapi2-2.1.20/tests/conftest.py +64 -0
- blizzardapi2-2.1.20/tests/test_base_api.py +326 -0
- blizzardapi2-2.1.20/tests/test_battlenet.py +152 -0
- blizzardapi2-2.1.20/tests/test_diablo3.py +207 -0
- blizzardapi2-2.1.20/tests/test_hearthstone.py +151 -0
- blizzardapi2-2.1.20/tests/test_starcraft2.py +168 -0
- blizzardapi2-2.1.20/tests/test_wow.py +274 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.github/dependabot.yml +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.github/workflows/README.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/.gitignore +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/CODE_OF_CONDUCT.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/LICENSE +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/README.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/SECURITY.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/__init__.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/battlenet/__init__.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/battlenet/battlenet_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/battlenet/battlenet_oauth_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/blizzard_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/diablo3/__init__.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/diablo3/diablo3_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/diablo3/diablo3_community_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/diablo3/diablo3_game_data_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/hearthstone/__init__.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/hearthstone/hearthstone_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/hearthstone/hearthstone_game_data_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/starcraft2/__init__.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/starcraft2/starcraft2_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/starcraft2/starcraft2_community_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/starcraft2/starcraft2_game_data_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/types.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/wow/__init__.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/wow/wow_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/wow/wow_game_data_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2/wow/wow_profile_api.py +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2.egg-info/dependency_links.txt +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/blizzardapi2.egg-info/top_level.txt +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/docs/battlenet/README.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/docs/diablo3/README.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/docs/hearthstone/README.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/docs/pull_request_template.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/docs/starcraft2/README.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/docs/wow/README.md +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/poetry.lock +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/setup.cfg +0 -0
- {blizzardapi2-2.1.19 → blizzardapi2-2.1.20}/uv.lock +0 -0
|
@@ -6,6 +6,8 @@ name: Python package
|
|
|
6
6
|
on:
|
|
7
7
|
push:
|
|
8
8
|
branches: ["main"]
|
|
9
|
+
pull_request:
|
|
10
|
+
branches: ["main"]
|
|
9
11
|
|
|
10
12
|
# Add permissions block
|
|
11
13
|
permissions:
|
|
@@ -14,7 +16,35 @@ permissions:
|
|
|
14
16
|
id-token: write
|
|
15
17
|
|
|
16
18
|
jobs:
|
|
19
|
+
test:
|
|
20
|
+
runs-on: ubuntu-latest
|
|
21
|
+
strategy:
|
|
22
|
+
fail-fast: false
|
|
23
|
+
matrix:
|
|
24
|
+
python-version: ["3.11", "3.12", "3.13"]
|
|
25
|
+
steps:
|
|
26
|
+
- uses: actions/checkout@v4
|
|
27
|
+
|
|
28
|
+
- name: Set up Python ${{ matrix.python-version }}
|
|
29
|
+
uses: actions/setup-python@v5
|
|
30
|
+
with:
|
|
31
|
+
python-version: ${{ matrix.python-version }}
|
|
32
|
+
|
|
33
|
+
- name: Install uv
|
|
34
|
+
run: |
|
|
35
|
+
curl -LsSf https://astral.sh/uv/install.sh | sh
|
|
36
|
+
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
|
|
37
|
+
|
|
38
|
+
- name: Create venv and install dev deps
|
|
39
|
+
run: |
|
|
40
|
+
uv venv
|
|
41
|
+
uv pip install -e ".[dev]"
|
|
42
|
+
|
|
43
|
+
- name: Run tests
|
|
44
|
+
run: uv run pytest tests/ -v
|
|
45
|
+
|
|
17
46
|
publish:
|
|
47
|
+
needs: test
|
|
18
48
|
if: github.ref == 'refs/heads/main'
|
|
19
49
|
runs-on: ubuntu-latest
|
|
20
50
|
steps:
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
+
|
|
5
|
+
## Project
|
|
6
|
+
|
|
7
|
+
`blizzardapi2` is a published PyPI package (synchronous client wrapper around Blizzard's Battle.net APIs). Public API surface is `from blizzardapi2 import BlizzardApi`. Treat the package boundary as load-bearing — every name, parameter shape, and return type is part of the contract for external users.
|
|
8
|
+
|
|
9
|
+
Python 3.11+ only. Uses `requests` synchronously today; `aiohttp` and `pydantic` are declared dependencies but not yet integrated into the public surface.
|
|
10
|
+
|
|
11
|
+
## Common commands
|
|
12
|
+
|
|
13
|
+
Use `uv` for environment management (matches CI):
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
uv venv
|
|
17
|
+
uv pip install -e ".[dev]"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Lint / format:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
ruff check . # lint (line-length 120, see caveat below)
|
|
24
|
+
ruff format . # format
|
|
25
|
+
black . # pre-commit also runs black with --line-length=88 (mismatch — see below)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Tests: **there is no `test_project/` directory in the repo despite CONTRIBUTING.md referencing it**, and no test job in CI. If you add tests, use `pytest` / `pytest-mock` / `pytest-asyncio` (already in `[dev]`) and configure a workflow.
|
|
29
|
+
|
|
30
|
+
Release: do not bump versions by hand. Pushing to `main` triggers `.github/workflows/python-package.yml`, which builds, publishes to PyPI, then runs `release-it` to tag and create a GitHub release. `release-it`'s `after:bump` hook `sed`s `pyproject.toml`'s `version = "..."`.
|
|
31
|
+
|
|
32
|
+
## Architecture
|
|
33
|
+
|
|
34
|
+
Single base class + one facade per game, each game facade composing sub-APIs:
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
BlizzardApi (blizzard_api.py)
|
|
38
|
+
├── wow → WowApi → { game_data: WowGameDataApi, profile: WowProfileApi }
|
|
39
|
+
├── diablo3 → Diablo3Api → { community, game_data }
|
|
40
|
+
├── hearthstone, starcraft2, battlenet → similar pattern
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
All API classes inherit `BaseApi` (`api.py`). New endpoint methods are thin wrappers: build a `resource` path + `query_params` dict (typically `{"namespace": f"static-{region}", "locale": locale}`), then call `super().get_resource(...)` or `super().get_oauth_resource(...)`. Patterns are most clearly visible in `wow/wow_game_data_api.py`.
|
|
44
|
+
|
|
45
|
+
### Token handling — the non-obvious part
|
|
46
|
+
|
|
47
|
+
`BaseApi._make_request` has a deliberate indirection: callers pass user OAuth tokens **inside `query_params` under the key `"access_token"`**. `_make_request` `.pop()`s that key and moves the value into the `Authorization: Bearer <token>` header. This keeps tokens out of URL query strings (visible in logs/proxies). Preserve this when adding OAuth-protected endpoints — see `battlenet/battlenet_oauth_api.py:get_user_info` for the canonical shape. Don't add a separate `access_token` keyword argument to `_make_request`; the pop-from-params pattern is the contract.
|
|
48
|
+
|
|
49
|
+
Client-credentials tokens are managed automatically: `_ensure_valid_token` lazily fetches and caches them, with a 5-minute refresh buffer (`TOKEN_REFRESH_BUFFER`). On a 401 with a client-credentials token, `_make_request` refreshes and retries once. User-supplied OAuth tokens are never refreshed by the library.
|
|
50
|
+
|
|
51
|
+
### Region URL routing
|
|
52
|
+
|
|
53
|
+
`BaseApi.OAUTH_URLS` and `API_URLS` route China (`"cn"`) to `*.battlenet.com.cn` hosts, all other regions to `oauth.battle.net` and `{region}.api.blizzard.com`. Always use `_build_oauth_url` / `_build_api_url` rather than f-stringing URLs by hand.
|
|
54
|
+
|
|
55
|
+
### Independent token caches per sub-API
|
|
56
|
+
|
|
57
|
+
Each game's facade instantiates its sub-APIs with `client_id`/`client_secret`, so `WowGameDataApi`, `WowProfileApi`, `Diablo3CommunityApi`, etc. each maintain their **own** `_session` and `_access_token`. There is no shared token cache across sub-APIs. This is fine for the current API surface but worth knowing if you're debugging unexpected token-fetch behavior.
|
|
58
|
+
|
|
59
|
+
### `Region` / `Locale` enums
|
|
60
|
+
|
|
61
|
+
`types.py` defines `Region` and `Locale` as `str` enums. Most current endpoint methods are typed as `region: str, locale: str` and accept either bare strings or enum members (since enums subclass `str`). Newer code (e.g., `BattlenetOAuthApi`) uses the enums in signatures — prefer that for new code.
|
|
62
|
+
|
|
63
|
+
## Conventions and gotchas
|
|
64
|
+
|
|
65
|
+
- **`blizzardapi2/_version.py` is auto-generated** by `setuptools_scm` (`write_to` configured in `pyproject.toml`). Never edit by hand; don't import it as authoritative — `pyproject.toml`'s `version` is what `release-it` mutates.
|
|
66
|
+
- **`tool.ruff.target-version` in `pyproject.toml` is currently `"2.1.18"`** (the package version). The release-it `sed` hook replaces every `version = "..."` line and clobbers it. If you touch ruff config, restore this to `"py311"` and consider tightening the sed to `^version =` to prevent recurrence.
|
|
67
|
+
- **Black line-length mismatch:** pre-commit runs `black --line-length=88`, but `tool.ruff.line-length = 120`. Don't reformat existing files just to "fix" this — it'll churn diffs. Match surrounding style.
|
|
68
|
+
- Inherit from `Api`/`BaseApi` (not `BaseApi` plus a separate base) — see CONTRIBUTING.md "Import Fixes" section.
|
|
69
|
+
- Commit style is conventional commits (`feat:`, `fix:`, `chore:`, etc.) — release notes are auto-generated from them.
|
|
@@ -131,7 +131,7 @@ Use conventional commit messages:
|
|
|
131
131
|
pytest
|
|
132
132
|
|
|
133
133
|
# Run specific test file
|
|
134
|
-
pytest
|
|
134
|
+
pytest tests/test_wow.py
|
|
135
135
|
|
|
136
136
|
# Run with verbose output
|
|
137
137
|
pytest -v
|
|
@@ -139,7 +139,7 @@ pytest -v
|
|
|
139
139
|
|
|
140
140
|
### Writing Tests
|
|
141
141
|
|
|
142
|
-
- Place tests in the `
|
|
142
|
+
- Place tests in the `tests/` directory
|
|
143
143
|
- Use descriptive test names
|
|
144
144
|
- Include both positive and negative test cases
|
|
145
145
|
- Mock external API calls
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: blizzardapi2
|
|
3
|
-
Version: 2.1.
|
|
3
|
+
Version: 2.1.20
|
|
4
4
|
Summary: A Python wrapper for Blizzard API
|
|
5
5
|
Author-email: lostcol0ny <c098os0k@4wrd.cc>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -17,7 +17,7 @@ Provides-Extra: dev
|
|
|
17
17
|
Requires-Dist: pytest<10.0.0,>=8.2.2; extra == "dev"
|
|
18
18
|
Requires-Dist: pytest-mock<4.0.0,>=3.14.0; extra == "dev"
|
|
19
19
|
Requires-Dist: pytest-asyncio<2.0.0,>=0.23.5; extra == "dev"
|
|
20
|
-
Requires-Dist: black<27.0.0,>=
|
|
20
|
+
Requires-Dist: black<27.0.0,>=26.3.1; extra == "dev"
|
|
21
21
|
Requires-Dist: ruff<1.0.0,>=0.3.0; extra == "dev"
|
|
22
22
|
Dynamic: license-file
|
|
23
23
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: blizzardapi2
|
|
3
|
-
Version: 2.1.
|
|
3
|
+
Version: 2.1.20
|
|
4
4
|
Summary: A Python wrapper for Blizzard API
|
|
5
5
|
Author-email: lostcol0ny <c098os0k@4wrd.cc>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -17,7 +17,7 @@ Provides-Extra: dev
|
|
|
17
17
|
Requires-Dist: pytest<10.0.0,>=8.2.2; extra == "dev"
|
|
18
18
|
Requires-Dist: pytest-mock<4.0.0,>=3.14.0; extra == "dev"
|
|
19
19
|
Requires-Dist: pytest-asyncio<2.0.0,>=0.23.5; extra == "dev"
|
|
20
|
-
Requires-Dist: black<27.0.0,>=
|
|
20
|
+
Requires-Dist: black<27.0.0,>=26.3.1; extra == "dev"
|
|
21
21
|
Requires-Dist: ruff<1.0.0,>=0.3.0; extra == "dev"
|
|
22
22
|
Dynamic: license-file
|
|
23
23
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
.gitignore
|
|
2
2
|
.pre-commit-config.yaml
|
|
3
3
|
.release-it.json
|
|
4
|
+
CLAUDE.md
|
|
4
5
|
CODE_OF_CONDUCT.md
|
|
5
6
|
CONTRIBUTING.md
|
|
6
7
|
LICENSE
|
|
@@ -48,4 +49,12 @@ docs/battlenet/README.md
|
|
|
48
49
|
docs/diablo3/README.md
|
|
49
50
|
docs/hearthstone/README.md
|
|
50
51
|
docs/starcraft2/README.md
|
|
51
|
-
docs/wow/README.md
|
|
52
|
+
docs/wow/README.md
|
|
53
|
+
tests/__init__.py
|
|
54
|
+
tests/conftest.py
|
|
55
|
+
tests/test_base_api.py
|
|
56
|
+
tests/test_battlenet.py
|
|
57
|
+
tests/test_diablo3.py
|
|
58
|
+
tests/test_hearthstone.py
|
|
59
|
+
tests/test_starcraft2.py
|
|
60
|
+
tests/test_wow.py
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "blizzardapi2"
|
|
3
|
-
version = "2.1.
|
|
3
|
+
version = "2.1.20"
|
|
4
4
|
description = "A Python wrapper for Blizzard API"
|
|
5
5
|
authors = [{ name = "lostcol0ny", email = "c098os0k@4wrd.cc" }]
|
|
6
6
|
license = "MIT"
|
|
@@ -29,12 +29,16 @@ include = ["blizzardapi2*"]
|
|
|
29
29
|
write_to = "blizzardapi2/_version.py"
|
|
30
30
|
local_scheme = "node-and-timestamp"
|
|
31
31
|
|
|
32
|
+
[tool.pytest.ini_options]
|
|
33
|
+
testpaths = ["tests"]
|
|
34
|
+
pythonpath = ["."]
|
|
35
|
+
|
|
32
36
|
[project.optional-dependencies]
|
|
33
37
|
dev = [
|
|
34
38
|
"pytest>=8.2.2,<10.0.0",
|
|
35
39
|
"pytest-mock>=3.14.0,<4.0.0",
|
|
36
40
|
"pytest-asyncio>=0.23.5,<2.0.0",
|
|
37
|
-
"black>=
|
|
41
|
+
"black>=26.3.1,<27.0.0",
|
|
38
42
|
"ruff>=0.3.0,<1.0.0",
|
|
39
43
|
]
|
|
40
44
|
|
|
@@ -70,10 +74,10 @@ exclude = [
|
|
|
70
74
|
]
|
|
71
75
|
|
|
72
76
|
# Same as Black.
|
|
73
|
-
line-length =
|
|
77
|
+
line-length = 88
|
|
74
78
|
|
|
75
79
|
# Assume Python 3.11
|
|
76
|
-
target-version = "
|
|
80
|
+
target-version = "py311"
|
|
77
81
|
|
|
78
82
|
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
|
|
79
83
|
select = ["E4", "E7", "E9", "F"]
|
|
File without changes
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Shared pytest fixtures for blizzardapi2 tests.
|
|
2
|
+
|
|
3
|
+
The Blizzard API client is a thin wrapper around `requests`. Tests verify URL
|
|
4
|
+
construction, query-parameter shape, and token handling — never live HTTP. All
|
|
5
|
+
network is patched at the `requests.Session` boundary.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from datetime import UTC, datetime, timedelta
|
|
11
|
+
from typing import Any
|
|
12
|
+
from unittest.mock import MagicMock
|
|
13
|
+
|
|
14
|
+
import pytest
|
|
15
|
+
|
|
16
|
+
CLIENT_ID = "test_client_id"
|
|
17
|
+
CLIENT_SECRET = "test_client_secret"
|
|
18
|
+
FAKE_TOKEN = "fake_access_token"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture
|
|
22
|
+
def fake_credentials() -> tuple[str, str]:
|
|
23
|
+
"""Stable (client_id, client_secret) pair for instantiating API clients."""
|
|
24
|
+
return CLIENT_ID, CLIENT_SECRET
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.fixture
|
|
28
|
+
def mock_get(mocker) -> MagicMock:
|
|
29
|
+
"""Patch `requests.Session.get` globally with a 200 + empty-dict response.
|
|
30
|
+
|
|
31
|
+
Tests typically inspect `mock_get.call_args` to assert URL, params, and
|
|
32
|
+
headers. Override `return_value.json.return_value` per-test for shaped data.
|
|
33
|
+
"""
|
|
34
|
+
mock = mocker.patch("requests.Session.get")
|
|
35
|
+
mock.return_value.status_code = 200
|
|
36
|
+
mock.return_value.json.return_value = {}
|
|
37
|
+
return mock
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@pytest.fixture
|
|
41
|
+
def mock_post(mocker) -> MagicMock:
|
|
42
|
+
"""Patch `requests.Session.post` to return a fake OAuth token response.
|
|
43
|
+
|
|
44
|
+
BaseApi calls POST only for `/oauth/token` (client-credentials flow).
|
|
45
|
+
"""
|
|
46
|
+
mock = mocker.patch("requests.Session.post")
|
|
47
|
+
mock.return_value.status_code = 200
|
|
48
|
+
mock.return_value.json.return_value = {
|
|
49
|
+
"access_token": FAKE_TOKEN,
|
|
50
|
+
"token_type": "bearer",
|
|
51
|
+
"expires_in": 86400,
|
|
52
|
+
}
|
|
53
|
+
return mock
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def prime_token(
|
|
57
|
+
api_instance: Any, token: str = FAKE_TOKEN, expires_in: int = 86400
|
|
58
|
+
) -> None:
|
|
59
|
+
"""Pre-populate an API instance with a non-expired client-credentials token.
|
|
60
|
+
|
|
61
|
+
Lets tests skip the token POST when they only care about the GET request.
|
|
62
|
+
"""
|
|
63
|
+
api_instance._access_token = token
|
|
64
|
+
api_instance._token_expires_at = datetime.now(UTC) + timedelta(seconds=expires_in)
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Tests for BaseApi — auth, URL construction, and token lifecycle.
|
|
2
|
+
|
|
3
|
+
BaseApi is the security-critical seam: every request flows through its
|
|
4
|
+
URL builders and `_make_request`. These tests verify that user-supplied
|
|
5
|
+
OAuth tokens are never leaked into URL query strings, that client
|
|
6
|
+
credentials are sent via HTTP Basic auth, and that the 401-retry path
|
|
7
|
+
only fires for the client-credentials flow (never for user tokens).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from datetime import UTC, datetime, timedelta
|
|
13
|
+
|
|
14
|
+
import pytest
|
|
15
|
+
|
|
16
|
+
from blizzardapi2.api import BaseApi
|
|
17
|
+
from tests.conftest import CLIENT_ID, CLIENT_SECRET, FAKE_TOKEN, prime_token
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@pytest.fixture
|
|
21
|
+
def api(fake_credentials) -> BaseApi:
|
|
22
|
+
"""A fresh BaseApi instance with no token primed."""
|
|
23
|
+
client_id, client_secret = fake_credentials
|
|
24
|
+
return BaseApi(client_id, client_secret)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ---------------------------------------------------------------------------
|
|
28
|
+
# URL construction
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.mark.parametrize("region", ["us", "eu", "kr", "tw"])
|
|
33
|
+
def test_build_api_url_non_cn_regions(api: BaseApi, region: str) -> None:
|
|
34
|
+
"""Non-CN regions resolve to `{region}.api.blizzard.com`."""
|
|
35
|
+
url = api._build_api_url("/data/wow/realm/index", region)
|
|
36
|
+
assert url == f"https://{region}.api.blizzard.com/data/wow/realm/index"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_build_api_url_cn_uses_gateway(api: BaseApi) -> None:
|
|
40
|
+
"""CN region uses the special gateway host with no region subdomain."""
|
|
41
|
+
url = api._build_api_url("/data/wow/realm/index", "cn")
|
|
42
|
+
assert url == "https://gateway.battlenet.com.cn/data/wow/realm/index"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@pytest.mark.parametrize("region", ["us", "eu", "kr", "tw"])
|
|
46
|
+
def test_build_oauth_url_non_cn_regions(api: BaseApi, region: str) -> None:
|
|
47
|
+
"""Non-CN OAuth always points to the global oauth.battle.net host."""
|
|
48
|
+
url = api._build_oauth_url("/oauth/token", region)
|
|
49
|
+
assert url == "https://oauth.battle.net/oauth/token"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_build_oauth_url_cn_uses_china_gateway(api: BaseApi) -> None:
|
|
53
|
+
"""CN OAuth uses the China-specific gateway host."""
|
|
54
|
+
url = api._build_oauth_url("/oauth/token", "cn")
|
|
55
|
+
assert url == "https://www.gateway.battlenet.com.cn/oauth/token"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ---------------------------------------------------------------------------
|
|
59
|
+
# Token expiry checks
|
|
60
|
+
# ---------------------------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_is_token_expired_true_when_no_token(api: BaseApi) -> None:
|
|
64
|
+
"""A never-fetched token is treated as expired."""
|
|
65
|
+
assert api._token_expires_at is None
|
|
66
|
+
assert api._is_token_expired() is True
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_is_token_expired_false_when_fresh(api: BaseApi) -> None:
|
|
70
|
+
"""A token comfortably outside the refresh buffer is not expired."""
|
|
71
|
+
prime_token(api, expires_in=86400)
|
|
72
|
+
assert api._is_token_expired() is False
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_is_token_expired_true_within_refresh_buffer(api: BaseApi) -> None:
|
|
76
|
+
"""A token expiring within TOKEN_REFRESH_BUFFER is treated as expired."""
|
|
77
|
+
api._access_token = FAKE_TOKEN
|
|
78
|
+
# Expires in 4 minutes — inside the 5-minute refresh window.
|
|
79
|
+
api._token_expires_at = datetime.now(UTC) + timedelta(minutes=4)
|
|
80
|
+
assert api._is_token_expired() is True
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ---------------------------------------------------------------------------
|
|
84
|
+
# _ensure_valid_token
|
|
85
|
+
# ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_ensure_valid_token_fetches_when_missing(api: BaseApi, mock_post) -> None:
|
|
89
|
+
"""First call lazily POSTs to /oauth/token."""
|
|
90
|
+
api._ensure_valid_token("us")
|
|
91
|
+
assert mock_post.call_count == 1
|
|
92
|
+
assert api._access_token == FAKE_TOKEN
|
|
93
|
+
assert api._token_expires_at is not None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_ensure_valid_token_noop_when_fresh(api: BaseApi, mock_post) -> None:
|
|
97
|
+
"""A fresh cached token must not trigger another POST."""
|
|
98
|
+
prime_token(api)
|
|
99
|
+
api._ensure_valid_token("us")
|
|
100
|
+
assert mock_post.call_count == 0
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ---------------------------------------------------------------------------
|
|
104
|
+
# _get_client_token
|
|
105
|
+
# ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_get_client_token_uses_basic_auth_and_grant_type(
|
|
109
|
+
api: BaseApi, mock_post
|
|
110
|
+
) -> None:
|
|
111
|
+
"""POST must use HTTP Basic with credentials and client_credentials grant."""
|
|
112
|
+
api._get_client_token("us")
|
|
113
|
+
|
|
114
|
+
mock_post.assert_called_once()
|
|
115
|
+
call = mock_post.call_args
|
|
116
|
+
# URL is positional arg 0
|
|
117
|
+
assert call.args[0] == "https://oauth.battle.net/oauth/token"
|
|
118
|
+
assert call.kwargs["params"] == {"grant_type": "client_credentials"}
|
|
119
|
+
assert call.kwargs["auth"] == (CLIENT_ID, CLIENT_SECRET)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_get_client_token_stores_token_and_expiry(api: BaseApi, mock_post) -> None:
|
|
123
|
+
"""Response is parsed into _access_token and _token_expires_at."""
|
|
124
|
+
before = datetime.now(UTC)
|
|
125
|
+
api._get_client_token("us")
|
|
126
|
+
after = datetime.now(UTC)
|
|
127
|
+
|
|
128
|
+
assert api._access_token == FAKE_TOKEN
|
|
129
|
+
assert api._token_expires_at is not None
|
|
130
|
+
# expires_in is 86400 in the fixture; expiry should sit roughly there.
|
|
131
|
+
expected_min = before + timedelta(seconds=86400)
|
|
132
|
+
expected_max = after + timedelta(seconds=86400)
|
|
133
|
+
assert expected_min <= api._token_expires_at <= expected_max
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_get_client_token_uses_cn_oauth_url(api: BaseApi, mock_post) -> None:
|
|
137
|
+
"""CN region routes through the China gateway host for token POST."""
|
|
138
|
+
api._get_client_token("cn")
|
|
139
|
+
assert (
|
|
140
|
+
mock_post.call_args.args[0]
|
|
141
|
+
== "https://www.gateway.battlenet.com.cn/oauth/token"
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# ---------------------------------------------------------------------------
|
|
146
|
+
# _make_request — happy path
|
|
147
|
+
# ---------------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def test_make_request_uses_cached_token_in_bearer_header(
|
|
151
|
+
api: BaseApi, mock_get
|
|
152
|
+
) -> None:
|
|
153
|
+
"""Cached client-credentials token is sent as `Authorization: Bearer ...`."""
|
|
154
|
+
prime_token(api)
|
|
155
|
+
mock_get.return_value.json.return_value = {"ok": True}
|
|
156
|
+
|
|
157
|
+
result = api._make_request("https://us.api.blizzard.com/data/wow/realm/index", "us")
|
|
158
|
+
|
|
159
|
+
assert result == {"ok": True}
|
|
160
|
+
mock_get.assert_called_once()
|
|
161
|
+
headers = mock_get.call_args.kwargs["headers"]
|
|
162
|
+
assert headers["Authorization"] == f"Bearer {FAKE_TOKEN}"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def test_make_request_passes_query_params_through(api: BaseApi, mock_get) -> None:
|
|
166
|
+
"""Non-token query params are forwarded to Session.get untouched."""
|
|
167
|
+
prime_token(api)
|
|
168
|
+
api._make_request(
|
|
169
|
+
"https://us.api.blizzard.com/data/wow/realm/index",
|
|
170
|
+
"us",
|
|
171
|
+
query_params={"locale": "en_US", "namespace": "dynamic-us"},
|
|
172
|
+
)
|
|
173
|
+
assert mock_get.call_args.kwargs["params"] == {
|
|
174
|
+
"locale": "en_US",
|
|
175
|
+
"namespace": "dynamic-us",
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# ---------------------------------------------------------------------------
|
|
180
|
+
# _make_request — user OAuth token must NEVER hit the URL
|
|
181
|
+
# ---------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def test_make_request_user_access_token_moves_to_header(
|
|
185
|
+
api: BaseApi, mock_get, mock_post
|
|
186
|
+
) -> None:
|
|
187
|
+
"""A user-supplied access_token is moved to the Authorization header.
|
|
188
|
+
|
|
189
|
+
Critical: it must NOT appear in the URL params, or it would be logged
|
|
190
|
+
by upstream proxies / web server access logs.
|
|
191
|
+
"""
|
|
192
|
+
user_token = "user_oauth_token_secret"
|
|
193
|
+
api._make_request(
|
|
194
|
+
"https://us.api.blizzard.com/profile/user/wow",
|
|
195
|
+
"us",
|
|
196
|
+
query_params={"access_token": user_token, "locale": "en_US"},
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
call = mock_get.call_args
|
|
200
|
+
# Token went to the header...
|
|
201
|
+
assert call.kwargs["headers"]["Authorization"] == f"Bearer {user_token}"
|
|
202
|
+
# ...and is NOT in the URL params.
|
|
203
|
+
assert "access_token" not in call.kwargs["params"]
|
|
204
|
+
assert call.kwargs["params"] == {"locale": "en_US"}
|
|
205
|
+
# And we did NOT trigger a client-credentials POST for a user-token call.
|
|
206
|
+
assert mock_post.call_count == 0
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def test_make_request_user_token_does_not_mutate_caller_dict(
|
|
210
|
+
api: BaseApi, mock_get
|
|
211
|
+
) -> None:
|
|
212
|
+
"""The popped access_token must not vanish from the caller's dict."""
|
|
213
|
+
caller_params = {"access_token": "user_token", "locale": "en_US"}
|
|
214
|
+
api._make_request(
|
|
215
|
+
"https://us.api.blizzard.com/profile/user/wow", "us", caller_params
|
|
216
|
+
)
|
|
217
|
+
# Caller's dict is preserved (copy() in _make_request).
|
|
218
|
+
assert caller_params == {"access_token": "user_token", "locale": "en_US"}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# ---------------------------------------------------------------------------
|
|
222
|
+
# _make_request — 401 retry semantics
|
|
223
|
+
# ---------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def test_make_request_401_refreshes_and_retries_for_client_credentials(
|
|
227
|
+
api: BaseApi, mock_get, mock_post
|
|
228
|
+
) -> None:
|
|
229
|
+
"""A 401 on a client-credentials call triggers one refresh + retry."""
|
|
230
|
+
prime_token(api, token="stale_token")
|
|
231
|
+
|
|
232
|
+
stale_response = mock_get.return_value
|
|
233
|
+
stale_response.status_code = 401
|
|
234
|
+
|
|
235
|
+
fresh_response = type(stale_response)()
|
|
236
|
+
fresh_response.status_code = 200
|
|
237
|
+
fresh_response.json = lambda: {"ok": True}
|
|
238
|
+
|
|
239
|
+
mock_get.side_effect = [stale_response, fresh_response]
|
|
240
|
+
|
|
241
|
+
# Have the refresh POST return a NEW token so we can assert the retry
|
|
242
|
+
# used it.
|
|
243
|
+
mock_post.return_value.json.return_value = {
|
|
244
|
+
"access_token": "fresh_token",
|
|
245
|
+
"token_type": "bearer",
|
|
246
|
+
"expires_in": 86400,
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
result = api._make_request("https://us.api.blizzard.com/data/wow/realm/index", "us")
|
|
250
|
+
|
|
251
|
+
assert result == {"ok": True}
|
|
252
|
+
assert mock_get.call_count == 2
|
|
253
|
+
assert mock_post.call_count == 1
|
|
254
|
+
# Retry must use the freshly-fetched token.
|
|
255
|
+
retry_headers = mock_get.call_args_list[1].kwargs["headers"]
|
|
256
|
+
assert retry_headers["Authorization"] == "Bearer fresh_token"
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def test_make_request_401_does_not_retry_for_user_token(
|
|
260
|
+
api: BaseApi, mock_get, mock_post
|
|
261
|
+
) -> None:
|
|
262
|
+
"""User-supplied tokens must NOT trigger an auto-refresh on 401."""
|
|
263
|
+
mock_get.return_value.status_code = 401
|
|
264
|
+
|
|
265
|
+
with pytest.raises(Exception): # raise_for_status -> HTTPError
|
|
266
|
+
# raise_for_status is a MagicMock — make it raise like requests does.
|
|
267
|
+
mock_get.return_value.raise_for_status.side_effect = __import__(
|
|
268
|
+
"requests"
|
|
269
|
+
).exceptions.HTTPError("401")
|
|
270
|
+
api._make_request(
|
|
271
|
+
"https://us.api.blizzard.com/profile/user/wow",
|
|
272
|
+
"us",
|
|
273
|
+
query_params={"access_token": "expired_user_token"},
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
# Exactly one GET, no token refresh POST.
|
|
277
|
+
assert mock_get.call_count == 1
|
|
278
|
+
assert mock_post.call_count == 0
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
# ---------------------------------------------------------------------------
|
|
282
|
+
# get_resource / get_oauth_resource integration
|
|
283
|
+
# ---------------------------------------------------------------------------
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def test_get_resource_end_to_end(api: BaseApi, mock_get, mock_post) -> None:
|
|
287
|
+
"""get_resource builds API URL, fetches token, and issues GET."""
|
|
288
|
+
mock_get.return_value.json.return_value = {"realms": []}
|
|
289
|
+
|
|
290
|
+
result = api.get_resource(
|
|
291
|
+
"/data/wow/realm/index",
|
|
292
|
+
"eu",
|
|
293
|
+
query_params={"locale": "en_GB"},
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
assert result == {"realms": []}
|
|
297
|
+
# Token POST happened once (lazy fetch).
|
|
298
|
+
assert mock_post.call_count == 1
|
|
299
|
+
# GET hit the EU API host.
|
|
300
|
+
assert (
|
|
301
|
+
mock_get.call_args.args[0] == "https://eu.api.blizzard.com/data/wow/realm/index"
|
|
302
|
+
)
|
|
303
|
+
assert mock_get.call_args.kwargs["params"] == {"locale": "en_GB"}
|
|
304
|
+
assert (
|
|
305
|
+
mock_get.call_args.kwargs["headers"]["Authorization"] == f"Bearer {FAKE_TOKEN}"
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def test_get_oauth_resource_end_to_end(api: BaseApi, mock_get, mock_post) -> None:
|
|
310
|
+
"""get_oauth_resource builds OAuth URL and forwards user token to header."""
|
|
311
|
+
mock_get.return_value.json.return_value = {"id": 42, "battletag": "x#1"}
|
|
312
|
+
|
|
313
|
+
result = api.get_oauth_resource(
|
|
314
|
+
"/oauth/userinfo",
|
|
315
|
+
"us",
|
|
316
|
+
query_params={"access_token": "user_token"},
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
assert result == {"id": 42, "battletag": "x#1"}
|
|
320
|
+
# No client-credentials POST when a user token is supplied.
|
|
321
|
+
assert mock_post.call_count == 0
|
|
322
|
+
# URL is the OAuth host, not the API host.
|
|
323
|
+
assert mock_get.call_args.args[0] == "https://oauth.battle.net/oauth/userinfo"
|
|
324
|
+
# Token in header, NOT in params.
|
|
325
|
+
assert "access_token" not in mock_get.call_args.kwargs["params"]
|
|
326
|
+
assert mock_get.call_args.kwargs["headers"]["Authorization"] == "Bearer user_token"
|