Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ dependencies = [
"rich>=13.0",
"PyYAML>=6.0",
"curl_cffi>=0.7",
"xclienttransaction>=1.0.1",
"xclienttransaction>=1.0.3",
"beautifulsoup4>=4.12",
]

Expand Down
39 changes: 39 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import yaml

from twitter_cli.cli import cli
from twitter_cli.exceptions import TwitterAPIError
from twitter_cli.formatter import article_to_markdown, print_tweet_table
from twitter_cli.models import Author, BookmarkFolder, Metrics, Tweet, UserProfile
from twitter_cli.serialization import tweets_to_json
Expand Down Expand Up @@ -542,6 +543,44 @@ def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str:
assert calls[0]["text"] == "Nice tweet!"


def test_cli_reply_failure_includes_upstream_response_only_in_structured_details(monkeypatch) -> None:
response_body = '{"data":{"create_tweet":{"errors":[{"message":"Rejected"}]}}}'

class FakeClient:
def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str:
raise TwitterAPIError(
0,
"Twitter API: Rejected",
upstream_status_code=200,
upstream_response=response_body,
)

monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient())
result = CliRunner().invoke(cli, ["reply", "12345", "Nice tweet!", "--json"])

assert result.exit_code == 1
payload = json.loads(result.output)
assert payload["error"]["details"] == {
"action": "reply",
"replyTo": "12345",
"upstream": {"httpStatus": 200, "responseBody": response_body},
}
assert response_body not in payload["error"]["message"]


def test_cli_post_failure_does_not_include_upstream_response(monkeypatch) -> None:
class FakeClient:
def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str:
raise TwitterAPIError(0, "Rejected", upstream_response="private response")

monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient())
result = CliRunner().invoke(cli, ["post", "hello", "--json"])

assert result.exit_code == 1
assert "upstream" not in json.loads(result.output)["error"]["details"]
assert "private response" not in result.output


def test_cli_quote_command(monkeypatch) -> None:
calls = []

Expand Down
95 changes: 95 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from __future__ import annotations

import copy
import json
from unittest.mock import MagicMock, patch

import pytest
Expand Down Expand Up @@ -265,6 +266,46 @@ def test_handles_malformed_html(self):

# ── TwitterClient._build_headers ─────────────────────────────────────────

# ClientTransaction initialization regression
class TestClientTransactionInitialization:
@patch("twitter_cli.client._update_features_from_html")
@patch("twitter_cli.client.ClientTransaction")
@patch("twitter_cli.client._gen_ct_headers", return_value={"User-Agent": "test"})
@patch("twitter_cli.client._get_cffi_session")
def test_fetches_home_route_for_ondemand_bundle(
self,
mock_session,
mock_headers,
mock_transaction,
mock_update_features,
):
home_html = (
'<script>window.__MODULES__={0:"unused",59924:"ondemand.s"};'
'window.__HASHES__={0:"unused",59924:"0cc29d94ce9e97ee"}</script>'
)
home_page = MagicMock(content=home_html.encode(), text=home_html)
ondemand_file = MagicMock(text="ondemand bundle")
mock_session.return_value.get.side_effect = [home_page, ondemand_file]

client = TwitterClient.__new__(TwitterClient)
client._client_transaction = None
client._ct_init_attempted = False
client._load_ct_cache = MagicMock(return_value=False)
client._save_ct_cache = MagicMock()

client._ensure_client_transaction()

first_request = mock_session.return_value.get.call_args_list[0]
second_request = mock_session.return_value.get.call_args_list[1]
assert first_request.args[0] == "https://x.com/home"
assert second_request.args[0] == (
"https://abs.twimg.com/responsive-web/client-web/"
"ondemand.s.0cc29d94ce9e97eea.js"
)
assert client._client_transaction is mock_transaction.return_value


# Header construction tests
class TestBuildHeaders:
@patch("twitter_cli.client._get_cffi_session")
@patch("twitter_cli.client._gen_ct_headers", return_value={})
Expand Down Expand Up @@ -1235,6 +1276,17 @@ def test_is_runtime_error(self):
err = TwitterAPIError(500, "Server error")
assert isinstance(err, RuntimeError)

