Skip to content

Instantly share code, notes, and snippets.

@NickTikhomirov
Created May 13, 2019 20:12
Show Gist options
  • Save NickTikhomirov/2e6f5aabcbcc1b77f416e12f6d313ee2 to your computer and use it in GitHub Desktop.
Save NickTikhomirov/2e6f5aabcbcc1b77f416e12f6d313ee2 to your computer and use it in GitHub Desktop.
lab05

Laboratory work V

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

Заходим в репозиторий google

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

Tasks

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

Tutorial

Подготовка к лабораторной работе - установка значений переменных

#Устанавливаем значение переменной GITHUB_USERNAME
$ export GITHUB_USERNAME=NickTikhomirov
#Назначили функционал команде gsed
$ alias gsed=sed # for *-nix system

Подготовка к лабораторной работе - переход на рабочее место

#Заходим в директорию рабочего места
$ cd ${GITHUB_USERNAME}/workspace
#Выводим адрес текущей директории - после перехода с babun-а на alpine путь немного отличается
$ pushd .
/mnt/c/workspace
#Активируем скрипт, написанный в одной из первой лаб
$ source scripts/activate

Создаем файлы пятой лабораторной на основе скачанных файлов четвёртой лабораторной

#Скачиваем лабораторную 4 - из неё получим лабораторную 5
$ git clone https://github.com/${GITHUB_USERNAME}/lab04 projects/lab05
Cloning into 'projects/lab05'...
remote: Enumerating objects: 24, done.
remote: Counting objects: 100% (24/24), done.
remote: Compressing objects: 100% (15/15), done.
remote: Total 24 (delta 4), reused 21 (delta 4), pack-reused 0
Unpacking objects: 100% (24/24), done.
#Заходим в папку с лабораторной 5
$ cd projects/lab05
#Убираем привязанный адрес репозитория
$ git remote remove origin
#Дописываем новый адрес
$ git remote add origin https://github.com/${GITHUB_USERNAME}/lab05

Готовим тестировщик

#Создаём директорию third-party
$ mkdir third-party
#Качаем модуль тестировщика с гитхаба google в указанную папку
$ git submodule add https://github.com/google/googletest third-party/gtest
Cloning into '/mnt/c/workspace/projects/lab05/third-party/gtest'...
remote: Enumerating objects: 32, done.
remote: Counting objects: 100% (32/32), done.
remote: Compressing objects: 100% (25/25), done.
remote: Total 16798 (delta 10), reused 11 (delta 6), pack-reused 16766
Receiving objects: 100% (16798/16798), 5.77 MiB | 162.00 KiB/s, done.
Resolving deltas: 100% (12375/12375), done.
#Заходим в папку, переходим в ветку release-1.8.1 и выходим из папки назад
$ cd third-party/gtest && git checkout release-1.8.1 && cd ../..
Checking out files: 100% (200/200), done.
Note: checking out 'release-1.8.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 2fe3bd99 Merge pull request #1433 from dsacre/fix-clang-warnings
#Фиксируем изменения
$ git add third-party/gtest
#Делаем коммит
$ git commit -m"added gtest framework"
[master 59a2899] 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)
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.3.0
-- The CXX compiler identification is GNU 8.3.0
-- 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
-- Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - found
-- Found Threads: TRUE
-- Configuring done
-- Generating done
-- Build files have been written to: /mnt/c/workspace/projects/lab05/_build
#Компиляция
$ cmake --build _build
Scanning dependencies of target gtest
[  8%] Building CXX object third-party/gtest/googlemock/gtest/CMakeFiles/gtest.dir/src/gtest-all.cc.o
[ 16%] Linking CXX static library libgtest.a
[ 16%] Built target gtest
Scanning dependencies of target print
[ 25%] Building CXX object CMakeFiles/print.dir/sources/print.cpp.o
[ 33%] Linking CXX static library libprint.a
[ 33%] Built target print
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 /mnt/c/workspace/projects/lab05/_build
    Start 1: check
1/1 Test #1: check ............................   Passed    0.02 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.04 sec

Дополнительная проверка

#Запускаем файл с тестами
$ _build/check
Running main() from /mnt/c/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 (5 ms)
[----------] 1 test from Print (8 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (23 ms total)
[  PASSED  ] 1 test.
#Компиляция+вывод
$ cmake --build _build --target test -- ARGS=--verbose
Running tests...
UpdateCTestConfiguration  from :/mnt/c/workspace/projects/lab05/_build/DartConfiguration.tcl
UpdateCTestConfiguration  from :/mnt/c/workspace/projects/lab05/_build/DartConfiguration.tcl
Test project /mnt/c/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: /mnt/c/workspace/projects/lab05/_build/check
1: Test timeout computed to be: 10000000
1: Running main() from /mnt/c/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 (3 ms)
1: [----------] 1 test from Print (3 ms total)
1:
1: [----------] Global test environment tear-down
1: [==========] 1 test from 1 test case ran. (4 ms total)
1: [  PASSED  ] 1 test.
1/1 Test #1: check ............................   Passed    0.02 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.06 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
Warnings for .travis.yml:
[x] value for addons section is empty, dropping
[x] in addons section: unexpected key apt, dropping

Отправляем изменения на удалённый репозиторий

#Фиксируем конфиги travis
$ git add .travis.yml
#Фиксируем файл тестов
$ git add tests
#Раздельная фиксация. На Alpine WSL не запустилось, потому что графику не тянет
$ git add -p
git: 'add--interactive' is not a git command. See 'git --help'.
#Коммит
$ git commit -m"added tests"
[master ed4f359] added tests
 2 files changed, 21 insertions(+), 1 deletion(-)
 create mode 100644 tests/test1.cpp
#Отправка на репозиторий
$ git push origin master
Enumerating objects: 33, done.
Counting objects: 100% (33/33), done.
Delta compression using up to 4 threads
Compressing objects: 100% (26/26), done.
Writing objects: 100% (33/33), 4.60 KiB | 68.00 KiB/s, done.
Total 33 (delta 7), reused 0 (delta 0)
remote: Resolving deltas: 100% (7/7), done.
To https://github.com/NickTikhomirov/lab05
 * [new branch]      master -> master

Зашли на травис и включили его связь с

$ travis login --auto
We need your GitHub login to identify you.
This information will not be sent to Travis CI, only to api.github.com.
The password will not be displayed.

Try running with --github-token or --auto if you don't want to enter your password anyway.

Username: NickTikhomirov
Password for NickTikhomirov:
Successfully logged in as NickTikhomirov!
$ travis enable
Detected repository as NickTikhomirov/lab05, is this correct? |yes| y
NickTikhomirov/lab05: enabled :)
#Создание директории
$ mkdir artifacts
#Ждём 20 секунд и делаем скриншот. Скриншот не делается, потому что Alpine WSL
#Сделал вручную
$ 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
$ 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