Lecture 16: GoogleTest Tutorial

Credit: GoogleTest from Google, CNOCycle/cpp_tutorial by E. Chen

Installation

以下為安裝 GoogleTest 的懶人包,詳細安裝方式請參考 Quickstart: Building with CMake

Download GoogleTest

release v1.11.0 release note assets

  • 解壓縮到你的 vscode 目錄下,並打開 vscode
    • 可以在 Explorer 內右鍵,選擇 Reveal in File ExplorerReveal in Finder 來打開現在 vscode 的目錄

(Optional) Install CMake

如果自己的電腦上沒有安裝 CMake,可以從 Download | CMake 下載自己電腦的安裝檔後安裝。

  • 若是 windows,要記得選 Add CMake to the system PATH for all users ,並重新開啟 vscode,才能讓 vscode 的 terminal 讀到 cmake 指令。

Build GoogleTest

打開 vscode 的 Terminal,輸入以下指令,將 GoogleTest 安裝到你的 vscode 目錄下

Windows (mingw)

cd googletest-release-1.11.0
mkdir build
cd build
cmake -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX="../../gtest" ..
mingw32-make -j
mingw32-make -j install

Linux & WSL

sudo apt update
sudo apt install -y cmake
cd googletest-release-1.11.0
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX=../../gtest ..
make -j
make install

macOS

  • Install brew first here
brew update
brew install cmake
cd googletest-release-1.11.0
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX=../../gtest ..
make -j
make install

Configure VSCode for GoogleTest

可以直接參考以下設定,設定好之後,就可以使用 VSCode 去編譯 GoogleTest

  • Windows/Linux:
    • Compile: Ctrl + Shift + B
    • Debug: F5
  • macOS:
    • Compile: Cmd + Shift + B
    • Debug: F5

Windows (MinGW)

.vscode/c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "./gtest/include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\\Users\\user\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gcc.exe",
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-gcc-x64",
            "compilerArgs": []
        }
    ],
    "version": 4
}

.vscode/launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++.exe - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\Users\\user\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++.exe build active file"
        }
    ]
}

.vscode/tasks.json

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: g++.exe build active file",
			"command": "C:\\Users\\user\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
			"args": [
				"-fdiagnostics-color=always",
				"-std=c++17",
				"-I./gtest/include",
				"-L./gtest/lib",
				"-lgtest_main",
				"-lgtest",
				"-pthread",
				"-g",
				"${file}",
				"-o",
				"${fileDirname}\\${fileBasenameNoExtension}.exe"
			],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"detail": "compiler: C:\\Users\\user\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe"
		}
	]
}

Linux & WSL

.vscode/c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "./gtest/include"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c17",
            "cppStandard": "c++17"
        }
    ],
    "version": 4
}

.vscode/launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++ - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}

.vscode/tasks.json

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: g++ build active file",
			"command": "/usr/bin/g++",
			"args": [
				"-fdiagnostics-color=always",
				"-std=c++17",
				"-I./gtest/include",
				"-L./gtest/lib",
				"-lgtest_main",
				"-lgtest",
				"-pthread",
				"-g",
				"${file}",
				"-o",
				"${fileDirname}/${fileBasenameNoExtension}"
			],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"detail": "compiler: /usr/bin/g++"
		}
	]
}

macOS

.vscode/c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**",
                "./gtest/include"
            ],
            "defines": [],
            "macFrameworkPath": [
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
            ],
            "compilerPath": "/usr/bin/clang++",
            "cStandard": "c17",
            "cppStandard": "c++17"
        }
    ],
    "version": 4
}

.vscode/launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "clang++ - build and debug active file",
            "type": "lldb",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [
                "-arg1",
                "-arg2"
            ],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb",
            "preLaunchTask": "C/C++: clang++ build active file"
        }
    ]
}

.vscode/settings.json

{
    "C_Cpp.default.cppStandard": "c++17"
}

