fix(libutil-tests/nix_api_util): get rid of unnecessary memory leaks

This commit is contained in:
Sergei Zimmerman 2024-11-06 10:54:38 +03:00
parent 2ef5e222df
commit 2e7466a4e0

View file

@ -7,6 +7,8 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <memory>
namespace nixC { namespace nixC {
TEST_F(nix_api_util_context, nix_context_error) TEST_F(nix_api_util_context, nix_context_error)
@ -57,6 +59,14 @@ struct MySettings : nix::Config
MySettings mySettings; MySettings mySettings;
static nix::GlobalConfig::Register rs(&mySettings); static nix::GlobalConfig::Register rs(&mySettings);
static auto createOwnedNixContext()
{
return std::unique_ptr<nix_c_context, decltype([](nix_c_context * ctx) {
if (ctx)
nix_c_context_free(ctx);
})>(nix_c_context_create(), {});
}
TEST_F(nix_api_util_context, nix_setting_get) TEST_F(nix_api_util_context, nix_setting_get)
{ {
ASSERT_EQ(ctx->last_err_code, NIX_OK); ASSERT_EQ(ctx->last_err_code, NIX_OK);
@ -97,7 +107,8 @@ TEST_F(nix_api_util_context, nix_err_msg)
// advanced usage // advanced usage
unsigned int sz; unsigned int sz;
err_msg = nix_err_msg(nix_c_context_create(), ctx, &sz); auto new_ctx = createOwnedNixContext();
err_msg = nix_err_msg(new_ctx.get(), ctx, &sz);
ASSERT_EQ(sz, err_msg.size()); ASSERT_EQ(sz, err_msg.size());
} }
@ -113,7 +124,8 @@ TEST_F(nix_api_util_context, nix_err_info_msg)
} catch (...) { } catch (...) {
nix_context_error(ctx); nix_context_error(ctx);
} }
nix_err_info_msg(nix_c_context_create(), ctx, OBSERVE_STRING(err_info)); auto new_ctx = createOwnedNixContext();
nix_err_info_msg(new_ctx.get(), ctx, OBSERVE_STRING(err_info));
ASSERT_STREQ("testing error", err_info.c_str()); ASSERT_STREQ("testing error", err_info.c_str());
} }
@ -130,7 +142,8 @@ TEST_F(nix_api_util_context, nix_err_name)
} catch (...) { } catch (...) {
nix_context_error(ctx); nix_context_error(ctx);
} }
nix_err_name(nix_c_context_create(), ctx, OBSERVE_STRING(err_name)); auto new_ctx = createOwnedNixContext();
nix_err_name(new_ctx.get(), ctx, OBSERVE_STRING(err_name));
ASSERT_EQ(std::string(err_name), "nix::Error"); ASSERT_EQ(std::string(err_name), "nix::Error");
} }