TestDb.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os
  2. import cStringIO as StringIO
  3. from Config import config
  4. from Db import Db
  5. class TestDb:
  6. def testCheckTables(self, db):
  7. tables = [row["name"] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")]
  8. assert "keyvalue" in tables # To store simple key -> value
  9. assert "json" in tables # Json file path registry
  10. assert "test" in tables # The table defined in dbschema.json
  11. # Verify test table
  12. cols = [col["name"] for col in db.execute("PRAGMA table_info(test)")]
  13. assert "test_id" in cols
  14. assert "title" in cols
  15. # Add new table
  16. assert "newtest" not in tables
  17. db.schema["tables"]["newtest"] = {
  18. "cols": [
  19. ["newtest_id", "INTEGER"],
  20. ["newtitle", "TEXT"],
  21. ],
  22. "indexes": ["CREATE UNIQUE INDEX newtest_id ON newtest(newtest_id)"],
  23. "schema_changed": 1426195822
  24. }
  25. db.checkTables()
  26. tables = [row["name"] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")]
  27. assert "test" in tables
  28. assert "newtest" in tables
  29. def testQueries(self, db):
  30. # Test insert
  31. for i in range(100):
  32. db.execute("INSERT INTO test ?", {"test_id": i, "title": "Test #%s" % i})
  33. assert db.execute("SELECT COUNT(*) AS num FROM test").fetchone()["num"] == 100
  34. # Test single select
  35. assert db.execute("SELECT COUNT(*) AS num FROM test WHERE ?", {"test_id": 1}).fetchone()["num"] == 1
  36. # Test multiple select
  37. assert db.execute("SELECT COUNT(*) AS num FROM test WHERE ?", {"test_id": [1, 2, 3]}).fetchone()["num"] == 3
  38. assert db.execute(
  39. "SELECT COUNT(*) AS num FROM test WHERE ?",
  40. {"test_id": [1, 2, 3], "title": "Test #2"}
  41. ).fetchone()["num"] == 1
  42. assert db.execute(
  43. "SELECT COUNT(*) AS num FROM test WHERE ?",
  44. {"test_id": [1, 2, 3], "title": ["Test #2", "Test #3", "Test #4"]}
  45. ).fetchone()["num"] == 2
  46. # Test named parameter escaping
  47. assert db.execute(
  48. "SELECT COUNT(*) AS num FROM test WHERE test_id = :test_id AND title LIKE :titlelike",
  49. {"test_id": 1, "titlelike": "Test%"}
  50. ).fetchone()["num"] == 1
  51. def testUpdateJson(self, db):
  52. f = StringIO.StringIO()
  53. f.write("""
  54. {
  55. "test": [
  56. {"test_id": 1, "title": "Test 1 title", "extra col": "Ignore it"}
  57. ]
  58. }
  59. """)
  60. f.seek(0)
  61. assert db.updateJson(db.db_dir + "data.json", f) == True
  62. assert db.execute("SELECT COUNT(*) AS num FROM test_importfilter").fetchone()["num"] == 1
  63. assert db.execute("SELECT COUNT(*) AS num FROM test").fetchone()["num"] == 1