testing: touch
[m6w6/libmemcached] / test / lib / common.hpp
1 #pragma once
2
3 #include <chrono>
4 #include <iostream>
5 #include <map>
6 #include <optional>
7 #include <string>
8 #include <sstream>
9 #include <stdexcept>
10 #include <thread>
11 #include <variant>
12 #include <vector>
13
14 #include "test/conf.h"
15 #include "test/lib/catch.hpp"
16 #include "test/lib/random.hpp"
17
18 #include "libmemcached/memcached.h"
19
20 using namespace std;
21 using socket_or_port_t = variant<string, int>;
22
23 /**
24 * Useful macros for testing
25 */
26 #define S(s) (s),strlen(s)
27 #define DECLARE_STREQUAL static auto strequal = equal_to<string>();
28 #define LOOPED_SECTION(tests) \
29 for (auto &[name, test] : tests) DYNAMIC_SECTION("test " << name)
30 #define REQUIRE_SUCCESS(rc) do { \
31 INFO("expected: SUCCESS"); \
32 REQUIRE_THAT(rc, test.returns.success()); \
33 } while(0)
34 #define REQUIRE_RC(rc, call) do { \
35 INFO("expected: " << memcached_strerror(nullptr, rc)); \
36 REQUIRE_THAT(call, test.returns(rc)); \
37 } while(0)
38
39 const char *getenv_else(const char *var, const char *defval);
40
41 inline memcached_return_t fetch_all_results(memcached_st *memc, unsigned int &keys_returned, memcached_return_t &rc) {
42 keys_returned = 0;
43
44 memcached_result_st *result = nullptr;
45 while ((result = memcached_fetch_result(memc, result, &rc))) {
46 REQUIRE(MEMCACHED_SUCCESS == rc);
47 keys_returned += 1;
48 }
49 memcached_result_free(result);
50 return MEMCACHED_SUCCESS;
51 }
52
53 inline memcached_return_t fetch_all_results(memcached_st *memc, unsigned int &keys_returned) {
54 memcached_return_t rc;
55 fetch_all_results(memc, keys_returned, rc);
56 return rc;
57 }
58
59 #include <cstdlib>
60 #include <unistd.h>
61
62 class Tempfile {
63 public:
64 explicit Tempfile(const char templ_[] = "memc.test.XXXXXX") {
65 *copy(S(templ_)+templ_, fn) = '\0';
66 fd = mkstemp(fn);
67 }
68 ~Tempfile() {
69 close(fd);
70 unlink(fn);
71 }
72 int getFd() const {
73 return fd;
74 }
75 const char *getFn() const {
76 return fn;
77 }
78 bool put(const char *buf, size_t len) const {
79 return static_cast<ssize_t >(len) == write(fd, buf, len);
80 }
81 private:
82 char fn[80];
83 int fd;
84 };
85
86 class MemcachedPtr {
87 public:
88 memcached_st *memc;
89
90 explicit
91 MemcachedPtr(memcached_st *memc_) {
92 memc = memc_;
93 }
94 MemcachedPtr()
95 : MemcachedPtr(memcached_create(nullptr))
96 {}
97 ~MemcachedPtr() {
98 memcached_free(memc);
99 }
100 memcached_st *operator * () const {
101 return memc;
102 }
103 auto operator ->() const{
104 return memc;
105 }
106 };
107
108 template<class T>
109 class Malloced {
110 T *ptr;
111 public:
112 explicit
113 Malloced(T *ptr_)
114 : ptr{ptr_}
115 {}
116 Malloced &operator=(T *ptr_) {
117 if (ptr)
118 free(ptr);
119 ptr = ptr_;
120 return *this;
121 }
122 ~Malloced() {
123 if(ptr)
124 free(ptr);
125 }
126 auto operator *() {
127 return ptr;
128 }
129 auto operator ->() {
130 return ptr;
131 }
132 };