Skip to content

Instantly share code, notes, and snippets.

@nothingholy
Last active June 4, 2019 21:49
Show Gist options
  • Save nothingholy/01cdf38df2de2b3c3d0b324fd28832f2 to your computer and use it in GitHub Desktop.
Save nothingholy/01cdf38df2de2b3c3d0b324fd28832f2 to your computer and use it in GitHub Desktop.
lab05

Laboratory work V

Данная лабораторная работа посвещена изучению фреймворков для тестирования на примере GTest

$ open https://github.com/google/googletest

Tasks

  • 1. Создать публичный репозиторий с названием lab05 на сервисе GitHub
  • 2. Выполнить инструкцию учебного материала
  • 3. Ознакомиться со ссылками учебного материала
  • 4. Составить отчет и отправить ссылку личным сообщением в Slack

Tutorial

Настройка окружения

$ export GITHUB_USERNAME=<имя_пользователя> 
$ alias gsed=sed # for *-nix system #Синоним команды gsed

Заходим в свой workspace и активируем скрипты

$ cd ${GITHUB_USERNAME}/workspace
$ pushd .
~/nothingholy/workspace ~/nothingholy/workspace
$ source scripts/activate

Получаем файлы из предыдущей лабораторной работы

$ git clone https://github.com/${GITHUB_USERNAME}/lab04 projects/lab05
Клонирование в «projects/lab05»…
remote: Enumerating objects: 27, done.
remote: Counting objects: 100% (27/27), done.
remote: Compressing objects: 100% (18/18), done.
remote: Total 27 (delta 5), reused 23 (delta 4), pack-reused 0
Распаковка объектов: 100% (27/27), готово.
$ cd projects/lab05
$ git remote remove origin
$ git remote add origin https://github.com/${GITHUB_USERNAME}/lab05

Добавление подмодуля тестирования

$ mkdir third-party #Создаем папку
$ git submodule add https://github.com/google/googletest third-party/gtest #Скачиваем удаленный репозиторый в указанную папку
Клонирование в «/home/nothingholy/nothingholy/workspace/projects/lab05/third-party/gtest»…
remote: Enumerating objects: 48, done.
remote: Counting objects: 100% (48/48), done.
remote: Compressing objects: 100% (36/36), done.
remote: Total 16857 (delta 15), reused 26 (delta 11), pack-reused 16809
Получение объектов: 100% (16857/16857), 5.86 MiB | 604.00 KiB/s, готово.
Определение изменений: 100% (12412/12412), готово.
$ cd third-party/gtest && git checkout release-1.8.1 && cd ../..   # Переход в указанную папку, переход в указанную ветку, возврат
$ git add third-party/gtest # Фиксация изменений
$ git commit -m"added gtest framework" # Коммит зафиксированных изменений
[master a8c643d] added gtest framework
 2 files changed, 4 insertions(+)
 create mode 100644 .gitmodules
 create mode 160000 third-party/gtest

Редактирование CmakeLists.txt

$ gsed -i '/option(BUILD_EXAMPLES "Build examples" OFF)/a\ #Вставка строки 
option(BUILD_TESTS "Build tests" OFF)
' CMakeLists.txt
$ cat >> CMakeLists.txt <<EOF

