test_db.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import tempfile
  2. import os
  3. from gevent import monkey
  4. monkey.patch_all(subprocess=True)
  5. import pytest
  6. from larigira.db import EventModel
  7. @pytest.yield_fixture
  8. def db():
  9. fname = tempfile.mktemp(suffix=".json", prefix="larigira-test")
  10. yield EventModel(uri=fname)
  11. os.unlink(fname)
  12. def test_empty(db):
  13. assert len(db.get_all_alarms()) == 0
  14. def test_add_basic(db):
  15. assert len(db.get_all_alarms()) == 0
  16. alarm_id = db.add_event(
  17. dict(kind="frequency", interval=60 * 3, start=1),
  18. [dict(kind="mpd", paths=["foo.mp3"], howmany=1)],
  19. )
  20. assert len(db.get_all_alarms()) == 1
  21. assert db.get_alarm_by_id(alarm_id) is not None
  22. assert len(tuple(db.get_actions_by_alarm(db.get_alarm_by_id(alarm_id)))) == 1
  23. def test_add_multiple_alarms(db):
  24. assert len(db.get_all_alarms()) == 0
  25. alarm_id = db.add_event(
  26. dict(kind="frequency", interval=60 * 3, start=1),
  27. [dict(kind="mpd", paths=["foo.mp3"], howmany=1), dict(kind="foo", a=3)],
  28. )
  29. assert len(db.get_all_alarms()) == 1
  30. assert db.get_alarm_by_id(alarm_id) is not None
  31. assert len(db.get_all_actions()) == 2
  32. assert len(tuple(db.get_actions_by_alarm(db.get_alarm_by_id(alarm_id)))) == 2
  33. def test_delete_alarm(db):
  34. assert len(db.get_all_alarms()) == 0
  35. alarm_id = db.add_event(
  36. dict(kind="frequency", interval=60 * 3, start=1),
  37. [dict(kind="mpd", paths=["foo.mp3"], howmany=1)],
  38. )
  39. action_id = next(db.get_actions_by_alarm(db.get_alarm_by_id(alarm_id))).eid
  40. assert len(db.get_all_alarms()) == 1
  41. db.delete_alarm(alarm_id)
  42. assert len(db.get_all_alarms()) == 0 # alarm deleted
  43. assert db.get_action_by_id(action_id) is not None
  44. assert "kind" in db.get_action_by_id(action_id) # action still there
  45. def test_delete_alarm_nonexisting(db):
  46. with pytest.raises(KeyError):
  47. db.delete_alarm(123)
  48. def test_delete_action(db):
  49. alarm_id = db.add_event(
  50. dict(kind="frequency", interval=60 * 3, start=1),
  51. [dict(kind="mpd", paths=["foo.mp3"], howmany=1)],
  52. )
  53. alarm = db.get_alarm_by_id(alarm_id)
  54. assert len(tuple(db.get_actions_by_alarm(alarm))) == 1
  55. action = next(db.get_actions_by_alarm(alarm))
  56. action_id = action.eid
  57. db.delete_action(action_id)
  58. assert len(tuple(db.get_actions_by_alarm(alarm))) == 0