leveldb分析——單元測試工具

leveldb中本身實現了一個簡單的單元測試工具,下面是一個對CRC類測試的一個例子工具

class CRC { }; TEST(CRC, Extend) { ASSERT_EQ(Value("hello world", 11), Extend(Value("hello ", 6), "world", 5)); }

 int main(int argc, char** argv) {
   return leveldb::test::RunAllTests();
 }單元測試

TEST() 和RunAllTests()空間是怎麼實現的呢?咱們來看看源碼:測試

#define TEST(base,name)                                                 \
class TCONCAT(_Test_,name) : public base { \ public: \ void _Run(); \ static void _RunIt() { \ TCONCAT(_Test_,name) t; \ t._Run(); \ } \ }; \ bool TCONCAT(_Test_ignored_,name) = \ ::leveldb::test::RegisterTest(#base, #name, &TCONCAT(_Test_,name)::_RunIt); \ void TCONCAT(_Test_,name)::_Run()

 對上面的測試程序實際展開後以下:spa

class _Test_Extend : public CRC { public: void _Run(); static void _RunIt(){ _Test_Extend t; t._Run(); } }; bool _Test_ignored_Extend = ::leveldb::test::Register("CRC","Extend",&_Test_Extend::_RunIt()); void _Test_Extend::Run(){ ASSERT_EQ(Value("hello world", 11), Extend(Value("hello ", 6), "world", 5)); }

註冊過程:code

struct Test { const char* base; const char* name; void (*func)(); }; std::vector<Test>* tests; } bool RegisterTest(const char* base, const char* name, void (*func)()) { if (tests == NULL) { tests = new std::vector<Test>; } Test t; t.base = base; t.name = name; t.func = func; tests->push_back(t); return true; }

 運行過程:blog

int RunAllTests() { int num = 0; if (tests != NULL) { for (int i = 0; i < tests->size(); i++) { const Test& t = (*tests)[i]; } fprintf(stderr, "==== Test %s.%s\n", t.base, t.name); (*t.func)(); ++num; } } fprintf(stderr, "==== PASSED %d tests\n", num); return 0; }
相關文章
相關標籤/搜索