Commit 6d3188fc authored by Pavel Vainerman's avatar Pavel Vainerman

(Catch): Начал переводить тесты на использование "Catch".

Написал тесты для PassiveTimer и HourGlass. Исправил найденные ошибки, доработал интерфейсы.
parent 50592bf8
...@@ -43,8 +43,9 @@ ...@@ -43,8 +43,9 @@
\par Пример использования. \par Пример использования.
Допустим у вас есть сигнал "перегрев"(in_overheating) и вам необходимо выставить какой-то Допустим у вас есть сигнал "перегрев"(in_overheating) и вам необходимо выставить какой-то
флаг о перегреве (isOverheating), если этот сигнал устойчиво держится в течение 10 секунд, флаг о перегреве (isOverheating), если этот сигнал устойчиво держится в течение 10 секунд,
и при этом если сигнал снялся, то вам необходимо как минимум те же 10 секунд, то check() станет "true". При этом если сигнал снимется на 5 секунд ("песок начнёт обратно пересыпаться"),
подождать прежде чем "снять" флаг. Для этого удобно использовать данный класс. а потом опять выставиться, то до срабатывания check() == true уже останется 5 сек, а не 10 сек.
Получается, что для срабатывания check()=true сигнал должен не колеблясь держаться больше заданного времени.
\code \code
HourGlass hg; HourGlass hg;
hg.run(10000); // настраиваем часы на 10 сек.. hg.run(10000); // настраиваем часы на 10 сек..
...@@ -67,7 +68,7 @@ class HourGlass ...@@ -67,7 +68,7 @@ class HourGlass
inline void run( timeout_t msec ) inline void run( timeout_t msec )
{ {
t.setTiming(msec); t.setTiming(msec);
_state = true; _state = true;
_sand = msec; _sand = msec;
_size = msec; _size = msec;
} }
...@@ -77,6 +78,7 @@ class HourGlass ...@@ -77,6 +78,7 @@ class HourGlass
run(_size); run(_size);
} }
// "ёмкость" песочных часов..
inline int duration() inline int duration()
{ {
return _size; return _size;
...@@ -93,43 +95,39 @@ class HourGlass ...@@ -93,43 +95,39 @@ class HourGlass
_state = st; _state = st;
if( !_state ) if( !_state )
{ {
int cur = t.getCurrent(); int cur = t.getCurrent();
_sand -= cur; if( cur > _size )
cur = _size;
if( _sand < 0 )
_sand = 0;
// std::cout << "перевернули: прошло " << cur _sand -= cur;
// << " осталось " << sand if( _sand < 0 )
// << " засекаем " << cur << endl; _sand = 0;
t.setTiming(cur); t.setTiming(cur);
} }
else else
{ {
_sand += t.getCurrent(); int cur = t.getCurrent();
if( cur > _size )
cur = _size;
_sand += cur;
if( _sand > _size ) if( _sand > _size )
_sand = _size; _sand = _size;
// std::cout << "вернули: прошло " << t.getCurrent()
// << " осталось " << sand
// << " засекам " << sand << endl;
t.setTiming(_sand); t.setTiming(_sand);
} }
return st; return st;
} }
// получить прошедшее время // получить прошедшее время
// для положения st inline timeout_t current()
inline timeout_t current( bool st )
{ {
return t.getCurrent(); return t.getCurrent();
} }
// получить заданное время // получить заданное время
// для положения st inline timeout_t interval()
inline timeout_t interval( bool st )
{ {
return t.getInterval(); return t.getInterval();
} }
...@@ -147,11 +145,42 @@ class HourGlass ...@@ -147,11 +145,42 @@ class HourGlass
inline bool state(){ return _state; } inline bool state(){ return _state; }
// текущее "насыпавшееся" количество "песка"
inline timeout_t amount()
{
return ( _size - remain() );
}
// остаток песка (времени)
inline timeout_t remain()
{
timeout_t c = t.getCurrent();
if( c > _size )
c = _size;
// _state=false - означает, что песок пересыпается обратно..
if( !_state )
{
int ret = ( _sand + c );
if( ret > _size )
return _size;
return ret;
}
// _state=true - означает, что песок пересыпается..
int ret = ( _sand - c );
if( ret < 0 )
return 0;
return ret;
}
protected: protected:
PassiveTimer t; PassiveTimer t; /*!< таймер для отсчёта времени.. */
bool _state; bool _state; /*!< текущее "положение часов", true - прямое, false - обратное (перевёрнутое) */
int _sand; int _sand; /*!< сколько песка ещё осталось.. */
timeout_t _size; timeout_t _size; /*!< размер часов */
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#endif #endif
......
...@@ -81,9 +81,7 @@ bool PassiveTimer::checkTime() ...@@ -81,9 +81,7 @@ bool PassiveTimer::checkTime()
timeout_t PassiveTimer::setTiming( timeout_t timeMS ) timeout_t PassiveTimer::setTiming( timeout_t timeMS )
{ {
if( timeMS == WaitUpTime ) if( timeMS == WaitUpTime )
{
timeSS = WaitUpTime; timeSS = WaitUpTime;
}
else else
{ {
timeSS=timeMS/10; // задержка в сантисекундах timeSS=timeMS/10; // задержка в сантисекундах
......
...@@ -2,51 +2,56 @@ ...@@ -2,51 +2,56 @@
# This file is part of the UniSet library # # This file is part of the UniSet library #
############################################################################ ############################################################################
noinst_PROGRAMS = passivetimer hourglass delaytimer unixml ui umutex conftest iterator_test sscanf_hex calibration threadtst dlog noinst_PROGRAMS = tests
#hourglass delaytimer unixml ui umutex conftest iterator_test sscanf_hex calibration threadtst dlog
passivetimer_SOURCES = passivetimer.cc
passivetimer_LDADD = $(top_builddir)/lib/libUniSet2.la tests_SOURCES = tests.cc passivetimer.cc hourglass.cc
passivetimer_CPPFLAGS = -I$(top_builddir)/include tests_LDADD = $(top_builddir)/lib/libUniSet2.la
tests_CPPFLAGS = -I$(top_builddir)/include -I$(includeir)/Catch
hourglass_SOURCES = hourglass.cc
hourglass_LDADD = $(top_builddir)/lib/libUniSet2.la #passivetimer_SOURCES = passivetimer.cc
hourglass_CPPFLAGS = -I$(top_builddir)/include #passivetimer_LDADD = $(top_builddir)/lib/libUniSet2.la
#passivetimer_CPPFLAGS = -I$(top_builddir)/include -ICatch
delaytimer_SOURCES = delaytimer.cc
delaytimer_LDADD = $(top_builddir)/lib/libUniSet2.la # hourglass_SOURCES = hourglass.cc
delaytimer_CPPFLAGS = -I$(top_builddir)/include # hourglass_LDADD = $(top_builddir)/lib/libUniSet2.la
# hourglass_CPPFLAGS = -I$(top_builddir)/include
unixml_SOURCES = unixml.cc #
unixml_LDADD = $(top_builddir)/lib/libUniSet2.la ${SIGC_LIBS} # delaytimer_SOURCES = delaytimer.cc
unixml_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS} # delaytimer_LDADD = $(top_builddir)/lib/libUniSet2.la
# delaytimer_CPPFLAGS = -I$(top_builddir)/include
iterator_test_SOURCES = iterator_test.cc #
iterator_test_LDADD = $(top_builddir)/lib/libUniSet2.la # unixml_SOURCES = unixml.cc
iterator_test_CPPFLAGS = -I$(top_builddir)/include # unixml_LDADD = $(top_builddir)/lib/libUniSet2.la ${SIGC_LIBS}
# unixml_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS}
ui_SOURCES = ui.cc #
ui_LDADD = $(top_builddir)/lib/libUniSet2.la # iterator_test_SOURCES = iterator_test.cc
ui_CPPFLAGS = -I$(top_builddir)/include # iterator_test_LDADD = $(top_builddir)/lib/libUniSet2.la
# iterator_test_CPPFLAGS = -I$(top_builddir)/include
umutex_SOURCES = umutex.cc #
umutex_LDADD = $(top_builddir)/lib/libUniSet2.la $(COMCPP_LIBS) # ui_SOURCES = ui.cc
umutex_CPPFLAGS = -I$(top_builddir)/include $(COMCPP_CFLAGS) # ui_LDADD = $(top_builddir)/lib/libUniSet2.la
# ui_CPPFLAGS = -I$(top_builddir)/include
conftest_SOURCES = conftest.cc #
conftest_LDADD = $(top_builddir)/lib/libUniSet2.la # umutex_SOURCES = umutex.cc
conftest_CPPFLAGS = -I$(top_builddir)/include # umutex_LDADD = $(top_builddir)/lib/libUniSet2.la $(COMCPP_LIBS)
# umutex_CPPFLAGS = -I$(top_builddir)/include $(COMCPP_CFLAGS)
sscanf_hex_SOURCES = sscanf_hex.cc #
# conftest_SOURCES = conftest.cc
calibration_SOURCES = calibration.cc # conftest_LDADD = $(top_builddir)/lib/libUniSet2.la
calibration_LDADD = $(top_builddir)/lib/libUniSet2.la ${SIGC_LIBS} # conftest_CPPFLAGS = -I$(top_builddir)/include
calibration_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS} #
# sscanf_hex_SOURCES = sscanf_hex.cc
threadtst_SOURCES = threadtst.cc #
threadtst_LDADD = $(top_builddir)/lib/libUniSet2.la ${SIGC_LIBS} $(COMCPP_LIBS) # calibration_SOURCES = calibration.cc
threadtst_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS} $(COMCPP_CFLAGS) # calibration_LDADD = $(top_builddir)/lib/libUniSet2.la ${SIGC_LIBS}
# calibration_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS}
dlog_SOURCES = dlog.cc #
dlog_LDADD = $(top_builddir)/lib/libUniSet2.la ${SIGC_LIBS} $(COMCPP_LIBS) # threadtst_SOURCES = threadtst.cc
dlog_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS} $(COMCPP_CFLAGS) # threadtst_LDADD = $(top_builddir)/lib/libUniSet2.la ${SIGC_LIBS} $(COMCPP_LIBS)
# threadtst_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS} $(COMCPP_CFLAGS)
#
# dlog_SOURCES = dlog.cc
# dlog_LDADD = $(top_builddir)/lib/libUniSet2.la ${SIGC_LIBS} $(COMCPP_LIBS)
# dlog_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS} $(COMCPP_CFLAGS)
#
#include <iostream> #include <Catch/catch.hpp>
#include <cmath>
using namespace std; using namespace std;
#include "HourGlass.h" #include "HourGlass.h"
#include "DelayTimer.h"
#include "UniSetTypes.h" #include "UniSetTypes.h"
int main() TEST_CASE("HourGlass", "[HourGlass]" )
{ {
HourGlass hg; SECTION( "Constructor" )
{
hg.run(1000); HourGlass hg;
hg.rotate(true); REQUIRE( hg.duration() == 0 );
msleep(200); msleep(60); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50
if( hg.check() ) REQUIRE( std::abs(hg.current()-60) <= 10 );
{ REQUIRE( hg.interval() == 0 );
cerr << "HourGlass: TEST1 FAILED! " << endl; REQUIRE( hg.amount() == 0 );
return 1; REQUIRE( hg.remain() == 0 );
} CHECK_FALSE( hg.state() );
CHECK_FALSE( hg.check() );
msleep(1000); }
if( !hg.check() )
{ SECTION( "Working" )
cerr << "HourGlass: TEST1 FAILED! " << endl; {
return 1; HourGlass hg;
} hg.run(100);
CHECK( hg.state() ); // часы начали тикать.. (в нормальном положении)
cout << "HourGlass: TEST1 OK!" << endl; REQUIRE( hg.duration() == 100 );
CHECK_FALSE( hg.check() );
msleep(110);
CHECK( hg.check() );
// Переворачиваем обратно..
// "песок высыпается назад" в течении 50 мсек,
// потом опять ставим "на ноги", ждём 60 мсек.. должно сработать
hg.rotate(false);
CHECK_FALSE( hg.state() );
CHECK_FALSE( hg.check() );
msleep(50);
CHECK_FALSE( hg.check() );
hg.rotate(true);
msleep(60);
CHECK( hg.check() );
}
hg.rotate(false); SECTION( "Reset" )
msleep(1000); {
if( hg.check() ) HourGlass hg;
{ hg.run(100);
cerr << "HourGlass: TEST2 FAILED! " << endl; msleep(110);
return 1; CHECK( hg.check() );
} hg.reset();
cout << "HourGlass: TEST2 OK!" << endl; CHECK_FALSE( hg.check() );
msleep(110);
CHECK( hg.check() );
}
hg.rotate(true); SECTION( "Debounce" )
msleep(500); {
if( hg.check() ) HourGlass hg;
{ hg.run(100); // [ 100 / 0 ]
cerr << "HourGlass: TEST3 FAILED! " << endl; REQUIRE( hg.remain() == 100 );
return 1; REQUIRE( hg.amount() == 0 );
} msleep(110); // [ 0 / 110 ] "110" --> "100"
cout << "HourGlass: TEST3 OK!" << endl; CHECK( hg.check() );
REQUIRE( hg.remain() == 0 );
REQUIRE( hg.amount() == 100 );
hg.rotate(false); hg.rotate(false); // начинает сыпаться "обратно"..
msleep(200); REQUIRE( hg.amount() == 100 );
hg.rotate(true); msleep(55);
msleep(200); CHECK_FALSE( hg.check() );
if( hg.check() ) REQUIRE( hg.amount() <= 50 ); // +-10 мсек..
{
cerr << "HourGlass: TEST4 FAILED! " << endl;
return 1;
}
msleep(820); hg.rotate(true); // опять начал сыпаться..
if( !hg.check() ) CHECK_FALSE( hg.check() );
{ msleep(25);
cerr << "HourGlass: TEST5 FAILED! " << endl; CHECK_FALSE( hg.check() );
return 1; REQUIRE( hg.amount() >= 60 );
}
cout << "HourGlass: TEST4 OK!" << endl; hg.rotate(false); // опять назад..
return 0; msleep(80); // по сути сигнал сбросился..(т.к. оставалось 70.. а прошло 80)
CHECK_FALSE( hg.check() );
REQUIRE( hg.amount() == 0 );
REQUIRE( hg.remain() == 100 );
hg.rotate(true); // вновь запустили
CHECK_FALSE( hg.check() );
msleep(55);
REQUIRE( hg.amount() >= 50 );
CHECK_FALSE( hg.check() );
msleep(60);
REQUIRE( hg.remain() == 0 );
REQUIRE( hg.amount() == 100 );
CHECK( hg.check() );
}
} }
#include <iostream> #include <Catch/catch.hpp>
using namespace std;
#include "PassiveTimer.h" #include "PassiveTimer.h"
#include "UniSetTypes.h" #include "UniSetTypes.h"
using namespace std;
PassiveTimer pt(1000); TEST_CASE("PassiveTimer", "[PassiveTimer]" )
void func( const std::string& s1 )
{ {
SECTION( "Default constructor" )
{
PassiveTimer pt;
} REQUIRE_FALSE( pt.checkTime() );
msleep(15);
int main() REQUIRE( pt.getCurrent() >= 10 );
{ REQUIRE( pt.getInterval() == 0 ); // TIMEOUT_INF );
func("test"); REQUIRE( pt.getLeft( pt.getCurrent() + 10 ) == 10 );
}
PassiveTimer pt1(5000); SECTION( "Init constructor" )
cout << " pt1.getInterval()=" << pt1.getInterval() << " TEST: " << ((pt1.getInterval()==5000) ? "OK" : "FAILED") << endl;
PassiveTimer pt2;
cout << " pt2.getInterval()=" << pt2.getInterval() << endl;
if( pt2.getInterval() != 0 )
{ {
cerr << "BAD DEFAULT INITIALIZATION!!!" << endl; PassiveTimer pt(100);
return 1; msleep(15); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50
REQUIRE( pt.getCurrent() >= 10 );
REQUIRE( pt.getInterval() == 100 );
REQUIRE( pt.getLeft(50) > 0 );
} }
PassiveTimer pt3(UniSetTimer::WaitUpTime); SECTION( "Init zero" )
cout << "pt3.getCurrent(): " << pt3.getCurrent() << endl;
msleep(3000);
int pt3_ms = pt3.getCurrent();
cout << "pt3.getCurrent(): " << pt3_ms << endl;
if( pt3_ms < 3000 )
{ {
cerr << "BAD getCurrent() function for WaitUpTime timer (pt3)" << endl; PassiveTimer pt(0);
return 1; REQUIRE( pt.getInterval() == 0 ); // TIMEOUT_INF );
REQUIRE( pt.getLeft(100) == 100 );
} }
SECTION( "Init < 0 " )
PassiveTimer pt0(0);
cout << "pt0: check msec=0: " << ( pt0.checkTime() ? "OK" : "FAILED" ) << endl;
PassiveTimer pt4(350);
for( int i=0;i<12; i++ )
{ {
cerr << "pt4: check time = " << pt4.checkTime() << endl; PassiveTimer pt(-10);
if( pt4.checkTime() ) REQUIRE( pt.getInterval() >= (timeout_t)(-10) ); // '>=' т.к. переданное время может быть округлено в большую сторону.
{ REQUIRE( pt.getLeft(10) == 10 );
cerr << "pt4: reset..." << endl;
pt4.reset();
}
msleep(200);
} }
while(1) SECTION( "Check working" )
{ {
cerr << "timer=" << pt.checkTime() << endl; PassiveTimer pt(100);
msleep(500); msleep(120); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50
REQUIRE( pt.getCurrent() >= 110 );
CHECK( pt.checkTime() );
INFO("Check reset");
pt.reset();
REQUIRE_FALSE( pt.checkTime() );
INFO("Check setTiming");
REQUIRE_FALSE( pt.checkTime() );
pt.setTiming(50);
msleep(55); // т.к. точность +-10 мсек.. делаем паузу 55..
CHECK( pt.checkTime() );
} }
return 0;
} }
#define CATCH_CONFIG_MAIN
#include <Catch/catch.hpp>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment