| 1 | """Tests for xurl_x module.""" |
| 2 | |
| 3 | import json |
| 4 | import tempfile |
| 5 | import unittest |
| 6 | from pathlib import Path |
| 7 | from unittest import mock |
| 8 | |
| 9 | from lib import xurl_x |
| 10 | |
| 11 | # --------------------------------------------------------------------------- |
| 12 | # Helpers |
| 13 | # --------------------------------------------------------------------------- |
| 14 | |
| 15 | |
| 16 | def _make_api_response(tweets=None, users=None): |
| 17 | """Build a minimal X API v2 search/recent response.""" |
| 18 | tweets = tweets or [] |
| 19 | users = users or [] |
| 20 | resp = {"data": tweets} |
| 21 | if users: |
| 22 | resp["includes"] = {"users": users} |
| 23 | return resp |
| 24 | |
| 25 | # --------------------------------------------------------------------------- |
| 26 | # is_available |
| 27 | # --------------------------------------------------------------------------- |
| 28 | |
| 29 | |
| 30 | class TestIsAvailable(unittest.TestCase): |
| 31 | def setUp(self): |
| 32 | # is_available() memoizes per process; isolate every test. |
| 33 | xurl_x.clear_availability_cache() |
| 34 | self.addCleanup(xurl_x.clear_availability_cache) |
| 35 | |
| 36 | def test_returns_true_when_bearer_configured(self): |
| 37 | completed = mock.Mock( |
| 38 | returncode=0, |
| 39 | stdout="oauth1: ✗\nbearer: ✓\n", |
| 40 | ) |
| 41 | with mock.patch("subprocess.run", return_value=completed) as run_mock: |
| 42 | self.assertTrue(xurl_x.is_available()) |
| 43 | call_args = run_mock.call_args[0][0] |
| 44 | self.assertEqual(call_args[:3], ["xurl", "auth", "status"]) |
| 45 | |
| 46 | def test_returns_false_when_oauth1_only(self): |
| 47 | # OAuth1 alone cannot satisfy search_x's --auth app requirement. |
| 48 | completed = mock.Mock( |
| 49 | returncode=0, |
| 50 | stdout="oauth1: ✓\nbearer: ✗\n", |
| 51 | ) |
| 52 | with mock.patch("subprocess.run", return_value=completed): |
| 53 | self.assertFalse(xurl_x.is_available()) |
| 54 | |
| 55 | def test_returns_false_when_not_authenticated(self): |
| 56 | completed = mock.Mock(returncode=1, stdout="") |
| 57 | with mock.patch("subprocess.run", return_value=completed): |
| 58 | self.assertFalse(xurl_x.is_available()) |
| 59 | |
| 60 | def test_returns_false_when_not_installed(self): |
| 61 | with mock.patch("subprocess.run", side_effect=FileNotFoundError): |
| 62 | self.assertFalse(xurl_x.is_available()) |
| 63 | |
| 64 | def test_returns_false_on_permission_error(self): |
| 65 | # WSL hits this when a Windows-mounted PATH entry points at an |
| 66 | # exec-blocked shim (e.g. WindowsApps), which raises PermissionError |
| 67 | # before any other PATH candidate is tried. |
| 68 | with mock.patch("subprocess.run", side_effect=PermissionError(13, "Permission denied", "xurl")): |
| 69 | self.assertFalse(xurl_x.is_available()) |
| 70 | |
| 71 | def test_returns_false_on_timeout(self): |
| 72 | import subprocess |
| 73 | with mock.patch("subprocess.run", side_effect=subprocess.TimeoutExpired("xurl", 10)): |
| 74 | self.assertFalse(xurl_x.is_available()) |
| 75 | |
| 76 | def test_returns_false_when_no_bearer_marker(self): |
| 77 | # returncode=0 but status output has no bearer: ✓ |
| 78 | completed = mock.Mock(returncode=0, stdout="oauth1: ✗\nbearer: ✗\n") |
| 79 | with mock.patch("subprocess.run", return_value=completed): |
| 80 | self.assertFalse(xurl_x.is_available()) |
| 81 | |
| 82 | # --------------------------------------------------------------------------- |
| 83 | # stored_auth_status / has_stored_auth (local-only doctor-path evidence) |
| 84 | # --------------------------------------------------------------------------- |
| 85 | |
| 86 | |
| 87 | class _UnreadableStore: |
| 88 | """Path stub: exists but every read raises (permission-denied store).""" |
| 89 | |
| 90 | def is_file(self): |
| 91 | return True |
| 92 | |
| 93 | def read_text(self, *args, **kwargs): |
| 94 | raise PermissionError(13, "Permission denied") |
| 95 | |
| 96 | def __str__(self): |
| 97 | return "/home/user/.xurl" |
| 98 | |
| 99 | |
| 100 | class TestStoredAuth(unittest.TestCase): |
| 101 | """F1/F10: the doctor path keys on xurl's on-disk token store (~/.xurl) |
| 102 | instead of the live `xurl whoami` network call. These tests forbid |
| 103 | subprocess entirely — local evidence must never spawn anything.""" |
| 104 | |
| 105 | def setUp(self): |
| 106 | self._tmp = tempfile.TemporaryDirectory() |
| 107 | self.addCleanup(self._tmp.cleanup) |
| 108 | self.store = Path(self._tmp.name) / ".xurl" |
| 109 | boom = mock.patch( |
| 110 | "subprocess.run", |
| 111 | side_effect=AssertionError("local auth evidence must not spawn a subprocess"), |
| 112 | ) |
| 113 | boom.start() |
| 114 | self.addCleanup(boom.stop) |
| 115 | |
| 116 | def _status(self, path=None): |
| 117 | with mock.patch("lib.xurl_x.token_store_path", return_value=path or self.store): |
| 118 | return xurl_x.stored_auth_status() |
| 119 | |
| 120 | def test_yaml_store_with_bearer_token_is_ok(self): |
| 121 | self.store.write_text( |
| 122 | "apps:\n app:\n bearer_token:\n bearer: dummy-not-real\n", |
| 123 | encoding="utf-8", |
| 124 | ) |
| 125 | status, detail = self._status() |
| 126 | self.assertEqual(xurl_x.AUTH_OK, status) |
| 127 | self.assertIn(str(self.store), detail) |
| 128 | |
| 129 | def test_yaml_store_with_oauth2_only_is_missing(self): |
| 130 | self.store.write_text( |
| 131 | "apps:\n app:\n oauth2_tokens:\n me:\n oauth2:\n" |
| 132 | " access_token: dummy-not-real\n", |
| 133 | encoding="utf-8", |
| 134 | ) |
| 135 | status, detail = self._status() |
| 136 | self.assertEqual(xurl_x.AUTH_MISSING, status) |
| 137 | self.assertIn("OAuth user tokens only", detail) |
| 138 | |
| 139 | def test_directory_layout_auth_yml_with_token_is_ok(self): |
| 140 | # Current xurl (>=1.1) stores credentials at ~/.xurl/auth.yml inside |
| 141 | # the ~/.xurl directory. Regression for #978: this was misread as |
| 142 | # "no token store" because the directory itself fails is_file(). |
| 143 | self.store.mkdir(exist_ok=True) |
| 144 | auth_yml = self.store / "auth.yml" |
| 145 | auth_yml.write_text( |
| 146 | "apps:\n app:\n bearer_token:\n bearer: dummy-not-real\n", |
| 147 | encoding="utf-8", |
| 148 | ) |
| 149 | status, detail = self._status() |
| 150 | self.assertEqual(xurl_x.AUTH_OK, status) |
| 151 | self.assertIn("auth.yml", detail) |
| 152 | |
| 153 | def test_directory_layout_empty_auth_yml_is_missing(self): |
| 154 | self.store.mkdir(exist_ok=True) |
| 155 | (self.store / "auth.yml").write_text("", encoding="utf-8") |
| 156 | status, _ = self._status() |
| 157 | self.assertEqual(xurl_x.AUTH_MISSING, status) |
| 158 | |
| 159 | def test_directory_layout_without_auth_yml_is_missing(self): |
| 160 | self.store.mkdir(exist_ok=True) |
| 161 | status, detail = self._status() |
| 162 | self.assertEqual(xurl_x.AUTH_MISSING, status) |
| 163 | self.assertIn("no token store", detail) |
| 164 | |
| 165 | def test_legacy_flat_file_layout_is_ok(self): |
| 166 | # When token_store_path() returns the canonical ~/.xurl/auth.yml but |
| 167 | # the legacy flat ~/.xurl file is what exists, still report OK. |
| 168 | self.store.write_text( |
| 169 | json.dumps({"bearer_token": {"bearer": "dummy-not-real"}}), |
| 170 | encoding="utf-8", |
| 171 | ) |
| 172 | status, detail = self._status() |
| 173 | self.assertEqual(xurl_x.AUTH_OK, status) |
| 174 | self.assertIn(str(self.store), detail) |
| 175 | |
| 176 | def test_directory_layout_unreadable_auth_yml_is_error(self): |
| 177 | self.store.mkdir(exist_ok=True) |
| 178 | (self.store / "auth.yml").write_text( |
| 179 | "bearer_token:\n bearer: dummy-not-real\n", encoding="utf-8" |
| 180 | ) |
| 181 | class _BrokenFile: |
| 182 | def __init__(self, path): |
| 183 | self._path = path |
| 184 | |
| 185 | def is_file(self): |
| 186 | return True |
| 187 | |
| 188 | def read_text(self, *args, **kwargs): |
| 189 | raise PermissionError(13, "Permission denied") |
| 190 | |
| 191 | def __str__(self): |
| 192 | return str(self._path) |
| 193 | |
| 194 | status, detail = self._status( |
| 195 | path=_BrokenFile(self.store / "auth.yml") |
| 196 | ) |
| 197 | self.assertEqual(xurl_x.AUTH_ERROR, status) |
| 198 | self.assertIn("PermissionError", detail) |
| 199 | |
| 200 | def test_permission_denied_read_reports_error_not_missing(self): |
| 201 | # Regression: a store that exists but cannot be read must report the |
| 202 | # typed AUTH_ERROR, not AUTH_MISSING. stat() on a chmod-000 file still |
| 203 | # succeeds on POSIX; read_text() is what raises PermissionError. |
| 204 | import os |
| 205 | |
| 206 | if hasattr(os, "geteuid") and os.geteuid() == 0: |
| 207 | self.skipTest("root bypasses permission checks") |
| 208 | self.store.mkdir(exist_ok=True) |
| 209 | auth_yml = self.store / "auth.yml" |
| 210 | auth_yml.write_text("bearer_token:\n bearer: dummy-not-real\n", encoding="utf-8") |
| 211 | auth_yml.chmod(0) |
| 212 | try: |
| 213 | status, detail = self._status() |
| 214 | self.assertEqual(xurl_x.AUTH_ERROR, status) |
| 215 | self.assertIn("PermissionError", detail) |
| 216 | finally: |
| 217 | auth_yml.chmod(0o600) |
| 218 | |
| 219 | def test_permission_denied_parent_stat_reports_error_not_missing(self): |
| 220 | # Regression: a store inside a non-searchable directory must report |
| 221 | # AUTH_ERROR, not AUTH_MISSING. stat() on the candidate inside a |
| 222 | # chmod-000 parent raises PermissionError, which must not be swallowed |
| 223 | # into "no token store" the way pathlib's is_file() would. |
| 224 | import os |
| 225 | |
| 226 | if hasattr(os, "geteuid") and os.geteuid() == 0: |
| 227 | self.skipTest("root bypasses permission checks") |
| 228 | self.store.mkdir(exist_ok=True) |
| 229 | (self.store / "auth.yml").write_text( |
| 230 | "bearer_token:\n bearer: dummy-not-real\n", encoding="utf-8" |
| 231 | ) |
| 232 | self.store.chmod(0) |
| 233 | try: |
| 234 | status, detail = self._status() |
| 235 | self.assertEqual(xurl_x.AUTH_ERROR, status) |
| 236 | self.assertIn("PermissionError", detail) |
| 237 | finally: |
| 238 | self.store.chmod(0o700) |
| 239 | |
| 240 | def test_permission_denied_grandparent_stat_reports_error_not_missing(self): |
| 241 | # Regression: distinct from the parent-chmod case above, which denies |
| 242 | # traversal INTO the store (raising on the per-candidate _is_file scan). |
| 243 | # Chmod-000 on the store's own PARENT directory instead blocks stat() |
| 244 | # on the store path itself, raising during the _is_dir(base) call that |
| 245 | # builds the candidate list -- a separate except-OSError branch that |
| 246 | # the parent-chmod case never reaches. |
| 247 | import os |
| 248 | |
| 249 | if hasattr(os, "geteuid") and os.geteuid() == 0: |
| 250 | self.skipTest("root bypasses permission checks") |
| 251 | self.store.mkdir(exist_ok=True) |
| 252 | (self.store / "auth.yml").write_text( |
| 253 | "bearer_token:\n bearer: dummy-not-real\n", encoding="utf-8" |
| 254 | ) |
| 255 | grandparent = self.store.parent |
| 256 | grandparent.chmod(0) |
| 257 | try: |
| 258 | status, detail = self._status() |
| 259 | self.assertEqual(xurl_x.AUTH_ERROR, status) |
| 260 | self.assertIn("PermissionError", detail) |
| 261 | finally: |
| 262 | grandparent.chmod(0o700) |
| 263 | |
| 264 | def test_directory_layout_has_stored_auth_with_binary(self): |
| 265 | self.store.mkdir(exist_ok=True) |
| 266 | (self.store / "auth.yml").write_text( |
| 267 | "bearer_token:\n bearer: dummy-not-real\n", encoding="utf-8" |
| 268 | ) |
| 269 | with mock.patch("lib.xurl_x.token_store_path", return_value=self.store), \ |
| 270 | mock.patch("lib.xurl_x.shutil.which", return_value="/usr/local/bin/xurl"): |
| 271 | self.assertTrue(xurl_x.has_stored_auth()) |
| 272 | |
| 273 | def test_directory_layout_no_subprocess_spawned(self): |
| 274 | self.store.mkdir(exist_ok=True) |
| 275 | (self.store / "auth.yml").write_text( |
| 276 | "bearer_token:\n bearer: dummy-not-real\n", encoding="utf-8" |
| 277 | ) |
| 278 | with mock.patch( |
| 279 | "subprocess.run", |
| 280 | side_effect=AssertionError("local auth evidence must not spawn a subprocess"), |
| 281 | ): |
| 282 | status, _ = self._status() |
| 283 | self.assertEqual(xurl_x.AUTH_OK, status) |
| 284 | |
| 285 | def test_walk_up_canonical_path_finds_legacy_flat_file(self): |
| 286 | # token_store_path() returns the canonical ~/.xurl/auth.yml, but only |
| 287 | # the legacy flat ~/.xurl file exists. The parent-walk must find it. |
| 288 | self.store.write_text( |
| 289 | json.dumps({"bearer_token": {"bearer": "dummy-not-real"}}), |
| 290 | encoding="utf-8", |
| 291 | ) |
| 292 | canonical = self.store / "auth.yml" |
| 293 | with mock.patch("lib.xurl_x.token_store_path", return_value=canonical): |
| 294 | status, detail = xurl_x.stored_auth_status() |
| 295 | self.assertEqual(xurl_x.AUTH_OK, status) |
| 296 | self.assertIn(str(self.store), detail) |
| 297 | |
| 298 | def test_canonical_path_preferred_when_both_layouts_exist(self): |
| 299 | # A stale legacy flat ~/.xurl must never shadow the live auth.yml. |
| 300 | self.store.mkdir(exist_ok=True) |
| 301 | (self.store / "auth.yml").write_text( |
| 302 | "bearer_token:\n bearer: live\n", |
| 303 | encoding="utf-8", |
| 304 | ) |
| 305 | canonical = self.store / "auth.yml" |
| 306 | with mock.patch("lib.xurl_x.token_store_path", return_value=canonical): |
| 307 | status, detail = xurl_x.stored_auth_status() |
| 308 | self.assertEqual(xurl_x.AUTH_OK, status) |
| 309 | self.assertIn("auth.yml", detail) |
| 310 | |
| 311 | def test_legacy_json_store_with_bearer_token_is_ok(self): |
| 312 | self.store.write_text( |
| 313 | json.dumps({"bearer_token": {"bearer": "dummy-not-real"}}), |
| 314 | encoding="utf-8", |
| 315 | ) |
| 316 | status, _ = self._status() |
| 317 | self.assertEqual(xurl_x.AUTH_OK, status) |
| 318 | |
| 319 | def test_absent_store_is_missing(self): |
| 320 | status, detail = self._status() |
| 321 | self.assertEqual(xurl_x.AUTH_MISSING, status) |
| 322 | self.assertIn("no token store", detail) |
| 323 | |
| 324 | def test_empty_store_is_missing(self): |
| 325 | self.store.write_text("", encoding="utf-8") |
| 326 | status, _ = self._status() |
| 327 | self.assertEqual(xurl_x.AUTH_MISSING, status) |
| 328 | |
| 329 | def test_store_without_credential_markers_is_missing(self): |
| 330 | self.store.write_text("apps: {}\ndefault_app: app\n", encoding="utf-8") |
| 331 | status, detail = self._status() |
| 332 | self.assertEqual(xurl_x.AUTH_MISSING, status) |
| 333 | self.assertIn("no stored credentials", detail) |
| 334 | |
| 335 | def test_unreadable_store_is_error_not_missing(self): |
| 336 | status, detail = self._status(path=_UnreadableStore()) |
| 337 | self.assertEqual(xurl_x.AUTH_ERROR, status) |
| 338 | self.assertIn("unreadable", detail) |
| 339 | self.assertIn("PermissionError", detail) |
| 340 | |
| 341 | def test_has_stored_auth_true_with_binary_and_store(self): |
| 342 | self.store.write_text("bearer_token: dummy-not-real\n", encoding="utf-8") |
| 343 | with mock.patch("lib.xurl_x.token_store_path", return_value=self.store), \ |
| 344 | mock.patch("lib.xurl_x.shutil.which", return_value="/usr/local/bin/xurl"): |
| 345 | self.assertTrue(xurl_x.has_stored_auth()) |
| 346 | |
| 347 | def test_has_stored_auth_false_without_binary(self): |
| 348 | self.store.write_text("bearer_token: dummy-not-real\n", encoding="utf-8") |
| 349 | with mock.patch("lib.xurl_x.token_store_path", return_value=self.store), \ |
| 350 | mock.patch("lib.xurl_x.shutil.which", return_value=None): |
| 351 | self.assertFalse(xurl_x.has_stored_auth()) |
| 352 | |
| 353 | def test_has_stored_auth_false_on_broken_store(self): |
| 354 | # has_stored_auth answers availability only; the typed ERROR surface |
| 355 | # lives in backends._probe_xurl (see test_backend_descriptors). |
| 356 | with mock.patch("lib.xurl_x.token_store_path", return_value=_UnreadableStore()), \ |
| 357 | mock.patch("lib.xurl_x.shutil.which", return_value="/usr/local/bin/xurl"): |
| 358 | self.assertFalse(xurl_x.has_stored_auth()) |
| 359 | |
| 360 | def test_default_store_path_is_home_dot_xurl_auth_yml(self): |
| 361 | self.assertEqual(Path.home() / ".xurl" / "auth.yml", xurl_x.token_store_path()) |
| 362 | |
| 363 | # --------------------------------------------------------------------------- |
| 364 | # search_x |
| 365 | # --------------------------------------------------------------------------- |
| 366 | |
| 367 | |
| 368 | class TestSearchX(unittest.TestCase): |
| 369 | def test_returns_parsed_json_on_success(self): |
| 370 | payload = {"data": [{"id": "1", "text": "hello world", "author_id": "u1"}]} |
| 371 | completed = mock.Mock(returncode=0, stdout=json.dumps(payload)) |
| 372 | with mock.patch("subprocess.run", return_value=completed): |
| 373 | result = xurl_x.search_x("hello world") |
| 374 | self.assertEqual(result["data"][0]["id"], "1") |
| 375 | |
| 376 | def test_returns_fixed_error_on_non_zero_exit(self): |
| 377 | # xurl's stderr may echo the request or the bearer; only an |
| 378 | # engine-authored fixed string (with a classifier marker) survives. |
| 379 | completed = mock.Mock( |
| 380 | returncode=1, stdout="", |
| 381 | stderr="rate limit exceeded for dummy-x-bearer-secret-000", |
| 382 | ) |
| 383 | with mock.patch("subprocess.run", return_value=completed): |
| 384 | result = xurl_x.search_x("test") |
| 385 | self.assertEqual(xurl_x.ERR_RATE_LIMITED, result["error"]) |
| 386 | self.assertIn("rate limit", result["error"]) |
| 387 | self.assertNotIn("dummy-x-bearer-secret-000", result["error"]) |
| 388 | |
| 389 | def test_returns_fixed_error_on_invalid_json(self): |
| 390 | completed = mock.Mock(returncode=0, stdout="NOT JSON dummy-x-bearer-secret-000") |
| 391 | with mock.patch("subprocess.run", return_value=completed): |
| 392 | result = xurl_x.search_x("test") |
| 393 | self.assertEqual(xurl_x.ERR_INVALID_JSON, result["error"]) |
| 394 | self.assertIn("invalid JSON", result["error"]) |
| 395 | self.assertNotIn("dummy-x-bearer-secret-000", result["error"]) |
| 396 | |
| 397 | def test_returns_error_when_not_installed(self): |
| 398 | with mock.patch("subprocess.run", side_effect=FileNotFoundError): |
| 399 | result = xurl_x.search_x("test") |
| 400 | self.assertIn("error", result) |
| 401 | self.assertIn("not found", result["error"]) |
| 402 | |
| 403 | def test_returns_error_on_timeout(self): |
| 404 | import subprocess |
| 405 | with mock.patch("subprocess.run", side_effect=subprocess.TimeoutExpired("xurl", 30)): |
| 406 | result = xurl_x.search_x("test") |
| 407 | self.assertIn("error", result) |
| 408 | self.assertIn("timed out", result["error"]) |
| 409 | |
| 410 | def test_search_uses_app_only_auth(self): |
| 411 | # Regression: default (OAuth1) auth 401s on any query needing |
| 412 | # percent-encoding (xurl >=1.1 signing bug); search must pin app-only. |
| 413 | completed = mock.Mock(returncode=0, stdout=json.dumps({})) |
| 414 | with mock.patch("subprocess.run", return_value=completed) as run_mock: |
| 415 | xurl_x.search_x("claude code") |
| 416 | call_args = run_mock.call_args[0][0] |
| 417 | self.assertIn("--auth", call_args) |
| 418 | self.assertEqual(call_args[call_args.index("--auth") + 1], "app") |
| 419 | |
| 420 | def test_max_results_clamped_to_100(self): |
| 421 | # DEPTH_CONFIG["deep"] = 60, should stay at 60 (within 10-100 range) |
| 422 | completed = mock.Mock(returncode=0, stdout=json.dumps({})) |
| 423 | with mock.patch("subprocess.run", return_value=completed) as run_mock: |
| 424 | xurl_x.search_x("test", depth="deep") |
| 425 | call_args = run_mock.call_args[0][0] |
| 426 | n_idx = call_args.index("-n") |
| 427 | self.assertLessEqual(int(call_args[n_idx + 1]), 100) |
| 428 | |
| 429 | def test_max_results_at_least_10(self): |
| 430 | completed = mock.Mock(returncode=0, stdout=json.dumps({})) |
| 431 | with mock.patch("subprocess.run", return_value=completed) as run_mock: |
| 432 | xurl_x.search_x("test", depth="quick") |
| 433 | call_args = run_mock.call_args[0][0] |
| 434 | n_idx = call_args.index("-n") |
| 435 | self.assertGreaterEqual(int(call_args[n_idx + 1]), 10) |
| 436 | |
| 437 | def test_unknown_depth_falls_back_to_default(self): |
| 438 | completed = mock.Mock(returncode=0, stdout=json.dumps({})) |
| 439 | with mock.patch("subprocess.run", return_value=completed) as run_mock: |
| 440 | xurl_x.search_x("test", depth="nonexistent") |
| 441 | call_args = run_mock.call_args[0][0] |
| 442 | n_idx = call_args.index("-n") |
| 443 | self.assertEqual(int(call_args[n_idx + 1]), xurl_x.DEPTH_CONFIG["default"]) |
| 444 | |
| 445 | |
| 446 | class TestSearchXQuerySanitization(unittest.TestCase): |
| 447 | """X's v2 grammar 400s on a bare lowercase and/or and treats colon |
| 448 | tokens, leading "-", parentheses and quotes as operators. The pipeline |
| 449 | hands search_x the raw user topic, so search_x must sanitize it while |
| 450 | keeping space-joined keyword semantics (not one exact phrase).""" |
| 451 | |
| 452 | def _argv_query(self, topic): |
| 453 | completed = mock.Mock(returncode=0, stdout=json.dumps({})) |
| 454 | with mock.patch("subprocess.run", return_value=completed) as run_mock: |
| 455 | xurl_x.search_x(topic) |
| 456 | argv = run_mock.call_args[0][0] |
| 457 | self.assertEqual(argv[:2], ["xurl", "search"]) |
| 458 | return argv[2] |
| 459 | |
| 460 | def test_bare_lowercase_and_is_dropped(self): |
| 461 | query = self._argv_query( |
| 462 | "AI code review and security review tools for Claude Code and Codex" |
| 463 | ) |
| 464 | self.assertEqual( |
| 465 | query, "AI code review security review tools for Claude Code Codex" |
| 466 | ) |
| 467 | |
| 468 | def test_or_and_in_any_case_are_dropped(self): |
| 469 | self.assertEqual(self._argv_query("cats or dogs OR birds AND fish"), "cats dogs birds fish") |
| 470 | |
| 471 | def test_keyword_semantics_not_exact_phrase(self): |
| 472 | query = self._argv_query("claude code") |
| 473 | self.assertEqual(query, "claude code") |
| 474 | self.assertNotIn('"', query) |
| 475 | self.assertNotIn("-is:retweet", query) |
| 476 | |
| 477 | def test_trailing_colon_keeps_python_subject(self): |
| 478 | self.assertEqual(self._argv_query("Python: what's new"), "Python what's new") |
| 479 | |
| 480 | def test_trailing_colon_keeps_cplusplus_subject(self): |
| 481 | self.assertEqual(self._argv_query("C++: memory safety"), "C++ memory safety") |
| 482 | |
| 483 | def test_trailing_colon_still_drops_operators_and_negation(self): |
| 484 | query = self._argv_query("Python: from:attacker since:2020-01-01 -spam and review") |
| 485 | self.assertEqual(query, "Python review") |
| 486 | |
| 487 | def test_colon_operator_tokens_are_dropped(self): |
| 488 | self.assertEqual(self._argv_query("from:x claude since:2020-01-01 code"), "claude code") |
| 489 | |
| 490 | def test_leading_negation_is_dropped(self): |
| 491 | query = self._argv_query("-foo claude -bar") |
| 492 | self.assertEqual(query, "claude") |
| 493 | self.assertFalse(query.startswith("-")) |
| 494 | |
| 495 | def test_parentheses_and_unbalanced_quotes_become_spaces(self): |
| 496 | self.assertEqual(self._argv_query('(claude "code) [agents] {x}'), "claude code agents x") |
| 497 | |
| 498 | def test_query_is_capped(self): |
| 499 | query = self._argv_query(" ".join(["word"] * 300)) |
| 500 | self.assertLessEqual(len(query), xurl_x.x_api.MAX_QUERY_CHARS) |
| 501 | self.assertTrue(query.startswith("word word")) |
| 502 | |
| 503 | def test_nothing_left_returns_error_without_spawning(self): |
| 504 | with mock.patch( |
| 505 | "subprocess.run", |
| 506 | side_effect=AssertionError("an empty query must not reach xurl"), |
| 507 | ): |
| 508 | result = xurl_x.search_x("and OR from:x -foo ()") |
| 509 | self.assertEqual(result, {"error": xurl_x.ERR_EMPTY_QUERY}) |
| 510 | |
| 511 | |
| 512 | class TestClassifyInvalidRequest(unittest.TestCase): |
| 513 | _BODY = ( |
| 514 | '{"errors":[{"parameters":{"query":["AI and dummy-x-bearer-secret-000"]},' |
| 515 | '"message":"Ambiguous use of and as a keyword. Use a space to logically ' |
| 516 | 'join two clauses, or \\"and\\" to find occurrences of and in text"}],' |
| 517 | '"title":"Invalid Request","detail":"One or more parameters to your ' |
| 518 | 'request was invalid.","type":"https://api.twitter.com/2/problems/invalid-request"}' |
| 519 | ) |
| 520 | |
| 521 | def test_invalid_request_problem_type(self): |
| 522 | self.assertEqual( |
| 523 | xurl_x._classify_cli_failure("type: .../2/problems/invalid-request"), |
| 524 | xurl_x.ERR_INVALID_REQUEST, |
| 525 | ) |
| 526 | |
| 527 | def test_invalid_request_title(self): |
| 528 | self.assertEqual( |
| 529 | xurl_x._classify_cli_failure("Error: Invalid Request"), |
| 530 | xurl_x.ERR_INVALID_REQUEST, |
| 531 | ) |
| 532 | |
| 533 | def test_search_x_surfaces_fixed_invalid_request_error(self): |
| 534 | completed = mock.Mock(returncode=1, stdout="", stderr=self._BODY) |
| 535 | with mock.patch("subprocess.run", return_value=completed): |
| 536 | result = xurl_x.search_x("AI code review") |
| 537 | self.assertEqual(result, {"error": xurl_x.ERR_INVALID_REQUEST}) |
| 538 | self.assertNotIn("dummy-x-bearer-secret-000", result["error"]) |
| 539 | self.assertNotIn("Ambiguous", result["error"]) |
| 540 | |
| 541 | def test_auth_and_rate_limit_still_win(self): |
| 542 | self.assertEqual( |
| 543 | xurl_x._classify_cli_failure("HTTP 401 Unauthorized invalid-request"), |
| 544 | xurl_x.ERR_UNAUTHORIZED, |
| 545 | ) |
| 546 | self.assertEqual( |
| 547 | xurl_x._classify_cli_failure("rate limit exceeded"), |
| 548 | xurl_x.ERR_RATE_LIMITED, |
| 549 | ) |
| 550 | |
| 551 | def test_unrelated_failure_stays_generic(self): |
| 552 | self.assertEqual(xurl_x._classify_cli_failure("boom"), xurl_x.ERR_FAILED) |
| 553 | |
| 554 | |
| 555 | # --------------------------------------------------------------------------- |
| 556 | # parse_x_response |
| 557 | # --------------------------------------------------------------------------- |
| 558 | |
| 559 | |
| 560 | class TestParseXResponse(unittest.TestCase): |
| 561 | def _tweet(self, id_, text, author_id, created_at=None, metrics=None): |
| 562 | t = {"id": id_, "text": text, "author_id": author_id} |
| 563 | if created_at: |
| 564 | t["created_at"] = created_at |
| 565 | if metrics: |
| 566 | t["public_metrics"] = metrics |
| 567 | return t |
| 568 | |
| 569 | def _user(self, id_, username): |
| 570 | return {"id": id_, "username": username} |
| 571 | |
| 572 | def test_empty_response_returns_empty_list(self): |
| 573 | self.assertEqual(xurl_x.parse_x_response({}), []) |
| 574 | |
| 575 | def test_error_response_returns_empty_list(self): |
| 576 | self.assertEqual(xurl_x.parse_x_response({"error": "oops"}), []) |
| 577 | |
| 578 | def test_parses_basic_tweet(self): |
| 579 | resp = _make_api_response( |
| 580 | tweets=[self._tweet("111", "Hello AI", "u1")], |
| 581 | users=[self._user("u1", "alice")], |
| 582 | ) |
| 583 | items = xurl_x.parse_x_response(resp) |
| 584 | self.assertEqual(len(items), 1) |
| 585 | self.assertEqual(items[0]["text"], "Hello AI") |
| 586 | self.assertEqual(items[0]["author_handle"], "alice") |
| 587 | self.assertIn("alice", items[0]["url"]) |
| 588 | self.assertIn("111", items[0]["url"]) |
| 589 | |
| 590 | def test_parses_date_from_iso(self): |
| 591 | resp = _make_api_response( |
| 592 | tweets=[self._tweet("1", "text", "u1", created_at="2024-06-15T12:00:00Z")], |
| 593 | ) |
| 594 | items = xurl_x.parse_x_response(resp) |
| 595 | self.assertEqual(items[0]["date"], "2024-06-15") |
| 596 | |
| 597 | def test_date_none_when_missing(self): |
| 598 | resp = _make_api_response(tweets=[self._tweet("1", "text", "u1")]) |
| 599 | items = xurl_x.parse_x_response(resp) |
| 600 | self.assertIsNone(items[0]["date"]) |
| 601 | |
| 602 | def test_parses_engagement_metrics(self): |
| 603 | metrics = { |
| 604 | "like_count": 42, |
| 605 | "retweet_count": 10, |
| 606 | "reply_count": 5, |
| 607 | "quote_count": 2, |
| 608 | } |
| 609 | resp = _make_api_response( |
| 610 | tweets=[self._tweet("1", "text", "u1", metrics=metrics)], |
| 611 | ) |
| 612 | items = xurl_x.parse_x_response(resp) |
| 613 | self.assertEqual(items[0]["engagement"]["likes"], 42) |
| 614 | self.assertEqual(items[0]["engagement"]["reposts"], 10) |
| 615 | self.assertEqual(items[0]["engagement"]["replies"], 5) |
| 616 | self.assertEqual(items[0]["engagement"]["quotes"], 2) |
| 617 | |
| 618 | def test_engagement_none_when_no_metrics(self): |
| 619 | resp = _make_api_response(tweets=[self._tweet("1", "text", "u1")]) |
| 620 | items = xurl_x.parse_x_response(resp) |
| 621 | self.assertIsNone(items[0]["engagement"]) |
| 622 | |
| 623 | def test_text_truncated_to_500_chars(self): |
| 624 | long_text = "x" * 600 |
| 625 | resp = _make_api_response(tweets=[self._tweet("1", long_text, "u1")]) |
| 626 | items = xurl_x.parse_x_response(resp) |
| 627 | self.assertLessEqual(len(items[0]["text"]), 500) |
| 628 | |
| 629 | def test_id_prefixed_with_xurl(self): |
| 630 | resp = _make_api_response(tweets=[self._tweet("1", "text", "u1")]) |
| 631 | items = xurl_x.parse_x_response(resp) |
| 632 | self.assertTrue(items[0]["id"].startswith("XURL")) |
| 633 | |
| 634 | def test_relevance_computed_when_topic_given(self): |
| 635 | resp = _make_api_response( |
| 636 | tweets=[self._tweet("1", "Claude Code is great for AI coding", "u1")], |
| 637 | ) |
| 638 | items = xurl_x.parse_x_response(resp, topic="Claude Code") |
| 639 | self.assertGreater(items[0]["relevance"], 0.5) |
| 640 | |
| 641 | def test_relevance_neutral_when_no_topic(self): |
| 642 | resp = _make_api_response(tweets=[self._tweet("1", "some text", "u1")]) |
| 643 | items = xurl_x.parse_x_response(resp) |
| 644 | self.assertEqual(items[0]["relevance"], 0.5) |
| 645 | |
| 646 | def test_url_falls_back_to_i_status_when_no_username(self): |
| 647 | # author_id not in includes.users → username="" but the post is |
| 648 | # kept with the id-only citation form (shared x_api parser). |
| 649 | resp = _make_api_response(tweets=[self._tweet("999", "text", "unknown_uid")]) |
| 650 | items = xurl_x.parse_x_response(resp) |
| 651 | self.assertEqual(items[0]["url"], "https://x.com/i/status/999") |
| 652 | self.assertEqual(items[0]["author_handle"], "") |
| 653 | self.assertEqual(items[0]["post_id"], "999") |
| 654 | |
| 655 | def test_multiple_tweets_parsed(self): |
| 656 | tweets = [self._tweet(str(i), f"tweet {i}", "u1") for i in range(5)] |
| 657 | resp = _make_api_response(tweets=tweets, users=[self._user("u1", "bob")]) |
| 658 | items = xurl_x.parse_x_response(resp) |
| 659 | self.assertEqual(len(items), 5) |
| 660 | |
| 661 | def test_empty_data_list(self): |
| 662 | resp = _make_api_response(tweets=[]) |
| 663 | self.assertEqual(xurl_x.parse_x_response(resp), []) |
| 664 | |
| 665 | def test_why_relevant_is_empty_string(self): |
| 666 | # xurl doesn't provide LLM-generated why_relevant (unlike xai_x) |
| 667 | resp = _make_api_response(tweets=[self._tweet("1", "text", "u1")]) |
| 668 | items = xurl_x.parse_x_response(resp) |
| 669 | self.assertEqual(items[0]["why_relevant"], "") |
| 670 | |
| 671 | # --------------------------------------------------------------------------- |
| 672 | # DEPTH_CONFIG |
| 673 | # --------------------------------------------------------------------------- |
| 674 | |
| 675 | |
| 676 | class TestDepthConfig(unittest.TestCase): |
| 677 | def test_all_standard_depths_present(self): |
| 678 | for depth in ("quick", "default", "deep"): |
| 679 | self.assertIn(depth, xurl_x.DEPTH_CONFIG) |
| 680 | |
| 681 | def test_depth_config_is_shared_with_x_api(self): |
| 682 | from lib import x_api |
| 683 | self.assertIs(x_api.DEPTH_CONFIG, xurl_x.DEPTH_CONFIG) |
| 684 | |
| 685 | def test_deep_greater_than_quick(self): |
| 686 | self.assertGreater( |
| 687 | xurl_x.DEPTH_CONFIG["deep"], |
| 688 | xurl_x.DEPTH_CONFIG["quick"], |
| 689 | ) |
| 690 | |
| 691 | if __name__ == "__main__": |
| 692 | unittest.main() |
| 693 |