def test_preserves_upstream_diagnostics_without_changing_message(self):
err = TwitterAPIError(
0,
"Failed to create tweet",
upstream_status_code=200,
upstream_response='{"errors":[{"message":"Rejected"}]}',
)
assert str(err) == "Twitter API error (HTTP 0): Failed to create tweet"
assert err.upstream_status_code == 200
assert err.upstream_response == '{"errors":[{"message":"Rejected"}]}'


class TestParseUserResult:
def test_coerces_count_fields_to_int(self):
Expand Down Expand Up @@ -1481,6 +1533,49 @@ def mock_graphql_post(operation_name, variables, features=None):
assert result == "88"
assert captured_body["media"]["media_entities"] == []

def test_create_tweet_without_id_preserves_full_response(self):
client = TwitterClient.__new__(TwitterClient)
client._request_delay = 0
response = {"data": {"create_tweet": {"tweet_results": {"result": {}}}}, "extra": [1, 2]}
client._graphql_post = lambda *args: response

with pytest.raises(TwitterAPIError, match="response missing tweet ID") as caught:
client.create_tweet("test", reply_to_id="123")

assert caught.value.upstream_status_code is None
assert json.loads(caught.value.upstream_response) == response


class TestApiRequestDiagnostics:
@patch("twitter_cli.client._get_cffi_session")
def test_http_error_preserves_full_body(self, mock_session):
response = MagicMock(status_code=403, text="x" * 600)
mock_session.return_value.get.return_value = response
client = TwitterClient.__new__(TwitterClient)
client._max_retries = 0
client._build_headers = lambda **kwargs: {}

with pytest.raises(TwitterAPIError) as caught:
client._api_request("https://x.com/test")

assert caught.value.upstream_status_code == 403
assert caught.value.upstream_response == "x" * 600
assert "x" * 501 not in str(caught.value)

@patch("twitter_cli.client._get_cffi_session")
def test_graphql_error_preserves_full_body_and_actual_http_status(self, mock_session):
body = '{"data":{"create_tweet":{"errors":[{"message":"Rejected","code":321}]}}}'
mock_session.return_value.post.return_value = MagicMock(status_code=200, text=body)
client = TwitterClient.__new__(TwitterClient)
client._max_retries = 0
client._build_headers = lambda **kwargs: {}

with pytest.raises(TwitterAPIError) as caught:
client._api_request("https://x.com/test", method="POST", body={})

assert caught.value.upstream_status_code == 200
assert caught.value.upstream_response == body


# ── fetch_search uses POST ────────────────────────────────────────────────

Expand Down
15 changes: 13 additions & 2 deletions twitter_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
from . import __version__
from .auth import get_cookies
from .cache import resolve_cached_tweet, save_tweet_cache
from .exceptions import TwitterError
from .exceptions import TwitterAPIError, TwitterError
from .client import TwitterClient
from .config import load_config
from .filter import filter_tweets
Expand Down Expand Up @@ -274,14 +274,24 @@ def _run_write_command(
progress_lines: Optional[List[str]] = None,
success_lines: Optional[List[str]] = None,
error_details: Optional[Dict[str, Any]] = None,
include_upstream_response: bool = False,
) -> Optional[WritePayload]:
mode = _structured_mode(as_json=as_json, as_yaml=as_yaml)
try:
client = _get_client(load_config())
_print_lines(progress_lines or [], mode)
payload = operation(client)
except (TwitterError, RuntimeError) as exc:
_handle_structured_runtime_error(exc, mode=mode, details=error_details)
details = error_details
if include_upstream_response and isinstance(exc, TwitterAPIError):
details = {
**(error_details or {}),
"upstream": {
"httpStatus": exc.upstream_status_code,
"responseBody": exc.upstream_response,
},
}
_handle_structured_runtime_error(exc, mode=mode, details=details)
return None

