【问题标题】:How can I test through CTest if an SQLite table exists and get the response?如果存在 SQLite 表并获得响应,我如何通过 CTest 进行测试?
【发布时间】:2017-06-05 22:21:06
【问题描述】:

这是我的主要代码:

   sqlite3 *db;
   sqlite3_stmt * stmt;
   string sqlstatement = "CREATE TABLE IF NOT EXISTS accounts (account_id integer primary key, balance integer not null)";

   if (sqlite3_open("test.db", &db) == SQLITE_OK)
   {
    sqlite3_prepare( db, sqlstatement.c_str(), -1, &stmt, NULL );//preparing the statement
    sqlite3_step( stmt );//executing the statement
   }

   sqlite3_finalize(stmt);
   sqlite3_close(db);

   return 0;

这是我的 CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.12.2)
enable_testing()
set(TEST_EXE_NAME tests)
add_executable(test main.cpp)
add_executable(${TEST_EXE_NAME} tests.cpp)
add_test(NAME "tests" COMMAND ${TEST_EXE_NAME})
target_link_libraries(tests sqlite3)

我怎样才能有另一个 C++ 测试文件 test.cpp 来测试 main 中提到的表是否已成功创建?

我的测试文件有以下代码:

string sql = ".tables";
sqlite3 *db;
sqlite3_stmt * stmt;

int rc=0;
if (sqlite3_open("test.db", &db) == SQLITE_OK) {
    rc = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL);
    rc = sqlite3_step(stmt);

}
return 0;

如何从“.tables”获得响应?

【问题讨论】:

    标签: c++ sqlite cmake ctest


    【解决方案1】:
    sqlite3* database;
    sqlite3_open("test.db", &database);
    sqlite3_stmt *statement;
    if(sqlite3_prepare_v2(database, "select * from accounts;", -1, &statement, 0) == SQLITE_OK)
    {
        return 0;
    }
    else {
        return -1;
    
    }
    

    【讨论】:

      【解决方案2】:

      使用 sqlite,您可以使用编译指示 .table 列出所有现有表。因此,您可以在 c 中使用

      string sqlstatement = ".table";
      

      并检查结果。

      或者您可以使用 sqlite3 命令行调用来实现

      sqlite3 test.db ".table"
      

      并在 c 或 bash 或 ctest 中检查结果

      bash 示例

      sqlite3 test.db ".table" | grep accounts
      if [[ "$?" != "0" ]]; then echo "Rescue the world"; fi 
      

      从 ctest 使用它:

      1. 将其放入脚本文件中,例如checkdb.sh

        /usr/local/bin/sqlite3 /path/to/test.db ".table" | grep accounts > /dev/null

      2. 使脚本可执行

        chmod a+x checkdb.sh

      3. 将以下内容添加到您的 CMakeLists.txt

        add_test(NAME check_database COMMAND "checkdb.sh")

      【讨论】:

      • 能否请您在 CTest 中给出示例,因为这是我最初要求的问题?谢谢!!
      • 由于 sqlite3 的行为,无法从 ctest 中调用它,因为它不再退出。但是可以使用脚本。
      猜你喜欢
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 2011-03-11
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多