feat(입출고): 입고증 사진 왼쪽·오른쪽 회전 — 돌린 상태로 저장
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -56,6 +56,8 @@
|
||||
|
||||
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
|
||||
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
|
||||
- **돌리기**(2026-11-02) — 크게 보기 창 왼쪽·오른쪽 버튼(입고 담당) → `POST /inout/orders/{id}/photos/{pid}/rotate?degrees=90|270` → 서버가 **저장된 사진 자체**를 돌려 덮어씀(`store.rotate_image`, EXIF 회전을 픽셀에 반영, 같은 형식, JPEG 품질 92) — 원본 링크·입고 요청 메일도 돌린 사진. 되돌리기 = 반대로 돌리기. HEIC·움직이는 GIF 는 못 돌림(HEIC 은 버튼 숨김).
|
||||
사진 응답은 `no-cache` + ETag(돌린 뒤 예전 사진이 캐시에 남지 않게).
|
||||
|
||||
## 상품 정보 (004, 옵션 세 번째 탭)
|
||||
|
||||
|
||||
@@ -432,6 +432,19 @@ class InoutDBStore:
|
||||
if not row:
|
||||
raise ValueError("사진을 찾을 수 없습니다.")
|
||||
|
||||
def rotate_receipt_photo(self, order_id: int, photo_id: int, degrees: int) -> None:
|
||||
"""저장된 사진 자체를 돌린다(2026-11-02) — 화면·원본·입고 요청 메일 모두 돌린 사진."""
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
head = self._lock_order(conn, order_id)
|
||||
if head["cancelled_at"]:
|
||||
raise ValueError("취소된 발주서입니다.")
|
||||
row = conn.execute("SELECT p.data FROM inout_receipt_photos p JOIN inout_receipts r ON r.id = p.receipt_id "
|
||||
"WHERE p.id=%s AND r.order_id=%s", (photo_id, order_id)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("사진을 찾을 수 없습니다.")
|
||||
data = store.rotate_image(bytes(row["data"]), degrees)
|
||||
conn.execute("UPDATE inout_receipt_photos SET data=%s, size_bytes=%s WHERE id=%s", (data, len(data), photo_id))
|
||||
|
||||
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
|
||||
"""사진 내용(+ 발주서 id) — 보여 주기용."""
|
||||
try:
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
|
||||
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
|
||||
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
|
||||
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
|
||||
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete|rotate · GET /inout/photos/{pid} 입고증 사진
|
||||
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
|
||||
GET|POST /inout/orders/{id}/receipts/{rid}/mail 입고 요청 메일(물류센터, 입고 담당 본인 Gmail, 005)
|
||||
POST /inout/settings/logistics 옵션 → 물류센터(입고 요청 메일 받는 주소·참조, 005)
|
||||
@@ -486,7 +486,7 @@ def receipt_delete(request: Request, order_id: int, receipt_id: int) -> Any:
|
||||
_PHOTO_HEADERS = {
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
|
||||
"Cache-Control": "private, max-age=86400",
|
||||
"Cache-Control": "private, no-cache",
|
||||
}
|
||||
|
||||
|
||||
@@ -530,6 +530,21 @@ def receipt_photo_delete(request: Request, order_id: int, photo_id: int) -> Any:
|
||||
return _redirect(f"/inout/orders/{order_id}", "사진을 지웠습니다.")
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/photos/{photo_id}/rotate")
|
||||
def receipt_photo_rotate(request: Request, order_id: int, photo_id: int, degrees: int = Query(...)) -> Any:
|
||||
"""크게 보기 창의 회전 버튼 — 창을 닫지 않게 JSON 으로 답한다(화면이 사진을 다시 받아 그림)."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "receive")
|
||||
try:
|
||||
st.rotate_receipt_photo(order_id, photo_id, degrees)
|
||||
except (ValueError, LookupError) as exc:
|
||||
return JSONResponse({"error": str(exc)}, status_code=400)
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.get("/photos/{photo_id}")
|
||||
def photo_view(request: Request, photo_id: int) -> Response:
|
||||
_user(request)
|
||||
@@ -537,12 +552,18 @@ def photo_view(request: Request, photo_id: int) -> Response:
|
||||
row = st.get_photo(photo_id) if st is not None else None
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
|
||||
from hashlib import md5 # noqa: WPS433
|
||||
from urllib.parse import quote # noqa: WPS433
|
||||
|
||||
data = bytes(row["data"])
|
||||
# 돌린 사진이 하루 동안 예전 모습으로 남지 않게 — 브라우저가 매번 내용이 같은지 묻는다(no-cache + ETag)
|
||||
etag = '"' + md5(data, usedforsecurity=False).hexdigest() + '"'
|
||||
if request.headers.get("if-none-match") == etag:
|
||||
return Response(status_code=304, headers={"ETag": etag, "Cache-Control": _PHOTO_HEADERS["Cache-Control"]})
|
||||
name = quote(str(row["filename"] or f"photo-{photo_id}"))
|
||||
disp = "attachment" if row["content_type"] == "image/heic" else "inline" # HEIC 은 브라우저가 못 보여 줌 → 내려받기
|
||||
return Response(content=bytes(row["data"]), media_type=row["content_type"],
|
||||
headers={**_PHOTO_HEADERS, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
|
||||
return Response(content=data, media_type=row["content_type"],
|
||||
headers={**_PHOTO_HEADERS, "ETag": etag, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -700,6 +700,41 @@ def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> lis
|
||||
return out
|
||||
|
||||
|
||||
def rotate_image(data: bytes, degrees: int) -> bytes:
|
||||
"""사진 내용을 시계 방향 90·270도로 돌려 같은 형식으로(2026-11-02). 휴대폰 사진의 회전 정보(EXIF)는 픽셀에 반영한 뒤 돌린다."""
|
||||
from io import BytesIO # noqa: WPS433
|
||||
|
||||
from PIL import Image, ImageOps # noqa: WPS433
|
||||
|
||||
if degrees not in (90, 270):
|
||||
raise ValueError("사진은 왼쪽·오른쪽으로만 돌릴 수 있습니다.")
|
||||
kind = sniff_image(data)
|
||||
if kind == "image/heic":
|
||||
raise ValueError("HEIC 사진은 돌릴 수 없습니다 — JPG 로 바꿔 다시 올려 주세요.")
|
||||
try:
|
||||
im = Image.open(BytesIO(data))
|
||||
if getattr(im, "n_frames", 1) > 1:
|
||||
raise ValueError("움직이는 사진은 돌릴 수 없습니다.")
|
||||
icc = im.info.get("icc_profile")
|
||||
im = ImageOps.exif_transpose(im)
|
||||
# PIL 의 ROTATE_n 은 반시계 방향 — 시계 90도 = ROTATE_270
|
||||
im = im.transpose(Image.Transpose.ROTATE_270 if degrees == 90 else Image.Transpose.ROTATE_90)
|
||||
fmt = {"image/jpeg": "JPEG", "image/png": "PNG", "image/webp": "WEBP", "image/gif": "GIF"}[kind]
|
||||
opts: dict[str, Any] = {"icc_profile": icc} if icc and fmt != "GIF" else {}
|
||||
if fmt in ("JPEG", "WEBP"):
|
||||
opts["quality"] = 92
|
||||
buf = BytesIO()
|
||||
im.save(buf, format=fmt, **opts)
|
||||
except ValueError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 — 깨진 파일 등(원본은 그대로 둔다)
|
||||
raise ValueError("이 사진은 돌릴 수 없습니다.") from exc
|
||||
out = buf.getvalue()
|
||||
if len(out) > MAX_PHOTO_BYTES:
|
||||
raise ValueError(f"돌린 사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지).")
|
||||
return out
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
|
||||
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261027b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261102a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -71,4 +71,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261027b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261102a" defer></script>{% endblock %}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
</footer>
|
||||
</dialog>
|
||||
{%- endmacro -%}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261027b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261102a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% set active = order.status in ('open', 'partial') %}
|
||||
@@ -232,6 +232,10 @@
|
||||
<dialog class="io-viewer" id="io-viewer" tabindex="-1" aria-label="입고증 사진" data-order="{{ order.id }}" data-can-delete="{{ '1' if photo_admin else '' }}">
|
||||
<div class="io-viewer-bar">
|
||||
<span class="io-viewer-title" id="io-viewer-title"></span>
|
||||
{% if photo_admin %}
|
||||
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="270" title="왼쪽으로 돌리기" aria-label="왼쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4v6h6"/><path d="M3.5 15a9 9 0 1 0 2.1-9.4L3 10"/></svg></button>
|
||||
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="90" title="오른쪽으로 돌리기" aria-label="오른쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 4v6h-6"/><path d="M20.5 15a9 9 0 1 1-2.1-9.4L21 10"/></svg></button>
|
||||
{% endif %}
|
||||
<a class="io-viewer-btn" id="io-viewer-open" href="#" target="_blank" rel="noopener">원본</a>
|
||||
{% if photo_admin %}<form method="post" id="io-viewer-del" data-erp-confirm="이 입고증 사진을 지울까요?"><button type="submit" class="io-viewer-btn">지우기</button></form>{% endif %}
|
||||
<button type="button" class="io-viewer-btn" data-close aria-label="닫기">✕</button>
|
||||
@@ -258,4 +262,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261027b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261102a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261027b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261102a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -95,4 +95,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261027b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261102a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import due, n, ymd %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261027b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261102a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -91,4 +91,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261027b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261102a" defer></script>{% endblock %}
|
||||
|
||||
@@ -256,6 +256,8 @@
|
||||
.io-viewer-btn { padding: 5px 12px; border: 1px solid rgba(255, 255, 255, .35); border-radius: 6px; background: rgba(0, 0, 0, .35); color: #fff;
|
||||
font: inherit; font-size: 12.5px; text-decoration: none; cursor: pointer; }
|
||||
.io-viewer-btn:hover { background: rgba(255, 255, 255, .15); }
|
||||
.io-viewer-rot { display: inline-flex; align-items: center; padding: 5px 9px; }
|
||||
.io-viewer-rot:disabled { opacity: .5; cursor: wait; }
|
||||
.io-viewer-img { max-width: 100%; max-height: 100%; object-fit: contain; }
|
||||
.io-viewer-heic { padding: 24px; text-align: center; }
|
||||
.io-viewer-nav { position: absolute; top: 50%; transform: translateY(-50%); width: 44px; height: 64px; border: 0; border-radius: 8px;
|
||||
|
||||
+23
-1
@@ -694,13 +694,15 @@
|
||||
const img = document.getElementById("io-viewer-img"), heic = document.getElementById("io-viewer-heic");
|
||||
const title = document.getElementById("io-viewer-title"), openA = document.getElementById("io-viewer-open");
|
||||
const del = document.getElementById("io-viewer-del");
|
||||
const rots = viewer.querySelectorAll("[data-rotate]");
|
||||
let list = [], at = 0;
|
||||
function show(i) {
|
||||
at = (i + list.length) % list.length;
|
||||
const b = list[at], id = b.dataset.photo, isHeic = b.dataset.type === "image/heic";
|
||||
img.hidden = isHeic;
|
||||
heic.hidden = !isHeic;
|
||||
if (!isHeic) img.src = "/inout/photos/" + id;
|
||||
rots.forEach(function (r) { r.hidden = isHeic; });
|
||||
if (!isHeic) img.src = "/inout/photos/" + id + (b.dataset.v ? "?v=" + b.dataset.v : "");
|
||||
openA.href = "/inout/photos/" + id;
|
||||
title.textContent = (b.dataset.name || "입고증") + " (" + (at + 1) + "/" + list.length + ")";
|
||||
if (del) del.action = "/inout/orders/" + viewer.dataset.order + "/photos/" + id + "/delete";
|
||||
@@ -714,10 +716,30 @@
|
||||
viewer.showModal();
|
||||
viewer.focus({ preventScroll: true }); // [원본]에 초점 테두리가 생기지 않게(←/→ 는 창에서 받음)
|
||||
});
|
||||
// 회전 = 서버가 저장된 사진 자체를 돌림(2026-11-02) — 창은 그대로 두고 큰 사진·썸네일만 새로 받는다
|
||||
async function rotate(degrees) {
|
||||
const b = list[at];
|
||||
rots.forEach(function (r) { r.disabled = true; });
|
||||
try {
|
||||
const res = await fetch("/inout/orders/" + viewer.dataset.order + "/photos/" + b.dataset.photo + "/rotate?degrees=" + degrees, { method: "POST" });
|
||||
const data = await res.json().catch(function () { return {}; });
|
||||
if (!res.ok) throw new Error(data.error || "사진을 돌리지 못했습니다.");
|
||||
b.dataset.v = String(Date.now());
|
||||
const thumb = b.querySelector("img");
|
||||
if (thumb) thumb.src = "/inout/photos/" + b.dataset.photo + "?v=" + b.dataset.v;
|
||||
show(at);
|
||||
} catch (err) {
|
||||
alertMsg(err.message || "사진을 돌리지 못했습니다.");
|
||||
} finally {
|
||||
rots.forEach(function (r) { r.disabled = false; });
|
||||
}
|
||||
}
|
||||
viewer.addEventListener("click", function (e) {
|
||||
if (e.target === viewer || e.target.closest("[data-close]")) viewer.close();
|
||||
const step = e.target.closest("[data-step]");
|
||||
if (step) show(at + parseInt(step.dataset.step, 10));
|
||||
const rot = e.target.closest("[data-rotate]");
|
||||
if (rot) rotate(rot.dataset.rotate);
|
||||
});
|
||||
viewer.addEventListener("keydown", function (e) {
|
||||
if (e.key === "ArrowLeft") show(at - 1);
|
||||
|
||||
+15
-1
@@ -197,9 +197,23 @@ class InoutDbTests(unittest.TestCase):
|
||||
self.st.add_receipt_photos(o["id"], rid, [("e.jpg", jpeg)], by="w@x")
|
||||
with self.assertRaisesRegex(ValueError, "찾을 수 없"):
|
||||
self.st.add_receipt_photos(o["id"], 999999, [("e.jpg", jpeg)], by="w@x")
|
||||
o2 = self.order([("MT-Q", 1)])
|
||||
# 돌리기(2026-11-02) — 저장된 내용·크기가 바뀌고, 다른 발주서 id 로는 못 돌린다(내용이 가짜 JPEG 이면 원본 그대로)
|
||||
with self.assertRaisesRegex(ValueError, "찾을 수 없"):
|
||||
self.st.rotate_receipt_photo(o2["id"], ph[1]["id"], 90)
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
buf = BytesIO()
|
||||
Image.new("RGB", (40, 20), (255, 0, 0)).save(buf, format="JPEG")
|
||||
with self.st._pool.connection() as conn:
|
||||
conn.execute("UPDATE inout_receipt_photos SET data=%s WHERE id=%s", (buf.getvalue(), ph[1]["id"]))
|
||||
self.st.rotate_receipt_photo(o["id"], ph[1]["id"], 90)
|
||||
turned = self.st.get_photo(ph[1]["id"])
|
||||
self.assertEqual(Image.open(BytesIO(bytes(turned["data"]))).size, (20, 40))
|
||||
self.st.delete_receipt_photo(o["id"], ph[0]["id"])
|
||||
self.assertIsNone(self.st.get_photo(ph[0]["id"]))
|
||||
o2 = self.order([("MT-Q", 1)])
|
||||
with self.assertRaisesRegex(ValueError, "찾을 수 없"): # 다른 발주서의 사진 id 로는 못 지운다
|
||||
self.st.delete_receipt_photo(o2["id"], ph[1]["id"])
|
||||
self.st.delete_receipt(o["id"], rid, by="w@x") # 입고를 지우면 사진도 함께
|
||||
|
||||
@@ -25,6 +25,69 @@ def _order(**over):
|
||||
return o
|
||||
|
||||
|
||||
class RotateTests(unittest.TestCase):
|
||||
"""입고증 사진 돌리기(2026-11-02) — 시계 방향·형식 유지·EXIF 반영."""
|
||||
|
||||
@staticmethod
|
||||
def _image(fmt, size=(40, 20), **save):
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
im = Image.new("RGB", size, (255, 0, 0))
|
||||
im.paste((0, 0, 255), (0, 0, size[0] // 2, size[1] // 2)) # 왼쪽 위만 파랑
|
||||
buf = BytesIO()
|
||||
im.save(buf, format=fmt, **save)
|
||||
return buf.getvalue()
|
||||
|
||||
@staticmethod
|
||||
def _open(data):
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
return Image.open(BytesIO(data))
|
||||
|
||||
def test_right_and_left_turn_corner_the_right_way(self):
|
||||
right = self._open(s.rotate_image(self._image("PNG"), 90))
|
||||
self.assertEqual(right.size, (20, 40))
|
||||
self.assertEqual(right.convert("RGB").getpixel((19, 0)), (0, 0, 255)) # 왼쪽 위 → 시계 방향이면 오른쪽 위
|
||||
left = self._open(s.rotate_image(self._image("PNG"), 270))
|
||||
self.assertEqual(left.convert("RGB").getpixel((0, 39)), (0, 0, 255)) # 반시계면 왼쪽 아래
|
||||
|
||||
def test_keeps_format(self):
|
||||
for fmt, kind in (("JPEG", "image/jpeg"), ("PNG", "image/png"), ("WEBP", "image/webp"), ("GIF", "image/gif")):
|
||||
with self.subTest(fmt=fmt):
|
||||
out = s.rotate_image(self._image(fmt), 90)
|
||||
self.assertEqual(s.sniff_image(out), kind)
|
||||
self.assertEqual(self._open(out).size, (20, 40))
|
||||
|
||||
def test_phone_exif_is_applied_then_dropped(self):
|
||||
"""휴대폰 사진(EXIF 회전 6 = 화면에선 세로) — 돌린 결과는 화면에 보이던 모습 기준이어야 하고 EXIF 회전이 남으면 안 된다."""
|
||||
from PIL import Image
|
||||
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = 6
|
||||
out = self._open(s.rotate_image(self._image("JPEG", exif=exif.tobytes()), 90))
|
||||
self.assertEqual(out.size, (40, 20)) # 화면 20×40 → 오른쪽으로 돌려 40×20
|
||||
self.assertNotEqual(out.getexif().get(0x0112), 6)
|
||||
|
||||
def test_refuses_what_cannot_be_turned(self):
|
||||
for bad, msg in ((b"....ftypheic" + b"0" * 20, "HEIC"), (JPEG, "돌릴 수 없")):
|
||||
with self.subTest(msg=msg), self.assertRaisesRegex(ValueError, msg):
|
||||
s.rotate_image(bad, 90)
|
||||
with self.assertRaisesRegex(ValueError, "왼쪽·오른쪽"):
|
||||
s.rotate_image(self._image("PNG"), 45)
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
buf = BytesIO()
|
||||
Image.new("RGB", (4, 4), (255, 0, 0)).save(buf, format="GIF", save_all=True, append_images=[Image.new("RGB", (4, 4), (0, 0, 255))])
|
||||
with self.assertRaisesRegex(ValueError, "움직이는"):
|
||||
s.rotate_image(buf.getvalue(), 90)
|
||||
|
||||
|
||||
class MailContentTests(unittest.TestCase):
|
||||
def test_parse_emails(self):
|
||||
self.assertEqual(s.parse_emails("a@x.com, B@y.co.kr; a@X.com\nc@z.kr"), ["a@x.com", "B@y.co.kr", "c@z.kr"])
|
||||
|
||||
@@ -225,6 +225,12 @@ def body(c):
|
||||
img = c.get("/inout/photos/%d" % pids[0])
|
||||
assert img.status_code == 200 and img.content == JPEG and img.headers["content-type"] == "image/jpeg"
|
||||
assert img.headers["x-content-type-options"] == "nosniff" and "sandbox" in img.headers["content-security-policy"]
|
||||
# 돌린 사진이 캐시에 남지 않게 — 매번 확인(no-cache + ETag), 같으면 304
|
||||
assert "no-cache" in img.headers["cache-control"] and img.headers["etag"]
|
||||
assert c.get("/inout/photos/%d" % pids[0], headers={"If-None-Match": img.headers["etag"]}).status_code == 304
|
||||
# 내용이 가짜 JPEG 이면 원본 그대로, 안내만(400)
|
||||
r = c.post("/inout/orders/%d/photos/%d/rotate?degrees=90" % (oid3, pids[0]))
|
||||
assert r.status_code == 400 and r.json()["error"] and c.get("/inout/photos/%d" % pids[0]).content == JPEG, r.text
|
||||
page = c.get("/inout/orders/%d" % oid3).text
|
||||
assert 'data-photo="%d"' % pids[0] in page and 'src="/inout/photos/%d"' % pids[0] in page
|
||||
rid3 = got["receipts"][0]["id"]
|
||||
@@ -234,6 +240,7 @@ def body(c):
|
||||
who["u"] = viewer
|
||||
assert c.get("/inout/photos/%d" % pids[0]).status_code == 200 # 모듈 권한이면 보기는 됨
|
||||
assert c.post("/inout/orders/%d/photos/%d/delete" % (oid3, pids[0])).status_code == 403
|
||||
assert c.post("/inout/orders/%d/photos/%d/rotate?degrees=90" % (oid3, pids[0])).status_code == 403
|
||||
who["u"] = U("nobody-%s@t.local" % tag, inout=False)
|
||||
assert c.get("/inout/photos/%d" % pids[0]).status_code == 403
|
||||
who["u"] = wh
|
||||
|
||||
Reference in New Issue
Block a user