claude-usage-limits 0.3.1__tar.gz → 0.3.2__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.
Files changed (19) hide show
  1. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/PKG-INFO +1 -1
  2. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/pyproject.toml +1 -1
  3. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage/__init__.py +1 -1
  4. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage/api.py +40 -21
  5. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage_limits.egg-info/PKG-INFO +1 -1
  6. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/tests/test_report.py +2 -2
  7. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/tests/test_sources.py +100 -23
  8. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/LICENSE +0 -0
  9. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/README.md +0 -0
  10. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/setup.cfg +0 -0
  11. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage/__main__.py +0 -0
  12. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage/auth.py +0 -0
  13. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage/cli.py +0 -0
  14. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage/report.py +0 -0
  15. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage_limits.egg-info/SOURCES.txt +0 -0
  16. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage_limits.egg-info/dependency_links.txt +0 -0
  17. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage_limits.egg-info/entry_points.txt +0 -0
  18. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/src/claude_usage_limits.egg-info/top_level.txt +0 -0
  19. {claude_usage_limits-0.3.1 → claude_usage_limits-0.3.2}/tests/test_auth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: claude-usage-limits
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: CLI for Claude subscription limits (5-hour, weekly, model caps, Enterprise spend) with status-line, SwiftBar menu bar, and warning thresholds.
5
5
  Author: claude-usage contributors
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "claude-usage-limits"
7
- version = "0.3.1"
7
+ version = "0.3.2"
8
8
  description = "CLI for Claude subscription limits (5-hour, weekly, model caps, Enterprise spend) with status-line, SwiftBar menu bar, and warning thresholds."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,3 +1,3 @@
1
1
  """claude-usage: read your Claude subscription rate-limit windows."""
2
2
 
3
- __version__ = "0.3.1"
3
+ __version__ = "0.3.2"
@@ -5,14 +5,17 @@ make at most one live request, then accept either cache for up to an hour.
5
5
  No retries, polling, or token refresh. All HTTP goes through ``_get_json``.
