### Install Google Mock Targets Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googlemock/CMakeLists.txt Registers the Google Mock libraries for installation. ```cmake install_project(gmock gmock_main) ``` -------------------------------- ### Install dependencies on Linux Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Install the required Boost and CMake packages using apt-get. ```bash apt-get install libboost-all-dev cmake ``` -------------------------------- ### Build and Install GoogleTest on Unix Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/README.md Compiles the generated build scripts and installs the library to the system directory. ```bash make sudo make install # Install in /usr/local/ by default ``` -------------------------------- ### Example pkg-config file content Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/pkgconfig.md The structure of a generated .pc file for GoogleTest. ```text libdir=/usr/lib64 includedir=/usr/include Name: gtest Description: GoogleTest (without main() function) Version: 1.11.0 URL: https://github.com/google/googletest Libs: -L${libdir} -lgtest -lpthread Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread ``` -------------------------------- ### Install dependencies on OSX Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Commands to install Boost and CMake using MacPorts or Homebrew. ```bash sudo port install boost -no_static ``` ```bash brew install boost cmake ``` -------------------------------- ### Build and install Python wheel Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Commands to clean, build, install, and verify the Python package using a virtual environment. ```bash git clean -fxd && pipx run build python3 -m venv venv && . venv/bin/activate pip install dist/pokerstove-*.whl python src/lib/python/test-python deactivate ``` -------------------------------- ### Define Project and Hermetic Build Setup Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googlemock/CMakeLists.txt Initializes the CMake project and executes the hermetic build setup if the command is defined. ```cmake cmake_minimum_required(VERSION 3.13) project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() ``` -------------------------------- ### Configure Include Directories Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googlemock/CMakeLists.txt Sets up build and install interface include directories for the Google Mock targets. ```cmake string(REPLACE ";" "$" dirs "${gmock_build_include_dirs}") target_include_directories(gmock SYSTEM INTERFACE "$" "$/${CMAKE_INSTALL_INCLUDEDIR}>") target_include_directories(gmock_main SYSTEM INTERFACE "$" "$/${CMAKE_INSTALL_INCLUDEDIR}>") ``` -------------------------------- ### Install SWIG Targets and Support Files Source: https://github.com/andrewprock/pokerstove/blob/master/src/lib/python/CMakeLists.txt Installs the generated SWIG library and associated support files to the designated Python directory. ```cmake install(TARGETS ${PS_TARGET} DESTINATION . COMPONENT python) get_property(_support_files TARGET ${PS_TARGET} PROPERTY SWIG_SUPPORT_FILES) install(FILES "${_support_files}" DESTINATION . COMPONENT python) ``` -------------------------------- ### Configure cross-compilation environment Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/pkgconfig.md Set up build and installation paths for cross-compiling GoogleTest. ```bash mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr .. ``` ```bash make -j install DESTDIR=/home/MYUSER/sysroot ``` ```bash export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes ``` -------------------------------- ### Install Google Test targets Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/CMakeLists.txt Defines the installation rules for the gtest and gtest_main libraries. ```cmake install_project(gtest gtest_main) ``` -------------------------------- ### Install Python dependencies Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Install the necessary system packages for Python and SWIG integration on Ubuntu. ```bash sudo apt install python3 swig ``` -------------------------------- ### Basic gMock Workflow Example Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_cheat_sheet.md Demonstrates the standard lifecycle of a mock object, from creation and default action configuration to expectation setting and verification. ```cpp using ::testing::Return; // #1 TEST(BarTest, DoesThis) { MockFoo foo; // #2 ON_CALL(foo, GetSize()) // #3 .WillByDefault(Return(1)); // ... other default actions ... EXPECT_CALL(foo, Describe(5)) // #4 .Times(3) .WillRepeatedly(Return("Category 5")); // ... other expectations ... EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5 } // #6 ``` -------------------------------- ### testing::Test::SetUp Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/testing.md Performs test fixture setup for an individual test. This method should be overridden in derived classes. ```APIDOC ## virtual void SetUp() ### Description Override this to perform test fixture setup. GoogleTest calls SetUp() before running each individual test. ``` -------------------------------- ### Cross-compilation pkg-config setup Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/pkgconfig.md Configure environment variables to correctly inject the sysroot into pkg-config flags. ```bash export PKG_CONFIG_DIR= export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig ``` -------------------------------- ### Dynamic Test Registration Example Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Implementation of a custom test fixture and dynamic registration loop using a lambda factory. ```c++ class MyFixture : public testing::Test { public: // All of these optional, just like in regular macro usage. static void SetUpTestSuite() { ... } static void TearDownTestSuite() { ... } void SetUp() override { ... } void TearDown() override { ... } }; class MyTest : public MyFixture { public: explicit MyTest(int data) : data_(data) {} void TestBody() override { ... } private: int data_; }; void RegisterMyTests(const std::vector& values) { for (int v : values) { testing::RegisterTest( "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, std::to_string(v).c_str(), __FILE__, __LINE__, // Important to use the fixture type as the return type here. [=]() -> MyFixture* { return new MyTest(v); }); } } ... int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); std::vector values_to_test = LoadValuesFromConfig(); RegisterMyTests(values_to_test); ... return RUN_ALL_TESTS(); } ``` -------------------------------- ### Write tests using the fixture Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/primer.md Example test cases utilizing the QueueTest fixture to verify queue behavior. ```c++ TEST_F(QueueTest, IsEmptyInitially) { EXPECT_EQ(q0_.size(), 0); } TEST_F(QueueTest, DequeueWorks) { int* n = q0_.Dequeue(); EXPECT_EQ(n, nullptr); n = q1_.Dequeue(); ASSERT_NE(n, nullptr); EXPECT_EQ(*n, 1); EXPECT_EQ(q1_.size(), 0); delete n; n = q2_.Dequeue(); ASSERT_NE(n, nullptr); EXPECT_EQ(*n, 2); EXPECT_EQ(q2_.size(), 1); delete n; } ``` -------------------------------- ### Defining Test Functions for Sharding Example Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Example test structure used to demonstrate how GoogleTest distributes work across multiple shards. ```cpp TEST(A, V) TEST(A, W) TEST(B, X) TEST(B, Y) TEST(B, Z) ``` -------------------------------- ### Implementing and using a predicate-formatter Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/assertions.md Example of defining a custom predicate-formatter and using it within an EXPECT_PRED_FORMAT2 assertion. ```cpp // Returns the smallest prime common divisor of m and n, // or 1 when m and n are mutually prime. int SmallestPrimeCommonDivisor(int m, int n) { ... } // Returns true if m and n have no common divisors except 1. bool MutuallyPrime(int m, int n) { ... } // A predicate-formatter for asserting that two integers are mutually prime. testing::AssertionResult AssertMutuallyPrime(const char* m_expr, const char* n_expr, int m, int n) { if (MutuallyPrime(m, n)) return testing::AssertionSuccess(); return testing::AssertionFailure() << m_expr << " and " << n_expr << " (" << m << " and " << n << ") are not mutually prime, " << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); } ... const int a = 3; const int b = 4; const int c = 10; ... EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails ``` -------------------------------- ### Implement a test fixture class Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/primer.md A concrete implementation of a test fixture class inheriting from ::testing::Test, demonstrating the use of SetUp. ```c++ class QueueTest : public ::testing::Test { protected: void SetUp() override { // q0_ remains empty q1_.Enqueue(1); q2_.Enqueue(2); q2_.Enqueue(3); } // void TearDown() override {} Queue q0_; Queue q1_; Queue q2_; }; ``` -------------------------------- ### Declare a function for testing Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/primer.md Example function declaration for a factorial calculation. ```c++ int Factorial(int n); // Returns the factorial of n ``` -------------------------------- ### Example failure message for EXPECT_THAT Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/assertions.md Shows the output format when an EXPECT_THAT assertion fails. ```text Value of: value1 Actual: "Hi, world!" Expected: starts with "Hello" ``` -------------------------------- ### Generated XML Report Example Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md A complete example of an XML report generated from the provided test definitions. ```xml ... ... ``` -------------------------------- ### Example GoogleTest Definitions Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Sample C++ test definitions used to demonstrate XML report generation. ```cpp TEST(MathTest, Addition) { ... } TEST(MathTest, Subtraction) { ... } TEST(LogicTest, NonContradiction) { ... } ``` -------------------------------- ### testing::Test::SetUpTestSuite Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/testing.md Performs shared setup for all tests in the test suite. This static method is invoked by GoogleTest before the first test in the suite runs. ```APIDOC ## static void SetUpTestSuite() ### Description Performs shared setup for all tests in the test suite. GoogleTest calls SetUpTestSuite() before running the first test in the test suite. ``` -------------------------------- ### Match Objects with FieldsAre Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/matchers.md Examples of using FieldsAre to match tuples and aggregate structures. ```cpp std::tuple my_tuple{7, "hello world"}; EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello"))); struct MyStruct { int value = 42; std::string greeting = "aloha"; }; MyStruct s; EXPECT_THAT(s, FieldsAre(42, "aloha")); ``` -------------------------------- ### Using matchers in expectations Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_for_dummies.md Examples of using matchers to define expected arguments, including specific values, wildcards, and predicates. ```cpp // Expects the turtle to move forward by 100 units. EXPECT_CALL(turtle, Forward(100)); ``` ```cpp using ::testing::_; ... // Expects that the turtle jumps to somewhere on the x=50 line. EXPECT_CALL(turtle, GoTo(50, _)); ``` ```cpp using ::testing::Ge; ... // Expects the turtle moves forward by at least 100. EXPECT_CALL(turtle, Forward(Ge(100))); ``` ```cpp // Expects the turtle to move forward. EXPECT_CALL(turtle, Forward); // Expects the turtle to jump somewhere. EXPECT_CALL(turtle, GoTo); ``` -------------------------------- ### Implement Per-Test-Suite Setup and Teardown Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Define static methods in a test fixture to manage shared resources that persist across all tests in the suite. ```c++ class FooTest : public testing::Test { protected: // Per-test-suite set-up. // Called before the first test in this test suite. // Can be omitted if not needed. static void SetUpTestSuite() { shared_resource_ = new ...; // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`, // reallocation should be prevented because `SetUpTestSuite()` may be called // in subclasses of FooTest and lead to memory leak. // // if (shared_resource_ == nullptr) { // shared_resource_ = new ...; // } } // Per-test-suite tear-down. // Called after the last test in this test suite. // Can be omitted if not needed. static void TearDownTestSuite() { delete shared_resource_; shared_resource_ = nullptr; } // You can define per-test set-up logic as usual. void SetUp() override { ... } // You can define per-test tear-down logic as usual. void TearDown() override { ... } // Some expensive resource shared by all tests. static T* shared_resource_; }; T* FooTest::shared_resource_ = nullptr; TEST_F(FooTest, Test1) { ... you can refer to shared_resource_ here ... } TEST_F(FooTest, Test2) { ... you can refer to shared_resource_ here ... } ``` -------------------------------- ### Example expectation with return values Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_for_dummies.md Demonstrates a specific expectation sequence where a method returns different values over multiple calls. ```cpp using ::testing::Return; ... EXPECT_CALL(turtle, GetX()) .Times(5) .WillOnce(Return(100)) .WillOnce(Return(150)) .WillRepeatedly(Return(200)); ``` -------------------------------- ### Example XML output for custom properties Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md The resulting XML structure after recording custom properties during a test execution. ```xml ... ... ``` -------------------------------- ### Sample JSON Report Output Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md An example of the generated JSON report based on the provided C++ test cases. ```json { "tests": 3, "failures": 1, "errors": 0, "time": "0.035s", "timestamp": "2011-10-31T18:52:42Z", "name": "AllTests", "testsuites": [ { "name": "MathTest", "tests": 2, "failures": 1, "errors": 0, "time": "0.015s", "testsuite": [ { "name": "Addition", "file": "test.cpp", "line": 1, "status": "RUN", "time": "0.007s", "classname": "", "failures": [ { "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", "type": "" }, { "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", "type": "" } ] }, { "name": "Subtraction", "file": "test.cpp", "line": 2, "status": "RUN", "time": "0.005s", "classname": "" } ] }, { "name": "LogicTest", "tests": 1, "failures": 0, "errors": 0, "time": "0.005s", "testsuite": [ { "name": "NonContradiction", "file": "test.cpp", "line": 3, "status": "RUN", "time": "0.005s", "classname": "" } ] } ] } ``` -------------------------------- ### Generate CMake Package Configuration Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/CMakeLists.txt Creates and installs package version and configuration files to support find_package integration. ```cmake # Create the CMake package file descriptors. if (INSTALL_GTEST) include(CMakePackageConfigHelpers) set(targets_export_name ${cmake_package_name}Targets CACHE INTERNAL "") set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated" CACHE INTERNAL "") set(cmake_files_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${cmake_package_name}") set(version_file "${generated_dir}/${cmake_package_name}ConfigVersion.cmake") write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion) install(EXPORT ${targets_export_name} COMPONENT "${PROJECT_NAME}" NAMESPACE ${cmake_package_name}:: DESTINATION ${cmake_files_install_dir}) set(config_file "${generated_dir}/${cmake_package_name}Config.cmake") configure_package_config_file("${gtest_SOURCE_DIR}/cmake/Config.cmake.in" "${config_file}" INSTALL_DESTINATION ${cmake_files_install_dir}) install(FILES ${version_file} ${config_file} COMPONENT "${PROJECT_NAME}" DESTINATION ${cmake_files_install_dir}) endif() ``` -------------------------------- ### Demonstrate Test Name Collision with Underscores Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/faq.md Example showing how different test suite and test name combinations can result in the same generated class name. ```c++ TEST(Time, Flies_Like_An_Arrow) { ... } TEST(Time_Flies, Like_An_Arrow) { ... } ``` -------------------------------- ### Include Hermetic Build Utilities Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googlemock/CMakeLists.txt Conditionally includes and executes hermetic build setup functions if available. ```cmake # Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL) if (COMMAND pre_project_set_up_hermetic_build) # Google Test also calls hermetic setup functions from add_subdirectory, # although its changes will not affect things at the current scope. pre_project_set_up_hermetic_build() endif() ``` -------------------------------- ### Define a Global Test Environment Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Subclass testing::Environment and override SetUp and TearDown methods to manage global resources. ```c++ class Environment : public ::testing::Environment { public: ~Environment() override {} // Override this to define how to set up the environment. void SetUp() override {} // Override this to define how to tear down the environment. void TearDown() override {} }; ``` -------------------------------- ### Example of interleaved test suite execution Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/faq.md Demonstrates a scenario where test suite execution order could conflict if tests were ordered by name rather than suite. ```c++ TEST_F(FooTest, AbcDeathTest) { ... } TEST_F(FooTest, Uvw) { ... } TEST_F(BarTest, DefDeathTest) { ... } TEST_F(BarTest, Xyz) { ... } ``` -------------------------------- ### ScopedTrace Usage Example Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/testing.md Instantiate ScopedTrace to include custom trace information in failure messages within the current scope. ```cpp testing::ScopedTrace trace("file.cc", 123, "message"); ``` -------------------------------- ### Create project directory Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/quickstart-cmake.md Initializes a new project directory and enters it. ```bash $ mkdir my_project && cd my_project ``` -------------------------------- ### Access Private Members via FRIEND_TEST Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Example showing the declaration of FRIEND_TEST in a header and its usage in a corresponding test file. ```c++ // foo.h class Foo { ... private: FRIEND_TEST(FooTest, BarReturnsZeroOnNull); int Bar(void* x); }; // foo_test.cc ... TEST(FooTest, BarReturnsZeroOnNull) { Foo foo; EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). } ``` -------------------------------- ### Example Failure Output with Scoped Trace Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md The resulting output format when an assertion fails within a scope defined by SCOPED_TRACE. ```none path/to/foo_test.cc:11: Failure Value of: Bar(n) Expected: 1 Actual: 2 Google Test trace: path/to/foo_test.cc:17: A path/to/foo_test.cc:12: Failure Value of: Bar(n + 1) Expected: 2 Actual: 3 ``` -------------------------------- ### Create a Bazel workspace directory Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/quickstart-bazel.md Initialize a new directory to serve as the Bazel workspace. ```bash $ mkdir my_workspace && cd my_workspace ``` -------------------------------- ### Implement Scoped Trace in Test Sub-routines Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Example demonstrating how SCOPED_TRACE identifies which invocation of a sub-routine caused an assertion failure. ```c++ 10: void Sub1(int n) { 11: EXPECT_EQ(Bar(n), 1); 12: EXPECT_EQ(Bar(n + 1), 2); 13: } 14: 15: TEST(FooTest, Bar) { 16: { 17: SCOPED_TRACE("A"); // This trace point will be included in 18: // every failure in this scope. 19: Sub1(1); 20: } 21: // Now it won't. 22: Sub1(9); 23: } ``` -------------------------------- ### Skip test execution with GTEST_SKIP Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Use GTEST_SKIP() to abort test execution at runtime in test cases or SetUp methods. ```c++ TEST(SkipTest, DoesSkip) { GTEST_SKIP() << "Skipping single test"; EXPECT_EQ(0, 1); // Won't fail; it won't be executed } class SkipFixture : public ::testing::Test { protected: void SetUp() override { GTEST_SKIP() << "Skipping all tests for this fixture"; } }; // Tests for SkipFixture won't be executed. TEST_F(SkipFixture, SkipsOneTest) { EXPECT_EQ(5, 7); // Won't fail } ``` -------------------------------- ### Build solution on Windows Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Menu path to build the solution within Visual Studio. ```text Menu->Build->Build Solution ``` -------------------------------- ### Build and run tests Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/CONTRIBUTING.md Compile the project and execute the test suite using make. ```bash make ``` ```bash make test ``` -------------------------------- ### Initialize CMake Project Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/CMakeLists.txt Sets the minimum required CMake version and initializes the project with CXX and C language support. ```cmake cmake_minimum_required(VERSION 3.13) project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() ``` -------------------------------- ### Mock Failure Output Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_for_dummies.md Example of the error message generated when an expectation is not met. ```text path/to/my_test.cc:119: Failure Actual function call count doesn't match this expectation: Actually: never called; Expected: called at least once. Stack trace: ... ``` -------------------------------- ### Meaningful const modifiers Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_faq.md Examples where const modifiers on pointers or references are significant. ```cpp void Bar(int* p); // Neither p nor *p is const. void Bar(const int* p); // p is not const, but *p is. ``` -------------------------------- ### Configure CMakeLists.txt Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/quickstart-cmake.md Defines the project requirements and fetches GoogleTest using the FetchContent module. ```cmake cmake_minimum_required(VERSION 3.14) project(my_project) # GoogleTest requires at least C++14 set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) include(FetchContent) FetchContent_Declare( googletest URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip ) # For Windows: Prevent overriding the parent project's compiler/linker settings set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) FetchContent_MakeAvailable(googletest) ``` -------------------------------- ### Build PokerStove on Linux Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Commands to clone the repository, configure the build with CMake, and compile the project. ```bash git clone https://github.com/andrewprock/pokerstove.git cmake -DCMAKE_BUILD_TYPE=Release -S \. -B build cmake --build build --target all test -j 4 ``` -------------------------------- ### Enable Testing Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/CMakeLists.txt Initializes the testing framework for the project. ```cmake enable_testing() ``` -------------------------------- ### Build and run the test Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/quickstart-bazel.md Command to execute the test using Bazel with C++14 standard optimization. ```bash my_workspace$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured). INFO: Found 1 test target... INFO: From Testing //:hello_test: ==================== Test output for //:hello_test: Running main() from gmock_main.cc [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from HelloTest [ RUN ] HelloTest.BasicAssertions [ OK ] HelloTest.BasicAssertions (0 ms) [----------] 1 test from HelloTest (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (0 ms total) [ PASSED ] 1 test. ================================================================================ Target //:hello_test up-to-date: bazel-bin/hello_test INFO: Elapsed time: 4.190s, Critical Path: 3.05s INFO: 27 processes: 8 internal, 19 linux-sandbox. INFO: Build completed successfully, 27 total actions //:hello_test PASSED in 0.1s INFO: Build completed successfully, 27 total actions ``` -------------------------------- ### Configure build directory with CMake Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/CONTRIBUTING.md Initialize a build directory and configure CMake to enable tests for both Google Test and Google Mock. ```bash mkdir mybuild cd mybuild cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} ``` -------------------------------- ### Clone and Configure GoogleTest with CMake Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/README.md Initializes the build environment by cloning the repository and generating native build scripts. ```bash git clone https://github.com/google/googletest.git -b v1.14.0 cd googletest # Main directory of the cloned repository. mkdir build # Create a directory to hold the build output. cd build cmake .. # Generate native build scripts for GoogleTest. ``` -------------------------------- ### MSVC warning examples Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_faq.md Compiler warnings encountered when overriding virtual functions with const parameters in MSVC. ```shell warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier ``` ```shell warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers ``` -------------------------------- ### Generate Python Initialization and Build Paths Source: https://github.com/andrewprock/pokerstove/blob/master/src/lib/python/CMakeLists.txt Configures output paths and generates the __init__.py file to ensure the Python wrapper is correctly importable. ```cmake set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/python/${PYTHON_PROJECT}) message(STATUS "PYTHON_PROJECT ${PYTHON_PROJECT_DIR}") message(STATUS "swig_add_library OUTPUT_DIR ${PYTHON_PROJECT_DIR}/${PS_TARGET}") file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/__init__.py CONTENT "__version__ = \"${PROJECT_VERSION}\"\nfrom .pokerstove import *\n") ``` -------------------------------- ### Create a C++ test file Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/quickstart-bazel.md A basic GoogleTest source file demonstrating assertions. ```cpp #include // Demonstrate some basic assertions. TEST(HelloTest, BasicAssertions) { // Expect two strings not to be equal. EXPECT_STRNE("hello", "world"); // Expect equality. EXPECT_EQ(7 * 6, 42); } ``` -------------------------------- ### Define and Use a Custom Matcher Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/matchers.md Demonstrates creating a custom matcher with the MATCHER macro and using it with Pointwise. ```cpp MATCHER(FooEq, "") { return std::get<0>(arg).Equals(std::get<1>(arg)); } ... EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); ``` -------------------------------- ### TEST_F(TestFixtureName, TestName) Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/testing.md Defines an individual test that utilizes a test fixture class for shared setup and teardown. ```APIDOC ## TEST_F(TestFixtureName, TestName) ### Description Defines an individual test named TestName that uses the test fixture class TestFixtureName. The test suite name is automatically set to TestFixtureName. ### Parameters - **TestFixtureName** (identifier) - Required - The name of the test fixture class; must be a valid C++ identifier without underscores. - **TestName** (identifier) - Required - The name of the individual test; must be a valid C++ identifier without underscores. ``` -------------------------------- ### Build and run tests via command line Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/quickstart-cmake.md Commands to configure, build, and execute the test suite using CMake and ctest. ```bash my_project$ cmake -S . -B build -- The C compiler identification is GNU 10.2.1 -- The CXX compiler identification is GNU 10.2.1 ... -- Build files have been written to: .../my_project/build my_project$ cmake --build build Scanning dependencies of target gtest ... [100%] Built target gmock_main my_project$ cd build && ctest Test project .../my_project/build Start 1: HelloTest.BasicAssertions 1/1 Test #1: HelloTest.BasicAssertions ........ Passed 0.00 sec 100% tests passed, 0 tests failed out of 1 Total Test time (real) = 0.01 sec ``` -------------------------------- ### Define a sample Queue interface Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/primer.md A template class definition for a FIFO queue used as the subject for testing examples. ```c++ template // E is the element type. class Queue { public: Queue(); void Enqueue(const E& element); E* Dequeue(); // Returns NULL if the queue is empty. size_t size() const; ... }; ``` -------------------------------- ### Initialize Google Test Utilities Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/CMakeLists.txt Includes internal utility scripts and configures the compiler and linker settings. ```cmake # Define helper functions and macros used by Google Test. include(cmake/internal_utils.cmake) config_compiler_and_linker() # Defined in internal_utils.cmake. # Needed to set the namespace for both the export targets and the # alias libraries set(cmake_package_name GTest CACHE INTERNAL "") ``` -------------------------------- ### Configure System-Specific Linking Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/CMakeLists.txt Handles additional linking requirements for specific platforms like QNX. ```cmake if(CMAKE_SYSTEM_NAME MATCHES "QNX") target_link_libraries(gtest PUBLIC regex) endif() target_link_libraries(gtest_main PUBLIC gtest) ``` -------------------------------- ### Conditional block for internal tests Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/CMakeLists.txt Starts a conditional block for building internal Google Test suites when gtest_build_tests is enabled. ```cmake if (gtest_build_tests) # This must be set in the root directory for the tests to be run by ``` -------------------------------- ### Build Directory and Subdirectory Configuration Source: https://github.com/andrewprock/pokerstove/blob/master/CMakeLists.txt Sets output directories and includes project subdirectories for building libraries, Python bindings, and executables. ```cmake # Also search for includes in PROJECT_BINARY_DIR to find config.h. include_directories("${PROJECT_BINARY_DIR}") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) # add the actual code include_directories(src/lib) add_subdirectory(src/lib) # This controls whether or not we are building the python # binaries, and possibly the wheel file. # TODO: add a separate option for building the wheel vs. python if(BUILD_PYTHON OR BUILD_WHEEL) add_subdirectory(src/lib/python) endif() if(NOT BUILD_WHEEL) # none of these are needed in the wheel file add_subdirectory(src/programs) add_subdirectory(src/ext/googletest) # Add make install functionality install(TARGETS peval) install(TARGETS penum) install(TARGETS ps-colex) install(TARGETS ps-eval) install(TARGETS ps-lut) endif() ``` -------------------------------- ### Set Include Directories Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googlemock/CMakeLists.txt Defines and adds the necessary header directories for Google Mock and Google Test to the search path. ```cmake set(gmock_build_include_dirs "${gmock_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}" "${gtest_SOURCE_DIR}/include" # This directory is needed to build directly from Google Test sources. "${gtest_SOURCE_DIR}") include_directories(${gmock_build_include_dirs}) ``` -------------------------------- ### Construct and Print CardSet Objects Source: https://github.com/andrewprock/pokerstove/blob/master/doc/peval.md Demonstrates creating CardSet instances using individual card objects or string representations and printing them to the console. ```cpp #include #include using pokerstove::CardSet; using pokerstove::Card; using pokerstove::Rank; using pokerstove::Suit; int main(void) { CardSet big_slick(Card(Rank('A'),Suit('s')), Card(Rank('K'),Suit('s'))); std::cout << big_slick.str() << std::endl; CardSet dead_mans_hand("AcAs8d8hJs"); std::cout << dead_mans_hand.str() << std::endl; } ``` -------------------------------- ### Configure SWIG and Python Environment Source: https://github.com/andrewprock/pokerstove/blob/master/src/lib/python/CMakeLists.txt Initializes SWIG and Python dependencies, setting necessary flags for 64-bit systems and Python 3 integration. ```cmake cmake_minimum_required(VERSION 3.18) # find swig and python and configure them set(CMAKE_SWIG_FLAGS) set(UseSWIG_MODULE_VERSION 2) find_package(SWIG REQUIRED) include(UseSWIG) if(UNIX AND NOT APPLE) list(APPEND CMAKE_SWIG_FLAGS "-DSWIGWORDSIZE64") endif() find_package(Python3 REQUIRED COMPONENTS Interpreter Development.Module) list(APPEND CMAKE_SWIG_FLAGS "-DPY3") ``` -------------------------------- ### Defining a Multi-parameter Action with ACTION_Pk Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/actions.md Defines a parameterized action that accepts k parameters and executes the provided statements. ```cpp ACTION_Pk(Foo, p1, ..., pk) { statements; } ``` -------------------------------- ### Project Initialization and Compiler Settings Source: https://github.com/andrewprock/pokerstove/blob/master/CMakeLists.txt Sets the minimum CMake version, project metadata, and global C++ compiler flags. ```cmake cmake_minimum_required(VERSION 3.5) project( pokerstove VERSION "1.2" LANGUAGES CXX) #include(GNUInstallDirs) # set up some global compiler opions set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-register") add_definitions("-fPIC") enable_testing() ``` -------------------------------- ### Example of invalid proto descriptor error message Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/faq.md This error indicates that a .proto file contains an unqualified type reference that must be corrected. ```text ... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto": ... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined. ``` -------------------------------- ### Build project with Python support Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Configure and build the project using CMake with the Python build flag enabled. ```bash cmake -DCMAKE_BUILD_TYPE=Release -S \. -B build -DBUILD_PYTHON=ON cmake --build build --target all test -j 16 ``` -------------------------------- ### Incorrect loop-based expectation definition Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_for_dummies.md Shows an example where sticky expectations cause an upper bound violation error when called multiple times. ```cpp using ::testing::Return; ... for (int i = n; i > 0; i--) { EXPECT_CALL(turtle, GetX()) .WillOnce(Return(10*i)); } ``` -------------------------------- ### GoogleTest CMake Configuration Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/CMakeLists.txt Initializes the project, sets versioning, and defines build options for GoogleTest and GoogleMock. ```cmake cmake_minimum_required(VERSION 3.13) project(googletest-distribution) set(GOOGLETEST_VERSION 1.14.0) if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) set(CMAKE_CXX_EXTENSIONS OFF) endif() enable_testing() include(CMakeDependentOption) include(GNUInstallDirs) #Note that googlemock target already builds googletest option(BUILD_GMOCK "Builds the googlemock subproject" ON) option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF) if(BUILD_GMOCK) add_subdirectory( googlemock ) else() add_subdirectory( googletest ) endif() ``` -------------------------------- ### Instantiate Test Suites with Parameters Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/advanced.md Use INSTANTIATE_TEST_SUITE_P at global or namespace scope to provide parameter values to the test suite. ```c++ INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, FooTest, testing::Values("meeny", "miny", "moe")); ``` ```c++ constexpr absl::string_view kPets[] = {"cat", "dog"}; INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets)); ``` -------------------------------- ### Mocking a method with a const parameter in MSVC Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_faq.md Example of a mock class definition that may trigger MSVC warnings due to const parameter qualifiers. ```cpp class Foo { ... virtual void Bar(const int i) = 0; }; class MockFoo : public Foo { ... MOCK_METHOD(void, Bar, (const int i), (override)); }; ``` -------------------------------- ### Integrate GoogleTest using FetchContent Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/README.md Use FetchContent to download and include GoogleTest during the CMake configure step. Requires CMake 3.14 or later. ```cmake include(FetchContent) FetchContent_Declare( googletest # Specify the commit you depend on and update it regularly. URL https://github.com/google/googletest/archive/5376968f6948923e2411081fd9372e71a59d8e77.zip ) # For Windows: Prevent overriding the parent project's compiler/linker settings set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) FetchContent_MakeAvailable(googletest) # Now simply link against gtest or gtest_main as needed. Eg add_executable(example example.cpp) target_link_libraries(example gtest_main) add_test(NAME example_test COMMAND example) ``` -------------------------------- ### GTEST_SKIP Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/testing.md A macro used to prevent further test execution at runtime. It can be invoked within test cases, SetUp methods of test fixtures, or global test environments. ```APIDOC ## GTEST_SKIP ### Description Prevents further test execution at runtime. When used in a global environment, it skips all tests; when used in a test fixture, it skips the corresponding test suite. ### Usage `GTEST_SKIP() << "Optional custom message";` ``` -------------------------------- ### Troubleshoot missing pkg-config files Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/pkgconfig.md Set the PKG_CONFIG_PATH environment variable to point to the directory containing the .pc files. ```bash export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig ``` -------------------------------- ### Derive a test fixture from a base class in C++ Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/faq.md Use a base class to hold shared logic and override SetUp and TearDown in derived classes to extend functionality. Ensure base class methods are called within the derived overrides. ```c++ // Defines a base test fixture. class BaseTest : public ::testing::Test { protected: ... }; // Derives a fixture FooTest from BaseTest. class FooTest : public BaseTest { protected: void SetUp() override { BaseTest::SetUp(); // Sets up the base fixture first. ... additional set-up work ... } void TearDown() override { ... clean-up work for FooTest ... BaseTest::TearDown(); // Remember to tear down the base fixture // after cleaning up FooTest! } ... functions and variables for FooTest ... }; // Tests that use the fixture FooTest. TEST_F(FooTest, Bar) { ... } TEST_F(FooTest, Baz) { ... } ... additional fixtures derived from BaseTest ... ``` -------------------------------- ### CMake Configuration for ps-lut Source: https://github.com/andrewprock/pokerstove/blob/master/src/programs/ps-lut/CMakeLists.txt Defines the project name, creates the ps-lut executable from main.cpp, and links the required peval and Boost libraries. ```cmake project(eval) add_executable(ps-lut main.cpp) target_link_libraries(ps-lut peval ${Boost_LIBRARIES} ) ``` -------------------------------- ### Configure Shared Library and Executable Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googletest/CMakeLists.txt Builds GoogleTest as a shared library and configures a test executable to link against it. ```cmake cxx_shared_library(gtest_dll "${cxx_default}" src/gtest-all.cc src/gtest_main.cc) cxx_executable_with_flags(gtest_dll_test_ "${cxx_default}" gtest_dll test/gtest_all_test.cc) set_target_properties(gtest_dll_test_ PROPERTIES COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") ``` -------------------------------- ### Test Python integration Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Run the Python test script from the build directory by setting the PYTHONPATH. ```bash PYTHONPATH=build/python/pokerstove/ ./src/lib/python/test-python ``` -------------------------------- ### Demonstrate default action behavior Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/gmock_for_dummies.md Shows that after WillOnce clauses are exhausted, the mock reverts to the default action for the return type. ```cpp using ::testing::Return; ... EXPECT_CALL(turtle, GetY()) .Times(4) .WillOnce(Return(100)); ``` -------------------------------- ### Configure CMake for GoogleTest Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/quickstart-cmake.md Add testing support, define the executable, and link against GTest::gtest_main. ```cmake enable_testing() add_executable( hello_test hello_test.cc ) target_link_libraries( hello_test GTest::gtest_main ) include(GoogleTest) gtest_discover_tests(hello_test) ``` -------------------------------- ### INSTANTIATE_TEST_SUITE_P Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/testing.md Instantiates a value-parameterized test suite defined with TEST_P. It requires a unique instantiation name, the test suite name, and a parameter generator. ```APIDOC ## INSTANTIATE_TEST_SUITE_P ### Description Instantiates a value-parameterized test suite. The instantiation name is used to distinguish between multiple instantiations of the same test suite. ### Signature INSTANTIATE_TEST_SUITE_P(InstantiationName, TestSuiteName, param_generator) INSTANTIATE_TEST_SUITE_P(InstantiationName, TestSuiteName, param_generator, name_generator) ### Parameters - **InstantiationName** (string) - A unique name for the instantiation. - **TestSuiteName** (string) - The name of the test suite defined with TEST_P. - **param_generator** (function) - A GoogleTest-provided generator (e.g., Range, Values, ValuesIn, Bool, Combine). - **name_generator** (function, optional) - A functor that generates custom test name suffixes. ``` -------------------------------- ### Configure Google Mock Test Environment Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/googlemock/CMakeLists.txt Enables testing and sets compiler options for MINGW or CYGWIN environments when gmock_build_tests is enabled. ```cmake if (gmock_build_tests) # This must be set in the root directory for the tests to be run by # 'make test' or ctest. enable_testing() if (MINGW OR CYGWIN) add_compile_options("-Wa,-mbig-obj") endif() ``` -------------------------------- ### testing::InitGoogleTest Source: https://github.com/andrewprock/pokerstove/blob/master/src/ext/googletest/docs/reference/testing.md Initializes the GoogleTest framework. This must be called before running tests to parse command-line flags. ```APIDOC ## void testing::InitGoogleTest(int* argc, char** argv) ## void testing::InitGoogleTest(int* argc, wchar_t** argv) ## void testing::InitGoogleTest() ### Description Initializes GoogleTest. This must be called before calling RUN_ALL_TESTS(). It parses the command line for flags recognized by GoogleTest, removing them from argv and decrementing argc. ### Parameters - **argc** (int*) - Optional - Pointer to the number of command line arguments. - **argv** (char** or wchar_t**) - Optional - Array of command line arguments. ``` -------------------------------- ### Execute ps-eval help Source: https://github.com/andrewprock/pokerstove/blob/master/README.md Display the help message for the ps-eval command-line tool. ```bash pokerstove/build $ ./bin/ps-eval Allowed options: -? [ --help ] produce help message -g [ --game ] arg (=h) game to use for evaluation -b [ --board ] arg community cards for he/o/o8 -h [ --hand ] arg a hand for evaluation -q [ --quiet ] produce no output For the --game option, one of the follwing games may be specified. h hold'em o omaha/8 O omaha high r razz s stud e stud/8 q stud high/low no qualifier d draw high l lowball (A-5) k Kansas City lowball (2-7) t triple draw lowball (2-7) T triple draw lowball (A-5) b badugi 3 three-card poker examples: ps-eval acas ps-eval AcAs Kh4d --board 5c8s9h ps-eval AcAs Kh4d --board 5c8s9h ps-eval --game l 7c5c4c3c2c ps-eval --game k 7c5c4c3c2c ps-eval --game kansas-city-lowball 7c5c4c3c2c ```