if(BUILD_TESTS)
  enable_testing()
  add_subdirectory(third-party/gtest)
  file(GLOB \${PROJECT_NAME}_TEST_SOURCES tests/*.cpp)
  add_executable(check \${\${PROJECT_NAME}_TEST_SOURCES})
  target_link_libraries(check \${PROJECT_NAME} gtest_main)
  add_test(NAME check COMMAND check) #добавление теста с названием check и необходимой командой для его запуска
endif()
EOF

Создаем код

$ mkdir tests
$ cat > tests/test1.cpp <<EOF
#include <print.hpp>

#include <gtest/gtest.h>

TEST(Print, InFileStream)
{
  std::string filepath = "file.txt";
  std::string text = "hello";
  std::ofstream out{filepath};

  print(text, out);
  out.close();

  std::string result;
  std::ifstream in{filepath};
  in >> result;

  EXPECT_EQ(result, text);
}
EOF

Сборка проекта

$ cmake -H. -B_build -DBUILD_TESTS=ON
-- The C compiler identification is GNU 8.2.1
-- The CXX compiler identification is GNU 8.2.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PythonInterp: /usr/bin/python (found version "3.7.2") 
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Check if compiler accepts -pthread
-- Check if compiler accepts -pthread - yes
-- Found Threads: TRUE  
-- Configuring done
-- Generating done
-- Build files have been written to: /home/nothingholy/nothingholy/workspace/projects/lab05/_build
$ cmake --build _build
Scanning dependencies of target print
[  8%] Building CXX object CMakeFiles/print.dir/sources/print.cpp.o
[ 16%] Linking CXX static library libprint.a
[ 16%] Built target print
Scanning dependencies of target gtest
[ 25%] Building CXX object third-party/gtest/googlemock/gtest/CMakeFiles/gtest.dir/src/gtest-all.cc.o
[ 33%] Linking CXX static library libgtest.a
[ 33%] Built target gtest
Scanning dependencies of target gtest_main
[ 41%] Building CXX object third-party/gtest/googlemock/gtest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.o
[ 50%] Linking CXX static library libgtest_main.a
[ 50%] Built target gtest_main
Scanning dependencies of target check
[ 58%] Building CXX object CMakeFiles/check.dir/tests/test1.cpp.o
[ 66%] Linking CXX executable check
[ 66%] Built target check
Scanning dependencies of target gmock
[ 75%] Building CXX object third-party/gtest/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.o
[ 83%] Linking CXX static library libgmock.a
[ 83%] Built target gmock
Scanning dependencies of target gmock_main
[ 91%] Building CXX object third-party/gtest/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.o
[100%] Linking CXX static library libgmock_main.a
[100%] Built target gmock_main
$ cmake --build _build --target test
Running tests...
Test project /home/nothingholy/nothingholy/workspace/projects/lab05/_build
    Start 1: check
1/1 Test #1: check ............................   Passed    0.00 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.01 sec

Проверка тестов

$ _build/check
Running main() from /home/nothingholy/nothingholy/workspace/projects/lab05/third-party/gtest/googletest/src/gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from Print
[ RUN      ] Print.InFileStream
[       OK ] Print.InFileStream (0 ms)
[----------] 1 test from Print (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 1 test.
$ cmake --build _build --target test -- ARGS=--verbose #компиляция с выводом информации
Running tests...
UpdateCTestConfiguration  from :/home/nothingholy/nothingholy/workspace/projects/lab05/_build/DartConfiguration.tcl
UpdateCTestConfiguration  from :/home/nothingholy/nothingholy/workspace/projects/lab05/_build/DartConfiguration.tcl
Test project /home/nothingholy/nothingholy/workspace/projects/lab05/_build
Constructing a list of tests
Done constructing a list of tests
Updating test list for fixtures
Added 0 tests to meet fixture requirements
Checking test dependency graph...
Checking test dependency graph end
test 1
    Start 1: check

1: Test command: /home/nothingholy/nothingholy/workspace/projects/lab05/_build/check
1: Test timeout computed to be: 10000000
1: Running main() from /home/nothingholy/nothingholy/workspace/projects/lab05/third-party/gtest/googletest/src/gtest_main.cc
1: [==========] Running 1 test from 1 test case.
1: [----------] Global test environment set-up.
1: [----------] 1 test from Print
1: [ RUN      ] Print.InFileStream
1: [       OK ] Print.InFileStream (0 ms)
1: [----------] 1 test from Print (0 ms total)
1: 
1: [----------] Global test environment tear-down
1: [==========] 1 test from 1 test case ran. (0 ms total)
1: [  PASSED  ] 1 test.
1/1 Test #1: check ............................   Passed    0.00 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.00 sec

Обновление Travis CI

$ gsed -i 's/lab04/lab05/g' README.md
$ gsed -i 's/\(DCMAKE_INSTALL_PREFIX=_install\)/\1 -DBUILD_TESTS=ON/' .travis.yml
$ gsed -i '/cmake --build _build --target install/a\
- cmake --build _build --target test -- ARGS=--verbose
' .travis.yml

Проверка конфига

$ travis lint

Отправка изменений

$ git add .travis.yml
$ git add tests
$ git add -p
$ git commit -m"added tests"
$ git push origin master

Активация репозитория в Travis

$ travis login --auto
$ travis enable
nothingholy/lab05: enabled :)

Сохранение результата

$ mkdir artifacts
$ sleep 20s && gnome-screenshot --file artifacts/screenshot.png
# for macOS: $ screencapture -T 20 artifacts/screenshot.png
# open https://github.com/${GITHUB_USERNAME}/lab05

Report

$ popd
~/nothingholy/workspace
$ export LAB_NUMBER=05
$ git clone https://github.com/tp-labs/lab${LAB_NUMBER} tasks/lab${LAB_NUMBER}
$ mkdir reports/lab${LAB_NUMBER}
$ cp tasks/lab${LAB_NUMBER}/README.md reports/lab${LAB_NUMBER}/REPORT.md
$ cd reports/lab${LAB_NUMBER}
$ edit REPORT.md
$ gistup -m "lab${LAB_NUMBER}"

Homework

Задание

  1. Создайте CMakeList.txt для библиотеки banking.
  2. Создайте модульные тесты на классы Transaction и Account.
    • Используйте mock-объекты.
    • Покрытие кода должно составлять 100%.
  3. Настройте сборочную процедуру на TravisCI.
  4. Настройте Coveralls.io.

Links

Copyright (c) 2015-2019 The ISC Authors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment