title: Mocking system calls - is there better way?
body: <p>We are now introducing unit tests in our company and thinking about best way of mocking system calls.</p>
  
  <p>Consider the following code</p>
  
  <pre><code>    int fd = open(path, O_RDONLY);
      if (fd &lt; 0) {
          LOG.error() &lt;&lt; "cannot load plugin " &lt;&lt; path &lt;&lt; std::endl;
          return ERROR(ERROR_OPENING_PLUGING);
      }
      // do other stuff
  </code></pre>
  
  <p>Obviously, we need to mock system call to <strong>open</strong></p>
  
  <p>I have found following ways to do so:</p>
  
  <ol>
  <li><p>Correct - in the terms of design but ugly way. Create interface and impl</p>
  
  <pre><code>class ISystem
  {
  public:
      typedef std::auto_ptr&lt;ISystem&gt; Ptr;
  
      ISystem() {};
      virtual ~ISystem() {};
  
      virtual int open(const char* file, int path) = 0;
  };
  
  class System : public ISystem
  {
  public:
      System() {};
      virtual ~System() {};
  
      virtual int open(const char* file, int path);
  
      static ISystem::Ptr Get();
  };
  </code></pre></li>
  </ol>
  
  <p>and use it</p>
  
  <pre><code>    Common::Error dlopen_signed(ISystem::Ptr&amp; system, const char* path, int flags, void*&amp; ret)
      {
      int fd = system-&gt;open(path, O_RDONLY);
      if (fd &lt; 0) {
          LOG.error() &lt;&lt; "cannot load plugin " &lt;&lt; path &lt;&lt; std::endl;
          return ERROR(ERROR_OPENING_PLUGING);
      }
      char fd_path[32];
  </code></pre>
  
  <p>I dont like it because every function will need to have one more argument - ISystem::Ptr&amp; system, that will be the same for all production code.</p>
  
  <p>Also, not sure about speed (this involves extra layers for basic system calls that must be really fast)</p>
  
  <p>2) Use a link seam
  Linker is designed so that it prefer your versions of functions than system ones. </p>
  
  <p>But this does not work for some system calls, for example open (not sure about the reason), and this solution is a little bit hackish. </p>
  
  <p>3) use --wrap compiler functionality</p>
  
  <p>--wrap symbol
  Use a wrapper function for symbol. Any undefined reference to symbol will be resolved to __wrap_symbol. Any undefined reference to __real_symbol will be resolved to symbol. This can be used to provide a wrapper for a system function. The wrapper function should be called __wrap_symbol. If it wishes to call the system function, it should call __real_symbol. Here is a trivial example:</p>
  
  <pre><code>void *
  __wrap_malloc (int c)
  {
    printf ("malloc called with %ld\n", c);
    return __real_malloc (c);
  } 
  </code></pre>
  
  <p>This solution is nice but does not work for all compilers I guess.</p>
  
  <p>The question is - <strong>which one are you using on your projects?</strong></p>