|
| 1 | +import unittest |
| 2 | +import os |
| 3 | +import ../../src/engine |
| 4 | +import ../../src/c_api |
| 5 | +import ../../src/errors |
| 6 | + |
| 7 | +proc makeTempDb(name: string): string = |
| 8 | + let path = getTempDir() / name |
| 9 | + if fileExists(path): removeFile(path) |
| 10 | + if fileExists(path & ".wal"): removeFile(path & ".wal") |
| 11 | + path |
| 12 | + |
| 13 | +suite "Memory leak tests for open/close cycles": |
| 14 | + test "opening and closing db connections many times via core engine should not leak memory": |
| 15 | + let path = makeTempDb("decentdb_engine_leak_test.db") |
| 16 | + |
| 17 | + # Warm up / initialize anything that might do lazy init |
| 18 | + for i in 1..5: |
| 19 | + let dbRes = openDb(path) |
| 20 | + require(dbRes.ok) |
| 21 | + discard dbRes.value.closeDb() |
| 22 | + |
| 23 | + GC_fullCollect() |
| 24 | + let initMem = getOccupiedMem() |
| 25 | + |
| 26 | + for i in 1..2000: |
| 27 | + let dbRes = openDb(path) |
| 28 | + doAssert(dbRes.ok) |
| 29 | + discard dbRes.value.closeDb() |
| 30 | + |
| 31 | + GC_fullCollect() |
| 32 | + let finalMem = getOccupiedMem() |
| 33 | + |
| 34 | + let diff = int(finalMem) - int(initMem) |
| 35 | + echo "Engine Initial Mem: ", initMem, " Final Mem: ", finalMem, " Diff: ", diff |
| 36 | + # A tiny bit of fluctuation might happen, restrict it strictly |
| 37 | + require(diff < 200000) |
| 38 | + |
| 39 | + test "opening and closing db connections many times via C API should not leak memory": |
| 40 | + let path = makeTempDb("decentdb_capi_leak_test.db") |
| 41 | + |
| 42 | + # Warm up |
| 43 | + for i in 1..5: |
| 44 | + let db = decentdb_open(path.cstring, "".cstring) |
| 45 | + require(db != nil) |
| 46 | + discard decentdb_close(db) |
| 47 | + |
| 48 | + GC_fullCollect() |
| 49 | + let initMem = getOccupiedMem() |
| 50 | + |
| 51 | + for i in 1..2000: |
| 52 | + let db = decentdb_open(path.cstring, "".cstring) |
| 53 | + doAssert(db != nil) |
| 54 | + discard decentdb_close(db) |
| 55 | + |
| 56 | + GC_fullCollect() |
| 57 | + let finalMem = getOccupiedMem() |
| 58 | + |
| 59 | + let diff = int(finalMem) - int(initMem) |
| 60 | + echo "C API Initial Mem: ", initMem, " Final Mem: ", finalMem, " Diff: ", diff |
| 61 | + require(diff < 200000) |
| 62 | + |
0 commit comments