Boost.Spirit 的单元测试

发布于 2024-07-12 04:10:53 字数 748 浏览 8 评论 0原文

我是 Boost.Spirit 和 Boost.Test 的新手,我想知道您如何验证语法的正确性。 下面是我目前的做法的简化版本,我非常确定有更好的方法:

每个测试用例都有一对两个字符串,其中包含要解析的文本和由分号分隔的预期结果。

解析函数执行实际的解析并返回一个应该等于预期结果的字符串。

 std::string parse(std::string const & line) {
  std::string name;
  int hours;

  rule<> top_rule = ... ; // rule assignes values to 'name' and 'hours'

  parse_info<> info = parse(line.c_str(), top_rule);

  if(info.full) {
    std::stringstream sstr;
    sstr << name << ";" << hours;

    return sstr.str();
  }

  return "parser failed.";
}

BOOST_AUTO_TEST_SUITE( TestSuite )

BOOST_AUTO_TEST_CASE( TestCase ) {
  BOOST_CHECK_EQUAL(parse("Tom worked for 10 hours."), "Tom;10");
}

BOOST_AUTO_TEST_SUITE_END()

I'm new to Boost.Spirit and Boost.Test and I would like to know how you verify the correctness of your grammars. Below is a simplified version of how I do it at the moment and I'm pretty sure that there's a better way:

Each test case hase a pair of two strings containing the text to parse and the expected result delimited by semicolons.

The parse functions does the actual parsing and returns a string which should be equal to the expected result.

 std::string parse(std::string const & line) {
  std::string name;
  int hours;

  rule<> top_rule = ... ; // rule assignes values to 'name' and 'hours'

  parse_info<> info = parse(line.c_str(), top_rule);

  if(info.full) {
    std::stringstream sstr;
    sstr << name << ";" << hours;

    return sstr.str();
  }

  return "parser failed.";
}

BOOST_AUTO_TEST_SUITE( TestSuite )

BOOST_AUTO_TEST_CASE( TestCase ) {
  BOOST_CHECK_EQUAL(parse("Tom worked for 10 hours."), "Tom;10");
}

BOOST_AUTO_TEST_SUITE_END()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悍妇囚夫 2024-07-19 04:10:53

总的来说,你的方法对我来说似乎很好。 我可能会将测试类分组到具有描述性名称的函数中,例如 TestInvalidGrammar、TestErrorHandling、TestNestedGrammar 等,并从 main 调用这些函数。

我确信您已阅读文档,但请查看 示例(如果有帮助)。

In general, your approach seems fine to me. I would probably group class of tests into function with descriptive names, e.g. TestInvalidGrammar, TestErrorHandling, TestNestedGrammar etc. and have those called from the main.

I am sure you have read documentation but take a look at examples if it helps.

骄傲 2024-07-19 04:10:53

在这里你可以看到他们(boostspirit作者)如何测试他们自己的解析器:http://svn.boost.org/svn/boost/trunk/libs/spirit/test/qi/grammar.cpp 。 对于 qi 的每个部分,您可以在这里找到一个 C++ 文件: http ://svn.boost.org/svn/boost/trunk/libs/spirit/test/qi/

Here you can see how they (the boost spirit authors) test their own parsers: http://svn.boost.org/svn/boost/trunk/libs/spirit/test/qi/grammar.cpp . For each part of qi you can find a C++ file here: http://svn.boost.org/svn/boost/trunk/libs/spirit/test/qi/.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文