代码之家  ›  专栏  ›  技术社区  ›  Robert S. Barnes Antoni

助推、测试和分叉

  •  1
  • Robert S. Barnes Antoni  · 技术社区  · 14 年前

    我正在使用Boost.Test进行单元测试,目前正在各个线程中运行各种模拟服务器,这些线程是从每个测试中启动的。为了更准确地测试我的代码,模拟服务器应该在不同的进程中。

    MY_TEST()
    if (fork() == 0) {
        runMockServer();  // responds to test requests or times out, then returns
        exit(0);
    }
    // Connect to MockServ and Run actual test here
    END_TEST()
    

    但我担心这会破坏测试框架。

    这安全吗?有人做过这样的事吗?

    2 回复  |  直到 14 年前
        1
  •  3
  •   Sam Miller    14 年前

    这听起来不像是对你想要达到的目标进行单元测试。虽然我不明白为什么不安全。如果MockServ还没有准备好,您可能有一个单元测试连接到MockServ的竞争条件,但这是很容易解决的。

    我从来没有直接做过这样的事情,但是我已经为fork/exec子进程的库编写了单元测试,而且工作得非常完美。

        2
  •  3
  •   mandrake    12 年前

    但是,要克服的一个障碍是在不使用boost断言宏的情况下从子进程发出错误信号。如果例如。 BOOST_REQUIRE 它将提前中止测试,任何后续的测试都将在父进程和子进程中执行。我最终使用进程退出代码向等待的父进程发出错误信号。但是,不要使用 exit() 就像你所做的那样 atexit() 指示子进程中错误的钩子,即使没有。使用 _exit()

    我用于测试的设置是这样的。

    BOOST_AUTO_TEST_CASE(Foo)
    {
      int pid = fork();
      BOOST_REQUIRE( pid >= 0 );
      if( pid  == 0 ) // child
      {
        // Don't use Boost assert macros here
        // signal errors with exit code
    
        // Don't use exit() since Boost test hooks 
        // and signal error in that case, use _exit instead.
        int rv = something(); 
        _exit(rv);
      }else{ // parent
        // OK to use boost assert macros in parent
        BOOST_REQUIRE_EQUAL(0,0);
        // Lastly wait for the child to exit
        int childRv;
        wait(&childRv);
        BOOST_CHECK_EQUAL(childRv, 0);
      }
    
    }