model.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import lc.config as c
  2. import lc.request as r
  3. import lc.model as m
  4. class TestDB:
  5. def setup_method(self, _):
  6. c.DB.init(":memory:")
  7. c.DB.create_tables(m.MODELS)
  8. def teardown_method(self, _):
  9. c.DB.close()
  10. def mk_user(self, name="gdritter", password="foo") -> m.User:
  11. return m.User.from_request(r.User(
  12. name=name,
  13. password=password,
  14. ))
  15. def test_create_user(self):
  16. name = "gdritter"
  17. u = self.mk_user(name=name)
  18. # it should be the only thing in the db
  19. all_users = m.User.select()
  20. assert len(all_users) == 1
  21. assert all_users[0].id == u.id
  22. assert all_users[0].name == name
  23. # we should be able to find it with the given name, too
  24. named_user = m.User.get(m.User.name == name)
  25. assert named_user.id == u.id
  26. assert named_user.name == name
  27. def test_user_passwords(self):
  28. name = "gdritter"
  29. password = "foo"
  30. u = self.mk_user(name=name, password=password)
  31. print(u.name, u.passhash)
  32. assert u.authenticate(password)
  33. assert u.authenticate("wrong password") is False
  34. def test_get_or_create_tag(self):
  35. u = self.mk_user()
  36. tag_name = "food"
  37. t = m.Tag.get_or_create_tag(u, tag_name)
  38. # we should be able to find the tag with the given name
  39. named_tags = m.Tag.select(m.Tag.user == u and m.Tag.name == tag_name)
  40. assert len(named_tags) == 1
  41. # subsequent calls to get_or_create_tag should return the same db row
  42. t2 = m.Tag.get_or_create_tag(u, tag_name)
  43. assert t.id == t2.id
  44. def test_find_hierarchy(self):
  45. u = self.mk_user()
  46. t = m.Tag.get_or_create_tag(u, "food/bread/rye")
  47. # this should have created three DB rows: for 'food', for
  48. # 'food/bread', and for 'food/bread/rye':
  49. assert len(m.Tag.select()) == 3
  50. # searching for a prefix of the tag should yield the same
  51. # parent tag
  52. assert t.parent.id == m.Tag.get(name="food/bread").id
  53. assert t.parent.parent.id == m.Tag.get(name="food").id
  54. # creating a new hierarchical tag with a shared prefix should
  55. # only create the new child tag
  56. t2 = m.Tag.get_or_create_tag(u, "food/bread/baguette")
  57. print([t.name for t in m.Tag.select()])
  58. assert len(m.Tag.select()) == 4
  59. # it should share the same parent tags
  60. assert t2.parent.id == t.parent.id
  61. assert t2.parent.parent.id == t.parent.parent.id
  62. # trying to get a hierarchical tag should result in the same
  63. # one already entered
  64. assert t.id == m.Tag.get(name="food/bread/rye").id
  65. assert t2.id == m.Tag.get(name="food/bread/baguette").id