summaryrefslogtreecommitdiff
path: root/jimbrella/test/test_routine.py
blob: 2a65b35d351204be6d592eee68d9c1ebffbf21f0 (plain)
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
67
68
69
70
71
72
from flask import Flask, Response, request
from threading import Thread
import json
import os
import shutil
import logging
from .jform_data import mock_jform_data
from ..routine import sync_database, process_overdue
from ..database import Database
from ..jform import JForm
from ..config import *

"""Set up logging."""
logging.basicConfig(
    filename="/tmp/jimbrella.log",
    encoding="utf-8",
    level=logging.INFO,
    format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s",
)
logging.info("----- BEGIN ROUTINE TEST -----")

"""Spin up a simple Flask app to mimic jForm."""
jform = Flask(__name__)

takeaway, giveback = mock_jform_data()

EMPTY_RESPONSE = Response(
    json.dumps(
        {
            "success": True,
            "message": "ok",
            "data": {
                "rows": [],
                "total": 0,
            },
            "code": 0,
        },
    ),
    content_type="application/json",
)


@jform.route("/<endpoint>")
def api(endpoint):
    params = request.args.get("params")
    if (
        params
        and "current" in json.loads(params)
        and json.loads(params)["current"] != 1
    ):
        return EMPTY_RESPONSE
    if endpoint == "takeaway":
        return Response(takeaway, content_type="application/json")
    elif endpoint == "giveback":
        return Response(giveback, content_type="application/json")


Thread(target=jform.run, kwargs={"port": 5001}).start()

"""Initialize Database and JForm."""
TEST_DATABASE_PATH = "/tmp/jimbrella.test.db.csv"
shutil.copyfile(DATABASE_PATH, TEST_DATABASE_PATH)
db = Database(TEST_DATABASE_PATH)
takeaway_jform = JForm("takeaway", "http://localhost:5001/takeaway", "/tmp")
giveback_jform = JForm("giveback", "http://localhost:5001/giveback", "/tmp")
sync_database(takeaway_jform, giveback_jform, db)
process_overdue(db)

"""Cleanup"""
os.remove(takeaway_jform._bookmark_fp)
os.remove(giveback_jform._bookmark_fp)
logging.info("----- END ROUTINE TEST -----")