【问题标题】:Using pipes in Boost unit tests在 Boost 单元测试中使用管道
【发布时间】:2014-05-19 08:41:54
【问题描述】:

我正在尝试为我的服务器编写 Boost 单元测试。 我想启动我的服务器 - start() 在线程中启动服务器 - 打开客户端,连接它并尝试下载文件。

我是这样做的:

tftp_server* my_test_server;

BOOST_AUTO_TEST_SUITE (tftptest) // name of the test suite is tftptest

BOOST_AUTO_TEST_CASE (test1)
{
    my_test_server = new tftp_server(69);
    my_test_server->start();

    FILE *in;
    char buff[512];


    if(!(in = popen("tftp", "w"))){
        exit(1);
    }

    fputs ( "connect xx.xx.xx.xx\n", in );
    fputs ( "mode binary\n", in );
    fputs ( "mode\n", in );
    fputs ( "get truc.txt\n", in );

    while(fgets(buff, sizeof(buff), in)!=NULL)
        printf("%s", buff);

    sleep(10);

    BOOST_CHECK(true);
}

1) 创建和启动服务器,

2) 使用系统 TFTP 客户端(我在 OSX 上),

3) 等待 10 秒。

不起作用:它只在测试完成后执行客户端。

Running 1 test case...
Server started on port 69
Server running.

*** No errors detected
$ Using octet mode to transfer files.
Transfer timed out.

知道如何解决我的问题吗?

谢谢!

编辑

void tftp_server::start()
{
    LOG_INFO("Server running.", 0);
    boost::thread bt(boost::bind(&boost::asio::io_service::run, &_io_service));
}

【问题讨论】:

  • 您的客户在哪里?你如何使用线程? my_test_server->start(); 是否启动线程?
  • 是的,它启动了一个线程(我已经用实现更新了我的问题)。客户端是OSX系统客户端(我一般在终端中使用)。
  • 好的,你在哪里启动客户端?我会说如果您以相同的测试方法启动客户端,它应该可以工作。
  • 我正在以相同的测试方法使用 popen 启动客户端(如您所见)。
  • 不要在测试框架中使用exit。请改用BOOST_FAIL。此外,似乎缺少一些清理:销毁 ftp 服务器,最好通过堆栈上的构造,或者如果需要通过智能指针。另外,你好像没有关闭管道。

标签: c++ unit-testing boost


【解决方案1】:

我添加了关闭,它的工作原理。 感谢 Arne Mertz。

if(!(in = popen("tftp", "w"))){
    exit(1);
}

//...

while(fgets(buff, sizeof(buff), in)!=NULL)
    printf("%s", buff);

pclose(in);

【讨论】:

  • 我猜要么服务器正在等待不关闭管道就不会发生的 EOF,或者有一些由关闭触发的刷新(我不知道管道) .您应该考虑为此类(智能指针、fstream、...)使用/编写 RAII 类,因为它是 C++ 的优势之一。
猜你喜欢
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 2020-08-04
  • 1970-01-01
相关资源
最近更新 更多