notefeed 0.2.0__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.
- notefeed-0.2.0/.gitignore +60 -0
- notefeed-0.2.0/LICENSE +21 -0
- notefeed-0.2.0/PKG-INFO +37 -0
- notefeed-0.2.0/README.md +21 -0
- notefeed-0.2.0/pyproject.toml +28 -0
- notefeed-0.2.0/src/notefeed/__init__.py +9 -0
- notefeed-0.2.0/src/notefeed/cli.py +63 -0
- notefeed-0.2.0/src/notefeed/client.py +93 -0
- notefeed-0.2.0/tests/conftest.py +49 -0
- notefeed-0.2.0/tests/test_cli.py +103 -0
- notefeed-0.2.0/tests/test_client.py +120 -0
- notefeed-0.2.0/tests/test_version.py +18 -0
|
@@ -0,0 +1,60 @@
|
|
|
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
|
+
# production
|
|
21
|
+
/build
|
|
22
|
+
|
|
23
|
+
# misc
|
|
24
|
+
.DS_Store
|
|
25
|
+
*.pem
|
|
26
|
+
|
|
27
|
+
# debug
|
|
28
|
+
npm-debug.log*
|
|
29
|
+
yarn-debug.log*
|
|
30
|
+
yarn-error.log*
|
|
31
|
+
.pnpm-debug.log*
|
|
32
|
+
|
|
33
|
+
# env files (can opt-in for committing if needed)
|
|
34
|
+
.env*
|
|
35
|
+
|
|
36
|
+
# vercel
|
|
37
|
+
.vercel
|
|
38
|
+
|
|
39
|
+
# typescript
|
|
40
|
+
*.tsbuildinfo
|
|
41
|
+
next-env.d.ts
|
|
42
|
+
|
|
43
|
+
# superpowers scratch
|
|
44
|
+
/.superpowers/
|
|
45
|
+
/.playwright-mcp/
|
|
46
|
+
!.env.example
|
|
47
|
+
|
|
48
|
+
# Superpowers specs/plans are local working notes; decisions are recorded as ADRs (/ccp:ship-pr).
|
|
49
|
+
/docs/superpowers/
|
|
50
|
+
/site/
|
|
51
|
+
/.venv-docs/
|
|
52
|
+
/data/
|
|
53
|
+
/.dev/
|
|
54
|
+
|
|
55
|
+
# Client packages
|
|
56
|
+
/packages/python/dist/
|
|
57
|
+
__pycache__/
|
|
58
|
+
*.egg-info/
|
|
59
|
+
/packages/js/dist/
|
|
60
|
+
/packages/js/node_modules/
|
notefeed-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Marcel Bruckner
|
|
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.
|
notefeed-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: notefeed
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Post markdown notes to a notefeed server, from Python or the command line.
|
|
5
|
+
Project-URL: Documentation, https://marceltov.github.io/notefeed/clients/
|
|
6
|
+
Project-URL: Source, https://github.com/Marceltov/notefeed
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Communications
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Provides-Extra: test
|
|
14
|
+
Requires-Dist: pytest>=9; extra == 'test'
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# notefeed
|
|
18
|
+
|
|
19
|
+
Post markdown notes to a [notefeed](https://github.com/Marceltov/notefeed) server from Python or the command line. No dependencies.
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
pip install notefeed
|
|
23
|
+
export NOTEFEED_URL=https://notes.example.com NOTEFEED_TOKEN=...
|
|
24
|
+
notefeed post "# Backup finished"
|
|
25
|
+
backup.sh 2>&1 | notefeed post -
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from notefeed import Client
|
|
30
|
+
|
|
31
|
+
client = Client("https://notes.example.com", token) # URL and token set once
|
|
32
|
+
print(client.post("# Deploy done\nversion 1.4.2").url)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The `notefeed` command reads `--url` / `--token`, or `NOTEFEED_URL` / `NOTEFEED_TOKEN`. The library itself never reads the environment.
|
|
36
|
+
|
|
37
|
+
Full documentation: https://marceltov.github.io/notefeed/clients/
|
notefeed-0.2.0/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# notefeed
|
|
2
|
+
|
|
3
|
+
Post markdown notes to a [notefeed](https://github.com/Marceltov/notefeed) server from Python or the command line. No dependencies.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install notefeed
|
|
7
|
+
export NOTEFEED_URL=https://notes.example.com NOTEFEED_TOKEN=...
|
|
8
|
+
notefeed post "# Backup finished"
|
|
9
|
+
backup.sh 2>&1 | notefeed post -
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
from notefeed import Client
|
|
14
|
+
|
|
15
|
+
client = Client("https://notes.example.com", token) # URL and token set once
|
|
16
|
+
print(client.post("# Deploy done\nversion 1.4.2").url)
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The `notefeed` command reads `--url` / `--token`, or `NOTEFEED_URL` / `NOTEFEED_TOKEN`. The library itself never reads the environment.
|
|
20
|
+
|
|
21
|
+
Full documentation: https://marceltov.github.io/notefeed/clients/
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "notefeed"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Post markdown notes to a notefeed server, from Python or the command line."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = []
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Environment :: Console",
|
|
17
|
+
"Topic :: Communications",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.optional-dependencies]
|
|
21
|
+
test = ["pytest>=9"]
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
notefeed = "notefeed.cli:main"
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Documentation = "https://marceltov.github.io/notefeed/clients/"
|
|
28
|
+
Source = "https://github.com/Marceltov/notefeed"
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Post markdown notes to a notefeed server."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version as _version
|
|
4
|
+
|
|
5
|
+
__version__ = _version("notefeed")
|
|
6
|
+
|
|
7
|
+
from .client import AuthError, Client, ConfigError, InvalidNoteError, Note, NotefeedError, NoteTooLargeError # noqa: E402
|
|
8
|
+
|
|
9
|
+
__all__ = ["AuthError", "Client", "ConfigError", "InvalidNoteError", "Note", "NotefeedError", "NoteTooLargeError"]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""`notefeed post ...` — post a note from the command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .client import Client, ConfigError, NotefeedError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def main(argv: list[str] | None = None) -> int:
|
|
14
|
+
parser = argparse.ArgumentParser(prog="notefeed", description="Post markdown notes to notefeed.")
|
|
15
|
+
parser.add_argument("--version", action="version", version=f"notefeed {__version__}")
|
|
16
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
17
|
+
p = sub.add_parser("post", help="post a note; prints its URL")
|
|
18
|
+
p.add_argument("text", nargs="?", help='the markdown, or "-" to read stdin')
|
|
19
|
+
p.add_argument("--file", help="read the markdown from this file")
|
|
20
|
+
p.add_argument("--url", help="notefeed base URL (default: $NOTEFEED_URL)")
|
|
21
|
+
p.add_argument("--token", help="API token (default: $NOTEFEED_TOKEN)")
|
|
22
|
+
args = parser.parse_args(argv)
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
markdown = _read(args)
|
|
26
|
+
url = args.url or os.environ.get("NOTEFEED_URL")
|
|
27
|
+
token = args.token or os.environ.get("NOTEFEED_TOKEN")
|
|
28
|
+
if not url:
|
|
29
|
+
raise _UsageError("no URL given; pass --url or set NOTEFEED_URL")
|
|
30
|
+
if not token:
|
|
31
|
+
raise _UsageError("no token given; pass --token or set NOTEFEED_TOKEN")
|
|
32
|
+
note = Client(url, token).post(markdown)
|
|
33
|
+
except (ConfigError, _UsageError) as e:
|
|
34
|
+
print(f"notefeed: {e}", file=sys.stderr)
|
|
35
|
+
return 2
|
|
36
|
+
except NotefeedError as e:
|
|
37
|
+
print(f"notefeed: {e}", file=sys.stderr)
|
|
38
|
+
return 1
|
|
39
|
+
print(note.url)
|
|
40
|
+
return 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _UsageError(Exception):
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _read(args: argparse.Namespace) -> str:
|
|
48
|
+
if args.file:
|
|
49
|
+
try:
|
|
50
|
+
with open(args.file, "rb") as f:
|
|
51
|
+
return f.read().decode("utf-8")
|
|
52
|
+
except OSError as e:
|
|
53
|
+
raise _UsageError(f"cannot read {args.file}: {e.strerror}") from None
|
|
54
|
+
except UnicodeDecodeError:
|
|
55
|
+
raise _UsageError(f"{args.file} is not UTF-8") from None
|
|
56
|
+
if args.text == "-":
|
|
57
|
+
try:
|
|
58
|
+
return sys.stdin.buffer.read().decode("utf-8")
|
|
59
|
+
except UnicodeDecodeError:
|
|
60
|
+
raise _UsageError("stdin is not UTF-8") from None
|
|
61
|
+
if args.text is None:
|
|
62
|
+
raise _UsageError('give the note text, "-" for stdin, or --file PATH')
|
|
63
|
+
return args.text
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""A tiny client for notefeed's POST /api/notes. Standard library only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import http.client
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Note:
|
|
15
|
+
id: str
|
|
16
|
+
url: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class NotefeedError(Exception):
|
|
20
|
+
"""Any failure talking to notefeed. `status` is the HTTP status, or None (network, config)."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, message: str, status: int | None = None):
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.status = status
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ConfigError(NotefeedError):
|
|
28
|
+
"""URL or token missing."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class InvalidNoteError(NotefeedError):
|
|
32
|
+
"""The server rejected the note (400, 415): empty, not UTF-8, wrong type."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AuthError(NotefeedError):
|
|
36
|
+
"""Missing or wrong token (401)."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class NoteTooLargeError(NotefeedError):
|
|
40
|
+
"""The note is over the server's size limit (413)."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_ERRORS = {400: InvalidNoteError, 415: InvalidNoteError, 401: AuthError, 413: NoteTooLargeError}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Client:
|
|
47
|
+
"""A notefeed server. URL and token are set once here; post() takes only the note."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, url: str, token: str, timeout: float = 10.0):
|
|
50
|
+
if not url:
|
|
51
|
+
raise ConfigError("no url given")
|
|
52
|
+
if not (token or "").strip():
|
|
53
|
+
raise ConfigError("no token given")
|
|
54
|
+
self.url = url.rstrip("/")
|
|
55
|
+
self.token = token.strip()
|
|
56
|
+
if re.search(r"[\x00-\x1f\x7f]", self.token):
|
|
57
|
+
# Never echo the value: it would end up in terminals and CI logs.
|
|
58
|
+
raise ConfigError("token contains invalid characters")
|
|
59
|
+
self.timeout = timeout
|
|
60
|
+
|
|
61
|
+
def post(self, markdown: str) -> Note:
|
|
62
|
+
req = urllib.request.Request(
|
|
63
|
+
f"{self.url}/api/notes",
|
|
64
|
+
data=markdown.encode("utf-8"),
|
|
65
|
+
method="POST",
|
|
66
|
+
headers={
|
|
67
|
+
"Authorization": f"Bearer {self.token}",
|
|
68
|
+
"Content-Type": "text/markdown; charset=utf-8",
|
|
69
|
+
},
|
|
70
|
+
)
|
|
71
|
+
try:
|
|
72
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
73
|
+
status, text = res.status, res.read().decode("utf-8", errors="replace")
|
|
74
|
+
except urllib.error.HTTPError as e:
|
|
75
|
+
raise _http_error(e) from None
|
|
76
|
+
except (urllib.error.URLError, http.client.HTTPException, OSError) as e:
|
|
77
|
+
reason = getattr(e, "reason", e)
|
|
78
|
+
raise NotefeedError(f"could not reach {self.url}: {reason}") from None
|
|
79
|
+
try:
|
|
80
|
+
data = json.loads(text)
|
|
81
|
+
return Note(id=data["id"], url=data["url"])
|
|
82
|
+
except (ValueError, KeyError, TypeError):
|
|
83
|
+
raise NotefeedError(f"unexpected response from {self.url} (not a notefeed server?)", status=status) from None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _http_error(e: urllib.error.HTTPError) -> NotefeedError:
|
|
87
|
+
text = e.read().decode("utf-8", errors="replace")
|
|
88
|
+
try:
|
|
89
|
+
message = json.loads(text)["error"]
|
|
90
|
+
except (ValueError, KeyError, TypeError):
|
|
91
|
+
message = f"HTTP {e.code}: {' '.join(text[:200].split())}"
|
|
92
|
+
return _ERRORS.get(e.code, NotefeedError)(message, status=e.code)
|
|
93
|
+
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import threading
|
|
3
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class FakeServer:
|
|
9
|
+
"""A local HTTP server that records requests and answers with queued replies."""
|
|
10
|
+
|
|
11
|
+
def __init__(self):
|
|
12
|
+
self.requests = []
|
|
13
|
+
self.replies = []
|
|
14
|
+
fake = self
|
|
15
|
+
|
|
16
|
+
class Handler(BaseHTTPRequestHandler):
|
|
17
|
+
def do_POST(self):
|
|
18
|
+
body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
|
19
|
+
fake.requests.append({"method": "POST", "path": self.path, "headers": dict(self.headers), "body": body})
|
|
20
|
+
status, payload, ctype = fake.replies.pop(0) if fake.replies else (201, {"id": "i", "url": "u"}, "application/json")
|
|
21
|
+
data = payload.encode() if isinstance(payload, str) else json.dumps(payload).encode()
|
|
22
|
+
self.send_response(status)
|
|
23
|
+
self.send_header("Content-Type", ctype)
|
|
24
|
+
self.send_header("Content-Length", str(len(data)))
|
|
25
|
+
self.end_headers()
|
|
26
|
+
self.wfile.write(data)
|
|
27
|
+
|
|
28
|
+
def log_message(self, *args):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
32
|
+
self.url = f"http://127.0.0.1:{self.httpd.server_port}"
|
|
33
|
+
threading.Thread(target=self.httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()
|
|
34
|
+
|
|
35
|
+
def reply(self, status, payload, ctype="application/json"):
|
|
36
|
+
self.replies.append((status, payload, ctype))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@pytest.fixture
|
|
40
|
+
def server():
|
|
41
|
+
s = FakeServer()
|
|
42
|
+
yield s
|
|
43
|
+
s.httpd.shutdown()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.fixture(autouse=True)
|
|
47
|
+
def clean_env(monkeypatch):
|
|
48
|
+
monkeypatch.delenv("NOTEFEED_URL", raising=False)
|
|
49
|
+
monkeypatch.delenv("NOTEFEED_TOKEN", raising=False)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
from notefeed.cli import main
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_post_text_prints_url(server, capsys):
|
|
8
|
+
server.reply(201, {"id": "i", "url": "https://n.example/n/i"})
|
|
9
|
+
assert main(["post", "hi", "--url", server.url, "--token", "t"]) == 0
|
|
10
|
+
assert capsys.readouterr().out.strip() == "https://n.example/n/i"
|
|
11
|
+
assert server.requests[0]["body"] == b"hi"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_post_stdin(server, monkeypatch):
|
|
15
|
+
monkeypatch.setattr(sys, "stdin", io.TextIOWrapper(io.BytesIO("# from stdin\r\nCafé\n".encode())))
|
|
16
|
+
assert main(["post", "-", "--url", server.url, "--token", "t"]) == 0
|
|
17
|
+
assert server.requests[0]["body"] == "# from stdin\r\nCafé\n".encode()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_post_file(server, tmp_path):
|
|
21
|
+
f = tmp_path / "note.md"
|
|
22
|
+
f.write_bytes("# File\r\nbody\n".encode())
|
|
23
|
+
assert main(["post", "--file", str(f), "--url", server.url, "--token", "t"]) == 0
|
|
24
|
+
assert server.requests[0]["body"] == b"# File\r\nbody\n"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_missing_file_exits_2(capsys, tmp_path):
|
|
28
|
+
assert main(["post", "--file", str(tmp_path / "nope.md"), "--url", "http://x", "--token", "t"]) == 2
|
|
29
|
+
assert capsys.readouterr().err.startswith("notefeed: ")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_no_text_exits_2_without_reading_stdin(capsys):
|
|
33
|
+
assert main(["post", "--url", "http://x", "--token", "t"]) == 2
|
|
34
|
+
assert "notefeed: " in capsys.readouterr().err
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_no_config_exits_2(capsys):
|
|
38
|
+
assert main(["post", "hi"]) == 2
|
|
39
|
+
assert "NOTEFEED_URL" in capsys.readouterr().err
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_server_error_exits_1(server, capsys):
|
|
43
|
+
server.reply(401, {"error": "missing or wrong bearer token"})
|
|
44
|
+
assert main(["post", "hi", "--url", server.url, "--token", "bad"]) == 1
|
|
45
|
+
assert capsys.readouterr().err.strip() == "notefeed: missing or wrong bearer token"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_connection_refused_exits_1_one_line(capsys):
|
|
49
|
+
assert main(["post", "hi", "--url", "http://127.0.0.1:1", "--token", "t"]) == 1
|
|
50
|
+
err = capsys.readouterr().err
|
|
51
|
+
assert err.startswith("notefeed: ") and err.count("\n") == 1
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_version(capsys):
|
|
55
|
+
try:
|
|
56
|
+
main(["--version"])
|
|
57
|
+
except SystemExit as e:
|
|
58
|
+
assert e.code == 0
|
|
59
|
+
import notefeed
|
|
60
|
+
|
|
61
|
+
assert capsys.readouterr().out.strip() == f"notefeed {notefeed.__version__}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_file_not_utf8_exits_2(server, capsys, tmp_path):
|
|
65
|
+
f = tmp_path / "latin1.md"
|
|
66
|
+
f.write_bytes(b"# Caf\xe9\n")
|
|
67
|
+
assert main(["post", "--file", str(f), "--url", server.url, "--token", "t"]) == 2
|
|
68
|
+
assert "not UTF-8" in capsys.readouterr().err
|
|
69
|
+
assert server.requests == []
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_stdin_not_utf8_exits_2(server, capsys, monkeypatch):
|
|
73
|
+
monkeypatch.setattr(sys, "stdin", io.TextIOWrapper(io.BytesIO(b"# Caf\xe9\n")))
|
|
74
|
+
assert main(["post", "-", "--url", server.url, "--token", "t"]) == 2
|
|
75
|
+
assert "not UTF-8" in capsys.readouterr().err
|
|
76
|
+
assert server.requests == []
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_list_item_text(server):
|
|
80
|
+
assert main(["post", "- buy milk", "--url", server.url, "--token", "t"]) == 0
|
|
81
|
+
assert server.requests[0]["body"] == b"- buy milk"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_env_vars(server, monkeypatch):
|
|
85
|
+
monkeypatch.setenv("NOTEFEED_URL", server.url)
|
|
86
|
+
monkeypatch.setenv("NOTEFEED_TOKEN", "envtok")
|
|
87
|
+
assert main(["post", "- buy milk"]) == 0
|
|
88
|
+
req = server.requests[0]
|
|
89
|
+
assert req["headers"]["Authorization"] == "Bearer envtok"
|
|
90
|
+
assert req["body"] == b"- buy milk"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_flags_win_over_env(server, monkeypatch):
|
|
94
|
+
monkeypatch.setenv("NOTEFEED_URL", "http://127.0.0.1:1")
|
|
95
|
+
monkeypatch.setenv("NOTEFEED_TOKEN", "envtok")
|
|
96
|
+
assert main(["post", "hi", "--url", server.url, "--token", "argtok"]) == 0
|
|
97
|
+
assert server.requests[0]["headers"]["Authorization"] == "Bearer argtok"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_no_token_names_flag_and_env(capsys):
|
|
101
|
+
assert main(["post", "hi", "--url", "http://x"]) == 2
|
|
102
|
+
err = capsys.readouterr().err
|
|
103
|
+
assert "--token" in err and "NOTEFEED_TOKEN" in err
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from notefeed import AuthError, Client, ConfigError, InvalidNoteError, Note, NotefeedError, NoteTooLargeError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_post_sends_markdown_and_returns_note(server):
|
|
7
|
+
server.reply(201, {"id": "20260930T100000Z-cafe", "url": "https://n.example/n/20260930T100000Z-cafe"})
|
|
8
|
+
note = Client(server.url, "t").post("# Café\r\nx")
|
|
9
|
+
assert note == Note("20260930T100000Z-cafe", "https://n.example/n/20260930T100000Z-cafe")
|
|
10
|
+
req = server.requests[0]
|
|
11
|
+
assert req["path"] == "/api/notes"
|
|
12
|
+
assert req["headers"]["Authorization"] == "Bearer t"
|
|
13
|
+
assert req["headers"]["Content-Type"] == "text/markdown; charset=utf-8"
|
|
14
|
+
assert req["body"] == "# Café\r\nx".encode()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_trailing_slash_and_subpath(server):
|
|
18
|
+
Client(server.url + "/sub/", "t").post("x")
|
|
19
|
+
assert server.requests[0]["path"] == "/sub/api/notes"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_ignores_environment(server, monkeypatch):
|
|
23
|
+
# The library takes url and token from code only; env vars are the CLI's business.
|
|
24
|
+
monkeypatch.setenv("NOTEFEED_URL", "http://127.0.0.1:1")
|
|
25
|
+
monkeypatch.setenv("NOTEFEED_TOKEN", "envtok")
|
|
26
|
+
Client(server.url, "argtok").post("x")
|
|
27
|
+
assert server.requests[0]["headers"]["Authorization"] == "Bearer argtok"
|
|
28
|
+
with pytest.raises(ConfigError):
|
|
29
|
+
Client("", "")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_missing_url_or_token():
|
|
33
|
+
with pytest.raises(ConfigError, match="url") as e:
|
|
34
|
+
Client("", "t")
|
|
35
|
+
assert e.value.status is None
|
|
36
|
+
with pytest.raises(ConfigError, match="token"):
|
|
37
|
+
Client("http://x", "")
|
|
38
|
+
with pytest.raises(TypeError):
|
|
39
|
+
Client() # both are required arguments
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_no_module_level_post():
|
|
43
|
+
import notefeed
|
|
44
|
+
|
|
45
|
+
assert not hasattr(notefeed, "post")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@pytest.mark.parametrize(
|
|
49
|
+
("status", "error"),
|
|
50
|
+
[(400, InvalidNoteError), (415, InvalidNoteError), (401, AuthError), (413, NoteTooLargeError), (500, NotefeedError)],
|
|
51
|
+
)
|
|
52
|
+
def test_error_mapping(server, status, error):
|
|
53
|
+
server.reply(status, {"error": f"reason {status}"})
|
|
54
|
+
with pytest.raises(NotefeedError) as e:
|
|
55
|
+
Client(server.url, "t").post("x")
|
|
56
|
+
assert type(e.value) is error
|
|
57
|
+
assert e.value.status == status
|
|
58
|
+
assert str(e.value) == f"reason {status}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_non_json_error_body(server):
|
|
62
|
+
server.reply(502, "<html>bad gateway</html>", "text/html")
|
|
63
|
+
with pytest.raises(NotefeedError) as e:
|
|
64
|
+
Client(server.url, "t").post("x")
|
|
65
|
+
assert type(e.value) is NotefeedError
|
|
66
|
+
assert e.value.status == 502
|
|
67
|
+
assert "502" in str(e.value)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_connection_refused():
|
|
71
|
+
with pytest.raises(NotefeedError) as e:
|
|
72
|
+
Client("http://127.0.0.1:1", "t").post("x")
|
|
73
|
+
assert e.value.status is None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_non_json_success_body(server):
|
|
77
|
+
server.reply(200, "<html>some other site</html>", "text/html")
|
|
78
|
+
with pytest.raises(NotefeedError) as e:
|
|
79
|
+
Client(server.url, "t").post("x")
|
|
80
|
+
assert type(e.value) is NotefeedError
|
|
81
|
+
assert e.value.status == 200
|
|
82
|
+
assert "not a notefeed" in str(e.value)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_token_whitespace_stripped(server):
|
|
86
|
+
Client(server.url, "tok\r\n").post("x")
|
|
87
|
+
assert server.requests[0]["headers"]["Authorization"] == "Bearer tok"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_token_control_chars_rejected_without_echo():
|
|
91
|
+
with pytest.raises(ConfigError) as e:
|
|
92
|
+
Client("http://x", "sec\nret")
|
|
93
|
+
assert "invalid characters" in str(e.value)
|
|
94
|
+
assert "sec" not in str(e.value) and "ret" not in str(e.value)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_non_http_reply():
|
|
98
|
+
import socket
|
|
99
|
+
import threading
|
|
100
|
+
|
|
101
|
+
srv = socket.create_server(("127.0.0.1", 0))
|
|
102
|
+
|
|
103
|
+
def banner():
|
|
104
|
+
conn, _ = srv.accept()
|
|
105
|
+
conn.recv(65536)
|
|
106
|
+
conn.sendall(b"SSH-2.0-OpenSSH_9.6\r\n")
|
|
107
|
+
conn.close()
|
|
108
|
+
|
|
109
|
+
threading.Thread(target=banner, daemon=True).start()
|
|
110
|
+
with pytest.raises(NotefeedError) as e:
|
|
111
|
+
Client(f"http://127.0.0.1:{srv.getsockname()[1]}", "t").post("x")
|
|
112
|
+
assert e.value.status is None
|
|
113
|
+
srv.close()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_html_error_body_collapsed(server):
|
|
117
|
+
server.reply(502, "<html>\n <body>bad gateway</body>\n</html>\n", "text/html")
|
|
118
|
+
with pytest.raises(NotefeedError) as e:
|
|
119
|
+
Client(server.url, "t").post("x")
|
|
120
|
+
assert str(e.value) == "HTTP 502: <html> <body>bad gateway</body> </html>"
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
import notefeed
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_version_matches_pyproject():
|
|
10
|
+
toml = (Path(__file__).parents[1] / "pyproject.toml").read_text()
|
|
11
|
+
assert f'\nversion = "{notefeed.__version__}"\n' in toml
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_matches_js_package():
|
|
15
|
+
pkg = Path(__file__).parents[2] / "js" / "package.json"
|
|
16
|
+
if not pkg.exists():
|
|
17
|
+
pytest.skip("JS package not present")
|
|
18
|
+
assert json.loads(pkg.read_text())["version"] == notefeed.__version__
|