taxformatter 0.1.1__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.
@@ -0,0 +1,75 @@
1
+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
+
3
+ # dependencies
4
+ /node_modules
5
+ /.pnp
6
+ .pnp.*
7
+ .yarn/*
8
+ !.yarn/patches
9
+ !.yarn/plugins
10
+ !.yarn/releases
11
+ !.yarn/versions
12
+
13
+ # testing
14
+ /coverage
15
+
16
+ # next.js
17
+ /.next/
18
+ /out/
19
+
20
+ # contentlayer (generated cache)
21
+ .contentlayer/
22
+
23
+ # production
24
+ /build
25
+
26
+ # misc
27
+ .DS_Store
28
+ *.pem
29
+ .mcp.json
30
+
31
+ # debug
32
+ npm-debug.log*
33
+ yarn-debug.log*
34
+ yarn-error.log*
35
+ .pnpm-debug.log*
36
+
37
+ # env files (can opt-in for committing if needed)
38
+ .env*
39
+ # Allow example templates so the expected layout is documented in git
40
+ !.env.example
41
+ !.env.test.local.example
42
+
43
+ # vercel
44
+ .vercel
45
+
46
+ # typescript
47
+ *.tsbuildinfo
48
+ next-env.d.ts
49
+
50
+ /generated/prisma
51
+
52
+ # Terraform
53
+ terraform.tfvars
54
+ *.tfstate
55
+ *.tfstate.*
56
+ .terraform/
57
+ .terraform.lock.hcl
58
+
59
+ # Backend build artifacts
60
+ backend/.build/
61
+ backend/**/__pycache__/
62
+ backend/**/*.pyc
63
+ *.zip
64
+
65
+ # Debug scripts
66
+ backend/debug_*.py
67
+
68
+ # Sentry Config File
69
+ .env.sentry-build-plugin
70
+
71
+ # Package build artifacts
72
+ packages/*/dist/
73
+ packages/*/node_modules/
74
+ packages/*/package-lock.json
75
+ __pycache__/
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 (2026-04-22)
4
+
5
+ - Rename PyPI package from `taxformatter-sdk` to `taxformatter` so the pip install name matches the import name. No code changes.
6
+
7
+ ## 0.1.0 (2026-03-24)
8
+
9
+ Initial release.
10
+
11
+ - `TaxFormatter` client: parse, list_sources, get_usage, health
12
+ - Accepts file path, Path, or bytes
13
+ - Auto-retry on 429 with exponential backoff (max 3)
14
+ - Typed errors: AuthenticationError, RateLimitError, ParseError
15
+ - TypedDict response types
16
+ - Python 3.8+, single dependency: requests
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TaxFormatter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: taxformatter
3
+ Version: 0.1.1
4
+ Summary: Official Python SDK for the TaxFormatter API — parse crypto CSVs and bank statement PDFs
5
+ Project-URL: Homepage, https://taxformatter.com
6
+ Project-URL: Documentation, https://taxformatter.com/docs/api
7
+ Project-URL: Repository, https://github.com/Sean-Bravo/trw
8
+ Project-URL: Issues, https://github.com/Sean-Bravo/trw/issues
9
+ Author-email: TaxFormatter <support@taxformatter.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: bank-statement,crypto-tax,csv-parser,pdf-parser,taxformatter
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Requires-Python: >=3.8
23
+ Requires-Dist: requests>=2.28
24
+ Description-Content-Type: text/markdown
25
+
26
+ # taxformatter
27
+
28
+ Official Python SDK for the [TaxFormatter API](https://taxformatter.com) — parse crypto exchange CSVs and bank statement PDFs programmatically.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ pip install taxformatter
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ```python
39
+ from taxformatter import TaxFormatter
40
+
41
+ tf = TaxFormatter("tf_live_xxx")
42
+
43
+ # Parse a file by path
44
+ result = tf.parse("./coinbase_2025.csv")
45
+
46
+ # Parse bytes with options
47
+ result = tf.parse(raw_bytes, filename="coinbase.csv", output_format="turbotax")
48
+
49
+ # List supported sources
50
+ sources = tf.list_sources()
51
+
52
+ # Check usage
53
+ usage = tf.get_usage()
54
+ ```
55
+
56
+ ## Configuration
57
+
58
+ ```python
59
+ tf = TaxFormatter(
60
+ "tf_live_xxx",
61
+ base_url="https://api.taxformatter.com", # default
62
+ timeout=30, # seconds, default
63
+ max_retries=3, # auto-retry on 429, default
64
+ )
65
+ ```
66
+
67
+ ## Error Handling
68
+
69
+ ```python
70
+ from taxformatter import TaxFormatter, AuthenticationError, RateLimitError, ParseError
71
+
72
+ try:
73
+ result = tf.parse("./file.csv")
74
+ except AuthenticationError:
75
+ # 401 — invalid or missing API key
76
+ pass
77
+ except RateLimitError as e:
78
+ # 429 — rate limited (auto-retried 3 times before raising)
79
+ print(e.retry_after)
80
+ except ParseError as e:
81
+ # 422 — file could not be parsed
82
+ print(e.suggestion)
83
+ ```
84
+
85
+ ## API
86
+
87
+ ### `tf.parse(input, filename=None, output_format=None, exchange=None, bank=None)`
88
+ Parse a crypto CSV or bank statement PDF.
89
+
90
+ - **input**: File path (`str`/`Path`) or `bytes`
91
+ - **filename**: Required when passing bytes
92
+ - **output_format**: `"koinly"`, `"turbotax"`, `"coinledger"`, or `"zenledger"`
93
+ - **exchange**: Force exchange detection (e.g., `"coinbase"`)
94
+ - **bank**: Force bank detection (e.g., `"chase"`)
95
+
96
+ ### `tf.list_sources()`
97
+ List all supported crypto exchanges and banks.
98
+
99
+ ### `tf.get_usage()`
100
+ Get current month's API usage.
101
+
102
+ ### `tf.health()`
103
+ Check API health status.
104
+
105
+ ## License
106
+
107
+ MIT
@@ -0,0 +1,82 @@
1
+ # taxformatter
2
+
3
+ Official Python SDK for the [TaxFormatter API](https://taxformatter.com) — parse crypto exchange CSVs and bank statement PDFs programmatically.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install taxformatter
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```python
14
+ from taxformatter import TaxFormatter
15
+
16
+ tf = TaxFormatter("tf_live_xxx")
17
+
18
+ # Parse a file by path
19
+ result = tf.parse("./coinbase_2025.csv")
20
+
21
+ # Parse bytes with options
22
+ result = tf.parse(raw_bytes, filename="coinbase.csv", output_format="turbotax")
23
+
24
+ # List supported sources
25
+ sources = tf.list_sources()
26
+
27
+ # Check usage
28
+ usage = tf.get_usage()
29
+ ```
30
+
31
+ ## Configuration
32
+
33
+ ```python
34
+ tf = TaxFormatter(
35
+ "tf_live_xxx",
36
+ base_url="https://api.taxformatter.com", # default
37
+ timeout=30, # seconds, default
38
+ max_retries=3, # auto-retry on 429, default
39
+ )
40
+ ```
41
+
42
+ ## Error Handling
43
+
44
+ ```python
45
+ from taxformatter import TaxFormatter, AuthenticationError, RateLimitError, ParseError
46
+
47
+ try:
48
+ result = tf.parse("./file.csv")
49
+ except AuthenticationError:
50
+ # 401 — invalid or missing API key
51
+ pass
52
+ except RateLimitError as e:
53
+ # 429 — rate limited (auto-retried 3 times before raising)
54
+ print(e.retry_after)
55
+ except ParseError as e:
56
+ # 422 — file could not be parsed
57
+ print(e.suggestion)
58
+ ```
59
+
60
+ ## API
61
+
62
+ ### `tf.parse(input, filename=None, output_format=None, exchange=None, bank=None)`
63
+ Parse a crypto CSV or bank statement PDF.
64
+
65
+ - **input**: File path (`str`/`Path`) or `bytes`
66
+ - **filename**: Required when passing bytes
67
+ - **output_format**: `"koinly"`, `"turbotax"`, `"coinledger"`, or `"zenledger"`
68
+ - **exchange**: Force exchange detection (e.g., `"coinbase"`)
69
+ - **bank**: Force bank detection (e.g., `"chase"`)
70
+
71
+ ### `tf.list_sources()`
72
+ List all supported crypto exchanges and banks.
73
+
74
+ ### `tf.get_usage()`
75
+ Get current month's API usage.
76
+
77
+ ### `tf.health()`
78
+ Check API health status.
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "taxformatter"
7
+ version = "0.1.1"
8
+ description = "Official Python SDK for the TaxFormatter API — parse crypto CSVs and bank statement PDFs"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.8"
12
+ authors = [{ name = "TaxFormatter", email = "support@taxformatter.com" }]
13
+ keywords = ["taxformatter", "crypto-tax", "csv-parser", "bank-statement", "pdf-parser"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.8",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ ]
25
+ dependencies = ["requests>=2.28"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://taxformatter.com"
29
+ Documentation = "https://taxformatter.com/docs/api"
30
+ Repository = "https://github.com/Sean-Bravo/trw"
31
+ Issues = "https://github.com/Sean-Bravo/trw/issues"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["taxformatter"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
@@ -0,0 +1,13 @@
1
+ """TaxFormatter Python SDK — parse crypto CSVs and bank statement PDFs."""
2
+
3
+ from .client import TaxFormatter
4
+ from .errors import TaxFormatterError, AuthenticationError, RateLimitError, ParseError
5
+
6
+ __version__ = "0.1.1"
7
+ __all__ = [
8
+ "TaxFormatter",
9
+ "TaxFormatterError",
10
+ "AuthenticationError",
11
+ "RateLimitError",
12
+ "ParseError",
13
+ ]
@@ -0,0 +1,138 @@
1
+ """TaxFormatter API client."""
2
+
3
+ import base64
4
+ import time
5
+ from pathlib import Path
6
+ from typing import Any, Dict, Optional, Union
7
+
8
+ import requests
9
+
10
+ from .errors import TaxFormatterError, AuthenticationError, RateLimitError, ParseError
11
+ from .types import ParseResponse, SourcesResponse, UsageResponse, HealthResponse
12
+
13
+ DEFAULT_BASE_URL = "https://api.taxformatter.com"
14
+ DEFAULT_TIMEOUT = 30
15
+ DEFAULT_MAX_RETRIES = 3
16
+
17
+
18
+ class TaxFormatter:
19
+ """Client for the TaxFormatter API.
20
+
21
+ Args:
22
+ api_key: Your TaxFormatter API key (tf_live_xxx).
23
+ base_url: API base URL. Default: https://api.taxformatter.com
24
+ timeout: Request timeout in seconds. Default: 30
25
+ max_retries: Max retries on 429. Default: 3
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ api_key: str,
31
+ base_url: str = DEFAULT_BASE_URL,
32
+ timeout: int = DEFAULT_TIMEOUT,
33
+ max_retries: int = DEFAULT_MAX_RETRIES,
34
+ ):
35
+ if not api_key:
36
+ raise ValueError("API key is required")
37
+ self.api_key = api_key
38
+ self.base_url = base_url.rstrip("/")
39
+ self.timeout = timeout
40
+ self.max_retries = max_retries
41
+ self._session = requests.Session()
42
+ self._session.headers.update({
43
+ "Content-Type": "application/json",
44
+ "X-API-Key": api_key,
45
+ })
46
+
47
+ def _request(self, method: str, path: str, json: Optional[Dict] = None, attempt: int = 1) -> Any:
48
+ """Make an API request with auto-retry on 429."""
49
+ try:
50
+ resp = self._session.request(
51
+ method,
52
+ f"{self.base_url}{path}",
53
+ json=json,
54
+ timeout=self.timeout,
55
+ )
56
+ except requests.Timeout:
57
+ raise TaxFormatterError("timeout", f"Request timed out after {self.timeout}s", 408)
58
+ except requests.ConnectionError as e:
59
+ raise TaxFormatterError("connection_error", str(e), 0)
60
+
61
+ data = resp.json()
62
+
63
+ if resp.ok:
64
+ return data
65
+
66
+ # Auto-retry on 429
67
+ if resp.status_code == 429 and attempt < self.max_retries:
68
+ retry_after = int(resp.headers.get("Retry-After", 0)) or (2 ** attempt)
69
+ time.sleep(retry_after)
70
+ return self._request(method, path, json=json, attempt=attempt + 1)
71
+
72
+ # Raise typed errors
73
+ code = data.get("code", "unknown_error")
74
+ message = data.get("message", f"Request failed with status {resp.status_code}")
75
+ suggestion = data.get("suggestion", "")
76
+
77
+ if resp.status_code == 401:
78
+ raise AuthenticationError(message)
79
+ if resp.status_code == 429:
80
+ raise RateLimitError(message, data.get("metadata", {}).get("retry_after_seconds", 0))
81
+ if resp.status_code == 422:
82
+ raise ParseError(code, message, suggestion)
83
+
84
+ raise TaxFormatterError(code, message, resp.status_code, suggestion)
85
+
86
+ def parse(
87
+ self,
88
+ input: Union[str, Path, bytes],
89
+ filename: Optional[str] = None,
90
+ output_format: Optional[str] = None,
91
+ exchange: Optional[str] = None,
92
+ bank: Optional[str] = None,
93
+ ) -> ParseResponse:
94
+ """Parse a crypto CSV or bank statement PDF.
95
+
96
+ Args:
97
+ input: File path (str/Path) or raw bytes.
98
+ filename: Required when passing bytes. Auto-derived from path otherwise.
99
+ output_format: koinly, turbotax, coinledger, or zenledger.
100
+ exchange: Force exchange detection (e.g., "coinbase").
101
+ bank: Force bank detection (e.g., "chase").
102
+ """
103
+ if isinstance(input, (str, Path)):
104
+ path = Path(input)
105
+ file_bytes = path.read_bytes()
106
+ filename = filename or path.name
107
+ elif isinstance(input, bytes):
108
+ file_bytes = input
109
+ if not filename:
110
+ raise ValueError("filename is required when passing bytes")
111
+ else:
112
+ raise TypeError(f"input must be str, Path, or bytes, got {type(input).__name__}")
113
+
114
+ body: Dict[str, str] = {
115
+ "file_content": base64.b64encode(file_bytes).decode(),
116
+ "filename": filename,
117
+ }
118
+
119
+ if output_format:
120
+ body["output_format"] = output_format
121
+ if exchange:
122
+ body["exchange"] = exchange
123
+ if bank:
124
+ body["bank"] = bank
125
+
126
+ return self._request("POST", "/v1/parse", json=body)
127
+
128
+ def list_sources(self) -> SourcesResponse:
129
+ """List all supported crypto exchanges and banks."""
130
+ return self._request("GET", "/v1/sources")
131
+
132
+ def get_usage(self) -> UsageResponse:
133
+ """Get current month's API usage."""
134
+ return self._request("GET", "/v1/usage")
135
+
136
+ def health(self) -> HealthResponse:
137
+ """Check API health status."""
138
+ return self._request("GET", "/v1/health")
@@ -0,0 +1,39 @@
1
+ """Error classes for the TaxFormatter SDK."""
2
+
3
+
4
+ class TaxFormatterError(Exception):
5
+ """Base error for all TaxFormatter API errors."""
6
+
7
+ def __init__(self, code: str, message: str, status_code: int, suggestion: str = ""):
8
+ super().__init__(message)
9
+ self.code = code
10
+ self.status_code = status_code
11
+ self.suggestion = suggestion
12
+
13
+ def __repr__(self) -> str:
14
+ return f"{self.__class__.__name__}(code={self.code!r}, status_code={self.status_code})"
15
+
16
+
17
+ class AuthenticationError(TaxFormatterError):
18
+ """Raised on 401 — invalid or missing API key."""
19
+
20
+ def __init__(self, message: str = "Invalid or missing API key"):
21
+ super().__init__("authentication_error", message, 401)
22
+
23
+
24
+ class RateLimitError(TaxFormatterError):
25
+ """Raised on 429 — rate limit exceeded (after retries exhausted)."""
26
+
27
+ def __init__(self, message: str = "Rate limit exceeded", retry_after: int = 0):
28
+ super().__init__(
29
+ "rate_limited", message, 429,
30
+ suggestion="Wait and retry. Upgrade your tier for higher limits.",
31
+ )
32
+ self.retry_after = retry_after
33
+
34
+
35
+ class ParseError(TaxFormatterError):
36
+ """Raised on 422 — file could not be parsed."""
37
+
38
+ def __init__(self, code: str, message: str, suggestion: str = ""):
39
+ super().__init__(code, message, 422, suggestion)
@@ -0,0 +1,66 @@
1
+ """Type definitions for TaxFormatter API responses."""
2
+
3
+ from typing import Any, Dict, List, Optional
4
+ try:
5
+ from typing import TypedDict
6
+ except ImportError:
7
+ from typing_extensions import TypedDict
8
+
9
+
10
+ class Metadata(TypedDict, total=False):
11
+ transaction_count: int
12
+ processing_time_ms: int
13
+ api_version: str
14
+
15
+
16
+ class ParseResponse(TypedDict, total=False):
17
+ status: str
18
+ summary: str
19
+ detected_source: str
20
+ source_type: str
21
+ output_format: str
22
+ transactions: List[Dict[str, Any]]
23
+ warnings: List[str]
24
+ metadata: Metadata
25
+ code: str
26
+ message: str
27
+ suggestion: str
28
+
29
+
30
+ class SourceInfo(TypedDict):
31
+ id: str
32
+ name: str
33
+
34
+
35
+ class OutputFormats(TypedDict):
36
+ crypto: List[str]
37
+ bank: List[str]
38
+
39
+
40
+ class SourcesResponse(TypedDict):
41
+ crypto_exchanges: List[SourceInfo]
42
+ banks: List[SourceInfo]
43
+ output_formats: OutputFormats
44
+
45
+
46
+ class MonthUsage(TypedDict):
47
+ file_count: int
48
+ request_count: int
49
+
50
+
51
+ class KeyUsage(TypedDict):
52
+ key_id: str
53
+ key_name: str
54
+ tier: str
55
+ monthly_quota: int
56
+ current_month: MonthUsage
57
+
58
+
59
+ class UsageResponse(TypedDict):
60
+ usage: List[KeyUsage]
61
+
62
+
63
+ class HealthResponse(TypedDict):
64
+ status: str
65
+ version: str
66
+ environment: str
File without changes
@@ -0,0 +1,220 @@
1
+ """Tests for the TaxFormatter Python SDK."""
2
+
3
+ import json
4
+ from unittest.mock import patch, MagicMock
5
+ import pytest
6
+ from taxformatter import TaxFormatter, TaxFormatterError, AuthenticationError, RateLimitError, ParseError
7
+
8
+
9
+ def mock_response(status_code, body, headers=None):
10
+ """Create a mock requests.Response."""
11
+ resp = MagicMock()
12
+ resp.status_code = status_code
13
+ resp.ok = 200 <= status_code < 300
14
+ resp.json.return_value = body
15
+ resp.headers = headers or {}
16
+ return resp
17
+
18
+
19
+ class TestInit:
20
+ def test_requires_api_key(self):
21
+ with pytest.raises(ValueError, match="API key is required"):
22
+ TaxFormatter("")
23
+
24
+ def test_default_options(self):
25
+ tf = TaxFormatter("tf_live_xxx")
26
+ assert tf.base_url == "https://api.taxformatter.com"
27
+ assert tf.timeout == 30
28
+ assert tf.max_retries == 3
29
+
30
+ def test_custom_options(self):
31
+ tf = TaxFormatter("tf_live_xxx", base_url="https://custom.api.com", timeout=5, max_retries=1)
32
+ assert tf.base_url == "https://custom.api.com"
33
+ assert tf.timeout == 5
34
+ assert tf.max_retries == 1
35
+
36
+
37
+ class TestParse:
38
+ @patch("taxformatter.client.requests.Session")
39
+ def test_sends_base64(self, MockSession):
40
+ session = MockSession.return_value
41
+ session.request.return_value = mock_response(200, {
42
+ "status": "success",
43
+ "detected_source": "coinbase",
44
+ "transactions": [{"date": "2025-01-01"}],
45
+ "metadata": {"transaction_count": 1},
46
+ })
47
+
48
+ tf = TaxFormatter("tf_live_xxx")
49
+ result = tf.parse(b"csv,data", filename="coinbase.csv")
50
+
51
+ assert result["status"] == "success"
52
+ assert result["detected_source"] == "coinbase"
53
+ call_args = session.request.call_args
54
+ body = call_args[1]["json"] if "json" in call_args[1] else call_args[0][2] if len(call_args[0]) > 2 else None
55
+ assert body is not None
56
+ assert body["filename"] == "coinbase.csv"
57
+
58
+ @patch("taxformatter.client.requests.Session")
59
+ def test_passes_options(self, MockSession):
60
+ session = MockSession.return_value
61
+ session.request.return_value = mock_response(200, {"status": "success"})
62
+
63
+ tf = TaxFormatter("tf_live_xxx")
64
+ tf.parse(b"data", filename="file.csv", output_format="turbotax", exchange="binance")
65
+
66
+ call_args = session.request.call_args
67
+ body = call_args[1].get("json", {})
68
+ assert body.get("output_format") == "turbotax"
69
+ assert body.get("exchange") == "binance"
70
+
71
+ @patch("taxformatter.client.requests.Session")
72
+ def test_requires_filename_for_bytes(self, MockSession):
73
+ tf = TaxFormatter("tf_live_xxx")
74
+ with pytest.raises(ValueError, match="filename is required"):
75
+ tf.parse(b"data")
76
+
77
+ @patch("taxformatter.client.requests.Session")
78
+ def test_auth_error(self, MockSession):
79
+ session = MockSession.return_value
80
+ session.request.return_value = mock_response(401, {
81
+ "code": "invalid_api_key",
82
+ "message": "Invalid or revoked API key.",
83
+ })
84
+
85
+ tf = TaxFormatter("bad_key")
86
+ with pytest.raises(AuthenticationError):
87
+ tf.parse(b"data", filename="file.csv")
88
+
89
+ @patch("taxformatter.client.requests.Session")
90
+ def test_parse_error(self, MockSession):
91
+ session = MockSession.return_value
92
+ session.request.return_value = mock_response(422, {
93
+ "code": "parse_error",
94
+ "message": "Could not detect exchange",
95
+ "suggestion": "Specify the exchange parameter",
96
+ })
97
+
98
+ tf = TaxFormatter("tf_live_xxx")
99
+ with pytest.raises(ParseError) as exc_info:
100
+ tf.parse(b"data", filename="file.csv")
101
+ assert exc_info.value.suggestion == "Specify the exchange parameter"
102
+
103
+ @patch("taxformatter.client.requests.Session")
104
+ @patch("taxformatter.client.time.sleep")
105
+ def test_retries_on_429(self, mock_sleep, MockSession):
106
+ session = MockSession.return_value
107
+ session.request.side_effect = [
108
+ mock_response(429, {
109
+ "code": "rate_limited",
110
+ "message": "Rate limit exceeded",
111
+ }, {"Retry-After": "1"}),
112
+ mock_response(200, {"status": "success"}),
113
+ ]
114
+
115
+ tf = TaxFormatter("tf_live_xxx", max_retries=2)
116
+ result = tf.parse(b"data", filename="file.csv")
117
+
118
+ assert result["status"] == "success"
119
+ assert session.request.call_count == 2
120
+ mock_sleep.assert_called_once_with(1)
121
+
122
+ @patch("taxformatter.client.requests.Session")
123
+ def test_rate_limit_after_max_retries(self, MockSession):
124
+ session = MockSession.return_value
125
+ session.request.return_value = mock_response(429, {
126
+ "code": "rate_limited",
127
+ "message": "Rate limit exceeded",
128
+ "metadata": {"retry_after_seconds": 60},
129
+ }, {"Retry-After": "0"})
130
+
131
+ tf = TaxFormatter("tf_live_xxx", max_retries=1)
132
+ with pytest.raises(RateLimitError) as exc_info:
133
+ tf.parse(b"data", filename="file.csv")
134
+ assert exc_info.value.retry_after == 60
135
+
136
+ @patch("taxformatter.client.requests.Session")
137
+ def test_server_error(self, MockSession):
138
+ session = MockSession.return_value
139
+ session.request.return_value = mock_response(500, {
140
+ "code": "internal_error",
141
+ "message": "Internal server error",
142
+ })
143
+
144
+ tf = TaxFormatter("tf_live_xxx")
145
+ with pytest.raises(TaxFormatterError) as exc_info:
146
+ tf.parse(b"data", filename="file.csv")
147
+ assert exc_info.value.status_code == 500
148
+
149
+
150
+ class TestListSources:
151
+ @patch("taxformatter.client.requests.Session")
152
+ def test_returns_sources(self, MockSession):
153
+ session = MockSession.return_value
154
+ session.request.return_value = mock_response(200, {
155
+ "crypto_exchanges": [{"id": "coinbase", "name": "Coinbase"}],
156
+ "banks": [{"id": "chase", "name": "Chase"}],
157
+ "output_formats": {"crypto": ["koinly"], "bank": ["csv"]},
158
+ })
159
+
160
+ tf = TaxFormatter("tf_live_xxx")
161
+ result = tf.list_sources()
162
+ assert len(result["crypto_exchanges"]) == 1
163
+ assert len(result["banks"]) == 1
164
+
165
+
166
+ class TestGetUsage:
167
+ @patch("taxformatter.client.requests.Session")
168
+ def test_returns_usage(self, MockSession):
169
+ session = MockSession.return_value
170
+ session.request.return_value = mock_response(200, {
171
+ "usage": [{"key_id": "k1", "key_name": "test", "tier": "starter", "monthly_quota": 100, "current_month": {"file_count": 5, "request_count": 10}}],
172
+ })
173
+
174
+ tf = TaxFormatter("tf_live_xxx")
175
+ result = tf.get_usage()
176
+ assert len(result["usage"]) == 1
177
+ assert result["usage"][0]["tier"] == "starter"
178
+
179
+
180
+ class TestHealth:
181
+ @patch("taxformatter.client.requests.Session")
182
+ def test_returns_health(self, MockSession):
183
+ session = MockSession.return_value
184
+ session.request.return_value = mock_response(200, {
185
+ "status": "ok",
186
+ "version": "2026-03-01",
187
+ "environment": "prod",
188
+ })
189
+
190
+ tf = TaxFormatter("tf_live_xxx")
191
+ result = tf.health()
192
+ assert result["status"] == "ok"
193
+
194
+
195
+ class TestErrors:
196
+ def test_base_error(self):
197
+ err = TaxFormatterError("test", "msg", 400, "suggestion")
198
+ assert err.code == "test"
199
+ assert err.status_code == 400
200
+ assert err.suggestion == "suggestion"
201
+ assert str(err) == "msg"
202
+
203
+ def test_auth_error_defaults(self):
204
+ err = AuthenticationError()
205
+ assert err.status_code == 401
206
+ assert err.code == "authentication_error"
207
+
208
+ def test_rate_limit_error(self):
209
+ err = RateLimitError("limit", 60)
210
+ assert err.status_code == 429
211
+ assert err.retry_after == 60
212
+
213
+ def test_parse_error(self):
214
+ err = ParseError("parse_error", "bad file", "try again")
215
+ assert err.status_code == 422
216
+ assert err.suggestion == "try again"
217
+
218
+ def test_error_repr(self):
219
+ err = TaxFormatterError("test", "msg", 400)
220
+ assert "TaxFormatterError" in repr(err)