.vscode/tasks.json

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "shell",
			"label": "C/C++: clang++ build active file",
			"command": "/usr/bin/clang++",
			"args": [
				"-fdiagnostics-color=always",
				"-std=c++17",
				"-stdlib=libc++",
				"-I./gtest/include",
				"-L./gtest/lib",
				"-lgtest_main",
				"-lgtest",
				"-pthread",
				"-g",
				"${file}",
				"-o",
				"${fileDirname}/${fileBasenameNoExtension}"
			],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"detail": "Compiler: /usr/bin/clang++"
		}
	]
}

Hello GoogleTest

Ref: Quickstart: Building with CMake

#include <gtest/gtest.h>

// 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);
}
Running main() from /Users/stevenokm/waste/projects/googletest-release-1.11.0/googletest/src/gtest_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. 

Code Structure

Ref: Testing Reference

TEST

TEST(TestSuiteName, TestName) {
  ... statements ...
}

Defines an individual test named TestName in the test suite TestSuiteName, consisting of the given statements.

Both arguments TestSuiteName and TestName must be valid C++ identifiers and must not contain underscores (_). Tests in different test suites can have the same individual name.

The statements within the test body can be any code under test. Assertions used within the test body determine the outcome of the test.

Assert & Expect

GoogleTest 提供了兩個新的測試模式,Assert 和 Expect,用來檢查測試結果是否正確。

Assert

Assert 的意思是只要敘述結果錯誤,該測試就會立刻失敗,而不會繼續執行下去。

Expect

Expect 的意思是檢查敘述結果是否正確,如果不正確,該測試會失敗,但是繼續執行下去。

Example: different of Assert & Expect

#include <gtest/gtest.h>

// Demonstrate some Assert assertions.
TEST(HelloTest, AssertAssertions)
{
    // Assert two strings to be equal.
    ASSERT_STREQ("hello", "world");
    // Assert non-equality.
    ASSERT_NE(7 * 6, 42);
}

// Demonstrate some Expect assertions.
TEST(HelloTest, ExpectAssertions)
{
    // Expect two strings to be equal.
    EXPECT_STREQ("hello", "world");
    // Expect non-equality.
    EXPECT_NE(7 * 6, 42);
}
Running main() from /Users/stevenokm/waste/projects/googletest-release-1.11.0/googletest/src/gtest_main.cc
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from HelloTest
[ RUN      ] HelloTest.AssertAssertions
/Users/stevenokm/waste/projects/test.cpp:7: Failure
Expected equality of these values:
  "hello"
  "world"
[  FAILED  ] HelloTest.AssertAssertions (0 ms)
[ RUN      ] HelloTest.ExpectAssertions
/Users/stevenokm/waste/projects/test.cpp:16: Failure
Expected equality of these values:
  "hello"
  "world"
