import csv import gzip import importlib.util import json import tempfile import unittest import zipfile from pathlib import Path SPEC = importlib.util.spec_from_file_location('prepare_shipping', Path(__file__).resolve().parents[2] / 'scripts/prepare-supplier-bookkeeping-shipping.py') MODULE = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(MODULE) class PrepareShippingTest(unittest.TestCase): def workbook(self, root, date='2026/10/1 0:09:50'): source = root / 'source.xlsx' ns = MODULE.NS[1:-1] headers = ['快递单号', '交易单号', '条形码', '数量', '运费', '发货时间', '结算运费', '收货姓名'] strings = ''.join(''+v+'' for v in headers) strings += 'SKU+A' head = ''.join(f'{i}' for i in range(8)) row = f'''00012345678901234567 ORDER-1,ORDER-2 82 1+23.8 {date} 900PRIVATE''' with zipfile.ZipFile(source,'w') as book: book.writestr('xl/workbook.xml', f'') book.writestr('xl/_rels/workbook.xml.rels','') book.writestr('xl/sharedStrings.xml', f'{strings}') book.writestr('xl/worksheets/export.xml',f'{head}{row}') return source def test_preserves_long_identifiers_reads_formula_cache_and_omits_private_fields(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) source = self.workbook(root) original = source.read_bytes() output = root/'shipping.csv.gz' result = MODULE.prepare(source,'2026-10',output,'运费') self.assertEqual(1,result['rows']) with gzip.open(output,'rt',encoding='utf-8',newline='') as stream: row = next(csv.DictReader(stream)) self.assertEqual('00012345678901234567',row['express_no']) self.assertEqual('SKU+A',row['barcode']) self.assertEqual('3.8',row['freight']) self.assertEqual('2026-10-01 00:09:50',row['ship_time']) self.assertNotIn('PRIVATE',str(row)) meta = json.loads(Path(str(output)+'.json').read_text(encoding='utf-8')) self.assertEqual(MODULE.digest(output),meta['data_sha256']) self.assertEqual(original,source.read_bytes()) with self.assertRaises(ValueError): MODULE.prepare(source,'2026-10',output,'运费') def test_rejects_wrong_month_and_wrong_freight_column(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) source = self.workbook(root) with self.assertRaises(ValueError): MODULE.prepare(source,'2026-09',root/'wrong-month.csv.gz','运费') with self.assertRaises(ValueError): MODULE.prepare(source,'2026-10',root/'wrong-column.csv.gz','系统运费') if __name__ == '__main__': unittest.main()