Hey everyone,
I just started looking into Zig as an interesting alternative for programming in C/Go/rust. In order to learn more about the language I started dabbling around with it. And since I found the high C-interoperability highly interesting, and with C lacking sound and built-in support for testing, I started with unit testing C code in zig. And maybe my question has been asked to death already…
I have a bunch of C code that I try to cover with zig tests instead of having my tests written in a custom C unit test framework. I have all the basics (calling C from zig, passing arguments, getting stuff back) figured out. The only thing I can’t wrap my head around is how to test cstrings returned from my C code in a good way.
Here’s an example of what I fight with. I have a C function with this signature:
const char* kv_store_get(kv_store* store, const char* key);
A fairly simple function that, as the name suggests, retrieves the value that matches the key stored in an inmemory key-value-store. Nothing fancy. It returns a char*
with a copy of the data from the key-value-store.
I already have a working zig test that checks if a key and value can be stored and retrieved correctly. It looks like this:
test "kvstore: put and get a value" {
const store = ckvstore.create_kv_store(1);
try std.testing.expect(store != null);
const key = "key";
const value: [*:0]const u8 = "value";
const result = ckvstore.kv_store_put(store, key, value);
try std.testing.expect(result == 0);
const retrieved_value = ckvstore.kv_store_get(store, key);
// this here is my workaround:
try std.testing.expect(C.strcmp(retrieved_value, value) == 0);
ckvstore.free_kv_store(store);
}
What bothers me is that I could not manage checking the returned string and comparing it with the initially stored value by using zig-native functions. Eventually I resorted to using strcmp
from native C.
I tried working with std.mem.eql
in different variations of
try std.mem.eql(u8, retrieved_value, value);
but I could not match the datatype of the cstring correctly and always get stuck at a variation of this error:
test\server_test.zig:24:25: error: expected type '[]const u8', found '[*c]const u8'
try std.mem.eql(u8, retrieved_value, value);
Any help and explanation of which concepts I (obviously) got wrong is highly appriciated. Thanks!