nim-datastore/tests/datastore/testdatabuffer.nim

108 lines
2.2 KiB
Nim
Raw Normal View History

2023-08-24 15:19:52 -07:00
import std/options
import std/sequtils
import std/algorithm
import std/locks
import std/os
2023-08-28 19:55:05 -07:00
import pkg/stew/byteutils
2023-08-24 15:19:52 -07:00
import pkg/unittest2
import pkg/questionable
import pkg/questionable/results
2023-09-14 18:42:58 -06:00
import pkg/datastore/key
2023-08-24 15:19:52 -07:00
2023-09-14 18:42:58 -06:00
include ../../datastore/threads/databuffer
2023-08-24 15:19:52 -07:00
var
shareVal: DataBuffer
lock: Lock
cond: Cond
var threads: array[2,Thread[int]]
proc thread1(val: int) {.thread.} =
echo "thread1"
{.cast(gcsafe).}:
for i in 0..<val:
os.sleep(20)
var myBytes2 = DataBuffer.new()
var myBytes = DataBuffer.new(@"hello world")
myBytes2 = myBytes
2023-08-28 19:44:41 -07:00
echo "thread1: sending: ", myBytes
echo "mybytes2: ", myBytes2
2023-08-24 15:19:52 -07:00
shareVal = myBytes
echo "thread1: sent, left over: ", $myBytes
lock.withLock:
signal(cond)
os.sleep(10)
proc thread2(val: int) {.thread.} =
echo "thread2"
{.cast(gcsafe).}:
for i in 0..<val:
lock.withLock:
wait(cond, lock)
echo "thread2: receiving "
let msg: DataBuffer = shareVal
2023-08-28 19:44:41 -07:00
echo "thread2: received: ", msg
2023-09-14 18:42:58 -06:00
check string.fromBytes(msg.toSeq()) == "hello world"
2023-08-24 15:19:52 -07:00
# os.sleep(100)
proc runBasicTest() =
echo "running"
lock.initLock()
cond.initCond()
let n = 1
createThread(threads[0], thread1, n)
createThread(threads[1], thread2, n)
joinThreads(threads)
suite "Share buffer test":
2023-09-14 18:42:58 -06:00
var
k1: Key
k2: Key
a: DataBuffer
b: DataBuffer
c: DataBuffer
2023-08-24 15:19:52 -07:00
2023-08-28 19:51:34 -07:00
setup:
2023-09-14 18:42:58 -06:00
k1 = Key.init("/a/b").tryGet()
k2 = Key.init("/a").tryGet()
a = DataBuffer.new($k1)
b = DataBuffer.new($Key.init("/a/b").tryGet())
c = DataBuffer.new($k2)
2023-08-28 19:51:34 -07:00
test "creation":
let db = DataBuffer.new("abc")
check db[].size == 3
check db[].buf[0].char == 'a'
check db[].buf[1].char == 'b'
check db[].buf[2].char == 'c'
2023-09-14 18:42:58 -06:00
2023-08-28 19:51:34 -07:00
test "equality":
check a == b
2023-09-14 18:42:58 -06:00
2023-08-28 19:51:34 -07:00
test "toString":
2023-09-14 18:42:58 -06:00
check $a == "/a/b"
2023-08-28 19:51:34 -07:00
test "hash":
check a.hash() == b.hash()
2023-09-14 18:42:58 -06:00
2023-08-28 19:51:34 -07:00
test "hashes differ":
check a.hash() != c.hash()
2023-09-14 18:42:58 -06:00
2023-08-28 19:55:05 -07:00
test "key conversion":
2023-09-14 18:42:58 -06:00
check Key.init(a).tryGet == k1
2023-08-28 19:55:05 -07:00
test "seq conversion":
2023-09-14 18:42:58 -06:00
check string.fromBytes(a.toSeq()) == "/a/b"
2023-08-28 19:55:05 -07:00
test "seq conversion":
2023-09-14 18:42:58 -06:00
check a.toSeq() == "/a/b".toBytes
2023-08-28 19:51:34 -07:00
test "basic thread test":
2023-08-24 15:19:52 -07:00
runBasicTest()