Commit ab08d21b by tianxing wang

Initial commit

parents
.cache
cmake-build-debug
.idea
.vscode
build
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CUDA_ARCHITECTURES 86)
set(CUDAToolkit_ROOT ~/.local/cuda)
set(CUDA_TOOLKIT_ROOT_DIR ~/.local/cuda11.8+cudnn8.9)
set(CMAKE_CUDA_COMPILER /home/wtx/.local/cuda/bin/nvcc)
project(gpucache CXX CUDA)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED on)
set(CMAKE_EXPORT_COMPILE_COMMANDS on)
file(GLOB SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/hash/*.cu
)
set(Torch_DIR ~/miniconda3/envs/dgl/lib/python3.10/site-packages/torch/share/cmake/Torch)
find_package(Torch REQUIRED)
set(Python3_ROOT_DIR ~/miniconda3/envs/dgl)
find_package (Python3 COMPONENTS Interpreter Development REQUIRED)
set(LIB_NAME gpucache)
add_library(${LIB_NAME} SHARED ${SOURCE_FILES})
set_target_properties(${LIB_NAME} PROPERTIES
CUDA_SEPARABLE_COMPILATION ON
CUDA_ARCHITECTURES "86"
)
target_include_directories(${LIB_NAME} PRIVATE /home/wtx/miniconda3/envs/dgl/include/python3.10) # path to your Python.h
target_compile_options(${LIB_NAME} PRIVATE ${TORCH_CXX_FLAGS} -O3)
target_link_libraries(${LIB_NAME} PRIVATE ${TORCH_LIBRARIES})
target_compile_definitions(${LIB_NAME} PRIVATE -DTORCH_EXTENSION_NAME=lib${LIB_NAME})
find_library(TORCH_PYTHON_LIBRARY torch_python "${TORCH_INSTALL_PREFIX}/lib" REQUIRED)
target_link_libraries(${LIB_NAME} PRIVATE ${TORCH_PYTHON_LIBRARY})
message(STATUS "TORCH_PYTHON_LIBRARY: " ${TORCH_PYTHON_LIBRARY})
This source diff could not be displayed because it is too large. You can view the blob instead.
File added
This diff is collapsed. Click to expand it.
#include "cache_wrapper.cuh"
#include "fifo_cache.cuh"
#include "lru_cache.cuh"
#include "lfu_cache.cuh"
// CacheWrapper API
namespace gpucache {
template<typename ElemType>
void NewInt32Cache(void **cache, CacheConfig cfg) {
void* c;
switch (cfg.strategy) {
case CacheConfig::CacheEvictStrategy::LRU:
c = new LRUCache<int32_t, ElemType>(cfg);
break;
case CacheConfig::CacheEvictStrategy::LFU:
c = new LFUCache<int32_t, ElemType>(cfg);
break;
case CacheConfig::CacheEvictStrategy::FIFO:
c = new FIFOCache<int32_t, ElemType>(cfg);
break;
}
//std::cout << "NewInt32Cache Cache keysize " << c->keySize << std::endl;
*cache = reinterpret_cast<void *>(c);
}
template<typename ElemType>
void NewInt64Cache(void **cache, CacheConfig cfg) {
void* c;
switch (cfg.strategy) {
case CacheConfig::CacheEvictStrategy::LRU:
c = new LRUCache<int64_t, ElemType>(cfg);
break;
case CacheConfig::CacheEvictStrategy::LFU:
c = new LFUCache<int64_t, ElemType>(cfg);
break;
case CacheConfig::CacheEvictStrategy::FIFO:
c = new FIFOCache<int64_t, ElemType>(cfg);
break;
}
*cache = reinterpret_cast<void *>(c);
}
CacheWrapper::CacheWrapper(torch::Tensor t, CacheConfig cfg) {
//std::cout << "CacheWrapper constructor" << std::endl;
vtype = t.scalar_type();
cache_cfg = cfg;
key_is_int32 = cfg.capacity < INT32_MAX;
if (key_is_int32) {
ktype = torch::kInt32;
AT_DISPATCH_ALL_TYPES(t.scalar_type(), "int32_cache", [&] {
NewInt32Cache<scalar_t>(&cache, cfg);
});
} else {
ktype = torch::kInt64;
AT_DISPATCH_ALL_TYPES(t.scalar_type(), "int64_cache", [&] {
NewInt64Cache<scalar_t>(&cache, cfg);
});
}
// AT_DISPATCH_ALL_TYPES(dtype,"cache_test",[&]{
// auto c = reinterpret_cast<Cache<int32_t,scalar_t>*>(cache);
// std::cout << "CacheWrapper constructor Cache dim: " << c->Dim() << " keySize: " << c->KeySize() << "\n";
// });
// std::cout << "CacheWrapper constructor dtype: " << dtype << " kdtype: " << kdtype << "\n";
}
CacheWrapper::~CacheWrapper() {
if (key_is_int32) {
AT_DISPATCH_ALL_TYPES(vtype, "int32_destructor", [&] {
auto c = reinterpret_cast<Cache<int32_t, scalar_t> *>(cache);
delete c;
});
} else {
AT_DISPATCH_ALL_TYPES(vtype, "int64_destructor", [&] {
auto c = reinterpret_cast<Cache<int64_t, scalar_t> *>(cache);
delete c;
});
}
//std::cout << "~LRUCacheWrapper()" << std::endl;
}
std::pair<torch::Tensor, torch::Tensor> CacheWrapper::Get(uint32_t num_query, const torch::Tensor queries) {
assert(queries.device().index() == cache_cfg.device_id &&
"query keys and cache should be in the same device");
assert(queries.size(0) == num_query && "num_query should equal queries.size(0)");
assert(num_query <= cache_cfg.max_query_num && "num_query must less than max_query_num");
assert(queries.dtype().toScalarType() == ktype && "key type doesn't match");
//std::cout << "Get queries: " << queries << std::endl;
// printf("hello!!!\n");
//std::cout << "Get num_query: " << num_query <<"\n";
//std::cout << "Get queries.sizes() " << queries.sizes() << "\n";
auto keys = queries.data_ptr();
auto stream = at::cuda::getCurrentCUDAStream(cache_cfg.device_id).stream();
auto result = torch::empty({num_query, cache_cfg.dim},
torch::dtype(vtype).device(torch::kCUDA, cache_cfg.device_id));
auto find_mask = torch::empty({num_query},
torch::dtype(torch::kBool).device(torch::kCUDA, cache_cfg.device_id));
if (key_is_int32) {
AT_DISPATCH_ALL_TYPES(vtype, "int32_get", [&] {
Cache<int32_t, scalar_t> *c = reinterpret_cast<Cache<int32_t, scalar_t> *>(cache);
// cache->Test();
//std::cout << "keysize: " << cache->KeySize() << "\n";
//std::cout << "dim: " << cache->Dim() << "\n";
c->Get(stream, num_query, reinterpret_cast<int32_t *>(keys),
reinterpret_cast<scalar_t *>(result.data_ptr()),
reinterpret_cast<bool *>(find_mask.data_ptr()));
});
} else {
//std::cout << "int64_lru_get" << "\n";
AT_DISPATCH_ALL_TYPES(vtype, "int64_lru_get", [&] {
Cache<int64_t, scalar_t> *c = reinterpret_cast<Cache<int64_t, scalar_t> *>(cache);
//std::cout << "cast success!" << std::endl;
c->Get(stream, num_query, reinterpret_cast<int64_t *>(keys),
reinterpret_cast<scalar_t *>(result.data_ptr()),
reinterpret_cast<bool *>(find_mask.data_ptr()));
});
}
return std::make_pair(result, find_mask);
}
void CacheWrapper::Put(uint32_t num_query, const torch::Tensor keys, const torch::Tensor values) {
assert(keys.device().index() == cache_cfg.device_id && cache_cfg.device_id == values.device().index() &&
"put keys, put values and cache should be in the same device");
assert(num_query == keys.size(0) && keys.size(0) == values.size(0) &&
"dim 0 of keys,values and num_query should be equal");
assert(num_query <= cache_cfg.max_query_num && "num_query must less than max_query_num");
assert(values.dtype() == vtype);
auto stream = at::cuda::getCurrentCUDAStream(cache_cfg.device_id).stream();
if (key_is_int32) {
//std::cout << "int32_put" << "\n";
AT_DISPATCH_ALL_TYPES(vtype, "int32_put", [&] {
auto c = reinterpret_cast<Cache<int32_t, scalar_t> *>(cache);
//std::cout << "put_dim" << cache->Dim() << std::endl;
c->Put(stream, num_query, reinterpret_cast<int32_t *>(keys.data_ptr()),
reinterpret_cast<scalar_t *>(values.data_ptr()));
});
} else {
//std::cout << "int64_put" << "\n";
AT_DISPATCH_ALL_TYPES(vtype, "int64_put", [&] {
auto c = reinterpret_cast<Cache<int64_t, scalar_t> *>(cache);
c->Put(stream, num_query, reinterpret_cast<int64_t *>(keys.data_ptr()),
reinterpret_cast<scalar_t *>(values.data_ptr()));
});
}
}
CacheConfig::CacheEvictStrategy CacheWrapper::Strategy() {
return cache_cfg.strategy;
}
uint64_t CacheWrapper::Capacity() { return cache_cfg.capacity; }
uint32_t CacheWrapper::KeySize() { return cache_cfg.key_size; }
uint32_t CacheWrapper::ValueSize() { return cache_cfg.value_size; }
uint32_t CacheWrapper::MaxQueryNum() { return cache_cfg.max_query_num; }
uint64_t CacheWrapper::DeviceId() { return cache_cfg.device_id; }
uint32_t CacheWrapper::Dim() { return cache_cfg.dim; }
void CacheWrapper::Clear() {
if (key_is_int32) {
AT_DISPATCH_ALL_TYPES(vtype, "int32_clear", [&] {
auto c = reinterpret_cast<Cache<int32_t, scalar_t> *>(cache);
c->Clear();
});
} else {
AT_DISPATCH_ALL_TYPES(vtype, "int64_clear", [&] {
auto c = reinterpret_cast<Cache<int64_t, scalar_t> *>(cache);
c->Clear();
});
}
}
std::unique_ptr<CacheWrapper> NewCache(at::Tensor t, CacheConfig cfg) {
return std::make_unique<CacheWrapper>(t, cfg);
}
} // namespace gpucache
\ No newline at end of file
#pragma once
#include "common.cuh"
namespace gpucache{
class CacheWrapper {
public:
CacheWrapper(at::Tensor t, CacheConfig cfg);
~CacheWrapper();
std::pair<torch::Tensor, torch::Tensor> Get(uint32_t num_query, const torch::Tensor queries);
void Put(uint32_t num_query, const torch::Tensor keys, const torch::Tensor values);
CacheConfig::CacheEvictStrategy Strategy();
uint64_t Capacity();
uint32_t KeySize();
uint32_t ValueSize();
uint32_t MaxQueryNum();
uint64_t DeviceId();
uint32_t Dim();
void Clear();
private:
void *cache;
c10::ScalarType vtype; // value dtype
c10::ScalarType ktype; // key dtype
bool key_is_int32; // only support int32 and int64
CacheConfig cache_cfg;
};
std::unique_ptr<CacheWrapper> NewCache(at::Tensor t, CacheConfig cfg);
}
#pragma once
#include <c10/cuda/CUDAStream.h>
#include <torch/extension.h>
#include <cstdint>
#include <cassert>
#include <cstdio>
#include <cuda_runtime.h>
#include <memory>
#include "utils.h"
#include "hash/hash.h"
#define CUDA_CHECK(call) \
{ \
const cudaError_t error = call; \
if (error != cudaSuccess) \
{ \
fprintf(stderr, "Error: %s:%d, ", __FILE__, __LINE__); \
fprintf(stderr, "code: %d, reason: %s\n", error, \
cudaGetErrorString(error)); \
} \
}
#define DISPATCH_GET(strategy, grid, block, smem, stream, ...) \
{ \
switch (strategy){ \
case CacheConfig::CacheEvictStrategy::LRU: \
GetInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::LRU><<<grid, block, smem, stream>>>(__VA_ARGS__); \
break; \
case CacheConfig::CacheEvictStrategy::FIFO: \
GetInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::FIFO><<<grid, block, smem, stream>>>(__VA_ARGS__);\
break; \
case CacheConfig::CacheEvictStrategy::LFU: \
GetInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::LFU><<<grid, block, smem, stream>>>(__VA_ARGS__); \
break; \
} \
}
#define DISPATCH_PUT(strategy, grid, block, smem, stream, ...) \
{ \
switch (strategy){ \
case CacheConfig::CacheEvictStrategy::LRU: \
PutWithoutEvictInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::LRU><<<grid, block, smem, stream>>>(__VA_ARGS__); \
break; \
case CacheConfig::CacheEvictStrategy::FIFO: \
PutWithoutEvictInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::FIFO><<<grid, block, smem, stream>>>(__VA_ARGS__);\
break; \
case CacheConfig::CacheEvictStrategy::LFU: \
PutWithoutEvictInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::LFU><<<grid, block, smem, stream>>>(__VA_ARGS__); \
break; \
} \
}
#define DISPATCH_EVICT(strategy, grid, block, smem, stream, ...) \
{ \
switch (strategy){ \
case CacheConfig::CacheEvictStrategy::LRU: \
EvictInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::LRU><<<grid, block, smem, stream>>>(__VA_ARGS__); \
break; \
case CacheConfig::CacheEvictStrategy::FIFO: \
EvictInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::FIFO><<<grid, block, smem, stream>>>(__VA_ARGS__);\
break; \
case CacheConfig::CacheEvictStrategy::LFU: \
EvictInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::LFU><<<grid, block, smem, stream>>>(__VA_ARGS__); \
break; \
} \
}
//#define CAST_CACHE_INT32(c, strategy) \
//{ \
// switch (strategy){ \
// case CacheConfig::CacheEvictStrategy::LRU: \
// c = reinterpret_cast<LRUCache> \
// break; \
// case CacheConfig::CacheEvictStrategy::FIFO: \
// EvictInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::FIFO><<<grid, block, smem, stream>>>(__VA_ARGS__);\
// break; \
// case CacheConfig::CacheEvictStrategy::LFU: \
// EvictInternal<KeyType,ElemType,CacheConfig::CacheEvictStrategy::LFU><<<grid, block, smem, stream>>>(__VA_ARGS__); \
// break; \
// }
//}
//
//
//
//#define CAST_CACHE(c, strategy,is_int32) \
//{ \
// if(is_int32){ \
// CAST_CACHE_INT32(c,strategy)\
// }else{ \
// CAST_CACHE_INT64(c,strategy)\
// }\
//}
//
#include <pybind11/pybind11.h>
#include "cache_wrapper.cuh"
namespace py = pybind11;
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
/* CacheConfig */
/*-----------------------------------------------------------------------------------------------------------------------------------*/
py::class_<gpucache::CacheConfig> cfg(m, "CacheConfig");
cfg.def(py::init<>())
.def(py::init<gpucache::CacheConfig::CacheEvictStrategy, uint64_t, uint32_t, uint32_t, uint32_t, int8_t, uint32_t>())
.def_readwrite("strategy", &gpucache::CacheConfig::strategy)
.def_readwrite("capacity", &gpucache::CacheConfig::capacity)
.def_readwrite("keySize", &gpucache::CacheConfig::key_size)
.def_readwrite("valueSize", &gpucache::CacheConfig::value_size)
.def_readwrite("maxQueryNum", &gpucache::CacheConfig::max_query_num)
.def_readwrite("deviceId", &gpucache::CacheConfig::device_id)
.def_readwrite("dim", &gpucache::CacheConfig::dim);
py::enum_<gpucache::CacheConfig::CacheEvictStrategy>(cfg, "CacheEvictStrategy")
.value("LRU", gpucache::CacheConfig::CacheEvictStrategy::LRU)
.value("LFU", gpucache::CacheConfig::CacheEvictStrategy::LFU)
.value("FIFO", gpucache::CacheConfig::CacheEvictStrategy::FIFO)
.export_values();
/*-----------------------------------------------------------------------------------------------------------------------------------*/
/* CacheWrapper */
/*-----------------------------------------------------------------------------------------------------------------------------------*/
py::class_<gpucache::CacheWrapper> cache(m, "Cache");
cache
.def(py::init<at::Tensor, gpucache::CacheConfig>())
.def("Get",&gpucache::CacheWrapper::Get,"get values for keys, find_mask return whether each key exists in cache")
.def("Put",&gpucache::CacheWrapper::Put,"put key-value pairs")
.def("Strategy",&gpucache::CacheWrapper::Strategy,"get evict strategy")
.def("Capacity",&gpucache::CacheWrapper::Capacity,"return cache capacity")
.def("KeySize",&gpucache::CacheWrapper::KeySize,"return key size")
.def("ValueSize",&gpucache::CacheWrapper::ValueSize,"return value size")
.def("MaxQueryNum",&gpucache::CacheWrapper::MaxQueryNum,"return max number of keys to get or key-values to put once")
.def("Clear",&gpucache::CacheWrapper::Clear,"clear cache")
.def("Device",&gpucache::CacheWrapper::DeviceId,"return device id")
.def("Dim",&gpucache::CacheWrapper::Dim,"return value dim");
m.def("NewCache", &gpucache::NewCache, "create a lru cache",py::return_value_policy::reference);
/*-----------------------------------------------------------------------------------------------------------------------------------*/
}
\ No newline at end of file
#pragma once
#include "cache.cuh"
namespace gpucache{
template<typename KeyType, typename ElemType, CacheConfig::CacheEvictStrategy Strategy>
struct BucketView;
template<typename KeyType, typename ElemType>
struct BucketView<KeyType,ElemType,CacheConfig::CacheEvictStrategy::FIFO> {
__device__ BucketView(KeyType *k, ElemType *v, uint8_t *ts, WarpMutex *m, uint32_t num_elems_per_value)
: mutex(m), bkeys(k), bvalues(v), btimestamps(ts), num_elems_per_value(num_elems_per_value) {}
__device__ int Get(const ThreadCtx &ctx, const KeyType key) {
KeyType lane_key = bkeys[ctx.lane_id];
KeyType ts = btimestamps[ctx.lane_id];
bool exist = (ts > 0 && lane_key == key);
uint32_t exist_mask = __ballot_sync(warpFullMask, exist);
int slot_num = __ffs(exist_mask) - 1; // if not exist slot_num is -1
return slot_num;
}
__device__ int TryPut(const ThreadCtx &ctx, const KeyType key) {
KeyType lane_key = bkeys[ctx.lane_id];
KeyType ts = btimestamps[ctx.lane_id];
bool exist = (ts > 0 && lane_key == key);
uint32_t exist_mask = __ballot_sync(warpFullMask, exist);
int slot_num = __ffs(exist_mask) - 1;
if (slot_num == -1) { // key doesn't exist
// if(ctx.lane_id == 0){
// printf("key %u doesn't exist\n",key);
// }
uint32_t empty_mask = __ballot_sync(warpFullMask, ts != 0);
// if(ctx.lane_id == 0){
// printf("try put key %u, empty_mask %u\n",key,empty_mask);
// }
if (empty_mask != warpFullMask) { // bucket not full
slot_num = __popc(empty_mask);
if (ts > 0) {
ts++;
} else if (ctx.lane_id == slot_num) {
bkeys[slot_num] = key;
ts = 1;
}
}
}
btimestamps[ctx.lane_id] = ts;
//printf("thread %u set btimestamps[%u] = %u\n",ctx.lane_id,ctx.lane_id,ts);
return slot_num;
}
__device__ int Evict(const ThreadCtx &ctx, const KeyType key, KeyType *evict_key) {
KeyType lane_key = bkeys[ctx.lane_id];
uint8_t ts = btimestamps[ctx.lane_id];
uint32_t evict_mask = __ballot_sync(warpFullMask, ts == 32);
int slot_num = __ffs(evict_mask) - 1;
if (slot_num == ctx.lane_id) {
ts = 1;
*evict_key = lane_key;
bkeys[ctx.lane_id] = key;
} else {
ts++;
}
btimestamps[ctx.lane_id] = ts;
return slot_num;
}
__device__ void ReadOneValue(const ThreadCtx &ctx, uint8_t slot_num,
ElemType *out) {
for (size_t i = ctx.lane_id; i < num_elems_per_value; i += warpSize) {
out[i] = bvalues[slot_num * num_elems_per_value + i];
}
}
__device__ void WriteOneValue(const ThreadCtx &ctx, uint8_t slot_num,
ElemType *v) {
for (size_t i = ctx.lane_id; i < num_elems_per_value; i += warpSize) {
bvalues[slot_num * num_elems_per_value + i] = v[i];
}
}
WarpMutex *mutex;
KeyType *bkeys;
ElemType *bvalues;
uint8_t *btimestamps;
uint32_t num_elems_per_value;
};
template<typename KeyType, typename ElemType>
class FIFOCache: public Cache<KeyType, ElemType>{
public:
explicit FIFOCache(CacheConfig cfg):Cache<KeyType,ElemType>(cfg){
// this->manager = new LRUCacheManager<KeyType,ElemType>();
}
~FIFOCache(){
// delete this->manager;
}
};
template<typename KeyType, typename ElemType>
FIFOCache<KeyType,ElemType>* NewFIFOCache(CacheConfig cfg){
return new FIFOCache<KeyType,ElemType>(cfg);
}
}
#pragma once
#include <cuda_runtime.h>
constexpr uint32_t seed = 0X12fb73ac;
__device__ void MurmurHash3_x86_32 ( const void * key, int len,
uint32_t seed, void * out );
template<typename KeyType>
__device__ size_t getHash(const KeyType obj){
size_t hash;
MurmurHash3_x86_32(reinterpret_cast<const void*>(&obj),sizeof(KeyType),seed,reinterpret_cast<void*>(&hash));
return hash;
}
// copy from https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp
#define FORCE_INLINE inline __attribute__((always_inline))
__device__ inline uint32_t rotl32 ( uint32_t x, int8_t r )
{
return (x << r) | (x >> (32 - r));
}
#define ROTL32(x,y) rotl32(x,y)
__device__ FORCE_INLINE uint32_t fmix32 ( uint32_t h )
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
__device__ void MurmurHash3_x86_32 ( const void * key, int len,
uint32_t seed, void * out )
{
const uint8_t * data = (const uint8_t*)key;
const int nblocks = len / 4;
uint32_t h1 = seed;
const uint32_t c1 = 0xcc9e2d51;
const uint32_t c2 = 0x1b873593;
//----------
// body
const uint32_t * blocks = (const uint32_t *)(data + nblocks*4);
for(int i = -nblocks; i; i++)
{
uint32_t k1 = blocks[i];
k1 *= c1;
k1 = ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = ROTL32(h1,13);
h1 = h1*5+0xe6546b64;
}
//----------
// tail
const uint8_t * tail = (const uint8_t*)(data + nblocks*4);
uint32_t k1 = 0;
switch(len & 3)
{
case 3: k1 ^= tail[2] << 16;
case 2: k1 ^= tail[1] << 8;
case 1: k1 ^= tail[0];
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
};
//----------
// finalization
h1 ^= len;
h1 = fmix32(h1);
*(uint32_t*)out = h1;
}
#pragma once
#include "cache.cuh"
namespace gpucache{
template<typename KeyType, typename ElemType, CacheConfig::CacheEvictStrategy Strategy>
struct BucketView;
template<typename KeyType, typename ElemType>
struct BucketView<KeyType,ElemType,CacheConfig::CacheEvictStrategy::LFU> {
__device__ BucketView(KeyType *k, ElemType *v, uint8_t *ts, WarpMutex *m,
uint32_t num_elems_per_value)
: mutex(m), bkeys(k), bvalues(v), btimestamps(ts),
num_elems_per_value(num_elems_per_value) {}
__device__ int Get(const ThreadCtx &ctx, const KeyType key) {
KeyType lane_key = bkeys[ctx.lane_id];
uint8_t ts = btimestamps[ctx.lane_id];
bool exist = (ts > 0 && lane_key == key);
uint32_t exist_mask = __ballot_sync(warpFullMask, exist);
int slot_num = __ffs(exist_mask) - 1;
if (exist_mask == 0) { // not found
return -1;
} else {
if (ctx.lane_id != slot_num && ts > 1) { // decrease the counter
btimestamps[ctx.lane_id] = ts - 1;
}
return slot_num; // return exist slot num
};
}
__device__ int TryPut(const ThreadCtx &ctx, const KeyType key) {
KeyType lane_key = bkeys[ctx.lane_id];
uint8_t ts = btimestamps[ctx.lane_id];
bool exist = (ts > 0 && lane_key == key);
uint32_t exist_mask = __ballot_sync(warpFullMask, exist);
int slot_num = __ffs(exist_mask) - 1;
if (exist_mask != 0) {
if (ctx.lane_id == slot_num) {
ts = warpSize;
}
__syncwarp();
}
if (slot_num == -1) { // key don't exist
uint32_t emptyMask = __ballot_sync(warpFullMask, ts != 0);
if (emptyMask != warpFullMask) { // bucket not full
slot_num = __popc(emptyMask);
if (ctx.lane_id == slot_num) {
bkeys[slot_num] = key;
ts = warpSize;
}
}
__syncwarp();
}
btimestamps[ctx.lane_id] = ts;
return slot_num;
}
__device__ int Evict(const ThreadCtx &ctx, const KeyType key,
KeyType *evict_key) {
KeyType lane_key = bkeys[ctx.lane_id];
uint8_t ts = btimestamps[ctx.lane_id];
uint32_t evict_mask = __ballot_sync(warpFullMask, ts == 1);
int slot_num = __ffs(evict_mask) - 1;
if(slot_num == -1){ // no ts equals 1, do warp reduction find min ts > 0
uint8_t min_ts = ts;
uint32_t min_ts_lane_id = ctx.lane_id;
uint32_t reduce_mask = __ballot_sync(warpFullMask, ts != 0);
for(int offset = 16; offset > 0; offset /= 2){
uint8_t temp_ts = __shfl_down_sync(reduce_mask,ts,offset);
if(temp_ts != 0 && temp_ts < min_ts){
min_ts = temp_ts;
min_ts_lane_id = ctx.lane_id + offset;
}
}
slot_num = __shfl_sync(warpFullMask, min_ts_lane_id, 0);
// if(ctx.lane_id == 0){
// printf("evict slot_num %d, ts = %u",slot_num,ts);
// }
}
if(ctx.lane_id == slot_num) {
*evict_key = lane_key;
bkeys[slot_num] = key;
btimestamps[slot_num] = warpSize;
}
return slot_num;
}
__device__ void ReadOneValue(const ThreadCtx &ctx, uint8_t slot_num,
ElemType *out) {
for (size_t i = ctx.lane_id; i < num_elems_per_value; i += warpSize) {
out[i] = bvalues[slot_num * num_elems_per_value + i];
}
}
__device__ void WriteOneValue(const ThreadCtx &ctx, uint8_t slot_num,
ElemType *v) {
for (size_t i = ctx.lane_id; i < num_elems_per_value; i += warpSize) {
bvalues[slot_num * num_elems_per_value + i] = v[i];
}
}
WarpMutex *mutex;
KeyType *bkeys;
ElemType *bvalues;
uint8_t *btimestamps;
uint32_t num_elems_per_value;
};
template<typename KeyType, typename ElemType>
class LFUCache: public Cache<KeyType, ElemType>{
public:
explicit LFUCache(CacheConfig cfg):Cache<KeyType,ElemType>(cfg){
// this->manager = new LRUCacheManager<KeyType,ElemType>();
}
~LFUCache(){
// delete this->manager;
}
};
template<typename KeyType, typename ElemType>
LFUCache<KeyType,ElemType>* NewLFUCache(CacheConfig cfg){
return new LFUCache<KeyType,ElemType>(cfg);
}
}
\ No newline at end of file
#pragma once
#include "cache.cuh"
namespace gpucache {
template<typename KeyType, typename ElemType, CacheConfig::CacheEvictStrategy Strategy>
struct BucketView;
template<typename KeyType, typename ElemType>
struct BucketView<KeyType, ElemType, CacheConfig::CacheEvictStrategy::LRU> {
__device__ BucketView(KeyType *k, ElemType *v, uint8_t *ts, WarpMutex *m, uint32_t num_elems_per_value) : bkeys(
k), bvalues(v), btimestamps(ts), mutex(m), num_elems_per_value(num_elems_per_value) {}
__device__ int Get(const ThreadCtx &ctx, const KeyType key) {
KeyType lane_key = this->bkeys[ctx.lane_id];
uint8_t ts = this->btimestamps[ctx.lane_id];
bool exist = (ts > 0 && lane_key == key);
uint32_t exist_mask = __ballot_sync(warpFullMask, exist);
int slot_num = __ffs(exist_mask) - 1;
if (exist_mask == 0) { // not found
return -1;
} else {
if (ctx.lane_id != slot_num && ts > 1) { // decrease the counter
this->btimestamps[ctx.lane_id] = ts - 1;
}
return slot_num; // return exist slot num
};
}
__device__ int TryPut(const ThreadCtx &ctx, const KeyType key) {
KeyType lane_key = this->bkeys[ctx.lane_id];
uint8_t ts = this->btimestamps[ctx.lane_id];
bool exist = (ts > 0 && lane_key == key);
uint32_t exist_mask = __ballot_sync(warpFullMask, exist);
int slot_num = __ffs(exist_mask) - 1;
if (exist_mask != 0) {
if (ctx.lane_id == slot_num) {
ts = warpSize;
}
__syncwarp();
}
if (slot_num == -1) { // key don't exist
uint32_t emptyMask = __ballot_sync(warpFullMask, ts != 0);
if (emptyMask != warpFullMask) { // bucket not full
slot_num = __popc(emptyMask);
if (ctx.lane_id == slot_num) {
this->bkeys[slot_num] = key;
ts = warpSize;
}
}
__syncwarp();
}
this->btimestamps[ctx.lane_id] = ts;
return slot_num;
}
__device__ int Evict(const ThreadCtx &ctx, const KeyType key,
KeyType *evict_key) {
KeyType lane_key = this->bkeys[ctx.lane_id];
uint8_t ts = this->btimestamps[ctx.lane_id];
uint32_t evict_mask = __ballot_sync(warpFullMask, ts == 1);
int slot_num = __ffs(evict_mask) - 1;
if (slot_num == -1) { // no ts equals 1, do warp reduction find min ts > 0
uint8_t min_ts = ts;
uint32_t min_ts_lane_id = ctx.lane_id;
uint32_t reduce_mask = __ballot_sync(warpFullMask, ts != 0);
for (int offset = 16; offset > 0; offset /= 2) {
uint8_t temp_ts = __shfl_down_sync(reduce_mask, ts, offset);
if (temp_ts != 0 && temp_ts < min_ts) {
min_ts = temp_ts;
min_ts_lane_id = ctx.lane_id + offset;
}
}
slot_num = __shfl_sync(warpFullMask, min_ts_lane_id, 0);
// if (ctx.lane_id == 0) {
// printf("evict slot_num %d, ts = %u", slot_num, ts);
// }
}
if (ctx.lane_id == slot_num) {
*evict_key = lane_key;
this->bkeys[slot_num] = key;
this->btimestamps[slot_num] = warpSize;
}
return slot_num;
}
__device__ void ReadOneValue(const ThreadCtx &ctx, uint8_t slot_num,
ElemType *out) {
for (size_t i = ctx.lane_id; i < num_elems_per_value; i += warpSize) {
out[i] = bvalues[slot_num * num_elems_per_value + i];
}
}
__device__ void WriteOneValue(const ThreadCtx &ctx, uint8_t slot_num,
ElemType *v) {
for (size_t i = ctx.lane_id; i < num_elems_per_value; i += warpSize) {
bvalues[slot_num * num_elems_per_value + i] = v[i];
}
}
WarpMutex *mutex;
KeyType *bkeys;
ElemType *bvalues;
uint8_t *btimestamps;
uint32_t num_elems_per_value;
};
// template<typename KeyType, typename ElemType>
// class LRUCacheManager: public CacheManager<KeyType,ElemType>{
// public:
// __device__ LRUCacheManager() =default;
//
// __device__ BucketView<KeyType, ElemType>*
// SetBucketView(ThreadCtx ctx, KeyType *cache_keys, ElemType *cache_values,
// uint8_t *cache_timestamps, void *cache_mutexes,
// uint32_t num_elem_per_value, uint32_t bucket_id) {
// return BucketView<KeyType, ElemType>(
// cache_keys + bucket_id * warpSize,
// cache_values + bucket_id * warpSize * num_elem_per_value,
// cache_timestamps + bucket_id * warpSize,
// reinterpret_cast<WarpMutex *>(cache_mutexes) + bucket_id,
// num_elem_per_value);
// }
// __device__ __host__ void Type(){
// printf("LRUCacheSetBucketView\n");
// }
//
// __device__ void DestroyBucketView(BucketView<KeyType,ElemType>* bucket){
// delete bucket;
// }
// };
template<typename KeyType, typename ElemType>
class LRUCache : public Cache<KeyType, ElemType> {
public:
explicit LRUCache(CacheConfig cfg) : Cache<KeyType, ElemType>(cfg) {
// this->manager = new LRUCacheManager<KeyType,ElemType>();
}
~LRUCache() {
// delete this->manager;
}
};
template<typename KeyType, typename ElemType>
LRUCache<KeyType, ElemType> *NewLRUCache(CacheConfig cfg) {
return new LRUCache<KeyType, ElemType>(cfg);
}
}
#include "utils.h"
namespace gpucache {
__device__ ThreadCtx::ThreadCtx() {
auto global_thread_id = blockIdx.x * blockDim.x + threadIdx.x;
global_warp_idx = global_thread_id / warpSize;
block_warp_idx = threadIdx.x / warpSize;
lane_id = threadIdx.x % warpSize;
num_warps = blockDim.x * gridDim.x / warpSize;
}
__device__ WarpMutex::WarpMutex() : flag(0) {}
__device__ void WarpMutex::Lock(ThreadCtx &ctx) {
if (ctx.lane_id == 0) {
while (atomicCAS(&flag, 0, 1) != 0) {}
}
__threadfence();
__syncwarp();
}
__device__ void WarpMutex::UnLock(ThreadCtx &ctx) {
__syncwarp();
__threadfence();
if (ctx.lane_id == 0) {
atomicExch(&flag, 0);
}
}
__global__ void initLocks(uint32_t n_bucket, void *bucketMutexes) {
uint32_t global_thread_idx = blockDim.x * blockIdx.x + threadIdx.x;
if (global_thread_idx < n_bucket) {
new(reinterpret_cast<WarpMutex *>(bucketMutexes) + global_thread_idx)
WarpMutex();
}
}
}
#pragma once
namespace gpucache{
constexpr unsigned int warpFullMask = 0xFFFFFFFF;
constexpr unsigned int defaultBlockX = 256;
constexpr unsigned int warpSize = 32;
constexpr unsigned int defaultNumWarpsPerBlock = defaultBlockX / warpSize;
// bucket_id + key
constexpr unsigned int SharedMemorySize = 2 * sizeof(uint32_t) * defaultNumWarpsPerBlock * warpSize;
struct ThreadCtx {
__device__ ThreadCtx();
uint32_t global_warp_idx;
uint32_t block_warp_idx;
uint32_t num_warps;
uint32_t lane_id;
};
struct WarpMutex {
public:
__device__ WarpMutex();
~WarpMutex() = default;
WarpMutex(const WarpMutex &) = delete;
WarpMutex &operator=(const WarpMutex &) = delete;
WarpMutex(WarpMutex &&) = delete;
WarpMutex &operator=(WarpMutex &&) = delete;
__device__ void Lock(ThreadCtx &ctx);
__device__ void UnLock(ThreadCtx &ctx);
// private:
uint32_t flag;
};
__global__ void initLocks(uint32_t n_bucket, void *bucketMutexes);
struct CacheConfig {
enum CacheEvictStrategy {
FIFO,
LRU,
LFU
};
CacheConfig() = default;
CacheConfig(CacheEvictStrategy s, uint64_t cap, uint32_t key_size, uint32_t value_size,
uint32_t max_query_num, uint32_t device_id, uint32_t dim) :
strategy(s), capacity(cap), key_size(key_size), value_size(value_size),
max_query_num(max_query_num), device_id(device_id), dim(dim) {}
CacheEvictStrategy strategy;
uint64_t capacity;
uint32_t key_size;
uint32_t value_size;
uint32_t dim;
uint32_t max_query_num;
uint32_t device_id;
};
}
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import libgpucache"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# args: strtegy, capacity, keySize(only support int32 and int64), valueSize(dim * sizeof(elem), elem is decided by the passing tensor dtype of NewLRUCache), deviceId, dim\n",
"# cfg = libgpucache.CacheConfig(libgpucache.CacheConfig.LRU,65536,4,128,4096,0,32)\n",
"# cfg = libgpucache.CacheConfig(libgpucache.CacheConfig.FIFO,65536,4,128,4096,0,32)\n",
"cfg = libgpucache.CacheConfig(libgpucache.CacheConfig.LFU,65536,4,128,4096,0,32)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(<CacheEvictStrategy.LFU: 2>, 65536, 4, 128, 4096, 0, 32)"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cfg.strategy, cfg.capacity, cfg.keySize, cfg.valueSize, cfg.maxQueryNum, cfg.deviceId, cfg.dim"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Cache: keySize: 4, valueSize: 128, dim: 32, capacity: 65536, maxQueryNum: 4096, deviceId: 0\n"
]
}
],
"source": [
"t = torch.empty([1],dtype=torch.float32)\n",
"cache = libgpucache.NewCache(t,cfg)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0.],\n",
" [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0.],\n",
" [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0.]], device='cuda:0'),\n",
" tensor([False, False, False], device='cuda:0'),\n",
" torch.Size([3, 32]))"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"keys = torch.tensor([1,2,3],dtype=torch.int32,device=\"cuda:0\")\n",
"values, find_mask = cache.Get(3,keys)\n",
"values, find_mask, values.shape"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"values = torch.arange(0,3*32,dtype=torch.float32).reshape(3,-1).to(\"cuda:0\")\n",
"cache.Put(3,keys,values)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13.,\n",
" 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27.,\n",
" 28., 29., 30., 31.],\n",
" [32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45.,\n",
" 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,\n",
" 60., 61., 62., 63.],\n",
" [64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77.,\n",
" 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91.,\n",
" 92., 93., 94., 95.]], device='cuda:0'),\n",
" tensor([True, True, True], device='cuda:0'),\n",
" torch.Size([3, 32]))"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"values, find_mask = cache.Get(3,keys)\n",
"values, find_mask, values.shape"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.,\n",
" 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28.,\n",
" 29., 30., 31., 32.],\n",
" [32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45.,\n",
" 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,\n",
" 60., 61., 62., 63.],\n",
" [64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77.,\n",
" 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91.,\n",
" 92., 93., 94., 95.]], device='cuda:0'),\n",
" tensor([False, True, True], device='cuda:0'),\n",
" torch.Size([3, 32]))"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"keys[0] = 999\n",
"values, find_mask = cache.Get(3,keys)\n",
"values, find_mask, values.shape"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.,\n",
" 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28.,\n",
" 29., 30., 31., 32.],\n",
" [32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45.,\n",
" 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,\n",
" 60., 61., 62., 63.],\n",
" [64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77.,\n",
" 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91.,\n",
" 92., 93., 94., 95.]], device='cuda:0'),\n",
" tensor([False, False, False], device='cuda:0'),\n",
" torch.Size([3, 32]))"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cache.Clear()\n",
"values, find_mask = cache.Get(3,keys)\n",
"values, find_mask, values.shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "dgl",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CUDA_COMPILER /home/wtx/.local/cuda/bin/nvcc)
set(CUDAToolkit_ROOT /home/wtx/.local/cuda)
set(CUDA_TOOLKIT_ROOT_DIR /home/wtx/.local/cuda11.8+cudnn8.9)
project(cache_test CXX CUDA)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED on)
set(CMAKE_EXPORT_COMPILE_COMMANDS on)
set(CMAKE_CUDA_STANDARD 14)
# prepare gtest
# for debug
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G -g")
set(Torch_DIR /home/wtx/miniconda3/envs/dgl/lib/python3.10/site-packages/torch/share/cmake/Torch)
find_package(Torch REQUIRED)
include_directories(${TORCH_INCLUDE_DIRS})
add_compile_options(${TORCH_CXX_FLAGS})
set(Python3_ROOT_DIR ~/miniconda3/envs/dgl)
find_package (Python3 COMPONENTS Interpreter Development REQUIRED)
include(FetchContent)
FetchContent_Declare(
googletest
SOURCE_DIR /home/wtx/workspace/cpp_project/gpucache_new/third_party/googletest
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
enable_testing()
#set(GTest_Path ${CMAKE_SOURCE_DIR}/../third_party/googletest)
#
#add_subdirectory(${GTest_Path} googletest-build)
add_executable(
cache_test
cache_test.cu
)
#target_compile_definitions(cache_test PRIVATE _GLIBCXX_USE_CXX11_ABI=0)
target_include_directories(cache_test
# PRIVATE ${GTest_Path}/googletest/include
PRIVATE /home/wtx/workspace/cpp_project/gpucache_new/src
PRIVATE /home/wtx/miniconda3/envs/dgl/include/python3.10
)
set_target_properties(cache_test
PROPERTIES
CUDA_SEPARABLE_COMPILATION ON
CUDA_RESOLVE_DEVICE_SYMBOLS ON
)
# target_link_directories(cache_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(
cache_test
PRIVATE
# gtest gtest_main
GTest::gtest_main
${TORCH_LIBRARIES}
# gpucache
)
target_compile_options(cache_test PRIVATE ${TORCH_CXX_FLAGS})
include(GoogleTest)
gtest_discover_tests(cache_test)
# Run manually to reformat a file:
# clang-format -i --style=file <file>
Language: Cpp
BasedOnStyle: Google
name: Bug Report
description: Let us know that something does not work as expected.
title: "[Bug]: Please title this bug report"
body:
- type: textarea
id: what-happened
attributes:
label: Describe the issue
description: What happened, and what did you expect to happen?
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce the problem
description: It is important that we are able to reproduce the problem that you are experiencing. Please provide all code and relevant steps to reproduce the problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the problem are also helpful.
validations:
required: true
- type: textarea
id: version
attributes:
label: What version of GoogleTest are you using?
description: Please include the output of `git rev-parse HEAD` or the GoogleTest release version number that you are using.
validations:
required: true
- type: textarea
id: os
attributes:
label: What operating system and version are you using?
description: If you are using a Linux distribution please include the name and version of the distribution as well.
validations:
required: true
- type: textarea
id: compiler
attributes:
label: What compiler and version are you using?
description: Please include the output of `gcc -v` or `clang -v`, or the equivalent for your compiler.
validations:
required: true
- type: textarea
id: buildsystem
attributes:
label: What build system are you using?
description: Please include the output of `bazel --version` or `cmake --version`, or the equivalent for your build system.
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false
name: Feature request
description: Propose a new feature.
title: "[FR]: Please title this feature request"
labels: "enhancement"
body:
- type: textarea
id: version
attributes:
label: Does the feature exist in the most recent commit?
description: We recommend using the latest commit from GitHub in your projects.
validations:
required: true
- type: textarea
id: why
attributes:
label: Why do we need this feature?
description: Ideally, explain why a combination of existing features cannot be used instead.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Describe the proposal.
description: Include a detailed description of the feature, with usage examples.
validations:
required: true
- type: textarea
id: platform
attributes:
label: Is the feature specific to an operating system, compiler, or build system version?
description: If it is, please specify which versions.
validations:
required: true
blank_issues_enabled: false
contact_links:
- name: Get Help
url: https://github.com/google/googletest/discussions
about: Please ask and answer questions here.
name: ci
on:
push:
pull_request:
env:
BAZEL_CXXOPTS: -std=c++14
jobs:
Linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ...
macOS:
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ...
Windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=/std:c++14 --features=external_include_paths --test_output=errors ...
# Ignore CI build directory
build/
xcuserdata
cmake-build-debug/
.idea/
bazel-bin
bazel-genfiles
bazel-googletest
bazel-out
bazel-testlogs
MODULE.bazel.lock
# python
*.pyc
# Visual Studio files
.vs
*.sdf
*.opensdf
*.VC.opendb
*.suo
*.user
_ReSharper.Caches/
Win32-Debug/
Win32-Release/
x64-Debug/
x64-Release/
# VSCode files
.cache/
cmake-variants.yaml
# Ignore autoconf / automake files
Makefile.in
aclocal.m4
configure
build-aux/
autom4te.cache/
googletest/m4/libtool.m4
googletest/m4/ltoptions.m4
googletest/m4/ltsugar.m4
googletest/m4/ltversion.m4
googletest/m4/lt~obsolete.m4
googlemock/m4
# Ignore generated directories.
googlemock/fused-src/
googletest/fused-src/
# macOS files
.DS_Store
googletest/.DS_Store
googletest/xcode/.DS_Store
# Ignore cmake generated directories and files.
CMakeFiles
CTestTestfile.cmake
Makefile
cmake_install.cmake
googlemock/CMakeFiles
googlemock/CTestTestfile.cmake
googlemock/Makefile
googlemock/cmake_install.cmake
googlemock/gtest
/bin
/googlemock/gmock.dir
/googlemock/gmock_main.dir
/googlemock/RUN_TESTS.vcxproj.filters
/googlemock/RUN_TESTS.vcxproj
/googlemock/INSTALL.vcxproj.filters
/googlemock/INSTALL.vcxproj
/googlemock/gmock_main.vcxproj.filters
/googlemock/gmock_main.vcxproj
/googlemock/gmock.vcxproj.filters
/googlemock/gmock.vcxproj
/googlemock/gmock.sln
/googlemock/ALL_BUILD.vcxproj.filters
/googlemock/ALL_BUILD.vcxproj
/lib
/Win32
/ZERO_CHECK.vcxproj.filters
/ZERO_CHECK.vcxproj
/RUN_TESTS.vcxproj.filters
/RUN_TESTS.vcxproj
/INSTALL.vcxproj.filters
/INSTALL.vcxproj
/googletest-distribution.sln
/CMakeCache.txt
/ALL_BUILD.vcxproj.filters
/ALL_BUILD.vcxproj
# Copyright 2017 Google Inc.
# All Rights Reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Bazel Build for Google C++ Testing Framework(Google Test)
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
exports_files(["LICENSE"])
config_setting(
name = "qnx",
constraint_values = ["@platforms//os:qnx"],
)
config_setting(
name = "windows",
constraint_values = ["@platforms//os:windows"],
)
config_setting(
name = "freebsd",
constraint_values = ["@platforms//os:freebsd"],
)
config_setting(
name = "openbsd",
constraint_values = ["@platforms//os:openbsd"],
)
# NOTE: Fuchsia is not an officially supported platform.
config_setting(
name = "fuchsia",
constraint_values = ["@platforms//os:fuchsia"],
)
config_setting(
name = "msvc_compiler",
flag_values = {
"@bazel_tools//tools/cpp:compiler": "msvc-cl",
},
visibility = [":__subpackages__"],
)
config_setting(
name = "has_absl",
values = {"define": "absl=1"},
)
# Library that defines the FRIEND_TEST macro.
cc_library(
name = "gtest_prod",
hdrs = ["googletest/include/gtest/gtest_prod.h"],
includes = ["googletest/include"],
)
# Google Test including Google Mock
cc_library(
name = "gtest",
srcs = glob(
include = [
"googletest/src/*.cc",
"googletest/src/*.h",
"googletest/include/gtest/**/*.h",
"googlemock/src/*.cc",
"googlemock/include/gmock/**/*.h",
],
exclude = [
"googletest/src/gtest-all.cc",
"googletest/src/gtest_main.cc",
"googlemock/src/gmock-all.cc",
"googlemock/src/gmock_main.cc",
],
),
hdrs = glob([
"googletest/include/gtest/*.h",
"googlemock/include/gmock/*.h",
]),
copts = select({
":qnx": [],
":windows": [],
"//conditions:default": ["-pthread"],
}),
defines = select({
":has_absl": ["GTEST_HAS_ABSL=1"],
"//conditions:default": [],
}),
features = select({
":windows": ["windows_export_all_symbols"],
"//conditions:default": [],
}),
includes = [
"googlemock",
"googlemock/include",
"googletest",
"googletest/include",
],
linkopts = select({
":qnx": ["-lregex"],
":windows": [],
":freebsd": [
"-lm",
"-pthread",
],
":openbsd": [
"-lm",
"-pthread",
],
"//conditions:default": ["-pthread"],
}),
deps = select({
":has_absl": [
"@com_google_absl//absl/container:flat_hash_set",
"@com_google_absl//absl/debugging:failure_signal_handler",
"@com_google_absl//absl/debugging:stacktrace",
"@com_google_absl//absl/debugging:symbolize",
"@com_google_absl//absl/flags:flag",
"@com_google_absl//absl/flags:parse",
"@com_google_absl//absl/flags:reflection",
"@com_google_absl//absl/flags:usage",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:any",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant",
"@com_googlesource_code_re2//:re2",
],
"//conditions:default": [],
}) + select({
# `gtest-death-test.cc` has `EXPECT_DEATH` that spawns a process,
# expects it to crash and inspects its logs with the given matcher,
# so that's why these libraries are needed.
# Otherwise, builds targeting Fuchsia would fail to compile.
":fuchsia": [
"@fuchsia_sdk//pkg/fdio",
"@fuchsia_sdk//pkg/syslog",
"@fuchsia_sdk//pkg/zx",
],
"//conditions:default": [],
}),
)
cc_library(
name = "gtest_main",
srcs = ["googlemock/src/gmock_main.cc"],
features = select({
":windows": ["windows_export_all_symbols"],
"//conditions:default": [],
}),
deps = [":gtest"],
)
# The following rules build samples of how to use gTest.
cc_library(
name = "gtest_sample_lib",
srcs = [
"googletest/samples/sample1.cc",
"googletest/samples/sample2.cc",
"googletest/samples/sample4.cc",
],
hdrs = [
"googletest/samples/prime_tables.h",
"googletest/samples/sample1.h",
"googletest/samples/sample2.h",
"googletest/samples/sample3-inl.h",
"googletest/samples/sample4.h",
],
features = select({
":windows": ["windows_export_all_symbols"],
"//conditions:default": [],
}),
)
cc_test(
name = "gtest_samples",
size = "small",
# All Samples except:
# sample9 (main)
# sample10 (main and takes a command line option and needs to be separate)
srcs = [
"googletest/samples/sample1_unittest.cc",
"googletest/samples/sample2_unittest.cc",
"googletest/samples/sample3_unittest.cc",
"googletest/samples/sample4_unittest.cc",
"googletest/samples/sample5_unittest.cc",
"googletest/samples/sample6_unittest.cc",
"googletest/samples/sample7_unittest.cc",
"googletest/samples/sample8_unittest.cc",
],
linkstatic = 0,
deps = [
"gtest_sample_lib",
":gtest_main",
],
)
cc_test(
name = "sample9_unittest",
size = "small",
srcs = ["googletest/samples/sample9_unittest.cc"],
deps = [":gtest"],
)
cc_test(
name = "sample10_unittest",
size = "small",
srcs = ["googletest/samples/sample10_unittest.cc"],
deps = [":gtest"],
)
# Note: CMake support is community-based. The maintainers do not use CMake
# internally.
cmake_minimum_required(VERSION 3.13)
project(googletest-distribution)
set(GOOGLETEST_VERSION 1.14.0)
if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
set(CMAKE_CXX_EXTENSIONS OFF)
endif()
enable_testing()
include(CMakeDependentOption)
include(GNUInstallDirs)
# Note that googlemock target already builds googletest.
option(BUILD_GMOCK "Builds the googlemock subproject" ON)
option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)
option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF)
if(GTEST_HAS_ABSL)
if(NOT TARGET absl::base)
find_package(absl REQUIRED)
endif()
if(NOT TARGET re2::re2)
find_package(re2 REQUIRED)
endif()
endif()
if(BUILD_GMOCK)
add_subdirectory( googlemock )
else()
add_subdirectory( googletest )
endif()
# How to become a contributor and submit your own code
## Contributor License Agreements
We'd love to accept your patches! Before we can take them, we have to jump a
couple of legal hurdles.
Please fill out either the individual or corporate Contributor License Agreement
(CLA).
* If you are an individual writing original source code and you're sure you
own the intellectual property, then you'll need to sign an
[individual CLA](https://developers.google.com/open-source/cla/individual).
* If you work for a company that wants to allow you to contribute your work,
then you'll need to sign a
[corporate CLA](https://developers.google.com/open-source/cla/corporate).
Follow either of the two links above to access the appropriate CLA and
instructions for how to sign and return it. Once we receive it, we'll be able to
accept your pull requests.
## Are you a Googler?
If you are a Googler, please make an attempt to submit an internal contribution
rather than a GitHub Pull Request. If you are not able to submit internally, a
PR is acceptable as an alternative.
## Contributing A Patch
1. Submit an issue describing your proposed change to the
[issue tracker](https://github.com/google/googletest/issues).
2. Please don't mix more than one logical change per submittal, because it
makes the history hard to follow. If you want to make a change that doesn't
have a corresponding issue in the issue tracker, please create one.
3. Also, coordinate with team members that are listed on the issue in question.
This ensures that work isn't being duplicated and communicating your plan
early also generally leads to better patches.
4. If your proposed change is accepted, and you haven't already done so, sign a
Contributor License Agreement
([see details above](#contributor-license-agreements)).
5. Fork the desired repo, develop and test your code changes.
6. Ensure that your code adheres to the existing style in the sample to which
you are contributing.
7. Ensure that your code has an appropriate set of unit tests which all pass.
8. Submit a pull request.
## The Google Test and Google Mock Communities
The Google Test community exists primarily through the
[discussion group](https://groups.google.com/group/googletestframework) and the
GitHub repository. Likewise, the Google Mock community exists primarily through
their own [discussion group](https://groups.google.com/group/googlemock). You
are definitely encouraged to contribute to the discussion and you can also help
us to keep the effectiveness of the group high by following and promoting the
guidelines listed here.
### Please Be Friendly
Showing courtesy and respect to others is a vital part of the Google culture,
and we strongly encourage everyone participating in Google Test development to
join us in accepting nothing less. Of course, being courteous is not the same as
failing to constructively disagree with each other, but it does mean that we
should be respectful of each other when enumerating the 42 technical reasons
that a particular proposal may not be the best choice. There's never a reason to
be antagonistic or dismissive toward anyone who is sincerely trying to
contribute to a discussion.
Sure, C++ testing is serious business and all that, but it's also a lot of fun.
Let's keep it that way. Let's strive to be one of the friendliest communities in
all of open source.
As always, discuss Google Test in the official GoogleTest discussion group. You
don't have to actually submit code in order to sign up. Your participation
itself is a valuable contribution.
## Style
To keep the source consistent, readable, diffable and easy to merge, we use a
fairly rigid coding style, as defined by the
[google-styleguide](https://github.com/google/styleguide) project. All patches
will be expected to conform to the style outlined
[here](https://google.github.io/styleguide/cppguide.html). Use
[.clang-format](https://github.com/google/googletest/blob/main/.clang-format) to
check your formatting.
## Requirements for Contributors
If you plan to contribute a patch, you need to build Google Test, Google Mock,
and their own tests from a git checkout, which has further requirements:
* [Python](https://www.python.org/) v3.6 or newer (for running some of the
tests and re-generating certain source files from templates)
* [CMake](https://cmake.org/) v2.8.12 or newer
## Developing Google Test and Google Mock
This section discusses how to make your own changes to the Google Test project.
### Testing Google Test and Google Mock Themselves
To make sure your changes work as intended and don't break existing
functionality, you'll want to compile and run Google Test and GoogleMock's own
tests. For that you can use CMake:
```
mkdir mybuild
cd mybuild
cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR}
```
To choose between building only Google Test or Google Mock, you may modify your
cmake command to be one of each
```
cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests
cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests
```
Make sure you have Python installed, as some of Google Test's tests are written
in Python. If the cmake command complains about not being able to find Python
(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it
explicitly where your Python executable can be found:
```
cmake -DPYTHON_EXECUTABLE=path/to/python ...
```
Next, you can build Google Test and / or Google Mock and all desired tests. On
\*nix, this is usually done by
```
make
```
To run the tests, do
```
make test
```
All tests should pass.
# This file contains a list of people who've made non-trivial
# contribution to the Google C++ Testing Framework project. People
# who commit code to the project are encouraged to add their names
# here. Please keep the list sorted by first names.
Ajay Joshi <jaj@google.com>
Balázs Dán <balazs.dan@gmail.com>
Benoit Sigoure <tsuna@google.com>
Bharat Mediratta <bharat@menalto.com>
Bogdan Piloca <boo@google.com>
Chandler Carruth <chandlerc@google.com>
Chris Prince <cprince@google.com>
Chris Taylor <taylorc@google.com>
Dan Egnor <egnor@google.com>
Dave MacLachlan <dmaclach@gmail.com>
David Anderson <danderson@google.com>
Dean Sturtevant
Eric Roman <eroman@chromium.org>
Gene Volovich <gv@cite.com>
Hady Zalek <hady.zalek@gmail.com>
Hal Burch <gmock@hburch.com>
Jeffrey Yasskin <jyasskin@google.com>
Jim Keller <jimkeller@google.com>
Joe Walnes <joe@truemesh.com>
Jon Wray <jwray@google.com>
Jói Sigurðsson <joi@google.com>
Keir Mierle <mierle@gmail.com>
Keith Ray <keith.ray@gmail.com>
Kenton Varda <kenton@google.com>
Kostya Serebryany <kcc@google.com>
Krystian Kuzniarek <krystian.kuzniarek@gmail.com>
Lev Makhlis
Manuel Klimek <klimek@google.com>
Mario Tanev <radix@google.com>
Mark Paskin
Markus Heule <markus.heule@gmail.com>
Martijn Vels <mvels@google.com>
Matthew Simmons <simmonmt@acm.org>
Mika Raento <mikie@iki.fi>
Mike Bland <mbland@google.com>
Miklós Fazekas <mfazekas@szemafor.com>
Neal Norwitz <nnorwitz@gmail.com>
Nermin Ozkiranartli <nermin@google.com>
Owen Carlsen <ocarlsen@google.com>
Paneendra Ba <paneendra@google.com>
Pasi Valminen <pasi.valminen@gmail.com>
Patrick Hanna <phanna@google.com>
Patrick Riley <pfr@google.com>
Paul Menage <menage@google.com>
Peter Kaminski <piotrk@google.com>
Piotr Kaminski <piotrk@google.com>
Preston Jackson <preston.a.jackson@gmail.com>
Rainer Klaffenboeck <rainer.klaffenboeck@dynatrace.com>
Russ Cox <rsc@google.com>
Russ Rufer <russ@pentad.com>
Sean Mcafee <eefacm@gmail.com>
Sigurður Ásgeirsson <siggi@google.com>
Soyeon Kim <sxshx818@naver.com>
Sverre Sundsdal <sundsdal@gmail.com>
Szymon Sobik <sobik.szymon@gmail.com>
Takeshi Yoshino <tyoshino@google.com>
Tracy Bialik <tracy@pentad.com>
Vadim Berman <vadimb@google.com>
Vlad Losev <vladl@google.com>
Wolfgang Klier <wklier@google.com>
Zhanyong Wan <wan@google.com>
Copyright 2008, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Copyright 2024 Google Inc.
# All Rights Reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# https://bazel.build/external/overview#bzlmod
module(
name = "googletest",
version = "head",
compatibility_level = 1,
)
# Only direct dependencies need to be listed below.
# Please keep the versions in sync with the versions in the WORKSPACE file.
bazel_dep(name = "abseil-cpp",
version = "20240116.0",
repo_name = "com_google_absl")
bazel_dep(name = "platforms",
version = "0.0.8")
bazel_dep(name = "re2",
repo_name = "com_googlesource_code_re2",
version = "2023-11-01")
bazel_dep(name = "rules_python",
version = "0.29.0")
fake_fuchsia_sdk = use_repo_rule("//:fake_fuchsia_sdk.bzl", "fake_fuchsia_sdk")
fake_fuchsia_sdk(name = "fuchsia_sdk")
# https://github.com/bazelbuild/rules_python/blob/main/BZLMOD_SUPPORT.md#default-toolchain-is-not-the-local-system-python
register_toolchains("@bazel_tools//tools/python:autodetecting_toolchain")
# GoogleTest
### Announcements
#### Live at Head
GoogleTest now follows the
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
We recommend
[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it).
We do publish occasional semantic versions, tagged with
`v${major}.${minor}.${patch}` (e.g. `v1.14.0`).
#### Documentation Updates
Our documentation is now live on GitHub Pages at
https://google.github.io/googletest/. We recommend browsing the documentation on
GitHub Pages rather than directly in the repository.
#### Release 1.14.0
[Release 1.14.0](https://github.com/google/googletest/releases/tag/v1.14.0) is
now available.
The 1.14.x branch requires at least C++14.
#### Continuous Integration
We use Google's internal systems for continuous integration. \
GitHub Actions were added for the convenience of open-source contributors. They
are exclusively maintained by the open-source community and not used by the
GoogleTest team.
#### Coming Soon
* We are planning to take a dependency on
[Abseil](https://github.com/abseil/abseil-cpp).
* More documentation improvements are planned.
## Welcome to **GoogleTest**, Google's C++ test framework!
This repository is a merger of the formerly separate GoogleTest and GoogleMock
projects. These were so closely related that it makes sense to maintain and
release them together.
### Getting Started
See the [GoogleTest User's Guide](https://google.github.io/googletest/) for
documentation. We recommend starting with the
[GoogleTest Primer](https://google.github.io/googletest/primer.html).
More information about building GoogleTest can be found at
[googletest/README.md](googletest/README.md).
## Features
* xUnit test framework: \
Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit)
testing framework, a popular architecture for unit testing
* Test discovery: \
Googletest automatically discovers and runs your tests, eliminating the need
to manually register your tests
* Rich set of assertions: \
Googletest provides a variety of assertions, such as equality, inequality,
exceptions, and more, making it easy to test your code
* User-defined assertions: \
You can define your own assertions with Googletest, making it simple to
write tests that are specific to your code
* Death tests: \
Googletest supports death tests, which verify that your code exits in a
certain way, making it useful for testing error-handling code
* Fatal and non-fatal failures: \
You can specify whether a test failure should be treated as fatal or
non-fatal with Googletest, allowing tests to continue running even if a
failure occurs
* Value-parameterized tests: \
Googletest supports value-parameterized tests, which run multiple times with
different input values, making it useful for testing functions that take
different inputs
* Type-parameterized tests: \
Googletest also supports type-parameterized tests, which run with different
data types, making it useful for testing functions that work with different
data types
* Various options for running tests: \
Googletest provides many options for running tests including running
individual tests, running tests in a specific order and running tests in
parallel
## Supported Platforms
GoogleTest follows Google's
[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
for a list of currently supported versions of compilers, platforms, and build
tools.
## Who Is Using GoogleTest?
In addition to many internal projects at Google, GoogleTest is also used by the
following notable projects:
* The [Chromium projects](https://www.chromium.org/) (behind the Chrome
browser and Chrome OS).
* The [LLVM](https://llvm.org/) compiler.
* [Protocol Buffers](https://github.com/google/protobuf), Google's data
interchange format.
* The [OpenCV](https://opencv.org/) computer vision library.
## Related Open Source Projects
[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based
automated test-runner and Graphical User Interface with powerful features for
Windows and Linux platforms.
[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that
runs your test binary, allows you to track its progress via a progress bar, and
displays a list of test failures. Clicking on one shows failure text. GoogleTest
UI is written in C#.
[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event
listener for GoogleTest that implements the
[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test
result output. If your test runner understands TAP, you may find it useful.
[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that
runs tests from your binary in parallel to provide significant speed-up.
[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)
is a VS Code extension allowing to view GoogleTest in a tree view and run/debug
your tests.
[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS
Code extension allowing to view GoogleTest in a tree view and run/debug your
tests.
[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser
that generates stub code for GoogleTest.
## Contributing Changes
Please read
[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md)
for details on how to contribute to this project.
Happy testing!
workspace(name = "com_google_googletest")
load("//:googletest_deps.bzl", "googletest_deps")
googletest_deps()
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_python",
sha256 = "d71d2c67e0bce986e1c5a7731b4693226867c45bfe0b7c5e0067228a536fc580",
strip_prefix = "rules_python-0.29.0",
urls = ["https://github.com/bazelbuild/rules_python/releases/download/0.29.0/rules_python-0.29.0.tar.gz"],
)
# https://github.com/bazelbuild/rules_python/releases/tag/0.29.0
load("@rules_python//python:repositories.bzl", "py_repositories")
py_repositories()
http_archive(
name = "bazel_skylib",
sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94",
urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz"],
)
http_archive(
name = "platforms",
sha256 = "8150406605389ececb6da07cbcb509d5637a3ab9a24bc69b1101531367d89d74",
urls = ["https://github.com/bazelbuild/platforms/releases/download/0.0.8/platforms-0.0.8.tar.gz"],
)
# Copyright 2024 Google Inc.
# All Rights Reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# https://bazel.build/external/migration#workspace.bzlmod
#
# This file is intentionally empty. When bzlmod is enabled and this
# file exists, the content of WORKSPACE is ignored. This prevents
# bzlmod builds from unintentionally depending on the WORKSPACE file.
#!/bin/bash
#
# Copyright 2020, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20231218"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20230120"
if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
if [[ -z ${STD:-} ]]; then
STD="c++14 c++17 c++20"
fi
# Test the CMake build
for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
for cmake_off_on in OFF ON; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--tmpfs="/build:exec" \
--workdir="/build" \
--rm \
--env="CC=${cc}" \
--env=CXXFLAGS="-Werror -Wdeprecated" \
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on} && \
make -j$(nproc) && \
ctest -j$(nproc) --output-on-failure"
done
done
# Do one test with an older version of GCC
# TODO(googletest-team): This currently uses Bazel 5. When upgrading to a
# version of Bazel that supports Bzlmod, add --enable_bzlmod=false to keep test
# coverage for the old WORKSPACE dependency management.
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--workdir="/src" \
--rm \
--env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=c++14" \
${LINUX_GCC_FLOOR_CONTAINER} \
/usr/local/bin/bazel test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--copt="-Wno-error=pragmas" \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors
# Test GCC
for std in ${STD}; do
for absl in 0 1; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--workdir="/src" \
--rm \
--env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=${std}" \
${LINUX_LATEST_CONTAINER} \
/usr/local/bin/bazel test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors
done
done
# Test Clang
for std in ${STD}; do
for absl in 0 1; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--workdir="/src" \
--rm \
--env="CC=/opt/llvm/clang/bin/clang" \
--env="BAZEL_CXXOPTS=-std=${std}" \
${LINUX_LATEST_CONTAINER} \
/usr/local/bin/bazel test ... \
--copt="--gcc-toolchain=/usr/local" \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--linkopt="--gcc-toolchain=/usr/local" \
--show_timestamps \
--test_output=errors
done
done
#!/bin/bash
#
# Copyright 2020, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
set -euox pipefail
if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
# Test the CMake build
for cmake_off_on in OFF ON; do
BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
cd ${BUILD_DIR}
time cmake ${GTEST_ROOT} \
-DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on}
time make
time ctest -j$(nproc) --output-on-failure
done
# Test the Bazel build
# If we are running on Kokoro, check for a versioned Bazel binary.
KOKORO_GFILE_BAZEL_BIN="bazel-7.0.0-darwin-x86_64"
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then
BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}"
chmod +x ${BAZEL_BIN}
else
BAZEL_BIN="bazel"
fi
cd ${GTEST_ROOT}
for absl in 0 1; do
${BAZEL_BIN} test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wundef" \
--cxxopt="-std=c++14" \
--define="absl=${absl}" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors
done
SETLOCAL ENABLEDELAYEDEXPANSION
SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-7.0.0-windows-x86_64.exe
SET PATH=C:\Python34;%PATH%
SET BAZEL_PYTHON=C:\python34\python.exe
SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe
SET CMAKE_BIN="cmake.exe"
SET CTEST_BIN="ctest.exe"
SET CTEST_OUTPUT_ON_FAILURE=1
SET CMAKE_BUILD_PARALLEL_LEVEL=16
SET CTEST_PARALLEL_LEVEL=16
IF EXIST git\googletest (
CD git\googletest
) ELSE IF EXIST github\googletest (
CD github\googletest
)
IF %errorlevel% neq 0 EXIT /B 1
:: ----------------------------------------------------------------------------
:: CMake
MKDIR cmake_msvc2022
CD cmake_msvc2022
%CMAKE_BIN% .. ^
-G "Visual Studio 17 2022" ^
-DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^
-DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^
-DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^
-Dgtest_build_samples=ON ^
-Dgtest_build_tests=ON ^
-Dgmock_build_tests=ON
IF %errorlevel% neq 0 EXIT /B 1
%CMAKE_BIN% --build . --target ALL_BUILD --config Debug -- -maxcpucount
IF %errorlevel% neq 0 EXIT /B 1
%CTEST_BIN% -C Debug --timeout 600
IF %errorlevel% neq 0 EXIT /B 1
CD ..
RMDIR /S /Q cmake_msvc2022
:: ----------------------------------------------------------------------------
:: Bazel
SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community
%BAZEL_EXE% test ... ^
--compilation_mode=dbg ^
--copt=/std:c++14 ^
--copt=/WX ^
--enable_bzlmod=true ^
--keep_going ^
--test_output=errors ^
--test_tag_filters=-no_test_msvc2017
IF %errorlevel% neq 0 EXIT /B 1
nav:
- section: "Get Started"
items:
- title: "Supported Platforms"
url: "/platforms.html"
- title: "Quickstart: Bazel"
url: "/quickstart-bazel.html"
- title: "Quickstart: CMake"
url: "/quickstart-cmake.html"
- section: "Guides"
items:
- title: "GoogleTest Primer"
url: "/primer.html"
- title: "Advanced Topics"
url: "/advanced.html"
- title: "Mocking for Dummies"
url: "/gmock_for_dummies.html"
- title: "Mocking Cookbook"
url: "/gmock_cook_book.html"
- title: "Mocking Cheat Sheet"
url: "/gmock_cheat_sheet.html"
- section: "References"
items:
- title: "Testing Reference"
url: "/reference/testing.html"
- title: "Mocking Reference"
url: "/reference/mocking.html"
- title: "Assertions"
url: "/reference/assertions.html"
- title: "Matchers"
url: "/reference/matchers.html"
- title: "Actions"
url: "/reference/actions.html"
- title: "Testing FAQ"
url: "/faq.html"
- title: "Mocking FAQ"
url: "/gmock_faq.html"
- title: "Code Samples"
url: "/samples.html"
- title: "Using pkg-config"
url: "/pkgconfig.html"
- title: "Community Documentation"
url: "/community_created_documentation.html"
<!DOCTYPE html>
<html lang="{{ site.lang | default: "en-US" }}">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% seo %}
<link rel="stylesheet" href="{{ "/assets/css/style.css?v=" | append: site.github.build_revision | relative_url }}">
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-197576187-1', { 'storage': 'none' });
ga('set', 'referrer', document.referrer.split('?')[0]);
ga('set', 'location', window.location.href.split('?')[0]);
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
</head>
<body>
<div class="sidebar">
<div class="header">
<h1><a href="{{ "/" | relative_url }}">{{ site.title | default: "Documentation" }}</a></h1>
</div>
<input type="checkbox" id="nav-toggle" class="nav-toggle">
<label for="nav-toggle" class="expander">
<span class="arrow"></span>
</label>
<nav>
{% for item in site.data.navigation.nav %}
<h2>{{ item.section }}</h2>
<ul>
{% for subitem in item.items %}
<a href="{{subitem.url | relative_url }}">
<li class="{% if subitem.url == page.url %}active{% endif %}">
{{ subitem.title }}
</li>
</a>
{% endfor %}
</ul>
{% endfor %}
</nav>
</div>
<div class="main markdown-body">
<div class="main-inner">
{{ content }}
</div>
<div class="footer">
GoogleTest &middot;
<a href="https://github.com/google/googletest">GitHub Repository</a> &middot;
<a href="https://github.com/google/googletest/blob/main/LICENSE">License</a> &middot;
<a href="https://policies.google.com/privacy">Privacy Policy</a>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.0/anchor.min.js" integrity="sha256-lZaRhKri35AyJSypXXs4o6OPFTbTmUoltBbDCbdzegg=" crossorigin="anonymous"></script>
<script>anchors.add('.main h2, .main h3, .main h4, .main h5, .main h6');</script>
</body>
</html>
// Styles for GoogleTest docs website on GitHub Pages.
// Color variables are defined in
// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables
$sidebar-width: 260px;
body {
display: flex;
margin: 0;
}
.sidebar {
background: $black;
color: $text-white;
flex-shrink: 0;
height: 100vh;
overflow: auto;
position: sticky;
top: 0;
width: $sidebar-width;
}
.sidebar h1 {
font-size: 1.5em;
}
.sidebar h2 {
color: $gray-light;
font-size: 0.8em;
font-weight: normal;
margin-bottom: 0.8em;
padding-left: 2.5em;
text-transform: uppercase;
}
.sidebar .header {
background: $black;
padding: 2em;
position: sticky;
top: 0;
width: 100%;
}
.sidebar .header a {
color: $text-white;
text-decoration: none;
}
.sidebar .nav-toggle {
display: none;
}
.sidebar .expander {
cursor: pointer;
display: none;
height: 3em;
position: absolute;
right: 1em;
top: 1.5em;
width: 3em;
}
.sidebar .expander .arrow {
border: solid $white;
border-width: 0 3px 3px 0;
display: block;
height: 0.7em;
margin: 1em auto;
transform: rotate(45deg);
transition: transform 0.5s;
width: 0.7em;
}
.sidebar nav {
width: 100%;
}
.sidebar nav ul {
list-style-type: none;
margin-bottom: 1em;
padding: 0;
&:last-child {
margin-bottom: 2em;
}
a {
text-decoration: none;
}
li {
color: $text-white;
padding-left: 2em;
text-decoration: none;
}
li.active {
background: $border-gray-darker;
font-weight: bold;
}
li:hover {
background: $border-gray-darker;
}
}
.main {
background-color: $bg-gray;
width: calc(100% - #{$sidebar-width});
}
.main .main-inner {
background-color: $white;
padding: 2em;
}
.main .footer {
margin: 0;
padding: 2em;
}
.main table th {
text-align: left;
}
.main .callout {
border-left: 0.25em solid $white;
padding: 1em;
a {
text-decoration: underline;
}
&.important {
background-color: $bg-yellow-light;
border-color: $bg-yellow;
color: $black;
}
&.note {
background-color: $bg-blue-light;
border-color: $text-blue;
color: $text-blue;
}
&.tip {
background-color: $green-000;
border-color: $green-700;
color: $green-700;
}
&.warning {
background-color: $red-000;
border-color: $text-red;
color: $text-red;
}
}
.main .good pre {
background-color: $bg-green-light;
}
.main .bad pre {
background-color: $red-000;
}
@media all and (max-width: 768px) {
body {
flex-direction: column;
}
.sidebar {
height: auto;
position: relative;
width: 100%;
}
.sidebar .expander {
display: block;
}
.sidebar nav {
height: 0;
overflow: hidden;
}
.sidebar .nav-toggle:checked {
& ~ nav {
height: auto;
}
& + .expander .arrow {
transform: rotate(-135deg);
}
}
.main {
width: 100%;
}
}
---
---
@import "jekyll-theme-primer";
@import "main";
# Community-Created Documentation
The following is a list, in no particular order, of links to documentation
created by the Googletest community.
* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md),
by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy)
# gMock Cheat Sheet
## Defining a Mock Class
### Mocking a Normal Class {#MockClass}
Given
```cpp
class Foo {
public:
virtual ~Foo();
virtual int GetSize() const = 0;
virtual string Describe(const char* name) = 0;
virtual string Describe(int type) = 0;
virtual bool Process(Bar elem, int count) = 0;
};
```
(note that `~Foo()` **must** be virtual) we can define its mock as
```cpp
#include <gmock/gmock.h>
class MockFoo : public Foo {
public:
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(string, Describe, (const char* name), (override));
MOCK_METHOD(string, Describe, (int type), (override));
MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
};
```
To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
which warns on all uninteresting calls, or a "strict" mock, which treats them as
failures:
```cpp
using ::testing::NiceMock;
using ::testing::NaggyMock;
using ::testing::StrictMock;
NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
```
{: .callout .note}
**Note:** A mock object is currently naggy by default. We may make it nice by
default in the future.
### Mocking a Class Template {#MockTemplate}
Class templates can be mocked just like any class.
To mock
```cpp
template <typename Elem>
class StackInterface {
public:
virtual ~StackInterface();
virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0;
};
```
(note that all member functions that are mocked, including `~StackInterface()`
**must** be virtual).
```cpp
template <typename Elem>
class MockStack : public StackInterface<Elem> {
public:
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```
### Specifying Calling Conventions for Mock Functions
If your mock function doesn't use the default calling convention, you can
specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
For example,
```cpp
MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(int, Bar, (double x, double y),
(const, Calltype(STDMETHODCALLTYPE)));
```
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
## Using Mocks in Tests {#UsingMocks}
The typical work flow is:
1. Import the gMock names you need to use. All gMock symbols are in the
`testing` namespace unless they are macros or otherwise noted.
2. Create the mock objects.
3. Optionally, set the default actions of the mock objects.
4. Set your expectations on the mock objects (How will they be called? What
will they do?).
5. Exercise code that uses the mock objects; if necessary, check the result
using googletest assertions.
6. When a mock object is destructed, gMock automatically verifies that all
expectations on it have been satisfied.
Here's an example:
```cpp
using ::testing::Return; // #1
TEST(BarTest, DoesThis) {
MockFoo foo; // #2
ON_CALL(foo, GetSize()) // #3
.WillByDefault(Return(1));
// ... other default actions ...
EXPECT_CALL(foo, Describe(5)) // #4
.Times(3)
.WillRepeatedly(Return("Category 5"));
// ... other expectations ...
EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5
} // #6
```
## Setting Default Actions {#OnCall}
gMock has a **built-in default action** for any function that returns `void`,
`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
the default-constructed value, if one exists for the given type.
To customize the default action for functions with return type `T`, use
[`DefaultValue<T>`](reference/mocking.md#DefaultValue). For example:
```cpp
// Sets the default action for return type std::unique_ptr<Buzz> to
// creating a new Buzz every time.
DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
[] { return std::make_unique<Buzz>(AccessLevel::kInternal); });
// When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
auto buzz1 = mock_buzzer_.MakeBuzz("hello");
auto buzz2 = mock_buzzer_.MakeBuzz("hello");
EXPECT_NE(buzz1, nullptr);
EXPECT_NE(buzz2, nullptr);
EXPECT_NE(buzz1, buzz2);
// Resets the default action for return type std::unique_ptr<Buzz>,
// to avoid interfere with other tests.
DefaultValue<std::unique_ptr<Buzz>>::Clear();
```
To customize the default action for a particular method of a specific mock
object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar
syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you
do not require that the mock method is called. See
[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed
discussion.
## Setting Expectations {#ExpectCall}
See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference.
## Matchers {#MatcherList}
See the [Matchers Reference](reference/matchers.md).
## Actions {#ActionList}
See the [Actions Reference](reference/actions.md).
## Cardinalities {#CardinalityList}
See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of
`EXPECT_CALL` in the Mocking Reference.
## Expectation Order
By default, expectations can be matched in *any* order. If some or all
expectations must be matched in a given order, you can use the
[`After` clause](reference/mocking.md#EXPECT_CALL.After) or
[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of
`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence).
## Verifying and Resetting a Mock
gMock will verify the expectations on a mock object when it is destructed, or
you can do it earlier:
```cpp
using ::testing::Mock;
...
// Verifies and removes the expectations on mock_obj;
// returns true if and only if successful.
Mock::VerifyAndClearExpectations(&mock_obj);
...
// Verifies and removes the expectations on mock_obj;
// also removes the default actions set by ON_CALL();
// returns true if and only if successful.
Mock::VerifyAndClear(&mock_obj);
```
Do not set new expectations after verifying and clearing a mock after its use.
Setting expectations after code that exercises the mock has undefined behavior.
See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more
information.
You can also tell gMock that a mock object can be leaked and doesn't need to be
verified:
```cpp
Mock::AllowLeak(&mock_obj);
```
## Mock Classes
gMock defines a convenient mock class template
```cpp
class MockFunction<R(A1, ..., An)> {
public:
MOCK_METHOD(R, Call, (A1, ..., An));
};
```
See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of
it.
## Flags
| Flag | Description |
| :----------------------------- | :---------------------------------------- |
| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
This source diff could not be displayed because it is too large. You can view the blob instead.
# GoogleTest User's Guide
## Welcome to GoogleTest!
GoogleTest is Google's C++ testing and mocking framework. This user's guide has
the following contents:
* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using
GoogleTest. Read this first if you are new to GoogleTest.
* [GoogleTest Advanced](advanced.md) - Read this when you've finished the
Primer and want to utilize GoogleTest to its full potential.
* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples.
* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here
first.
* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock
objects and use them in tests.
* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to
common mocking use cases.
* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for
matchers, actions, invariants, and more.
* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific
questions.
## Using GoogleTest from various build systems
GoogleTest comes with pkg-config files that can be used to determine all
necessary flags for compiling and linking to GoogleTest (and GoogleMock).
Pkg-config is a standardised plain-text format containing
* the includedir (-I) path
* necessary macro (-D) definitions
* further required flags (-pthread)
* the library (-L) path
* the library (-l) to link to
All current build systems support pkg-config in one way or another. For all
examples here we assume you want to compile the sample
`samples/sample3_unittest.cc`.
### CMake
Using `pkg-config` in CMake is fairly easy:
```cmake
find_package(PkgConfig)
pkg_search_module(GTEST REQUIRED gtest_main)
add_executable(testapp)
target_sources(testapp PRIVATE samples/sample3_unittest.cc)
target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS})
target_compile_options(testapp PRIVATE ${GTEST_CFLAGS})
enable_testing()
add_test(first_and_only_test testapp)
```
It is generally recommended that you use `target_compile_options` + `_CFLAGS`
over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not
just -I flags (GoogleTest might require a macro indicating to internal headers
that all libraries have been compiled with threading enabled. In addition,
GoogleTest might also require `-pthread` in the compiling step, and as such
splitting the pkg-config `Cflags` variable into include dirs and macros for
`target_compile_definitions()` might still miss this). The same recommendation
goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens
to discard `-L` flags and `-pthread`.
### Help! pkg-config can't find GoogleTest!
Let's say you have a `CMakeLists.txt` along the lines of the one in this
tutorial and you try to run `cmake`. It is very possible that you get a failure
along the lines of:
```
-- Checking for one of the modules 'gtest_main'
CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message):
None of the required 'gtest_main' found
```
These failures are common if you installed GoogleTest yourself and have not
sourced it from a distro or other package manager. If so, you need to tell
pkg-config where it can find the `.pc` files containing the information. Say you
installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are
installed under `/usr/local/lib64/pkgconfig`. If you set
```
export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig
```
pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`.
### Using pkg-config in a cross-compilation setting
Pkg-config can be used in a cross-compilation setting too. To do this, let's
assume the final prefix of the cross-compiled installation will be `/usr`, and
your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using
```
mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr ..
```
Install into the sysroot using `DESTDIR`:
```
make -j install DESTDIR=/home/MYUSER/sysroot
```
Before we continue, it is recommended to **always** define the following two
variables for pkg-config in a cross-compilation setting:
```
export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes
export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes
```
otherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes
such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for
reasons why this stripping needs to occur usually).
If you look at the generated pkg-config file, it will look something like
```
libdir=/usr/lib64
includedir=/usr/include
Name: gtest
Description: GoogleTest (without main() function)
Version: 1.11.0
URL: https://github.com/google/googletest
Libs: -L${libdir} -lgtest -lpthread
Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread
```
Notice that the sysroot is not included in `libdir` and `includedir`! If you try
to run `pkg-config` with the correct
`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc`
file, you will get
```
$ pkg-config --cflags gtest
-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include
$ pkg-config --libs gtest
-L/usr/lib64 -lgtest -lpthread
```
which is obviously wrong and points to the `CBUILD` and not `CHOST` root. In
order to use this in a cross-compilation setting, we need to tell pkg-config to
inject the actual sysroot into `-I` and `-L` variables. Let us now tell
pkg-config about the actual sysroot
```
export PKG_CONFIG_DIR=
export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot
export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig
```
and running `pkg-config` again we get
```
$ pkg-config --cflags gtest
-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include
$ pkg-config --libs gtest
-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread
```
which contains the correct sysroot now. For a more comprehensive guide to also
including `${CHOST}` in build system calls, see the excellent tutorial by Diego
Elio Pettenò: <https://autotools.io/pkgconfig/cross-compiling.html>
# Supported Platforms
GoogleTest follows Google's
[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
for a list of currently supported versions compilers, platforms, and build
tools.
# Quickstart: Building with Bazel
This tutorial aims to get you up and running with GoogleTest using the Bazel
build system. If you're using GoogleTest for the first time or need a refresher,
we recommend this tutorial as a starting point.
## Prerequisites
To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++14.
* [Bazel](https://bazel.build/), the preferred build system used by the
GoogleTest team.
See [Supported Platforms](platforms.md) for more information about platforms
compatible with GoogleTest.
If you don't already have Bazel installed, see the
[Bazel installation guide](https://bazel.build/install).
{: .callout .note} Note: The terminal commands in this tutorial show a Unix
shell prompt, but the commands work on the Windows command line as well.
## Set up a Bazel workspace
A
[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace)
is a directory on your filesystem that you use to manage source files for the
software you want to build. Each workspace directory has a text file named
`WORKSPACE` which may be empty, or may contain references to external
dependencies required to build the outputs.
First, create a directory for your workspace:
```
$ mkdir my_workspace && cd my_workspace
```
Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and
recommended way to depend on GoogleTest is to use a
[Bazel external dependency](https://docs.bazel.build/versions/main/external.html)
via the
[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive).
To do this, in the root directory of your workspace (`my_workspace/`), create a
file named `WORKSPACE` with the following contents:
```
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "com_google_googletest",
urls = ["https://github.com/google/googletest/archive/5ab508a01f9eb089207ee87fd547d290da39d015.zip"],
strip_prefix = "googletest-5ab508a01f9eb089207ee87fd547d290da39d015",
)
```
The above configuration declares a dependency on GoogleTest which is downloaded
as a ZIP archive from GitHub. In the above example,
`5ab508a01f9eb089207ee87fd547d290da39d015` is the Git commit hash of the
GoogleTest version to use; we recommend updating the hash often to point to the
latest version. Use a recent hash on the `main` branch.
Now you're ready to build C++ code that uses GoogleTest.
## Create and run a binary
With your Bazel workspace set up, you can now use GoogleTest code within your
own project.
As an example, create a file named `hello_test.cc` in your `my_workspace`
directory with the following contents:
```cpp
#include <gtest/gtest.h>
// Demonstrate some basic assertions.
TEST(HelloTest, BasicAssertions) {
// Expect two strings not to be equal.
EXPECT_STRNE("hello", "world");
// Expect equality.
EXPECT_EQ(7 * 6, 42);
}
```
GoogleTest provides [assertions](primer.md#assertions) that you use to test the
behavior of your code. The above sample includes the main GoogleTest header file
and demonstrates some basic assertions.
To build the code, create a file named `BUILD` in the same directory with the
following contents:
```
cc_test(
name = "hello_test",
size = "small",
srcs = ["hello_test.cc"],
deps = ["@com_google_googletest//:gtest_main"],
)
```
This `cc_test` rule declares the C++ test binary you want to build, and links to
GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE`
file (`@com_google_googletest`). For more information about Bazel `BUILD` files,
see the
[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html).
{: .callout .note}
NOTE: In the example below, we assume Clang or GCC and set `--cxxopt=-std=c++14`
to ensure that GoogleTest is compiled as C++14 instead of the compiler's default
setting (which could be C++11). For MSVC, the equivalent would be
`--cxxopt=/std:c++14`. See [Supported Platforms](platforms.md) for more details
on supported language versions.
Now you can build and run your test:
<pre>
<strong>my_workspace$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test</strong>
INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
INFO: Found 1 test target...
INFO: From Testing //:hello_test:
==================== Test output for //:hello_test:
Running main() from gmock_main.cc
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from HelloTest
[ RUN ] HelloTest.BasicAssertions
[ OK ] HelloTest.BasicAssertions (0 ms)
[----------] 1 test from HelloTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
================================================================================
Target //:hello_test up-to-date:
bazel-bin/hello_test
INFO: Elapsed time: 4.190s, Critical Path: 3.05s
INFO: 27 processes: 8 internal, 19 linux-sandbox.
INFO: Build completed successfully, 27 total actions
//:hello_test PASSED in 0.1s
INFO: Build completed successfully, 27 total actions
</pre>
Congratulations! You've successfully built and run a test binary using
GoogleTest.
## Next steps
* [Check out the Primer](primer.md) to start learning how to write simple
tests.
* [See the code samples](samples.md) for more examples showing how to use a
variety of GoogleTest features.
# Quickstart: Building with CMake
This tutorial aims to get you up and running with GoogleTest using CMake. If
you're using GoogleTest for the first time or need a refresher, we recommend
this tutorial as a starting point. If your project uses Bazel, see the
[Quickstart for Bazel](quickstart-bazel.md) instead.
## Prerequisites
To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++14.
* [CMake](https://cmake.org/) and a compatible build tool for building the
project.
* Compatible build tools include
[Make](https://www.gnu.org/software/make/),
[Ninja](https://ninja-build.org/), and others - see
[CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html)
for more information.
See [Supported Platforms](platforms.md) for more information about platforms
compatible with GoogleTest.
If you don't already have CMake installed, see the
[CMake installation guide](https://cmake.org/install).
{: .callout .note}
Note: The terminal commands in this tutorial show a Unix shell prompt, but the
commands work on the Windows command line as well.
## Set up a project
CMake uses a file named `CMakeLists.txt` to configure the build system for a
project. You'll use this file to set up your project and declare a dependency on
GoogleTest.
First, create a directory for your project:
```
$ mkdir my_project && cd my_project
```
Next, you'll create the `CMakeLists.txt` file and declare a dependency on
GoogleTest. There are many ways to express dependencies in the CMake ecosystem;
in this quickstart, you'll use the
[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html).
To do this, in your project directory (`my_project`), create a file named
`CMakeLists.txt` with the following contents:
```cmake
cmake_minimum_required(VERSION 3.14)
project(my_project)
# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
```
The above configuration declares a dependency on GoogleTest which is downloaded
from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is
the Git commit hash of the GoogleTest version to use; we recommend updating the
hash often to point to the latest version.
For more information about how to create `CMakeLists.txt` files, see the
[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html).
## Create and run a binary
With GoogleTest declared as a dependency, you can use GoogleTest code within
your own project.
As an example, create a file named `hello_test.cc` in your `my_project`
directory with the following contents:
```cpp
#include <gtest/gtest.h>
// Demonstrate some basic assertions.
TEST(HelloTest, BasicAssertions) {
// Expect two strings not to be equal.
EXPECT_STRNE("hello", "world");
// Expect equality.
EXPECT_EQ(7 * 6, 42);
}
```
GoogleTest provides [assertions](primer.md#assertions) that you use to test the
behavior of your code. The above sample includes the main GoogleTest header file
and demonstrates some basic assertions.
To build the code, add the following to the end of your `CMakeLists.txt` file:
```cmake
enable_testing()
add_executable(
hello_test
hello_test.cc
)
target_link_libraries(
hello_test
GTest::gtest_main
)
include(GoogleTest)
gtest_discover_tests(hello_test)
```
The above configuration enables testing in CMake, declares the C++ test binary
you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The
last two lines enable CMake's test runner to discover the tests included in the
binary, using the
[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html).
Now you can build and run your test:
<pre>
<strong>my_project$ cmake -S . -B build</strong>
-- The C compiler identification is GNU 10.2.1
-- The CXX compiler identification is GNU 10.2.1
...
-- Build files have been written to: .../my_project/build
<strong>my_project$ cmake --build build</strong>
Scanning dependencies of target gtest
...
[100%] Built target gmock_main
<strong>my_project$ cd build && ctest</strong>
Test project .../my_project/build
Start 1: HelloTest.BasicAssertions
1/1 Test #1: HelloTest.BasicAssertions ........ Passed 0.00 sec
100% tests passed, 0 tests failed out of 1
Total Test time (real) = 0.01 sec
</pre>
Congratulations! You've successfully built and run a test binary using
GoogleTest.
## Next steps
* [Check out the Primer](primer.md) to start learning how to write simple
tests.
* [See the code samples](samples.md) for more examples showing how to use a
variety of GoogleTest features.
# Actions Reference
[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a
mock function should do when invoked. This page lists the built-in actions
provided by GoogleTest. All actions are defined in the `::testing` namespace.
## Returning a Value
| Action | Description |
| :-------------------------------- | :-------------------------------------------- |
| `Return()` | Return from a `void` mock function. |
| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed. |
| `ReturnArg<N>()` | Return the `N`-th (0-based) argument. |
| `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. |
| `ReturnNull()` | Return a null pointer. |
| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. |
| `ReturnRef(variable)` | Return a reference to `variable`. |
| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. |
| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. |
## Side Effects
| Action | Description |
| :--------------------------------- | :-------------------------------------- |
| `Assign(&variable, value)` | Assign `value` to variable. |
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
| `SetArgReferee<N>(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. |
| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. |
| `SetArgumentPointee<N>(value)` | Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0. |
| `SetArrayArgument<N>(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. |
| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. |
| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. |
## Using a Function, Functor, or Lambda as an Action
In the following, by "callable" we mean a free function, `std::function`,
functor, or lambda.
| Action | Description |
| :---------------------------------- | :------------------------------------- |
| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. |
| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. |
| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. |
| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. |
| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. |
| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. |
The return value of the invoked function is used as the return value of the
action.
When defining a callable to be used with `Invoke*()`, you can declare any unused
parameters as `Unused`:
```cpp
using ::testing::Invoke;
double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
...
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
```
`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of
`callback`, which must be permanent. The type of `callback` must be a base
callback type instead of a derived one, e.g.
```cpp
BlockingClosure* done = new BlockingClosure;
... Invoke(done) ...; // This won't compile!
Closure* done2 = new BlockingClosure;
... Invoke(done2) ...; // This works.
```
In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference,
wrap it inside `std::ref()`. For example,
```cpp
using ::testing::InvokeArgument;
...
InvokeArgument<2>(5, string("Hi"), std::ref(foo))
```
calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by
value, and `foo` by reference.
## Default Action
| Action | Description |
| :------------ | :----------------------------------------------------- |
| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
{: .callout .note}
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a
composite action - trying to do so will result in a run-time error.
## Composite Actions
| Action | Description |
| :----------------------------- | :------------------------------------------ |
| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. |
| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. |
| `WithArg<N>(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |
| `WithArgs<N1, N2, ..., Nk>(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |
| `WithoutArgs(a)` | Perform action `a` without any arguments. |
## Defining Actions
| Macro | Description |
| :--------------------------------- | :-------------------------------------- |
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. |
The `ACTION*` macros cannot be used inside a function or class.
# Googletest Samples
If you're like us, you'd like to look at
[googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a
variety of googletest features.
* Sample #1 shows the basic steps of using googletest to test C++ functions.
* Sample #2 shows a more complex unit test for a class with multiple member
functions.
* Sample #3 uses a test fixture.
* Sample #4 teaches you how to use googletest and `googletest.h` together to
get the best of both libraries.
* Sample #5 puts shared testing logic in a base test fixture, and reuses it in
derived fixtures.
* Sample #6 demonstrates type-parameterized tests.
* Sample #7 teaches the basics of value-parameterized tests.
* Sample #8 shows using `Combine()` in value-parameterized tests.
* Sample #9 shows use of the listener API to modify Google Test's console
output and the use of its reflection API to inspect test results.
* Sample #10 shows use of the listener API to implement a primitive memory
leak checker.
"""Provides a fake @fuchsia_sdk implementation that's used when the real one isn't available.
This is needed since bazel queries on targets that depend on //:gtest (eg:
`bazel query "deps(set(//googletest/test:gtest_all_test))"`) will fail if @fuchsia_sdk is not
defined when bazel is evaluating the transitive closure of the query target.
See https://github.com/google/googletest/issues/4472.
"""
def _fake_fuchsia_sdk_impl(repo_ctx):
for stub_target in repo_ctx.attr._stub_build_targets:
stub_package = stub_target
stub_target_name = stub_target.split("/")[-1]
repo_ctx.file("%s/BUILD.bazel" % stub_package, """
filegroup(
name = "%s",
)
""" % stub_target_name)
fake_fuchsia_sdk = repository_rule(
doc = "Used to create a fake @fuchsia_sdk repository with stub build targets.",
implementation = _fake_fuchsia_sdk_impl,
attrs = {
"_stub_build_targets": attr.string_list(
doc = "The stub build targets to initialize.",
default = [
"pkg/fdio",
"pkg/syslog",
"pkg/zx",
],
),
},
)
########################################################################
# Note: CMake support is community-based. The maintainers do not use CMake
# internally.
#
# CMake build script for Google Mock.
#
# To run the tests for Google Mock itself on Linux, use 'make test' or
# ctest. You can select which tests to run using 'ctest -R regex'.
# For more options, run 'ctest --help'.
option(gmock_build_tests "Build all of Google Mock's own tests." OFF)
# A directory to find Google Test sources.
if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt")
set(gtest_dir gtest)
else()
set(gtest_dir ../googletest)
endif()
# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().
include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL)
if (COMMAND pre_project_set_up_hermetic_build)
# Google Test also calls hermetic setup functions from add_subdirectory,
# although its changes will not affect things at the current scope.
pre_project_set_up_hermetic_build()
endif()
########################################################################
#
# Project-wide settings
# Name of the project.
#
# CMake files in this project can refer to the root source directory
# as ${gmock_SOURCE_DIR} and to the root binary directory as
# ${gmock_BINARY_DIR}.
# Language "C" is required for find_package(Threads).
cmake_minimum_required(VERSION 3.13)
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
if (COMMAND set_up_hermetic_build)
set_up_hermetic_build()
endif()
# Instructs CMake to process Google Test's CMakeLists.txt and add its
# targets to the current scope. We are placing Google Test's binary
# directory in a subdirectory of our own as VC compilation may break
# if they are the same (the default).
add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}")
# These commands only run if this is the main project
if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution")
# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
# make it prominent in the GUI.
option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF)
else()
mark_as_advanced(gmock_build_tests)
endif()
# Although Google Test's CMakeLists.txt calls this function, the
# changes there don't affect the current scope. Therefore we have to
# call it again here.
config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake
# Adds Google Mock's and Google Test's header directories to the search path.
# Get Google Test's include dirs from the target, gtest_SOURCE_DIR is broken
# when using fetch-content with the name "GTest".
get_target_property(gtest_include_dirs gtest INCLUDE_DIRECTORIES)
set(gmock_build_include_dirs
"${gmock_SOURCE_DIR}/include"
"${gmock_SOURCE_DIR}"
"${gtest_include_dirs}")
include_directories(${gmock_build_include_dirs})
########################################################################
#
# Defines the gmock & gmock_main libraries. User tests should link
# with one of them.
# Google Mock libraries. We build them using more strict warnings than what
# are used for other targets, to ensure that Google Mock can be compiled by
# a user aggressive about warnings.
if (MSVC)
cxx_library(gmock
"${cxx_strict}"
"${gtest_dir}/src/gtest-all.cc"
src/gmock-all.cc)
cxx_library(gmock_main
"${cxx_strict}"
"${gtest_dir}/src/gtest-all.cc"
src/gmock-all.cc
src/gmock_main.cc)
else()
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
target_link_libraries(gmock PUBLIC gtest)
set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION})
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
target_link_libraries(gmock_main PUBLIC gmock)
set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
endif()
string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
target_include_directories(gmock SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gmock_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
########################################################################
#
# Install rules.
install_project(gmock gmock_main)
########################################################################
#
# Google Mock's own tests.
#
# You can skip this section if you aren't interested in testing
# Google Mock itself.
#
# The tests are not built by default. To build them, set the
# gmock_build_tests option to ON. You can do it by running ccmake
# or specifying the -Dgmock_build_tests=ON flag when running cmake.
if (gmock_build_tests)
# This must be set in the root directory for the tests to be run by
# 'make test' or ctest.
enable_testing()
if (MINGW OR CYGWIN)
add_compile_options("-Wa,-mbig-obj")
endif()
############################################################
# C++ tests built with standard compiler flags.
cxx_test(gmock-actions_test gmock_main)
cxx_test(gmock-cardinalities_test gmock_main)
cxx_test(gmock_ex_test gmock_main)
cxx_test(gmock-function-mocker_test gmock_main)
cxx_test(gmock-internal-utils_test gmock_main)
cxx_test(gmock-matchers-arithmetic_test gmock_main)
cxx_test(gmock-matchers-comparisons_test gmock_main)
cxx_test(gmock-matchers-containers_test gmock_main)
cxx_test(gmock-matchers-misc_test gmock_main)
cxx_test(gmock-more-actions_test gmock_main)
cxx_test(gmock-nice-strict_test gmock_main)
cxx_test(gmock-port_test gmock_main)
cxx_test(gmock-spec-builders_test gmock_main)
cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc)
cxx_test(gmock_test gmock_main)
if (DEFINED GTEST_HAS_PTHREAD)
cxx_test(gmock_stress_test gmock)
endif()
# gmock_all_test is commented to save time building and running tests.
# Uncomment if necessary.
# cxx_test(gmock_all_test gmock_main)
############################################################
# C++ tests built with non-standard compiler flags.
if (MSVC)
cxx_library(gmock_main_no_exception "${cxx_no_exception}"
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}"
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
else()
cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc)
target_link_libraries(gmock_main_no_exception PUBLIC gmock)
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc)
target_link_libraries(gmock_main_no_rtti PUBLIC gmock)
endif()
cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}"
gmock_main_no_exception test/gmock-more-actions_test.cc)
cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}"
gmock_main_no_rtti test/gmock-spec-builders_test.cc)
cxx_shared_library(shared_gmock_main "${cxx_default}"
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
# Tests that a binary can be built with Google Mock as a shared library. On
# some system configurations, it may not possible to run the binary without
# knowing more details about the system configurations. We do not try to run
# this binary. To get a more robust shared library coverage, configure with
# -DBUILD_SHARED_LIBS=ON.
cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}"
shared_gmock_main test/gmock-spec-builders_test.cc)
set_target_properties(shared_gmock_test_
PROPERTIES
COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
############################################################
# Python tests.
cxx_executable(gmock_leak_test_ test gmock_main)
py_test(gmock_leak_test)
cxx_executable(gmock_output_test_ test gmock)
py_test(gmock_output_test)
endif()
# Googletest Mocking (gMock) Framework
### Overview
Google's framework for writing and using C++ mock classes. It can help you
derive better designs of your system and write better tests.
It is inspired by:
* [jMock](http://www.jmock.org/)
* [EasyMock](https://easymock.org/)
* [Hamcrest](https://code.google.com/p/hamcrest/)
It is designed with C++'s specifics in mind.
gMock:
- Provides a declarative syntax for defining mocks.
- Can define partial (hybrid) mocks, which are a cross of real and mock
objects.
- Handles functions of arbitrary types and overloaded functions.
- Comes with a rich set of matchers for validating function arguments.
- Uses an intuitive syntax for controlling the behavior of a mock.
- Does automatic verification of expectations (no record-and-replay needed).
- Allows arbitrary (partial) ordering constraints on function calls to be
expressed.
- Lets a user extend it by defining new matchers and actions.
- Does not use exceptions.
- Is easy to learn and use.
Details and examples can be found here:
* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html)
* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html)
* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html)
* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html)
GoogleMock is a part of
[GoogleTest C++ testing framework](https://github.com/google/googletest/) and a
subject to the same requirements.
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
Name: gmock
Description: GoogleMock (without main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
Requires: gtest = @PROJECT_VERSION@
Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
Name: gmock_main
Description: GoogleMock (with main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
Requires: gmock = @PROJECT_VERSION@
Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
# Content Moved
We are working on updates to the GoogleTest documentation, which has moved to
the top-level [docs](../../docs) directory.
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some commonly used cardinalities. More
// cardinalities can be defined by the user implementing the
// CardinalityInterface interface if necessary.
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#include <limits.h>
#include <memory>
#include <ostream> // NOLINT
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
namespace testing {
// To implement a cardinality Foo, define:
// 1. a class FooCardinality that implements the
// CardinalityInterface interface, and
// 2. a factory function that creates a Cardinality object from a
// const FooCardinality*.
//
// The two-level delegation design follows that of Matcher, providing
// consistency for extension developers. It also eases ownership
// management as Cardinality objects can now be copied like plain values.
// The implementation of a cardinality.
class CardinalityInterface {
public:
virtual ~CardinalityInterface() = default;
// Conservative estimate on the lower/upper bound of the number of
// calls allowed.
virtual int ConservativeLowerBound() const { return 0; }
virtual int ConservativeUpperBound() const { return INT_MAX; }
// Returns true if and only if call_count calls will satisfy this
// cardinality.
virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
// Returns true if and only if call_count calls will saturate this
// cardinality.
virtual bool IsSaturatedByCallCount(int call_count) const = 0;
// Describes self to an ostream.
virtual void DescribeTo(::std::ostream* os) const = 0;
};
// A Cardinality is a copyable and IMMUTABLE (except by assignment)
// object that specifies how many times a mock function is expected to
// be called. The implementation of Cardinality is just a std::shared_ptr
// to const CardinalityInterface. Don't inherit from Cardinality!
class GTEST_API_ Cardinality {
public:
// Constructs a null cardinality. Needed for storing Cardinality
// objects in STL containers.
Cardinality() = default;
// Constructs a Cardinality from its implementation.
explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
// Conservative estimate on the lower/upper bound of the number of
// calls allowed.
int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
// Returns true if and only if call_count calls will satisfy this
// cardinality.
bool IsSatisfiedByCallCount(int call_count) const {
return impl_->IsSatisfiedByCallCount(call_count);
}
// Returns true if and only if call_count calls will saturate this
// cardinality.
bool IsSaturatedByCallCount(int call_count) const {
return impl_->IsSaturatedByCallCount(call_count);
}
// Returns true if and only if call_count calls will over-saturate this
// cardinality, i.e. exceed the maximum number of allowed calls.
bool IsOverSaturatedByCallCount(int call_count) const {
return impl_->IsSaturatedByCallCount(call_count) &&
!impl_->IsSatisfiedByCallCount(call_count);
}
// Describes self to an ostream
void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
// Describes the given actual call count to an ostream.
static void DescribeActualCallCountTo(int actual_call_count,
::std::ostream* os);
private:
std::shared_ptr<const CardinalityInterface> impl_;
};
// Creates a cardinality that allows at least n calls.
GTEST_API_ Cardinality AtLeast(int n);
// Creates a cardinality that allows at most n calls.
GTEST_API_ Cardinality AtMost(int n);
// Creates a cardinality that allows any number of calls.
GTEST_API_ Cardinality AnyNumber();
// Creates a cardinality that allows between min and max calls.
GTEST_API_ Cardinality Between(int min, int max);
// Creates a cardinality that allows exactly n calls.
GTEST_API_ Cardinality Exactly(int n);
// Creates a cardinality from its implementation.
inline Cardinality MakeCardinality(const CardinalityInterface* c) {
return Cardinality(c);
}
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
This source diff could not be displayed because it is too large. You can view the blob instead.
// Copyright 2013, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some matchers that depend on gmock-matchers.h.
//
// Note that tests are implemented in gmock-matchers_test.cc rather than
// gmock-more-matchers-test.cc.
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#include <ostream>
#include <string>
#include "gmock/gmock-matchers.h"
namespace testing {
// Silence C4100 (unreferenced formal
// parameter) for MSVC
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#if defined(_MSC_VER) && (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#endif
namespace internal {
// Implements the polymorphic IsEmpty matcher, which
// can be used as a Matcher<T> as long as T is either a container that defines
// empty() and size() (e.g. std::vector or std::string), or a C-style string.
class IsEmptyMatcher {
public:
// Matches anything that defines empty() and size().
template <typename MatcheeContainerType>
bool MatchAndExplain(const MatcheeContainerType& c,
MatchResultListener* listener) const {
if (c.empty()) {
return true;
}
*listener << "whose size is " << c.size();
return false;
}
// Matches C-style strings.
bool MatchAndExplain(const char* s, MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener);
}
// Describes what this matcher matches.
void DescribeTo(std::ostream* os) const { *os << "is empty"; }
void DescribeNegationTo(std::ostream* os) const { *os << "isn't empty"; }
};
} // namespace internal
// Creates a polymorphic matcher that matches an empty container or C-style
// string. The container must support both size() and empty(), which all
// STL-like containers provide.
inline PolymorphicMatcher<internal::IsEmptyMatcher> IsEmpty() {
return MakePolymorphicMatcher(internal::IsEmptyMatcher());
}
// Define a matcher that matches a value that evaluates in boolean
// context to true. Useful for types that define "explicit operator
// bool" operators and so can't be compared for equality with true
// and false.
MATCHER(IsTrue, negation ? "is false" : "is true") {
return static_cast<bool>(arg);
}
// Define a matcher that matches a value that evaluates in boolean
// context to false. Useful for types that define "explicit operator
// bool" operators and so can't be compared for equality with true
// and false.
MATCHER(IsFalse, negation ? "is true" : "is false") {
return !static_cast<bool>(arg);
}
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#endif
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
} // namespace testing
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This is the main header file a user should include.
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
// This file implements the following syntax:
//
// ON_CALL(mock_object, Method(...))
// .With(...) ?
// .WillByDefault(...);
//
// where With() is optional and WillByDefault() must appear exactly
// once.
//
// EXPECT_CALL(mock_object, Method(...))
// .With(...) ?
// .Times(...) ?
// .InSequence(...) *
// .WillOnce(...) *
// .WillRepeatedly(...) ?
// .RetiresOnSaturation() ? ;
//
// where all clauses are optional and WillOnce() can be repeated.
#include "gmock/gmock-actions.h" // IWYU pragma: export
#include "gmock/gmock-cardinalities.h" // IWYU pragma: export
#include "gmock/gmock-function-mocker.h" // IWYU pragma: export
#include "gmock/gmock-matchers.h" // IWYU pragma: export
#include "gmock/gmock-more-actions.h" // IWYU pragma: export
#include "gmock/gmock-more-matchers.h" // IWYU pragma: export
#include "gmock/gmock-nice-strict.h" // IWYU pragma: export
#include "gmock/gmock-spec-builders.h" // IWYU pragma: export
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
// Declares Google Mock flags that we want a user to use programmatically.
GMOCK_DECLARE_bool_(catch_leaked_mocks);
GMOCK_DECLARE_string_(verbose);
GMOCK_DECLARE_int32_(default_mock_behavior);
namespace testing {
// Initializes Google Mock. This must be called before running the
// tests. In particular, it parses the command line for the flags
// that Google Mock recognizes. Whenever a Google Mock flag is seen,
// it is removed from argv, and *argc is decremented.
//
// No value is returned. Instead, the Google Mock flag variables are
// updated.
//
// Since Google Test is needed for Google Mock to work, this function
// also initializes Google Test and parses its flags, if that hasn't
// been done.
GTEST_API_ void InitGoogleMock(int* argc, char** argv);
// This overloaded version can be used in Windows programs compiled in
// UNICODE mode.
GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
// This overloaded version can be used on Arduino/embedded platforms where
// there is no argc/argv.
GTEST_API_ void InitGoogleMock();
} // namespace testing
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
# Customization Points
The custom directory is an injection point for custom user configurations.
## Header `gmock-port.h`
The following macros can be defined:
### Flag related macros:
* `GMOCK_DECLARE_bool_(name)`
* `GMOCK_DECLARE_int32_(name)`
* `GMOCK_DECLARE_string_(name)`
* `GMOCK_DEFINE_bool_(name, default_val, doc)`
* `GMOCK_DEFINE_int32_(name, default_val, doc)`
* `GMOCK_DEFINE_string_(name, default_val, doc)`
* `GMOCK_FLAG_GET(flag_name)`
* `GMOCK_FLAG_SET(flag_name, value)`
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Injection point for custom user configurations. See README for details
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Injection point for custom user configurations. See README for details
//
// ** Custom implementation starts here **
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Low-level types and utilities for porting Google Mock to various
// platforms. All macros ending with _ and symbols defined in an
// internal namespace are subject to change without notice. Code
// outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't
// end with _ are part of Google Mock's public API and can be used by
// code outside Google Mock.
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
#include <assert.h>
#include <stdlib.h>
#include <cstdint>
#include <iostream>
// Most of the utilities needed for porting Google Mock are also
// required for Google Test and are defined in gtest-port.h.
//
// Note to maintainers: to reduce code duplication, prefer adding
// portability utilities to Google Test's gtest-port.h instead of
// here, as Google Mock depends on Google Test. Only add a utility
// here if it's truly specific to Google Mock.
#include "gmock/internal/custom/gmock-port.h"
#include "gtest/internal/gtest-port.h"
#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
#include "absl/flags/declare.h"
#include "absl/flags/flag.h"
#endif
// For MS Visual C++, check the compiler version. At least VS 2015 is
// required to compile Google Mock.
#if defined(_MSC_VER) && _MSC_VER < 1900
#error "At least Visual C++ 2015 (14.0) is required to compile Google Mock."
#endif
// Macro for referencing flags. This is public as we want the user to
// use this syntax to reference Google Mock flags.
#define GMOCK_FLAG_NAME_(name) gmock_##name
#define GMOCK_FLAG(name) FLAGS_gmock_##name
// Pick a command line flags implementation.
#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
// Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \
ABSL_FLAG(bool, GMOCK_FLAG_NAME_(name), default_val, doc)
#define GMOCK_DEFINE_int32_(name, default_val, doc) \
ABSL_FLAG(int32_t, GMOCK_FLAG_NAME_(name), default_val, doc)
#define GMOCK_DEFINE_string_(name, default_val, doc) \
ABSL_FLAG(std::string, GMOCK_FLAG_NAME_(name), default_val, doc)
// Macros for declaring flags.
#define GMOCK_DECLARE_bool_(name) \
ABSL_DECLARE_FLAG(bool, GMOCK_FLAG_NAME_(name))
#define GMOCK_DECLARE_int32_(name) \
ABSL_DECLARE_FLAG(int32_t, GMOCK_FLAG_NAME_(name))
#define GMOCK_DECLARE_string_(name) \
ABSL_DECLARE_FLAG(std::string, GMOCK_FLAG_NAME_(name))
#define GMOCK_FLAG_GET(name) ::absl::GetFlag(GMOCK_FLAG(name))
#define GMOCK_FLAG_SET(name, value) \
(void)(::absl::SetFlag(&GMOCK_FLAG(name), value))
#else // defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
// Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \
namespace testing { \
GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DEFINE_int32_(name, default_val, doc) \
namespace testing { \
GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DEFINE_string_(name, default_val, doc) \
namespace testing { \
GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val); \
} \
static_assert(true, "no-op to require trailing semicolon")
// Macros for declaring flags.
#define GMOCK_DECLARE_bool_(name) \
namespace testing { \
GTEST_API_ extern bool GMOCK_FLAG(name); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DECLARE_int32_(name) \
namespace testing { \
GTEST_API_ extern int32_t GMOCK_FLAG(name); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DECLARE_string_(name) \
namespace testing { \
GTEST_API_ extern ::std::string GMOCK_FLAG(name); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name)
#define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value)
#endif // defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Google C++ Mocking Framework (Google Mock)
//
// This file #includes all Google Mock implementation .cc files. The
// purpose is to allow a user to build Google Mock by compiling this
// file alone.
// This line ensures that gmock.h can be compiled on its own, even
// when it's fused.
#include "gmock/gmock.h"
// The following lines pull in the real gmock *.cc files.
#include "src/gmock-cardinalities.cc"
#include "src/gmock-internal-utils.cc"
#include "src/gmock-matchers.cc"
#include "src/gmock-spec-builders.cc"
#include "src/gmock.cc"
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements cardinalities.
#include "gmock/gmock-cardinalities.h"
#include <limits.h>
#include <ostream> // NOLINT
#include <sstream>
#include <string>
#include "gmock/internal/gmock-internal-utils.h"
#include "gtest/gtest.h"
namespace testing {
namespace {
// Implements the Between(m, n) cardinality.
class BetweenCardinalityImpl : public CardinalityInterface {
public:
BetweenCardinalityImpl(int min, int max)
: min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {
std::stringstream ss;
if (min < 0) {
ss << "The invocation lower bound must be >= 0, "
<< "but is actually " << min << ".";
internal::Expect(false, __FILE__, __LINE__, ss.str());
} else if (max < 0) {
ss << "The invocation upper bound must be >= 0, "
<< "but is actually " << max << ".";
internal::Expect(false, __FILE__, __LINE__, ss.str());
} else if (min > max) {
ss << "The invocation upper bound (" << max
<< ") must be >= the invocation lower bound (" << min << ").";
internal::Expect(false, __FILE__, __LINE__, ss.str());
}
}
// Conservative estimate on the lower/upper bound of the number of
// calls allowed.
int ConservativeLowerBound() const override { return min_; }
int ConservativeUpperBound() const override { return max_; }
bool IsSatisfiedByCallCount(int call_count) const override {
return min_ <= call_count && call_count <= max_;
}
bool IsSaturatedByCallCount(int call_count) const override {
return call_count >= max_;
}
void DescribeTo(::std::ostream* os) const override;
private:
const int min_;
const int max_;
BetweenCardinalityImpl(const BetweenCardinalityImpl&) = delete;
BetweenCardinalityImpl& operator=(const BetweenCardinalityImpl&) = delete;
};
// Formats "n times" in a human-friendly way.
inline std::string FormatTimes(int n) {
if (n == 1) {
return "once";
} else if (n == 2) {
return "twice";
} else {
std::stringstream ss;
ss << n << " times";
return ss.str();
}
}
// Describes the Between(m, n) cardinality in human-friendly text.
void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
if (min_ == 0) {
if (max_ == 0) {
*os << "never called";
} else if (max_ == INT_MAX) {
*os << "called any number of times";
} else {
*os << "called at most " << FormatTimes(max_);
}
} else if (min_ == max_) {
*os << "called " << FormatTimes(min_);
} else if (max_ == INT_MAX) {
*os << "called at least " << FormatTimes(min_);
} else {
// 0 < min_ < max_ < INT_MAX
*os << "called between " << min_ << " and " << max_ << " times";
}
}
} // Unnamed namespace
// Describes the given call count to an ostream.
void Cardinality::DescribeActualCallCountTo(int actual_call_count,
::std::ostream* os) {
if (actual_call_count > 0) {
*os << "called " << FormatTimes(actual_call_count);
} else {
*os << "never called";
}
}
// Creates a cardinality that allows at least n calls.
GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
// Creates a cardinality that allows at most n calls.
GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
// Creates a cardinality that allows any number of calls.
GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
// Creates a cardinality that allows between min and max calls.
GTEST_API_ Cardinality Between(int min, int max) {
return Cardinality(new BetweenCardinalityImpl(min, max));
}
// Creates a cardinality that allows exactly n calls.
GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
} // namespace testing
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment