142 lines
7.5 KiB
Python
142 lines
7.5 KiB
Python
"""Manual queue fidelity, atomic autosave, export recovery and API isolation."""
|
|
|
|
import io
|
|
import json
|
|
import unittest
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
from openpyxl import load_workbook
|
|
|
|
import main
|
|
from manual_orders import HEADERS, CellConflict, ManualOrderStore, build_xlsx, validate_source
|
|
from test_google_resilience import request
|
|
|
|
|
|
CELLS = ["2026-10-22 10:00:00", "", "3500", "테스트", "TEST-1", "상품", "2", "주소", "00123", "010-0000-0000", "010-0000-0000", "요청", "", "수동발주", "비고"]
|
|
|
|
|
|
class FormatTests(unittest.TestCase):
|
|
def test_excel_keeps_column_order_leading_zeros_and_literal_formulas(self):
|
|
cells = CELLS.copy()
|
|
cells[14] = '=HYPERLINK("https://example.invalid","text")'
|
|
book = load_workbook(io.BytesIO(build_xlsx(HEADERS, [cells])))
|
|
sheet = book.active
|
|
self.assertEqual(list(next(sheet.values)), HEADERS)
|
|
self.assertEqual(sheet["I2"].value, "00123")
|
|
self.assertEqual(sheet["G2"].value, 2)
|
|
self.assertEqual(sheet["O2"].data_type, "s")
|
|
self.assertEqual(sheet["O2"].value, cells[14])
|
|
|
|
def test_source_padding_keeps_blank_rows_and_extra_columns(self):
|
|
headers, rows = validate_source({"kind": "corm-manual-orders", "headers": HEADERS + ["추가 열"], "rows": [[], CELLS + ["추가 값"]]})
|
|
self.assertEqual(len(rows[0]), 16)
|
|
self.assertEqual(rows[1][-1], "추가 값")
|
|
|
|
|
|
class StoreTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.store = ManualOrderStore({})
|
|
self.connection = MagicMock()
|
|
self.cursor = self.connection.cursor.return_value.__enter__.return_value
|
|
connect = patch.object(self.store, "_connect", return_value=self.connection)
|
|
connect.start()
|
|
self.addCleanup(connect.stop)
|
|
|
|
def test_same_cell_conflict_aborts_entire_batch(self):
|
|
self.cursor.fetchall.return_value = [(1, CELLS.copy(), 2)]
|
|
with self.assertRaises(CellConflict):
|
|
self.store.patch_cells([{"id": 1, "column": 3, "value": "새 이름", "previous_value": "다른 이름"}])
|
|
self.assertIs(self.connection.__exit__.call_args.args[0], CellConflict)
|
|
self.assertEqual(self.cursor.execute.call_count, 1)
|
|
|
|
def test_retry_of_already_saved_value_succeeds_and_other_cells_are_preserved(self):
|
|
self.cursor.fetchall.return_value = [(1, CELLS.copy(), 2)]
|
|
self.cursor.fetchone.return_value = (3,)
|
|
rows = self.store.patch_cells([{"id": 1, "column": 3, "value": CELLS[3], "previous_value": "old"}])
|
|
self.assertEqual(rows[0]["cells"][8], "00123")
|
|
self.assertEqual(rows[0]["version"], 3)
|
|
|
|
def test_missing_or_archived_row_is_not_recreated_by_autosave(self):
|
|
self.cursor.fetchall.return_value = []
|
|
with self.assertRaises(LookupError):
|
|
self.store.patch_cells([{"id": 1, "column": 3, "value": "new", "previous_value": "old"}])
|
|
|
|
def test_order_and_summary_share_one_transaction(self):
|
|
self.cursor.fetchone.return_value = (HEADERS,)
|
|
self.cursor.execute.side_effect = [None, None, RuntimeError("summary insert failed")]
|
|
with self.assertRaises(RuntimeError):
|
|
self.store.append([CELLS], {"timestamp": CELLS[0], "customer_name": "테스트", "total_amount": 3500})
|
|
self.assertIs(self.connection.__exit__.call_args.args[0], RuntimeError)
|
|
|
|
def test_export_failure_never_archives_rows(self):
|
|
self.cursor.fetchone.return_value = (HEADERS,)
|
|
self.cursor.fetchall.return_value = [(1, CELLS)]
|
|
with patch("manual_orders.build_xlsx", side_effect=RuntimeError("file failed")), self.assertRaises(RuntimeError):
|
|
self.store.export_and_archive("test.xlsx")
|
|
self.assertEqual(self.cursor.execute.call_count, 2)
|
|
|
|
def test_export_is_archived_with_exact_row_ids_for_redownload(self):
|
|
self.cursor.fetchone.return_value = (HEADERS,)
|
|
self.cursor.fetchall.return_value = [(4, CELLS)]
|
|
data, export_id = self.store.export_and_archive("test.xlsx")
|
|
self.assertTrue(data.startswith(b"PK"))
|
|
calls = self.cursor.execute.call_args_list
|
|
self.assertIn("corm_manual_exports", calls[2].args[0])
|
|
self.assertEqual(calls[3].args[1], ([4],))
|
|
|
|
|
|
class ApiTests(unittest.IsolatedAsyncioTestCase):
|
|
def setUp(self):
|
|
self.store = MagicMock()
|
|
self.store.list_rows.return_value = {"headers": HEADERS, "rows": [{"id": 1, "cells": CELLS, "version": 1}]}
|
|
self.store.patch_cells.return_value = []
|
|
self.store.export_and_archive.return_value = (build_xlsx(HEADERS, [CELLS]), "00000000-0000-0000-0000-000000000001")
|
|
for key, value in (("MANUAL_ORDERS_BACKEND", "postgres"), ("HISTORY_BACKEND", "postgres"), ("_manual_orders", self.store)):
|
|
mock = patch.object(main, key, value)
|
|
mock.start()
|
|
self.addCleanup(mock.stop)
|
|
google = patch.object(main, "get_manual_worksheet", side_effect=AssertionError("Unexpected Google call"))
|
|
google.start()
|
|
self.addCleanup(google.stop)
|
|
|
|
async def test_grid_read_patch_and_export_do_not_use_google(self):
|
|
with patch.object(main, "run_google_io", side_effect=AssertionError("Google unavailable")):
|
|
self.assertEqual((await request("GET", "/api/manual/orders"))[0], 200)
|
|
self.assertEqual((await request("PATCH", "/api/manual/orders/cells", {"changes": [{"id": 1, "column": 3, "value": "새 이름", "previous_value": "테스트"}]}))[0], 200)
|
|
self.assertEqual((await request("POST", "/api/sheet/download_and_clear"))[0], 200)
|
|
|
|
async def test_conflicting_autosave_returns_current_values(self):
|
|
self.store.patch_cells.side_effect = CellConflict([{"id": 1, "column": 3, "value": "최신 이름"}])
|
|
status, _, body = await request("PATCH", "/api/manual/orders/cells", {"changes": [{"id": 1, "column": 3, "value": "내 이름", "previous_value": "old"}]})
|
|
self.assertEqual(status, 409)
|
|
self.assertEqual(json.loads(body)["detail"]["conflicts"][0]["value"], "최신 이름")
|
|
|
|
async def test_submission_saves_summary_server_side_and_retains_sheet_layout(self):
|
|
payload = {"customer_name": "테스트", "phone": "01000000000", "address": "주소", "comment": "요청",
|
|
"order_type": "normal", "no_lid": False, "total_amount": 3500,
|
|
"items": [{"code": "TEST-1", "name": "상품", "label": "상품", "quantity": 2, "item_type": "ORDER_SINGLE"}]}
|
|
status, _, body = await request("POST", "/api/order/submit", payload)
|
|
self.assertEqual(status, 200)
|
|
self.assertTrue(json.loads(body)["history_saved"])
|
|
rows, history = self.store.append.call_args.args
|
|
self.assertEqual(len(rows[0]), 15)
|
|
self.assertEqual(rows[0][4:7], ["TEST-1", "상품", 2])
|
|
self.assertEqual(history["total_amount"], 3500)
|
|
|
|
async def test_cancellation_updates_queue_and_history_through_same_store(self):
|
|
self.assertEqual((await request("DELETE", "/api/manual/history/records/1"))[0], 200)
|
|
self.store.delete_history.assert_called_once_with(1)
|
|
|
|
async def test_legacy_template_uses_sheet_until_migration_and_db_template_uses_grid(self):
|
|
# Reuse the actual template render path with service authentication.
|
|
status, _, body = await request("GET", "/")
|
|
self.assertEqual(status, 200)
|
|
self.assertIn(b'id="manual-grid-panel"', body)
|
|
self.assertNotIn(b'id="manual-iframe-container"', body)
|
|
with patch.object(main, "MANUAL_ORDERS_BACKEND", "google"):
|
|
self.assertEqual((await request("GET", "/api/manual/orders"))[0], 409)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|