Merge pull request #1056 from theopolis/fast_tests

Fast tests
This commit is contained in:
Teddy Reed 2015-04-27 10:49:51 -07:00
commit 3f36241448
62 changed files with 810 additions and 507 deletions

View File

@ -13,20 +13,6 @@ macro(SET_OSQUERY_COMPILE TARGET)
endif()
endmacro(SET_OSQUERY_COMPILE)
macro(ADD_OSQUERY_TEST IS_CORE TEST_NAME SOURCE)
if(NOT DEFINED ENV{SKIP_TESTS} AND (${IS_CORE} OR NOT OSQUERY_BUILD_SDK_ONLY))
add_executable(${TEST_NAME} ${SOURCE})
TARGET_OSQUERY_LINK_WHOLE(${TEST_NAME} libosquery)
set(TEST_LINK_ADDITIONAL ${ARGN})
if(NOT ${IS_CORE})
TARGET_OSQUERY_LINK_WHOLE(${TEST_NAME} libosquery_additional)
endif()
target_link_libraries(${TEST_NAME} gtest libosquery_testing)
SET_OSQUERY_COMPILE(${TEST_NAME} "${CXX_COMPILE_FLAGS} -DGTEST_HAS_TR1_TUPLE=0")
add_test(${TEST_NAME} ${TEST_NAME})
endif()
endmacro(ADD_OSQUERY_TEST)
macro(ADD_OSQUERY_PYTHON_TEST TEST_NAME SOURCE)
add_test(NAME python_${TEST_NAME}
COMMAND python "${CMAKE_SOURCE_DIR}/tools/tests/${SOURCE}" --build "${CMAKE_BINARY_DIR}"
@ -59,6 +45,25 @@ macro(ADD_OSQUERY_LINK_INTERNAL LINK LINK_PATHS LINK_SET)
set(${LINK_SET} "${${LINK_SET}}" PARENT_SCOPE)
endmacro(ADD_OSQUERY_LINK_INTERNAL)
macro(ADD_OSQUERY_TEST IS_CORE)
if(NOT DEFINED ENV{SKIP_TESTS} AND (${IS_CORE} OR NOT OSQUERY_BUILD_SDK_ONLY))
if(${IS_CORE})
list(APPEND OSQUERY_TESTS ${ARGN})
set(OSQUERY_TESTS ${OSQUERY_TESTS} PARENT_SCOPE)
else()
list(APPEND OSQUERY_ADDITIONAL_TESTS ${ARGN})
set(OSQUERY_ADDITIONAL_TESTS ${OSQUERY_ADDITIONAL_TESTS} PARENT_SCOPE)
endif()
endif()
endmacro(ADD_OSQUERY_TEST)
macro(ADD_OSQUERY_TABLE_TEST)
if(NOT DEFINED ENV{SKIP_TESTS} AND NOT OSQUERY_BUILD_SDK_ONLY)
list(APPEND OSQUERY_TABLES_TESTS ${ARGN})
set(OSQUERY_TABLES_TESTS ${OSQUERY_TABLES_TESTS} PARENT_SCOPE)
endif()
endmacro(ADD_OSQUERY_TABLE_TEST)
# Core/non core lists of target source files.
macro(ADD_OSQUERY_LIBRARY IS_CORE TARGET)
if(${IS_CORE} OR NOT OSQUERY_BUILD_SDK_ONLY)

View File

@ -11,15 +11,11 @@
#pragma once
#include <string>
#include <vector>
#include <glog/logging.h>
#include <osquery/database/results.h>
#include <osquery/flags.h>
#include <osquery/registry.h>
namespace osquery {
/**
* @brief Superclass for enrollment plugins
*
@ -54,4 +50,4 @@ class EnrollmentPlugin : public Plugin {
* provides a helper member for transforming PluginRequests to strings.
*/
CREATE_LAZY_REGISTRY(EnrollmentPlugin, "enrollment");
}
}

View File

