diff --git a/novem/code/space_content.py b/novem/code/space_content.py index 65b8c53..08da80f 100644 --- a/novem/code/space_content.py +++ b/novem/code/space_content.py @@ -36,7 +36,7 @@ from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple, Union from urllib.parse import quote -from novem.exceptions import Novem403, Novem404, NovemException, raise_on_response +from novem.exceptions import Novem403, Novem404, Novem409, NovemException, raise_on_response if TYPE_CHECKING: from . import NovemCodeAPI @@ -222,6 +222,15 @@ def _request( raise Novem404(f"{path or '/'}") if r.status_code == 403: raise Novem403(f"{path or '/'}") + if r.status_code == 409: + # raise_on_response treats 409 as success; for content requests it + # means the write did not happen (e.g. a create-only PUT on an + # existing file), so it must not pass silently. + try: + message = r.json().get("message") or r.text + except ValueError: + message = r.text + raise Novem409(message or f"{path or '/'}: conflict") if not r.ok: raise_on_response(r) @@ -346,8 +355,9 @@ def write( """Write a file (create or replace); parent folders are auto-created. ``if_match`` writes only when the file's current ETag matches; - ``no_clobber`` refuses to replace an existing file. Both surface a - 412 as a NovemException when the condition fails. + ``no_clobber`` refuses to replace an existing file. A failed + condition raises a NovemException (412, or Novem409 when the file + already exists). """ npath = _norm(path) if npath.endswith("/"): @@ -364,7 +374,9 @@ def write( if no_clobber: headers["If-None-Match"] = "*" - self._request("PUT", npath, headers=headers, data=body) + # PUT is create-only (409 if the file exists); POST is the upsert. + method = "PUT" if no_clobber else "POST" + self._request(method, npath, headers=headers, data=body) def write_bytes( self, diff --git a/tests/test_space_content.py b/tests/test_space_content.py index 90cb126..1f87219 100644 --- a/tests/test_space_content.py +++ b/tests/test_space_content.py @@ -7,7 +7,7 @@ import pytest from novem import Space -from novem.exceptions import Novem404, NovemException +from novem.exceptions import Novem404, Novem409, NovemException BASE = os.path.dirname(os.path.abspath(__file__)) CONFIG_FILE = f"{BASE}/test.conf" @@ -172,7 +172,7 @@ def on_put(request, context): context.status_code = 201 return "" - requests_mock.register_uri("put", f"{base}/doc.json", text=on_put) + requests_mock.register_uri("post", f"{base}/doc.json", text=on_put) s.content["doc.json"] = '{"a": 1}' assert seen["body"] == b'{"a": 1}' @@ -189,7 +189,7 @@ def on_put(request, context): context.status_code = 201 return "" - requests_mock.register_uri("put", f"{base}/blob.bin", text=on_put) + requests_mock.register_uri("post", f"{base}/blob.bin", text=on_put) s.content["blob.bin"] = b"\x00\x01\x02" assert seen["body"] == b"\x00\x01\x02" @@ -200,24 +200,52 @@ def test_write_conditions(requests_mock): s, base = _space(requests_mock) seen = {} - def on_put(request, context): + def on_write(request, context): + seen["method"] = request.method seen["if_match"] = request.headers.get("If-Match") seen["if_none_match"] = request.headers.get("If-None-Match") context.status_code = 200 return "" - requests_mock.register_uri("put", f"{base}/state.json", text=on_put) + requests_mock.register_uri("post", f"{base}/state.json", text=on_write) + requests_mock.register_uri("put", f"{base}/state.json", text=on_write) + # a conditional replacement is still an upsert s.content.write("state.json", "{}", if_match="abc123") + assert seen["method"] == "POST" assert seen["if_match"] == "abc123" + # no_clobber means create-only, which is PUT s.content.write("state.json", "{}", no_clobber=True) + assert seen["method"] == "PUT" assert seen["if_none_match"] == "*" +def test_write_replaces_with_post_not_put(requests_mock): + s, base = _space(requests_mock) + put = requests_mock.register_uri("put", f"{base}/doc.txt", status_code=409, json={"message": "exists"}) + post = requests_mock.register_uri("post", f"{base}/doc.txt", status_code=200) + + s.content["doc.txt"] = "v1" + s.content["doc.txt"] = "v2" + s.content.write("doc.txt", "v3") + (s / "doc.txt").content = "v4" + + assert not put.called + assert [r.body for r in post.request_history] == [b"v1", b"v2", b"v3", b"v4"] + + +def test_create_conflict_raises_409(requests_mock): + s, base = _space(requests_mock) + requests_mock.register_uri("put", f"{base}/state.json", status_code=409, json={"message": "file exists"}) + + with pytest.raises(Novem409, match="file exists"): + s.content.write("state.json", "{}", no_clobber=True) + + def test_write_conflict_raises(requests_mock): s, base = _space(requests_mock) - requests_mock.register_uri("put", f"{base}/state.json", status_code=412, json={"message": "precondition failed"}) + requests_mock.register_uri("post", f"{base}/state.json", status_code=412, json={"message": "precondition failed"}) with pytest.raises(NovemException, match="precondition failed"): s.content.write("state.json", "{}", if_match="stale") @@ -310,7 +338,7 @@ def on_put(request, context): url = f"{base}/path/to/document.json" requests_mock.register_uri("get", url, text=on_get) - requests_mock.register_uri("put", url, text=on_put) + requests_mock.register_uri("post", url, text=on_put) path = s / "path" / "to/document.json" assert str(path) == "path/to/document.json"