跳到主要內容

Breaking dependency by templates in C++

There are many different ways to break dependencies when doing unit testing in C++. We can use approaches described in the book, including constructor injection, setter injection, extract and override, and...yes, the factory design pattern. They work well in some cases so that we should know the pros and cons of every tricks above. However, they have some common shortcomings:
  • unnecessary run-time indirection by using inheritance (it is getting worse when critical execution path is on the objects)
  • unnecessary interfaces should be added and used. (those interfaces are merely for unit test convenience, not so meaningful in production code)
Those traditional tricks used in unit test are based on common OO features. If we focus on C++, can we solve these two problems by different thinking? 

I gave template a try by writing a simple word count program. Before we go on, you can clone it to play. The main class (mwc) is a class template with a template parameter contains two dependencies will be used in it.

  1.    /* abstract dependency policy for mwc */
  2.    template<typename FL_, typename INI_>
  3.       struct mwc_dep {
  4.          typedef FL_            FL;
  5.          typedef INI_           INI;
  6.       };
  7.    /* production dependency to be used in mwc */
  8.    typedef mwc_dep<product_file_loader, product_ini_mgr> product_mwc_dep;
  9.    /* mwc, our CUT, have some dependency needed to be broken by abstraction tricks */
  10.    template <typename DEP = product_mwc_dep>
  11.       class mwc {
  12.          typedef typename DEP::FL               FL;
  13.          typedef typename DEP::INI              INI;

The production code (production_mwc_dep) would do every practical work and it is the default template parameter of mwc. We can use it as following:

  1. void ProductMWCTester::MWC_QueryValidWord_ReturnCount()
  2. {
  3.    MC::mwc<> wc;
  4.    wc.load("./data");
  5.    CPPUNIT_ASSERT_EQUAL(2, wc.query("ooooo"));
  6. }

Then I do the unit test by writing some mock classes. Here comes the mock part:

  1. class mock_file_loader0: public MC::file_loader {
  2.    public:
  3.       void content(const std::string &fn, std::string &source)
  4.       {
  5.          source = "";
  6.          source += "ooooo\nI\nam who ooooo\nwho ope\nThere\n";
  7.       }
  8. };
  9. class mock_ini_mgr0: public MC::ini_mgr {
  10.    public:
  11.       void open(const char *ini_file)
  12.       {
  13.          exclude_words_.insert("The");
  14.          exclude_words_.insert("I");
  15.          exclude_words_.insert("There");
  16.       }
  17.       uint32_t min_word_length() const { return 2; }
  18.       const std::set<std::string> &exclude_words() const { return exclude_words_; }
  19.       bool enable_case_sensitive() const { return true; }
  20.    private:
  21.       std::set<std::string> exclude_words_;
  22. };
  23. void MockMWCTester::MWC_QueryValidWord_ReturnCount()
  24. {
  25.    typedef MC::mwc_dep<mock_file_loader0, mock_ini_mgr0> mock_mwc_dep;
  26.    MC::mwc<mock_mwc_dep> wc;
  27.    wc.load("./data");
  28.    CPPUNIT_ASSERT_EQUAL(2, wc.query("ooooo"));
  29. }

Yes!! By using templates, we can really solve the problems we mentioned. However, experienced programmers might ask: how can I create mock classes conveniently just as gmock? The answer is: No, we don't.

Currently I can't find any mock framework which can mock "type". They all mock objects. If we want to mock types and then use the mock types as template parameters(which should be types), we must do it on our own. For now, I would like to try this method for a while to get more experience when using templates as dependency breaking tricks. And might try to create a mock framework to mock type if I can do it. Just wait and see. :-)

留言

這個網誌中的熱門文章

誰在呼叫我?不同的backtrace實作說明好文章

今天下班前一個同事問到:如何在Linux kernel的function中主動印出backtrace以方便除錯? 寫過kernel module的人都知道,基本上就是用dump_stack()之類的function就可以作到了。但是dump_stack()的功能是如何作到的呢?概念上其實並不難,慣用手法就是先觀察stack在function call時的變化(一般OS或計組教科書都有很好的說明,如果不想翻書,可以參考 這篇 ),然後將對應的return address一層一層找出來後,再將對應的function名稱印出即可(透過執行檔中的section去讀取函式名稱即可,所以要將KALLSYM選項打開)。在userspace的實作可參考Jserv介紹過的 whocallme 或對岸好手實作過的 backtrace() ,都是針對x86架構的很好說明文章。 不過從前面兩篇文章可以知道,只要知道編譯器的calling convention,就可以實作出backtrace,所以是否GCC有提供現成的機制呢?Yes, that is what __builtin_return_address() for!! 可以參考這篇 文章 。該篇文章還提到了其他可以拿來實作功能更齊全的backtrace的 程式庫 ,在了解了運作原理後,用那些東西還蠻方便的。 OK,那Linux kernel是怎麼做的呢?就是用頭兩篇文章的方式啦~ 每個不同的CPU架構各自手工實作一份dump_stack()。 為啥不用GCC的機制?畢竟...嗯,我猜想,除了backtrace以外,開發者還會想看其他register的值,還有一些有的沒的,所以光是GCC提供的介面是很難印出全部所要的資訊,與其用半套GCC的機制,不如全都自己來~ arm的實作 大致上長這樣,可以看到基本上就只是透過迭代fp, lr, pc來完成: 352 void unwind_backtrace (struct pt_regs * regs , struct task_struct *tsk) 353 { 354 struct stackframe frame ; 355 register unsigned long current_sp asm ( "...

淺讀Linux root file system初始化流程

在Unix的世界中,file system佔據一個極重要的抽象化地位。其中,/ 所代表的rootfs更是所有後續新增file system所必須依賴前提條件。以Linux為例,黑客 Jserv 就曾經詳細說明過 initramfs的背後設計考量 。本篇文章不再重複背景知識,主要將追蹤rootfs初始化的流程作點整理,免得自己日後忘記。 :-) file system與特定CPU架構無關,所以我觀察的起點從init/main.c的start_kernel()開始,這是Linux作完基本CPU初始化後首先跳進的C function(我閱讀的版本為 3.12 )。跟root file system有關的流程羅列如下: start_kernel()         -> vfs_caches_init_early()         -> vfs_caches_init()                 -> mnt_init()                         -> init_rootfs()                         -> init_mount_tree()         -> rest_init()                 -> kernel_thread(kernel_init,...) 其中比較重要的是mnt_int()中的init_rootfs()與init_mout_tree()。init_rootfs()實作如下: int __init init_root...

中文試譯:Load-time relocation of shared libraries

作者: eliben 原文連結: http://eli.thegreenplace.net/2011/08/25/load-time-relocation-of-shared-libraries/ 共享庫的載入時重定位 這篇文章的目的在解釋現代作業系統如何讓共享庫在載入時的連結動作發生。我們聚焦在32位元的x86 Linux上頭,但相同的原則在其他的作業系統與CPUs上一樣適用。 要注意的是,共享庫有許多不同的名字 - 共享庫(shared libraries),共享物件( shared objects),動態共享物件( dynamic shared objects (DSOs)),動態連結庫( dynamically linked libraries(如果你習慣的是Windows的環境,就知道這是所謂的DLL))。為了一致性,我在整篇文章中會使用"共享庫"這個字眼。 載入可執行檔 如同其他支援虛擬記憶體的作業系統,Linux將可執行檔載入到一個固定的記憶體位址。如果我們檢視任意一個可執行檔的ELF header,我們將可發現一個Entry point的位址: $ readelf -h /usr/bin/uptime ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 [...] some header fields Entry point address: 0x8048470 [...] some header fields 這是由linker所放置的,可告訴作業系統要從何處開始執行此執行檔[1]。如果我們用GDB載入程式並觀察0x8048470的位址,我們將可看到.text segment的第一個被執行的指令。 這代表的是,當linker連結可執行檔時,會把全部的內部符號引用的位址都確定下來(function以及data),確定它們的固定的、最終的位址。Linker本身會對自己進行一些relocation[2],但最終的結果不會有任何的relocation。 講啥啊?注意,我在上段文中特別強...