@ -1,13 +1,13 @@
# Fill this in with objects and (linker/linker options) for libosquery.
# osquery core source files included with the SDK (libosquery).
set(OSQUERY_SOURCES "")
set(OSQUERY_LINKS "")
# Fill this in in with non-core links and linker options (for plugins).
set(OSQUERY_TESTS "")
# osquery core additional sources files not included with SDK (libosquery_additional).
set(OSQUERY_ADDITIONAL_SOURCES "")
set(OSQUERY_ADDITIONAL_LINKS "")
set(Boost_USE_STATIC_LIBS ON)
set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "")
set(OSQUERY_ADDITIONAL_TESTS "")
set(OSQUERY_TABLES_TESTS "")
# The core set of osquery libraries most discovered with find_package.
set(OSQUERY_LIBS
@ -27,10 +27,10 @@ set(OSQUERY_LIBS
z
)
# Add default linking details
# Add default linking details (the first argument means SDK + core).
ADD_OSQUERY_LINK(TRUE "-rdynamic")
# The platform-specific core libraries.
# The platform-specific SDK + core libraries.
if(APPLE)
ADD_OSQUERY_LINK(TRUE "-mmacosx-version-min=${APPLE_MIN_ABI}")
ADD_OSQUERY_LINK(TRUE "boost_thread-mt")
@ -67,29 +67,26 @@ add_subdirectory(remote)
add_subdirectory(sql)
add_subdirectory(tables)
# Finally amalgamate the tables needed to compile.
# Amalgamate the utility tables needed to compile.
GENERATE_UTILITIES("${CMAKE_SOURCE_DIR}/osquery/tables")
AMALGAMATE("${CMAKE_SOURCE_DIR}" "utils" AMALGAMATION_UTILS)
ADD_OSQUERY_LIBRARY(TRUE osquery_utils_amalgamation ${AMALGAMATION_UTILS})
ADD_OSQUERY_LIBRARY(TRUE osquery_amalgamation ${AMALGAMATION_UTILS})
# Bubble the subdirectory (component) sources and links for this build.
list(APPEND OSQUERY_OBJECTS ${OSQUERY_SOURCES})
list(APPEND OSQUERY_LIBS ${OSQUERY_LINKS})
# Create the static libosquery (everything but non-util tables).
# Create the static libosquery (everything but non-utility tables).
set(CMAKE_MACOSX_RPATH 0)
add_library(libosquery STATIC main/lib.cpp ${OSQUERY_OBJECTS})
target_link_libraries(libosquery ${OSQUERY_LIBS})
set_target_properties(libosquery PROPERTIES OUTPUT_NAME osquery)
# Also create a static testing library (mostly testing utilities).
add_library(libosquery_testing STATIC core/test_util.cpp)
add_dependencies(libosquery_testing libosquery)
set_target_properties(libosquery_testing PROPERTIES OUTPUT_NAME osquery_testing)
set_target_properties(libosquery_testing PROPERTIES COMPILE_FLAGS "${CXX_COMPILE_FLAGS}")
add_custom_target(BUILD_LIB_SUCCESS ALL
# A friendly echo printed after the library is built.
add_custom_target(osquery_library ALL
DEPENDS libosquery
COMMAND ${CMAKE_COMMAND} -E cmake_echo_color --cyan --bold "Built libosquery: ${CMAKE_BINARY_DIR}"
COMMAND ${CMAKE_COMMAND} -E cmake_echo_color --cyan --bold
"Built libosquery: ${CMAKE_BINARY_DIR}"
)
# make devel (implies install)
@ -101,12 +98,12 @@ add_custom_target(devel
)
add_dependencies(devel libosquery)
# Generate the osquery additional tables (the non-util).
GENERATE_TABLES("${CMAKE_SOURCE_DIR}/osquery/tables")
AMALGAMATE("${CMAKE_SOURCE_DIR}" "additional" AMALGAMATION)
ADD_OSQUERY_LIBRARY(FALSE osquery_amalgamation ${AMALGAMATION})
if(NOT OSQUERY_BUILD_SDK_ONLY)
# Generate the osquery additional tables (the non-util).
GENERATE_TABLES("${CMAKE_SOURCE_DIR}/osquery/tables")
AMALGAMATE("${CMAKE_SOURCE_DIR}" "additional" AMALGAMATION)
ADD_OSQUERY_LIBRARY(FALSE osquery_additional_amalgamation ${AMALGAMATION})
# Create the static libosquery_additional.
add_library(libosquery_additional STATIC ${OSQUERY_ADDITIONAL_SOURCES})
target_link_libraries(libosquery_additional ${OSQUERY_ADDITIONAL_LINKS})
@ -115,22 +112,15 @@ if(NOT OSQUERY_BUILD_SDK_ONLY)
add_executable(shell devtools/shell.cpp main/shell.cpp)
TARGET_OSQUERY_LINK_WHOLE(shell libosquery)
TARGET_OSQUERY_LINK_WHOLE(shell libosquery_additional)
set_target_properties(shell PROPERTIES COMPILE_FLAGS "${CXX_COMPILE_FLAGS}")
SET_OSQUERY_COMPILE(shell "${CXX_COMPILE_FLAGS}")
set_target_properties(shell PROPERTIES OUTPUT_NAME osqueryi)
add_executable(daemon main/daemon.cpp)
TARGET_OSQUERY_LINK_WHOLE(daemon libosquery)
TARGET_OSQUERY_LINK_WHOLE(daemon libosquery_additional)
set_target_properties(daemon PROPERTIES COMPILE_FLAGS "${CXX_COMPILE_FLAGS}")
SET_OSQUERY_COMPILE(daemon "${CXX_COMPILE_FLAGS}")
set_target_properties(daemon PROPERTIES OUTPUT_NAME osqueryd)
if(NOT DEFINED ENV{SKIP_TESTS})
add_executable(run main/run.cpp)
TARGET_OSQUERY_LINK_WHOLE(run libosquery)
TARGET_OSQUERY_LINK_WHOLE(run libosquery_additional)
set_target_properties(run PROPERTIES COMPILE_FLAGS "${CXX_COMPILE_FLAGS}")
endif()
# Include the public API includes if make devel.
install(TARGETS libosquery ARCHIVE DESTINATION lib COMPONENT devel OPTIONAL)
install(DIRECTORY "${CMAKE_SOURCE_DIR}/include/" DESTINATION include COMPONENT devel OPTIONAL)
@ -151,10 +141,48 @@ if(NOT OSQUERY_BUILD_SDK_ONLY)
endif()
endif()
if (NOT DEFINED ENV{SKIP_TESTS})
# Build the example extension with the SDK
if(NOT DEFINED ENV{SKIP_TESTS})
# osquery testing library (testing helper methods/libs).
add_library(libosquery_testing STATIC core/test_util.cpp)
add_dependencies(libosquery_testing libosquery)
SET_OSQUERY_COMPILE(libosquery_testing "${CXX_COMPILE_FLAGS}")
set_target_properties(libosquery_testing PROPERTIES OUTPUT_NAME osquery_testing)
# osquery core set of unit tests build with SDK.
add_executable(osquery_tests main/tests.cpp ${OSQUERY_TESTS})
TARGET_OSQUERY_LINK_WHOLE(osquery_tests libosquery)
target_link_libraries(osquery_tests gtest libosquery_testing)
SET_OSQUERY_COMPILE(osquery_tests "${CXX_COMPILE_FLAGS} -DGTEST_HAS_TR1_TUPLE=0")
add_test(osquery_tests osquery_tests)
if(NOT OSQUERY_BUILD_SDK_ONLY)
# osquery core (additional) set of unit tests built outside of SDK.
add_executable(osquery_additional_tests main/tests.cpp ${OSQUERY_ADDITIONAL_TESTS})
TARGET_OSQUERY_LINK_WHOLE(osquery_additional_tests libosquery)
TARGET_OSQUERY_LINK_WHOLE(osquery_additional_tests libosquery_additional)
target_link_libraries(osquery_additional_tests gtest libosquery_testing)
SET_OSQUERY_COMPILE(osquery_additional_tests "${CXX_COMPILE_FLAGS} -DGTEST_HAS_TR1_TUPLE=0")
add_test(osquery_additional_tests osquery_additional_tests)
# osquery tables set of unit tests (extracted for organization).
add_executable(osquery_tables_tests main/tests.cpp ${OSQUERY_TABLES_TESTS})
TARGET_OSQUERY_LINK_WHOLE(osquery_tables_tests libosquery)
TARGET_OSQUERY_LINK_WHOLE(osquery_tables_tests libosquery_additional)
target_link_libraries(osquery_tables_tests gtest libosquery_testing)
SET_OSQUERY_COMPILE(osquery_tables_tests "${CXX_COMPILE_FLAGS} -DGTEST_HAS_TR1_TUPLE=0")
add_test(osquery_tables_tests osquery_tables_tests)
# osquery table run profiler built outside of SDK.
add_executable(run main/run.cpp)
TARGET_OSQUERY_LINK_WHOLE(run libosquery)
TARGET_OSQUERY_LINK_WHOLE(run libosquery_additional)
SET_OSQUERY_COMPILE(run "${CXX_COMPILE_FLAGS}")
set_target_properties(run PROPERTIES OUTPUT_NAME run)
endif()
# Build the example extension with the SDK.
ADD_OSQUERY_EXTENSION(example_extension examples/example_extension.cpp)
# Build the example extension module with the SDK
# Build the example extension module with the SDK.
ADD_OSQUERY_MODULE(modexample examples/example_module.cpp)
endif()

View File

@ -8,5 +8,8 @@ ADD_OSQUERY_LIBRARY(FALSE osquery_config_plugins
plugins/http.cpp
)
ADD_OSQUERY_TEST(FALSE config_tests config_tests.cpp)
ADD_OSQUERY_TEST(FALSE config_http_tests plugins/http_tests.cpp)
file(GLOB OSQUERY_CONFIG_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_CONFIG_TESTS})
file(GLOB OSQUERY_CONFIG_PLUGIN_TESTS "*/tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_CONFIG_PLUGIN_TESTS})

View File

@ -67,7 +67,6 @@ Status getConfig(boost::property_tree::ptree& recv) {
PluginResponse resp;
Status stat =
Registry::call("enrollment", "get_key", {{"enroll", "0"}}, resp);
params.put<std::string>("enrollment_key", resp[0]["key"]);
params.put<std::string>("app_id", FLAGS_enrollment_app_id);
stat = r.call(params);

View File

@ -7,16 +7,20 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <thread>
#include <iostream>
#include <random>
#include <sstream>
#include <thread>
#include <boost/network/protocol/http/server.hpp>
#include <boost/property_tree/ptree.hpp>
#include <gtest/gtest.h>
#include <osquery/config.h>
#include <osquery/enrollment.h>
#include "osquery/remote/requests.h"
#include "osquery/remote/transports/http.h"
#include "osquery/remote/serializers/json.h"
@ -29,11 +33,6 @@ DECLARE_string(enrollment_uri);
DECLARE_string(config_enrollment_uri);
DECLARE_string(enrollment_app_id);
class HttpConfigTests : public testing::Test {
public:
void SetUp() {}
};
struct EnrollHTTPHandler;
struct ConfigHTTPHandler;
typedef http::server<EnrollHTTPHandler> EnrollServer;
@ -55,14 +54,53 @@ struct ConfigHTTPHandler {
response = ConfigServer::response::stock_reply(
ConfigServer::response::ok,
std::string(
"{ \"schedule\": { \"launchd\": { \"query\": \"select * from "
"launchd;\", \"interval\": 3600 }, \"all_kexts\": { \"query\": "
"\"select name, version from kextstat;\", \"interval\": 600 } } "
"}"));
"{ \"schedule\": {\"config_server_launchd\": {\"query\": \"select "
"* from launchd;\", \"interval\": 3600 }}}"));
}
void log(...) {}
};
class HttpConfigTests : public testing::Test {
public:
HttpConfigTests() {
auto enroll_port = rand() % 10000 + 10000;
auto config_port = enroll_port + 1;
FLAGS_enrollment_uri = "http://localhost:" + std::to_string(enroll_port);
FLAGS_config_enrollment_uri =
"http://localhost:" + std::to_string(config_port);
FLAGS_enrollment_app_id = "just_a_test_id";
EnrollHTTPHandler enrollment;
ConfigHTTPHandler config;
EnrollServer::options opt_enroll(enrollment);
ConfigServer::options opt_config(config);
enrollment_server_ = std::make_shared<EnrollServer>(
opt_enroll.address("127.0.0.1").port(std::to_string(enroll_port)));
config_server_ = std::make_shared<ConfigServer>(
opt_config.address("127.0.0.1").port(std::to_string(config_port)));
config_thread_ = std::make_shared<boost::thread>(
boost::bind(&ConfigServer::run, &*config_server_));
enroll_thread_ = std::make_shared<boost::thread>(
boost::bind(&EnrollServer::run, &*enrollment_server_));
}
~HttpConfigTests() {
enrollment_server_->stop();
config_server_->stop();
enroll_thread_->join();
config_thread_->join();
}
protected:
std::shared_ptr<EnrollServer> enrollment_server_;
std::shared_ptr<ConfigServer> config_server_;
std::shared_ptr<boost::thread> enroll_thread_;
std::shared_ptr<boost::thread> config_thread_;
};
TEST_F(HttpConfigTests, test_enroll_config) {
// Change the active config plugin.
EXPECT_TRUE(Registry::setActive("config", "http").ok());
@ -72,35 +110,6 @@ TEST_F(HttpConfigTests, test_enroll_config) {
EXPECT_TRUE(stat.ok());
Config::update(response[0]);
ConfigDataInstance config;
EXPECT_EQ(config.schedule().size(), 2);
EXPECT_EQ(config.schedule().count("config_server_launchd"), 1);
}
}
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
osquery::FLAGS_enrollment_uri = "http://localhost:8851";
osquery::FLAGS_config_enrollment_uri = "http://localhost:8852";
osquery::FLAGS_enrollment_app_id = "just_a_test_id";
osquery::EnrollHTTPHandler enrollment;
osquery::ConfigHTTPHandler config;
osquery::EnrollServer::options opt_enroll(enrollment);
osquery::ConfigServer::options opt_config(config);
osquery::EnrollServer enrollment_server(
opt_enroll.address("127.0.0.1").port("8851"));
osquery::ConfigServer config_server(
opt_config.address("127.0.0.1").port("8852"));
boost::thread enroll_thread(
boost::bind(&osquery::EnrollServer::run, &enrollment_server)),
config_thread(boost::bind(&osquery::ConfigServer::run, &config_server));
auto ret = RUN_ALL_TESTS();
// Clean up
enrollment_server.stop();
config_server.stop();
enroll_thread.join();
config_thread.join();
return ret;
}

View File

