Commit f4b97bbb authored by gejun's avatar gejun

Remove UT's deps on gmock & fix UT

parent 5b817802
......@@ -9,6 +9,7 @@ include config.mk
CPPFLAGS+=-DBTHREAD_USE_FAST_PTHREAD_MUTEX -D__const__= -D_GNU_SOURCE -DUSE_SYMBOLIZE -DNO_TCMALLOC -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS -DBRPC_REVISION=\"$(shell git rev-parse --short HEAD)\"
CXXFLAGS+=$(CPPFLAGS) -g -O2 -pipe -Wall -W -fPIC -fstrict-aliasing -Wno-invalid-offsetof -Wno-unused-parameter -fno-omit-frame-pointer -std=c++0x
CFLAGS+=$(CPPFLAGS) -g -O2 -pipe -Wall -W -fPIC -fstrict-aliasing -Wno-unused-parameter -fno-omit-frame-pointer
DEBUG_CXXFLAGS = $(CXXFLAGS) -DUNIT_TEST -DBVAR_NOT_LINK_DEFAULT_VARIABLES
HDRPATHS=-I./src $(addprefix -I, $(HDRS))
LIBPATHS = $(addprefix -L, $(LIBS))
COMMA = ,
......@@ -168,13 +169,15 @@ MCPACK2PB_SOURCES = \
MCPACK2PB_OBJS = src/idl_options.pb.o $(addsuffix .o, $(basename $(MCPACK2PB_SOURCES)))
OBJS=$(BUTIL_OBJS) $(BVAR_OBJS) $(BTHREAD_OBJS) $(JSON2PB_OBJS) $(MCPACK2PB_OBJS) $(BRPC_OBJS)
BVAR_DEBUG_OBJS=$(BUTIL_OBJS:.o=.dbg.o) $(BVAR_OBJS:.o=.dbg.o)
DEBUG_OBJS = $(OBJS:.o=.dbg.o)
.PHONY:all
all: protoc-gen-mcpack libbrpc.a libbrpc.so output/include output/lib output/bin
.PHONY:debug
debug: libbrpc.dbg.a
debug: libbrpc.dbg.a libbvar.dbg.a
.PHONY:clean
clean:clean_debug
......@@ -183,7 +186,9 @@ clean:clean_debug
.PHONY:clean_debug
clean_debug:
@rm -rf libbrpc.dbg.a $(DEBUG_OBJS)
@rm -rf libbrpc.dbg.a libbvar.dbg.a $(DEBUG_OBJS)
.PRECIOUS: %.o
protoc-gen-mcpack: src/idl_options.pb.cc src/mcpack2pb/generator.o libbrpc.a
@echo "Linking $@"
......@@ -192,15 +197,19 @@ protoc-gen-mcpack: src/idl_options.pb.cc src/mcpack2pb/generator.o libbrpc.a
# force generation of pb headers before compiling to avoid fail-to-import issues in compiling pb.cc
libbrpc.a:$(BRPC_PROTOS:.proto=.pb.h) $(OBJS)
@echo "Packing $@"
@ar crs $@ $(OBJS)
@ar crs $@ $(filter %.o,$^)
libbrpc.so:$(BRPC_PROTOS:.proto=.pb.h) $(OBJS)
@echo "Linking $@"
$(CXX) -shared -o $@ $(HDRPATHS) $(LIBPATHS) $(SOPATHS) -Xlinker "-(" $(OBJS) -Xlinker "-)" $(STATIC_LINKINGS) $(DYNAMIC_LINKINGS)
$(CXX) -shared -o $@ $(LIBPATHS) $(SOPATHS) -Xlinker "-(" $(filter %.o,$^) -Xlinker "-)" $(STATIC_LINKINGS) $(DYNAMIC_LINKINGS)
libbvar.dbg.a:$(BVAR_DEBUG_OBJS)
@echo "Packing $@"
@ar crs $@ $^
libbrpc.dbg.a:$(BRPC_PROTOS:.proto=.pb.h) $(DEBUG_OBJS)
@echo "Packing $@"
@ar crs $@ $(DEBUG_OBJS)
@ar crs $@ $(filter %.o,$^)
.PHONY:output/include
output/include:
......@@ -231,7 +240,7 @@ output/bin:protoc-gen-mcpack
%.dbg.o:%.cpp
@echo "Compiling $@"
@$(CXX) -c $(HDRPATHS) $(CXXFLAGS) -DBVAR_NOT_LINK_DEFAULT_VARIABLES $< -o $@
@$(CXX) -c $(HDRPATHS) $(DEBUG_CXXFLAGS) $< -o $@
%.o:%.cc
@echo "Compiling $@"
......@@ -239,7 +248,7 @@ output/bin:protoc-gen-mcpack
%.dbg.o:%.cc
@echo "Compiling $@"
@$(CXX) -c $(HDRPATHS) $(CXXFLAGS) $< -o $@
@$(CXX) -c $(HDRPATHS) $(DEBUG_CXXFLAGS) $< -o $@
%.o:%.c
@echo "Compiling $@"
......
......@@ -324,22 +324,6 @@ else
fi
append_to_output "endif"
#gmock
GMOCK_LIB=$(find_dir_of_lib gmock)
HDRS=$OLD_HDRS
LIBS=$OLD_LIBS
append_to_output "ifeq (\$(NEED_GMOCK), 1)"
if [ -z "$GMOCK_LIB" ]; then
append_to_output " \$(error \"Fail to find gmock\")"
else
GMOCK_HDR=$(find_dir_of_header_or_die gmock/gmock.h)
append_to_output_libs $GMOCK_LIB " "
append_to_output_headers $GMOCK_HDR " "
append_to_output_linkings $GMOCK_LIB gmock " "
append_to_output_linkings $GMOCK_LIB gmock_main " "
fi
append_to_output "endif"
# generate src/butil/config.h
cat << EOF > src/butil/config.h
// This file is auto-generated by $(basename "$0"). DON'T edit it!
......
......@@ -36,15 +36,8 @@ Examples link brpc statically, if you need to link the shared version, `make cle
To run examples with cpu/heap profilers, install `libgoogle-perftools-dev` and re-run `config_brpc.sh` before compiling
### compile tests
Install gmock and gtest, use the gtest embedded in gmock and don't install libgtest-dev
```
$ sudo apt-get install google-mock
$ cd /usr/src
$ sudo cmake .
$ sudo make
$ sudo mv lib*.a gtest/lib*.a /usr/lib
$ sudo mv gtest/include/gtest /usr/include/
```
Install libgtest-dev
Rerun config_brpc.sh and run make in test/
## Fedora/CentOS
......
......@@ -25,8 +25,6 @@
namespace bvar {
namespace detail {
// set to true in UT. Not using gflags since users hardly need to change it.
bool FLAGS_show_sampler_usage = true;
const int WARN_NOSLEEP_THRESHOLD = 2;
// Combine two circular linked list into one.
......@@ -94,11 +92,11 @@ private:
void SamplerCollector::run() {
butil::LinkNode<Sampler> root;
int consecutive_nosleep = 0;
#ifndef UNIT_TEST
PassiveStatus<double> cumulated_time(get_cumulated_time, this);
bvar::PerSecond<bvar::PassiveStatus<double> > usage(&cumulated_time, 10);
if (FLAGS_show_sampler_usage) {
usage.expose("bvar_sampler_collector_usage");
}
bvar::PerSecond<bvar::PassiveStatus<double> > usage(
"bvar_sampler_collector_usage", &cumulated_time, 10);
#endif
while (!_stop) {
int64_t abstime = butil::gettimeofday_us();
Sampler* s = this->reset();
......
NEED_GPERFTOOLS=1
NEED_GTEST=1
NEED_GMOCK=1
include ../config.mk
CPPFLAGS+=-DBTHREAD_USE_FAST_PTHREAD_MUTEX -D__const__= -D_GNU_SOURCE -DUSE_SYMBOLIZE -DNO_TCMALLOC -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS
CPPFLAGS+=-DUNIT_TEST -Dprivate=public -Dprotected=public -DBVAR_NOT_LINK_DEFAULT_VARIABLES --include sstream_workaround.h
......@@ -15,8 +14,8 @@ ifeq ($(shell test $(GCC_VERSION) -ge 70000; echo $$?),0)
CXXFLAGS+=-Wno-aligned-new
endif
HDRPATHS=-I. -I.. -I../src $(addprefix -I, $(HDRS))
LIBPATHS=$(addprefix -L, $(LIBS))
HDRPATHS=-I. -I../src $(addprefix -I, $(HDRS))
LIBPATHS=-L.. $(addprefix -L, $(LIBS))
TEST_BUTIL_SOURCES = \
at_exit_unittest.cc \
......@@ -137,7 +136,7 @@ TEST_BINS = test_butil test_bvar $(TEST_BTHREAD_SOURCES:.cpp=) $(TEST_BRPC_SOURC
all: $(TEST_BINS)
.PHONY:clean
clean:clean_bins clean_dbg
clean:clean_bins clean_debug
@echo "Cleaning"
@rm -rf $(TEST_BUTIL_OBJS) $(TEST_BVAR_OBJS) $(TEST_BTHREAD_OBJS) \
$(TEST_BRPC_OBJS) $(TEST_PROTO_OBJS)
......@@ -146,12 +145,12 @@ clean:clean_bins clean_dbg
clean_bins:
@rm -rf $(TEST_BINS)
.PHONY:clean_dbg
clean_dbg:
.PHONY:clean_debug
clean_debug:
@$(MAKE) -C.. clean_debug
../libbrpc.dbg.a: FORCE
@$(MAKE) -C.. libbrpc.dbg.a
../libbrpc.dbg.a ../libbvar.dbg.a: FORCE
@$(MAKE) -C.. debug
FORCE:
......@@ -161,7 +160,7 @@ test_butil:$(TEST_BUTIL_OBJS) ../libbrpc.dbg.a
@echo "Linking $@"
@$(CXX) -o $@ $(LIBPATHS) -Xlinker "-(" $^ -Wl,-Bstatic $(STATIC_LINKINGS) -Wl,-Bdynamic -Xlinker "-)" $(DYNAMIC_LINKINGS)
test_bvar:$(TEST_BVAR_OBJS) ../libbrpc.dbg.a
test_bvar:$(TEST_BVAR_OBJS) ../libbvar.dbg.a
@echo "Linking $@"
@$(CXX) -o $@ $(LIBPATHS) -Xlinker "-(" $^ -Wl,-Bstatic $(STATIC_LINKINGS) -Wl,-Bdynamic -Xlinker "-)" $(DYNAMIC_LINKINGS)
......
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "butil/bind.h"
#include "butil/callback.h"
#include "butil/memory/ref_counted.h"
#include "butil/memory/scoped_ptr.h"
#include "butil/memory/weak_ptr.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::Mock;
using ::testing::Return;
using ::testing::StrictMock;
namespace butil {
namespace {
class IncompleteType;
class NoRef {
public:
NoRef() {}
MOCK_METHOD0(VoidMethod0, void(void));
MOCK_CONST_METHOD0(VoidConstMethod0, void(void));
MOCK_METHOD0(IntMethod0, int(void));
MOCK_CONST_METHOD0(IntConstMethod0, int(void));
private:
// Particularly important in this test to ensure no copies are made.
DISALLOW_COPY_AND_ASSIGN(NoRef);
};
class HasRef : public NoRef {
public:
HasRef() {}
MOCK_CONST_METHOD0(AddRef, void(void));
MOCK_CONST_METHOD0(Release, bool(void));
private:
// Particularly important in this test to ensure no copies are made.
DISALLOW_COPY_AND_ASSIGN(HasRef);
};
class HasRefPrivateDtor : public HasRef {
private:
~HasRefPrivateDtor() {}
};
static const int kParentValue = 1;
static const int kChildValue = 2;
class Parent {
public:
void AddRef(void) const {}
void Release(void) const {}
virtual void VirtualSet() { value = kParentValue; }
void NonVirtualSet() { value = kParentValue; }
int value;
};
class Child : public Parent {
public:
virtual void VirtualSet() OVERRIDE { value = kChildValue; }
void NonVirtualSet() { value = kChildValue; }
};
class NoRefParent {
public:
virtual void VirtualSet() { value = kParentValue; }
void NonVirtualSet() { value = kParentValue; }
int value;
};
class NoRefChild : public NoRefParent {
virtual void VirtualSet() OVERRIDE { value = kChildValue; }
void NonVirtualSet() { value = kChildValue; }
};
// Used for probing the number of copies that occur if a type must be coerced
// during argument forwarding in the Run() methods.
struct DerivedCopyCounter {
DerivedCopyCounter(int* copies, int* assigns)
: copies_(copies), assigns_(assigns) {
}
int* copies_;
int* assigns_;
};
// Used for probing the number of copies in an argument.
class CopyCounter {
public:
CopyCounter(int* copies, int* assigns)
: copies_(copies), assigns_(assigns) {
}
CopyCounter(const CopyCounter& other)
: copies_(other.copies_),
assigns_(other.assigns_) {
(*copies_)++;
}
// Probing for copies from coercion.
explicit CopyCounter(const DerivedCopyCounter& other)
: copies_(other.copies_),
assigns_(other.assigns_) {
(*copies_)++;
}
const CopyCounter& operator=(const CopyCounter& rhs) {
copies_ = rhs.copies_;
assigns_ = rhs.assigns_;
if (assigns_) {
(*assigns_)++;
}
return *this;
}
int copies() const {
return *copies_;
}
private:
int* copies_;
int* assigns_;
};
class DeleteCounter {
public:
explicit DeleteCounter(int* deletes)
: deletes_(deletes) {
}
~DeleteCounter() {
(*deletes_)++;
}
void VoidMethod0() {}
private:
int* deletes_;
};
template <typename T>
T PassThru(T scoper) {
return scoper.Pass();
}
// Some test functions that we can Bind to.
template <typename T>
T PolymorphicIdentity(T t) {
return t;
}
template <typename T>
void VoidPolymorphic1(T t) {
}
int Identity(int n) {
return n;
}
int ArrayGet(const int array[], int n) {
return array[n];
}
int Sum(int a, int b, int c, int d, int e, int f) {
return a + b + c + d + e + f;
}
const char* CStringIdentity(const char* s) {
return s;
}
int GetCopies(const CopyCounter& counter) {
return counter.copies();
}
int UnwrapNoRefParent(NoRefParent p) {
return p.value;
}
int UnwrapNoRefParentPtr(NoRefParent* p) {
return p->value;
}
int UnwrapNoRefParentConstRef(const NoRefParent& p) {
return p.value;
}
void RefArgSet(int &n) {
n = 2;
}
void PtrArgSet(int *n) {
*n = 2;
}
int FunctionWithWeakFirstParam(WeakPtr<NoRef> o, int n) {
return n;
}
int FunctionWithScopedRefptrFirstParam(const scoped_refptr<HasRef>& o, int n) {
return n;
}
void TakesACallback(const Closure& callback) {
callback.Run();
}
class BindTest : public ::testing::Test {
public:
BindTest() {
const_has_ref_ptr_ = &has_ref_;
const_no_ref_ptr_ = &no_ref_;
static_func_mock_ptr = &static_func_mock_;
}
virtual ~BindTest() {
}
static void VoidFunc0(void) {
static_func_mock_ptr->VoidMethod0();
}
static int IntFunc0(void) { return static_func_mock_ptr->IntMethod0(); }
protected:
StrictMock<NoRef> no_ref_;
StrictMock<HasRef> has_ref_;
const HasRef* const_has_ref_ptr_;
const NoRef* const_no_ref_ptr_;
StrictMock<NoRef> static_func_mock_;
// Used by the static functions to perform expectations.
static StrictMock<NoRef>* static_func_mock_ptr;
private:
DISALLOW_COPY_AND_ASSIGN(BindTest);
};
StrictMock<NoRef>* BindTest::static_func_mock_ptr;
// Sanity check that we can instantiate a callback for each arity.
TEST_F(BindTest, ArityTest) {
Callback<int(void)> c0 = Bind(&Sum, 32, 16, 8, 4, 2, 1);
EXPECT_EQ(63, c0.Run());
Callback<int(int)> c1 = Bind(&Sum, 32, 16, 8, 4, 2);
EXPECT_EQ(75, c1.Run(13));
Callback<int(int,int)> c2 = Bind(&Sum, 32, 16, 8, 4);
EXPECT_EQ(85, c2.Run(13, 12));
Callback<int(int,int,int)> c3 = Bind(&Sum, 32, 16, 8);
EXPECT_EQ(92, c3.Run(13, 12, 11));
Callback<int(int,int,int,int)> c4 = Bind(&Sum, 32, 16);
EXPECT_EQ(94, c4.Run(13, 12, 11, 10));
Callback<int(int,int,int,int,int)> c5 = Bind(&Sum, 32);
EXPECT_EQ(87, c5.Run(13, 12, 11, 10, 9));
Callback<int(int,int,int,int,int,int)> c6 = Bind(&Sum);
EXPECT_EQ(69, c6.Run(13, 12, 11, 10, 9, 14));
}
// Test the Currying ability of the Callback system.
TEST_F(BindTest, CurryingTest) {
Callback<int(int,int,int,int,int,int)> c6 = Bind(&Sum);
EXPECT_EQ(69, c6.Run(13, 12, 11, 10, 9, 14));
Callback<int(int,int,int,int,int)> c5 = Bind(c6, 32);
EXPECT_EQ(87, c5.Run(13, 12, 11, 10, 9));
Callback<int(int,int,int,int)> c4 = Bind(c5, 16);
EXPECT_EQ(94, c4.Run(13, 12, 11, 10));
Callback<int(int,int,int)> c3 = Bind(c4, 8);
EXPECT_EQ(92, c3.Run(13, 12, 11));
Callback<int(int,int)> c2 = Bind(c3, 4);
EXPECT_EQ(85, c2.Run(13, 12));
Callback<int(int)> c1 = Bind(c2, 2);
EXPECT_EQ(75, c1.Run(13));
Callback<int(void)> c0 = Bind(c1, 1);
EXPECT_EQ(63, c0.Run());
}
// Test that currying the rvalue result of another Bind() works correctly.
// - rvalue should be usable as argument to Bind().
// - multiple runs of resulting Callback remain valid.
TEST_F(BindTest, CurryingRvalueResultOfBind) {
int n = 0;
Closure cb = butil::Bind(&TakesACallback, butil::Bind(&PtrArgSet, &n));
// If we implement Bind() such that the return value has auto_ptr-like
// semantics, the second call here will fail because ownership of
// the internal BindState<> would have been transfered to a *temporary*
// constructon of a Callback object on the first call.
cb.Run();
EXPECT_EQ(2, n);
n = 0;
cb.Run();
EXPECT_EQ(2, n);
}
// Function type support.
// - Normal function.
// - Normal function bound with non-refcounted first argument.
// - Method bound to non-const object.
// - Method bound to scoped_refptr.
// - Const method bound to non-const object.
// - Const method bound to const object.
// - Derived classes can be used with pointers to non-virtual base functions.
// - Derived classes can be used with pointers to virtual base functions (and
// preserve virtual dispatch).
TEST_F(BindTest, FunctionTypeSupport) {
EXPECT_CALL(static_func_mock_, VoidMethod0());
EXPECT_CALL(has_ref_, AddRef()).Times(5);
EXPECT_CALL(has_ref_, Release()).Times(5);
EXPECT_CALL(has_ref_, VoidMethod0()).Times(2);
EXPECT_CALL(has_ref_, VoidConstMethod0()).Times(2);
Closure normal_cb = Bind(&VoidFunc0);
Callback<NoRef*(void)> normal_non_refcounted_cb =
Bind(&PolymorphicIdentity<NoRef*>, &no_ref_);
normal_cb.Run();
EXPECT_EQ(&no_ref_, normal_non_refcounted_cb.Run());
Closure method_cb = Bind(&HasRef::VoidMethod0, &has_ref_);
Closure method_refptr_cb = Bind(&HasRef::VoidMethod0,
make_scoped_refptr(&has_ref_));
Closure const_method_nonconst_obj_cb = Bind(&HasRef::VoidConstMethod0,
&has_ref_);
Closure const_method_const_obj_cb = Bind(&HasRef::VoidConstMethod0,
const_has_ref_ptr_);
method_cb.Run();
method_refptr_cb.Run();
const_method_nonconst_obj_cb.Run();
const_method_const_obj_cb.Run();
Child child;
child.value = 0;
Closure virtual_set_cb = Bind(&Parent::VirtualSet, &child);
virtual_set_cb.Run();
EXPECT_EQ(kChildValue, child.value);
child.value = 0;
Closure non_virtual_set_cb = Bind(&Parent::NonVirtualSet, &child);
non_virtual_set_cb.Run();
EXPECT_EQ(kParentValue, child.value);
}
// Return value support.
// - Function with return value.
// - Method with return value.
// - Const method with return value.
TEST_F(BindTest, ReturnValues) {
EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
EXPECT_CALL(has_ref_, AddRef()).Times(3);
EXPECT_CALL(has_ref_, Release()).Times(3);
EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(31337));
EXPECT_CALL(has_ref_, IntConstMethod0())
.WillOnce(Return(41337))
.WillOnce(Return(51337));
Callback<int(void)> normal_cb = Bind(&IntFunc0);
Callback<int(void)> method_cb = Bind(&HasRef::IntMethod0, &has_ref_);
Callback<int(void)> const_method_nonconst_obj_cb =
Bind(&HasRef::IntConstMethod0, &has_ref_);
Callback<int(void)> const_method_const_obj_cb =
Bind(&HasRef::IntConstMethod0, const_has_ref_ptr_);
EXPECT_EQ(1337, normal_cb.Run());
EXPECT_EQ(31337, method_cb.Run());
EXPECT_EQ(41337, const_method_nonconst_obj_cb.Run());
EXPECT_EQ(51337, const_method_const_obj_cb.Run());
}
// IgnoreResult adapter test.
// - Function with return value.
// - Method with return value.
// - Const Method with return.
// - Method with return value bound to WeakPtr<>.
// - Const Method with return bound to WeakPtr<>.
TEST_F(BindTest, IgnoreResult) {
EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
EXPECT_CALL(has_ref_, AddRef()).Times(2);
EXPECT_CALL(has_ref_, Release()).Times(2);
EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
EXPECT_CALL(no_ref_, IntMethod0()).WillOnce(Return(12));
EXPECT_CALL(no_ref_, IntConstMethod0()).WillOnce(Return(13));
Closure normal_func_cb = Bind(IgnoreResult(&IntFunc0));
normal_func_cb.Run();
Closure non_void_method_cb =
Bind(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
non_void_method_cb.Run();
Closure non_void_const_method_cb =
Bind(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
non_void_const_method_cb.Run();
WeakPtrFactory<NoRef> weak_factory(&no_ref_);
WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
Closure non_void_weak_method_cb =
Bind(IgnoreResult(&NoRef::IntMethod0), weak_factory.GetWeakPtr());
non_void_weak_method_cb.Run();
Closure non_void_weak_const_method_cb =
Bind(IgnoreResult(&NoRef::IntConstMethod0), weak_factory.GetWeakPtr());
non_void_weak_const_method_cb.Run();
weak_factory.InvalidateWeakPtrs();
non_void_weak_const_method_cb.Run();
non_void_weak_method_cb.Run();
}
// Argument binding tests.
// - Argument binding to primitive.
// - Argument binding to primitive pointer.
// - Argument binding to a literal integer.
// - Argument binding to a literal string.
// - Argument binding with template function.
// - Argument binding to an object.
// - Argument binding to pointer to incomplete type.
// - Argument gets type converted.
// - Pointer argument gets converted.
// - Const Reference forces conversion.
TEST_F(BindTest, ArgumentBinding) {
int n = 2;
Callback<int(void)> bind_primitive_cb = Bind(&Identity, n);
EXPECT_EQ(n, bind_primitive_cb.Run());
Callback<int*(void)> bind_primitive_pointer_cb =
Bind(&PolymorphicIdentity<int*>, &n);
EXPECT_EQ(&n, bind_primitive_pointer_cb.Run());
Callback<int(void)> bind_int_literal_cb = Bind(&Identity, 3);
EXPECT_EQ(3, bind_int_literal_cb.Run());
Callback<const char*(void)> bind_string_literal_cb =
Bind(&CStringIdentity, "hi");
EXPECT_STREQ("hi", bind_string_literal_cb.Run());
Callback<int(void)> bind_template_function_cb =
Bind(&PolymorphicIdentity<int>, 4);
EXPECT_EQ(4, bind_template_function_cb.Run());
NoRefParent p;
p.value = 5;
Callback<int(void)> bind_object_cb = Bind(&UnwrapNoRefParent, p);
EXPECT_EQ(5, bind_object_cb.Run());
IncompleteType* incomplete_ptr = reinterpret_cast<IncompleteType*>(123);
Callback<IncompleteType*(void)> bind_incomplete_ptr_cb =
Bind(&PolymorphicIdentity<IncompleteType*>, incomplete_ptr);
EXPECT_EQ(incomplete_ptr, bind_incomplete_ptr_cb.Run());
NoRefChild c;
c.value = 6;
Callback<int(void)> bind_promotes_cb = Bind(&UnwrapNoRefParent, c);
EXPECT_EQ(6, bind_promotes_cb.Run());
c.value = 7;
Callback<int(void)> bind_pointer_promotes_cb =
Bind(&UnwrapNoRefParentPtr, &c);
EXPECT_EQ(7, bind_pointer_promotes_cb.Run());
c.value = 8;
Callback<int(void)> bind_const_reference_promotes_cb =
Bind(&UnwrapNoRefParentConstRef, c);
EXPECT_EQ(8, bind_const_reference_promotes_cb.Run());
}
// Unbound argument type support tests.
// - Unbound value.
// - Unbound pointer.
// - Unbound reference.
// - Unbound const reference.
// - Unbound unsized array.
// - Unbound sized array.
// - Unbound array-of-arrays.
TEST_F(BindTest, UnboundArgumentTypeSupport) {
Callback<void(int)> unbound_value_cb = Bind(&VoidPolymorphic1<int>);
Callback<void(int*)> unbound_pointer_cb = Bind(&VoidPolymorphic1<int*>);
Callback<void(int&)> unbound_ref_cb = Bind(&VoidPolymorphic1<int&>);
Callback<void(const int&)> unbound_const_ref_cb =
Bind(&VoidPolymorphic1<const int&>);
// NOTE(gejun): Not work for gcc3.4
#if !defined(COMPILER_GCC) || __GNUC__ >= 4
Callback<void(int[])> unbound_unsized_array_cb =
Bind(&VoidPolymorphic1<int[]>);
#endif
Callback<void(int[2])> unbound_sized_array_cb =
Bind(&VoidPolymorphic1<int[2]>);
// NOTE(gejun): Not work for gcc3.4
#if !defined(COMPILER_GCC) || __GNUC__ >= 4
Callback<void(int[][2])> unbound_array_of_arrays_cb =
Bind(&VoidPolymorphic1<int[][2]>);
#endif
}
// Function with unbound reference parameter.
// - Original parameter is modified by callback.
TEST_F(BindTest, UnboundReferenceSupport) {
int n = 0;
Callback<void(int&)> unbound_ref_cb = Bind(&RefArgSet);
unbound_ref_cb.Run(n);
EXPECT_EQ(2, n);
}
// Functions that take reference parameters.
// - Forced reference parameter type still stores a copy.
// - Forced const reference parameter type still stores a copy.
TEST_F(BindTest, ReferenceArgumentBinding) {
int n = 1;
int& ref_n = n;
const int& const_ref_n = n;
Callback<int(void)> ref_copies_cb = Bind(&Identity, ref_n);
EXPECT_EQ(n, ref_copies_cb.Run());
n++;
EXPECT_EQ(n - 1, ref_copies_cb.Run());
Callback<int(void)> const_ref_copies_cb = Bind(&Identity, const_ref_n);
EXPECT_EQ(n, const_ref_copies_cb.Run());
n++;
EXPECT_EQ(n - 1, const_ref_copies_cb.Run());
}
// Check that we can pass in arrays and have them be stored as a pointer.
// - Array of values stores a pointer.
// - Array of const values stores a pointer.
TEST_F(BindTest, ArrayArgumentBinding) {
int array[4] = {1, 1, 1, 1};
const int (*const_array_ptr)[4] = &array;
Callback<int(void)> array_cb = Bind(&ArrayGet, array, 1);
EXPECT_EQ(1, array_cb.Run());
Callback<int(void)> const_array_cb = Bind(&ArrayGet, *const_array_ptr, 1);
EXPECT_EQ(1, const_array_cb.Run());
array[1] = 3;
EXPECT_EQ(3, array_cb.Run());
EXPECT_EQ(3, const_array_cb.Run());
}
// Verify SupportsAddRefAndRelease correctly introspects the class type for
// AddRef() and Release().
// - Class with AddRef() and Release()
// - Class without AddRef() and Release()
// - Derived Class with AddRef() and Release()
// - Derived Class without AddRef() and Release()
// - Derived Class with AddRef() and Release() and a private destructor.
TEST_F(BindTest, SupportsAddRefAndRelease) {
EXPECT_TRUE(internal::SupportsAddRefAndRelease<HasRef>::value);
EXPECT_FALSE(internal::SupportsAddRefAndRelease<NoRef>::value);
// StrictMock<T> is a derived class of T. So, we use StrictMock<HasRef> and
// StrictMock<NoRef> to test that SupportsAddRefAndRelease works over
// inheritance.
EXPECT_TRUE(internal::SupportsAddRefAndRelease<StrictMock<HasRef> >::value);
EXPECT_FALSE(internal::SupportsAddRefAndRelease<StrictMock<NoRef> >::value);
// This matters because the implementation creates a dummy class that
// inherits from the template type.
EXPECT_TRUE(internal::SupportsAddRefAndRelease<HasRefPrivateDtor>::value);
}
// Unretained() wrapper support.
// - Method bound to Unretained() non-const object.
// - Const method bound to Unretained() non-const object.
// - Const method bound to Unretained() const object.
TEST_F(BindTest, Unretained) {
EXPECT_CALL(no_ref_, VoidMethod0());
EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
Callback<void(void)> method_cb =
Bind(&NoRef::VoidMethod0, Unretained(&no_ref_));
method_cb.Run();
Callback<void(void)> const_method_cb =
Bind(&NoRef::VoidConstMethod0, Unretained(&no_ref_));
const_method_cb.Run();
Callback<void(void)> const_method_const_ptr_cb =
Bind(&NoRef::VoidConstMethod0, Unretained(const_no_ref_ptr_));
const_method_const_ptr_cb.Run();
}
// WeakPtr() support.
// - Method bound to WeakPtr<> to non-const object.
// - Const method bound to WeakPtr<> to non-const object.
// - Const method bound to WeakPtr<> to const object.
// - Normal Function with WeakPtr<> as P1 can have return type and is
// not canceled.
TEST_F(BindTest, WeakPtr) {
EXPECT_CALL(no_ref_, VoidMethod0());
EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
WeakPtrFactory<NoRef> weak_factory(&no_ref_);
WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
Closure method_cb =
Bind(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
method_cb.Run();
Closure const_method_cb =
Bind(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
const_method_cb.Run();
Closure const_method_const_ptr_cb =
Bind(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
const_method_const_ptr_cb.Run();
Callback<int(int)> normal_func_cb =
Bind(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
EXPECT_EQ(1, normal_func_cb.Run(1));
weak_factory.InvalidateWeakPtrs();
const_weak_factory.InvalidateWeakPtrs();
method_cb.Run();
const_method_cb.Run();
const_method_const_ptr_cb.Run();
// Still runs even after the pointers are invalidated.
EXPECT_EQ(2, normal_func_cb.Run(2));
}
// ConstRef() wrapper support.
// - Binding w/o ConstRef takes a copy.
// - Binding a ConstRef takes a reference.
// - Binding ConstRef to a function ConstRef does not copy on invoke.
TEST_F(BindTest, ConstRef) {
int n = 1;
Callback<int(void)> copy_cb = Bind(&Identity, n);
Callback<int(void)> const_ref_cb = Bind(&Identity, ConstRef(n));
EXPECT_EQ(n, copy_cb.Run());
EXPECT_EQ(n, const_ref_cb.Run());
n++;
EXPECT_EQ(n - 1, copy_cb.Run());
EXPECT_EQ(n, const_ref_cb.Run());
int copies = 0;
int assigns = 0;
CopyCounter counter(&copies, &assigns);
Callback<int(void)> all_const_ref_cb =
Bind(&GetCopies, ConstRef(counter));
EXPECT_EQ(0, all_const_ref_cb.Run());
EXPECT_EQ(0, copies);
EXPECT_EQ(0, assigns);
}
TEST_F(BindTest, ScopedRefptr) {
// BUG: The scoped_refptr should cause the only AddRef()/Release() pair. But
// due to a bug in butil::Bind(), there's an extra call when invoking the
// callback.
// https://code.google.com/p/chromium/issues/detail?id=251937
EXPECT_CALL(has_ref_, AddRef()).Times(2);
EXPECT_CALL(has_ref_, Release()).Times(2);
const scoped_refptr<StrictMock<HasRef> > refptr(&has_ref_);
Callback<int(void)> scoped_refptr_const_ref_cb =
Bind(&FunctionWithScopedRefptrFirstParam, butil::ConstRef(refptr), 1);
EXPECT_EQ(1, scoped_refptr_const_ref_cb.Run());
}
// Test Owned() support.
TEST_F(BindTest, Owned) {
int deletes = 0;
DeleteCounter* counter = new DeleteCounter(&deletes);
// If we don't capture, delete happens on Callback destruction/reset.
// return the same value.
Callback<DeleteCounter*(void)> no_capture_cb =
Bind(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
ASSERT_EQ(counter, no_capture_cb.Run());
ASSERT_EQ(counter, no_capture_cb.Run());
EXPECT_EQ(0, deletes);
no_capture_cb.Reset(); // This should trigger a delete.
EXPECT_EQ(1, deletes);
deletes = 0;
counter = new DeleteCounter(&deletes);
butil::Closure own_object_cb =
Bind(&DeleteCounter::VoidMethod0, Owned(counter));
own_object_cb.Run();
EXPECT_EQ(0, deletes);
own_object_cb.Reset();
EXPECT_EQ(1, deletes);
}
// Passed() wrapper support.
// - Passed() can be constructed from a pointer to scoper.
// - Passed() can be constructed from a scoper rvalue.
// - Using Passed() gives Callback Ownership.
// - Ownership is transferred from Callback to callee on the first Run().
// - Callback supports unbound arguments.
TEST_F(BindTest, ScopedPtr) {
int deletes = 0;
// Tests the Passed() function's support for pointers.
scoped_ptr<DeleteCounter> ptr(new DeleteCounter(&deletes));
Callback<scoped_ptr<DeleteCounter>(void)> unused_callback =
Bind(&PassThru<scoped_ptr<DeleteCounter> >, Passed(&ptr));
EXPECT_FALSE(ptr.get());
EXPECT_EQ(0, deletes);
// If we never invoke the Callback, it retains ownership and deletes.
unused_callback.Reset();
EXPECT_EQ(1, deletes);
// Tests the Passed() function's support for rvalues.
deletes = 0;
DeleteCounter* counter = new DeleteCounter(&deletes);
Callback<scoped_ptr<DeleteCounter>(void)> callback =
Bind(&PassThru<scoped_ptr<DeleteCounter> >,
Passed(scoped_ptr<DeleteCounter>(counter)));
EXPECT_FALSE(ptr.get());
EXPECT_EQ(0, deletes);
// Check that ownership can be transferred back out.
scoped_ptr<DeleteCounter> result = callback.Run();
ASSERT_EQ(counter, result.get());
EXPECT_EQ(0, deletes);
// Resetting does not delete since ownership was transferred.
callback.Reset();
EXPECT_EQ(0, deletes);
// Ensure that we actually did get ownership.
result.reset();
EXPECT_EQ(1, deletes);
// Test unbound argument forwarding.
Callback<scoped_ptr<DeleteCounter>(scoped_ptr<DeleteCounter>)> cb_unbound =
Bind(&PassThru<scoped_ptr<DeleteCounter> >);
ptr.reset(new DeleteCounter(&deletes));
cb_unbound.Run(ptr.Pass());
}
// Argument Copy-constructor usage for non-reference parameters.
// - Bound arguments are only copied once.
// - Forwarded arguments are only copied once.
// - Forwarded arguments with coercions are only copied twice (once for the
// coercion, and one for the final dispatch).
TEST_F(BindTest, ArgumentCopies) {
int copies = 0;
int assigns = 0;
CopyCounter counter(&copies, &assigns);
Callback<void(void)> copy_cb =
Bind(&VoidPolymorphic1<CopyCounter>, counter);
EXPECT_GE(1, copies);
EXPECT_EQ(0, assigns);
copies = 0;
assigns = 0;
Callback<void(CopyCounter)> forward_cb =
Bind(&VoidPolymorphic1<CopyCounter>);
forward_cb.Run(counter);
EXPECT_GE(1, copies);
EXPECT_EQ(0, assigns);
copies = 0;
assigns = 0;
DerivedCopyCounter dervied(&copies, &assigns);
Callback<void(CopyCounter)> coerce_cb =
Bind(&VoidPolymorphic1<CopyCounter>);
coerce_cb.Run(CopyCounter(dervied));
EXPECT_GE(2, copies);
EXPECT_EQ(0, assigns);
}
// Callback construction and assignment tests.
// - Construction from an InvokerStorageHolder should not cause ref/deref.
// - Assignment from other callback should only cause one ref
//
// TODO(ajwong): Is there actually a way to test this?
#if defined(OS_WIN)
int __fastcall FastCallFunc(int n) {
return n;
}
int __stdcall StdCallFunc(int n) {
return n;
}
// Windows specific calling convention support.
// - Can bind a __fastcall function.
// - Can bind a __stdcall function.
TEST_F(BindTest, WindowsCallingConventions) {
Callback<int(void)> fastcall_cb = Bind(&FastCallFunc, 1);
EXPECT_EQ(1, fastcall_cb.Run());
Callback<int(void)> stdcall_cb = Bind(&StdCallFunc, 2);
EXPECT_EQ(2, stdcall_cb.Run());
}
#endif
#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) && GTEST_HAS_DEATH_TEST
// Test null callbacks cause a DCHECK.
TEST(BindDeathTest, NullCallback) {
butil::Callback<void(int)> null_cb;
ASSERT_TRUE(null_cb.is_null());
EXPECT_DEATH(butil::Bind(null_cb, 42), "");
}
#endif // (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) &&
// GTEST_HAS_DEATH_TEST
} // namespace
} // namespace butil
......@@ -37,7 +37,7 @@
#include "brpc/builtin/sockets_service.h" // SocketsService
#include "brpc/builtin/common.h"
#include "brpc/builtin/bad_method_service.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
DEFINE_bool(foo, false, "Flags for UT");
BRPC_VALIDATE_GFLAG(foo, brpc::PassValidate);
......@@ -194,7 +194,7 @@ protected:
service.default_method(&cntl, &req, &res, &done);
EXPECT_FALSE(cntl.Failed());
EXPECT_EQ(expect_type, cntl.http_response().content_type());
CheckContent(cntl, "test_builtin_service");
CheckContent(cntl, "brpc_builtin_service_unittest");
#endif
}
......@@ -655,8 +655,8 @@ TEST_F(BuiltinServiceTest, pprof) {
ClosureChecker done;
brpc::Controller cntl;
service.growth(&cntl, NULL, NULL, &done);
// MUST fail since tcmalloc hasn't been linked in
EXPECT_EQ(brpc::ENOMETHOD, cntl.ErrorCode());
// linked tcmalloc in UT
EXPECT_EQ(0, cntl.ErrorCode());
}
{
ClosureChecker done;
......@@ -670,7 +670,7 @@ TEST_F(BuiltinServiceTest, pprof) {
brpc::Controller cntl;
service.cmdline(&cntl, NULL, NULL, &done);
EXPECT_FALSE(cntl.Failed());
CheckContent(cntl, "test_builtin_service");
CheckContent(cntl, "brpc_builtin_service_unittest");
}
}
......
......@@ -26,7 +26,7 @@
#include "brpc/selective_channel.h"
#include "brpc/socket_map.h"
#include "brpc/controller.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
#include "brpc/options.pb.h"
namespace brpc {
......
......@@ -9,7 +9,7 @@
#include "brpc/server.h"
#include "brpc/details/http_message.h"
#include "brpc/policy/http_rpc_protocol.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
namespace brpc {
namespace policy {
......
......@@ -19,7 +19,7 @@
#include "brpc/channel.h"
#include "brpc/policy/most_common_message.h"
#include "brpc/controller.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
#include "brpc/policy/http_rpc_protocol.h"
#include "json2pb/pb_to_json.h"
#include "json2pb/json_to_pb.h"
......
......@@ -19,7 +19,7 @@
#include "brpc/policy/hulu_pbrpc_protocol.h"
#include "brpc/policy/most_common_message.h"
#include "brpc/controller.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
......
// Copyright (c) 2014 Baidu, Inc.
// Date: Thu Jun 11 14:30:07 CST 2015
#include <iostream>
#ifdef BAIDU_INTERNAL
#include <iostream>
#include "butil/time.h"
#include "butil/logging.h"
#include <brpc/memcache.h>
......@@ -164,3 +165,5 @@ TEST_F(MemcacheTest, version) {
std::cout << "version=" << version << std::endl;
}
} //namespace
#endif // BAIDU_INTERNAL
......@@ -13,7 +13,7 @@
#include "brpc/policy/file_naming_service.h"
#include "brpc/policy/list_naming_service.h"
#include "brpc/policy/remote_file_naming_service.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
#include "brpc/server.h"
namespace {
......
......@@ -18,7 +18,7 @@
#include "brpc/policy/nova_pbrpc_protocol.h"
#include "brpc/policy/most_common_message.h"
#include "brpc/controller.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
namespace {
void* RunClosure(void* arg) {
......
......@@ -8,7 +8,7 @@
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include "brpc/policy/baidu_rpc_meta.pb.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
namespace {
using namespace google::protobuf;
......
......@@ -19,7 +19,7 @@
#include "brpc/policy/public_pbrpc_protocol.h"
#include "brpc/policy/most_common_message.h"
#include "brpc/controller.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
......
// Copyright (c) 2014 Baidu, Inc.
// Date: Thu Jun 11 14:30:07 CST 2015
#include <iostream>
#ifdef BAIDU_INTERNAL
#include <iostream>
#include "butil/time.h"
#include "butil/logging.h"
#include <brpc/redis.h>
......@@ -234,3 +235,4 @@ TEST_F(RedisTest, by_components) {
ASSERT_EQ(-10, response.reply(3).integer());
}
} //namespace
#endif // BAIDU_INTERNAL
......@@ -37,9 +37,9 @@
#include "brpc/channel.h"
#include "brpc/socket_map.h"
#include "brpc/controller.h"
#include "test/echo.pb.h"
#include "test/v1.pb.h"
#include "test/v2.pb.h"
#include "echo.pb.h"
#include "v1.pb.h"
#include "v2.pb.h"
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
......
......@@ -9,7 +9,7 @@
#include "butil/macros.h"
#include "butil/iobuf.h"
#include "butil/time.h"
#include "test/snappy_message.pb.h"
#include "snappy_message.pb.h"
#include "brpc/policy/snappy_compress.h"
#include "brpc/policy/gzip_compress.h"
......
......@@ -19,7 +19,7 @@
#include "brpc/policy/sofa_pbrpc_protocol.h"
#include "brpc/policy/most_common_message.h"
#include "brpc/controller.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
......
......@@ -9,7 +9,7 @@
#include "brpc/controller.h"
#include "brpc/channel.h"
#include "brpc/stream_impl.h"
#include "test/echo.pb.h"
#include "echo.pb.h"
class AfterAcceptStream {
public:
......
......@@ -6,7 +6,7 @@
#include "butil/base_switches.h"
#include "butil/at_exit.h"
#include "butil/logging.h"
#include "test/multiprocess_func_list.h"
#include "multiprocess_func_list.h"
// Disable coredumps by default to avoid generating a lot of coredumps
// after running death tests.
......
......@@ -14,17 +14,10 @@
#include "bvar/bvar.h"
#include <gtest/gtest.h>
namespace bvar {
namespace detail {
extern bool FLAGS_show_sampler_usage;
}
}
namespace {
class StatusTest : public testing::Test {
protected:
void SetUp() {
bvar::detail::FLAGS_show_sampler_usage = false;
}
void TearDown() {
ASSERT_EQ(0UL, bvar::Variable::count_exposed());
......
......@@ -19,9 +19,6 @@
namespace bvar {
DECLARE_bool(bvar_log_dumpped);
namespace detail {
extern bool FLAGS_show_sampler_usage;
}
}
template <typename T>
......@@ -41,7 +38,6 @@ namespace {
class VariableTest : public testing::Test {
protected:
void SetUp() {
bvar::detail::FLAGS_show_sampler_usage = false;
}
void TearDown() {
ASSERT_EQ(0UL, bvar::Variable::count_exposed());
......
......@@ -5,7 +5,6 @@
#include "butil/basictypes.h"
#include "butil/logging.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <gflags/gflags.h>
......@@ -17,8 +16,6 @@ DECLARE_int32(v);
namespace {
using ::testing::Return;
// Needs to be global since log assert handlers can't maintain state.
int log_sink_call_count = 0;
......@@ -65,44 +62,6 @@ private:
LogStateSaver log_state_saver_;
};
class MockLogSource {
public:
MOCK_METHOD0(Log, const char*());
};
TEST_F(LoggingTest, BasicLogging) {
MockLogSource mock_log_source;
EXPECT_CALL(mock_log_source, Log()).Times(DEBUG_MODE ? 16 : 8).
WillRepeatedly(Return("log message"));
SetMinLogLevel(BLOG_INFO);
EXPECT_TRUE(LOG_IS_ON(INFO));
// As of g++-4.5, the first argument to EXPECT_EQ cannot be a
// constant expression.
const bool kIsDebugMode = (DEBUG_MODE != 0);
EXPECT_TRUE(kIsDebugMode == DLOG_IS_ON(INFO));
EXPECT_TRUE(VLOG_IS_ON(0));
LOG(INFO) << mock_log_source.Log();
LOG_IF(INFO, true) << mock_log_source.Log();
PLOG(INFO) << mock_log_source.Log();
PLOG_IF(INFO, true) << mock_log_source.Log();
VLOG(0) << mock_log_source.Log();
VLOG_IF(0, true) << mock_log_source.Log();
VPLOG(0) << mock_log_source.Log();
VPLOG_IF(0, true) << mock_log_source.Log();
DLOG(INFO) << mock_log_source.Log();
DLOG_IF(INFO, true) << mock_log_source.Log();
DPLOG(INFO) << mock_log_source.Log();
DPLOG_IF(INFO, true) << mock_log_source.Log();
DVLOG(0) << mock_log_source.Log();
DVLOG_IF(0, true) << mock_log_source.Log();
DVPLOG(0) << mock_log_source.Log();
DVPLOG_IF(0, true) << mock_log_source.Log();
}
TEST_F(LoggingTest, LogIsOn) {
#if defined(NDEBUG)
const bool kDfatalIsFatal = false;
......@@ -140,56 +99,6 @@ TEST_F(LoggingTest, LogIsOn) {
EXPECT_TRUE(kDfatalIsFatal == LOG_IS_ON(DFATAL));
}
TEST_F(LoggingTest, LoggingIsLazy) {
MockLogSource mock_log_source;
EXPECT_CALL(mock_log_source, Log()).Times(0);
SetMinLogLevel(BLOG_WARNING);
EXPECT_FALSE(LOG_IS_ON(INFO));
EXPECT_FALSE(DLOG_IS_ON(INFO));
EXPECT_FALSE(VLOG_IS_ON(1));
LOG(INFO) << mock_log_source.Log();
LOG_IF(INFO, false) << mock_log_source.Log();
PLOG(INFO) << mock_log_source.Log();
PLOG_IF(INFO, false) << mock_log_source.Log();
VLOG(1) << mock_log_source.Log();
VLOG_IF(1, true) << mock_log_source.Log();
VPLOG(1) << mock_log_source.Log();
VPLOG_IF(1, true) << mock_log_source.Log();
DLOG(INFO) << mock_log_source.Log();
DLOG_IF(INFO, true) << mock_log_source.Log();
DPLOG(INFO) << mock_log_source.Log();
DPLOG_IF(INFO, true) << mock_log_source.Log();
DVLOG(1) << mock_log_source.Log();
DVLOG_IF(1, true) << mock_log_source.Log();
DVPLOG(1) << mock_log_source.Log();
DVPLOG_IF(1, true) << mock_log_source.Log();
}
// Official builds have CHECKs directly call BreakDebugger.
#if !defined(OFFICIAL_BUILD)
TEST_F(LoggingTest, CheckStreamsAreLazy) {
MockLogSource mock_log_source, uncalled_mock_log_source;
EXPECT_CALL(mock_log_source, Log()).Times(8).
WillRepeatedly(Return("check message"));
EXPECT_CALL(uncalled_mock_log_source, Log()).Times(0);
SetLogAssertHandler(&LogSink);
CHECK(mock_log_source.Log()) << uncalled_mock_log_source.Log();
PCHECK(!mock_log_source.Log()) << mock_log_source.Log();
CHECK_EQ(mock_log_source.Log(), mock_log_source.Log())
<< uncalled_mock_log_source.Log();
CHECK_NE(mock_log_source.Log(), mock_log_source.Log())
<< mock_log_source.Log();
}
#endif
TEST_F(LoggingTest, DebugLoggingReleaseBehavior) {
#if !defined(NDEBUG)
int debug_only_variable = 1;
......@@ -202,21 +111,6 @@ TEST_F(LoggingTest, DebugLoggingReleaseBehavior) {
DVLOG_IF(1, debug_only_variable) << "test";
}
TEST_F(LoggingTest, DcheckStreamsAreLazy) {
MockLogSource mock_log_source;
EXPECT_CALL(mock_log_source, Log()).Times(0);
#if DCHECK_IS_ON()
DCHECK(true) << mock_log_source.Log();
DCHECK_EQ(0, 0) << mock_log_source.Log();
#else
DCHECK(mock_log_source.Log()) << mock_log_source.Log();
DPCHECK(mock_log_source.Log()) << mock_log_source.Log();
DCHECK_EQ(0, 0) << mock_log_source.Log();
DCHECK_EQ(mock_log_source.Log(), static_cast<const char*>(NULL))
<< mock_log_source.Log();
#endif
}
TEST_F(LoggingTest, Dcheck) {
#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
// Release build.
......
#/bin/bash -f
test_num=0
failed_test=""
rc=0
make -j8
test_bins="test_butil test_bvar bthread*unittest brpc*unittest"
for test_bin in $test_bins; do
test_num=$((test_num + 1))
>&2 echo "[runtest] $test_bin"
./$test_bin
rc=$?
if [[ $rc -ne 0 ]]; then
failed_test="$test_bin"
break;
fi
done
if [[ $test_num -eq 0 ]]; then
>&2 echo "[runtest] Cannot find any tests"
exit 1
fi
if [[ -z "$failed_test" ]]; then
>&2 echo "[runtest] $test_num succeeded"
elif [[ $test_num -gt 1 ]]; then
>&2 echo "[runtest] '$failed_test' failed, $((test_num-1)) succeeded"
else
>&2 echo "[runtest] '$failed_test' failed"
fi
exit $rc
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "test/scoped_locale.h"
#include "scoped_locale.h"
#include <locale.h>
......
......@@ -9,11 +9,11 @@
#include "butil/rand_util.h"
#include "butil/strings/string_number_conversions.h"
#include "butil/sys_info.h"
#include "test/multiprocess_test.h"
#include "multiprocess_test.h"
#include "butil/threading/platform_thread.h"
#include "butil/time/time.h"
#include <gtest/gtest.h>
#include "test/multiprocess_func_list.h"
#include "multiprocess_func_list.h"
#if defined(OS_MACOSX)
#include "butil/mac/scoped_nsautorelease_pool.h"
......
......@@ -5,15 +5,21 @@
#include "butil/strings/string_split.h"
#include "butil/strings/utf_string_conversions.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::ElementsAre;
namespace butil {
namespace {
void AssertElements(std::vector<std::string>& result,
const char* const expected_data[],
size_t data_size) {
ASSERT_EQ(data_size, result.size());
for (size_t i = 0; i < data_size; ++i) {
ASSERT_STREQ(expected_data[i], result[i].c_str());
}
}
#if !defined(WCHAR_T_IS_UTF16)
// Overload SplitString with a wide-char version to make it easier to
// test the string16 version with wide character literals.
......@@ -165,8 +171,8 @@ TEST_F(SplitStringIntoKeyValuePairsTest, DelimiterInValue) {
TEST(SplitStringUsingSubstrTest, EmptyString) {
std::vector<std::string> results;
SplitStringUsingSubstr(std::string(), "DELIMITER", &results);
ASSERT_EQ(1u, results.size());
EXPECT_THAT(results, ElementsAre(""));
const char* const expected[] = { "" };
AssertElements(results, expected, arraysize(expected));
}
TEST(StringUtilTest, SplitString) {
......@@ -236,8 +242,8 @@ TEST(StringUtilTest, SplitString) {
TEST(SplitStringUsingSubstrTest, StringWithNoDelimiter) {
std::vector<std::string> results;
SplitStringUsingSubstr("alongwordwithnodelimiter", "DELIMITER", &results);
ASSERT_EQ(1u, results.size());
EXPECT_THAT(results, ElementsAre("alongwordwithnodelimiter"));
const char* const expected[] = { "alongwordwithnodelimiter" };
AssertElements(results, expected, arraysize(expected));
}
TEST(SplitStringUsingSubstrTest, LeadingDelimitersSkipped) {
......@@ -246,8 +252,8 @@ TEST(SplitStringUsingSubstrTest, LeadingDelimitersSkipped) {
"DELIMITERDELIMITERDELIMITERoneDELIMITERtwoDELIMITERthree",
"DELIMITER",
&results);
ASSERT_EQ(6u, results.size());
EXPECT_THAT(results, ElementsAre("", "", "", "one", "two", "three"));
const char* const expected[] = { "", "", "", "one", "two", "three" };
AssertElements(results, expected, arraysize(expected));
}
TEST(SplitStringUsingSubstrTest, ConsecutiveDelimitersSkipped) {
......@@ -256,8 +262,9 @@ TEST(SplitStringUsingSubstrTest, ConsecutiveDelimitersSkipped) {
"unoDELIMITERDELIMITERDELIMITERdosDELIMITERtresDELIMITERDELIMITERcuatro",
"DELIMITER",
&results);
ASSERT_EQ(7u, results.size());
EXPECT_THAT(results, ElementsAre("uno", "", "", "dos", "tres", "", "cuatro"));
const char* const expected[] = { "uno", "", "", "dos", "tres", "", "cuatro" };
AssertElements(results, expected, arraysize(expected));
}
TEST(SplitStringUsingSubstrTest, TrailingDelimitersSkipped) {
......@@ -266,9 +273,8 @@ TEST(SplitStringUsingSubstrTest, TrailingDelimitersSkipped) {
"unDELIMITERdeuxDELIMITERtroisDELIMITERquatreDELIMITERDELIMITERDELIMITER",
"DELIMITER",
&results);
ASSERT_EQ(7u, results.size());
EXPECT_THAT(
results, ElementsAre("un", "deux", "trois", "quatre", "", "", ""));
const char* const expected[] = { "un", "deux", "trois", "quatre", "", "", "" };
AssertElements(results, expected, arraysize(expected));
}
TEST(StringSplitTest, StringSplitDontTrim) {
......
......@@ -12,11 +12,8 @@
#include "butil/basictypes.h"
#include "butil/strings/string16.h"
#include "butil/strings/utf_string_conversions.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::ElementsAre;
namespace butil {
static const struct trim_case {
......
......@@ -8,7 +8,7 @@
#include "butil/strings/string_piece.h"
#include "butil/strings/sys_string_conversions.h"
#include "butil/strings/utf_string_conversions.h"
#include "test/scoped_locale.h"
#include "scoped_locale.h"
#include <gtest/gtest.h>
#ifdef WCHAR_T_IS_UTF32
......
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "test/test_switches.h"
#include "test_switches.h"
// Time (in milliseconds) that the tests should wait before timing out.
// TODO(phajdan.jr): Clean up the switch names.
......
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "butil/nix/xdg_util.h"
#include "butil/environment.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::Return;
using ::testing::SetArgumentPointee;
using ::testing::StrEq;
namespace butil {
namespace nix {
namespace {
class MockEnvironment : public Environment {
public:
MOCK_METHOD2(GetVar, bool(const char*, std::string* result));
MOCK_METHOD2(SetVar, bool(const char*, const std::string& new_value));
MOCK_METHOD1(UnSetVar, bool(const char*));
};
const char* kGnome = "gnome";
const char* kKDE4 = "kde4";
const char* kKDE = "kde";
const char* kXFCE = "xfce";
} // namespace
TEST(XDGUtilTest, GetDesktopEnvironmentGnome) {
MockEnvironment getter;
EXPECT_CALL(getter, GetVar(_, _)).WillRepeatedly(Return(false));
EXPECT_CALL(getter, GetVar(StrEq("DESKTOP_SESSION"), _))
.WillOnce(DoAll(SetArgumentPointee<1>(kGnome), Return(true)));
EXPECT_EQ(DESKTOP_ENVIRONMENT_GNOME,
GetDesktopEnvironment(&getter));
}
TEST(XDGUtilTest, GetDesktopEnvironmentKDE4) {
MockEnvironment getter;
EXPECT_CALL(getter, GetVar(_, _)).WillRepeatedly(Return(false));
EXPECT_CALL(getter, GetVar(StrEq("DESKTOP_SESSION"), _))
.WillOnce(DoAll(SetArgumentPointee<1>(kKDE4), Return(true)));
EXPECT_EQ(DESKTOP_ENVIRONMENT_KDE4,
GetDesktopEnvironment(&getter));
}
TEST(XDGUtilTest, GetDesktopEnvironmentKDE3) {
MockEnvironment getter;
EXPECT_CALL(getter, GetVar(_, _)).WillRepeatedly(Return(false));
EXPECT_CALL(getter, GetVar(StrEq("DESKTOP_SESSION"), _))
.WillOnce(DoAll(SetArgumentPointee<1>(kKDE), Return(true)));
EXPECT_EQ(DESKTOP_ENVIRONMENT_KDE3,
GetDesktopEnvironment(&getter));
}
TEST(XDGUtilTest, GetDesktopEnvironmentXFCE) {
MockEnvironment getter;
EXPECT_CALL(getter, GetVar(_, _)).WillRepeatedly(Return(false));
EXPECT_CALL(getter, GetVar(StrEq("DESKTOP_SESSION"), _))
.WillOnce(DoAll(SetArgumentPointee<1>(kXFCE), Return(true)));
EXPECT_EQ(DESKTOP_ENVIRONMENT_XFCE,
GetDesktopEnvironment(&getter));
}
} // namespace nix
} // namespace butil
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