File size: 2,390 Bytes
4e837d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / 'src'
for candidate in (ROOT, SRC):
    if str(candidate) not in sys.path:
        sys.path.insert(0, str(candidate))

from app_kit.config import load_app_config
from app_kit.storage import SQLiteStore
from apps._base import _process_uploaded_files
from apps.p4_food_waste.app import create_project_spec


def _prepare_env(monkeypatch, tmp_path: Path) -> None:
    monkeypatch.setenv('APP_ROOT_DIR', str(ROOT))
    monkeypatch.setenv('ARTIFACT_DIR', str(tmp_path / 'artifacts'))
    monkeypatch.setenv('SQLITE_PATH', str(tmp_path / 'sqlite' / 'p4.sqlite3'))


def test_upload_processing_creates_trace_artifact_and_record(tmp_path, monkeypatch) -> None:
    _prepare_env(monkeypatch, tmp_path)
    spec = create_project_spec()
    config = load_app_config(spec.key, data_subdir=spec.data_subdir)
    store = SQLiteStore(config.sqlite_path, config.artifact_dir)

    note_path = tmp_path / 'note.txt'
    receipt_path = tmp_path / 'receipt.txt'
    note_path.write_text(
        'Weekly household notes with leafy greens and fruit waste. Several leftovers were forgotten.',
        encoding='utf-8',
    )
    receipt_path.write_text(
        'Receipt summary: leafy greens, fruit, bread\nItem list: groceries and leftovers.',
        encoding='utf-8',
    )

    try:
        output, status = _process_uploaded_files([str(note_path), str(receipt_path)], spec, store, config)
        records = store.list_records(spec.key)
    finally:
        store.close()

    assert status == '✅ Processed 2 document(s) successfully.'
    assert output
    assert not output.startswith('❌')
    assert len(records) == 1

    record = records[0]
    assert record['project'] == spec.key
    assert record['pack_id'].startswith('upload_')
    payload = json.loads(record['json_blob'])
    assert payload['waste_category']
    assert payload['receipt_table']
    trace_paths = sorted((Path(config.artifact_dir) / 'traces').glob('app-upload-*.json'))
    assert trace_paths, 'expected an app-upload trace artifact to be written'
    trace = json.loads(trace_paths[-1].read_text(encoding='utf-8'))
    assert trace['kind'] == 'app-upload'
    assert trace['project'] == spec.key
    assert trace['file_count'] == 2
    assert trace['pack_id'].startswith('upload_')