@ -149,7 +149,9 @@ TEST_F(ConfigTests, test_config_update) {
class TestConfigParserPlugin : public ConfigParserPlugin {
public:
std::vector<std::string> keys() { return {"dictionary", "dictionary2", "list"}; }
std::vector<std::string> keys() {
return {"dictionary", "dictionary2", "list"};
}
Status update(const std::map<std::string, ConfigTree>& config) {
// Set a simple boolean indicating the update callin occurred.
@ -249,8 +251,3 @@ TEST_F(ConfigTests, test_splay) {
EXPECT_EQ(val5, 1);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -18,9 +18,5 @@ ADD_OSQUERY_LIBRARY(TRUE osquery_core
watcher.cpp
)
ADD_OSQUERY_TEST(TRUE flags_tests flags_tests.cpp)
ADD_OSQUERY_TEST(TRUE hash_test hash_tests.cpp)
ADD_OSQUERY_TEST(TRUE status_test status_tests.cpp)
ADD_OSQUERY_TEST(TRUE tables_tests tables_tests.cpp)
ADD_OSQUERY_TEST(TRUE text_tests text_tests.cpp)
ADD_OSQUERY_TEST(TRUE conversions_tests conversions_tests.cpp)
file(GLOB OSQUERY_CORE_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(TRUE ${OSQUERY_CORE_TESTS})

View File

@ -26,9 +26,9 @@ namespace osquery {
const std::string kTestQuery = "SELECT * FROM test_table";
#ifndef OSQUERY_BUILD_SDK
const std::string kTestDataPath = "../../../../tools/tests/";
const std::string kTestDataPath = "../../../tools/tests/";
#else
const std::string kTestDataPath = "../../../../../tools/tests/";
const std::string kTestDataPath = "../../../../tools/tests/";
#endif
QueryData getTestDBExpectedResults() {

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -52,8 +52,3 @@ TEST_F(ConversionsTests, test_ascii_false) {
EXPECT_FALSE(result);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -138,8 +138,3 @@ TEST_F(FlagsTests, test_alias_types) {
EXPECT_EQ(value, "test3");
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -47,8 +47,3 @@ TEST_F(HashTests, test_file_hashing) {
EXPECT_EQ(digest, "88ee11f2aa7903f34b8b8785d92208b1");
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -40,8 +40,3 @@ TEST_F(StatusTests, test_to_string) {
EXPECT_EQ(s.toString(), "foobar");
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -127,8 +127,3 @@ TEST_F(TablesTests, test_constraint_map) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -40,9 +40,3 @@ TEST_F(TextTests, test_split_occurences) {
EXPECT_EQ(split(content, ":", 1), expected);
}
}
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -4,6 +4,5 @@ ADD_OSQUERY_LIBRARY(TRUE osquery_database
results.cpp
)
ADD_OSQUERY_TEST(TRUE query_tests query_tests.cpp)
ADD_OSQUERY_TEST(TRUE db_handle_tests db_handle_tests.cpp)
ADD_OSQUERY_TEST(TRUE results_tests results_tests.cpp)
file(GLOB OSQUERY_DATABASE_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(TRUE ${OSQUERY_DATABASE_TESTS})

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -32,6 +32,8 @@ class DBHandleTests : public testing::Test {
DBHandle::getInstance()->getHandleForColumnFamily("foobartest");
}
void TearDown() { boost::filesystem::remove_all(kTestingDBHandlePath); }
public:
rocksdb::ColumnFamilyHandle* cfh_queries;
rocksdb::ColumnFamilyHandle* cfh_foobar;
@ -88,11 +90,3 @@ TEST_F(DBHandleTests, test_scan) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
int status = RUN_ALL_TESTS();
boost::filesystem::remove_all(kTestingDBHandlePath);
return status;
}

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -27,6 +27,7 @@ namespace osquery {
class QueryTests : public testing::Test {
public:
void SetUp() { db = DBHandle::getInstanceAtPath(kTestingQueryDBPath); }
void TearDown() { boost::filesystem::remove_all(kTestingQueryDBPath); }
public:
std::shared_ptr<DBHandle> db;
@ -137,10 +138,3 @@ TEST_F(QueryTests, test_get_current_results) {
EXPECT_EQ(qd, hQR.second.mostRecentResults.second);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
int status = RUN_ALL_TESTS();
boost::filesystem::remove_all(kTestingQueryDBPath);
return status;
}

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -185,9 +185,3 @@ TEST_F(ResultsTests, test_adding_duplicate_rows_to_query_data) {
EXPECT_EQ(q.size(), 2);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -2,4 +2,5 @@ ADD_OSQUERY_LIBRARY(FALSE osquery_devtools
printer.cpp
)
ADD_OSQUERY_TEST(FALSE printer_tests printer_tests.cpp)
file(GLOB OSQUERY_DEVTOOLS_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_DEVTOOLS_TESTS})

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -104,9 +104,3 @@ TEST_F(PrinterTests, test_unicode) {
EXPECT_EQ(lengths, expected);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -3,6 +3,5 @@ ADD_OSQUERY_LIBRARY(TRUE osquery_dispatcher
scheduler.cpp
)
if(APPLE)
ADD_OSQUERY_TEST(TRUE dispatcher_tests dispatcher_tests.cpp)
endif()
file(GLOB OSQUERY_DISPATCHER_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(TRUE ${OSQUERY_DISPATCHER_TESTS})

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -46,8 +46,3 @@ TEST_F(DispatcherTests, test_add_work) {
EXPECT_EQ(i, base + repetitions);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -1,3 +1,4 @@
ADD_OSQUERY_LIBRARY(TRUE osquery_distributed distributed.cpp)
ADD_OSQUERY_TEST(FALSE distributed_tests distributed_tests.cpp)
file(GLOB OSQUERY_DISTRIBUTED_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_DISTRIBUTED_TESTS})

View File

@ -46,7 +46,7 @@ TEST_F(DistributedTests, test_test_distributed_provider) {
}
TEST_F(DistributedTests, test_parse_query_json) {
std::string request_json = R"([{"query": "foo", "id": "bar"}])";
std::string request_json = "[{\"query\": \"foo\", \"id\": \"bar\"}]";
std::vector<DistributedQueryRequest> requests;
Status s = DistributedQueryHandler::parseQueriesJSON(request_json, requests);
ASSERT_EQ(Status(), s);
@ -54,7 +54,8 @@ TEST_F(DistributedTests, test_parse_query_json) {
EXPECT_EQ("foo", requests[0].query);
EXPECT_EQ("bar", requests[0].id);
std::string bad_json = R"([{"query": "foo", "id": "bar"}, {"query": "b"}])";
std::string bad_json =
"[{\"query\": \"foo\", \"id\": \"bar\"}, {\"query\": \"b\"}]";
requests.clear();
s = DistributedQueryHandler::parseQueriesJSON(bad_json, requests);
ASSERT_FALSE(s.ok());
@ -62,7 +63,7 @@ TEST_F(DistributedTests, test_parse_query_json) {
}
TEST_F(DistributedTests, test_handle_query) {
// Access to the internal SQL implementation is only available in core.
// Access to the internal SQL implementation is only available in core.
SQL query = DistributedQueryHandler::handleQuery("SELECT hour from time");
ASSERT_TRUE(query.ok());
QueryData rows = query.rows();
@ -88,8 +89,10 @@ TEST_F(DistributedTests, test_serialize_results_empty) {
TEST_F(DistributedTests, test_serialize_results_basic) {
DistributedQueryRequest r0("foo", "foo_id");
QueryData rows0 = {{{"foo0", "foo0_val"}, {"bar0", "bar0_val"}},
{{"foo1", "foo1_val"}, {"bar1", "bar1_val"}}, };
QueryData rows0 = {
{{"foo0", "foo0_val"}, {"bar0", "bar0_val"}},
{{"foo1", "foo1_val"}, {"bar1", "bar1_val"}},
};
MockSQL q0 = MockSQL(rows0);
pt::ptree tree;
@ -110,8 +113,10 @@ TEST_F(DistributedTests, test_serialize_results_basic) {
TEST_F(DistributedTests, test_serialize_results_multiple) {
DistributedQueryRequest r0("foo", "foo_id");
QueryData rows0 = {{{"foo0", "foo0_val"}, {"bar0", "bar0_val"}},
{{"foo1", "foo1_val"}, {"bar1", "bar1_val"}}, };
QueryData rows0 = {
{{"foo0", "foo0_val"}, {"bar0", "bar0_val"}},
{{"foo1", "foo1_val"}, {"bar1", "bar1_val"}},
};
MockSQL q0 = MockSQL(rows0);
DistributedQueryRequest r1("bar", "bar_id");
@ -137,14 +142,14 @@ TEST_F(DistributedTests, test_serialize_results_multiple) {
}
TEST_F(DistributedTests, test_do_queries) {
// Access to the internal SQL implementation is only available in core.
// Access to the internal SQL implementation is only available in core.
auto provider_raw = new MockDistributedProvider();
provider_raw->queriesJSON_ =
R"([
{"query": "SELECT hour FROM time", "id": "hour"},
{"query": "bad", "id": "bad"},
{"query": "SELECT minutes FROM time", "id": "minutes"}
])";
"[ \
{\"query\": \"SELECT hour FROM time\", \"id\": \"hour\"},\
{\"query\": \"bad\", \"id\": \"bad\"},\
{\"query\": \"SELECT minutes FROM time\", \"id\": \"minutes\"}\
]";
std::unique_ptr<MockDistributedProvider>
provider(provider_raw);
DistributedQueryHandler handler(std::move(provider));
@ -185,12 +190,10 @@ TEST_F(DistributedTests, test_do_queries) {
}
TEST_F(DistributedTests, test_duplicate_request) {
// Access to the internal SQL implementation is only available in core.
// Access to the internal SQL implementation is only available in core.
auto provider_raw = new MockDistributedProvider();
provider_raw->queriesJSON_ =
R"([
{"query": "SELECT hour FROM time", "id": "hour"}
])";
"[{\"query\": \"SELECT hour FROM time\", \"id\": \"hour\"}]";
std::unique_ptr<MockDistributedProvider>
provider(provider_raw);
DistributedQueryHandler handler(std::move(provider));
@ -218,8 +221,3 @@ TEST_F(DistributedTests, test_duplicate_request) {
EXPECT_EQ(0, tree.get_child("results").size());
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -26,11 +26,13 @@ ADD_OSQUERY_LIBRARY(TRUE osquery_events
events.cpp
)
ADD_OSQUERY_TEST(TRUE events_tests events_tests.cpp)
ADD_OSQUERY_TEST(TRUE events_database_tests events_database_tests.cpp)
file(GLOB OSQUERY_EVENTS_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(TRUE ${OSQUERY_EVENTS_TESTS})
if(APPLE)
ADD_OSQUERY_TEST(FALSE fsevents_tests darwin/fsevents_tests.cpp)
file(GLOB OSQUERY_DARWIN_EVENTS_TESTS "darwin/tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_DARWIN_EVENTS_TESTS})
elseif(LINUX)
ADD_OSQUERY_TEST(FALSE inotify_tests linux/inotify_tests.cpp)
file(GLOB OSQUERY_LINUX_EVENTS_TESTS "linux/tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_LINUX_EVENTS_TESTS})
endif()

View File

@ -143,7 +143,10 @@ class TestFSEventsEventSubscriber
: public EventSubscriber<FSEventsEventPublisher> {
public:
TestFSEventsEventSubscriber() { setName("TestFSEventsEventSubscriber"); }
Status init() { callback_count_ = 0; return Status(0, "OK"); }
Status init() {
callback_count_ = 0;
return Status(0, "OK");
}
Status SimpleCallback(const FSEventsEventContextRef& ec,
const void* user_data) {
callback_count_ += 1;
@ -197,7 +200,8 @@ TEST_F(FSEventsTests, test_fsevents_run) {
// Create a subscriptioning context
auto mc = std::make_shared<FSEventsSubscriptionContext>();
mc->path = kRealTestPath;
EventFactory::addSubscription("fsevents", Subscription::create("TestFSEventsEventSubscriber", mc));
EventFactory::addSubscription(
"fsevents", Subscription::create("TestFSEventsEventSubscriber", mc));
// Create an event loop thread (similar to main)
boost::thread temp_thread(EventFactory::run, "fsevents");
@ -256,8 +260,3 @@ TEST_F(FSEventsTests, test_fsevents_event_action) {
EndEventLoop();
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -379,10 +379,3 @@ TEST_F(EventsTests, test_fire_event) {
EXPECT_EQ(kBellHathTolled, 4);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
int status = RUN_ALL_TESTS();
boost::filesystem::remove_all(osquery::kTestingEventsDBPath);
return status;
}

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -150,7 +150,10 @@ class TestINotifyEventSubscriber
: public EventSubscriber<INotifyEventPublisher> {
public:
TestINotifyEventSubscriber() { setName("TestINotifyEventSubscriber"); }
Status init() { callback_count_ = 0; return Status(0, "OK"); }
Status init() {
callback_count_ = 0;
return Status(0, "OK");
}
Status SimpleCallback(const INotifyEventContextRef& ec,
const void* user_data) {
callback_count_ += 1;
@ -205,7 +208,6 @@ TEST_F(INotifyTests, test_inotify_run) {
// Create a temporary file to watch, open writeable
FILE* fd = fopen(kRealTestPath.c_str(), "w");
// Create a subscriber.
auto sub = std::make_shared<TestINotifyEventSubscriber>();
EventFactory::registerEventSubscriber(sub);
@ -213,7 +215,8 @@ TEST_F(INotifyTests, test_inotify_run) {
// Create a subscriptioning context
auto mc = std::make_shared<INotifySubscriptionContext>();
mc->path = kRealTestPath;
status = EventFactory::addSubscription("inotify", Subscription::create("TestINotifyEventSubscriber", mc));
status = EventFactory::addSubscription(
"inotify", Subscription::create("TestINotifyEventSubscriber", mc));
EXPECT_TRUE(status.ok());
// Create an event loop thread (similar to main)
@ -309,8 +312,3 @@ TEST_F(INotifyTests, test_inotify_recursion) {
StopEventLoop();
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -27,6 +27,11 @@ class EventsDatabaseTests : public ::testing::Test {
// Setup a testing DB instance
DBHandle::getInstanceAtPath(kTestingEventsDBPath);
}
void TearDown() {
// Todo: each test set should operate on a clear working directory.
boost::filesystem::remove_all(osquery::kTestingEventsDBPath);
}
};
class FakeEventPublisher
@ -48,7 +53,7 @@ class FakeEventSubscriber : public EventSubscriber<FakeEventPublisher> {
TEST_F(EventsDatabaseTests, test_event_module_id) {
auto sub = std::make_shared<FakeEventSubscriber>();
sub->doNotExpire();
// Not normally available outside of EventSubscriber->Add().
auto event_id1 = sub->getEventID();
EXPECT_EQ(event_id1, "1");
@ -56,7 +61,6 @@ TEST_F(EventsDatabaseTests, test_event_module_id) {
EXPECT_EQ(event_id2, "2");
}
TEST_F(EventsDatabaseTests, test_event_add) {
auto sub = std::make_shared<FakeEventSubscriber>();
auto status = sub->testAdd(1);
@ -144,10 +148,3 @@ TEST_F(EventsDatabaseTests, test_record_expiration) {
EXPECT_EQ(records.size(), 1); // 11
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
int status = RUN_ALL_TESTS();
boost::filesystem::remove_all(osquery::kTestingEventsDBPath);
return status;
}

View File

@ -0,0 +1,384 @@
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <typeinfo>
#include <boost/filesystem/operations.hpp>
#include <gtest/gtest.h>
#include <osquery/database.h>
#include <osquery/events.h>
#include <osquery/tables.h>
namespace osquery {
const std::string kTestingEventsDBPath = "/tmp/rocksdb-osquery-testevents";
class EventsTests : public ::testing::Test {
public:
void SetUp() {
// Setup a testing DB instance
DBHandle::getInstanceAtPath(kTestingEventsDBPath);
}
void TearDown() {
EventFactory::end();
boost::filesystem::remove_all(osquery::kTestingEventsDBPath);
}
};
// The most basic event publisher uses useless Subscription/Event.
class BasicEventPublisher
: public EventPublisher<SubscriptionContext, EventContext> {};
class AnotherBasicEventPublisher
: public EventPublisher<SubscriptionContext, EventContext> {};
// Create some semi-useless subscription and event structures.
struct FakeSubscriptionContext : SubscriptionContext {
int require_this_value;
};
struct FakeEventContext : EventContext {
int required_value;
};
// Typdef the shared_ptr accessors.
typedef std::shared_ptr<FakeSubscriptionContext> FakeSubscriptionContextRef;
typedef std::shared_ptr<FakeEventContext> FakeEventContextRef;
// Now a publisher with a type.
class FakeEventPublisher
: public EventPublisher<FakeSubscriptionContext, FakeEventContext> {
DECLARE_PUBLISHER("FakePublisher");
};
class AnotherFakeEventPublisher
: public EventPublisher<FakeSubscriptionContext, FakeEventContext> {
DECLARE_PUBLISHER("AnotherFakePublisher");
};
TEST_F(EventsTests, test_event_pub) {
auto pub = std::make_shared<FakeEventPublisher>();
EXPECT_EQ(pub->type(), "FakePublisher");
// Test type names.
auto pub_sub = pub->createSubscriptionContext();
EXPECT_EQ(typeid(FakeSubscriptionContext), typeid(*pub_sub));
}
TEST_F(EventsTests, test_register_event_pub) {
auto basic_pub = std::make_shared<BasicEventPublisher>();
auto status = EventFactory::registerEventPublisher(basic_pub);
// This class is the SAME, there was no type override.
auto another_basic_pub = std::make_shared<AnotherBasicEventPublisher>();
status = EventFactory::registerEventPublisher(another_basic_pub);
EXPECT_FALSE(status.ok());
// This class is different but also uses different types!
auto fake_pub = std::make_shared<FakeEventPublisher>();
status = EventFactory::registerEventPublisher(fake_pub);
EXPECT_TRUE(status.ok());
// May also register the event_pub instance
auto another_fake_pub = std::make_shared<AnotherFakeEventPublisher>();
status = EventFactory::registerEventPublisher(another_fake_pub);
EXPECT_TRUE(status.ok());
}
TEST_F(EventsTests, test_event_pub_types) {
auto pub = std::make_shared<FakeEventPublisher>();
EXPECT_EQ(pub->type(), "FakePublisher");
EventFactory::registerEventPublisher(pub);
auto pub2 = EventFactory::getEventPublisher("FakePublisher");
EXPECT_EQ(pub->type(), pub2->type());
}
TEST_F(EventsTests, test_create_event_pub) {
auto pub = std::make_shared<BasicEventPublisher>();
auto status = EventFactory::registerEventPublisher(pub);
EXPECT_TRUE(status.ok());
// Make sure only the first event type was recorded.
EXPECT_EQ(EventFactory::numEventPublishers(), 1);
}
class UniqueEventPublisher
: public EventPublisher<FakeSubscriptionContext, FakeEventContext> {
DECLARE_PUBLISHER("unique");
};
TEST_F(EventsTests, test_create_using_registry) {
// The events API uses attachEvents to move registry event publishers and
// subscribers into the events factory.
EXPECT_EQ(EventFactory::numEventPublishers(), 0);
attachEvents();
// Store the number of default event publishers (in core).
int default_publisher_count = EventFactory::numEventPublishers();
// Now add another registry item, but do not yet attach it.
auto UniqueEventPublisherRegistryItem =
Registry::add<UniqueEventPublisher>("event_publisher", "unique");
EXPECT_EQ(EventFactory::numEventPublishers(), default_publisher_count);
// Now attach and make sure it was added.
attachEvents();
EXPECT_EQ(EventFactory::numEventPublishers(), default_publisher_count + 1);
}
TEST_F(EventsTests, test_create_subscription) {
auto pub = std::make_shared<BasicEventPublisher>();
EventFactory::registerEventPublisher(pub);
// Make sure a subscription cannot be added for a non-existent event type.
// Note: It normally would not make sense to create a blank subscription.
auto subscription = Subscription::create("FakeSubscriber");
auto status = EventFactory::addSubscription("FakePublisher", subscription);
EXPECT_FALSE(status.ok());
// In this case we can still add a blank subscription to an existing event
// type.
status = EventFactory::addSubscription("publisher", subscription);
EXPECT_TRUE(status.ok());
// Make sure the subscription is added.
EXPECT_EQ(EventFactory::numSubscriptions("publisher"), 1);
}
TEST_F(EventsTests, test_multiple_subscriptions) {
Status status;
auto pub = std::make_shared<BasicEventPublisher>();
EventFactory::registerEventPublisher(pub);
auto subscription = Subscription::create("subscriber");
status = EventFactory::addSubscription("publisher", subscription);
status = EventFactory::addSubscription("publisher", subscription);
EXPECT_EQ(EventFactory::numSubscriptions("publisher"), 2);
}
struct TestSubscriptionContext : public SubscriptionContext {
int smallest;
};
class TestEventPublisher
: public EventPublisher<TestSubscriptionContext, EventContext> {
DECLARE_PUBLISHER("TestPublisher");
public:
Status setUp() {
smallest_ever_ += 1;
return Status(0, "OK");
}
void configure() {
int smallest_subscription = smallest_ever_;
configure_run = true;
for (const auto& subscription : subscriptions_) {
auto subscription_context = getSubscriptionContext(subscription->context);
if (smallest_subscription > subscription_context->smallest) {
smallest_subscription = subscription_context->smallest;
}
}
smallest_ever_ = smallest_subscription;
}
void tearDown() { smallest_ever_ += 1; }
TestEventPublisher() : EventPublisher() {
smallest_ever_ = 0;
configure_run = false;
}
// Custom methods do not make sense, but for testing it exists.
int getTestValue() { return smallest_ever_; }
public:
bool configure_run;
private:
int smallest_ever_;
};
TEST_F(EventsTests, test_create_custom_event_pub) {
auto basic_pub = std::make_shared<BasicEventPublisher>();
EventFactory::registerEventPublisher(basic_pub);
auto pub = std::make_shared<TestEventPublisher>();
auto status = EventFactory::registerEventPublisher(pub);
// These event types have unique event type IDs
EXPECT_TRUE(status.ok());
EXPECT_EQ(EventFactory::numEventPublishers(), 2);
// Make sure the setUp function was called.
EXPECT_EQ(pub->getTestValue(), 1);
}
TEST_F(EventsTests, test_custom_subscription) {
// Step 1, register event type
auto pub = std::make_shared<TestEventPublisher>();
auto status = EventFactory::registerEventPublisher(pub);
// Step 2, create and configure a subscription context
auto sc = std::make_shared<TestSubscriptionContext>();
sc->smallest = -1;
// Step 3, add the subscription to the event type
status = EventFactory::addSubscription("TestPublisher", "TestSubscriber", sc);
EXPECT_TRUE(status.ok());
EXPECT_EQ(pub->numSubscriptions(), 1);
// The event type must run configure for each added subscription.
EXPECT_TRUE(pub->configure_run);
EXPECT_EQ(pub->getTestValue(), -1);
}
TEST_F(EventsTests, test_tear_down) {
auto pub = std::make_shared<TestEventPublisher>();
auto status = EventFactory::registerEventPublisher(pub);
// Make sure set up incremented the test value.
EXPECT_EQ(pub->getTestValue(), 1);
status = EventFactory::deregisterEventPublisher("TestPublisher");
EXPECT_TRUE(status.ok());
// Make sure tear down inremented the test value.
EXPECT_EQ(pub->getTestValue(), 2);
// Once more, now deregistering all event types.
status = EventFactory::registerEventPublisher(pub);
EXPECT_EQ(pub->getTestValue(), 3);
EventFactory::end();
EXPECT_EQ(pub->getTestValue(), 4);
// Make sure the factory state represented.
EXPECT_EQ(EventFactory::numEventPublishers(), 0);
}
static int kBellHathTolled = 0;
Status TestTheeCallback(EventContextRef context, const void* user_data) {
kBellHathTolled += 1;
return Status(0, "OK");
}
class FakeEventSubscriber : public EventSubscriber<FakeEventPublisher> {
public:
bool bellHathTolled;
bool contextBellHathTolled;
bool shouldFireBethHathTolled;
FakeEventSubscriber() {
setName("FakeSubscriber");
bellHathTolled = false;
contextBellHathTolled = false;
shouldFireBethHathTolled = false;
}
Status Callback(const EventContextRef& ec, const void* user_data) {
// We don't care about the subscription or the event contexts.
bellHathTolled = true;
return Status(0, "OK");
}
Status SpecialCallback(const FakeEventContextRef& ec, const void* user_data) {
// Now we care that the event context is corrected passed.
if (ec->required_value == 42) {
contextBellHathTolled = true;
}
return Status(0, "OK");
}
void lateInit() {
auto sub_ctx = createSubscriptionContext();
subscribe(&FakeEventSubscriber::Callback, sub_ctx, nullptr);
}
void laterInit() {
auto sub_ctx = createSubscriptionContext();
sub_ctx->require_this_value = 42;
subscribe(&FakeEventSubscriber::SpecialCallback, sub_ctx, nullptr);
}
};
TEST_F(EventsTests, test_event_sub) {
auto sub = std::make_shared<FakeEventSubscriber>();
EXPECT_EQ(sub->type(), "FakePublisher");
EXPECT_EQ(sub->getName(), "FakeSubscriber");
}
TEST_F(EventsTests, test_event_sub_subscribe) {
auto pub = std::make_shared<FakeEventPublisher>();
EventFactory::registerEventPublisher(pub);
auto sub = std::make_shared<FakeEventSubscriber>();
EventFactory::registerEventSubscriber(sub);
// Don't overload the normal `init` Subscription member.
sub->lateInit();
EXPECT_EQ(pub->numSubscriptions(), 1);
auto ec = pub->createEventContext();
pub->fire(ec, 0);
EXPECT_TRUE(sub->bellHathTolled);
}
TEST_F(EventsTests, test_event_sub_context) {
auto pub = std::make_shared<FakeEventPublisher>();
EventFactory::registerEventPublisher(pub);
auto sub = std::make_shared<FakeEventSubscriber>();
EventFactory::registerEventSubscriber(sub);
sub->laterInit();
auto ec = pub->createEventContext();
ec->required_value = 42;
pub->fire(ec, 0);
EXPECT_TRUE(sub->contextBellHathTolled);
}
TEST_F(EventsTests, test_fire_event) {
Status status;
auto pub = std::make_shared<BasicEventPublisher>();
status = EventFactory::registerEventPublisher(pub);
auto sub = std::make_shared<FakeEventSubscriber>();
auto subscription = Subscription::create("FakeSubscriber");
subscription->callback = TestTheeCallback;
status = EventFactory::addSubscription("publisher", subscription);
// The event context creation would normally happen in the event type.
auto ec = pub->createEventContext();
pub->fire(ec, 0);
EXPECT_EQ(kBellHathTolled, 1);
auto second_subscription = Subscription::create("FakeSubscriber");
status = EventFactory::addSubscription("publisher", second_subscription);
// Now there are two subscriptions (one sans callback).
pub->fire(ec, 0);
EXPECT_EQ(kBellHathTolled, 2);
// Now both subscriptions have callbacks.
second_subscription->callback = TestTheeCallback;
pub->fire(ec, 0);
EXPECT_EQ(kBellHathTolled, 4);
}
}

View File

@ -13,4 +13,5 @@ ADD_OSQUERY_LIBRARY(TRUE osquery_extensions
interface.cpp
)
ADD_OSQUERY_TEST(TRUE extensions_test extensions_tests.cpp)
file(GLOB OSQUERY_EXTENSIONS_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(TRUE ${OSQUERY_EXTENSIONS_TESTS})

View File

@ -186,8 +186,7 @@ TEST_F(ExtensionsTest, test_extension_broadcast) {
RouteUUID uuid;
try {
uuid = (RouteUUID)stoi(status.getMessage(), nullptr, 0);
}
catch (const std::exception& e) {
} catch (const std::exception& e) {
EXPECT_TRUE(false);
return;
}
@ -239,8 +238,3 @@ TEST_F(ExtensionsTest, test_extension_module_search) {
tearDownMockFileStructure();
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -16,8 +16,10 @@ ADD_OSQUERY_LIBRARY(TRUE osquery_filesystem
globbing.cpp
)
ADD_OSQUERY_TEST(TRUE filesystem_tests filesystem_tests.cpp)
file(GLOB OSQUERY_FILESYSTEM_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(TRUE ${OSQUERY_FILESYSTEM_TESTS})
if(APPLE)
ADD_OSQUERY_TEST(TRUE plist_tests darwin/plist_tests.cpp)
ADD_OSQUERY_TEST(TRUE plist_benchmark darwin/plist_benchmark.cpp)
file(GLOB OSQUERY_DARWIN_FILESYSTEM_TESTS "darwin/tests/*.cpp")
ADD_OSQUERY_TEST(TRUE ${OSQUERY_DARWIN_FILESYSTEM_TESTS})
endif()

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -96,10 +96,3 @@ TEST_F(PlistTests, test_parse_plist_content_with_blobs) {
EXPECT_NE(alias.find("Applications/Flux.app"), std::string::npos);
}
}
int main(int argc, char* argv[]) {
argv0 = argv[0];
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -3,12 +3,11 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <fstream>
#include <stdio.h>
@ -63,16 +62,16 @@ TEST_F(FilesystemTests, test_wildcard_single_file_list) {
EXPECT_TRUE(status.ok());
EXPECT_EQ(files.size(), 3);
EXPECT_EQ(files.size(), files_flag.size());
EXPECT_NE(
std::find(files.begin(), files.end(), kFakeDirectory + "/roto.txt"),
files.end());
EXPECT_NE(std::find(files.begin(), files.end(), kFakeDirectory + "/roto.txt"),
files.end());
}
TEST_F(FilesystemTests, test_wildcard_dual) {
std::vector<std::string> files;
auto status = resolveFilePattern(kFakeDirectory + "/%/%", files);
EXPECT_TRUE(status.ok());
EXPECT_NE(std::find(files.begin(), files.end(),
EXPECT_NE(std::find(files.begin(),
files.end(),
kFakeDirectory + "/deep1/level1.txt"),
files.end());
}
@ -81,7 +80,8 @@ TEST_F(FilesystemTests, test_wildcard_full_recursion) {
std::vector<std::string> files;
auto status = resolveFilePattern(kFakeDirectory + "/%%", files);
EXPECT_TRUE(status.ok());
EXPECT_NE(std::find(files.begin(), files.end(),
EXPECT_NE(std::find(files.begin(),
files.end(),
kFakeDirectory + "/deep1/deep2/level2.txt"),
files.end());
}
@ -90,7 +90,8 @@ TEST_F(FilesystemTests, test_wildcard_end_last_component) {
std::vector<std::string> files;
auto status = resolveFilePattern(kFakeDirectory + "/%11/%sh", files);
EXPECT_TRUE(status.ok());
EXPECT_NE(std::find(files.begin(), files.end(),
EXPECT_NE(std::find(files.begin(),
files.end(),
kFakeDirectory + "/deep11/not_bash"),
files.end());
}
@ -99,7 +100,8 @@ TEST_F(FilesystemTests, test_wildcard_three_kinds) {
std::vector<std::string> files;
auto status = resolveFilePattern(kFakeDirectory + "/%p11/%/%%", files);
EXPECT_TRUE(status.ok());
EXPECT_NE(std::find(files.begin(), files.end(),
EXPECT_NE(std::find(files.begin(),
files.end(),
kFakeDirectory + "/deep11/deep2/deep3/level3.txt"),
files.end());
}
@ -115,10 +117,12 @@ TEST_F(FilesystemTests, test_wildcard_filewild) {
std::vector<std::string> files;
auto status = resolveFilePattern(kFakeDirectory + "/deep1%/%", files);
EXPECT_TRUE(status.ok());
EXPECT_NE(std::find(files.begin(), files.end(),
EXPECT_NE(std::find(files.begin(),
files.end(),
kFakeDirectory + "/deep1/level1.txt"),
files.end());
EXPECT_NE(std::find(files.begin(), files.end(),
EXPECT_NE(std::find(files.begin(),
files.end(),
kFakeDirectory + "/deep11/level1.txt"),
files.end());
}
@ -186,8 +190,8 @@ TEST_F(FilesystemTests, test_wildcard_double_all) {
}
TEST_F(FilesystemTests, test_double_wild_event_opt) {
std::vector<std::string> all;
auto status = resolveFilePattern(kFakeDirectory + "/%%", all,
REC_LIST_FOLDERS | REC_EVENT_OPT);
auto status = resolveFilePattern(
kFakeDirectory + "/%%", all, REC_LIST_FOLDERS | REC_EVENT_OPT);
EXPECT_TRUE(status.ok());
EXPECT_EQ(all.size(), 1);
EXPECT_NE(std::find(all.begin(), all.end(), kFakeDirectory), all.end());
@ -195,8 +199,8 @@ TEST_F(FilesystemTests, test_double_wild_event_opt) {
TEST_F(FilesystemTests, test_letter_wild_opt) {
std::vector<std::string> all;
auto status = resolveFilePattern(kFakeDirectory + "/d%", all,
REC_LIST_FOLDERS | REC_EVENT_OPT);
auto status = resolveFilePattern(
kFakeDirectory + "/d%", all, REC_LIST_FOLDERS | REC_EVENT_OPT);
EXPECT_TRUE(status.ok());
EXPECT_EQ(all.size(), 3);
EXPECT_NE(std::find(all.begin(), all.end(), kFakeDirectory + "/deep1"),
@ -207,19 +211,19 @@ TEST_F(FilesystemTests, test_letter_wild_opt) {
TEST_F(FilesystemTests, test_dotdot) {
std::vector<std::string> all;
auto status = resolveFilePattern(kFakeDirectory + "/deep11/deep2/../../%",
all, REC_LIST_FILES);
auto status = resolveFilePattern(
kFakeDirectory + "/deep11/deep2/../../%", all, REC_LIST_FILES);
EXPECT_TRUE(status.ok());
EXPECT_EQ(all.size(), 3);
EXPECT_NE(std::find(all.begin(), all.end(),
EXPECT_NE(std::find(all.begin(),
all.end(),
kFakeDirectory + "/deep11/deep2/../../door.txt"),
all.end());
}
TEST_F(FilesystemTests, test_dotdot_relative) {
std::vector<std::string> all;
auto status =
resolveFilePattern("../../../../tools/tests/%", all, REC_LIST_ALL);
auto status = resolveFilePattern(kTestDataPath + "%", all, REC_LIST_ALL);
EXPECT_TRUE(status.ok());
bool found = false;
@ -234,12 +238,11 @@ TEST_F(FilesystemTests, test_dotdot_relative) {
TEST_F(FilesystemTests, test_no_wild) {
std::vector<std::string> all;
auto status = resolveFilePattern(kFakeDirectory + "/roto.txt",
all, REC_LIST_FILES);
auto status =
resolveFilePattern(kFakeDirectory + "/roto.txt", all, REC_LIST_FILES);
EXPECT_TRUE(status.ok());
EXPECT_EQ(all.size(), 1);
EXPECT_NE(std::find(all.begin(), all.end(),
kFakeDirectory + "/roto.txt"),
EXPECT_NE(std::find(all.begin(), all.end(), kFakeDirectory + "/roto.txt"),
all.end());
}
@ -254,9 +257,3 @@ TEST_F(FilesystemTests, test_safe_permissions) {
EXPECT_TRUE(safePermissions("/", "/dev/zero"));
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -7,4 +7,5 @@ ADD_OSQUERY_LIBRARY(FALSE osquery_logger_plugins
plugins/filesystem.cpp
)
ADD_OSQUERY_TEST(FALSE logger_tests logger_tests.cpp)
file(GLOB OSQUERY_LOGGER_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_LOGGER_TESTS})

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
@ -129,8 +129,3 @@ TEST_F(LoggerTests, test_logger_variations) {
EXPECT_EQ(LoggerTests::statuses_logged, 0);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

23
osquery/main/tests.cpp Normal file
View File

@ -0,0 +1,23 @@
/*
* Copyright (c) 2015, Wesley Shields
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <cstdlib>
#include <time.h>
#include <gtest/gtest.h>
int main(int argc, char* argv[]) {
srand(time(nullptr));
testing::InitGoogleTest(&argc, argv);
// Optionally enable Goggle Logging
// google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -2,4 +2,5 @@ ADD_OSQUERY_LIBRARY(TRUE osquery_registry
registry.cpp
)
ADD_OSQUERY_TEST(TRUE registry_tests registry_tests.cpp)
file(GLOB OSQUERY_REGISTRY_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(TRUE ${OSQUERY_REGISTRY_TESTS})

View File

@ -3,11 +3,11 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <gtest/gtest.h>
#include <osquery/logger.h>
@ -270,9 +270,3 @@ TEST_F(RegistryTests, test_registry_modules) {
EXPECT_EQ(RegistryFactory::getModule(), 0);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -1,16 +1,18 @@
ADD_OSQUERY_LIBRARY(TRUE osquery_requests
requests.h
transports/http.h
transports/http.cpp
serializers/json.h
ADD_OSQUERY_LIBRARY(TRUE osquery_remote
enrollment/enrollment.cpp
serializers/json.cpp
transports/http.cpp
)
ADD_OSQUERY_LIBRARY(FALSE osquery_enrollment
enrollment/plugins/http_enrollment.cpp
ADD_OSQUERY_LIBRARY(FALSE osquery_enrollment_plugins
enrollment/plugins/http.cpp
)
ADD_OSQUERY_TEST(FALSE requests_tests requests_tests.cpp)
ADD_OSQUERY_TEST(FALSE json_tests serializers/json_tests.cpp)
ADD_OSQUERY_TEST(FALSE http_tests transports/http_tests.cpp)
ADD_OSQUERY_TEST(FALSE enrollment_tests enrollment/enrollment_tests.cpp)
file(GLOB OSQUERY_ENROLLMENT_PLUGIN_TESTS "enrollment/plugins/tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_ENROLLMENT_PLUGIN_TESTS})
file(GLOB OSQUERY_REMOTE_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_REMOTE_TESTS})
file(GLOB OSQUERY_REMOTE_COMPONENT_TESTS "*/tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_REMOTE_COMPONENT_TESTS})

View File

@ -0,0 +1,29 @@
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <osquery/enrollment.h>
namespace osquery {
Status EnrollmentPlugin::call(const PluginRequest& request,
PluginResponse& response) {
if (request.count("enroll") == 0) {
return Status(1, "Unsupported call to enrollment plugin");
}
std::string key = this->getKey(request.at("enroll") == "1");
response.push_back({{"key", key}});
if (key == "") {
return Status(1, "Could not enroll");
} else {
return Status(0, "OK");
}
}
}

View File

@ -7,9 +7,11 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <boost/property_tree/json_parser.hpp>
#include <osquery/enrollment.h>
#include "osquery/remote/requests.h"
#include "osquery/remote/transports/http.h"
#include "osquery/remote/serializers/json.h"
@ -82,19 +84,4 @@ std::string RemoteEnrollmentPlugin::getKey(bool force) {
}
return enrollment_key_;
}
Status EnrollmentPlugin::call(const PluginRequest& request,
PluginResponse& response) {
if (request.count("enroll") == 0) {
return Status(1, "Unsupported call to enrollment plugin");
}
std::string key = this->getKey(request.at("enroll") == "1");
response.push_back({{"key", key}});
if (key == "") {
return Status(1, "Could not enroll");
} else {
return Status(0, "OK");
}
}
}

View File

@ -7,9 +7,12 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <random>
#include <thread>
#include <boost/network/protocol/http/server.hpp>
#include <gtest/gtest.h>
#include <osquery/enrollment.h>
@ -24,15 +27,10 @@ namespace osquery {
DECLARE_string(enrollment_uri);
DECLARE_string(enrollment_app_id);
class EnrollmentTests : public testing::Test {
public:
void SetUp() {}
};
struct TestHTTPEnrollmentHandler;
typedef http::server<TestHTTPEnrollmentHandler> Server;
struct FooBarHTTPHandler;
typedef http::server<FooBarHTTPHandler> Server;
struct FooBarHTTPHandler {
struct TestHTTPEnrollmentHandler {
void operator()(Server::request const &request, Server::response &response) {
response = Server::response::stock_reply(
Server::response::ok, std::string("{\"enrollment_key\":\"potatoes\"}"));
@ -40,7 +38,31 @@ struct FooBarHTTPHandler {
void log(...) {}
};
TEST_F(EnrollmentTests, test_enroll) {
class RemoteEnrollmentTests : public testing::Test {
public:
RemoteEnrollmentTests() {
auto enroll_port = std::to_string(rand() % 10000 + 10000);
FLAGS_enrollment_uri = "http://localhost:" + enroll_port;
FLAGS_enrollment_app_id = "just_a_test_id";
TestHTTPEnrollmentHandler handler;
Server::options options(handler);
server_ = std::make_shared<Server>(
options.address("127.0.0.1").port(enroll_port));
t_ =
std::make_shared<boost::thread>(boost::bind(&Server::run, &(*server_)));
}
~RemoteEnrollmentTests() {
server_->stop();
t_->join();
}
private:
std::shared_ptr<Server> server_;
std::shared_ptr<boost::thread> t_;
};
TEST_F(RemoteEnrollmentTests, test_enroll) {
// Call enroll
PluginRequest request = {
{"enroll", "1"}, // 0 enroll if needed, 1 force re-enroll
@ -56,18 +78,3 @@ TEST_F(EnrollmentTests, test_enroll) {
}
}
}
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
osquery::FLAGS_enrollment_uri = "http://localhost:8241";
osquery::FLAGS_enrollment_app_id = "just_a_test_id";
osquery::FooBarHTTPHandler handler;
osquery::Server::options options(handler);
osquery::Server server(options.address("127.0.0.1").port("8241"));
boost::thread t(boost::bind(&osquery::Server::run, &server));
auto ret = RUN_ALL_TESTS();
server.stop();
t.join();
return ret;
}

View File

@ -14,9 +14,9 @@
namespace osquery {
class JSONTests : public testing::Test {};
class JSONSerializersTests : public testing::Test {};
TEST_F(JSONTests, testSerialize) {
TEST_F(JSONSerializersTests, test_serialize) {
auto json = JSONSerializer();
boost::property_tree::ptree params;
params.put<std::string>("foo", "bar");
@ -27,7 +27,7 @@ TEST_F(JSONTests, testSerialize) {
EXPECT_EQ(serialized, "{\"foo\":\"bar\"}\n");
}
TEST_F(JSONTests, testDeserialize) {
TEST_F(JSONSerializersTests, test_deserialize) {
auto json = JSONSerializer();
boost::property_tree::ptree params;
std::string serialized = "{\"foo\":\"bar\"}\n";
@ -40,9 +40,3 @@ TEST_F(JSONTests, testDeserialize) {
EXPECT_EQ(params, expected);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -50,7 +50,7 @@ class MockSerializer : public Serializer {
}
};
TEST_F(RequestsTests, testCall) {
TEST_F(RequestsTests, test_call) {
auto req = Request<MockTransport, MockSerializer>("foobar");
auto s1 = req.call();
EXPECT_TRUE(s1.ok());
@ -62,7 +62,7 @@ TEST_F(RequestsTests, testCall) {
EXPECT_EQ(params, empty_ptree);
}
TEST_F(RequestsTests, testCallWithParams) {
TEST_F(RequestsTests, test_call_with_params) {
auto req = Request<MockTransport, MockSerializer>("foobar");
boost::property_tree::ptree params;
params.put<std::string>("foo", "bar");
@ -78,9 +78,3 @@ TEST_F(RequestsTests, testCallWithParams) {
EXPECT_EQ(recv, expected);
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -8,9 +8,11 @@
*
*/
#include <random>
#include <thread>
#include <boost/network/protocol/http/server.hpp>
#include <gtest/gtest.h>
#include "osquery/remote/requests.h"
@ -21,10 +23,10 @@ namespace http = boost::network::http;
namespace osquery {
struct FooBarHTTPHandler;
typedef http::server<FooBarHTTPHandler> Server;
struct TestHTTPTransportHandler;
typedef http::server<TestHTTPTransportHandler> Server;
struct FooBarHTTPHandler {
struct TestHTTPTransportHandler {
void operator()(Server::request const &request, Server::response &response) {
response = Server::response::stock_reply(Server::response::ok,
std::string("{\"foo\":\"bar\"}"));
@ -33,10 +35,31 @@ struct FooBarHTTPHandler {
void log(...) {}
};
class HTTPTests : public testing::Test {};
class HTTPTransportsTests : public testing::Test {
public:
HTTPTransportsTests() {
port_ = std::to_string(rand() % 10000 + 10000);
TestHTTPTransportHandler handler;
Server::options options(handler);
server_ =
std::make_shared<Server>(options.address("127.0.0.1").port(port_));
t_ =
std::make_shared<boost::thread>(boost::bind(&Server::run, &(*server_)));
}
TEST_F(HTTPTests, testCall) {
auto r = Request<HTTPTransport, JSONSerializer>("http://127.0.0.1:8237");
~HTTPTransportsTests() {
server_->stop();
t_->join();
}
protected:
std::shared_ptr<Server> server_;
std::shared_ptr<boost::thread> t_;
std::string port_;
};
TEST_F(HTTPTransportsTests, test_call) {
auto r = Request<HTTPTransport, JSONSerializer>("http://127.0.0.1:" + port_);
auto s1 = r.call();
EXPECT_TRUE(s1.ok());
boost::property_tree::ptree params;
@ -44,29 +67,16 @@ TEST_F(HTTPTests, testCall) {
EXPECT_TRUE(s2.ok());
}
TEST_F(HTTPTests, testCallWithParams) {
auto r = Request<HTTPTransport, JSONSerializer>("http://127.0.0.1:8237");
TEST_F(HTTPTransportsTests, test_call_with_params) {
auto r = Request<HTTPTransport, JSONSerializer>("http://127.0.0.1:" + port_);
boost::property_tree::ptree params;
params.put<std::string>("foo", "bar");
auto s1 = r.call(params);
EXPECT_TRUE(s1.ok());
boost::property_tree::ptree recv;
auto s2 = r.getResponse(recv);
EXPECT_TRUE(s2.ok());
EXPECT_EQ(params, recv);
}
}
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
osquery::FooBarHTTPHandler handler;
osquery::Server::options options(handler);
osquery::Server server(options.address("127.0.0.1").port("8237"));
boost::thread t(boost::bind(&osquery::Server::run, &server));
auto ret = RUN_ALL_TESTS();
server.stop();
t.join();
return ret;
}

View File

@ -7,6 +7,5 @@ ADD_OSQUERY_LIBRARY(FALSE osquery_sql_internal
virtual_table.cpp
)
ADD_OSQUERY_TEST(TRUE sql_test sql_tests.cpp)
ADD_OSQUERY_TEST(FALSE sqlite_util_tests sqlite_util_tests.cpp)
ADD_OSQUERY_TEST(FALSE virtual_table_tests virtual_table_tests.cpp)
file(GLOB OSQUERY_SQL_TESTS "tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_SQL_TESTS})

View File

@ -26,7 +26,7 @@ TEST_F(SQLTests, test_raw_access) {
EXPECT_EQ(results.size(), 1);
}
class TestTable : public tables::TablePlugin {
class TestTablePlugin : public tables::TablePlugin {
private:
tables::TableColumns columns() const {
return {{"test_int", "INTEGER"}, {"test_text", "TEXT"}};
@ -50,22 +50,17 @@ class TestTable : public tables::TablePlugin {
};
TEST_F(SQLTests, test_raw_access_context) {
Registry::add<TestTable>("table", "test_table");
auto results = SQL::selectAllFrom("test_table");
Registry::add<TestTablePlugin>("table", "test");
auto results = SQL::selectAllFrom("test");
EXPECT_EQ(results.size(), 1);
EXPECT_EQ(results[0]["test_text"], "1");
results = SQL::selectAllFrom("test_table", "test_int", tables::EQUALS, "1");
results = SQL::selectAllFrom("test", "test_int", tables::EQUALS, "1");
EXPECT_EQ(results.size(), 2);
results = SQL::selectAllFrom("test_table", "test_int", tables::EQUALS, "2");
results = SQL::selectAllFrom("test", "test_int", tables::EQUALS, "2");
EXPECT_EQ(results.size(), 2);
EXPECT_EQ(results[0]["test_int"], "0");
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -26,16 +26,15 @@ SQLiteDBInstance getTestDBC() {
SQLiteDBInstance dbc = SQLiteDBManager::getUnique();
char* err = nullptr;
std::vector<std::string> queries = {
"CREATE TABLE test_table ("
"username varchar(30) primary key, "
"age int"
")",
"CREATE TABLE test_table (username varchar(30) primary key, age int)",
"INSERT INTO test_table VALUES (\"mike\", 23)",
"INSERT INTO test_table VALUES (\"matt\", 24)"};
for (auto q : queries) {
sqlite3_exec(dbc.db(), q.c_str(), nullptr, nullptr, &err);
if (err != nullptr) {
throw std::domain_error("Cannot create testing DBC's db.");
throw std::domain_error(std::string("Cannot create testing DBC's db: ") +
err);
}
}
@ -117,31 +116,16 @@ TEST_F(SQLiteUtilTests, test_get_test_db_result_stream) {
TEST_F(SQLiteUtilTests, test_get_query_columns) {
auto dbc = getTestDBC();
std::string query;
Status status;
tables::TableColumns results;
query =
"SELECT hour, minutes, seconds, version, config_md5, config_path, \
pid FROM time JOIN osquery_info";
status = getQueryColumnsInternal(query, results, dbc.db());
std::string query = "SELECT seconds, version FROM time JOIN osquery_info";
auto status = getQueryColumnsInternal(query, results, dbc.db());
ASSERT_TRUE(status.ok());
ASSERT_EQ(7, results.size());
EXPECT_EQ(std::make_pair(std::string("hour"), std::string("INTEGER")),
results[0]);
EXPECT_EQ(std::make_pair(std::string("minutes"), std::string("INTEGER")),
results[1]);
ASSERT_EQ(2, results.size());
EXPECT_EQ(std::make_pair(std::string("seconds"), std::string("INTEGER")),
results[2]);
results[0]);
EXPECT_EQ(std::make_pair(std::string("version"), std::string("TEXT")),
results[3]);
EXPECT_EQ(std::make_pair(std::string("config_md5"), std::string("TEXT")),
results[4]);
EXPECT_EQ(std::make_pair(std::string("config_path"), std::string("TEXT")),
results[5]);
EXPECT_EQ(std::make_pair(std::string("pid"), std::string("INTEGER")),
results[6]);
results[1]);
query = "SELECT hour + 1 AS hour1, minutes + 1 FROM time";
status = getQueryColumnsInternal(query, results, dbc.db());
@ -157,8 +141,3 @@ TEST_F(SQLiteUtilTests, test_get_query_columns) {
ASSERT_FALSE(status.ok());
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -39,8 +39,10 @@ TEST_F(VirtualTableTests, test_tableplugin_columndefinition) {
TEST_F(VirtualTableTests, test_sqlite3_attach_vtable) {
auto table = std::make_shared<sampleTablePlugin>();
table->setName("sample");
//sqlite3* db = nullptr;
//sqlite3_open(":memory:", &db);
// Request a managed "connection".
// This will be a single (potentially locked) instance or a transient
// SQLite database if there is contention and a lock was not requested.
auto dbc = SQLiteDBManager::get();
// Virtual tables require the registry/plugin API to query tables.
@ -67,8 +69,3 @@ TEST_F(VirtualTableTests, test_sqlite3_attach_vtable) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -269,7 +269,7 @@ Status attachTableInternal(const std::string &name,
if (rc == SQLITE_OK || rc == SQLITE_MISUSE) {
auto format =
"CREATE VIRTUAL TABLE temp." + name + " USING " + name + statement;
rc = sqlite3_exec(db, format.c_str(), 0, 0, 0);
rc = sqlite3_exec(db, format.c_str(), nullptr, nullptr, 0);
} else {
LOG(ERROR) << "Error attaching table: " << name << " (" << rc << ")";
}
@ -278,7 +278,7 @@ Status attachTableInternal(const std::string &name,
Status detachTableInternal(const std::string &name, sqlite3 *db) {
auto format = "DROP TABLE IF EXISTS temp." + name;
int rc = sqlite3_exec(db, format.c_str(), 0, 0, 0);
int rc = sqlite3_exec(db, format.c_str(), nullptr, nullptr, 0);
if (rc != SQLITE_OK) {
LOG(ERROR) << "Error detaching table: " << name << " (" << rc << ")";
}

View File

@ -9,6 +9,9 @@ if(APPLE)
${OSQUERY_DARWIN_TABLES}
)
file(GLOB OSQUERY_DARWIN_TABLES_TESTS "*/darwin/tests/*.cpp")
ADD_OSQUERY_TABLE_TEST(${OSQUERY_DARWIN_TABLES_TESTS})
ADD_OSQUERY_LINK(FALSE "-framework CoreFoundation")
ADD_OSQUERY_LINK(FALSE "-framework Security")
ADD_OSQUERY_LINK(FALSE "-framework OpenDirectory")
@ -18,12 +21,18 @@ elseif(FREEBSD)
ADD_OSQUERY_LIBRARY(FALSE osquery_tables_freebsd
${OSQUERY_FREEBSD_TABLES}
)
file(GLOB OSQUERY_FREEBSD_TABLES_TESTS "*/freebsd/tests/*.cpp")
ADD_OSQUERY_TABLE_TEST(${OSQUERY_FREEBSD_TABLES_TESTS})
else()
file(GLOB OSQUERY_LINUX_TABLES "*/linux/*.cpp")
ADD_OSQUERY_LIBRARY(FALSE osquery_tables_linux
${OSQUERY_LINUX_TABLES}
)
file(GLOB OSQUERY_LINUX_TABLES_TESTS "*/linux/tests/*.cpp")
ADD_OSQUERY_TABLE_TEST(${OSQUERY_LINUX_TABLES_TESTS})
if(CENTOS)
# CentOS specific tables
file(GLOB OSQUERY_REDHAT_TABLES "*/centos/*.cpp")
@ -55,6 +64,9 @@ ADD_OSQUERY_LIBRARY(FALSE osquery_tables
${OSQUERY_CROSS_TABLES}
)
file(GLOB OSQUERY_CROSS_TABLES_TESTS "[!u]*/tests/*.cpp")
ADD_OSQUERY_TABLE_TEST(${OSQUERY_CROSS_TABLES_TESTS})
file(GLOB OSQUERY_UTILITY_TABLES "utility/*.cpp")
ADD_OSQUERY_LIBRARY(TRUE osquery_tables_utility
${OSQUERY_UTILITY_TABLES}
@ -65,12 +77,5 @@ ADD_OSQUERY_LIBRARY(FALSE osquery_utils
${OSQUERY_UTILS}
)
ADD_OSQUERY_TEST(FALSE etc_hosts_tests networking/tests/etc_hosts_tests.cpp)
ADD_OSQUERY_TEST(FALSE etc_protocols_tests networking/tests/etc_protocols_tests.cpp)
ADD_OSQUERY_TEST(FALSE yara_tests utils/tests/yara_tests.cpp)
if(APPLE)
ADD_OSQUERY_TEST(FALSE apps_tests system/darwin/tests/apps_tests.cpp)
ADD_OSQUERY_TEST(FALSE certificates_tests system/darwin/tests/certificates_tests.cpp)
ADD_OSQUERY_TEST(FALSE firewall_tests system/darwin/tests/firewall_tests.cpp)
ADD_OSQUERY_TEST(FALSE launchd_tests system/darwin/tests/launchd_tests.cpp)
endif()
file(GLOB OSQUERY_UTILS_TESTS "utils/tests/*.cpp")
ADD_OSQUERY_TEST(FALSE ${OSQUERY_UTILS_TESTS})

View File

@ -28,9 +28,3 @@ TEST_F(EtcHostsTests, test_parse_etc_hosts_content) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -28,9 +28,3 @@ TEST_F(EtcProtocolsTests, test_parse_etc_protocols_content) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -110,8 +110,3 @@ TEST_F(AppsTests, test_sanity_check) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -83,9 +83,3 @@ TEST_F(CACertsTests, test_certificate_properties) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -151,9 +151,3 @@ TEST_F(FirewallTests, test_on_disk_format) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -58,9 +58,3 @@ TEST_F(LaunchdTests, test_parse_launchd_item) {
}
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}

View File

@ -76,8 +76,3 @@ TEST_F(YARATest, test_match_false) {
EXPECT_TRUE(r["count"] == "0");
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -3,7 +3,7 @@
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/