0

This is my main code:

   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;

and this is my 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)

How can I have another C++ test file, test.cpp, which tests if the table mentioned in main was successfully created?

My test file has the following code:

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;

How can I get the response from ".tables"?

2 Answers2

0

With sqlite you can list all existing tables with the pragma .table. Thus you can do it in c with

string sqlstatement = ".table";

and check the result.

Or you can do it as a sqlite3 command line call with

sqlite3 test.db ".table"

and check the result in c or bash or ctest

Example for bash

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

To use it from ctest:

  1. Put it into a scriptfile, e.g. checkdb.sh

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

  2. Make the script executable

    chmod a+x checkdb.sh

  3. Add following to your CMakeLists.txt

    add_test(NAME check_database COMMAND "checkdb.sh")

Th. Thielemann
  • 2,592
  • 1
  • 23
  • 38
  • Could you please give the example in CTest, as that is what my question originally requested? Thank you!! –  Jan 23 '17 at 13:58
  • Due to sqlite3's behaviour it is not possible to call it from within ctest because it does not quit anymore. But a script can be used. – Th. Thielemann Jan 24 '17 at 10:05
0
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;

}