Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
nix_api_util.hh
Go to the documentation of this file.
1#pragma once
3#include "nix_api_util.h"
4
5#include <gtest/gtest.h>
6#include <string_view>
7
8namespace nixC {
9
10class nix_api_util_context : public ::testing::Test
11{
12protected:
13
14 nix_api_util_context()
15 {
16 ctx = nix_c_context_create();
17 nix_libutil_init(ctx);
18 };
19
20 ~nix_api_util_context() override
21 {
22 nix_c_context_free(ctx);
23 ctx = nullptr;
24 }
25
26 nix_c_context * ctx;
27
28 inline std::string loc(const char * file, int line)
29 {
30 return std::string(file) + ":" + std::to_string(line);
31 }
32
33 inline void assert_ctx_ok(const char * file, int line)
34 {
35 if (nix_err_code(ctx) == NIX_OK) {
36 return;
37 }
38 unsigned int n;
39 const char * p = nix_err_msg(nullptr, ctx, &n);
40 std::string msg(p, n);
41 throw std::runtime_error(loc(file, line) + ": nix_err_code(ctx) != NIX_OK, message: " + msg);
42 }
43
44#define assert_ctx_ok() assert_ctx_ok(__FILE__, __LINE__)
45
46 inline void assert_ctx_err(const char * file, int line)
47 {
48 if (nix_err_code(ctx) != NIX_OK) {
49 return;
50 }
51 throw std::runtime_error(loc(file, line) + ": Got NIX_OK, but expected an error!");
52 }
53
54#define assert_ctx_err() assert_ctx_err(__FILE__, __LINE__)
55};
56
57static inline auto createOwnedNixContext()
58{
59 return std::unique_ptr<nix_c_context, decltype([](nix_c_context * ctx) {
60 if (ctx)
61 nix_c_context_free(ctx);
62 })>(nix_c_context_create(), {});
63}
64
65} // namespace nixC