6
6
  """
7
7
 
8
+ import http.client
8
9
  import json
9
10
  import os
10
11
  import sys
12
+ import tempfile
11
13
  import time
12
14
  import urllib.error
13
15
  import urllib.request
14
16
  from pathlib import Path
15
17
 
18
+ from . import __version__
16
19
  from .auth import config_dir, resolve_token
17
20
  from .report import shape
18
21
 
@@ -26,15 +29,26 @@ def write_cache(path, data):
26
29
  """Replace a cache atomically, never exposing a partially written JSON file."""
27
30
  path = Path(path)
28
31
  path.parent.mkdir(parents=True, exist_ok=True)
29
- tmp = path.with_name(path.name + '.tmp')
30
- with tmp.open('w', encoding='utf-8') as stream:
31
- json.dump(data, stream)
32
- os.replace(tmp, path)
32
+ tmp = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent,
33
+ prefix=path.name + '.', suffix='.tmp', delete=False)
34
+ try:
35
+ with tmp:
36
+ json.dump(data, tmp)
37
+ os.replace(tmp.name, path)
38
+ finally:
39
+ Path(tmp.name).unlink(missing_ok=True)
40
+
41
+
42
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
43
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
44
+ # urllib otherwise forwards the Authorization header to redirect targets.
45
+ return None
33
46
 
34
47
 
35
48
  def _get_json(url, headers, timeout):
36
49
  request = urllib.request.Request(url, headers=headers)
37
- with urllib.request.urlopen(request, timeout=timeout) as response:
50
+ opener = urllib.request.build_opener(_NoRedirect())
51
+ with opener.open(request, timeout=timeout) as response:
38
52
  return json.load(response)
39
53
 
40
54
 
@@ -43,13 +57,14 @@ def from_endpoint(config, verbose=False):
43
57
  'Authorization': 'Bearer ' + resolve_token(config, verbose=verbose),
44
58
  'anthropic-beta': 'oauth-2025-04-20',
45
59
  'Accept': 'application/json',
60
+ 'User-Agent': f'claude-usage/{__version__}',
46
61
  }
47
62
  try:
48
63
  data = _get_json(URL, headers, 15)
49
64
  except urllib.error.HTTPError as exc:
50
65
  raise RuntimeError(f'HTTP {exc.code} from {URL}') from None
51
- except urllib.error.URLError as exc:
52
- raise RuntimeError(str(exc.reason)) from None
66
+ except (OSError, http.client.HTTPException):
67
+ raise RuntimeError(f'could not reach {URL}') from None
53
68
  except (ValueError, TypeError):
54
69
  # A rejected HTTP header can appear verbatim in the library exception.
55
70
  raise RuntimeError(f'invalid request or JSON response from {URL}') from None
@@ -60,26 +75,30 @@ def from_endpoint(config, verbose=False):
60
75
 
61
76
  def from_last(config, max_age):
62
77
  path = Path(config) / 'last-usage.json'
63
- if not path.exists():
64
- raise RuntimeError('no saved endpoint answer yet')
65
- age = time.time() - path.stat().st_mtime
66
- if age >= max_age:
67
- raise RuntimeError(f'last endpoint answer is {int(age // 60)} min old')
68
- with path.open(encoding='utf-8') as stream:
69
- data = json.load(stream)
78
+ try:
79
+ age = time.time() - path.stat().st_mtime
80
+ if age >= max_age:
81
+ raise RuntimeError(f'last endpoint answer is {int(age // 60)} min old')
82
+ with path.open(encoding='utf-8') as stream:
83
+ data = json.load(stream)
84
+ except FileNotFoundError:
85
+ raise RuntimeError('no saved endpoint answer yet') from None
70
86
  source = f'endpoint, {int(age // 60)} min ago' if age >= 60 else 'endpoint'
71
87
  return shape(data, source)
72
88
 
73
89
 
74
90
  def from_cache(config):
75
91
  path = Path(config) / 'last-statusline.json'
76
- if not path.exists():
77
- raise RuntimeError('no status-line cache yet (is the status line set to `claude-usage --statusline`?)')
78
- age = time.time() - path.stat().st_mtime
79
- if age >= MAX_AGE:
80
- raise RuntimeError(f'status-line cache is {int(age // 60)} min old')
81
- with path.open(encoding='utf-8') as stream:
82
- data = json.load(stream)
92
+ try:
93
+ age = time.time() - path.stat().st_mtime
94
+ if age >= MAX_AGE:
95
+ raise RuntimeError(f'status-line cache is {int(age // 60)} min old')
96
+ with path.open(encoding='utf-8') as stream:
97
+ data = json.load(stream)
98
+ except FileNotFoundError:
99
+ raise RuntimeError(
100
+ 'no status-line cache yet (is the status line set to `claude-usage --statusline`?)'
101
+ ) from None
83
102
  if not isinstance(data, dict) or not data.get('rate_limits'):
84
103
  raise RuntimeError('status-line cache has no rate_limits (Pro/Max only, after the first reply)')
85
104
  return shape(data, f'status line, {int(age // 60)} min ago')
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: claude-usage-limits
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: CLI for Claude subscription limits (5-hour, weekly, model caps, Enterprise spend) with status-line, SwiftBar menu bar, and warning thresholds.
5
5
  Author: claude-usage contributors
6
6
  License-Expression: MIT
@@ -186,7 +186,7 @@ def test_statusline_cache_and_line(monkeypatch, capsys, tmp_path):
186
186
  assert cli.main(["--statusline"]) == 0
187
187
  assert capsys.readouterr().out == "Fable 5.1 · 5h 25% · 7d 59%\n"
188
188
  assert json.loads((tmp_path / 'last-statusline.json').read_text()) == STATUS
189
- assert not (tmp_path / 'last-statusline.json.tmp').exists()
189
+ assert not list(tmp_path.glob('*.tmp'))
190
190
 
191
191
 
192
192
  def test_statusline_write_failure_is_silent(monkeypatch, capsys, tmp_path):
@@ -210,7 +210,7 @@ def test_version(capsys):
210
210
  with pytest.raises(SystemExit) as exc:
211
211
  cli.main(["--version"])
212
212
  assert exc.value.code == 0
213
- assert capsys.readouterr().out == "claude-usage 0.3.1\n"
213
+ assert capsys.readouterr().out == "claude-usage 0.3.2\n"
214
214
 
215
215
 
216
216
  def test_help_hides_statusline(capsys):
@@ -1,12 +1,17 @@
1
+ import http.client
2
+ import io
1
3
  import json
2
4
  import os
3
5
  import time
4
6
  import urllib.error
7
+ import urllib.request
8
+ import urllib.response
9
+ from pathlib import Path
5
10
  from types import SimpleNamespace
6
11
 
7
12
  import pytest
8
13
 
9
- from claude_usage import api, auth, cli
14
+ from claude_usage import __version__, api, auth, cli
10
15
 
11
16
  ENDPOINT = {"five_hour": None,
12
17
  "seven_day": {"utilization": 59.0, "resets_at": "2026-10-25T07:00:00.886762+00:00"}}
@@ -53,17 +58,58 @@ def test_under_one_minute_source(tmp_path):
53
58
  def test_endpoint_success_saves_atomically(monkeypatch, tmp_path, capsys):
54
59
  def get(url, headers, timeout):
55
60
  assert url == 'https://api.anthropic.com/api/oauth/usage'
56
- assert headers == {"Authorization": "Bearer PRIVATE-TOKEN", "anthropic-beta": "oauth-2025-04-20", "Accept": "application/json"}
61
+ assert headers == {
62
+ "Authorization": "Bearer PRIVATE-TOKEN",
63
+ "anthropic-beta": "oauth-2025-04-20",
64
+ "Accept": "application/json",
65
+ "User-Agent": f"claude-usage/{__version__}",
66
+ }
57
67
  assert timeout == 15
58
68
  return ENDPOINT
59
69
  monkeypatch.setattr(api, '_get_json', get)
60
70
  out = api.usage(verbose=True)
61
71
  assert out['source'] == 'endpoint'
62
72
  assert json.loads((tmp_path / 'last-usage.json').read_text()) == ENDPOINT
63
- assert not (tmp_path / 'last-usage.json.tmp').exists()
73
+ assert not list(tmp_path.glob('*.tmp'))
64
74
  assert capsys.readouterr().err == 'credentials: CLAUDE_CODE_OAUTH_TOKEN\nusage: endpoint\n'
65
75
 
66
76
 
77
+ def test_overlapping_cache_writes_use_separate_files(monkeypatch, tmp_path):
78
+ path = tmp_path / 'last-usage.json'
79
+ real_replace = os.replace
80
+ sources = []
81
+
82
+ def replace(source, target):
83
+ source = Path(source)
84
+ assert source.parent == target.parent == tmp_path
85
+ assert source not in sources
86
+ sources.append(source)
87
+ if len(sources) == 1:
88
+ api.write_cache(path, STATUS)
89
+ assert json.loads(path.read_text()) == STATUS
90
+ real_replace(source, target)
91
+
92
+ monkeypatch.setattr(api.os, 'replace', replace)
93
+ api.write_cache(path, ENDPOINT)
94
+ assert json.loads(path.read_text()) == ENDPOINT
95
+ assert list(tmp_path.iterdir()) == [path]
96
+
97
+
98
+ def test_failed_replace_leaves_prior_cache(monkeypatch, tmp_path):
99
+ path = save(tmp_path, 'last-usage.json', ENDPOINT)
100
+
101
+ def fail(source, target):
102
+ assert json.loads(Path(source).read_text()) == STATUS
103
+ assert target == path
104
+ raise OSError('replace blocked')
105
+
106
+ monkeypatch.setattr(api.os, 'replace', fail)
107
+ with pytest.raises(OSError, match='replace blocked'):
108
+ api.write_cache(path, STATUS)
109
+ assert json.loads(path.read_text()) == ENDPOINT
110
+ assert list(tmp_path.iterdir()) == [path]
111
+
112
+
67
113
  def test_429_uses_stale_endpoint_before_status(monkeypatch, tmp_path):
68
114
  save(tmp_path, 'last-usage.json', ENDPOINT, 600)
69
115
  save(tmp_path, 'last-statusline.json', STATUS, 120)
@@ -104,12 +150,22 @@ def test_no_rate_limits_pro_max_message(monkeypatch, tmp_path):
104
150
  api.usage()
105
151
 
106
152
 
107
- def test_urlerror_reason(monkeypatch):
108
- def get(*args):
109
- raise urllib.error.URLError('offline')
110
- monkeypatch.setattr(api, '_get_json', get)
111
- with pytest.raises(RuntimeError, match='; offline;'):
112
- api.usage()
153
+ def test_cache_removed_after_stat_is_reported_missing(monkeypatch, tmp_path):
154
+ last = save(tmp_path, 'last-usage.json', ENDPOINT)
155
+ status = save(tmp_path, 'last-statusline.json', STATUS)
156
+ real_stat = Path.stat
157
+
158
+ def stat_then_unlink(self, *args, **kwargs):
159
+ info = real_stat(self, *args, **kwargs)
160
+ if self in (last, status):
161
+ self.unlink()
162
+ return info
163
+
164
+ monkeypatch.setattr(Path, 'stat', stat_then_unlink)
165
+ with pytest.raises(RuntimeError, match='^no saved endpoint answer yet$'):
166
+ api.from_last(tmp_path, api.MAX_AGE)
167
+ with pytest.raises(RuntimeError, match='^no status-line cache yet'):
168
+ api.from_cache(tmp_path)
113
169
 
114
170
 
115
171
  def test_invalid_endpoint_cache_falls_through(monkeypatch, tmp_path):
@@ -137,28 +193,49 @@ def test_cli_status_source_details_and_raw(monkeypatch, tmp_path, capsys):
137
193
  assert json.loads(capsys.readouterr().out) == STATUS
138
194
 
139
195
 
140
- def test_get_json_uses_urllib(monkeypatch, local_only):
141
- # Exercise the real HTTP seam with an in-memory response, never a socket.
142
- import io
143
- def urlopen(request, timeout):
196
+ @pytest.mark.parametrize('code,reason', [(200, 'OK'), (302, 'Found')])
197
+ def test_get_json_uses_urllib_without_redirects(monkeypatch, local_only, code, reason):
198
+ # Mock the transport so urllib can handle the response without opening a socket.
199
+ def https_open(self, request):
144
200
  assert request.full_url == api.URL
145
201
  assert request.get_method() == 'GET'
146
202
  assert request.get_header('Authorization') == 'Bearer test'
147
- assert timeout == 15
148
- return io.StringIO(json.dumps(ENDPOINT))
149
- monkeypatch.setattr(api.urllib.request, 'urlopen', urlopen)
150
- assert local_only(api.URL, {'Authorization': 'Bearer test'}, 15) == ENDPOINT
151
-
203
+ assert request.timeout == 15
204
+ response = urllib.response.addinfourl(
205
+ io.BytesIO(json.dumps(ENDPOINT).encode('utf-8')),
206
+ {'location': 'https://example.invalid/usage'}, request.full_url, code,
207
+ )
208
+ response.msg = reason
209
+ return response
210
+
211
+ monkeypatch.setattr(urllib.request, 'getproxies', lambda: {})
212
+ monkeypatch.setattr(urllib.request.HTTPSHandler, 'https_open', https_open)
213
+ headers = {'Authorization': 'Bearer test'}
214
+ if code == 200:
215
+ assert local_only(api.URL, headers, 15) == ENDPOINT
216
+ else:
217
+ with pytest.raises(urllib.error.HTTPError) as exc:
218
+ local_only(api.URL, headers, 15)
219
+ assert (exc.value.code, exc.value.url) == (code, api.URL)
220
+
221
+
222
+ @pytest.mark.parametrize('error,message', [
223
+ (urllib.error.URLError('Bearer PRIVATE-TOKEN'), 'could not reach'),
224
+ (OSError('Bearer PRIVATE-TOKEN'), 'could not reach'),
225
+ (TimeoutError('Bearer PRIVATE-TOKEN'), 'could not reach'),
226
+ (http.client.HTTPException('Bearer PRIVATE-TOKEN'), 'could not reach'),
227
+ (ValueError("Invalid header value b'Bearer PRIVATE-TOKEN'"), 'invalid request or JSON response from'),
228
+ ])
229
+ def test_request_errors_never_print_credentials(monkeypatch, capsys, error, message):
230
+ def get(*args):
231
+ raise error
152
232
 
153
- def test_request_errors_never_print_credentials(monkeypatch, capsys):
154
- def invalid_header(*args):
155
- raise ValueError("Invalid header value b'Bearer PRIVATE-TOKEN'")
156
- monkeypatch.setattr(api, '_get_json', invalid_header)
233
+ monkeypatch.setattr(api, '_get_json', get)
157
234
  assert cli.main(['-v']) == 1
158
235
  captured = capsys.readouterr()
159
236
  assert 'PRIVATE-TOKEN' not in captured.out + captured.err
160
237
  assert 'Bearer' not in captured.err
161
- assert 'invalid request or JSON response' in captured.err
238
+ assert f'{message} {api.URL}' in captured.err
162
239
 
163
240
 
164
241
  @pytest.mark.parametrize('subscription,tier,expected', [