/Users/stevenokm/waste/projects/test.cpp:18: Failure
Expected: (7 * 6) != (42), actual: 42 vs 42
[  FAILED  ] HelloTest.ExpectAssertions (0 ms)
[----------] 2 tests from HelloTest (0 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test suite ran. (0 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 2 tests, listed below:
[  FAILED  ] HelloTest.AssertAssertions
[  FAILED  ] HelloTest.ExpectAssertions

 2 FAILED TESTS

Types of Assertions

sample1.h

// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// A sample program demonstrating using Google C++ testing framework.

#ifndef GOOGLETEST_SAMPLES_SAMPLE1_H_
#define GOOGLETEST_SAMPLES_SAMPLE1_H_

// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
int Factorial(int n)
{
    int result = 1;
    for (int i = 1; i <= n; i++)
    {
        result *= i;
    }

    return result;
}

// Returns true if and only if n is a prime number.
bool IsPrime(int n)
{
    // Trivial case 1: small numbers
    if (n <= 1)
        return false;

    // Trivial case 2: even numbers
    if (n % 2 == 0)
        return n == 2;

    // Now, we have that n is odd and n >= 3.

    // Try to divide n by every odd number i, starting from 3
    for (int i = 3;; i += 2)
    {
        // We only have to try i up to the square root of n
        if (i > n / i)
            break;

        // Now, we have i <= n/i < n.
        // If n is divisible by i, n is not prime.
        if (n % i == 0)
            return false;
    }

    // n has no integer factor in the range (1, n), and thus is prime.
    return true;
}

#endif // GOOGLETEST_SAMPLES_SAMPLE1_H_

sample1_unittest.cc

// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// A sample program demonstrating using Google C++ testing framework.

// This sample shows how to write a simple unit test for a function,
// using Google C++ testing framework.
//
// Writing a unit test using Google C++ testing framework is easy as 1-2-3:

// Step 1. Include necessary header files such that the stuff your
// test logic needs is declared.
//
// Don't forget gtest.h, which declares the testing framework.

#include <limits.h>
#include "sample1.h"
#include "gtest/gtest.h"
namespace
{

  // Step 2. Use the TEST macro to define your tests.
  //
  // TEST has two parameters: the test case name and the test name.
  // After using the macro, you should define your test logic between a
  // pair of braces.  You can use a bunch of macros to indicate the
  // success or failure of a test.  EXPECT_TRUE and EXPECT_EQ are
  // examples of such macros.  For a complete list, see gtest.h.
  //
  // <TechnicalDetails>
  //
  // In Google Test, tests are grouped into test cases.  This is how we
  // keep test code organized.  You should put logically related tests
  // into the same test case.
  //
  // The test case name and the test name should both be valid C++
  // identifiers.  And you should not use underscore (_) in the names.
  //
  // Google Test guarantees that each test you define is run exactly
  // once, but it makes no guarantee on the order the tests are
  // executed.  Therefore, you should write your tests in such a way
  // that their results don't depend on their order.
  //
  // </TechnicalDetails>

  // Tests Factorial().

  // Tests factorial of negative numbers.
  TEST(FactorialTest, Negative)
  {
    // This test is named "Negative", and belongs to the "FactorialTest"
    // test case.
    EXPECT_EQ(1, Factorial(-5));
    EXPECT_EQ(1, Factorial(-1));
    EXPECT_GT(Factorial(-10), 0);

    // <TechnicalDetails>
    //
    // EXPECT_EQ(expected, actual) is the same as
    //
    //   EXPECT_TRUE((expected) == (actual))
    //
    // except that it will print both the expected value and the actual
    // value when the assertion fails.  This is very helpful for
    // debugging.  Therefore in this case EXPECT_EQ is preferred.
    //
    // On the other hand, EXPECT_TRUE accepts any Boolean expression,
    // and is thus more general.
    //
    // </TechnicalDetails>
  }

  // Tests factorial of 0.
  TEST(FactorialTest, Zero)
  {
    EXPECT_EQ(1, Factorial(0));
  }

  // Tests factorial of positive numbers.
  TEST(FactorialTest, Positive)
  {
    EXPECT_EQ(1, Factorial(1));
    EXPECT_EQ(2, Factorial(2));
    EXPECT_EQ(6, Factorial(3));
    EXPECT_EQ(40320, Factorial(8));
  }

  // Tests IsPrime()

  // Tests negative input.
  TEST(IsPrimeTest, Negative)
  {
    // This test belongs to the IsPrimeTest test case.

    EXPECT_FALSE(IsPrime(-1));
    EXPECT_FALSE(IsPrime(-2));
    EXPECT_FALSE(IsPrime(INT_MIN));
  }

  // Tests some trivial cases.
  TEST(IsPrimeTest, Trivial)
  {
    EXPECT_FALSE(IsPrime(0));
    EXPECT_FALSE(IsPrime(1));
    EXPECT_TRUE(IsPrime(2));
    EXPECT_TRUE(IsPrime(3));
  }

  // Tests positive input.
  TEST(IsPrimeTest, Positive)
  {
    EXPECT_FALSE(IsPrime(4));
    EXPECT_TRUE(IsPrime(5));
    EXPECT_FALSE(IsPrime(6));
    EXPECT_TRUE(IsPrime(23));
  }
} // namespace

// Step 3. Call RUN_ALL_TESTS() in main().
//
// We do this by linking in src/gtest_main.cc file, which consists of
// a main() function which calls RUN_ALL_TESTS() for us.
//
// This runs all the tests you've defined, prints the result, and
// returns 0 if successful, or 1 otherwise.
//
// Did you notice that we didn't register the tests?  The
// RUN_ALL_TESTS() macro magically knows about all the tests we
// defined.  Isn't this convenient?

Example: Postfix Calculator

lab12_3_include.h

#ifndef LAB12_3_INCLUDE_H
#define LAB12_3_INCLUDE_H

#include <iostream>
#include <string>
#include <vector>

using namespace std;

bool is_number(string str) // Check if a string is a number
{
    for (int i = 0; i < str.length(); i++)
    {
        if (i == 0 && str[i] == '-' && str.length() > 1)
            continue;
        if (!isdigit(str[i]))
            return false;
    }
    return true;
}

void parse_expression(const string &expression, vector<string> &tokens)
{
    string temp;
    for (int i = 0; i < expression.size(); i++)
    {
        if (expression[i] == ' ')
        {
            tokens.push_back(temp);
            temp.clear();
        }
        else if (i == expression.size() - 1) // End of Input_Buffer
        {
            temp += expression.substr(i, 1);
            tokens.push_back(temp);
        }
        else
            temp += expression.substr(i, 1);
    }
}

void print_nums(const vector<string> &tokens)
{
    cout << "Operands:";
    for (int i = 0; i < tokens.size(); i++)
    {
        if (tokens[i].length() != 1 || isdigit(tokens[i][0]))
            cout << ' ' << tokens[i];
    }
    cout << endl;
}

void print_ops(const vector<string> &tokens)
{
    cout << "Operators:";
    for (int i = 0; i < tokens.size(); i++)
    {
        if (tokens[i].length() == 1 && !isdigit(tokens[i][0]))
            cout << ' ' << tokens[i];
    }
    cout << endl;
}

void calculate_expression(
    const vector<string> tokens, vector<long> &num_stack)
{
    if (tokens.size() == 1)
    {
        num_stack.push_back(stol(tokens[0]));
        return;
    }

    int now = 0;
    while (now < tokens.size())
    {
        while (is_number(tokens[now]))
        {
            num_stack.push_back(stol(tokens[now]));
            now++;
        }
        long a = num_stack[num_stack.size() - 2],
             b = num_stack[num_stack.size() - 1];
        num_stack.pop_back();
        num_stack.pop_back();

        if (tokens[now] == "+")
            num_stack.push_back(a + b);
        else if (tokens[now] == "-")
            num_stack.push_back(a - b);
        else if (tokens[now] == "*")
            num_stack.push_back(a * b);
        else if (tokens[now] == "/")
            num_stack.push_back(a / b);

        now++;
    }
}

bool check_postfix_expression(const vector<string> &tokens)
{
    int stack_count = 0;

    for (int i = 0; i < tokens.size(); i++)
    {
        if (i > 0 && stack_count < 1)
            return false;
        if (is_number(tokens[i]))
            stack_count++;
        else if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
            stack_count--;
        else
            return false;
    }
    return stack_count == 1;
}

#endif //LAB12_3_INCLUDE_H

lab12_3_main.cpp

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#include "lab12_3_include.h"

using namespace std;

int main(int argc, char *argv[])
{
    string input_buffer;
    vector<string> tokens;

    cout << "Please input the expression: ";
    std::getline(cin, input_buffer);

    parse_expression(input_buffer, tokens);

    if (!check_postfix_expression(tokens))
    {
        cout << "Invalid expression." << endl;
        return EXIT_FAILURE;
    }

    print_ops(tokens);

    print_nums(tokens);

    cout << "Result: ";
    int last_pos = tokens.size() - 1;
    vector<long> num_stack;
    calculate_expression(tokens, num_stack);
    cout << num_stack[0] << endl;

    return EXIT_SUCCESS;
}

lab12_3_unittest.cpp

#include "lab12_3_include.h"
#include "gtest/gtest.h"

TEST(ParseExpression, Operands)
{
    vector<string> tokens;
    string input_buffer = "1 2 3 4 5 6 7 8 9";
    parse_expression(input_buffer, tokens);
    ASSERT_EQ(tokens.size(), 9);
    for (int i = 0; i < tokens.size(); i++)
    {
        EXPECT_EQ(tokens[i], to_string(i + 1));
    }
}

TEST(ParseExpression, Operators)
{
    vector<string> tokens;
    string input_buffer = "+ - * /";
    parse_expression(input_buffer, tokens);
    ASSERT_EQ(tokens.size(), 4);
    EXPECT_EQ(tokens[0], "+");
    EXPECT_EQ(tokens[1], "-");
    EXPECT_EQ(tokens[2], "*");
    EXPECT_EQ(tokens[3], "/");
}

TEST(ParseExpression, Mixed1)
{
    vector<string> tokens;
    string input_buffer = "1 2 3 4 * + -";
    parse_expression(input_buffer, tokens);
    ASSERT_EQ(tokens.size(), 7);
    EXPECT_EQ(tokens[0], "1");
    EXPECT_EQ(tokens[1], "2");
    EXPECT_EQ(tokens[2], "3");
    EXPECT_EQ(tokens[3], "4");
    EXPECT_EQ(tokens[4], "*");
    EXPECT_EQ(tokens[5], "+");
    EXPECT_EQ(tokens[6], "-");
}

TEST(ParseExpression, Mixed2)
{
    vector<string> tokens;
    string input_buffer = "-1 -2 -3 -4 * + -";
    parse_expression(input_buffer, tokens);
    EXPECT_EQ(tokens.size(), 7);
    EXPECT_EQ(tokens[0], "-1");
    EXPECT_EQ(tokens[1], "-2");
    EXPECT_EQ(tokens[2], "-3");
    EXPECT_EQ(tokens[3], "-4");
    EXPECT_EQ(tokens[4], "*");
    EXPECT_EQ(tokens[5], "+");
    EXPECT_EQ(tokens[6], "-");
}

TEST(ParseExpression, Mixed3)
{
    vector<string> tokens;
    string input_buffer = "-1 -2 -3 -4 * + %";
    parse_expression(input_buffer, tokens);
    EXPECT_EQ(tokens.size(), 7);
    EXPECT_EQ(tokens[0], "-1");
    EXPECT_EQ(tokens[1], "-2");
    EXPECT_EQ(tokens[2], "-3");
    EXPECT_EQ(tokens[3], "-4");
    EXPECT_EQ(tokens[4], "*");
    EXPECT_EQ(tokens[5], "+");
    EXPECT_EQ(tokens[6], "%");
}

TEST(CheckPostfixExpression, Operand)
{
    vector<string> tokens;
    tokens.push_back("1");
    EXPECT_TRUE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, Operator)
{
    vector<string> tokens;
    tokens.push_back("+");
    EXPECT_FALSE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, Mixed)
{
    vector<string> tokens;
    tokens.push_back("1");
    tokens.push_back("+");
    EXPECT_FALSE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, SimpleExpression)
{
    vector<string> tokens;
    tokens.push_back("1");
    tokens.push_back("2");
    tokens.push_back("+");
    EXPECT_TRUE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, ComplexExpression1)
{
    vector<string> tokens;
    tokens.push_back("1");
    tokens.push_back("2");
    tokens.push_back("3");
    tokens.push_back("4");
    tokens.push_back("*");
    tokens.push_back("+");
    tokens.push_back("-");
    EXPECT_TRUE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, ComplexExpression2)
{
    vector<string> tokens;
    tokens.push_back("-1");
    tokens.push_back("-2");
    tokens.push_back("-3");
    tokens.push_back("-4");
    tokens.push_back("*");
    tokens.push_back("+");
    tokens.push_back("-");
    EXPECT_TRUE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, ComplexExpression3)
{
    vector<string> tokens;
    tokens.push_back("-1");
    tokens.push_back("-2");
    tokens.push_back("*");
    tokens.push_back("-3");
    tokens.push_back("+");
    tokens.push_back("-4");
    tokens.push_back("-");
    EXPECT_TRUE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, ComplexExpression4)
{
    vector<string> tokens;
    tokens.push_back("1");
    tokens.push_back("2");
    tokens.push_back("-");
    tokens.push_back("2");
    tokens.push_back("1");
    tokens.push_back("+");
    tokens.push_back("/");
    EXPECT_TRUE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, NotExpression1)
{
    vector<string> tokens;
    tokens.push_back("-1");
    tokens.push_back("-2");
    tokens.push_back("-3");
    tokens.push_back("-4");
    tokens.push_back("*");
    tokens.push_back("+");
    EXPECT_FALSE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, NotExpression2)
{
    vector<string> tokens;
    tokens.push_back("-1");
    tokens.push_back("-2");
    tokens.push_back("-3");
    tokens.push_back("*");
    tokens.push_back("+");
    tokens.push_back("-");
    EXPECT_FALSE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, NotExpression3)
{
    vector<string> tokens;
    tokens.push_back("-1");
    tokens.push_back("-2");
    tokens.push_back("-3");
    tokens.push_back("-4");
    tokens.push_back("*");
    tokens.push_back("+");
    tokens.push_back("%");
    EXPECT_FALSE(check_postfix_expression(tokens));
}

TEST(CheckPostfixExpression, NotExpression4)
{
    vector<string> tokens;
    tokens.push_back("-1");
    tokens.push_back("*");
    tokens.push_back("-2");
    tokens.push_back("+");
    tokens.push_back("-3");
    tokens.push_back("-");
    tokens.push_back("-4");
    EXPECT_FALSE(check_postfix_expression(tokens));
}

TEST(CalculateExpression, Operand)
{
    vector<string> tokens;
    vector<long> num_stack;
    tokens.push_back("1");
    calculate_expression(tokens, num_stack);
    ASSERT_EQ(num_stack.size(), 1);
    EXPECT_EQ(num_stack[0], 1);
}

TEST(CalculateExpression, SimpleExpression)
{
    vector<string> tokens;
    vector<long> num_stack;
    tokens.push_back("1");
    tokens.push_back("2");
    tokens.push_back("+");
    calculate_expression(tokens, num_stack);
    ASSERT_EQ(num_stack.size(), 1);
    EXPECT_EQ(num_stack[0], 3);
}

TEST(CalculateExpression, ComplexExpression1)
{
    vector<string> tokens;
    vector<long> num_stack;
    //1 2 3 4 * + -
    tokens.push_back("1");
    tokens.push_back("2");
    tokens.push_back("3");
    tokens.push_back("4");
    tokens.push_back("*");
    tokens.push_back("+");
    tokens.push_back("-");
    calculate_expression(tokens, num_stack);
    ASSERT_EQ(num_stack.size(), 1);
    EXPECT_EQ(num_stack[0], -13);
}

TEST(CalculateExpression, ComplexExpression2)
{
    vector<string> tokens;
    vector<long> num_stack;
    //-1 -2 -3 -4 * + -
    tokens.push_back("-1");
    tokens.push_back("-2");
    tokens.push_back("-3");
    tokens.push_back("-4");
    tokens.push_back("*");
    tokens.push_back("+");
    tokens.push_back("-");
    calculate_expression(tokens, num_stack);
    ASSERT_EQ(num_stack.size(), 1);
    EXPECT_EQ(num_stack[0], -11);
}

TEST(CalculateExpression, ComplexExpression3)
{
    vector<string> tokens;
    vector<long> num_stack;
    //-1 -2 * -3 + -4 -
    tokens.push_back("-1");
    tokens.push_back("-2");
    tokens.push_back("*");
    tokens.push_back("-3");
    tokens.push_back("+");
    tokens.push_back("-4");
    tokens.push_back("-");
    calculate_expression(tokens, num_stack);
    ASSERT_EQ(num_stack.size(), 1);
    EXPECT_EQ(num_stack[0], 3);
}

TEST(CalculateExpression, ComplexExpression4)
{
    vector<string> tokens;
    vector<long> num_stack;
    //1 2 - 2 1 + /
    tokens.push_back("1");
    tokens.push_back("2");
    tokens.push_back("-");
    tokens.push_back("2");
    tokens.push_back("1");
    tokens.push_back("+");
    tokens.push_back("/");
    calculate_expression(tokens, num_stack);
    ASSERT_EQ(num_stack.size(), 1);
    EXPECT_EQ(num_stack[0], 0);
}
Running main() from /Users/stevenokm/waste/projects/googletest-release-1.11.0/googletest/src/gtest_main.cc
[==========] Running 23 tests from 3 test suites.
[----------] Global test environment set-up.
[----------] 5 tests from ParseExpression
[ RUN      ] ParseExpression.Operands
[       OK ] ParseExpression.Operands (0 ms)
[ RUN      ] ParseExpression.Operators
[       OK ] ParseExpression.Operators (0 ms)
[ RUN      ] ParseExpression.Mixed1
[       OK ] ParseExpression.Mixed1 (0 ms)
[ RUN      ] ParseExpression.Mixed2
[       OK ] ParseExpression.Mixed2 (0 ms)
[ RUN      ] ParseExpression.Mixed3
[       OK ] ParseExpression.Mixed3 (0 ms)
[----------] 5 tests from ParseExpression (0 ms total)

[----------] 12 tests from CheckPostfixExpression
[ RUN      ] CheckPostfixExpression.Operand
[       OK ] CheckPostfixExpression.Operand (0 ms)
[ RUN      ] CheckPostfixExpression.Operator
[       OK ] CheckPostfixExpression.Operator (0 ms)
[ RUN      ] CheckPostfixExpression.Mixed
[       OK ] CheckPostfixExpression.Mixed (0 ms)
[ RUN      ] CheckPostfixExpression.SimpleExpression
[       OK ] CheckPostfixExpression.SimpleExpression (0 ms)
[ RUN      ] CheckPostfixExpression.ComplexExpression1
[       OK ] CheckPostfixExpression.ComplexExpression1 (0 ms)
[ RUN      ] CheckPostfixExpression.ComplexExpression2
[       OK ] CheckPostfixExpression.ComplexExpression2 (0 ms)
[ RUN      ] CheckPostfixExpression.ComplexExpression3
[       OK ] CheckPostfixExpression.ComplexExpression3 (0 ms)
[ RUN      ] CheckPostfixExpression.ComplexExpression4
[       OK ] CheckPostfixExpression.ComplexExpression4 (0 ms)
[ RUN      ] CheckPostfixExpression.NotExpression1
[       OK ] CheckPostfixExpression.NotExpression1 (0 ms)
[ RUN      ] CheckPostfixExpression.NotExpression2
[       OK ] CheckPostfixExpression.NotExpression2 (0 ms)
[ RUN      ] CheckPostfixExpression.NotExpression3
[       OK ] CheckPostfixExpression.NotExpression3 (0 ms)
[ RUN      ] CheckPostfixExpression.NotExpression4
[       OK ] CheckPostfixExpression.NotExpression4 (0 ms)
[----------] 12 tests from CheckPostfixExpression (0 ms total)

[----------] 6 tests from CalculateExpression
[ RUN      ] CalculateExpression.Operand
[       OK ] CalculateExpression.Operand (0 ms)
[ RUN      ] CalculateExpression.SimpleExpression
[       OK ] CalculateExpression.SimpleExpression (0 ms)
[ RUN      ] CalculateExpression.ComplexExpression1
[       OK ] CalculateExpression.ComplexExpression1 (0 ms)
[ RUN      ] CalculateExpression.ComplexExpression2
[       OK ] CalculateExpression.ComplexExpression2 (0 ms)
[ RUN      ] CalculateExpression.ComplexExpression3
[       OK ] CalculateExpression.ComplexExpression3 (0 ms)
[ RUN      ] CalculateExpression.ComplexExpression4
[       OK ] CalculateExpression.ComplexExpression4 (0 ms)
[----------] 6 tests from CalculateExpression (0 ms total)

[----------] Global test environment tear-down
[==========] 23 tests from 3 test suites ran. (0 ms total)
[  PASSED  ] 23 tests.