if _emit_mode_payload(payload, mode):
Expand Down Expand Up @@ -1223,6 +1233,7 @@ def operation(client: TwitterClient) -> WritePayload:
progress_lines=["💬 Replying to %s..." % tweet_id],
success_lines=["[green]✅ Reply posted![/green]"],
error_details={"action": "reply", "replyTo": tweet_id},
include_upstream_response=True,
)
if payload and not _structured_mode(as_json=as_json, as_yaml=as_yaml):
console.print("🔗 %s" % payload["url"])
Expand Down
49 changes: 39 additions & 10 deletions twitter_cli/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,9 +585,14 @@ def create_tweet(self, text, reply_to_id=None, media_ids=None):
data = self._graphql_post("CreateTweet", variables, FEATURES)
self._write_delay()
result = _deep_get(data, "data", "create_tweet", "tweet_results", "result")
if result:
return result.get("rest_id", "")
raise TwitterAPIError(0, "Failed to create tweet")
tweet_id = result.get("rest_id") if isinstance(result, dict) else None
if isinstance(tweet_id, str) and tweet_id:
return tweet_id
raise TwitterAPIError(
0,
"Failed to create tweet: response missing tweet ID",
upstream_response=json.dumps(data, ensure_ascii=False),
)

def delete_tweet(self, tweet_id):
# type: (str) -> bool
Expand Down Expand Up @@ -976,8 +981,14 @@ def _api_request(self, url, method="GET", body=None):
time.sleep(wait)
continue
if status_code >= 400:
message = "Twitter API error %d: %s" % (status_code, response.text[:500])
raise TwitterAPIError(status_code, message)
response_text = response.text
message = "Twitter API error %d: %s" % (status_code, response_text[:500])
raise TwitterAPIError(
status_code,
message,
upstream_status_code=status_code,
upstream_response=response_text,
)

payload = response.text
except TwitterAPIError:
Expand All @@ -988,7 +999,12 @@ def _api_request(self, url, method="GET", body=None):
try:
parsed = json.loads(payload)
except (json.JSONDecodeError, ValueError):
raise TwitterAPIError(0, "Twitter API returned invalid JSON")
raise TwitterAPIError(
0,
"Twitter API returned invalid JSON",
upstream_status_code=status_code,
upstream_response=payload,
)

if isinstance(parsed, dict) and parsed.get("errors"):
err_msg = parsed["errors"][0].get("message", "Unknown error")
Expand All @@ -1007,9 +1023,17 @@ def _api_request(self, url, method="GET", body=None):
# Provide user-friendly message
if err_code in (348, 349):
raise TwitterAPIError(
429, "Rate limited: %s (try again later, recommended wait: 15+ minutes)" % err_msg
429,
"Rate limited: %s (try again later, recommended wait: 15+ minutes)" % err_msg,
upstream_status_code=status_code,
upstream_response=payload,
)
raise TwitterAPIError(0, "Twitter API returned errors: %s" % err_msg)
raise TwitterAPIError(
0,
"Twitter API returned errors: %s" % err_msg,
upstream_status_code=status_code,
upstream_response=payload,
)

# GraphQL write mutations return errors in data.errors (separate from top-level)
if isinstance(parsed, dict) and "data" in parsed:
Expand All @@ -1020,7 +1044,12 @@ def _api_request(self, url, method="GET", body=None):
inner_errors = val["errors"]
if inner_errors:
inner_msg = inner_errors[0].get("message", "Unknown error")
raise TwitterAPIError(0, "Twitter API: %s" % inner_msg)
raise TwitterAPIError(
0,
"Twitter API: %s" % inner_msg,
upstream_status_code=status_code,
upstream_response=payload,
)

return parsed

Expand Down Expand Up @@ -1104,7 +1133,7 @@ def _ensure_client_transaction(self):
cffi_session = _get_cffi_session()
ct_headers = _gen_ct_headers()
home_page = cffi_session.get(
"https://x.com", headers=ct_headers, timeout=10,
"https://x.com/home", headers=ct_headers, timeout=10,
)
home_page_response = bs4.BeautifulSoup(home_page.content, "html.parser")
ondemand_url = get_ondemand_file_url(response=home_page_response)
Expand Down
11 changes: 10 additions & 1 deletion twitter_cli/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,18 @@ class InvalidInputError(TwitterError):
class TwitterAPIError(TwitterError):
"""Raised on non-OK Twitter API responses with HTTP status + message."""

def __init__(self, status_code: int, message: str):
def __init__(
self,
status_code: int,
message: str,
*,
upstream_status_code: int | None = None,
upstream_response: str | None = None,
):
self.status_code = status_code
self.message = message
self.upstream_status_code = upstream_status_code
self.upstream_response = upstream_response
# Derive error_code from HTTP status
if status_code in (401, 403):
self.error_code = "not_authenticated"
Expand Down
8 changes: 4 additions & 4 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.