Compare commits
16
Commits
v4.0.2
...
b3ed21eec2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3ed21eec2 | ||
|
|
b0a220e7a2 | ||
|
|
ae737c0bd0 | ||
|
|
d0b3fc6e18 | ||
|
|
5f66d1e1e0 | ||
|
|
8b7eac51c8 | ||
|
|
fb1387e6cc | ||
|
|
d972fdf145 | ||
|
|
753750530d | ||
|
|
f4f41abbe8 | ||
|
|
7fb3663097 | ||
|
|
530aeba667 | ||
|
|
10290fd28d | ||
|
|
b26a6a2d0a | ||
|
|
78ee9ac9da | ||
|
|
cef6886fd2 |
@@ -0,0 +1,193 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
schedule:
|
||||||
|
- cron: "0 6 * * 1"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-scan:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Build Docker image
|
||||||
|
run: |
|
||||||
|
docker build -t nvidia-stock-bot:ci . 2>&1 | tee build.log
|
||||||
|
if grep -q "Building wheel for" build.log; then
|
||||||
|
echo "::warning::A dependency was built from source — check Python/Alpine compatibility"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Smoke test (syntax check)
|
||||||
|
run: |
|
||||||
|
docker run --rm --entrypoint python nvidia-stock-bot:ci -c "
|
||||||
|
import ast, glob
|
||||||
|
ok = True
|
||||||
|
for f in glob.glob('/app/*.py'):
|
||||||
|
with open(f) as fh:
|
||||||
|
source = fh.read()
|
||||||
|
try:
|
||||||
|
ast.parse(source, filename=f)
|
||||||
|
except SyntaxError as e:
|
||||||
|
print(f'::error::Syntax error in {f}: {e}')
|
||||||
|
ok = False
|
||||||
|
if not ok:
|
||||||
|
exit(1)
|
||||||
|
print('OK: syntax is valid')
|
||||||
|
"
|
||||||
|
|
||||||
|
- name: Run unit tests
|
||||||
|
run: |
|
||||||
|
docker build --target test -t nvidia-stock-bot:test .
|
||||||
|
docker run --rm nvidia-stock-bot:test pytest -v
|
||||||
|
|
||||||
|
- name: Check deprecation warnings
|
||||||
|
run: |
|
||||||
|
docker run --rm --entrypoint python \
|
||||||
|
-e DISCORD_WEBHOOK_URL="https://discord.com/api/webhooks/123456789012345678/abcdef" \
|
||||||
|
-e PRODUCT_NAMES="RTX 5090 Founders Edition" \
|
||||||
|
-e TEST_MODE=True \
|
||||||
|
nvidia-stock-bot:ci -W error::DeprecationWarning -c "import main" 2>&1 | tee deprecation.log || true
|
||||||
|
if grep -qi "deprecat" deprecation.log; then
|
||||||
|
echo "::warning::Deprecation warning detected, check logs"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Scan with Trivy (critical - blocking)
|
||||||
|
run: |
|
||||||
|
docker run --rm \
|
||||||
|
-e DOCKER_HOST=tcp://dockerhost:2375 \
|
||||||
|
--add-host=dockerhost:host-gateway \
|
||||||
|
aquasec/trivy:0.74.0 image --exit-code 1 --severity CRITICAL nvidia-stock-bot:ci
|
||||||
|
|
||||||
|
- name: Scan with Trivy (high - informative)
|
||||||
|
run: |
|
||||||
|
docker run --rm \
|
||||||
|
-e DOCKER_HOST=tcp://dockerhost:2375 \
|
||||||
|
--add-host=dockerhost:host-gateway \
|
||||||
|
aquasec/trivy:0.74.0 image --exit-code 0 --severity HIGH nvidia-stock-bot:ci
|
||||||
|
|
||||||
|
- name: Publish tagged image
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
run: |
|
||||||
|
BEFORE="${{ github.event.before }}"
|
||||||
|
if [ -n "$BEFORE" ] && [ "$BEFORE" != "0000000000000000000000000000000000000000" ] && git cat-file -e "$BEFORE" 2>/dev/null; then
|
||||||
|
BASE_REF="$BEFORE"
|
||||||
|
else
|
||||||
|
BASE_REF="HEAD~1"
|
||||||
|
fi
|
||||||
|
CHANGED=$(git diff --name-only "$BASE_REF" "${{ github.sha }}")
|
||||||
|
echo "Changed files:"
|
||||||
|
echo "$CHANGED"
|
||||||
|
|
||||||
|
if ! echo "$CHANGED" | grep -qE '^(Dockerfile|VERSION)$|^app/'; then
|
||||||
|
echo "No container-relevant file changed, skipping publish."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if echo "$CHANGED" | grep -qE '^VERSION$'; then
|
||||||
|
echo "VERSION was manually edited in this push, using it as-is."
|
||||||
|
else
|
||||||
|
echo "VERSION untouched but container files changed, auto-bumping the build number (Z)."
|
||||||
|
OLD_VERSION=$(tr -d '[:space:]' < VERSION)
|
||||||
|
IFS='.' read -r MAJOR MINOR PATCH <<< "$OLD_VERSION"
|
||||||
|
NEW_VERSION="${MAJOR}.${MINOR}.$((PATCH + 1))"
|
||||||
|
echo "$NEW_VERSION" > VERSION
|
||||||
|
|
||||||
|
git config user.name "nvidia-stock-bot-ci"
|
||||||
|
git config user.email "[email protected]"
|
||||||
|
git add VERSION
|
||||||
|
git commit -m "Bump build version to $NEW_VERSION [skip ci]"
|
||||||
|
|
||||||
|
# Belt and suspenders: actions/checkout can leave its own ephemeral
|
||||||
|
# credential injected as an extraheader, which would silently override
|
||||||
|
# the URL-embedded token below. persist-credentials:false on checkout
|
||||||
|
# should already prevent this, but strip it here too just in case.
|
||||||
|
git config --unset-all http.https://git.djeex.fr/.extraheader || true
|
||||||
|
|
||||||
|
git push "https://Djeex:${{ secrets.CI_PUSH_TOKEN }}@git.djeex.fr/Djeex/nvidia-stock-bot.git" HEAD:main
|
||||||
|
fi
|
||||||
|
|
||||||
|
VERSION=$(tr -d '[:space:]' < VERSION)
|
||||||
|
IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION"
|
||||||
|
MINOR_TAG="${MAJOR}.${MINOR}"
|
||||||
|
|
||||||
|
IMAGE=git.djeex.fr/djeex/nvidia-stock-bot
|
||||||
|
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.djeex.fr -u Djeex --password-stdin
|
||||||
|
|
||||||
|
# Retag the already-built, already-scanned image — never rebuild for publish,
|
||||||
|
# so what ships is byte-for-byte what Trivy just scanned.
|
||||||
|
docker tag nvidia-stock-bot:ci "$IMAGE:latest"
|
||||||
|
docker tag nvidia-stock-bot:ci "$IMAGE:$MINOR_TAG"
|
||||||
|
docker tag nvidia-stock-bot:ci "$IMAGE:$VERSION"
|
||||||
|
docker push "$IMAGE:latest"
|
||||||
|
docker push "$IMAGE:$MINOR_TAG"
|
||||||
|
docker push "$IMAGE:$VERSION"
|
||||||
|
|
||||||
|
TRIGGER_MSG=$(git log -1 --format=%s "${{ github.sha }}")
|
||||||
|
PR_NUM=$(echo "$TRIGGER_MSG" | grep -oE '#[0-9]+' | head -1 | tr -d '#' || true)
|
||||||
|
|
||||||
|
CATEGORY="🔧 Maintenance"
|
||||||
|
CHANGE_TITLE="$TRIGGER_MSG"
|
||||||
|
|
||||||
|
if [ -n "$PR_NUM" ]; then
|
||||||
|
PR_JSON=$(curl -s -H "Authorization: token ${{ secrets.CI_PUSH_TOKEN }}" \
|
||||||
|
"https://git.djeex.fr/api/v1/repos/Djeex/nvidia-stock-bot/pulls/$PR_NUM")
|
||||||
|
PR_TITLE=$(echo "$PR_JSON" | jq -r '.title // empty' 2>/dev/null || true)
|
||||||
|
LABELS=$(echo "$PR_JSON" | jq -r '.labels[]?.name' 2>/dev/null || true)
|
||||||
|
|
||||||
|
if [ -n "$PR_TITLE" ]; then
|
||||||
|
CHANGE_TITLE="$PR_TITLE"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if echo "$LABELS" | grep -qx 'bug'; then
|
||||||
|
CATEGORY="⚠️ Hotfix"
|
||||||
|
elif echo "$LABELS" | grep -qx 'major'; then
|
||||||
|
CATEGORY="💥 Breaking change"
|
||||||
|
elif echo "$LABELS" | grep -qx 'minor'; then
|
||||||
|
CATEGORY="✨ Update"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
REPO_URL="https://git.djeex.fr/Djeex/nvidia-stock-bot"
|
||||||
|
COMMIT_LIST=$(git log --no-merges --format="- [%h](${REPO_URL}/commit/%H) %s" "$BASE_REF".."${{ github.sha }}")
|
||||||
|
|
||||||
|
SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||||
|
SOURCE_LINE="[${SHORT_SHA}](${REPO_URL}/commit/${{ github.sha }})"
|
||||||
|
if [ -n "$PR_NUM" ]; then
|
||||||
|
SOURCE_LINE="[#${PR_NUM}](${REPO_URL}/pulls/${PR_NUM}) · ${SOURCE_LINE}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
BODY=$(cat <<EOF
|
||||||
|
## Changelog
|
||||||
|
---
|
||||||
|
|
||||||
|
### ${CATEGORY}
|
||||||
|
---
|
||||||
|
${CHANGE_TITLE}
|
||||||
|
|
||||||
|
**Source:** ${SOURCE_LINE}
|
||||||
|
**Image:** \`${IMAGE}:${VERSION}\`
|
||||||
|
|
||||||
|
**Commits:**
|
||||||
|
${COMMIT_LIST}
|
||||||
|
EOF
|
||||||
|
)
|
||||||
|
|
||||||
|
JSON_PAYLOAD=$(jq -n \
|
||||||
|
--arg tag "$VERSION" \
|
||||||
|
--arg name "$VERSION" \
|
||||||
|
--arg body "$BODY" \
|
||||||
|
'{tag_name: $tag, name: $name, target_commitish: "main", body: $body}')
|
||||||
|
|
||||||
|
curl -s -o /dev/null -w "Release API response: %{http_code}\n" -X POST \
|
||||||
|
-H "Authorization: token ${{ secrets.CI_PUSH_TOKEN }}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "$JSON_PAYLOAD" \
|
||||||
|
"https://git.djeex.fr/api/v1/repos/Djeex/nvidia-stock-bot/releases"
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
.venv
|
||||||
|
__pycache__/
|
||||||
|
.coverage
|
||||||
|
.pytest_cache/
|
||||||
+17
-1
@@ -1,11 +1,27 @@
|
|||||||
FROM python:3.13-alpine
|
FROM python:3.14.7-alpine AS base
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates
|
RUN apk add --no-cache ca-certificates
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY VERSION /VERSION
|
||||||
COPY /app/ /app/
|
COPY /app/ /app/
|
||||||
|
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
FROM base AS test
|
||||||
|
|
||||||
|
RUN pip install --no-cache-dir pytest==9.1.1
|
||||||
|
|
||||||
|
COPY pytest.ini /app/pytest.ini
|
||||||
|
COPY /tests/ /app/tests/
|
||||||
|
|
||||||
|
CMD ["pytest", "-v"]
|
||||||
|
|
||||||
|
FROM base
|
||||||
|
|
||||||
|
RUN addgroup -g 911 nvbot && adduser -D -u 911 -G nvbot nvbot
|
||||||
|
|
||||||
|
USER nvbot
|
||||||
|
|
||||||
CMD ["python", "main.py"]
|
CMD ["python", "main.py"]
|
||||||
+7
-2
@@ -4,7 +4,9 @@ import logging
|
|||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
VERSION = "4.0.2"
|
# Read version from VERSION file
|
||||||
|
with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), "VERSION"), "r", encoding="utf-8") as f:
|
||||||
|
VERSION = f.read().strip()
|
||||||
|
|
||||||
# Logger setup
|
# Logger setup
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@@ -89,7 +91,10 @@ HEADERS = {
|
|||||||
"Sec-Fetch-Dest": "empty",
|
"Sec-Fetch-Dest": "empty",
|
||||||
"Sec-Fetch-Mode": "cors",
|
"Sec-Fetch-Mode": "cors",
|
||||||
"Sec-Ch-Ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not.A/Brand\";v=\"24\"",
|
"Sec-Ch-Ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not.A/Brand\";v=\"24\"",
|
||||||
"Sec-Ch-Ua-Platform": "\"macOS\""
|
"Sec-Ch-Ua-Platform": "\"macOS\"",
|
||||||
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||||
|
"Pragma": "no-cache",
|
||||||
|
"Expires": "0"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Load country setting and localization config
|
# Load country setting and localization config
|
||||||
|
|||||||
+9
-3
@@ -1,5 +1,6 @@
|
|||||||
import requests
|
import requests
|
||||||
import logging
|
import logging
|
||||||
|
import time
|
||||||
from env_config import HEADERS, PRODUCT_NAMES, API_URL_SKU, API_URL_STOCK, PRODUCT_URL
|
from env_config import HEADERS, PRODUCT_NAMES, API_URL_SKU, API_URL_STOCK, PRODUCT_URL
|
||||||
from notifier import send_discord_notification, send_out_of_stock_notification, send_sku_change_notification
|
from notifier import send_discord_notification, send_out_of_stock_notification, send_sku_change_notification
|
||||||
from requests.adapters import HTTPAdapter, Retry
|
from requests.adapters import HTTPAdapter, Retry
|
||||||
@@ -8,6 +9,7 @@ from requests.adapters import HTTPAdapter, Retry
|
|||||||
session = requests.Session()
|
session = requests.Session()
|
||||||
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
|
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
|
||||||
session.mount('https://', HTTPAdapter(max_retries=retries))
|
session.mount('https://', HTTPAdapter(max_retries=retries))
|
||||||
|
session.headers.update(HEADERS)
|
||||||
|
|
||||||
# Keeping memory of last run
|
# Keeping memory of last run
|
||||||
last_sku_dict = {}
|
last_sku_dict = {}
|
||||||
@@ -20,7 +22,10 @@ def check_rtx_50_founders():
|
|||||||
|
|
||||||
# Fetching nvidia API data
|
# Fetching nvidia API data
|
||||||
try:
|
try:
|
||||||
response = session.get(API_URL_SKU, headers=HEADERS, timeout=10)
|
cache_buster = int(time.time() * 1000)
|
||||||
|
sku_url = f"{API_URL_SKU}&_t={cache_buster}"
|
||||||
|
|
||||||
|
response = session.get(sku_url, timeout=10)
|
||||||
logging.info(f"SKU API response: {response.status_code}")
|
logging.info(f"SKU API response: {response.status_code}")
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
data = response.json()
|
data = response.json()
|
||||||
@@ -57,11 +62,12 @@ def check_rtx_50_founders():
|
|||||||
first_run_dict[product_name] = False
|
first_run_dict[product_name] = False
|
||||||
|
|
||||||
# Check product availability in API_URL_STOCK for each SKU
|
# Check product availability in API_URL_STOCK for each SKU
|
||||||
api_stock_url = API_URL_STOCK + product_sku
|
cache_buster = int(time.time() * 1000)
|
||||||
|
api_stock_url = f"{API_URL_STOCK}{product_sku}&_t={cache_buster}"
|
||||||
logging.info(f"[{product_name}] Checking stock: {api_stock_url}")
|
logging.info(f"[{product_name}] Checking stock: {api_stock_url}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = session.get(api_stock_url, headers=HEADERS, timeout=10)
|
response = session.get(api_stock_url, timeout=10)
|
||||||
logging.info(f"[{product_name}] Stock API response: {response.status_code}")
|
logging.info(f"[{product_name}] Stock API response: {response.status_code}")
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
stock_data = response.json()
|
stock_data = response.json()
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
requests
|
requests==2.34.2
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
[pytest]
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||||
|
"extends": ["config:recommended"],
|
||||||
|
"timezone": "Europe/Paris",
|
||||||
|
"labels": ["bot"],
|
||||||
|
"vulnerabilityAlerts": {
|
||||||
|
"addLabels": ["bug"]
|
||||||
|
},
|
||||||
|
"packageRules": [
|
||||||
|
{
|
||||||
|
"matchManagers": ["pip_requirements"],
|
||||||
|
"matchUpdateTypes": ["patch", "minor"],
|
||||||
|
"automerge": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"matchManagers": ["dockerfile"],
|
||||||
|
"matchUpdateTypes": ["patch"],
|
||||||
|
"automerge": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"matchUpdateTypes": ["major"],
|
||||||
|
"addLabels": ["major"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"matchUpdateTypes": ["minor"],
|
||||||
|
"addLabels": ["minor"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
_REPO_ROOT = os.path.dirname(_TESTS_DIR)
|
||||||
|
|
||||||
|
# app/*.py open their JSON config files with plain relative paths, so the
|
||||||
|
# process cwd must be the directory the app modules live in — matches how
|
||||||
|
# the Dockerfile runs them (WORKDIR /app).
|
||||||
|
_APP_DIR = os.path.join(_REPO_ROOT, "app")
|
||||||
|
if not os.path.isfile(os.path.join(_APP_DIR, "gpu_checker.py")):
|
||||||
|
_APP_DIR = _REPO_ROOT # container test stage: code copied flat next to tests/
|
||||||
|
|
||||||
|
if _APP_DIR not in sys.path:
|
||||||
|
sys.path.insert(0, _APP_DIR)
|
||||||
|
|
||||||
|
os.chdir(_APP_DIR)
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import importlib
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
MODULE_NAME = "env_config"
|
||||||
|
|
||||||
|
VALID_WEBHOOK = "https://discord.com/api/webhooks/123456789012345678/abcdef"
|
||||||
|
|
||||||
|
ENV_KEYS = [
|
||||||
|
"DISCORD_WEBHOOK_URL",
|
||||||
|
"DISCORD_SERVER_NAME",
|
||||||
|
"DISCORD_ROLES",
|
||||||
|
"COUNTRY",
|
||||||
|
"REFRESH_TIME",
|
||||||
|
"TEST_MODE",
|
||||||
|
"PRODUCT_NAMES",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _reload_env_config(monkeypatch, env):
|
||||||
|
for key in ENV_KEYS:
|
||||||
|
monkeypatch.delenv(key, raising=False)
|
||||||
|
for key, value in env.items():
|
||||||
|
monkeypatch.setenv(key, value)
|
||||||
|
sys.modules.pop(MODULE_NAME, None)
|
||||||
|
return importlib.import_module(MODULE_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_webhook_exits(monkeypatch):
|
||||||
|
with pytest.raises(SystemExit):
|
||||||
|
_reload_env_config(monkeypatch, {"PRODUCT_NAMES": "RTX 5090"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_product_names_exits(monkeypatch):
|
||||||
|
with pytest.raises(SystemExit):
|
||||||
|
_reload_env_config(monkeypatch, {"DISCORD_WEBHOOK_URL": VALID_WEBHOOK})
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_role_map_is_everyone(monkeypatch):
|
||||||
|
cfg = _reload_env_config(monkeypatch, {
|
||||||
|
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||||
|
"PRODUCT_NAMES": "RTX 5090, RTX 5080",
|
||||||
|
})
|
||||||
|
assert cfg.DISCORD_ROLE_MAP == {"RTX 5090": "@everyone", "RTX 5080": "@everyone"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_role_count_mismatch_exits(monkeypatch):
|
||||||
|
with pytest.raises(SystemExit):
|
||||||
|
_reload_env_config(monkeypatch, {
|
||||||
|
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||||
|
"PRODUCT_NAMES": "RTX 5090, RTX 5080",
|
||||||
|
"DISCORD_ROLES": "<@&123456789012345678>",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_role_format_exits(monkeypatch):
|
||||||
|
with pytest.raises(SystemExit):
|
||||||
|
_reload_env_config(monkeypatch, {
|
||||||
|
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||||
|
"PRODUCT_NAMES": "RTX 5090",
|
||||||
|
"DISCORD_ROLES": "not-a-role",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def test_valid_role_format_accepted(monkeypatch):
|
||||||
|
cfg = _reload_env_config(monkeypatch, {
|
||||||
|
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||||
|
"PRODUCT_NAMES": "RTX 5090",
|
||||||
|
"DISCORD_ROLES": "<@&123456789012345678>",
|
||||||
|
})
|
||||||
|
assert cfg.DISCORD_ROLE_MAP["RTX 5090"] == "<@&123456789012345678>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_country_falls_back_to_us(monkeypatch):
|
||||||
|
cfg = _reload_env_config(monkeypatch, {
|
||||||
|
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||||
|
"PRODUCT_NAMES": "RTX 5090",
|
||||||
|
"COUNTRY": "ZZ",
|
||||||
|
})
|
||||||
|
assert cfg.currency == "$"
|
||||||
|
|
||||||
|
|
||||||
|
def test_known_country_currency(monkeypatch):
|
||||||
|
cfg = _reload_env_config(monkeypatch, {
|
||||||
|
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||||
|
"PRODUCT_NAMES": "RTX 5090",
|
||||||
|
"COUNTRY": "GB",
|
||||||
|
})
|
||||||
|
assert cfg.currency == "£"
|
||||||
|
|
||||||
|
|
||||||
|
def test_refresh_time_invalid_exits(monkeypatch):
|
||||||
|
with pytest.raises(SystemExit):
|
||||||
|
_reload_env_config(monkeypatch, {
|
||||||
|
"DISCORD_WEBHOOK_URL": VALID_WEBHOOK,
|
||||||
|
"PRODUCT_NAMES": "RTX 5090",
|
||||||
|
"REFRESH_TIME": "not-a-number",
|
||||||
|
})
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import importlib
|
||||||
|
import sys
|
||||||
|
|
||||||
|
VALID_WEBHOOK = "https://discord.com/api/webhooks/123456789012345678/abcdef"
|
||||||
|
PRODUCT_NAME = "RTX 5090 Founders Edition"
|
||||||
|
|
||||||
|
SKU_PAYLOAD = {
|
||||||
|
"searchedProducts": {
|
||||||
|
"productDetails": [
|
||||||
|
{"gpu": PRODUCT_NAME, "productSKU": "SKU-1", "productUPC": "ABC123"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResponse:
|
||||||
|
def __init__(self, payload, status_code=200):
|
||||||
|
self._payload = payload
|
||||||
|
self.status_code = status_code
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
if self.status_code >= 400:
|
||||||
|
raise Exception(f"HTTP {self.status_code}")
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._payload
|
||||||
|
|
||||||
|
|
||||||
|
def _stock_payload(in_stock, price="1999"):
|
||||||
|
return {
|
||||||
|
"listMap": [
|
||||||
|
{"fe_sku": "ABC123", "is_active": "true" if in_stock else "false", "price": price}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _import_gpu_checker(monkeypatch):
|
||||||
|
monkeypatch.setenv("DISCORD_WEBHOOK_URL", VALID_WEBHOOK)
|
||||||
|
monkeypatch.setenv("PRODUCT_NAMES", PRODUCT_NAME)
|
||||||
|
monkeypatch.setenv("TEST_MODE", "True")
|
||||||
|
monkeypatch.delenv("DISCORD_ROLES", raising=False)
|
||||||
|
for mod in ("env_config", "notifier", "gpu_checker"):
|
||||||
|
sys.modules.pop(mod, None)
|
||||||
|
return importlib.import_module("gpu_checker")
|
||||||
|
|
||||||
|
|
||||||
|
def _queue_responses(monkeypatch, checker, *payloads):
|
||||||
|
responses = [FakeResponse(p) for p in payloads]
|
||||||
|
monkeypatch.setattr(checker.session, "get", lambda *a, **k: responses.pop(0))
|
||||||
|
|
||||||
|
|
||||||
|
def test_transition_to_in_stock_sends_notification(monkeypatch):
|
||||||
|
checker = _import_gpu_checker(monkeypatch)
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(checker, "send_discord_notification", lambda *a: calls.append(("in_stock", a)))
|
||||||
|
monkeypatch.setattr(checker, "send_out_of_stock_notification", lambda *a: calls.append(("out_of_stock", a)))
|
||||||
|
monkeypatch.setattr(checker, "send_sku_change_notification", lambda *a: calls.append(("sku_change", a)))
|
||||||
|
|
||||||
|
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(True))
|
||||||
|
checker.check_rtx_50_founders()
|
||||||
|
|
||||||
|
assert len(calls) == 1
|
||||||
|
assert calls[0][0] == "in_stock"
|
||||||
|
assert calls[0][1][0] == PRODUCT_NAME
|
||||||
|
|
||||||
|
|
||||||
|
def test_transition_to_out_of_stock_sends_notification(monkeypatch):
|
||||||
|
checker = _import_gpu_checker(monkeypatch)
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(checker, "send_discord_notification", lambda *a: calls.append(("in_stock", a)))
|
||||||
|
monkeypatch.setattr(checker, "send_out_of_stock_notification", lambda *a: calls.append(("out_of_stock", a)))
|
||||||
|
monkeypatch.setattr(checker, "send_sku_change_notification", lambda *a: calls.append(("sku_change", a)))
|
||||||
|
|
||||||
|
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(True))
|
||||||
|
checker.check_rtx_50_founders()
|
||||||
|
|
||||||
|
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(False))
|
||||||
|
checker.check_rtx_50_founders()
|
||||||
|
|
||||||
|
assert calls[-1][0] == "out_of_stock"
|
||||||
|
assert calls[-1][1][0] == PRODUCT_NAME
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_duplicate_notification_while_still_in_stock(monkeypatch):
|
||||||
|
checker = _import_gpu_checker(monkeypatch)
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(checker, "send_discord_notification", lambda *a: calls.append(("in_stock", a)))
|
||||||
|
monkeypatch.setattr(checker, "send_out_of_stock_notification", lambda *a: calls.append(("out_of_stock", a)))
|
||||||
|
monkeypatch.setattr(checker, "send_sku_change_notification", lambda *a: calls.append(("sku_change", a)))
|
||||||
|
|
||||||
|
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(True))
|
||||||
|
checker.check_rtx_50_founders()
|
||||||
|
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(True))
|
||||||
|
checker.check_rtx_50_founders()
|
||||||
|
|
||||||
|
assert len(calls) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_sku_change_triggers_notification_after_first_run(monkeypatch):
|
||||||
|
checker = _import_gpu_checker(monkeypatch)
|
||||||
|
sku_change_calls = []
|
||||||
|
monkeypatch.setattr(checker, "send_discord_notification", lambda *a: None)
|
||||||
|
monkeypatch.setattr(checker, "send_out_of_stock_notification", lambda *a: None)
|
||||||
|
monkeypatch.setattr(checker, "send_sku_change_notification", lambda *a: sku_change_calls.append(a))
|
||||||
|
|
||||||
|
_queue_responses(monkeypatch, checker, SKU_PAYLOAD, _stock_payload(False))
|
||||||
|
checker.check_rtx_50_founders()
|
||||||
|
assert sku_change_calls == [] # first run must never fire a "change" notification
|
||||||
|
|
||||||
|
changed_payload = {
|
||||||
|
"searchedProducts": {
|
||||||
|
"productDetails": [
|
||||||
|
{"gpu": PRODUCT_NAME, "productSKU": "SKU-2", "productUPC": "ABC123"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_queue_responses(monkeypatch, checker, changed_payload, _stock_payload(False))
|
||||||
|
checker.check_rtx_50_founders()
|
||||||
|
|
||||||
|
assert len(sku_change_calls) == 1
|
||||||
|
assert sku_change_calls[0][1] == "SKU-1"
|
||||||
|
assert sku_change_calls[0][2] == "SKU-2"
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_product_in_api_is_skipped_gracefully(monkeypatch):
|
||||||
|
checker = _import_gpu_checker(monkeypatch)
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(checker, "send_discord_notification", lambda *a: calls.append(a))
|
||||||
|
|
||||||
|
empty_payload = {"searchedProducts": {"productDetails": []}}
|
||||||
|
monkeypatch.setattr(checker.session, "get", lambda *a, **k: FakeResponse(empty_payload))
|
||||||
|
|
||||||
|
checker.check_rtx_50_founders() # must not raise, just log a warning and skip
|
||||||
|
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_sku_api_error_is_handled_without_raising(monkeypatch):
|
||||||
|
checker = _import_gpu_checker(monkeypatch)
|
||||||
|
|
||||||
|
def raise_error(*a, **k):
|
||||||
|
raise checker.requests.exceptions.ConnectionError("boom")
|
||||||
|
|
||||||
|
monkeypatch.setattr(checker.session, "get", raise_error)
|
||||||
|
|
||||||
|
checker.check_rtx_50_founders() # must not propagate the network error
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import importlib
|
||||||
|
import sys
|
||||||
|
|
||||||
|
VALID_WEBHOOK = "https://discord.com/api/webhooks/123456789012345678/abcdef"
|
||||||
|
|
||||||
|
|
||||||
|
def _import_notifier(monkeypatch, test_mode="False", discord_roles=None):
|
||||||
|
monkeypatch.setenv("DISCORD_WEBHOOK_URL", VALID_WEBHOOK)
|
||||||
|
monkeypatch.setenv("PRODUCT_NAMES", "RTX 5090 Founders Edition")
|
||||||
|
monkeypatch.setenv("TEST_MODE", test_mode)
|
||||||
|
if discord_roles is not None:
|
||||||
|
monkeypatch.setenv("DISCORD_ROLES", discord_roles)
|
||||||
|
else:
|
||||||
|
monkeypatch.delenv("DISCORD_ROLES", raising=False)
|
||||||
|
for mod in ("env_config", "notifier"):
|
||||||
|
sys.modules.pop(mod, None)
|
||||||
|
return importlib.import_module("notifier")
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResponse:
|
||||||
|
def __init__(self, status_code=204, text=""):
|
||||||
|
self.status_code = status_code
|
||||||
|
self.text = text
|
||||||
|
|
||||||
|
|
||||||
|
def test_test_mode_skips_network_call(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="True")
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: calls.append((a, k)))
|
||||||
|
|
||||||
|
notifier.send_discord_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||||
|
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_in_stock_notification_posts_expected_payload(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
def fake_post(url, json=None, **kwargs):
|
||||||
|
captured["url"] = url
|
||||||
|
captured["json"] = json
|
||||||
|
return FakeResponse()
|
||||||
|
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", fake_post)
|
||||||
|
|
||||||
|
notifier.send_discord_notification("RTX 5090 Founders Edition", "https://example.com/buy", "1999")
|
||||||
|
|
||||||
|
assert captured["url"] == notifier.DISCORD_WEBHOOK_URL
|
||||||
|
assert captured["json"]["content"] == "@everyone"
|
||||||
|
embed = captured["json"]["embeds"][0]
|
||||||
|
assert "RTX 5090 Founders Edition" in embed["title"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_discord_notification_survives_http_error(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: FakeResponse(status_code=500, text="boom"))
|
||||||
|
|
||||||
|
notifier.send_discord_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||||
|
|
||||||
|
|
||||||
|
def test_discord_notification_survives_connection_error(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||||
|
|
||||||
|
def raise_error(*a, **k):
|
||||||
|
raise notifier.requests.exceptions.ConnectionError("boom")
|
||||||
|
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", raise_error)
|
||||||
|
|
||||||
|
# Should not raise even though the request itself blew up (network down, DNS, etc.)
|
||||||
|
notifier.send_discord_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||||
|
|
||||||
|
|
||||||
|
def test_out_of_stock_test_mode_skips_network_call(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="True")
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: calls.append((a, k)))
|
||||||
|
|
||||||
|
notifier.send_out_of_stock_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||||
|
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_out_of_stock_notification_posts_on_success(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
def fake_post(url, json=None, **kwargs):
|
||||||
|
captured["json"] = json
|
||||||
|
return FakeResponse(status_code=204)
|
||||||
|
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", fake_post)
|
||||||
|
|
||||||
|
notifier.send_out_of_stock_notification("RTX 5090 Founders Edition", "https://example.com/buy", "1999")
|
||||||
|
|
||||||
|
assert captured["json"]["embeds"][0]["url"] == "https://example.com/buy"
|
||||||
|
|
||||||
|
|
||||||
|
def test_out_of_stock_notification_survives_http_error(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: FakeResponse(status_code=500, text="boom"))
|
||||||
|
|
||||||
|
# Should not raise even though the webhook call "fails"
|
||||||
|
notifier.send_out_of_stock_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||||
|
|
||||||
|
|
||||||
|
def test_out_of_stock_notification_survives_connection_error(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||||
|
|
||||||
|
def raise_error(*a, **k):
|
||||||
|
raise notifier.requests.exceptions.ConnectionError("boom")
|
||||||
|
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", raise_error)
|
||||||
|
|
||||||
|
notifier.send_out_of_stock_notification("RTX 5090 Founders Edition", "https://example.com", "1999")
|
||||||
|
|
||||||
|
|
||||||
|
def test_sku_change_test_mode_skips_network_call(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="True")
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: calls.append((a, k)))
|
||||||
|
|
||||||
|
notifier.send_sku_change_notification("RTX 5090 Founders Edition", "old-sku", "new-sku", "https://example.com")
|
||||||
|
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_sku_change_notification_survives_http_error(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", lambda *a, **k: FakeResponse(status_code=500, text="boom"))
|
||||||
|
|
||||||
|
notifier.send_sku_change_notification("RTX 5090 Founders Edition", "old-sku", "new-sku", "https://example.com")
|
||||||
|
|
||||||
|
|
||||||
|
def test_sku_change_notification_survives_connection_error(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False")
|
||||||
|
|
||||||
|
def raise_error(*a, **k):
|
||||||
|
raise notifier.requests.exceptions.ConnectionError("boom")
|
||||||
|
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", raise_error)
|
||||||
|
|
||||||
|
notifier.send_sku_change_notification("RTX 5090 Founders Edition", "old-sku", "new-sku", "https://example.com")
|
||||||
|
|
||||||
|
|
||||||
|
def test_sku_change_notification_mentions_role_and_skus(monkeypatch):
|
||||||
|
notifier = _import_notifier(monkeypatch, test_mode="False", discord_roles="<@&123456789012345678>")
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
def fake_post(url, json=None, **kwargs):
|
||||||
|
captured["json"] = json
|
||||||
|
return FakeResponse()
|
||||||
|
|
||||||
|
monkeypatch.setattr(notifier.requests, "post", fake_post)
|
||||||
|
|
||||||
|
notifier.send_sku_change_notification(
|
||||||
|
"RTX 5090 Founders Edition", "old-sku-123", "new-sku-456", "https://example.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "<@&123456789012345678>" in captured["json"]["content"]
|
||||||
|
description = captured["json"]["embeds"][0]["description"]
|
||||||
|
assert "old-sku-123" in description
|
||||||
|
assert "new-sku-456" in description
|
||||||
Reference in New Issue
Block a user